diff --git a/SimPEG/DCIP/BaseDC.py b/SimPEG/DCIP/BaseDC.py index 4eb4ca69..b46d9f62 100644 --- a/SimPEG/DCIP/BaseDC.py +++ b/SimPEG/DCIP/BaseDC.py @@ -1,3 +1,12 @@ +from __future__ import division +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import absolute_import +from builtins import super +from future import standard_library +standard_library.install_aliases() +from builtins import range +from past.utils import old_div from SimPEG import * class FieldsDC_CC(Problem.Fields): @@ -61,7 +70,7 @@ class SrcDipole(Survey.BaseSrc): pts = [self.loc[0], self.loc[1]] inds = Utils.closestPoints(prob.mesh, pts) q = np.zeros(prob.mesh.nC) - q[inds] = - self.current * ( np.r_[1., -1.] / prob.mesh.vol[inds] ) + q[inds] = - self.current * ( old_div(np.r_[1., -1.], prob.mesh.vol[inds]) ) # self._rhsDict[mesh] = q # return self._rhsDict[mesh] return q @@ -145,7 +154,7 @@ class ProblemDC_CC(Problem.BaseProblem): if getattr(self, '_Msig', None) is None: sigma = self.curModel.transform Av = self.mesh.aveF2CC - self._Msig = Utils.sdiag(1/(self.mesh.dim * Av.T * (1/sigma))) + self._Msig = Utils.sdiag(old_div(1,(self.mesh.dim * Av.T * (old_div(1,sigma))))) return self._Msig @property @@ -153,7 +162,7 @@ class ProblemDC_CC(Problem.BaseProblem): if getattr(self, '_dMdsig', None) is None: sigma = self.curModel.transform Av = self.mesh.aveF2CC - dMdprop = self.mesh.dim * Utils.sdiag(self.Msig.diagonal()**2) * Av.T * Utils.sdiag(1./sigma**2) + dMdprop = self.mesh.dim * Utils.sdiag(self.Msig.diagonal()**2) * Av.T * Utils.sdiag(old_div(1.,sigma**2)) self._dMdsig = lambda Gu: Utils.sdiag(Gu) * dMdprop return self._dMdsig diff --git a/SimPEG/DCIP/BaseIP.py b/SimPEG/DCIP/BaseIP.py index bab3af3a..b9d91b01 100644 --- a/SimPEG/DCIP/BaseIP.py +++ b/SimPEG/DCIP/BaseIP.py @@ -1,5 +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 builtins import range +from past.utils import old_div from SimPEG import * -from BaseDC import SurveyDC, FieldsDC_CC +from .BaseDC import SurveyDC, FieldsDC_CC class SurveyIP(SurveyDC): """ @@ -52,7 +60,7 @@ class ProblemIP(Problem.BaseProblem): # sigma = self.curModel.transform sigma = self.sigma Av = self.mesh.aveF2CC - self._Msig = Utils.sdiag(1/(self.mesh.dim * Av.T * (1/sigma))) + self._Msig = Utils.sdiag(old_div(1,(self.mesh.dim * Av.T * (old_div(1,sigma))))) return self._Msig @property @@ -61,7 +69,7 @@ class ProblemIP(Problem.BaseProblem): # sigma = self.curModel.transform sigma = self.sigma Av = self.mesh.aveF2CC - dMdprop = self.mesh.dim * Utils.sdiag(self.Msig.diagonal()**2) * Av.T * Utils.sdiag(1./sigma**2) + dMdprop = self.mesh.dim * Utils.sdiag(self.Msig.diagonal()**2) * Av.T * Utils.sdiag(old_div(1.,sigma**2)) self._dMdsig = lambda Gu: Utils.sdiag(Gu) * dMdprop return self._dMdsig diff --git a/SimPEG/DCIP/DCIPUtils.py b/SimPEG/DCIP/DCIPUtils.py index 8e1ca5e9..c9862690 100644 --- a/SimPEG/DCIP/DCIPUtils.py +++ b/SimPEG/DCIP/DCIPUtils.py @@ -1,6 +1,17 @@ +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import unicode_literals +from builtins import open +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import map +from builtins import range +from past.utils import old_div from SimPEG import np, Utils -import BaseDC as DC -import BaseDC as IP +from . import BaseDC as DC +from . import BaseDC as IP import warnings def getActiveindfromTopo(mesh, topo): @@ -67,7 +78,7 @@ def readUBC_DC3Dobstopo(filename,mesh,topo,probType="CC"): if "!" in line.split(): continue elif line == '\n': continue elif line == ' \n': continue - temp = map(float, line.split()) + temp = list(map(float, line.split())) # Read a line for the current electrode if len(temp) == 5: # SRC: Only X and Y are provided (assume no topography) #TODO consider topography and assign the closest cell center in the earth @@ -211,8 +222,8 @@ def plot_pseudoSection(DCsurvey, axs, surveyType='dipole-dipole', unitType='volt MN = np.abs(Rx[1][:,0] - Rx[0][:,0]) # Create mid-point location - Cmid = (Tx[0][0] + Tx[1][0])/2 - Pmid = (Rx[0][:,0] + Rx[1][:,0])/2 + Cmid = old_div((Tx[0][0] + Tx[1][0]),2) + Pmid = old_div((Rx[0][:,0] + Rx[1][:,0]),2) # Change output for unitType if unitType == 'volt': @@ -228,16 +239,16 @@ def plot_pseudoSection(DCsurvey, axs, surveyType='dipole-dipole', unitType='volt elif surveyType == 'dipole-dipole': - leg = data * 2*np.pi / ( 1/MA - 1/MB - 1/NB + 1/NA ) + leg = data * 2*np.pi / ( old_div(1,MA) - old_div(1,MB) - old_div(1,NB) + old_div(1,NA) ) else: - print """unitType must be 'pole-dipole' | 'dipole-dipole' """ + print("""unitType must be 'pole-dipole' | 'dipole-dipole' """) break if unitType == 'appConductivity': - leg = np.log10(abs(1./leg)) + leg = np.log10(abs(old_div(1.,leg))) rho = np.hstack([rho,leg]) elif unitType == 'appResistivity': @@ -246,11 +257,11 @@ def plot_pseudoSection(DCsurvey, axs, surveyType='dipole-dipole', unitType='volt rho = np.hstack([rho,leg]) else: - print """unitType must be 'appResistivity' | 'appConductivity' | 'volt' """ + print("""unitType must be 'appResistivity' | 'appConductivity' | 'volt' """) break - midx = np.hstack([midx, ( Cmid + Pmid )/2 ]) - midz = np.hstack([midz, -np.abs(Cmid-Pmid)/2 + (Tx[0][2] + Tx[1][2])/2 ]) + midx = np.hstack([midx, old_div(( Cmid + Pmid ),2) ]) + midz = np.hstack([midz, old_div(-np.abs(Cmid-Pmid),2) + old_div((Tx[0][2] + Tx[1][2]),2) ]) # Grid points grid_x, grid_z = np.mgrid[np.min(midx):np.max(midx), np.min(midz):np.max(midz)] @@ -337,14 +348,14 @@ def gen_DCIPsurvey(endl, mesh, surveyType, AM_sep, MN_sep, nrx): # Mesure survey length and direction dl_len = xy_2_r(endl[0,0],endl[1,0],endl[0,1],endl[1,1]) - dl_x = ( endl[1,0] - endl[0,0] ) / dl_len - dl_y = ( endl[1,1] - endl[0,1] ) / dl_len + dl_x = old_div(( endl[1,0] - endl[0,0] ), dl_len) + dl_y = old_div(( endl[1,1] - endl[0,1] ), dl_len) - nstn = np.floor( dl_len / AM_sep ) + nstn = np.floor( old_div(dl_len, AM_sep) ) # Compute discrete pole location along line - stn_x = endl[0,0] + np.array(range(int(nstn)))*dl_x*AM_sep - stn_y = endl[0,1] + np.array(range(int(nstn)))*dl_y*AM_sep + stn_x = endl[0,0] + np.array(list(range(int(nstn))))*dl_x*AM_sep + stn_y = endl[0,1] + np.array(list(range(int(nstn))))*dl_y*AM_sep # Create line of P1 locations M = np.c_[stn_x, stn_y, np.ones(nstn).T*mesh.vectorNz[-1]] @@ -376,15 +387,15 @@ def gen_DCIPsurvey(endl, mesh, surveyType, AM_sep, MN_sep, nrx): AB = xy_2_r(tx[0,1],endl[1,0],tx[1,1],endl[1,1]) # Number of receivers to fit - nstn = np.min([np.floor( (AB - MN_sep) / AM_sep ) , nrx]) + nstn = np.min([np.floor( old_div((AB - MN_sep), AM_sep) ) , nrx]) # Check if there is enough space, else break the loop if nstn <= 0: continue # Compute discrete pole location along line - stn_x = N[ii,0] + dl_x*MN_sep + np.array(range(int(nstn)))*dl_x*AM_sep - stn_y = N[ii,1] + dl_y*MN_sep + np.array(range(int(nstn)))*dl_y*AM_sep + stn_x = N[ii,0] + dl_x*MN_sep + np.array(list(range(int(nstn))))*dl_x*AM_sep + stn_y = N[ii,1] + dl_y*MN_sep + np.array(list(range(int(nstn))))*dl_y*AM_sep # Create receiver poles # Create line of P1 locations @@ -417,17 +428,17 @@ def gen_DCIPsurvey(endl, mesh, surveyType, AM_sep, MN_sep, nrx): max_y = endl[1,1] - dl_y * MN_sep box_l = np.sqrt( (min_x - max_x)**2 + (min_y - max_y)**2 ) - box_w = box_l/2. + box_w = old_div(box_l,2.) - nstn = np.floor( box_l / AM_sep ) + nstn = np.floor( old_div(box_l, AM_sep) ) # Compute discrete pole location along line - stn_x = min_x + np.array(range(int(nstn)))*dl_x*AM_sep - stn_y = min_y + np.array(range(int(nstn)))*dl_y*AM_sep + stn_x = min_x + np.array(list(range(int(nstn))))*dl_x*AM_sep + stn_y = min_y + np.array(list(range(int(nstn))))*dl_y*AM_sep # Define number of cross lines - nlin = int(np.floor( box_w / AM_sep )) - lind = range(-nlin,nlin+1) + nlin = int(np.floor( old_div(box_w, AM_sep) )) + lind = list(range(-nlin,nlin+1)) ngrad = nstn * len(lind) @@ -449,7 +460,7 @@ def gen_DCIPsurvey(endl, mesh, surveyType, AM_sep, MN_sep, nrx): srcClass = DC.SrcDipole([rxClass], M[0,:], N[-1,:]) SrcList.append(srcClass) else: - print """surveyType must be either 'pole-dipole', 'dipole-dipole' or 'gradient'. """ + print("""surveyType must be either 'pole-dipole', 'dipole-dipole' or 'gradient'. """) survey = DC.SurveyDC(SrcList) return survey, Tx, Rx @@ -668,7 +679,7 @@ def readUBC_DC3Dobs(fileName, rtype = 'DC'): obsfile = np.genfromtxt(fileName,delimiter=' \n',dtype=np.str,comments='!') else: - print "rtype must be 'DC'(default) | 'IP'" + print("rtype must be 'DC'(default) | 'IP'") # Pre-allocate srcLists = [] @@ -983,7 +994,7 @@ def xy_2_lineID(DCsurvey): ang2 = np.abs(vec3.dot(vec4)) # If the angles are smaller then 45d, than next point is on a new line - if ((ang1 < np.cos(np.pi/4.)) | (ang2 < np.cos(np.pi/4.))) & (np.all(np.r_[r1,r2,r3,r4] > 0)): + if ((ang1 < np.cos(old_div(np.pi,4.))) | (ang2 < np.cos(old_div(np.pi,4.)))) & (np.all(np.r_[r1,r2,r3,r4] > 0)): # Re-initiate start and mid-point location xy0 = A[:2] @@ -1023,7 +1034,7 @@ def r_unit(p1,p2): if r!=0: - vec = dx/r + vec = old_div(dx,r) else: vec = np.zeros(len(p1)) diff --git a/SimPEG/DCIP/Utils.py b/SimPEG/DCIP/Utils.py index 702a2333..9b0776ed 100644 --- a/SimPEG/DCIP/Utils.py +++ b/SimPEG/DCIP/Utils.py @@ -1,3 +1,11 @@ +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 builtins import range +from past.utils import old_div import numpy as np def WennerSrcList(nElecs, aSpacing, in2D=False, plotIt=False): @@ -5,7 +13,7 @@ def WennerSrcList(nElecs, aSpacing, in2D=False, plotIt=False): import SimPEG.DCIP as DC elocs = np.arange(0,aSpacing*nElecs,aSpacing) - elocs -= (nElecs*aSpacing - aSpacing)/2 + elocs -= old_div((nElecs*aSpacing - aSpacing),2) space = 1 WENNER = np.zeros((0,),dtype=int) for ii in range(nElecs): diff --git a/SimPEG/DCIP/__init__.py b/SimPEG/DCIP/__init__.py index 08d1fe12..87b13ee2 100644 --- a/SimPEG/DCIP/__init__.py +++ b/SimPEG/DCIP/__init__.py @@ -1,4 +1,10 @@ -from BaseDC import * -from BaseIP import * -from DCIPUtils import * -import Utils +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 .BaseDC import * +from .BaseIP import * +from .DCIPUtils import * +from . import Utils diff --git a/SimPEG/DataMisfit.py b/SimPEG/DataMisfit.py index 53728c4e..2606f414 100644 --- a/SimPEG/DataMisfit.py +++ b/SimPEG/DataMisfit.py @@ -1,7 +1,17 @@ -import Utils, Survey, Problem, numpy as np, scipy.sparse as sp, gc +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 +from builtins import object +from . import Utils, Survey, Problem +import numpy as np, scipy.sparse as sp, gc +from future.utils import with_metaclass -class BaseDataMisfit(object): +class BaseDataMisfit(with_metaclass(Utils.SimPEGMetaClass, object)): """BaseDataMisfit .. note:: @@ -9,8 +19,6 @@ class BaseDataMisfit(object): You should inherit from this class to create your own data misfit term. """ - __metaclass__ = Utils.SimPEGMetaClass - debug = False #: Print debugging information counter = None #: Set this to a SimPEG.Utils.Counter() if you want to count things @@ -93,14 +101,14 @@ class l2_DataMisfit(BaseDataMisfit): survey = self.survey if getattr(survey,'std', None) is None: - print 'SimPEG.DataMisfit.l2_DataMisfit assigning default std of 5%' + print('SimPEG.DataMisfit.l2_DataMisfit assigning default std of 5%') survey.std = 0.05 if getattr(survey, 'eps', None) is None: - print 'SimPEG.DataMisfit.l2_DataMisfit assigning default eps of 1e-5 * ||dobs||' + print('SimPEG.DataMisfit.l2_DataMisfit assigning default eps of 1e-5 * ||dobs||') survey.eps = np.linalg.norm(Utils.mkvc(survey.dobs),2)*1e-5 - self._Wd = Utils.sdiag(1/(abs(survey.dobs)*survey.std+survey.eps)) + self._Wd = Utils.sdiag(old_div(1,(abs(survey.dobs)*survey.std+survey.eps))) return self._Wd @Wd.setter diff --git a/SimPEG/Directives.py b/SimPEG/Directives.py index 765711b7..4ee7a707 100644 --- a/SimPEG/Directives.py +++ b/SimPEG/Directives.py @@ -1,4 +1,16 @@ -import Utils, numpy as np +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import +from builtins import open +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import str +from past.utils import old_div +from builtins import object +from . import Utils +import numpy as np class InversionDirective(object): """InversionDirective""" @@ -15,7 +27,7 @@ class InversionDirective(object): @inversion.setter def inversion(self, i): if getattr(self,'_inversion',None) is not None: - print 'Warning: InversionDirective %s has switched to a new inversion.' % self.__name__ + print('Warning: InversionDirective %s has switched to a new inversion.' % self.__name__) self._inversion = i @property @@ -68,7 +80,7 @@ class DirectiveList(object): def inversion(self, i): if self.inversion is i: return if getattr(self,'_inversion',None) is not None: - print 'Warning: %s has switched to a new inversion.' % self.__name__ + print('Warning: %s has switched to a new inversion.' % self.__name__) for d in self.dList: d.inversion = i self._inversion = i @@ -120,7 +132,7 @@ class BetaEstimate_ByEig(InversionDirective): :return: beta0 """ - if self.debug: print 'Calculating the beta0 parameter.' + if self.debug: print('Calculating the beta0 parameter.') m = self.invProb.curModel f = self.invProb.getFields(m, store=True, deleteWarmstart=False) @@ -128,7 +140,7 @@ class BetaEstimate_ByEig(InversionDirective): x0 = np.random.rand(*m.shape) t = x0.dot(self.dmisfit.eval2Deriv(m,x0,f=f)) b = x0.dot(self.reg.eval2Deriv(m, v=x0)) - self.beta0 = self.beta0_ratio*(t/b) + self.beta0 = self.beta0_ratio*(old_div(t,b)) self.invProb.beta = self.beta0 @@ -141,7 +153,7 @@ class BetaSchedule(InversionDirective): def endIter(self): if self.opt.iter > 0 and self.opt.iter % self.coolingRate == 0: - if self.debug: print 'BetaSchedule is cooling Beta. Iteration: %d' % self.opt.iter + if self.debug: print('BetaSchedule is cooling Beta. Iteration: %d' % self.opt.iter) self.invProb.beta /= self.coolingFactor @@ -192,7 +204,7 @@ class SaveModelEveryIteration(SaveEveryIteration): """SaveModelEveryIteration""" def initialize(self): - print "SimPEG.SaveModelEveryIteration will save your models as: '###-%s.npy'"%self.fileName + print("SimPEG.SaveModelEveryIteration will save your models as: '###-%s.npy'"%self.fileName) def endIter(self): np.save('%03d-%s' % (self.opt.iter, self.fileName), self.opt.xc) @@ -202,7 +214,7 @@ class SaveOutputEveryIteration(SaveEveryIteration): """SaveModelEveryIteration""" def initialize(self): - print "SimPEG.SaveOutputEveryIteration will save your inversion progress as: '###-%s.txt'"%self.fileName + print("SimPEG.SaveOutputEveryIteration will save your inversion progress as: '###-%s.txt'"%self.fileName) f = open(self.fileName+'.txt', 'w') f.write(" # beta phi_d phi_m f\n") f.close() @@ -216,7 +228,7 @@ class SaveOutputDictEveryIteration(SaveEveryIteration): """SaveOutputDictEveryIteration""" def initialize(self): - print "SimPEG.SaveOutputDictEveryIteration will save your inversion progress as dictionary: '###-%s.npz'"%self.fileName + print("SimPEG.SaveOutputDictEveryIteration will save your inversion progress as dictionary: '###-%s.npz'"%self.fileName) def endIter(self): # Save the data. @@ -294,7 +306,7 @@ class Update_IRLS(InversionDirective): # After reaching target misfit with l2-norm, switch to IRLS (mode:2) if self.invProb.phi_d < self.target and self.mode == 1: - print "Convergence with smooth l2-norm regularization: Start IRLS steps..." + print("Convergence with smooth l2-norm regularization: Start IRLS steps...") self.mode = 2 @@ -302,17 +314,17 @@ class Update_IRLS(InversionDirective): # model values if getattr(self, 'reg.eps', None) is None: self.reg.eps_p = np.percentile(np.abs(self.invProb.curModel),self.prctile) - else: + else: self.reg.eps_p = self.eps[0] - + if getattr(self, 'reg.eps', None) is None: self.reg.eps_q = np.percentile(np.abs(self.reg.regmesh.cellDiffxStencil*(self.reg.mapping * self.invProb.curModel)),self.prctile) - else: + else: self.reg.eps_q = self.eps[1] - - print "L[p qx qy qz]-norm : " + str(self.reg.norms) - print "eps_p: " + str(self.reg.eps_p) + " eps_q: " + str(self.reg.eps_q) - + + print("L[p qx qy qz]-norm : " + str(self.reg.norms)) + print("eps_p: " + str(self.reg.eps_p) + " eps_q: " + str(self.reg.eps_q)) + self.reg.norms = self.norms self.coolingFactor = 1. self.coolingRate = 1 @@ -328,7 +340,7 @@ class Update_IRLS(InversionDirective): # Beta Schedule if self.opt.iter > 0 and self.opt.iter % self.coolingRate == 0: - if self.debug: print 'BetaSchedule is cooling Beta. Iteration: %d' % self.opt.iter + if self.debug: print('BetaSchedule is cooling Beta. Iteration: %d' % self.opt.iter) self.invProb.beta /= self.coolingFactor @@ -338,19 +350,19 @@ class Update_IRLS(InversionDirective): self.IRLSiter += 1 phim_new = self.reg.eval(self.invProb.curModel) - self.f_change = np.abs(self.f_old - phim_new) / self.f_old + self.f_change = old_div(np.abs(self.f_old - phim_new), self.f_old) - print "Regularization decrease: %6.3e" % (self.f_change) + print("Regularization decrease: %6.3e" % (self.f_change)) # Check for maximum number of IRLS cycles if self.IRLSiter == self.maxIRLSiter: - print "Reach maximum number of IRLS cycles: %i" % self.maxIRLSiter + print("Reach maximum number of IRLS cycles: %i" % self.maxIRLSiter) self.opt.stopNextIteration = True return # Check if the function has changed enough if self.f_change < self.f_min_change and self.IRLSiter > 1: - print "Minimum decrease in regularization. End of IRLS" + print("Minimum decrease in regularization. End of IRLS") self.opt.stopNextIteration = True return else: @@ -385,7 +397,7 @@ class Update_IRLS(InversionDirective): phim_new = self.reg.eval(self.invProb.curModel) # Update gamma to scale the regularization between IRLS iterations - self.reg.gamma = self.phi_m_last / phim_new + self.reg.gamma = old_div(self.phi_m_last, phim_new) # Reset the regularization matrices again for new gamma self.reg._Wsmall = None @@ -394,7 +406,7 @@ class Update_IRLS(InversionDirective): self.reg._Wz = None # Check if misfit is within the tolerance, otherwise scale beta - val = self.invProb.phi_d / (self.survey.nD*0.5) + val = old_div(self.invProb.phi_d, (self.survey.nD*0.5)) if np.abs(1.-val) > self.beta_tol: self.invProb.beta = self.invProb.beta * self.survey.nD*0.5 / self.invProb.phi_d @@ -438,7 +450,7 @@ class Update_Wj(InversionDirective): m = self.invProb.curModel if self.k is None: - self.k = int(self.survey.nD/10) + self.k = int(old_div(self.survey.nD,10)) def JtJv(v): @@ -447,6 +459,6 @@ class Update_Wj(InversionDirective): return self.prob.Jtvec(m,Jv) JtJdiag = Utils.diagEst(JtJv,len(m),k=self.k) - JtJdiag = JtJdiag / max(JtJdiag) + JtJdiag = old_div(JtJdiag, max(JtJdiag)) self.reg.wght = JtJdiag diff --git a/SimPEG/EM/Analytics/DC.py b/SimPEG/EM/Analytics/DC.py index f67843d6..d974e686 100644 --- a/SimPEG/EM/Analytics/DC.py +++ b/SimPEG/EM/Analytics/DC.py @@ -1,3 +1,11 @@ +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 builtins import range +from past.utils import old_div import numpy as np from scipy.constants import mu_0, pi from scipy import special @@ -24,8 +32,8 @@ def DCAnalyticHalf(txloc, rxlocs, sigma, earth_type="wholespace"): rM = np.sqrt( (M[:,0]-txloc[0])**2 + (M[:,1]-txloc[1])**2 + (M[:,2]-txloc[1])**2 ) rN = np.sqrt( (N[:,0]-txloc[0])**2 + (N[:,1]-txloc[1])**2 + (N[:,2]-txloc[1])**2 ) - phiM = 1./(4*np.pi*rM*sigma) - phiN = 1./(4*np.pi*rN*sigma) + phiM = old_div(1.,(4*np.pi*rM*sigma)) + phiN = old_div(1.,(4*np.pi*rN*sigma)) phi = phiM - phiN if earth_type == "halfspace": @@ -69,8 +77,8 @@ def DCAnalyticSphere(txloc, rxloc, xc, radius, sigma, sigma1, \ Pleg.append(special.legendre(i, monic=0)) - rho = 1./sigma - rho1 = 1./sigma1 + rho = old_div(1.,sigma) + rho1 = old_div(1.,sigma1) # Center of the sphere should be aligned in txloc in y-direction yc = txloc[1] diff --git a/SimPEG/EM/Analytics/FDEM.py b/SimPEG/EM/Analytics/FDEM.py index 1f52459c..08ce1a00 100644 --- a/SimPEG/EM/Analytics/FDEM.py +++ b/SimPEG/EM/Analytics/FDEM.py @@ -1,4 +1,9 @@ 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() import numpy as np from scipy.constants import mu_0, pi from scipy.special import erf diff --git a/SimPEG/EM/Analytics/FDEMDipolarfields.py b/SimPEG/EM/Analytics/FDEMDipolarfields.py index e65bbdd1..a6e9201f 100644 --- a/SimPEG/EM/Analytics/FDEMDipolarfields.py +++ b/SimPEG/EM/Analytics/FDEMDipolarfields.py @@ -1,4 +1,9 @@ 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() import numpy as np from scipy.constants import mu_0, pi, epsilon_0 from scipy.special import erf diff --git a/SimPEG/EM/Analytics/FDEMcasing.py b/SimPEG/EM/Analytics/FDEMcasing.py index d3db381d..7d0f5432 100644 --- a/SimPEG/EM/Analytics/FDEMcasing.py +++ b/SimPEG/EM/Analytics/FDEMcasing.py @@ -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 from SimPEG import Utils, np from scipy.constants import mu_0, epsilon_0 from SimPEG.EM.Utils.EMUtils import k @@ -6,7 +13,7 @@ def getKc(freq,sigma,a,b,mu=mu_0,eps=epsilon_0): a = float(a) b = float(b) # return 1./(2*np.pi) * np.sqrt(b / a) * np.exp(-1j*k(freq,sigma,mu,eps)*(b-a)) - return np.sqrt(b / a) * np.exp(-1j*k(freq,sigma,mu,eps)*(b-a)) + return np.sqrt(old_div(b, a)) * np.exp(-1j*k(freq,sigma,mu,eps)*(b-a)) def _r2(xyz): return np.sum(xyz**2,1) @@ -34,7 +41,7 @@ def _getCasingHertzMagDipoleDeriv_r(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones sqrtr2z2 = np.sqrt(r2 + dxyz[:,2]**2) k2 = k(freq,sigma[2],mu[2],eps) - return -HertzZ * np.sqrt(r2) / sqrtr2z2 * (1j*k2 + 1./ sqrtr2z2) + return -HertzZ * np.sqrt(r2) / sqrtr2z2 * (1j*k2 + old_div(1., sqrtr2z2)) def _getCasingHertzMagDipoleDeriv_z(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.): @@ -47,7 +54,7 @@ def _getCasingHertzMagDipoleDeriv_z(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones sqrtr2z2 = np.sqrt(r2z2) k2 = k(freq,sigma[2],mu[2],eps) - return -HertzZ*dxyz[:,2] /sqrtr2z2 * (1j*k2 + 1./sqrtr2z2) + return -HertzZ*dxyz[:,2] /sqrtr2z2 * (1j*k2 + old_div(1.,sqrtr2z2)) def _getCasingHertzMagDipole2Deriv_z_r(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.): HertzZ = _getCasingHertzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment) @@ -62,7 +69,7 @@ def _getCasingHertzMagDipole2Deriv_z_r(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.o sqrtr2z2 = np.sqrt(r2 + z**2) k2 = k(freq,sigma[2],mu[2],eps) - return dHertzZdr*(-z/sqrtr2z2)*(1j*k2+1./sqrtr2z2) + HertzZ*(z*r/sqrtr2z2**3)*(1j*k2 + 2./sqrtr2z2) + return dHertzZdr*(old_div(-z,sqrtr2z2))*(1j*k2+old_div(1.,sqrtr2z2)) + HertzZ*(z*r/sqrtr2z2**3)*(1j*k2 + old_div(2.,sqrtr2z2)) def _getCasingHertzMagDipole2Deriv_z_z(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.): HertzZ = _getCasingHertzMagDipole(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment) @@ -77,7 +84,7 @@ def _getCasingHertzMagDipole2Deriv_z_z(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.o sqrtr2z2 = np.sqrt(r2 + z**2) k2 = k(freq,sigma[2],mu[2],eps) - return (dHertzZdz*z + HertzZ)/sqrtr2z2*(-1j*k2 - 1./sqrtr2z2) + HertzZ*z/sqrtr2z2**3*(1j*k2*z + 2.*z/sqrtr2z2) + return (dHertzZdz*z + HertzZ)/sqrtr2z2*(-1j*k2 - old_div(1.,sqrtr2z2)) + HertzZ*z/sqrtr2z2**3*(1j*k2*z + 2.*z/sqrtr2z2) def getCasingEphiMagDipole(srcloc,obsloc,freq,sigma,a,b,mu=mu_0*np.ones(3),eps=epsilon_0,moment=1.): return 1j * omega(freq) * mu * _getCasingHertzMagDipoleDeriv_r(srcloc,obsloc,freq,sigma,a,b,mu,eps,moment) diff --git a/SimPEG/EM/Analytics/TDEM.py b/SimPEG/EM/Analytics/TDEM.py index b20e8191..5fc1a3aa 100644 --- a/SimPEG/EM/Analytics/TDEM.py +++ b/SimPEG/EM/Analytics/TDEM.py @@ -1,12 +1,19 @@ +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 scipy.constants import mu_0, pi from scipy.special import erf def hzAnalyticDipoleT(r, t, sigma): - theta = np.sqrt((sigma*mu_0)/(4*t)) + theta = np.sqrt(old_div((sigma*mu_0),(4*t))) tr = theta*r etr = erf(tr) - t1 = (9/(2*tr**2) - 1)*etr - t2 = (1/np.sqrt(pi))*(9/tr + 4*tr)*np.exp(-tr**2) - hz = (t1 - t2)/(4*pi*r**3) + t1 = (old_div(9,(2*tr**2)) - 1)*etr + t2 = (old_div(1,np.sqrt(pi)))*(old_div(9,tr) + 4*tr)*np.exp(-tr**2) + hz = old_div((t1 - t2),(4*pi*r**3)) return hz diff --git a/SimPEG/EM/Analytics/__init__.py b/SimPEG/EM/Analytics/__init__.py index 8331501d..380296c6 100644 --- a/SimPEG/EM/Analytics/__init__.py +++ b/SimPEG/EM/Analytics/__init__.py @@ -1,5 +1,11 @@ -from TDEM import hzAnalyticDipoleT -from FDEM import hzAnalyticDipoleF -from FDEMcasing import * -from DC import DCAnalyticHalf, DCAnalyticSphere -from FDEMDipolarfields 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 .TDEM import hzAnalyticDipoleT +from .FDEM import hzAnalyticDipoleF +from .FDEMcasing import * +from .DC import DCAnalyticHalf, DCAnalyticSphere +from .FDEMDipolarfields import * diff --git a/SimPEG/EM/Base.py b/SimPEG/EM/Base.py index 15a0ce60..948e3d18 100644 --- a/SimPEG/EM/Base.py +++ b/SimPEG/EM/Base.py @@ -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 from SimPEG import Survey, Problem, Utils, Models, Maps, PropMaps, np, sp, Solver as SimpegSolver from scipy.constants import mu_0 @@ -11,7 +18,7 @@ class EMPropMap(Maps.PropMap): mu = Maps.Property("Inverse Magnetic Permeability", defaultVal = mu_0, propertyLink=('mui',Maps.ReciprocalMap)) rho = Maps.Property("Electrical Resistivity", propertyLink=('sigma', Maps.ReciprocalMap)) - mui = Maps.Property("Inverse Magnetic Permeability", defaultVal = 1./mu_0, propertyLink=('mu', Maps.ReciprocalMap)) + mui = Maps.Property("Inverse Magnetic Permeability", defaultVal = old_div(1.,mu_0), propertyLink=('mu', Maps.ReciprocalMap)) class BaseEMProblem(Problem.BaseProblem): diff --git a/SimPEG/EM/FDEM/FieldsFDEM.py b/SimPEG/EM/FDEM/FieldsFDEM.py index e0f54be2..11c54af7 100644 --- a/SimPEG/EM/FDEM/FieldsFDEM.py +++ b/SimPEG/EM/FDEM/FieldsFDEM.py @@ -1,3 +1,11 @@ +from __future__ import division +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from past.utils import old_div import numpy as np import scipy.sparse as sp import SimPEG @@ -42,7 +50,7 @@ class FieldsFDEM(SimPEG.Problem.Fields): :return: total electric field """ if getattr(self, '_ePrimary', None) is None or getattr(self, '_eSecondary', None) is None: - raise NotImplementedError ('Getting e from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting e from %s is not implemented' %list(self.knownFields.keys())[0]) return self._ePrimary(solution,srcList) + self._eSecondary(solution,srcList) @@ -56,7 +64,7 @@ class FieldsFDEM(SimPEG.Problem.Fields): :return: total magnetic flux density """ if getattr(self, '_bPrimary', None) is None or getattr(self, '_bSecondary', None) is None: - raise NotImplementedError ('Getting b from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting b from %s is not implemented' %list(self.knownFields.keys())[0]) return self._bPrimary(solution, srcList) + self._bSecondary(solution, srcList) @@ -70,7 +78,7 @@ class FieldsFDEM(SimPEG.Problem.Fields): :return: total magnetic field """ if getattr(self, '_hPrimary', None) is None or getattr(self, '_hSecondary', None) is None: - raise NotImplementedError ('Getting h from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting h from %s is not implemented' %list(self.knownFields.keys())[0]) return self._hPrimary(solution, srcList) + self._hSecondary(solution, srcList) @@ -84,7 +92,7 @@ class FieldsFDEM(SimPEG.Problem.Fields): :return: total current density """ if getattr(self, '_jPrimary', None) is None or getattr(self, '_jSecondary', None) is None: - raise NotImplementedError ('Getting j from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting j from %s is not implemented' %list(self.knownFields.keys())[0]) return self._jPrimary(solution, srcList) + self._jSecondary(solution, srcList) @@ -100,7 +108,7 @@ class FieldsFDEM(SimPEG.Problem.Fields): :return: derivative times a vector (or tuple for adjoint) """ if getattr(self, '_eDeriv_u', None) is None or getattr(self, '_eDeriv_m', None) is None: - raise NotImplementedError ('Getting eDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting eDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._eDeriv_u(src, v, adjoint), self._eDeriv_m(src, v, adjoint) @@ -118,7 +126,7 @@ class FieldsFDEM(SimPEG.Problem.Fields): :return: derivative times a vector (or tuple for adjoint) """ if getattr(self, '_bDeriv_u', None) is None or getattr(self, '_bDeriv_m', None) is None: - raise NotImplementedError ('Getting bDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting bDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._bDeriv_u(src, v, adjoint), self._bDeriv_m(src, v, adjoint) @@ -136,7 +144,7 @@ class FieldsFDEM(SimPEG.Problem.Fields): :return: derivative times a vector (or tuple for adjoint) """ if getattr(self, '_hDeriv_u', None) is None or getattr(self, '_hDeriv_m', None) is None: - raise NotImplementedError ('Getting hDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting hDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._hDeriv_u(src, v, adjoint), self._hDeriv_m(src, v, adjoint) @@ -154,7 +162,7 @@ class FieldsFDEM(SimPEG.Problem.Fields): :return: derivative times a vector (or tuple for adjoint) """ if getattr(self, '_jDeriv_u', None) is None or getattr(self, '_jDeriv_m', None) is None: - raise NotImplementedError ('Getting jDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting jDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._jDeriv_u(src, v, adjoint), self._jDeriv_m(src, v, adjoint) @@ -285,7 +293,7 @@ class Fields3D_e(FieldsFDEM): C = self._edgeCurl b = (C * eSolution) for i, src in enumerate(srcList): - b[:,i] *= - 1./(1j*omega(src.freq)) + b[:,i] *= old_div(- 1.,(1j*omega(src.freq))) s_m, _ = src.eval(self.prob) b[:,i] = b[:,i]+ 1./(1j*omega(src.freq)) * s_m return b @@ -331,8 +339,8 @@ class Fields3D_e(FieldsFDEM): :return: current density """ aveE2CCV = self._aveE2CCV - n = int(aveE2CCV.shape[0] / self._nC) # number of components (instead of checking if cyl or not) - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(aveE2CCV.shape[0], self._nC)) # number of components (instead of checking if cyl or not) + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) return VI * (aveE2CCV * (self._MeSigma * self._e(eSolution,srcList) ) ) def _jDeriv_u(self, src, du_dm_v, adjoint = False): @@ -345,8 +353,8 @@ class Fields3D_e(FieldsFDEM): :rtype: numpy.ndarray :return: product of the derivative of the current density with respect to the field we solved for with a vector """ - n = int(self._aveE2CCV.shape[0] / self._nC) # number of components (instead of checking if cyl or not) - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveE2CCV.shape[0], self._nC)) # number of components (instead of checking if cyl or not) + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return self._eDeriv_u(src, self._MeSigma.T * (self._aveE2CCV.T * (VI.T * du_dm_v) ), adjoint = adjoint) @@ -364,8 +372,8 @@ class Fields3D_e(FieldsFDEM): :return: product of the current density derivative with respect to the inversion model with a vector """ e = self[src, 'e'] - n = int(self._aveE2CCV.shape[0] / self._nC) #number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveE2CCV.shape[0], self._nC)) #number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return self._MeSigmaDeriv(e).T * (self._aveE2CCV.T * (VI.T * v)) + self._eDeriv_m(src, self._aveE2CCV.T * (VI.T * v), adjoint=adjoint) @@ -382,8 +390,8 @@ class Fields3D_e(FieldsFDEM): :rtype: numpy.ndarray :return: magnetic field """ - n = int(self._aveF2CCV.shape[0] / self._nC) # Number of Components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) # Number of Components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) return VI * (self._aveF2CCV * (self._MfMui * self._b(eSolution, srcList))) @@ -397,8 +405,8 @@ class Fields3D_e(FieldsFDEM): :rtype: numpy.ndarray :return: product of the derivative of the magnetic field with respect to the field we solved for with a vector """ - n = int(self._aveF2CCV.shape[0] / self._nC) # Number of Components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) # Number of Components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: v = self._MfMui.T * (self._aveF2CCV.T * (VI.T * du_dm_v)) return self._bDeriv_u(src, v, adjoint=adjoint) @@ -414,8 +422,8 @@ class Fields3D_e(FieldsFDEM): :rtype: numpy.ndarray :return: product of the magnetic field derivative with respect to the inversion model with a vector """ - n = int(self._aveF2CCV.shape[0] / self._nC) # Number of Components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) # Number of Components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: v = self._MfMui.T * (self._aveF2CCV.T * (VI.T * v)) return self._bDeriv_m(src, v, adjoint=adjoint) @@ -607,8 +615,8 @@ class Fields3D_b(FieldsFDEM): :return: primary current density """ - n = int(self._aveE2CCV.shape[0] / self._nC) # number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveE2CCV.shape[0], self._nC)) # number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) return VI * (self._aveE2CCV * ( self._MeSigma * self._e(bSolution,srcList ) ) ) @@ -624,8 +632,8 @@ class Fields3D_b(FieldsFDEM): :rtype: numpy.ndarray :return: product of the derivative of the current density with respect to the field we solved for with a vector """ - n = int(self._aveE2CCV.shape[0] / self._nC) # number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveE2CCV.shape[0], self._nC)) # number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return self._MfMui.T * ( self._edgeCurl * ( self._aveE2CCV.T * (VI.T * du_dm_v) ) ) return VI * (self._aveE2CCV * (self._edgeCurl.T * ( self._MfMui * du_dm_v ) ) ) @@ -652,8 +660,8 @@ class Fields3D_b(FieldsFDEM): :rtype: numpy.ndarray :return: magnetic field """ - n = int(self._aveF2CCV.shape[0] / self._nC) #number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) #number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) return VI * (self._aveF2CCV * (self._MfMui * self._b(bSolution, srcList))) def _hDeriv_u(self, src, du_dm_v, adjoint=False): @@ -667,8 +675,8 @@ class Fields3D_b(FieldsFDEM): :rtype: numpy.ndarray :return: product of the derivative of the magnetic field with respect to the field we solved for with a vector """ - n = int(self._aveF2CCV.shape[0] / self._nC) #number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) #number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return self._MfMui.T * ( self._aveF2CCV.T * ( VI.T * du_dm_v) ) @@ -827,7 +835,7 @@ class Fields3D_j(FieldsFDEM): h = (self._edgeCurl.T * (self._MfRho * jSolution) ) for i, src in enumerate(srcList): - h[:,i] *= -1./(1j*omega(src.freq)) + h[:,i] *= old_div(-1.,(1j*omega(src.freq))) s_m,_ = src.eval(self.prob) h[:,i] = h[:,i] + 1./(1j*omega(src.freq)) * (s_m) return self._MeMuI * h @@ -890,8 +898,8 @@ class Fields3D_j(FieldsFDEM): :rtype: numpy.ndarray :return: electric field """ - n = int(self._aveF2CCV.shape[0] / self._nC) # number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) # number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) return VI * (self._aveF2CCV * (self._MfRho * self._j(jSolution, srcList))) def _eDeriv_u(self, src, du_dm_v, adjoint=False): @@ -904,8 +912,8 @@ class Fields3D_j(FieldsFDEM): :rtype: numpy.ndarray :return: product of the derivative of the electric field with respect to the field we solved for with a vector """ - n = int(self._aveF2CCV.shape[0] / self._nC) # number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) # number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return self._MfRho.T * ( self._aveF2CCV.T * ( VI.T * du_dm_v ) ) return VI * (self._aveF2CCV * (self._MfRho * du_dm_v)) @@ -921,8 +929,8 @@ class Fields3D_j(FieldsFDEM): :return: product of the derivative of the electric field with respect to the model with a vector """ jSolution = Utils.mkvc(self[src,'jSolution']) - n = int(self._aveF2CCV.shape[0] / self._nC) # number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) # number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return self._MfRhoDeriv(jSolution).T * ( self._aveF2CCV.T * ( VI.T * v ) ) return VI * (self._aveF2CCV * (self._MfRhoDeriv(jSolution) * v)) @@ -936,8 +944,8 @@ class Fields3D_j(FieldsFDEM): :rtype: numpy.ndarray :return: secondary magnetic flux density """ - n = int(self._aveE2CCV.shape[0] / self._nC) # number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveE2CCV.shape[0], self._nC)) # number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) return VI * (self._aveE2CCV * ( self._MeMu * self._h(jSolution,srcList)) ) @@ -951,8 +959,8 @@ class Fields3D_j(FieldsFDEM): :rtype: numpy.ndarray :return: product of the derivative of the magnetic flux density with respect to the field we solved for with a vector """ - n = int(self._aveF2CCV.shape[0] / self._nC) # number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) # number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return -1./(1j*omega(src.freq)) * self._MfRho.T * ( self._edgeCurl * ( self._aveE2CCV.T * (VI.T * du_dm_v) ) ) @@ -969,8 +977,8 @@ class Fields3D_j(FieldsFDEM): :return: product of the derivative of the magnetic flux density with respect to the model with a vector """ jSolution = self[src,'jSolution'] - n = int(self._aveE2CCV.shape[0] / self._nC) # number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveE2CCV.shape[0], self._nC)) # number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) s_mDeriv,_ = src.evalDeriv(self.prob, adjoint = adjoint) if adjoint: @@ -1151,8 +1159,8 @@ class Fields3D_h(FieldsFDEM): :rtype: numpy.ndarray :return: electric field """ - n = int(self._aveF2CCV.shape[0] / self._nC) #number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) #number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) return VI * (self._aveF2CCV * (self._MfRho * self._j(hSolution, srcList))) def _eDeriv_u(self, src, du_dm_v, adjoint=False): @@ -1165,8 +1173,8 @@ class Fields3D_h(FieldsFDEM): :rtype: numpy.ndarray :return: product of the derivative of the electric field with respect to the field we solved for with a vector """ - n = int(self._aveF2CCV.shape[0] / self._nC) #number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) #number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return self._edgeCurl.T * ( self._MfRho.T * ( self._aveF2CCV.T * ( VI.T * du_dm_v ) ) ) return VI * (self._aveF2CCV * (self._MfRho * self._edgeCurl * du_dm_v )) @@ -1182,8 +1190,8 @@ class Fields3D_h(FieldsFDEM): :return: product of the electric field derivative with respect to the inversion model with a vector """ hSolution = Utils.mkvc(self[src,'hSolution']) - n = int(self._aveF2CCV.shape[0] / self._nC) #number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveF2CCV.shape[0], self._nC)) #number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return ( self._MfRhoDeriv(self._edgeCurl * hSolution).T * ( self._aveF2CCV.T * (VI.T * v) ) ) return VI * (self._aveF2CCV * (self._MfRhoDeriv(self._edgeCurl * hSolution) * v )) @@ -1198,8 +1206,8 @@ class Fields3D_h(FieldsFDEM): :return: magnetic flux density """ h = self._h(hSolution, srcList) - n = int(self._aveE2CCV.shape[0] / self._nC) #number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveE2CCV.shape[0], self._nC)) #number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) return VI * (self._aveE2CCV * (self._MeMu * h)) @@ -1213,8 +1221,8 @@ class Fields3D_h(FieldsFDEM): :rtype: numpy.ndarray :return: product of the derivative of the magnetic flux density with respect to the field we solved for with a vector """ - n = int(self._aveE2CCV.shape[0] / self._nC) #number of components - VI = sdiag(np.kron(np.ones(n), 1./self.prob.mesh.vol)) + n = int(old_div(self._aveE2CCV.shape[0], self._nC)) #number of components + VI = sdiag(np.kron(np.ones(n), old_div(1.,self.prob.mesh.vol))) if adjoint: return self._MeMu.T * (self._aveE2CCV.T * ( VI.T * du_dm_v )) return VI * (self._aveE2CCV * (self._MeMu * du_dm_v)) diff --git a/SimPEG/EM/FDEM/ProblemFDEM.py b/SimPEG/EM/FDEM/ProblemFDEM.py index cbc01b9e..2fafb371 100644 --- a/SimPEG/EM/FDEM/ProblemFDEM.py +++ b/SimPEG/EM/FDEM/ProblemFDEM.py @@ -1,7 +1,13 @@ +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 SimPEG import Problem, Utils, np, sp, Solver as SimpegSolver from scipy.constants import mu_0 -from SurveyFDEM import Survey as SurveyFDEM -from FieldsFDEM import FieldsFDEM, Fields3D_e, Fields3D_b, Fields3D_h, Fields3D_j +from .SurveyFDEM import Survey as SurveyFDEM +from .FieldsFDEM import FieldsFDEM, Fields3D_e, Fields3D_b, Fields3D_h, Fields3D_j from SimPEG.EM.Base import BaseEMProblem from SimPEG.EM.Utils import omega diff --git a/SimPEG/EM/FDEM/RxFDEM.py b/SimPEG/EM/FDEM/RxFDEM.py index 13e2f291..9c2c89fe 100644 --- a/SimPEG/EM/FDEM/RxFDEM.py +++ b/SimPEG/EM/FDEM/RxFDEM.py @@ -1,3 +1,10 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import super +from future import standard_library +standard_library.install_aliases() import SimPEG from SimPEG import sp diff --git a/SimPEG/EM/FDEM/SrcFDEM.py b/SimPEG/EM/FDEM/SrcFDEM.py index 7557ada7..8615b6ef 100644 --- a/SimPEG/EM/FDEM/SrcFDEM.py +++ b/SimPEG/EM/FDEM/SrcFDEM.py @@ -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 from SimPEG import Survey, Problem, Utils, np, sp from scipy.constants import mu_0 from SimPEG.EM.Utils import * @@ -375,7 +382,7 @@ class MagDipole(BaseSrc): formulation = prob._formulation if formulation is 'EB': - mui_s = prob.curModel.mui - 1./self.mu + mui_s = prob.curModel.mui - old_div(1.,self.mu) MMui_s = prob.mesh.getFaceInnerProduct(mui_s) C = prob.mesh.edgeCurl elif formulation is 'HJ': @@ -489,7 +496,7 @@ class MagDipole_Bfield(BaseSrc): formulation = prob._formulation if formulation is 'EB': - mui_s = prob.curModel.mui - 1./self.mu + mui_s = prob.curModel.mui - old_div(1.,self.mu) MMui_s = prob.mesh.getFaceInnerProduct(mui_s) C = prob.mesh.edgeCurl elif formulation is 'HJ': @@ -601,7 +608,7 @@ class CircularLoop(BaseSrc): formulation = prob._formulation if formulation is 'EB': - mui_s = prob.curModel.mui - 1./self.mu + mui_s = prob.curModel.mui - old_div(1.,self.mu) MMui_s = prob.mesh.getFaceInnerProduct(mui_s) C = prob.mesh.edgeCurl diff --git a/SimPEG/EM/FDEM/SurveyFDEM.py b/SimPEG/EM/FDEM/SurveyFDEM.py index 46ae2523..3327d3e0 100644 --- a/SimPEG/EM/FDEM/SurveyFDEM.py +++ b/SimPEG/EM/FDEM/SurveyFDEM.py @@ -1,10 +1,16 @@ +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() import SimPEG from SimPEG.EM.Utils import * from SimPEG.EM.Base import BaseEMSurvey from scipy.constants import mu_0 from SimPEG.Utils import Zero, Identity -import SrcFDEM as Src -import RxFDEM as Rx +from . import SrcFDEM as Src +from . import RxFDEM as Rx from SimPEG import sp class Survey(BaseEMSurvey): diff --git a/SimPEG/EM/FDEM/__init__.py b/SimPEG/EM/FDEM/__init__.py index c4ff6451..5ad6224c 100644 --- a/SimPEG/EM/FDEM/__init__.py +++ b/SimPEG/EM/FDEM/__init__.py @@ -1,5 +1,11 @@ -from SurveyFDEM import Survey -import SrcFDEM as Src -import RxFDEM as Rx -from ProblemFDEM import Problem3D_e, Problem3D_b, Problem3D_j, Problem3D_h -from FieldsFDEM import Fields3D_e, Fields3D_b, Fields3D_j, Fields3D_h +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 .SurveyFDEM import Survey +from . import SrcFDEM as Src +from . import RxFDEM as Rx +from .ProblemFDEM import Problem3D_e, Problem3D_b, Problem3D_j, Problem3D_h +from .FieldsFDEM import Fields3D_e, Fields3D_b, Fields3D_j, Fields3D_h diff --git a/SimPEG/EM/Static/DC/BoundaryUtils.py b/SimPEG/EM/Static/DC/BoundaryUtils.py index 3967eb46..8964da84 100644 --- a/SimPEG/EM/Static/DC/BoundaryUtils.py +++ b/SimPEG/EM/Static/DC/BoundaryUtils.py @@ -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 def getxBCyBC_CC(mesh, alpha, beta, gamma): @@ -31,15 +38,15 @@ def getxBCyBC_CC(mesh, alpha, beta, gamma): # h_xm, h_xp = mesh.gridCC[fCCxm], mesh.gridCC[fCCxp] h_xm, h_xp = mesh.hx[0], mesh.hx[-1] - a_xm = gamma_xm/(0.5*alpha_xm-beta_xm/h_xm) - b_xm = (0.5*alpha_xm+beta_xm/h_xm)/(0.5*alpha_xm-beta_xm/h_xm) - a_xp = gamma_xp/(0.5*alpha_xp-beta_xp/h_xp) - b_xp = (0.5*alpha_xp+beta_xp/h_xp)/(0.5*alpha_xp-beta_xp/h_xp) + a_xm = old_div(gamma_xm,(0.5*alpha_xm-old_div(beta_xm,h_xm))) + b_xm = old_div((0.5*alpha_xm+old_div(beta_xm,h_xm)),(0.5*alpha_xm-old_div(beta_xm,h_xm))) + a_xp = old_div(gamma_xp,(0.5*alpha_xp-old_div(beta_xp,h_xp))) + b_xp = old_div((0.5*alpha_xp+old_div(beta_xp,h_xp)),(0.5*alpha_xp-old_div(beta_xp,h_xp))) xBC_xm = 0.5*a_xm xBC_xp = 0.5*a_xp/b_xp yBC_xm = 0.5*(1.-b_xm) - yBC_xp = 0.5*(1.-1./b_xp) + yBC_xp = 0.5*(1.-old_div(1.,b_xp)) xBC = np.r_[xBC_xm, xBC_xp] yBC = np.r_[yBC_xm, yBC_xp] @@ -62,24 +69,24 @@ def getxBCyBC_CC(mesh, alpha, beta, gamma): h_xm, h_xp = mesh.hx[0]*np.ones_like(alpha_xm), mesh.hx[-1]*np.ones_like(alpha_xp) h_ym, h_yp = mesh.hy[0]*np.ones_like(alpha_ym), mesh.hy[-1]*np.ones_like(alpha_yp) - a_xm = gamma_xm/(0.5*alpha_xm-beta_xm/h_xm) - b_xm = (0.5*alpha_xm+beta_xm/h_xm)/(0.5*alpha_xm-beta_xm/h_xm) - a_xp = gamma_xp/(0.5*alpha_xp-beta_xp/h_xp) - b_xp = (0.5*alpha_xp+beta_xp/h_xp)/(0.5*alpha_xp-beta_xp/h_xp) + a_xm = old_div(gamma_xm,(0.5*alpha_xm-old_div(beta_xm,h_xm))) + b_xm = old_div((0.5*alpha_xm+old_div(beta_xm,h_xm)),(0.5*alpha_xm-old_div(beta_xm,h_xm))) + a_xp = old_div(gamma_xp,(0.5*alpha_xp-old_div(beta_xp,h_xp))) + b_xp = old_div((0.5*alpha_xp+old_div(beta_xp,h_xp)),(0.5*alpha_xp-old_div(beta_xp,h_xp))) - a_ym = gamma_ym/(0.5*alpha_ym-beta_ym/h_ym) - b_ym = (0.5*alpha_ym+beta_ym/h_ym)/(0.5*alpha_ym-beta_ym/h_ym) - a_yp = gamma_yp/(0.5*alpha_yp-beta_yp/h_yp) - b_yp = (0.5*alpha_yp+beta_yp/h_yp)/(0.5*alpha_yp-beta_yp/h_yp) + a_ym = old_div(gamma_ym,(0.5*alpha_ym-old_div(beta_ym,h_ym))) + b_ym = old_div((0.5*alpha_ym+old_div(beta_ym,h_ym)),(0.5*alpha_ym-old_div(beta_ym,h_ym))) + a_yp = old_div(gamma_yp,(0.5*alpha_yp-old_div(beta_yp,h_yp))) + b_yp = old_div((0.5*alpha_yp+old_div(beta_yp,h_yp)),(0.5*alpha_yp-old_div(beta_yp,h_yp))) xBC_xm = 0.5*a_xm xBC_xp = 0.5*a_xp/b_xp yBC_xm = 0.5*(1.-b_xm) - yBC_xp = 0.5*(1.-1./b_xp) + yBC_xp = 0.5*(1.-old_div(1.,b_xp)) xBC_ym = 0.5*a_ym xBC_yp = 0.5*a_yp/b_yp yBC_ym = 0.5*(1.-b_ym) - yBC_yp = 0.5*(1.-1./b_yp) + yBC_yp = 0.5*(1.-old_div(1.,b_yp)) sortindsfx = np.argsort(np.r_[np.arange(mesh.nFx)[fxm], np.arange(mesh.nFx)[fxp]]) sortindsfy = np.argsort(np.r_[np.arange(mesh.nFy)[fym], np.arange(mesh.nFy)[fyp]]) @@ -114,33 +121,33 @@ def getxBCyBC_CC(mesh, alpha, beta, gamma): h_ym, h_yp = mesh.hy[0]*np.ones_like(alpha_ym), mesh.hy[-1]*np.ones_like(alpha_yp) h_zm, h_zp = mesh.hz[0]*np.ones_like(alpha_zm), mesh.hz[-1]*np.ones_like(alpha_zp) - a_xm = gamma_xm/(0.5*alpha_xm-beta_xm/h_xm) - b_xm = (0.5*alpha_xm+beta_xm/h_xm)/(0.5*alpha_xm-beta_xm/h_xm) - a_xp = gamma_xp/(0.5*alpha_xp-beta_xp/h_xp) - b_xp = (0.5*alpha_xp+beta_xp/h_xp)/(0.5*alpha_xp-beta_xp/h_xp) + a_xm = old_div(gamma_xm,(0.5*alpha_xm-old_div(beta_xm,h_xm))) + b_xm = old_div((0.5*alpha_xm+old_div(beta_xm,h_xm)),(0.5*alpha_xm-old_div(beta_xm,h_xm))) + a_xp = old_div(gamma_xp,(0.5*alpha_xp-old_div(beta_xp,h_xp))) + b_xp = old_div((0.5*alpha_xp+old_div(beta_xp,h_xp)),(0.5*alpha_xp-old_div(beta_xp,h_xp))) - a_ym = gamma_ym/(0.5*alpha_ym-beta_ym/h_ym) - b_ym = (0.5*alpha_ym+beta_ym/h_ym)/(0.5*alpha_ym-beta_ym/h_ym) - a_yp = gamma_yp/(0.5*alpha_yp-beta_yp/h_yp) - b_yp = (0.5*alpha_yp+beta_yp/h_yp)/(0.5*alpha_yp-beta_yp/h_yp) + a_ym = old_div(gamma_ym,(0.5*alpha_ym-old_div(beta_ym,h_ym))) + b_ym = old_div((0.5*alpha_ym+old_div(beta_ym,h_ym)),(0.5*alpha_ym-old_div(beta_ym,h_ym))) + a_yp = old_div(gamma_yp,(0.5*alpha_yp-old_div(beta_yp,h_yp))) + b_yp = old_div((0.5*alpha_yp+old_div(beta_yp,h_yp)),(0.5*alpha_yp-old_div(beta_yp,h_yp))) - a_zm = gamma_zm/(0.5*alpha_zm-beta_zm/h_zm) - b_zm = (0.5*alpha_zm+beta_zm/h_zm)/(0.5*alpha_zm-beta_zm/h_zm) - a_zp = gamma_zp/(0.5*alpha_zp-beta_zp/h_zp) - b_zp = (0.5*alpha_zp+beta_zp/h_zp)/(0.5*alpha_zp-beta_zp/h_zp) + a_zm = old_div(gamma_zm,(0.5*alpha_zm-old_div(beta_zm,h_zm))) + b_zm = old_div((0.5*alpha_zm+old_div(beta_zm,h_zm)),(0.5*alpha_zm-old_div(beta_zm,h_zm))) + a_zp = old_div(gamma_zp,(0.5*alpha_zp-old_div(beta_zp,h_zp))) + b_zp = old_div((0.5*alpha_zp+old_div(beta_zp,h_zp)),(0.5*alpha_zp-old_div(beta_zp,h_zp))) xBC_xm = 0.5*a_xm xBC_xp = 0.5*a_xp/b_xp yBC_xm = 0.5*(1.-b_xm) - yBC_xp = 0.5*(1.-1./b_xp) + yBC_xp = 0.5*(1.-old_div(1.,b_xp)) xBC_ym = 0.5*a_ym xBC_yp = 0.5*a_yp/b_yp yBC_ym = 0.5*(1.-b_ym) - yBC_yp = 0.5*(1.-1./b_yp) + yBC_yp = 0.5*(1.-old_div(1.,b_yp)) xBC_zm = 0.5*a_zm xBC_zp = 0.5*a_zp/b_zp yBC_zm = 0.5*(1.-b_zm) - yBC_zp = 0.5*(1.-1./b_zp) + yBC_zp = 0.5*(1.-old_div(1.,b_zp)) sortindsfx = np.argsort(np.r_[np.arange(mesh.nFx)[fxm], np.arange(mesh.nFx)[fxp]]) sortindsfy = np.argsort(np.r_[np.arange(mesh.nFy)[fym], np.arange(mesh.nFy)[fyp]]) diff --git a/SimPEG/EM/Static/DC/FieldsDC.py b/SimPEG/EM/Static/DC/FieldsDC.py index 6fcea083..0c151bb7 100644 --- a/SimPEG/EM/Static/DC/FieldsDC.py +++ b/SimPEG/EM/Static/DC/FieldsDC.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import SimPEG from SimPEG.Utils import Identity, Zero import numpy as np @@ -9,7 +15,7 @@ class Fields(SimPEG.Problem.Fields): def _phiDeriv(self, src, du_dm_v, v, adjoint=False): if getattr(self, '_phiDeriv_u', None) is None or getattr(self, '_phiDeriv_m', None) is None: - raise NotImplementedError ('Getting phiDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting phiDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._phiDeriv_u(src, v, adjoint=adjoint), self._phiDeriv_m(src, v, adjoint=adjoint) @@ -18,7 +24,7 @@ class Fields(SimPEG.Problem.Fields): def _eDeriv(self, src, du_dm_v, v, adjoint=False): if getattr(self, '_eDeriv_u', None) is None or getattr(self, '_eDeriv_m', None) is None: - raise NotImplementedError ('Getting eDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting eDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._eDeriv_u(src, v, adjoint), self._eDeriv_m(src, v, adjoint) @@ -26,7 +32,7 @@ class Fields(SimPEG.Problem.Fields): def _jDeriv(self, src, du_dm_v, v, adjoint=False): if getattr(self, '_jDeriv_u', None) is None or getattr(self, '_jDeriv_m', None) is None: - raise NotImplementedError ('Getting jDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting jDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._jDeriv_u(src, v, adjoint), self._jDeriv_m(src, v, adjoint) diff --git a/SimPEG/EM/Static/DC/FieldsDC_2D.py b/SimPEG/EM/Static/DC/FieldsDC_2D.py index da1fbf97..df0826d6 100644 --- a/SimPEG/EM/Static/DC/FieldsDC_2D.py +++ b/SimPEG/EM/Static/DC/FieldsDC_2D.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import SimPEG from SimPEG.Utils import Identity, Zero import numpy as np @@ -32,7 +38,7 @@ class Fields_ky(SimPEG.Problem.TimeFields): def _phiDeriv(self,kyInd, src, du_dm_v, v, adjoint=False): if getattr(self, '_phiDeriv_u', None) is None or getattr(self, '_phiDeriv_m', None) is None: - raise NotImplementedError ('Getting phiDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting phiDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._phiDeriv_u(kyInd, src, v, adjoint=adjoint), self._phiDeriv_m(kyInd, src, v, adjoint=adjoint) @@ -41,7 +47,7 @@ class Fields_ky(SimPEG.Problem.TimeFields): def _eDeriv(self,kyInd, src, du_dm_v, v, adjoint=False): if getattr(self, '_eDeriv_u', None) is None or getattr(self, '_eDeriv_m', None) is None: - raise NotImplementedError ('Getting eDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting eDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._eDeriv_u(kyInd, src, v, adjoint), self._eDeriv_m(kyInd, src, v, adjoint) @@ -49,7 +55,7 @@ class Fields_ky(SimPEG.Problem.TimeFields): def _jDeriv(self,kyInd, src, du_dm_v, v, adjoint=False): if getattr(self, '_jDeriv_u', None) is None or getattr(self, '_jDeriv_m', None) is None: - raise NotImplementedError ('Getting jDerivs from %s is not implemented' %self.knownFields.keys()[0]) + raise NotImplementedError ('Getting jDerivs from %s is not implemented' %list(self.knownFields.keys())[0]) if adjoint: return self._jDeriv_u(kyInd, src, v, adjoint), self._jDeriv_m(kyInd, src, v, adjoint) diff --git a/SimPEG/EM/Static/DC/ProblemDC.py b/SimPEG/EM/Static/DC/ProblemDC.py index 81653e83..af3fde21 100644 --- a/SimPEG/EM/Static/DC/ProblemDC.py +++ b/SimPEG/EM/Static/DC/ProblemDC.py @@ -1,11 +1,17 @@ +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 SimPEG import Problem, Utils from SimPEG.EM.Base import BaseEMProblem -from SurveyDC import Survey -from FieldsDC import Fields, Fields_CC, Fields_N +from .SurveyDC import Survey +from .FieldsDC import Fields, Fields_CC, Fields_N from SimPEG.Utils import sdiag import numpy as np from SimPEG.Utils import Zero -from BoundaryUtils import getxBCyBC_CC +from .BoundaryUtils import getxBCyBC_CC class BaseDCProblem(BaseEMProblem): diff --git a/SimPEG/EM/Static/DC/ProblemDC_2D.py b/SimPEG/EM/Static/DC/ProblemDC_2D.py index 8e0561f9..dd7a4198 100644 --- a/SimPEG/EM/Static/DC/ProblemDC_2D.py +++ b/SimPEG/EM/Static/DC/ProblemDC_2D.py @@ -1,11 +1,19 @@ +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 past.utils import old_div from SimPEG import Problem, Utils from SimPEG.EM.Base import BaseEMProblem -from SurveyDC import Survey, Survey_ky -from FieldsDC_2D import Fields_ky, Fields_ky_CC, Fields_ky_N +from .SurveyDC import Survey, Survey_ky +from .FieldsDC_2D import Fields_ky, Fields_ky_CC, Fields_ky_N from SimPEG.Utils import sdiag import numpy as np from SimPEG.Utils import Zero -from BoundaryUtils import getxBCyBC_CC +from .BoundaryUtils import getxBCyBC_CC class BaseDCProblem_2D(BaseEMProblem): @@ -182,8 +190,8 @@ class Problem2D_CC(BaseDCProblem_2D): MfRhoIDeriv = self.MfRhoIDeriv rho = self.curModel.rho if adjoint: - return(MfRhoIDeriv( G * u ).T) * ( D.T * v) + ky**2*Utils.sdiag(u.flatten()*vol*(-1./rho**2))*v - return D * ((MfRhoIDeriv( G * u )) * v) + ky**2*Utils.sdiag(u.flatten()*vol*(-1./rho**2))*v + return(MfRhoIDeriv( G * u ).T) * ( D.T * v) + ky**2*Utils.sdiag(u.flatten()*vol*(old_div(-1.,rho**2)))*v + return D * ((MfRhoIDeriv( G * u )) * v) + ky**2*Utils.sdiag(u.flatten()*vol*(old_div(-1.,rho**2)))*v def getRHS(self, ky): """ diff --git a/SimPEG/EM/Static/DC/RxDC.py b/SimPEG/EM/Static/DC/RxDC.py index d2ec6098..a3d671ee 100644 --- a/SimPEG/EM/Static/DC/RxDC.py +++ b/SimPEG/EM/Static/DC/RxDC.py @@ -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 builtins import range import SimPEG import numpy as np from SimPEG.Utils import Zero, closestPoints diff --git a/SimPEG/EM/Static/DC/SrcDC.py b/SimPEG/EM/Static/DC/SrcDC.py index ae52f376..7837ab14 100644 --- a/SimPEG/EM/Static/DC/SrcDC.py +++ b/SimPEG/EM/Static/DC/SrcDC.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import SimPEG # from SimPEG.EM.Base import BaseEMSurvey from SimPEG.Utils import Zero, closestPoints, mkvc diff --git a/SimPEG/EM/Static/DC/SurveyDC.py b/SimPEG/EM/Static/DC/SurveyDC.py index d9c493a2..48e9ed0c 100644 --- a/SimPEG/EM/Static/DC/SurveyDC.py +++ b/SimPEG/EM/Static/DC/SurveyDC.py @@ -1,9 +1,15 @@ +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() import SimPEG from SimPEG.EM.Base import BaseEMSurvey from SimPEG import sp, Survey from SimPEG.Utils import Zero, Identity -from RxDC import BaseRx -from SrcDC import BaseSrc +from .RxDC import BaseRx +from .SrcDC import BaseSrc class Survey(BaseEMSurvey): rxPair = BaseRx diff --git a/SimPEG/EM/Static/DC/Utils.py b/SimPEG/EM/Static/DC/Utils.py index 626ae368..d9b34e73 100644 --- a/SimPEG/EM/Static/DC/Utils.py +++ b/SimPEG/EM/Static/DC/Utils.py @@ -1,3 +1,11 @@ +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 builtins import range +from past.utils import old_div import numpy as np def WennerSrcList(nElecs, aSpacing, in2D=False, plotIt=False): @@ -5,7 +13,7 @@ def WennerSrcList(nElecs, aSpacing, in2D=False, plotIt=False): import SimPEG.EM.Static.DC as DC elocs = np.arange(0,aSpacing*nElecs,aSpacing) - elocs -= (nElecs*aSpacing - aSpacing)/2 + elocs -= old_div((nElecs*aSpacing - aSpacing),2) space = 1 WENNER = np.zeros((0,),dtype=int) for ii in range(nElecs): diff --git a/SimPEG/EM/Static/DC/__init__.py b/SimPEG/EM/Static/DC/__init__.py index 1080e391..876063ff 100644 --- a/SimPEG/EM/Static/DC/__init__.py +++ b/SimPEG/EM/Static/DC/__init__.py @@ -1,8 +1,14 @@ -from ProblemDC import Problem3D_CC, Problem3D_N -from ProblemDC_2D import Problem2D_CC, Problem2D_N -from SurveyDC import Survey, Survey_ky -import SrcDC as Src #Pole -import RxDC as Rx -from FieldsDC import Fields_CC -from BoundaryUtils import getxBCyBC_CC -import Utils +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 .ProblemDC import Problem3D_CC, Problem3D_N +from .ProblemDC_2D import Problem2D_CC, Problem2D_N +from .SurveyDC import Survey, Survey_ky +from . import SrcDC as Src #Pole +from . import RxDC as Rx +from .FieldsDC import Fields_CC +from .BoundaryUtils import getxBCyBC_CC +from . import Utils diff --git a/SimPEG/EM/Static/IP/ProblemIP.py b/SimPEG/EM/Static/IP/ProblemIP.py index 77767452..6d1a40ae 100644 --- a/SimPEG/EM/Static/IP/ProblemIP.py +++ b/SimPEG/EM/Static/IP/ProblemIP.py @@ -1,3 +1,9 @@ +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 SimPEG import Problem, Utils, Maps, Mesh from SimPEG.EM.Base import BaseEMProblem from SimPEG.EM.Static.DC.FieldsDC import Fields, Fields_CC, Fields_N @@ -5,7 +11,7 @@ from SimPEG.Utils import sdiag import numpy as np from SimPEG.Utils import Zero from SimPEG.EM.Static.DC import getxBCyBC_CC -from SurveyIP import Survey +from .SurveyIP import Survey class IPPropMap(Maps.PropMap): """ diff --git a/SimPEG/EM/Static/IP/SurveyIP.py b/SimPEG/EM/Static/IP/SurveyIP.py index c980d927..3702b8a4 100644 --- a/SimPEG/EM/Static/IP/SurveyIP.py +++ b/SimPEG/EM/Static/IP/SurveyIP.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import SimPEG from SimPEG.EM.Base import BaseEMSurvey from SimPEG import sp, Survey diff --git a/SimPEG/EM/Static/IP/__init__.py b/SimPEG/EM/Static/IP/__init__.py index 663117d3..069e2aae 100644 --- a/SimPEG/EM/Static/IP/__init__.py +++ b/SimPEG/EM/Static/IP/__init__.py @@ -1,2 +1,8 @@ -from ProblemIP import Problem3D_CC, Problem3D_N -from SurveyIP import Survey +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 .ProblemIP import Problem3D_CC, Problem3D_N +from .SurveyIP import Survey diff --git a/SimPEG/EM/Static/SIP/ProblemSIP.py b/SimPEG/EM/Static/SIP/ProblemSIP.py index 97be624d..1801b76c 100644 --- a/SimPEG/EM/Static/SIP/ProblemSIP.py +++ b/SimPEG/EM/Static/SIP/ProblemSIP.py @@ -1,3 +1,12 @@ +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 builtins import range +from past.utils import old_div from SimPEG import Problem, Utils, Maps, Mesh from SimPEG.EM.Base import BaseEMProblem from SimPEG.EM.Static.DC.FieldsDC import Fields, Fields_CC, Fields_N @@ -5,7 +14,7 @@ from SimPEG.Utils import sdiag import numpy as np from SimPEG.Utils import Zero from SimPEG.EM.Static.DC import getxBCyBC_CC -from SurveySIP import Survey, Data +from .SurveySIP import Survey, Data class ColeColePropMap(Maps.PropMap): """ @@ -105,7 +114,7 @@ class BaseSIPProblem(BaseEMProblem): JvAll = [] #Assume only eta and tau (eta first then tau) # v = [2*Mx1] - v = v.reshape((int(v.size/2), 2), order='F') + v = v.reshape((int(old_div(v.size,2)), 2), order='F') for tind in range(len(self.survey.times)): t = self.survey.times[tind] diff --git a/SimPEG/EM/Static/SIP/Regularization.py b/SimPEG/EM/Static/SIP/Regularization.py index 3c20e6fe..eb865f8a 100644 --- a/SimPEG/EM/Static/SIP/Regularization.py +++ b/SimPEG/EM/Static/SIP/Regularization.py @@ -1,3 +1,10 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import range from SimPEG import Utils, Maps, Mesh, sp, np from SimPEG.Regularization import BaseRegularization, Simple diff --git a/SimPEG/EM/Static/SIP/RxSIP.py b/SimPEG/EM/Static/SIP/RxSIP.py index b8144d0f..a5bd8093 100644 --- a/SimPEG/EM/Static/SIP/RxSIP.py +++ b/SimPEG/EM/Static/SIP/RxSIP.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import SimPEG import numpy as np from SimPEG.Utils import Zero, closestPoints diff --git a/SimPEG/EM/Static/SIP/SrcSIP.py b/SimPEG/EM/Static/SIP/SrcSIP.py index b1f0a452..e98a35c3 100644 --- a/SimPEG/EM/Static/SIP/SrcSIP.py +++ b/SimPEG/EM/Static/SIP/SrcSIP.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import SimPEG # from SimPEG.EM.Base import BaseEMSurvey from SimPEG.Utils import Zero, closestPoints, mkvc diff --git a/SimPEG/EM/Static/SIP/SurveySIP.py b/SimPEG/EM/Static/SIP/SurveySIP.py index 9362a35c..39032c6c 100644 --- a/SimPEG/EM/Static/SIP/SurveySIP.py +++ b/SimPEG/EM/Static/SIP/SurveySIP.py @@ -1,3 +1,10 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import str import SimPEG from SimPEG.EM.Base import BaseEMSurvey from SimPEG import np, sp, Survey, Utils diff --git a/SimPEG/EM/Static/SIP/__init__.py b/SimPEG/EM/Static/SIP/__init__.py index 1de46fcf..9572ecbb 100644 --- a/SimPEG/EM/Static/SIP/__init__.py +++ b/SimPEG/EM/Static/SIP/__init__.py @@ -1,5 +1,11 @@ -from ProblemSIP import Problem3D_CC, Problem3D_N -from SurveySIP import Survey, Data -import SrcSIP as Src #Pole -import RxSIP as Rx -from Regularization import MultiRegularization +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 .ProblemSIP import Problem3D_CC, Problem3D_N +from .SurveySIP import Survey, Data +from . import SrcSIP as Src #Pole +from . import RxSIP as Rx +from .Regularization import MultiRegularization diff --git a/SimPEG/EM/Static/Utils/StaticUtils.py b/SimPEG/EM/Static/Utils/StaticUtils.py index 43181c8a..b71901e3 100644 --- a/SimPEG/EM/Static/Utils/StaticUtils.py +++ b/SimPEG/EM/Static/Utils/StaticUtils.py @@ -1,3 +1,12 @@ +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import range +from past.utils import old_div from SimPEG import np from SimPEG.EM.Static import DC, IP @@ -51,7 +60,7 @@ def plot_pseudoSection(DCsurvey, axs, stype='dpdp', dtype="appc", clim=None): # Create mid-point location Cmid = Tx[0] - Pmid = (Rx[0][:,0] + Rx[1][:,0])/2 + Pmid = old_div((Rx[0][:,0] + Rx[1][:,0]),2) if DCsurvey.mesh.dim == 2: zsrc = Tx[1] elif DCsurvey.mesh.dim ==3: @@ -64,12 +73,12 @@ def plot_pseudoSection(DCsurvey, axs, stype='dpdp', dtype="appc", clim=None): NB = np.abs(Tx[1][0] - Rx[1][:,0]) # Create mid-point location - Cmid = (Tx[0][0] + Tx[1][0])/2 - Pmid = (Rx[0][:,0] + Rx[1][:,0])/2 + Cmid = old_div((Tx[0][0] + Tx[1][0]),2) + Pmid = old_div((Rx[0][:,0] + Rx[1][:,0]),2) if DCsurvey.mesh.dim == 2: - zsrc = (Tx[0][1] + Tx[1][1])/2 + zsrc = old_div((Tx[0][1] + Tx[1][1]),2) elif DCsurvey.mesh.dim ==3: - zsrc = (Tx[0][2] + Tx[1][2])/2 + zsrc = old_div((Tx[0][2] + Tx[1][2]),2) # Change output for dtype if dtype == 'volt': @@ -85,16 +94,16 @@ def plot_pseudoSection(DCsurvey, axs, stype='dpdp', dtype="appc", clim=None): elif stype == 'dpdp': - leg = data * 2*np.pi / ( 1/MA - 1/MB + 1/NB - 1/NA ) - LEG.append(1./(2*np.pi) *( 1/MA - 1/MB + 1/NB - 1/NA )) + leg = data * 2*np.pi / ( old_div(1,MA) - old_div(1,MB) + old_div(1,NB) - old_div(1,NA) ) + LEG.append(1./(2*np.pi) *( old_div(1,MA) - old_div(1,MB) + old_div(1,NB) - old_div(1,NA) )) else: - print """dtype must be 'pdp'(pole-dipole) | 'dpdp' (dipole-dipole) """ + print("""dtype must be 'pdp'(pole-dipole) | 'dpdp' (dipole-dipole) """) break if dtype == 'appc': - leg = np.log10(abs(1./leg)) + leg = np.log10(abs(old_div(1.,leg))) rho = np.hstack([rho,leg]) elif dtype == 'appr': @@ -103,15 +112,15 @@ def plot_pseudoSection(DCsurvey, axs, stype='dpdp', dtype="appc", clim=None): rho = np.hstack([rho,leg]) else: - print """dtype must be 'appr' | 'appc' | 'volt' """ + print("""dtype must be 'appr' | 'appc' | 'volt' """) break - midx = np.hstack([midx, ( Cmid + Pmid )/2 ]) + midx = np.hstack([midx, old_div(( Cmid + Pmid ),2) ]) if DCsurvey.mesh.dim==3: - midz = np.hstack([midz, -np.abs(Cmid-Pmid)/2 + zsrc ]) + midz = np.hstack([midz, old_div(-np.abs(Cmid-Pmid),2) + zsrc ]) elif DCsurvey.mesh.dim==2: - midz = np.hstack([midz, -np.abs(Cmid-Pmid)/2 + zsrc ]) + midz = np.hstack([midz, old_div(-np.abs(Cmid-Pmid),2) + zsrc ]) ax = axs # Grid points @@ -184,14 +193,14 @@ def gen_DCIPsurvey(endl, mesh, stype, a, b, n): # Mesure survey length and direction dl_len = xy_2_r(endl[0,0],endl[1,0],endl[0,1],endl[1,1]) - dl_x = ( endl[1,0] - endl[0,0] ) / dl_len - dl_y = ( endl[1,1] - endl[0,1] ) / dl_len + dl_x = old_div(( endl[1,0] - endl[0,0] ), dl_len) + dl_y = old_div(( endl[1,1] - endl[0,1] ), dl_len) - nstn = np.floor( dl_len / a ) + nstn = np.floor( old_div(dl_len, a) ) # Compute discrete pole location along line - stn_x = endl[0,0] + np.array(range(int(nstn)))*dl_x*a - stn_y = endl[0,1] + np.array(range(int(nstn)))*dl_y*a + stn_x = endl[0,0] + np.array(list(range(int(nstn))))*dl_x*a + stn_y = endl[0,1] + np.array(list(range(int(nstn))))*dl_y*a if mesh.dim==2: ztop = mesh.vectorNy[-1] @@ -230,15 +239,15 @@ def gen_DCIPsurvey(endl, mesh, stype, a, b, n): AB = xy_2_r(tx[0,1],endl[1,0],tx[1,1],endl[1,1]) # Number of receivers to fit - nstn = np.min([np.floor( (AB - b) / a ) , n]) + nstn = np.min([np.floor( old_div((AB - b), a) ) , n]) # Check if there is enough space, else break the loop if nstn <= 0: continue # Compute discrete pole location along line - stn_x = N[ii,0] + dl_x*b + np.array(range(int(nstn)))*dl_x*a - stn_y = N[ii,1] + dl_y*b + np.array(range(int(nstn)))*dl_y*a + stn_x = N[ii,0] + dl_x*b + np.array(list(range(int(nstn))))*dl_x*a + stn_y = N[ii,1] + dl_y*b + np.array(list(range(int(nstn))))*dl_y*a # Create receiver poles @@ -275,17 +284,17 @@ def gen_DCIPsurvey(endl, mesh, stype, a, b, n): max_y = endl[1,1] - dl_y * b box_l = np.sqrt( (min_x - max_x)**2 + (min_y - max_y)**2 ) - box_w = box_l/2. + box_w = old_div(box_l,2.) - nstn = np.floor( box_l / a ) + nstn = np.floor( old_div(box_l, a) ) # Compute discrete pole location along line - stn_x = min_x + np.array(range(int(nstn)))*dl_x*a - stn_y = min_y + np.array(range(int(nstn)))*dl_y*a + stn_x = min_x + np.array(list(range(int(nstn))))*dl_x*a + stn_y = min_y + np.array(list(range(int(nstn))))*dl_y*a # Define number of cross lines - nlin = int(np.floor( box_w / a )) - lind = range(-nlin,nlin+1) + nlin = int(np.floor( old_div(box_w, a) )) + lind = list(range(-nlin,nlin+1)) ngrad = nstn * len(lind) @@ -310,7 +319,7 @@ def gen_DCIPsurvey(endl, mesh, stype, a, b, n): srcClass = DC.Src.Dipole([rxClass], M[0,:], N[-1,:]) SrcList.append(srcClass) else: - print """stype must be either 'pdp', 'dpdp' or 'gradient'. """ + print("""stype must be either 'pdp', 'dpdp' or 'gradient'. """) return SrcList diff --git a/SimPEG/EM/Static/Utils/__init__.py b/SimPEG/EM/Static/Utils/__init__.py index adc317ae..8f11fa39 100644 --- a/SimPEG/EM/Static/Utils/__init__.py +++ b/SimPEG/EM/Static/Utils/__init__.py @@ -1 +1,7 @@ -from StaticUtils 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 .StaticUtils import * diff --git a/SimPEG/EM/Static/__init__.py b/SimPEG/EM/Static/__init__.py index f6e0e757..3e558463 100644 --- a/SimPEG/EM/Static/__init__.py +++ b/SimPEG/EM/Static/__init__.py @@ -1,3 +1,9 @@ -import DC -import IP -import SIP +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 . import DC +from . import IP +from . import SIP diff --git a/SimPEG/EM/TDEM/BaseTDEM.py b/SimPEG/EM/TDEM/BaseTDEM.py index cb93ab40..19af289a 100644 --- a/SimPEG/EM/TDEM/BaseTDEM.py +++ b/SimPEG/EM/TDEM/BaseTDEM.py @@ -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 range from SimPEG import Solver, Problem from SimPEG.Problem import BaseTimeProblem from SimPEG.EM.Utils import * @@ -47,7 +54,7 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem): self.waveformType = "GENERAL" def fields(self, m): - if self.verbose: print '%s\nCalculating fields(m)\n%s'%('*'*50,'*'*50) + if self.verbose: print('%s\nCalculating fields(m)\n%s'%('*'*50,'*'*50)) self.curModel = m # Create a fields storage object F = self._FieldsForward_pair(self.mesh, self.survey) @@ -55,7 +62,7 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem): # Set the initial conditions F[src,:,0] = src.getInitialFields(self.mesh) F = self.forward(m, self.getRHS, F=F) - if self.verbose: print '%s\nDone calculating fields(m)\n%s'%('*'*50,'*'*50) + if self.verbose: print('%s\nDone calculating fields(m)\n%s'%('*'*50,'*'*50)) return F def forward(self, m, RHS, F=None): @@ -70,13 +77,13 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem): if Ainv is not None: Ainv.clean() A = self.getA(tInd) - if self.verbose: print 'Factoring... (dt = %e)'%dt + if self.verbose: print('Factoring... (dt = %e)'%dt) Ainv = self.Solver(A, **self.solverOpts) - if self.verbose: print 'Done' + if self.verbose: print('Done') rhs = RHS(tInd, F) - if self.verbose: print ' Solving... (tInd = %d)'%tInd + if self.verbose: print(' Solving... (tInd = %d)'%tInd) sol = Ainv * rhs - if self.verbose: print ' Done...' + if self.verbose: print(' Done...') if sol.ndim == 1: sol.shape = (sol.size,1) F[:,self.solType,tInd+1] = sol @@ -95,13 +102,13 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem): if Ainv is not None: Ainv.clean() A = self.getA(tInd) - if self.verbose: print 'Factoring (Adjoint)... (dt = %e)'%dt + if self.verbose: print('Factoring (Adjoint)... (dt = %e)'%dt) Ainv = self.Solver(A, **self.solverOpts) - if self.verbose: print 'Done' + if self.verbose: print('Done') rhs = RHS(tInd, F) - if self.verbose: print ' Solving (Adjoint)... (tInd = %d)'%tInd + if self.verbose: print(' Solving (Adjoint)... (tInd = %d)'%tInd) sol = Ainv * rhs - if self.verbose: print ' Done...' + if self.verbose: print(' Done...') if sol.ndim == 1: sol.shape = (sol.size,1) F[:,self.solType,tInd+1] = sol @@ -123,14 +130,14 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem): * Compute \\\(\\\\vec{w} = -\\\mathbf{Q} \\\\vec{y}\\\) """ - if self.verbose: print '%s\nCalculating J(v)\n%s'%('*'*50,'*'*50) + if self.verbose: print('%s\nCalculating J(v)\n%s'%('*'*50,'*'*50)) self.curModel = m if f is None: f = self.fields(m) p = self.Gvec(m, v, f) y = self.solveAh(m, p) Jv = self.survey.evalDeriv(f, v=y) - if self.verbose: print '%s\nDone calculating J(v)\n%s'%('*'*50,'*'*50) + if self.verbose: print('%s\nDone calculating J(v)\n%s'%('*'*50,'*'*50)) return - mkvc(Jv) def Jtvec(self, m, v, f=None): @@ -148,7 +155,7 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem): * Compute \\\(\\\\vec{w} = -\\\mathbf{G}^\\\\top y\\\) """ - if self.verbose: print '%s\nCalculating J^T(v)\n%s'%('*'*50,'*'*50) + if self.verbose: print('%s\nCalculating J^T(v)\n%s'%('*'*50,'*'*50)) self.curModel = m if f is None: f = self.fields(m) @@ -159,6 +166,6 @@ class BaseTDEMProblem(BaseTimeProblem, BaseEMProblem): p = self.survey.evalDeriv(f, v=v, adjoint=True) y = self.solveAht(m, p) w = self.Gtvec(m, y, f) - if self.verbose: print '%s\nDone calculating J^T(v)\n%s'%('*'*50,'*'*50) + if self.verbose: print('%s\nDone calculating J^T(v)\n%s'%('*'*50,'*'*50)) return - mkvc(w) diff --git a/SimPEG/EM/TDEM/SurveyTDEM.py b/SimPEG/EM/TDEM/SurveyTDEM.py index 9c9ed4b9..847bdb15 100644 --- a/SimPEG/EM/TDEM/SurveyTDEM.py +++ b/SimPEG/EM/TDEM/SurveyTDEM.py @@ -1,7 +1,13 @@ +from __future__ import print_function +from __future__ import absolute_import +from __future__ import unicode_literals +from __future__ import division +from future import standard_library +standard_library.install_aliases() from SimPEG import Utils, Survey, np from SimPEG.Survey import BaseSurvey from SimPEG.EM.Utils import * -from BaseTDEM import FieldsTDEM +from .BaseTDEM import FieldsTDEM class RxTDEM(Survey.BaseTimeRx): @@ -87,7 +93,7 @@ class SrcTDEM_VMD_MVP(SrcTDEM): def getInitialFields(self, mesh): """Vertical magnetic dipole, magnetic vector potential""" if self.waveformType == "STEPOFF": - print ">> Step waveform: Non-zero initial condition" + print(">> Step waveform: Non-zero initial condition") if mesh._meshType is 'CYL': if mesh.isSymmetric: MVP = MagneticDipoleVectorPotential(self.loc, mesh, 'Ey') @@ -99,7 +105,7 @@ class SrcTDEM_VMD_MVP(SrcTDEM): raise Exception('Unknown mesh for VMD') return {"b": mesh.edgeCurl*MVP} elif self.waveformType == "GENERAL": - print ">> General waveform: Zero initial condition" + print(">> General waveform: Zero initial condition") return {"b": np.zeros(mesh.nF)} else: raise NotImplementedError("Only use STEPOFF or GENERAL") @@ -127,7 +133,7 @@ class SrcTDEM_CircularLoop_MVP(SrcTDEM): def getInitialFields(self, mesh): """Circular Loop, magnetic vector potential""" if self.waveformType == "STEPOFF": - print ">> Step waveform: Non-zero initial condition" + print(">> Step waveform: Non-zero initial condition") if mesh._meshType is 'CYL': if mesh.isSymmetric: MVP = MagneticLoopVectorPotential(self.loc, mesh, 'Ey', self.radius) @@ -139,7 +145,7 @@ class SrcTDEM_CircularLoop_MVP(SrcTDEM): raise Exception('Unknown mesh for CircularLoop') return {"b": mesh.edgeCurl*MVP} elif self.waveformType == "GENERAL": - print ">> General waveform: Zero initial condition" + print(">> General waveform: Zero initial condition") return {"b": np.zeros(mesh.nF)} else: raise NotImplementedError("Only use STEPOFF or GENERAL") diff --git a/SimPEG/EM/TDEM/TDEM_b.py b/SimPEG/EM/TDEM/TDEM_b.py index f88066e0..bb0cfe16 100644 --- a/SimPEG/EM/TDEM/TDEM_b.py +++ b/SimPEG/EM/TDEM/TDEM_b.py @@ -1,7 +1,15 @@ -from BaseTDEM import BaseTDEMProblem, FieldsTDEM +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 past.utils import old_div +from .BaseTDEM import BaseTDEMProblem, FieldsTDEM from SimPEG.Utils import mkvc, sdiag import numpy as np -from SurveyTDEM import SurveyTDEM +from .SurveyTDEM import SurveyTDEM class FieldsTDEM_e_from_b(FieldsTDEM): @@ -69,14 +77,14 @@ class ProblemTDEM_b(BaseTDEMProblem): :return: A """ dt = self.timeSteps[tInd] - return self.MfMui*self.mesh.edgeCurl*self.MeSigmaI*self.mesh.edgeCurl.T*self.MfMui + (1.0/dt)*self.MfMui + return self.MfMui*self.mesh.edgeCurl*self.MeSigmaI*self.mesh.edgeCurl.T*self.MfMui + (old_div(1.0,dt))*self.MfMui def getRHS(self, tInd, F): dt = self.timeSteps[tInd] B_n = np.c_[[F[src,'b',tInd] for src in self.survey.srcList]].T if B_n.shape[0] is not 1: raise NotImplementedError('getRHS not implemented for this shape of B_n') - RHS = (1.0/dt)*self.MfMui*B_n[0,:,:] #TODO: This is a hack + RHS = (old_div(1.0,dt))*self.MfMui*B_n[0,:,:] #TODO: This is a hack return RHS #################################################### diff --git a/SimPEG/EM/TDEM/__init__.py b/SimPEG/EM/TDEM/__init__.py index dd5a8bce..2e4abb62 100644 --- a/SimPEG/EM/TDEM/__init__.py +++ b/SimPEG/EM/TDEM/__init__.py @@ -1,3 +1,9 @@ -from SurveyTDEM import * #SurveyTDEM, RxTDEM, SrcTDEM -from BaseTDEM import BaseTDEMProblem, FieldsTDEM -from TDEM_b import ProblemTDEM_b +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 .SurveyTDEM import * #SurveyTDEM, RxTDEM, SrcTDEM +from .BaseTDEM import BaseTDEMProblem, FieldsTDEM +from .TDEM_b import ProblemTDEM_b diff --git a/SimPEG/EM/Utils/AnalyticUtils.py b/SimPEG/EM/Utils/AnalyticUtils.py index 1827f6b2..d8bfebfc 100644 --- a/SimPEG/EM/Utils/AnalyticUtils.py +++ b/SimPEG/EM/Utils/AnalyticUtils.py @@ -1,3 +1,11 @@ +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 builtins import range +from past.utils import old_div from SimPEG import * from scipy.special import ellipk, ellipe from scipy.constants import mu_0, pi @@ -17,7 +25,7 @@ def MagneticDipoleVectorPotential(srcLoc, obsLoc, component, moment=1., dipoleMo #TODO: break this out! if type(component) in [list, tuple]: - out = range(len(component)) + out = list(range(len(component))) for i, comp in enumerate(component): out[i] = MagneticDipoleVectorPotential(srcLoc, obsLoc, comp, dipoleMoment=dipoleMoment) return np.concatenate(out) @@ -49,7 +57,7 @@ def MagneticDipoleVectorPotential(srcLoc, obsLoc, component, moment=1., dipoleMo dR = obsLoc - srcLoc[i, np.newaxis].repeat(nEdges, axis=0) mCr = np.cross(m, dR) r = np.sqrt((dR**2).sum(axis=1)) - A[:, i] = +(mu/(4*pi)) * mCr[:,dimInd]/(r**3) + A[:, i] = +(old_div(mu,(4*pi))) * mCr[:,dimInd]/(r**3) if nSrc == 1: return A.flatten() return A @@ -90,11 +98,11 @@ def MagneticDipoleFields(srcLoc, obsLoc, component, moment=1., mu = mu_0): dR = obsLoc - srcLoc[i, np.newaxis].repeat(nFaces, axis=0) r = np.sqrt((dR**2).sum(axis=1)) if dimInd == 0: - B[:, i] = +(mu/(4*pi)) /(r**3) * (3*dR[:,2]*dR[:,0]/r**2) + B[:, i] = +(old_div(mu,(4*pi))) /(r**3) * (3*dR[:,2]*dR[:,0]/r**2) elif dimInd == 1: - B[:, i] = +(mu/(4*pi)) /(r**3) * (3*dR[:,2]*dR[:,1]/r**2) + B[:, i] = +(old_div(mu,(4*pi))) /(r**3) * (3*dR[:,2]*dR[:,1]/r**2) elif dimInd == 2: - B[:, i] = +(mu/(4*pi)) /(r**3) * (3*dR[:,2]**2/r**2-1) + B[:, i] = +(old_div(mu,(4*pi))) /(r**3) * (3*dR[:,2]**2/r**2-1) else: raise Exception("Not Implemented") if nSrc == 1: @@ -118,7 +126,7 @@ def MagneticLoopVectorPotential(srcLoc, obsLoc, component, radius, mu=mu_0): """ if type(component) in [list, tuple]: - out = range(len(component)) + out = list(range(len(component))) for i, comp in enumerate(component): out[i] = MagneticLoopVectorPotential(srcLoc, obsLoc, comp, radius, mu) return np.concatenate(out) @@ -148,7 +156,7 @@ def MagneticLoopVectorPotential(srcLoc, obsLoc, component, radius, mu=mu_0): y = obsLoc[:, 1] - srcLoc[i, 1] z = obsLoc[:, 2] - srcLoc[i, 2] r = np.sqrt(x**2 + y**2) - m = (4 * radius * r) / ((radius + r)**2 + z**2) + m = old_div((4 * radius * r), ((radius + r)**2 + z**2)) m[m > 1.] = 1. # m might be slightly larger than 1 due to rounding errors # but ellipke requires 0 <= m <= 1 @@ -158,11 +166,11 @@ def MagneticLoopVectorPotential(srcLoc, obsLoc, component, radius, mu=mu_0): # % 1/r singular at r = 0 and K(m) singular at m = 1 Aphi = np.zeros(n) # % Common factor is (mu * I) / pi with I = 1 and mu = 4e-7 * pi. - Aphi[ind] = 4e-7 / np.sqrt(m[ind]) * np.sqrt(radius / r[ind]) *((1. - m[ind] / 2.) * K[ind] - E[ind]) + Aphi[ind] = 4e-7 / np.sqrt(m[ind]) * np.sqrt(old_div(radius, r[ind])) *((1. - old_div(m[ind], 2.)) * K[ind] - E[ind]) if component == 'x': - A[ind, i] = Aphi[ind] * (-y[ind] / r[ind] ) + A[ind, i] = Aphi[ind] * (old_div(-y[ind], r[ind]) ) elif component == 'y': - A[ind, i] = Aphi[ind] * ( x[ind] / r[ind] ) + A[ind, i] = Aphi[ind] * ( old_div(x[ind], r[ind]) ) else: raise ValueError('Invalid component') diff --git a/SimPEG/EM/Utils/EMUtils.py b/SimPEG/EM/Utils/EMUtils.py index e7dbf441..5486c205 100644 --- a/SimPEG/EM/Utils/EMUtils.py +++ b/SimPEG/EM/Utils/EMUtils.py @@ -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 scipy.constants import mu_0, epsilon_0 @@ -9,8 +16,8 @@ def omega(freq): def k(freq, sigma, mu=mu_0, eps=epsilon_0): """ Eq 1.47 - 1.49 in Ward and Hohmann """ w = omega(freq) - alp = w * np.sqrt( mu*eps/2 * ( np.sqrt(1. + (sigma / (eps*w))**2 ) + 1) ) - beta = w * np.sqrt( mu*eps/2 * ( np.sqrt(1. + (sigma / (eps*w))**2 ) - 1) ) + alp = w * np.sqrt( mu*eps/2 * ( np.sqrt(1. + (old_div(sigma, (eps*w)))**2 ) + 1) ) + beta = w * np.sqrt( mu*eps/2 * ( np.sqrt(1. + (old_div(sigma, (eps*w)))**2 ) - 1) ) return alp - 1j*beta diff --git a/SimPEG/EM/Utils/__init__.py b/SimPEG/EM/Utils/__init__.py index ef779042..781797bb 100644 --- a/SimPEG/EM/Utils/__init__.py +++ b/SimPEG/EM/Utils/__init__.py @@ -1,2 +1,8 @@ -from EMUtils import omega, k -from AnalyticUtils import MagneticDipoleFields, MagneticDipoleVectorPotential, MagneticLoopVectorPotential \ No newline at end of file +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 .EMUtils import omega, k +from .AnalyticUtils import MagneticDipoleFields, MagneticDipoleVectorPotential, MagneticLoopVectorPotential \ No newline at end of file diff --git a/SimPEG/EM/Utils/testingUtils.py b/SimPEG/EM/Utils/testingUtils.py index 22c925b6..04503446 100644 --- a/SimPEG/EM/Utils/testingUtils.py +++ b/SimPEG/EM/Utils/testingUtils.py @@ -1,3 +1,11 @@ +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from past.utils import old_div import unittest from SimPEG import * from SimPEG import EM @@ -24,7 +32,7 @@ def getFDEMProblem(fdemType, comp, SrcList, freq, useMu=False, verbose=False): else: mapping = Maps.ExpMap(mesh) - x = np.array([np.linspace(-5.*cs,-2.*cs,3),np.linspace(5.*cs,2.*cs,3)]) + cs/4. #don't sample right by the source, slightly off alignment from either staggered grid + x = np.array([np.linspace(-5.*cs,-2.*cs,3),np.linspace(5.*cs,2.*cs,3)]) + old_div(cs,4.) #don't sample right by the source, slightly off alignment from either staggered grid XYZ = Utils.ndgrid(x,x,np.linspace(-2.*cs,2.*cs,5)) Rx0 = getattr(EM.FDEM.Rx, 'Point_' + comp[0]) if comp[2] == 'r': @@ -58,7 +66,7 @@ def getFDEMProblem(fdemType, comp, SrcList, freq, useMu=False, verbose=False): Src.append(EM.FDEM.Src.RawVec([rx0], freq, mesh.getEdgeInnerProduct()*S_m, S_e)) if verbose: - print ' Fetching %s problem' % (fdemType) + print(' Fetching %s problem' % (fdemType)) if fdemType == 'e': survey = EM.FDEM.Survey(Src) @@ -83,7 +91,7 @@ def getFDEMProblem(fdemType, comp, SrcList, freq, useMu=False, verbose=False): try: from pymatsolver import MumpsSolver prb.Solver = MumpsSolver - except ImportError, e: + except ImportError as e: prb.Solver = SolverLU return prb @@ -94,7 +102,7 @@ def crossCheckTest(SrcList, fdemType1, fdemType2, comp, addrandoms = False, useM prb1 = getFDEMProblem(fdemType1, comp, SrcList, freq, useMu, verbose) mesh = prb1.mesh - print 'Cross Checking Forward: %s, %s formulations - %s' % (fdemType1, fdemType2, comp) + print('Cross Checking Forward: %s, %s formulations - %s' % (fdemType1, fdemType2, comp)) logsig = np.log(np.ones(mesh.nC)*CONDUCTIVITY) mu = np.ones(mesh.nC)*MU @@ -112,7 +120,7 @@ def crossCheckTest(SrcList, fdemType1, fdemType2, comp, addrandoms = False, useM d1 = survey1.dpred(m) if verbose: - print ' Problem 1 solved' + print(' Problem 1 solved') prb2 = getFDEMProblem(fdemType2, comp, SrcList, freq, useMu, verbose) @@ -121,11 +129,11 @@ def crossCheckTest(SrcList, fdemType1, fdemType2, comp, addrandoms = False, useM d2 = survey2.dpred(m) if verbose: - print ' Problem 2 solved' + print(' Problem 2 solved') r = d2-d1 l2r = l2norm(r) tol = np.max([TOL*(10**int(np.log10(0.5* (l2norm(d1) + l2norm(d2)) ))),FLR]) - print l2norm(d1), l2norm(d2), l2r , tol, l2r < tol + print(l2norm(d1), l2norm(d2), l2r , tol, l2r < tol) return l2r < tol diff --git a/SimPEG/EM/__init__.py b/SimPEG/EM/__init__.py index e42afbc5..b25ca9be 100644 --- a/SimPEG/EM/__init__.py +++ b/SimPEG/EM/__init__.py @@ -1,7 +1,13 @@ -import TDEM -import FDEM -import Static -import Base -import Analytics -import Utils +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 . import TDEM +from . import FDEM +from . import Static +from . import Base +from . import Analytics +from . import Utils from scipy.constants import mu_0, epsilon_0 diff --git a/SimPEG/Examples/DC_Analytic_Dipole.py b/SimPEG/Examples/DC_Analytic_Dipole.py index 347446e3..be9b7ab9 100644 --- a/SimPEG/Examples/DC_Analytic_Dipole.py +++ b/SimPEG/Examples/DC_Analytic_Dipole.py @@ -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 from SimPEG import * import SimPEG.EM.Static.DC as DC @@ -29,7 +36,7 @@ def run(plotIt=True): try: from pymatsolver import MumpsSolver problem.Solver = MumpsSolver - except Exception, e: + except Exception as e: pass data = survey.dpred(sigma) @@ -38,7 +45,7 @@ def run(plotIt=True): rn = (srclocN.reshape([1,-1])).repeat(rxloc.shape[0], axis = 0) rP = np.sqrt(((rxloc-rp)**2).sum(axis=1)) rN = np.sqrt(((rxloc-rn)**2).sum(axis=1)) - return I/(sigma*2.*np.pi)*(1/rP-1/rN) + return I/(sigma*2.*np.pi)*(old_div(1,rP)-old_div(1,rN)) data_anaP = DChalf(np.r_[-200, 0, 0.],np.r_[+200, 0, 0.], xyz_rxP, sighalf) data_anaN = DChalf(np.r_[-200, 0, 0.],np.r_[+200, 0, 0.], xyz_rxN, sighalf) @@ -61,8 +68,8 @@ def run(plotIt=True): ax[0].set_title('Computed') plt.show() - return np.linalg.norm(data-data_ana)/np.linalg.norm(data_ana) + return old_div(np.linalg.norm(data-data_ana),np.linalg.norm(data_ana)) if __name__ == '__main__': - print run() + print(run()) diff --git a/SimPEG/Examples/DC_Forward_PseudoSection.py b/SimPEG/Examples/DC_Forward_PseudoSection.py index 240cbb33..67488bc8 100644 --- a/SimPEG/Examples/DC_Forward_PseudoSection.py +++ b/SimPEG/Examples/DC_Forward_PseudoSection.py @@ -1,3 +1,12 @@ +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import range +from past.utils import old_div from SimPEG import Mesh, Utils, np, sp import SimPEG.DCIP as DC import time @@ -57,7 +66,7 @@ def run(loc=None, sig=None, radi=None, param=None, surveyType='dipole-dipole', u model[ind] = sig[2] # Get index of the center - indy = int(mesh.nCy/2) + indy = int(old_div(mesh.nCy,2)) # Plot the model for reference # Define core mesh extent @@ -78,8 +87,8 @@ def run(loc=None, sig=None, radi=None, param=None, surveyType='dipole-dipole', u # Define some global geometry dl_len = np.sqrt( np.sum((locs[0,:] - locs[1,:])**2) ) - dl_x = ( Tx[-1][0,1] - Tx[0][0,0] ) / dl_len - dl_y = ( Tx[-1][1,1] - Tx[0][1,0] ) / dl_len + dl_x = old_div(( Tx[-1][0,1] - Tx[0][0,0] ), dl_len) + dl_y = old_div(( Tx[-1][1,1] - Tx[0][1,0] ), dl_len) #azm = np.arctan(dl_y/dl_x) #Set boundary conditions @@ -89,7 +98,7 @@ def run(loc=None, sig=None, radi=None, param=None, surveyType='dipole-dipole', u # line source for simplicity. Div = mesh.faceDiv Grad = mesh.cellGrad - Msig = Utils.sdiag(1./(mesh.aveF2CC.T*(1./model))) + Msig = Utils.sdiag(old_div(1.,(mesh.aveF2CC.T*(old_div(1.,model))))) A = Div*Msig*Grad @@ -100,7 +109,7 @@ def run(loc=None, sig=None, radi=None, param=None, surveyType='dipole-dipole', u # We will solve the system iteratively, so a pre-conditioner is helpful # This is simply a Jacobi preconditioner (inverse of the main diagonal) dA = A.diagonal() - P = sp.spdiags(1/dA,0,A.shape[0],A.shape[0]) + P = sp.spdiags(old_div(1,dA),0,A.shape[0],A.shape[0]) # Now we can solve the system for all the transmitters # We want to store the data @@ -124,10 +133,10 @@ def run(loc=None, sig=None, radi=None, param=None, surveyType='dipole-dipole', u tx = np.squeeze(Tx[ii][:,0:1]) tinf = tx + np.array([dl_x,dl_y,0])*dl_len*2 inds = Utils.closestPoints(mesh, np.c_[tx,tinf].T) - RHS = mesh.getInterpolationMat(np.asarray(Tx[ii]).T, 'CC').T*( [-1] / mesh.vol[inds] ) + RHS = mesh.getInterpolationMat(np.asarray(Tx[ii]).T, 'CC').T*( old_div([-1], mesh.vol[inds]) ) else: inds = Utils.closestPoints(mesh, np.asarray(Tx[ii]).T ) - RHS = mesh.getInterpolationMat(np.asarray(Tx[ii]).T, 'CC').T*( [-1,1] / mesh.vol[inds] ) + RHS = mesh.getInterpolationMat(np.asarray(Tx[ii]).T, 'CC').T*( old_div([-1,1], mesh.vol[inds]) ) # Iterative Solve Ainvb = sp.linalg.bicgstab(P*A,P*RHS, tol=1e-5) @@ -143,10 +152,10 @@ def run(loc=None, sig=None, radi=None, param=None, surveyType='dipole-dipole', u dtemp = (P1*phi - P2*phi)*np.pi data.append( dtemp ) - print '\rTransmitter {0} of {1} -> Time:{2} sec'.format(ii,len(Tx),time.time()- start_time), + print('\rTransmitter {0} of {1} -> Time:{2} sec'.format(ii,len(Tx),time.time()- start_time), end=' ') - print 'Transmitter {0} of {1}'.format(ii,len(Tx)) - print 'Forward completed' + print('Transmitter {0} of {1}'.format(ii,len(Tx))) + print('Forward completed') # Let's just convert the 3D format into 2D (distance along line) and plot survey2D = DC.convertObs_DC3D_to_2D(survey, np.ones(survey.nSrc) , 'Xloc') diff --git a/SimPEG/Examples/EM_FDEM_1D_Inversion.py b/SimPEG/Examples/EM_FDEM_1D_Inversion.py index 4275903d..ece518d0 100644 --- a/SimPEG/Examples/EM_FDEM_1D_Inversion.py +++ b/SimPEG/Examples/EM_FDEM_1D_Inversion.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() from SimPEG import * import SimPEG.EM as EM from SimPEG.EM import mu_0 @@ -56,7 +62,7 @@ def run(plotIt=True): try: from pymatsolver import MumpsSolver prb.Solver = MumpsSolver - except ImportError, e: + except ImportError as e: prb.Solver = SolverLU prb.pair(survey) diff --git a/SimPEG/Examples/EM_FDEM_Analytic_MagDipoleWholespace.py b/SimPEG/Examples/EM_FDEM_Analytic_MagDipoleWholespace.py index 15ff9f62..ac17d177 100644 --- a/SimPEG/Examples/EM_FDEM_Analytic_MagDipoleWholespace.py +++ b/SimPEG/Examples/EM_FDEM_Analytic_MagDipoleWholespace.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() from SimPEG import * import SimPEG.EM as EM diff --git a/SimPEG/Examples/EM_Schenkel_Morrison_Casing.py b/SimPEG/Examples/EM_Schenkel_Morrison_Casing.py index 3e0b308c..50ada57c 100644 --- a/SimPEG/Examples/EM_Schenkel_Morrison_Casing.py +++ b/SimPEG/Examples/EM_Schenkel_Morrison_Casing.py @@ -1,3 +1,11 @@ +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 builtins import range +from past.utils import old_div from SimPEG import * from SimPEG.EM import FDEM, Analytics, mu_0 import time @@ -67,8 +75,8 @@ def run(plotIt=True): casing_l = 300 # length of the casing casing_r = 0.1 - casing_a = casing_r - casing_t/2. # inner radius - casing_b = casing_r + casing_t/2. # outer radius + casing_a = casing_r - old_div(casing_t,2.) # inner radius + casing_b = casing_r + old_div(casing_t,2.) # outer radius casing_z = np.r_[-casing_l,0.] @@ -78,25 +86,25 @@ def run(plotIt=True): src_loc = np.r_[0.,0.,dsz] inf_loc = np.r_[0.,0.,1e4] - print 'Skin Depth: ', [(500./np.sqrt(sigmaback*_)) for _ in freqs] + print('Skin Depth: ', [(old_div(500.,np.sqrt(sigmaback*_))) for _ in freqs]) # ------------------ MESH ------------------ # fine cells near well bore csx1, csx2 = 2e-3, 60. pfx1, pfx2 = 1.3, 1.3 - ncx1 = np.ceil(casing_b/csx1+2) + ncx1 = np.ceil(old_div(casing_b,csx1)+2) # pad nicely to second cell size - npadx1 = np.floor(np.log(csx2/csx1) / np.log(pfx1)) + npadx1 = np.floor(old_div(np.log(old_div(csx2,csx1)), np.log(pfx1))) hx1a,hx1b = Utils.meshTensor([(csx1,ncx1)]),Utils.meshTensor([(csx1,npadx1,pfx1)]) dx1 = sum(hx1a)+sum(hx1b) - dx1 = np.floor(dx1/csx2) - hx1b *= (dx1*csx2 - sum(hx1a))/sum(hx1b) + dx1 = np.floor(old_div(dx1,csx2)) + hx1b *= old_div((dx1*csx2 - sum(hx1a)),sum(hx1b)) # second chunk of mesh dx2 = 300. # uniform mesh out to here - ncx2 = np.ceil((dx2 - dx1)/csx2) + ncx2 = np.ceil(old_div((dx2 - dx1),csx2)) npadx2 = 45 hx2a, hx2b = Utils.meshTensor([(csx2,ncx2)]), Utils.meshTensor([(csx2,npadx2,pfx2)]) hx = np.hstack([hx1a,hx1b,hx2a,hx2b]) @@ -104,14 +112,14 @@ def run(plotIt=True): # z-direction csz = 0.05 nza = 10 - ncz, npadzu, npadzd = np.int(np.ceil(np.diff(casing_z)[0]/csz))+10, 68, 68 # cell size, number of core cells, number of padding cells in the x- direction + ncz, npadzu, npadzd = np.int(np.ceil(old_div(np.diff(casing_z)[0],csz)))+10, 68, 68 # cell size, number of core cells, number of padding cells in the x- direction hz = Utils.meshTensor([(csz,npadzd,-1.3), (csz,ncz), (csz,npadzu,1.3)]) # vector of cell widths in the z-direction # Mesh mesh = Mesh.CylMesh([hx,1.,hz], [0.,0.,-np.sum(hz[:npadzu+ncz-nza])]) - print 'Mesh Extent xmax: %f,: zmin: %f, zmax: %f'%(mesh.vectorCCx.max(), mesh.vectorCCz.min(), mesh.vectorCCz.max()) - print 'Number of cells', mesh.nC + print('Mesh Extent xmax: %f,: zmin: %f, zmax: %f'%(mesh.vectorCCx.max(), mesh.vectorCCz.min(), mesh.vectorCCz.max())) + print('Number of cells', mesh.nC) if plotIt is True: fig, ax = plt.subplots(1, 1, figsize=(6, 4)) @@ -182,7 +190,7 @@ def run(plotIt=True): # assemble the source sg = np.hstack([sg_x,sg_y,sg_z]) - sg_p = [FDEM.Src.RawVec_e([],_,sg/mesh.area) for _ in freqs] + sg_p = [FDEM.Src.RawVec_e([],_,old_div(sg,mesh.area)) for _ in freqs] # downhole source dg_x = np.zeros(mesh.vnF[0],dtype=complex) @@ -191,7 +199,7 @@ def run(plotIt=True): # vertically directed wire dgv_indx = (mesh.gridFz[:,0] < csx1) # go through the center of the well - dgv_indz = (mesh.gridFz[:,2] <= +csz*nza) & (mesh.gridFz[:,2] > dsz + csz/2.) + dgv_indz = (mesh.gridFz[:,2] <= +csz*nza) & (mesh.gridFz[:,2] > dsz + old_div(csz,2.)) dgv_ind = dgv_indx & dgv_indz dg_z[dgv_ind] = -1. @@ -213,7 +221,7 @@ def run(plotIt=True): # assemble the source dg = np.hstack([dg_x,dg_y,dg_z]) - dg_p = [FDEM.Src.RawVec_e([],_,dg/mesh.area) for _ in freqs] + dg_p = [FDEM.Src.RawVec_e([],_,old_div(dg,mesh.area)) for _ in freqs] # ------------ Problem and Survey --------------- survey = FDEM.Survey(sg_p + dg_p) @@ -224,7 +232,7 @@ def run(plotIt=True): # ------------- Solve --------------------------- t0 = time.time() fieldsCasing = problem.fields(sigCasing) - print 'Time to solve 2 sources', time.time() - t0 + print('Time to solve 2 sources', time.time() - t0) # Plot current @@ -251,9 +259,9 @@ def run(plotIt=True): in1_in = in1[np.r_[inds]] z_in = mesh.gridFz[inds_fz,2] - in0_in = in0_in.reshape([in0_in.shape[0]/3,3]) - in1_in = in1_in.reshape([in1_in.shape[0]/3,3]) - z_in = z_in.reshape([z_in.shape[0]/3,3]) + in0_in = in0_in.reshape([old_div(in0_in.shape[0],3),3]) + in1_in = in1_in.reshape([old_div(in1_in.shape[0],3),3]) + z_in = z_in.reshape([old_div(z_in.shape[0],3),3]) I0 = in0_in.sum(1).real I1 = in1_in.sum(1).real diff --git a/SimPEG/Examples/EM_TDEM_1D_Inversion.py b/SimPEG/Examples/EM_TDEM_1D_Inversion.py index 629811ca..b5dc0de3 100644 --- a/SimPEG/Examples/EM_TDEM_1D_Inversion.py +++ b/SimPEG/Examples/EM_TDEM_1D_Inversion.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() from SimPEG import * import SimPEG.EM as EM from SimPEG.EM import mu_0 diff --git a/SimPEG/Examples/FLOW_Richards_1D_Celia1990.py b/SimPEG/Examples/FLOW_Richards_1D_Celia1990.py index 4c90ea7b..5a87da8f 100644 --- a/SimPEG/Examples/FLOW_Richards_1D_Celia1990.py +++ b/SimPEG/Examples/FLOW_Richards_1D_Celia1990.py @@ -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 from SimPEG import * from SimPEG.FLOW import Richards @@ -46,7 +53,7 @@ def run(plotIt=True): def getFields(timeStep,method): - timeSteps = np.ones(360/timeStep)*timeStep + timeSteps = np.ones(old_div(360,timeStep))*timeStep prob = Richards.RichardsProblem(M, mapping=E, timeSteps=timeSteps, boundaryConditions=bc, initialConditions=h, doNewton=False, method=method) diff --git a/SimPEG/Examples/Inversion_IRLS.py b/SimPEG/Examples/Inversion_IRLS.py index 0a0757cf..5d796423 100644 --- a/SimPEG/Examples/Inversion_IRLS.py +++ b/SimPEG/Examples/Inversion_IRLS.py @@ -1,3 +1,12 @@ +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 builtins import str +from builtins import range +from past.utils import old_div from SimPEG import * @@ -47,10 +56,10 @@ def run(N=100, plotIt=True): # Distance weighting wr = np.sum(prob.G**2.,axis=0)**0.5 - wr = ( wr/np.max(wr) ) + wr = ( old_div(wr,np.max(wr)) ) dmis = DataMisfit.l2_DataMisfit(survey) - dmis.Wd = 1./wd + dmis.Wd = old_div(1.,wd) betaest = Directives.BetaEstimate_ByEig() @@ -75,7 +84,7 @@ def run(N=100, plotIt=True): # Run inversion mrec = inv.run(m0) - print "Final misfit:" + str(invProb.dmisfit.eval(mrec)) + print("Final misfit:" + str(invProb.dmisfit.eval(mrec))) if plotIt: diff --git a/SimPEG/Examples/Inversion_Linear.py b/SimPEG/Examples/Inversion_Linear.py index 47d49c7f..fe2a3a00 100644 --- a/SimPEG/Examples/Inversion_Linear.py +++ b/SimPEG/Examples/Inversion_Linear.py @@ -1,3 +1,10 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import range from SimPEG import * diff --git a/SimPEG/Examples/MT_1D_ForwardAndInversion.py b/SimPEG/Examples/MT_1D_ForwardAndInversion.py index 446613e5..e6430589 100644 --- a/SimPEG/Examples/MT_1D_ForwardAndInversion.py +++ b/SimPEG/Examples/MT_1D_ForwardAndInversion.py @@ -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 SimPEG as simpeg import numpy as np import SimPEG.MT as MT @@ -84,7 +91,7 @@ def run(plotIt=True): std = 0.05 # 5% std survey.std = np.abs(survey.dobs*std) # Assign the data weight - Wd = 1./survey.std + Wd = old_div(1.,survey.std) ## Setup the inversion proceedure # Define a counter diff --git a/SimPEG/Examples/MT_3D_Foward.py b/SimPEG/Examples/MT_3D_Foward.py index 1d0db148..0f728d70 100644 --- a/SimPEG/Examples/MT_3D_Foward.py +++ b/SimPEG/Examples/MT_3D_Foward.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() # Test script to use SimPEG.MT platform to forward model synthetic data. # Import diff --git a/SimPEG/Examples/Maps_ComboMaps.py b/SimPEG/Examples/Maps_ComboMaps.py index 3e495023..cab28fa6 100644 --- a/SimPEG/Examples/Maps_ComboMaps.py +++ b/SimPEG/Examples/Maps_ComboMaps.py @@ -1,3 +1,10 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import dict +from future import standard_library +standard_library.install_aliases() from SimPEG import Mesh, Maps, np def run(plotIt=True): diff --git a/SimPEG/Examples/Maps_Mesh2Mesh.py b/SimPEG/Examples/Maps_Mesh2Mesh.py index 254dc036..9152c1af 100644 --- a/SimPEG/Examples/Maps_Mesh2Mesh.py +++ b/SimPEG/Examples/Maps_Mesh2Mesh.py @@ -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 from SimPEG import Mesh, Maps, Utils def run(plotIt=True): @@ -12,7 +19,7 @@ def run(plotIt=True): M = Mesh.TensorMesh([100,100]) h1 = Utils.meshTensor([(6,7,-1.5),(6,10),(6,7,1.5)]) - h1 = h1/h1.sum() + h1 = old_div(h1,h1.sum()) M2 = Mesh.TensorMesh([h1,h1]) V = Utils.ModelBuilder.randomModel(M.vnC, seed=79, its=50) v = Utils.mkvc(V) diff --git a/SimPEG/Examples/Mesh_Basic_ForwardDC.py b/SimPEG/Examples/Mesh_Basic_ForwardDC.py index bd4ea18a..993d26ea 100644 --- a/SimPEG/Examples/Mesh_Basic_ForwardDC.py +++ b/SimPEG/Examples/Mesh_Basic_ForwardDC.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() from SimPEG import Mesh, Utils, np, SolverLU def run(plotIt=True): diff --git a/SimPEG/Examples/Mesh_Basic_PlotImage.py b/SimPEG/Examples/Mesh_Basic_PlotImage.py index 3154f281..8943f955 100644 --- a/SimPEG/Examples/Mesh_Basic_PlotImage.py +++ b/SimPEG/Examples/Mesh_Basic_PlotImage.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() from SimPEG import * def run(plotIt=True): diff --git a/SimPEG/Examples/Mesh_Basic_Types.py b/SimPEG/Examples/Mesh_Basic_Types.py index 430fe698..71f10af2 100644 --- a/SimPEG/Examples/Mesh_Basic_Types.py +++ b/SimPEG/Examples/Mesh_Basic_Types.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() from SimPEG import * def run(plotIt=True): diff --git a/SimPEG/Examples/Mesh_Operators_CahnHilliard.py b/SimPEG/Examples/Mesh_Operators_CahnHilliard.py index 8e42e617..b6d7572e 100644 --- a/SimPEG/Examples/Mesh_Operators_CahnHilliard.py +++ b/SimPEG/Examples/Mesh_Operators_CahnHilliard.py @@ -1,3 +1,11 @@ +from __future__ import print_function +from __future__ import unicode_literals +from __future__ import division +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import zip from SimPEG import * def run(plotIt=True, n=60): @@ -87,7 +95,7 @@ def run(plotIt=True, n=60): if elapsed > capture[jj]: PHIS += [(elapsed, phi.copy())] jj += 1 - if ii % 10 == 0: print ii, elapsed + if ii % 10 == 0: print(ii, elapsed) ii += 1 if plotIt: diff --git a/SimPEG/Examples/Mesh_QuadTree_Creation.py b/SimPEG/Examples/Mesh_QuadTree_Creation.py index ede69a63..a1ca846c 100644 --- a/SimPEG/Examples/Mesh_QuadTree_Creation.py +++ b/SimPEG/Examples/Mesh_QuadTree_Creation.py @@ -1,3 +1,10 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import range from SimPEG import * def run(plotIt=True): diff --git a/SimPEG/Examples/Mesh_QuadTree_FaceDiv.py b/SimPEG/Examples/Mesh_QuadTree_FaceDiv.py index 5bd67929..2958a0a4 100644 --- a/SimPEG/Examples/Mesh_QuadTree_FaceDiv.py +++ b/SimPEG/Examples/Mesh_QuadTree_FaceDiv.py @@ -1,3 +1,11 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import zip +from builtins import range from SimPEG import * def run(plotIt=True, n=60): @@ -28,15 +36,15 @@ def run(plotIt=True, n=60): axes[0].set_xlim([-1,17]) axes[0].set_ylim([-1,17]) - for ii, loc in zip(range(M.nC),M.gridCC): + for ii, loc in zip(list(range(M.nC)),M.gridCC): axes[0].text(loc[0]+0.2,loc[1],'%d'%ii, color='r') axes[0].plot(M.gridFx[:,0],M.gridFx[:,1], 'g>') - for ii, loc in zip(range(M.nFx),M.gridFx): + for ii, loc in zip(list(range(M.nFx)),M.gridFx): axes[0].text(loc[0]+0.2,loc[1],'%d'%ii, color='g') axes[0].plot(M.gridFy[:,0],M.gridFy[:,1], 'm^') - for ii, loc in zip(range(M.nFy),M.gridFy): + for ii, loc in zip(list(range(M.nFy)),M.gridFy): axes[0].text(loc[0]+0.2,loc[1]+0.2,'%d'%(ii+M.nFx), color='m') axes[1].spy(M.faceDiv) diff --git a/SimPEG/Examples/Mesh_QuadTree_HangingNodes.py b/SimPEG/Examples/Mesh_QuadTree_HangingNodes.py index 11726995..bcd89153 100644 --- a/SimPEG/Examples/Mesh_QuadTree_HangingNodes.py +++ b/SimPEG/Examples/Mesh_QuadTree_HangingNodes.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() from SimPEG import * def run(plotIt=True): diff --git a/SimPEG/Examples/Mesh_Tensor_Creation.py b/SimPEG/Examples/Mesh_Tensor_Creation.py index 31ad3d69..3007a5a1 100644 --- a/SimPEG/Examples/Mesh_Tensor_Creation.py +++ b/SimPEG/Examples/Mesh_Tensor_Creation.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() from SimPEG import * def run(plotIt=True): diff --git a/SimPEG/Examples/Utils_surface2ind_topo.py b/SimPEG/Examples/Utils_surface2ind_topo.py index 07e3e4aa..35f4a5b1 100644 --- a/SimPEG/Examples/Utils_surface2ind_topo.py +++ b/SimPEG/Examples/Utils_surface2ind_topo.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() from SimPEG import * from SimPEG.Utils import surface2ind_topo diff --git a/SimPEG/Examples/__init__.py b/SimPEG/Examples/__init__.py index 3c9cbca9..56319388 100644 --- a/SimPEG/Examples/__init__.py +++ b/SimPEG/Examples/__init__.py @@ -1,28 +1,35 @@ +from __future__ import print_function +from __future__ import absolute_import +from __future__ import unicode_literals +from __future__ import division +from builtins import open +from future import standard_library +standard_library.install_aliases() # Run this file to add imports. ##### AUTOIMPORTS ##### -import DC_Analytic_Dipole -import DC_Forward_PseudoSection -import EM_FDEM_1D_Inversion -import EM_FDEM_Analytic_MagDipoleWholespace -import EM_Schenkel_Morrison_Casing -import EM_TDEM_1D_Inversion -import FLOW_Richards_1D_Celia1990 -import Inversion_IRLS -import Inversion_Linear -import Maps_ComboMaps -import Maps_Mesh2Mesh -import Mesh_Basic_ForwardDC -import Mesh_Basic_PlotImage -import Mesh_Basic_Types -import Mesh_Operators_CahnHilliard -import Mesh_QuadTree_Creation -import Mesh_QuadTree_FaceDiv -import Mesh_QuadTree_HangingNodes -import Mesh_Tensor_Creation -import MT_1D_ForwardAndInversion -import MT_3D_Foward -import Utils_surface2ind_topo +from . import DC_Analytic_Dipole +from . import DC_Forward_PseudoSection +from . import EM_FDEM_1D_Inversion +from . import EM_FDEM_Analytic_MagDipoleWholespace +from . import EM_Schenkel_Morrison_Casing +from . import EM_TDEM_1D_Inversion +from . import FLOW_Richards_1D_Celia1990 +from . import Inversion_IRLS +from . import Inversion_Linear +from . import Maps_ComboMaps +from . import Maps_Mesh2Mesh +from . import Mesh_Basic_ForwardDC +from . import Mesh_Basic_PlotImage +from . import Mesh_Basic_Types +from . import Mesh_Operators_CahnHilliard +from . import Mesh_QuadTree_Creation +from . import Mesh_QuadTree_FaceDiv +from . import Mesh_QuadTree_HangingNodes +from . import Mesh_Tensor_Creation +from . import MT_1D_ForwardAndInversion +from . import MT_3D_Foward +from . import Utils_surface2ind_topo __examples__ = ["DC_Analytic_Dipole", "DC_Forward_PseudoSection", "EM_FDEM_1D_Inversion", "EM_FDEM_Analytic_MagDipoleWholespace", "EM_Schenkel_Morrison_Casing", "EM_TDEM_1D_Inversion", "FLOW_Richards_1D_Celia1990", "Inversion_IRLS", "Inversion_Linear", "Maps_ComboMaps", "Maps_Mesh2Mesh", "Mesh_Basic_ForwardDC", "Mesh_Basic_PlotImage", "Mesh_Basic_Types", "Mesh_Operators_CahnHilliard", "Mesh_QuadTree_Creation", "Mesh_QuadTree_FaceDiv", "Mesh_QuadTree_HangingNodes", "Mesh_Tensor_Creation", "MT_1D_ForwardAndInversion", "MT_3D_Foward", "Utils_surface2ind_topo"] @@ -104,7 +111,7 @@ if __name__ == '__main__': rst = os.path.sep.join((filePath.split(os.path.sep)[:-3] + ['docs', 'content', 'examples', name + '.rst'])) - print 'Creating: %s.rst'%name + print('Creating: %s.rst'%name) f = open(rst, 'w') f.write(out) f.close() diff --git a/SimPEG/FLOW/Richards/Empirical.py b/SimPEG/FLOW/Richards/Empirical.py index c6624e94..79e15fef 100644 --- a/SimPEG/FLOW/Richards/Empirical.py +++ b/SimPEG/FLOW/Richards/Empirical.py @@ -1,14 +1,21 @@ +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 +from builtins import object from SimPEG import Mesh, Maps, Utils, np +from future.utils import with_metaclass -class NonLinearMap(object): +class NonLinearMap(with_metaclass(Utils.SimPEGMetaClass, object)): """ SimPEG NonLinearMap """ - __metaclass__ = Utils.SimPEGMetaClass - counter = None #: A SimPEG.Utils.Counter object mesh = None #: A SimPEG Mesh @@ -186,8 +193,8 @@ class _haverkamp_theta(NonLinearMap): def transformDerivU(self, u, m): self.setModel(m) - g = (self.alpha*((self.theta_s - self.theta_r)/ - (self.alpha + abs(u)**self.beta)**2) + g = (self.alpha*(old_div((self.theta_s - self.theta_r), + (self.alpha + abs(u)**self.beta)**2)) *(-self.beta*abs(u)**(self.beta-1)*np.sign(u))) g[u >= 0] = 0 g = Utils.sdiag(g) @@ -230,7 +237,7 @@ class _haverkamp_k(NonLinearMap): def transformDerivU(self, u, m): self.setModel(m) - g = -(np.exp(self.Ks)*self.A*self.gamma*abs(u)**(self.gamma-1)*np.sign(u))/((self.A+abs(u)**self.gamma)**2) + g = old_div(-(np.exp(self.Ks)*self.A*self.gamma*abs(u)**(self.gamma-1)*np.sign(u)),((self.A+abs(u)**self.gamma)**2)) g[u >= 0] = 0 g = Utils.sdiag(g) return g @@ -272,9 +279,9 @@ class _vangenuchten_theta(NonLinearMap): def transform(self, u, m): self.setModel(m) - m = 1 - 1.0/self.n - f = (( self.theta_s - self.theta_r )/ - ((1+abs(self.alpha*u)**self.n)**m) + self.theta_r) + m = 1 - old_div(1.0,self.n) + f = (old_div(( self.theta_s - self.theta_r ), + ((1+abs(self.alpha*u)**self.n)**m)) + self.theta_r) if Utils.isScalar(self.theta_s): f[u >= 0] = self.theta_s else: @@ -286,7 +293,7 @@ class _vangenuchten_theta(NonLinearMap): self.setModel(m) def transformDerivU(self, u, m): - g = -self.alpha*self.n*abs(self.alpha*u)**(self.n - 1)*np.sign(self.alpha*u)*(1./self.n - 1)*(self.theta_r - self.theta_s)*(abs(self.alpha*u)**self.n + 1)**(1./self.n - 2) + g = -self.alpha*self.n*abs(self.alpha*u)**(self.n - 1)*np.sign(self.alpha*u)*(old_div(1.,self.n) - 1)*(self.theta_r - self.theta_s)*(abs(self.alpha*u)**self.n + 1)**(old_div(1.,self.n) - 2) g[u >= 0] = 0 g = Utils.sdiag(g) return g @@ -315,10 +322,10 @@ class _vangenuchten_k(NonLinearMap): I = self.I n = self.n Ks = self.Ks - m = 1.0 - 1.0/n + m = 1.0 - old_div(1.0,n) - theta_e = 1.0/((1.0+abs(alpha*u)**n)**m) - f = np.exp(Ks)*theta_e**I* ( ( 1.0 - ( 1.0 - theta_e**(1.0/m) )**m )**2 ) + theta_e = old_div(1.0,((1.0+abs(alpha*u)**n)**m)) + f = np.exp(Ks)*theta_e**I* ( ( 1.0 - ( 1.0 - theta_e**(old_div(1.0,m)) )**m )**2 ) if Utils.isScalar(self.Ks): f[u >= 0] = np.exp(self.Ks) else: @@ -341,9 +348,9 @@ class _vangenuchten_k(NonLinearMap): I = self.I n = self.n Ks = self.Ks - m = 1.0 - 1.0/n + m = 1.0 - old_div(1.0,n) - g = I*alpha*n*np.exp(Ks)*abs(alpha*u)**(n - 1.0)*np.sign(alpha*u)*(1.0/n - 1.0)*((abs(alpha*u)**n + 1)**(1.0/n - 1))**(I - 1)*((1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1 - 1.0/n) - 1)**2*(abs(alpha*u)**n + 1)**(1.0/n - 2) - (2*alpha*n*np.exp(Ks)*abs(alpha*u)**(n - 1)*np.sign(alpha*u)*(1.0/n - 1)*((abs(alpha*u)**n + 1)**(1.0/n - 1))**I*((1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1 - 1.0/n) - 1)*(abs(alpha*u)**n + 1)**(1.0/n - 2))/(((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1) + 1)*(1 - 1.0/((abs(alpha*u)**n + 1)**(1.0/n - 1))**(1.0/(1.0/n - 1)))**(1.0/n)) + g = I*alpha*n*np.exp(Ks)*abs(alpha*u)**(n - 1.0)*np.sign(alpha*u)*(old_div(1.0,n) - 1.0)*((abs(alpha*u)**n + 1)**(old_div(1.0,n) - 1))**(I - 1)*((1 - old_div(1.0,((abs(alpha*u)**n + 1)**(old_div(1.0,n) - 1))**(old_div(1.0,(old_div(1.0,n) - 1)))))**(1 - old_div(1.0,n)) - 1)**2*(abs(alpha*u)**n + 1)**(old_div(1.0,n) - 2) - old_div((2*alpha*n*np.exp(Ks)*abs(alpha*u)**(n - 1)*np.sign(alpha*u)*(old_div(1.0,n) - 1)*((abs(alpha*u)**n + 1)**(old_div(1.0,n) - 1))**I*((1 - old_div(1.0,((abs(alpha*u)**n + 1)**(old_div(1.0,n) - 1))**(old_div(1.0,(old_div(1.0,n) - 1)))))**(1 - old_div(1.0,n)) - 1)*(abs(alpha*u)**n + 1)**(old_div(1.0,n) - 2)),(((abs(alpha*u)**n + 1)**(old_div(1.0,n) - 1))**(old_div(1.0,(old_div(1.0,n) - 1)) + 1)*(1 - old_div(1.0,((abs(alpha*u)**n + 1)**(old_div(1.0,n) - 1))**(old_div(1.0,(old_div(1.0,n) - 1)))))**(old_div(1.0,n)))) g[u >= 0] = 0 g = Utils.sdiag(g) return g diff --git a/SimPEG/FLOW/Richards/RichardsProblem.py b/SimPEG/FLOW/Richards/RichardsProblem.py index 2346f4da..310846dc 100644 --- a/SimPEG/FLOW/Richards/RichardsProblem.py +++ b/SimPEG/FLOW/Richards/RichardsProblem.py @@ -1,5 +1,13 @@ +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 from SimPEG import * -from Empirical import RichardsMap +from .Empirical import RichardsMap import time @@ -61,7 +69,7 @@ class RichardsSurvey(Survey.BaseSurvey): @Utils.requires('prob') def eval(self, U, m): - Ds = range(len(self.rxList)) + Ds = list(range(len(self.rxList))) for ii, rx in enumerate(self.rxList): Ds[ii] = rx.eval(U, m, self.prob.mapping, @@ -73,7 +81,7 @@ class RichardsSurvey(Survey.BaseSurvey): @Utils.requires('prob') def evalDeriv(self, U, m): """The Derivative with respect to the fields.""" - Ds = range(len(self.rxList)) + Ds = list(range(len(self.rxList))) for ii, rx in enumerate(self.rxList): Ds[ii] = rx.evalDeriv(U, m, self.prob.mapping, @@ -135,12 +143,12 @@ class RichardsProblem(Problem.BaseTimeProblem): @Utils.timeIt def fields(self, m): tic = time.time() - u = range(self.nT+1) + u = list(range(self.nT+1)) u[0] = self.initialConditions for ii, dt in enumerate(self.timeSteps): bc = self.getBoundaryConditions(ii, u[ii]) u[ii+1] = self.rootFinder.root(lambda hn1m, return_g=True: self.getResidual(m, u[ii], hn1m, dt, bc, return_g=return_g), u[ii]) - if self.debug: print "Solving Fields (%4d/%d - %3.1f%% Done) %d Iterations, %4.2f seconds"%(ii+1, self.nT, 100.0*(ii+1)/self.nT, self.rootFinder.iter, time.time() - tic) + if self.debug: print("Solving Fields (%4d/%d - %3.1f%% Done) %d Iterations, %4.2f seconds"%(ii+1, self.nT, 100.0*(ii+1)/self.nT, self.rootFinder.iter, time.time() - tic)) return u @Utils.timeIt @@ -168,7 +176,7 @@ class RichardsProblem(Problem.BaseTimeProblem): # DIV*diag(GRAD*hn1+BC*bc)*(AV*(1.0/K))^-1 DdiagGh1 = DIV*Utils.sdiag(GRAD*hn1+BC*bc) - diagAVk2_AVdiagK2 = Utils.sdiag((AV*(1./K1))**(-2)) * AV*Utils.sdiag(K1**(-2)) + diagAVk2_AVdiagK2 = Utils.sdiag((AV*(old_div(1.,K1)))**(-2)) * AV*Utils.sdiag(K1**(-2)) # The matrix that we are computing has the form: # @@ -180,12 +188,12 @@ class RichardsProblem(Problem.BaseTimeProblem): # | Asub Adiag | | hn | | bn | # - - - - - - - Asub = (-1.0/dt)*dT + Asub = (old_div(-1.0,dt))*dT Adiag = ( - (1.0/dt)*dT1 + (old_div(1.0,dt))*dT1 -DdiagGh1*diagAVk2_AVdiagK2*dK1 - -DIV*Utils.sdiag(1./(AV*(1./K1)))*GRAD + -DIV*Utils.sdiag(old_div(1.,(AV*(old_div(1.,K1)))))*GRAD -Dz*diagAVk2_AVdiagK2*dK1 ) @@ -215,17 +223,17 @@ class RichardsProblem(Problem.BaseTimeProblem): K = self.mapping.k(h, m) dK = self.mapping.kDerivU(h, m) - aveK = 1./(AV*(1./K)) + aveK = old_div(1.,(AV*(old_div(1.,K)))) RHS = DIV*Utils.sdiag(aveK)*(GRAD*h+BC*bc) + Dz*aveK if self.method == 'mixed': - r = (T-Tn)/dt - RHS + r = old_div((T-Tn),dt) - RHS elif self.method == 'head': r = dT*(h - hn)/dt - RHS if not return_g: return r - J = dT/dt - DIV*Utils.sdiag(aveK)*GRAD + J = old_div(dT,dt) - DIV*Utils.sdiag(aveK)*GRAD if self.doNewton: DDharmAve = Utils.sdiag(aveK**2)*AV*Utils.sdiag(K**(-2)) * dK J = J - DIV*Utils.sdiag(GRAD*h + BC*bc)*DDharmAve - Dz*DDharmAve @@ -238,7 +246,7 @@ class RichardsProblem(Problem.BaseTimeProblem): f = self.fields(m) nn = len(f)-1 - Asubs, Adiags, Bs = range(nn), range(nn), range(nn) + Asubs, Adiags, Bs = list(range(nn)), list(range(nn)), list(range(nn)) for ii in range(nn): dt = self.timeSteps[ii] bc = self.getBoundaryConditions(ii, f[ii]) @@ -263,7 +271,7 @@ class RichardsProblem(Problem.BaseTimeProblem): if f is None: f = self.fields(m) - JvC = range(len(f)-1) # Cell to hold each row of the long vector. + JvC = list(range(len(f)-1)) # Cell to hold each row of the long vector. # This is done via forward substitution. bc = self.getBoundaryConditions(0, f[0]) @@ -295,7 +303,7 @@ class RichardsProblem(Problem.BaseTimeProblem): bc = self.getBoundaryConditions(ii-1, f[ii-1]) Asub, Adiag, B = self.diagsJacobian(m, f[ii-1], f[ii], self.timeSteps[ii-1], bc) #select the correct part of v - vpart = range((ii)*Adiag.shape[0], (ii+1)*Adiag.shape[0]) + vpart = list(range((ii)*Adiag.shape[0], (ii+1)*Adiag.shape[0])) AdiaginvT = self.Solver(Adiag.T, **self.solverOpts) JTvC = AdiaginvT * (PTv[vpart] - minus) minus = Asub.T*JTvC # this is now the super diagonal. diff --git a/SimPEG/FLOW/Richards/__init__.py b/SimPEG/FLOW/Richards/__init__.py index 6e25d292..7b5fb2d0 100644 --- a/SimPEG/FLOW/Richards/__init__.py +++ b/SimPEG/FLOW/Richards/__init__.py @@ -1,2 +1,8 @@ -import Empirical -from RichardsProblem 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 . import Empirical +from .RichardsProblem import * diff --git a/SimPEG/FLOW/__init__.py b/SimPEG/FLOW/__init__.py index 622d2f2f..c656c2c7 100644 --- a/SimPEG/FLOW/__init__.py +++ b/SimPEG/FLOW/__init__.py @@ -1 +1,7 @@ -import Richards +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 . import Richards diff --git a/SimPEG/Fields.py b/SimPEG/Fields.py index 9baa32f8..6bdf29a8 100644 --- a/SimPEG/Fields.py +++ b/SimPEG/Fields.py @@ -1,4 +1,13 @@ -import Utils, numpy as np, scipy.sparse as sp +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 builtins import range +from builtins import object +from . import Utils +import numpy as np, scipy.sparse as sp class Fields(object): """Fancy Field Storage @@ -244,7 +253,7 @@ class TimeFields(Fields): out = func(pointerFields, srcII, timeII) else: #loop over the time steps nT = pointerShape[2] - out = range(nT) + out = list(range(nT)) for i, TIND_i in enumerate(timeII): fieldI = pointerFields[:,:,i] if fieldI.shape[0] == fieldI.size: diff --git a/SimPEG/InvProblem.py b/SimPEG/InvProblem.py index fd6c48c3..0e90e5c5 100644 --- a/SimPEG/InvProblem.py +++ b/SimPEG/InvProblem.py @@ -1,14 +1,21 @@ -import Utils, Survey, Problem, numpy as np, scipy.sparse as sp, gc -from Utils.SolverUtils import * -import DataMisfit -import Regularization +from __future__ import print_function +from __future__ import absolute_import +from __future__ import unicode_literals +from __future__ import division +from future import standard_library +standard_library.install_aliases() +from builtins import object +from . import Utils, Survey, Problem +import numpy as np, scipy.sparse as sp, gc +from .Utils.SolverUtils import * +from . import DataMisfit +from . import Regularization +from future.utils import with_metaclass -class BaseInvProblem(object): +class BaseInvProblem(with_metaclass(Utils.SimPEGMetaClass, object)): """BaseInvProblem(dmisfit, reg, opt)""" - __metaclass__ = Utils.SimPEGMetaClass - beta = 1.0 #: Trade-off parameter debug = False #: Print debugging information @@ -54,10 +61,10 @@ class BaseInvProblem(object): Called when inversion is first starting. """ - if self.debug: print 'Calling InvProblem.startup' + if self.debug: print('Calling InvProblem.startup') if self.reg.mref is None: - print 'SimPEG.InvProblem will set Regularization.mref to m0.' + print('SimPEG.InvProblem will set Regularization.mref to m0.') self.reg.mref = m0 self.phi_d = np.nan @@ -65,8 +72,8 @@ class BaseInvProblem(object): self.curModel = m0 - print """SimPEG.InvProblem is setting bfgsH0 to the inverse of the eval2Deriv. - ***Done using same Solver and solverOpts as the problem***""" + print("""SimPEG.InvProblem is setting bfgsH0 to the inverse of the eval2Deriv. + ***Done using same Solver and solverOpts as the problem***""") self.opt.bfgsH0 = self.prob.Solver(self.reg.eval2Deriv(self.curModel), **self.prob.solverOpts) @property @@ -87,7 +94,7 @@ class BaseInvProblem(object): for mtest, u_ofmtest in self.warmstart: if m is mtest: f = u_ofmtest - if self.debug: print 'InvProb is Warm Starting!' + if self.debug: print('InvProb is Warm Starting!') break if f is None: diff --git a/SimPEG/Inversion.py b/SimPEG/Inversion.py index 3e92374f..0be2a133 100644 --- a/SimPEG/Inversion.py +++ b/SimPEG/Inversion.py @@ -1,18 +1,24 @@ +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 object import SimPEG from SimPEG import Utils, sp, np -from Optimization import Remember, IterationPrinters, StoppingCriteria -import Directives +from .Optimization import Remember, IterationPrinters, StoppingCriteria +from . import Directives +from future.utils import with_metaclass -class BaseInversion(object): +class BaseInversion(with_metaclass(Utils.SimPEGMetaClass, object)): """ Inversion Class. """ - __metaclass__ = Utils.SimPEGMetaClass - name = 'BaseInversion' debug = False #: Print debugging information diff --git a/SimPEG/MT/BaseMT.py b/SimPEG/MT/BaseMT.py index 579f590f..02fd062a 100644 --- a/SimPEG/MT/BaseMT.py +++ b/SimPEG/MT/BaseMT.py @@ -1,7 +1,13 @@ +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 SimPEG import SolverLU as SimpegSolver, PropMaps, Utils, mkvc, sp, np from SimPEG.EM.FDEM.ProblemFDEM import BaseFDEMProblem -from SurveyMT import Survey, Data -from FieldsMT import BaseMTFields +from .SurveyMT import Survey, Data +from .FieldsMT import BaseMTFields class BaseMTProblem(BaseFDEMProblem): diff --git a/SimPEG/MT/FieldsMT.py b/SimPEG/MT/FieldsMT.py index 86ac7343..290d1770 100644 --- a/SimPEG/MT/FieldsMT.py +++ b/SimPEG/MT/FieldsMT.py @@ -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 from SimPEG import Survey, Utils, Problem, np, sp, mkvc from scipy.constants import mu_0 import sys @@ -63,7 +70,7 @@ class Fields1D_e(BaseMTFields): C = self.mesh.nodalGrad b = (C * eSolution) for i, src in enumerate(srcList): - b[:,i] *= - 1./(1j*omega(src.freq)) + b[:,i] *= old_div(- 1.,(1j*omega(src.freq))) # There is no magnetic source in the MT problem # S_m, _ = src.eval(self.survey.prob) # if S_m is not None: @@ -188,7 +195,7 @@ class Fields3D_e(BaseMTFields): # adjoint: returns a 2*nE long vector with zero's for py return np.vstack((v,np.zeros_like(v))) # Not adjoint: return only the px part of the vector - return v[:len(v)/2] + return v[:old_div(len(v),2)] def _e_pyDeriv_u(self, src, v, adjoint = False): ''' @@ -198,7 +205,7 @@ class Fields3D_e(BaseMTFields): # adjoint: returns a 2*nE long vector with zero's for px return np.vstack((np.zeros_like(v),v)) # Not adjoint: return only the px part of the vector - return v[len(v)/2::] + return v[old_div(len(v),2)::] def _e_pxDeriv_m(self, src, v, adjoint = False): # assuming primary does not depend on the model @@ -227,7 +234,7 @@ class Fields3D_e(BaseMTFields): C = self.mesh.edgeCurl b = (C * e_pxSolution) for i, src in enumerate(srcList): - b[:,i] *= - 1./(1j*omega(src.freq)) + b[:,i] *= old_div(- 1.,(1j*omega(src.freq))) # There is no magnetic source in the MT problem # S_m, _ = src.eval(self.survey.prob) # if S_m is not None: @@ -238,7 +245,7 @@ class Fields3D_e(BaseMTFields): C = self.mesh.edgeCurl b = (C * e_pySolution) for i, src in enumerate(srcList): - b[:,i] *= - 1./(1j*omega(src.freq)) + b[:,i] *= old_div(- 1.,(1j*omega(src.freq))) # There is no magnetic source in the MT problem # S_m, _ = src.eval(self.survey.prob) # if S_m is not None: diff --git a/SimPEG/MT/Problem1D/Probs.py b/SimPEG/MT/Problem1D/Probs.py index eb7aa331..11ea0d35 100644 --- a/SimPEG/MT/Problem1D/Probs.py +++ b/SimPEG/MT/Problem1D/Probs.py @@ -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 from SimPEG.EM.Utils import omega from SimPEG import mkvc from scipy.constants import mu_0 @@ -46,7 +53,7 @@ class eForm_psField(BaseMTProblem): Edge inner product matrix """ if getattr(self, '_MeMui', None) is None: - self._MeMui = self.mesh.getEdgeInnerProduct(1.0/mu_0) + self._MeMui = self.mesh.getEdgeInnerProduct(old_div(1.0,mu_0)) return self._MeMui @property @@ -142,7 +149,7 @@ class eForm_psField(BaseMTProblem): for freq in self.survey.freqs: if self.verbose: startTime = time.time() - print 'Starting work for {:.3e}'.format(freq) + print('Starting work for {:.3e}'.format(freq)) sys.stdout.flush() A = self.getA(freq) rhs = self.getRHS(freq) @@ -158,7 +165,7 @@ class eForm_psField(BaseMTProblem): # b = -( self.mesh.nodalGrad * e )/( 1j*omega(freq) ) # F[Src, 'b_1d'] = b[:,1] if self.verbose: - print 'Ran for {:f} seconds'.format(time.time()-startTime) + print('Ran for {:f} seconds'.format(time.time()-startTime)) sys.stdout.flush() return F @@ -191,7 +198,7 @@ class eForm_TotalField(BaseMTProblem): Edge inner product matrix """ if getattr(self, '_MeMui', None) is None: - self._MeMui = self.mesh.getEdgeInnerProduct(1.0/mu_0) + self._MeMui = self.mesh.getEdgeInnerProduct(old_div(1.0,mu_0)) return self._MeMui @property @@ -249,7 +256,7 @@ class eForm_TotalField(BaseMTProblem): Ed, Eu, Hd, Hu = getEHfields(self.mesh,self.curModel.sigma,freq,self.mesh.vectorNx) Etot = (Ed + Eu) sourceAmp = 1.0 - Etot = ((Etot/Etot[-1])*sourceAmp) # Scale the fields to be equal to sourceAmp at the top + Etot = ((old_div(Etot,Etot[-1]))*sourceAmp) # Scale the fields to be equal to sourceAmp at the top ## Note: The analytic solution is derived with e^iwt eBC = np.r_[Etot[0],Etot[-1]] # The right hand side @@ -274,7 +281,7 @@ class eForm_TotalField(BaseMTProblem): for freq in self.survey.freqs: if self.verbose: startTime = time.time() - print 'Starting work for {:.3e}'.format(freq) + print('Starting work for {:.3e}'.format(freq)) sys.stdout.flush() A = self.getA(freq) rhs, e_o = self.getRHS(freq) @@ -286,6 +293,6 @@ class eForm_TotalField(BaseMTProblem): # NOTE: only store e fields F[Src, 'e_1dSolution'] = e[:,0] if self.verbose: - print 'Ran for {:f} seconds'.format(time.time()-startTime) + print('Ran for {:f} seconds'.format(time.time()-startTime)) sys.stdout.flush() return F diff --git a/SimPEG/MT/Problem1D/__init__.py b/SimPEG/MT/Problem1D/__init__.py index b0a77250..17762dc8 100644 --- a/SimPEG/MT/Problem1D/__init__.py +++ b/SimPEG/MT/Problem1D/__init__.py @@ -1 +1,7 @@ -from Probs import eForm_TotalField, eForm_psField \ No newline at end of file +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 .Probs import eForm_TotalField, eForm_psField \ No newline at end of file diff --git a/SimPEG/MT/Problem2D/__init__.py b/SimPEG/MT/Problem2D/__init__.py index fc80254b..a9740d73 100644 --- a/SimPEG/MT/Problem2D/__init__.py +++ b/SimPEG/MT/Problem2D/__init__.py @@ -1 +1,7 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() pass \ No newline at end of file diff --git a/SimPEG/MT/Problem3D/Probs.py b/SimPEG/MT/Problem3D/Probs.py index 512362b8..d36a567e 100644 --- a/SimPEG/MT/Problem3D/Probs.py +++ b/SimPEG/MT/Problem3D/Probs.py @@ -1,3 +1,9 @@ +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 SimPEG import Survey, Problem, Utils, Models, np, sp, mkvc, SolverLU as SimpegSolver from SimPEG.EM.Utils import omega from scipy.constants import mu_0 @@ -115,7 +121,7 @@ class eForm_ps(BaseMTProblem): for freq in self.survey.freqs: if self.verbose: startTime = time.time() - print 'Starting work for {:.3e}'.format(freq) + print('Starting work for {:.3e}'.format(freq)) sys.stdout.flush() A = self.getA(freq) rhs = self.getRHS(freq) @@ -131,7 +137,7 @@ class eForm_ps(BaseMTProblem): # Note curl e = -iwb so b = -curl/iw if self.verbose: - print 'Ran for {:f} seconds'.format(time.time()-startTime) + print('Ran for {:f} seconds'.format(time.time()-startTime)) sys.stdout.flush() Ainv.clean() return F diff --git a/SimPEG/MT/Problem3D/__init__.py b/SimPEG/MT/Problem3D/__init__.py index 27e761a9..0018f3d4 100644 --- a/SimPEG/MT/Problem3D/__init__.py +++ b/SimPEG/MT/Problem3D/__init__.py @@ -1 +1,7 @@ -from Probs import eForm_ps \ No newline at end of file +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 .Probs import eForm_ps \ No newline at end of file diff --git a/SimPEG/MT/SrcMT.py b/SimPEG/MT/SrcMT.py index 138d161f..705c02be 100644 --- a/SimPEG/MT/SrcMT.py +++ b/SimPEG/MT/SrcMT.py @@ -1,10 +1,17 @@ +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 from SimPEG import Utils, Problem, Maps, np, sp, mkvc from SimPEG.EM.FDEM.SrcFDEM import BaseSrc as FDEMBaseSrc from SimPEG.EM.Utils import omega from scipy.constants import mu_0 from numpy.lib import recfunctions as recFunc -from Utils.sourceUtils import homo1DModelSource -from Utils import rec2ndarr +from .Utils.sourceUtils import homo1DModelSource +from .Utils import rec2ndarr import sys ################# @@ -78,7 +85,7 @@ class polxy_1Dprimary(BaseMTSrc): C = problem.mesh.nodalGrad elif problem.mesh.dim == 3: C = problem.mesh.edgeCurl - bBG_bp = (- C * self.ePrimary(problem) )*(1/( 1j*omega(self.freq) )) + bBG_bp = (- C * self.ePrimary(problem) )*(old_div(1,( 1j*omega(self.freq) ))) return bBG_bp def S_e(self,problem): @@ -155,7 +162,7 @@ class polxy_3Dprimary(BaseMTSrc): C = problem.mesh.nodalGrad elif problem.mesh.dim == 3: C = problem.mesh.edgeCurl - bBG_bp = (- C * self.ePrimary(problem) )*(1/( 1j*omega(self.freq) )) + bBG_bp = (- C * self.ePrimary(problem) )*(old_div(1,( 1j*omega(self.freq) ))) return bBG_bp def S_e(self,problem): diff --git a/SimPEG/MT/SurveyMT.py b/SimPEG/MT/SurveyMT.py index 0ec91a0e..ee680234 100644 --- a/SimPEG/MT/SurveyMT.py +++ b/SimPEG/MT/SurveyMT.py @@ -1,10 +1,17 @@ +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 from SimPEG import Survey as SimPEGsurvey, Utils, Problem, Maps, np, sp, mkvc from SimPEG.EM.FDEM.SrcFDEM import BaseSrc as FDEMBaseSrc from SimPEG.EM.Utils import omega from scipy.constants import mu_0 from numpy.lib import recfunctions as recFunc -from Utils import rec2ndarr -import SrcMT +from .Utils import rec2ndarr +from . import SrcMT import sys ################# @@ -76,7 +83,7 @@ class Rx(SimPEGsurvey.BaseRx): bx = Pbx*mkvc(f[src,'b_1d'],2)/mu_0 # Note: Has a minus sign in front, to comply with quadrant calculations. # Can be derived from zyx case for the 3D case. - f_part_complex = -ex/bx + f_part_complex = old_div(-ex,bx) # elif self.projType is 'Z2D': elif self.projType is 'Z3D': ## NOTE: Assumes that e is on edges and b on the faces. Need to generalize that or use a prop of fields to determine that. @@ -103,13 +110,13 @@ class Rx(SimPEGsurvey.BaseRx): hy_py = Pby*f[src,'b_py']/mu_0 # Make the complex data if 'zxx' in self.rxType: - f_part_complex = ( ex_px*hy_py - ex_py*hy_px)/(hx_px*hy_py - hx_py*hy_px) + f_part_complex = old_div(( ex_px*hy_py - ex_py*hy_px),(hx_px*hy_py - hx_py*hy_px)) elif 'zxy' in self.rxType: - f_part_complex = (-ex_px*hx_py + ex_py*hx_px)/(hx_px*hy_py - hx_py*hy_px) + f_part_complex = old_div((-ex_px*hx_py + ex_py*hx_px),(hx_px*hy_py - hx_py*hy_px)) elif 'zyx' in self.rxType: - f_part_complex = ( ey_px*hy_py - ey_py*hy_px)/(hx_px*hy_py - hx_py*hy_px) + f_part_complex = old_div(( ey_px*hy_py - ey_py*hy_px),(hx_px*hy_py - hx_py*hy_px)) elif 'zyy' in self.rxType: - f_part_complex = (-ey_px*hx_py + ey_py*hx_px)/(hx_px*hy_py - hx_py*hy_px) + f_part_complex = old_div((-ey_px*hx_py + ey_py*hx_px),(hx_px*hy_py - hx_py*hy_px)) elif self.projType is 'T3D': if self.locs.ndim == 3: horLoc = self.locs[:,:,0] @@ -127,9 +134,9 @@ class Rx(SimPEGsurvey.BaseRx): by_py = Pby*f[src,'b_py'] bz_py = Pbz*f[src,'b_py'] if 'tzx' in self.rxType: - f_part_complex = (- by_px*bz_py + by_py*bz_px)/(bx_px*by_py - bx_py*by_px) + f_part_complex = old_div((- by_px*bz_py + by_py*bz_px),(bx_px*by_py - bx_py*by_px)) if 'tzy' in self.rxType: - f_part_complex = ( bx_px*bz_py - bx_py*bz_px)/(bx_px*by_py - bx_py*by_px) + f_part_complex = old_div(( bx_px*bz_py - bx_py*bz_px),(bx_px*by_py - bx_py*by_px)) else: NotImplementedError('Projection of {:s} receiver type is not implemented.'.format(self.rxType)) @@ -157,8 +164,8 @@ class Rx(SimPEGsurvey.BaseRx): Pbx = mesh.getInterpolationMat(self.locs[:,-1],'Ex') # ex = Pex*mkvc(f[src,'e_1d'],2) # bx = Pbx*mkvc(f[src,'b_1d'],2)/mu_0 - dP_de = -mkvc(Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))*(Pex*v),2) - dP_db = mkvc( Utils.sdiag(Pex*mkvc(f[src,'e_1d'],2))*(Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)).T*Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)))*(Pbx*f._bDeriv_u(src,v)/mu_0),2) + dP_de = -mkvc(Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)))*(Pex*v),2) + dP_db = mkvc( Utils.sdiag(Pex*mkvc(f[src,'e_1d'],2))*(Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))).T*Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))))*(Pbx*f._bDeriv_u(src,v)/mu_0),2) PDeriv_complex = np.sum(np.hstack((dP_de,dP_db)),1) elif self.projType is 'Z2D': raise NotImplementedError('Has not been implement for 2D impedance tensor') @@ -198,7 +205,7 @@ class Rx(SimPEGsurvey.BaseRx): # Update the input vector sDiag = lambda t: Utils.sdiag(mkvc(t,2)) # Define the components of the derivative - Hd = sDiag(1./(sDiag(hx_px)*hy_py - sDiag(hx_py)*hy_px)) + Hd = sDiag(old_div(1.,(sDiag(hx_px)*hy_py - sDiag(hx_py)*hy_px))) Hd_uV = sDiag(hy_py)*hx_px_u(v) + sDiag(hx_px)*hy_py_u(v) - sDiag(hx_py)*hy_px_u(v) - sDiag(hy_px)*hx_py_u(v) # Calculate components if 'zxx' in self.rxType: @@ -247,7 +254,7 @@ class Rx(SimPEGsurvey.BaseRx): # Update the input vector sDiag = lambda t: Utils.sdiag(mkvc(t,2)) # Define the components of the derivative - Hd = sDiag(1./(sDiag(bx_px)*by_py - sDiag(bx_py)*by_px)) + Hd = sDiag(old_div(1.,(sDiag(bx_px)*by_py - sDiag(bx_py)*by_px))) Hd_uV = sDiag(by_py)*bx_px_u(v) + sDiag(bx_px)*by_py_u(v) - sDiag(bx_py)*by_px_u(v) - sDiag(by_px)*bx_py_u(v) if 'tzx' in self.rxType: Tij = sDiag(Hd*( - sDiag(by_px)*bz_py + sDiag(by_py)*bz_px )) @@ -267,8 +274,8 @@ class Rx(SimPEGsurvey.BaseRx): Pbx = mesh.getInterpolationMat(self.locs[:,-1],'Ex') # ex = Pex*mkvc(f[src,'e_1d'],2) # bx = Pbx*mkvc(f[src,'b_1d'],2)/mu_0 - dP_deTv = -mkvc(Pex.T*Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)).T*v,2) - db_duv = Pbx.T/mu_0*Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))*(Utils.sdiag(1./(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))).T*Utils.sdiag(Pex*mkvc(f[src,'e_1d'],2)).T*v + dP_deTv = -mkvc(Pex.T*Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0))).T*v,2) + db_duv = Pbx.T/mu_0*Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)))*(Utils.sdiag(old_div(1.,(Pbx*mkvc(f[src,'b_1d'],2)/mu_0)))).T*Utils.sdiag(Pex*mkvc(f[src,'e_1d'],2)).T*v dP_dbTv = mkvc(f._bDeriv_u(src,db_duv,adjoint=True),2) PDeriv_real = np.sum(np.hstack((dP_deTv,dP_dbTv)),1) elif self.projType is 'Z2D': @@ -300,17 +307,17 @@ class Rx(SimPEGsurvey.BaseRx): aey_px_u = lambda vec: f._e_pxDeriv_u(src,Pey.T*vec,adjoint=True) aex_py_u = lambda vec: f._e_pyDeriv_u(src,Pex.T*vec,adjoint=True) aey_py_u = lambda vec: f._e_pyDeriv_u(src,Pey.T*vec,adjoint=True) - ahx_px_u = lambda vec: f._b_pxDeriv_u(src,Pbx.T*vec,adjoint=True)/mu_0 - ahy_px_u = lambda vec: f._b_pxDeriv_u(src,Pby.T*vec,adjoint=True)/mu_0 - ahx_py_u = lambda vec: f._b_pyDeriv_u(src,Pbx.T*vec,adjoint=True)/mu_0 - ahy_py_u = lambda vec: f._b_pyDeriv_u(src,Pby.T*vec,adjoint=True)/mu_0 + ahx_px_u = lambda vec: old_div(f._b_pxDeriv_u(src,Pbx.T*vec,adjoint=True),mu_0) + ahy_px_u = lambda vec: old_div(f._b_pxDeriv_u(src,Pby.T*vec,adjoint=True),mu_0) + ahx_py_u = lambda vec: old_div(f._b_pyDeriv_u(src,Pbx.T*vec,adjoint=True),mu_0) + ahy_py_u = lambda vec: old_div(f._b_pyDeriv_u(src,Pby.T*vec,adjoint=True),mu_0) # Update the input vector # Define shortcuts sDiag = lambda t: Utils.sdiag(mkvc(t,2)) sVec = lambda t: Utils.sp.csr_matrix(mkvc(t,2)) # Define the components of the derivative - aHd = sDiag(1./(sDiag(ahx_px)*ahy_py - sDiag(ahx_py)*ahy_px)) + aHd = sDiag(old_div(1.,(sDiag(ahx_px)*ahy_py - sDiag(ahx_py)*ahy_px))) aHd_uV = lambda x: ahx_px_u(sDiag(ahy_py)*x) + ahx_px_u(sDiag(ahy_py)*x) - ahy_px_u(sDiag(ahx_py)*x) - ahx_py_u(sDiag(ahy_px)*x) # Need to fix this to reflect the adjoint if 'zxx' in self.rxType: @@ -362,7 +369,7 @@ class Rx(SimPEGsurvey.BaseRx): sDiag = lambda t: Utils.sdiag(mkvc(t,2)) sVec = lambda t: Utils.sp.csr_matrix(mkvc(t,2)) # Define the components of the derivative - aHd = sDiag(1./(sDiag(abx_px)*aby_py - sDiag(abx_py)*aby_px)) + aHd = sDiag(old_div(1.,(sDiag(abx_px)*aby_py - sDiag(abx_py)*aby_px))) aHd_uV = lambda x: abx_px_u(sDiag(aby_py)*x) + abx_px_u(sDiag(aby_py)*x) - aby_px_u(sDiag(abx_py)*x) - abx_py_u(sDiag(aby_px)*x) # Need to fix this to reflect the adjoint if 'tzx' in self.rxType: diff --git a/SimPEG/MT/Utils/MT1Danalytic.py b/SimPEG/MT/Utils/MT1Danalytic.py index a28777cb..8592fc63 100644 --- a/SimPEG/MT/Utils/MT1Danalytic.py +++ b/SimPEG/MT/Utils/MT1Danalytic.py @@ -1,3 +1,11 @@ +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 builtins import zip +from past.utils import old_div # Analytic solution of EM fields due to a plane wave import numpy as np, SimPEG as simpeg @@ -33,8 +41,8 @@ def getEHfields(m1d,sigma,freq,zd,scaleUD=True): # Loop over all the layers, starting at the bottom layer for lnr, h in enumerate(m1d.hx): # lnr-number of layer, h-thickness of the layer # Calculate - yp1 = k[lnr]/(w*mu[lnr]) # Admittance of the layer below the current layer - zp = (w*mu[lnr+1])/k[lnr+1] # Impedance in the current layer + yp1 = old_div(k[lnr],(w*mu[lnr])) # Admittance of the layer below the current layer + zp = old_div((w*mu[lnr+1]),k[lnr+1]) # Impedance in the current layer # Build the propagation matrix # Convert fields to down/up going components in layer below current layer @@ -48,7 +56,7 @@ def getEHfields(m1d,sigma,freq,zd,scaleUD=True): UDp[:,lnr+1] = elamh.dot(Pjinv.dot(Pj1)).dot(UDp[:,lnr]) if scaleUD: - UDp[:,lnr+1::-1] = UDp[:,lnr+1::-1]/UDp[1,lnr+1] + UDp[:,lnr+1::-1] = old_div(UDp[:,lnr+1::-1],UDp[1,lnr+1]) # Calculate the fields Ed = np.empty((zd.size,),dtype=complex) @@ -62,14 +70,14 @@ def getEHfields(m1d,sigma,freq,zd,scaleUD=True): dind = dup >= zd Ed[dind] = UDp[1,0]*np.exp(-1j*k[0]*(dup-zd[dind])) Eu[dind] = UDp[0,0]*np.exp(1j*k[0]*(dup-zd[dind])) - Hd[dind] = (k[0]/(w*mu[0]))*UDp[1,0]*np.exp(-1j*k[0]*(dup-zd[dind])) - Hu[dind] = -(k[0]/(w*mu[0]))*UDp[0,0]*np.exp(1j*k[0]*(dup-zd[dind])) + Hd[dind] = (old_div(k[0],(w*mu[0])))*UDp[1,0]*np.exp(-1j*k[0]*(dup-zd[dind])) + Hu[dind] = -(old_div(k[0],(w*mu[0])))*UDp[0,0]*np.exp(1j*k[0]*(dup-zd[dind])) for ki,mui,epsi,dlow,dup,Up,Dp in zip(k[1::],mu[1::],eps[1::],m1d.vectorNx[:-1],m1d.vectorNx[1::],UDp[0,1::],UDp[1,1::]): dind = np.logical_and(dup >= zd, zd > dlow) Ed[dind] = Dp*np.exp(-1j*ki*(dup-zd[dind])) Eu[dind] = Up*np.exp(1j*ki*(dup-zd[dind])) - Hd[dind] = (ki/(w*mui))*Dp*np.exp(-1j*ki*(dup-zd[dind])) - Hu[dind] = -(ki/(w*mui))*Up*np.exp(1j*ki*(dup-zd[dind])) + Hd[dind] = (old_div(ki,(w*mui)))*Dp*np.exp(-1j*ki*(dup-zd[dind])) + Hu[dind] = -(old_div(ki,(w*mui)))*Up*np.exp(1j*ki*(dup-zd[dind])) # Return return the fields return Ed, Eu, Hd, Hu @@ -92,15 +100,15 @@ def getImpedance(m1d,sigma,freq): om = 2*np.pi*fr Zall = np.empty(len(h)+1,dtype='complex') # Calculate the impedance for the bottom layer - Zall[0] = (mu_0*om)/np.sqrt(mu_0*eps_0*(om)**2 - 1j*mu_0*sigma[0]*om) + Zall[0] = old_div((mu_0*om),np.sqrt(mu_0*eps_0*(om)**2 - 1j*mu_0*sigma[0]*om)) for nr,hi in enumerate(h): # Calculate the wave number # print nr,sigma[nr] k = np.sqrt(mu_0*eps_0*om**2 - 1j*mu_0*sigma[nr]*om) - Z = (mu_0*om)/k + Z = old_div((mu_0*om),k) - Zall[nr+1] = Z *((Zall[nr] + Z*np.tanh(1j*k*hi))/(Z + Zall[nr]*np.tanh(1j*k*hi))) + Zall[nr+1] = Z *(old_div((Zall[nr] + Z*np.tanh(1j*k*hi)),(Z + Zall[nr]*np.tanh(1j*k*hi)))) #pdb.set_trace() Z1d[nrFr] = Zall[-1] diff --git a/SimPEG/MT/Utils/MT1Dsolutions.py b/SimPEG/MT/Utils/MT1Dsolutions.py index aae83162..654687d7 100644 --- a/SimPEG/MT/Utils/MT1Dsolutions.py +++ b/SimPEG/MT/Utils/MT1Dsolutions.py @@ -1,5 +1,12 @@ +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, SimPEG as simpeg -from MT1Danalytic import getEHfields +from .MT1Danalytic import getEHfields from scipy.constants import mu_0 def get1DEfields(m1d,sigma,freq,sourceAmp=1.0): @@ -9,7 +16,7 @@ def get1DEfields(m1d,sigma,freq,sourceAmp=1.0): G = m1d.nodalGrad # Mass matrices # Magnetic permeability - Mmu = simpeg.Utils.sdiag(m1d.vol*(1.0/mu_0)) + Mmu = simpeg.Utils.sdiag(m1d.vol*(old_div(1.0,mu_0))) # Conductivity Msig = m1d.getFaceInnerProduct(sigma) # Set up the solution matrix @@ -23,7 +30,7 @@ def get1DEfields(m1d,sigma,freq,sourceAmp=1.0): Ed, Eu, Hd, Hu = getEHfields(m1d,sigma,freq,m1d.vectorNx) Etot = (Ed + Eu) if sourceAmp is not None: - Etot = ((Etot/Etot[-1])*sourceAmp) # Scale the fields to be equal to sourceAmp at the top + Etot = ((old_div(Etot,Etot[-1]))*sourceAmp) # Scale the fields to be equal to sourceAmp at the top ## Note: The analytic solution is derived with e^iwt bc = np.r_[Etot[0],Etot[-1]] # The right hand side diff --git a/SimPEG/MT/Utils/__init__.py b/SimPEG/MT/Utils/__init__.py index b683f8b4..14d9307b 100644 --- a/SimPEG/MT/Utils/__init__.py +++ b/SimPEG/MT/Utils/__init__.py @@ -1,4 +1,10 @@ -from MT1Dsolutions import * # Add the names of the functions -from MT1Danalytic import * -from dataUtils import * -from ediFilesUtils 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 .MT1Dsolutions import * # Add the names of the functions +from .MT1Danalytic import * +from .dataUtils import * +from .ediFilesUtils import * diff --git a/SimPEG/MT/Utils/dataUtils.py b/SimPEG/MT/Utils/dataUtils.py index 614470d9..2e97a06b 100644 --- a/SimPEG/MT/Utils/dataUtils.py +++ b/SimPEG/MT/Utils/dataUtils.py @@ -1,3 +1,10 @@ +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 past.utils import old_div # Utils used for the data, import numpy as np, matplotlib.pyplot as plt, sys import SimPEG as simpeg @@ -45,13 +52,13 @@ def rotateData(MTdata, rotAngle): def appResPhs(freq, z): - app_res = ((1./(8e-7*np.pi**2))/freq)*np.abs(z)**2 - app_phs = np.arctan2(z.imag,z.real)*(180/np.pi) + app_res = (old_div((old_div(1.,(8e-7*np.pi**2))),freq))*np.abs(z)**2 + app_phs = np.arctan2(z.imag,z.real)*(old_div(180,np.pi)) return app_res, app_phs def skindepth(rho, freq): ''' Function to calculate the skindepth of EM waves''' - return np.sqrt( (rho*((1/(freq * mu_0 * np.pi ))))) + return np.sqrt( (rho*((old_div(1,(freq * mu_0 * np.pi )))))) def rec2ndarr(x, dt=float): return x.view((dt, len(x.dtype.names))) @@ -64,7 +71,7 @@ def makeAnalyticSolution(mesh, model, elev, freqs): anaE = anaEd+anaEu anaH = anaHd+anaHu - anaZ = anaE/anaH + anaZ = old_div(anaE,anaH) # Add to the list data1D.append((freq,0,0,elev,anaZ[0])) dataRec = np.array(data1D,dtype=[('freq',float),('x',float),('y',float),('z',float),('zyx',complex)]) @@ -97,7 +104,7 @@ def plotMT1DModelData(problem, models, symList=None): # if not symList: # symList = ['x']*len(models) - import plotDataTypes as pDt + from . import plotDataTypes as pDt # Loop through the models. modelList = [problem.survey.mtrue] modelList.extend(models) @@ -110,14 +117,14 @@ def plotMT1DModelData(problem, models, symList=None): else: data1D = problem.dataPair(problem.survey,problem.survey.dpred(model)).toRecArray('Complex') # Plot the data and the model - colRat = nr/((len(modelList)-1.999)*1.) + colRat = old_div(nr,((len(modelList)-1.999)*1.)) if colRat > 1.: col = 'k' else: col = plt.cm.seismic(1-colRat) # The model - make the pts to plot meshPts = np.concatenate((problem.mesh.gridN[0:1],np.kron(problem.mesh.gridN[1::],np.ones(2))[:-1])) - modelPts = np.kron(1./(problem.mapping.sigmaMap*model),np.ones(2,)) + modelPts = np.kron(old_div(1.,(problem.mapping.sigmaMap*model)),np.ones(2,)) axM.semilogx(modelPts,meshPts,color=col) ## Data @@ -144,7 +151,7 @@ def plotMT1DModelData(problem, models, symList=None): # Fix labels and ticks - yMtick = [l/1000 for l in axM.get_yticks().tolist()] + yMtick = [old_div(l,1000) for l in axM.get_yticks().tolist()] axM.set_yticklabels(yMtick) [ l.set_rotation(90) for l in axM.get_yticklabels()] [ l.set_rotation(90) for l in axR.get_yticklabels()] @@ -157,7 +164,7 @@ def plotMT1DModelData(problem, models, symList=None): def printTime(): import time - print time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime()) + print(time.strftime("%a, %d %b %Y %H:%M:%S +0000", time.localtime())) def convert3Dto1Dobject(MTdata,rxType3D='zyx'): from SimPEG import MT diff --git a/SimPEG/MT/Utils/ediFilesUtils.py b/SimPEG/MT/Utils/ediFilesUtils.py index d8f5e0ad..f358795f 100644 --- a/SimPEG/MT/Utils/ediFilesUtils.py +++ b/SimPEG/MT/Utils/ediFilesUtils.py @@ -1,3 +1,13 @@ +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import +from builtins import open +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import object +from past.utils import old_div # Functions to import and export MT EDI files. from SimPEG import mkvc from scipy.constants import mu_0 @@ -9,7 +19,7 @@ import numpy as np import os, sys, re -class EDIimporter: +class EDIimporter(object): """ A class to import EDIfiles. @@ -18,7 +28,7 @@ class EDIimporter: # Define data converters _impUnitEDI2SI = 4*np.pi*1e-4 # Convert Z[mV/km/nT] (as in EDI)to Z[V/A] SI unit - _impUnitSI2EDI = 1./_impUnitEDI2SI # ConvertZ[V/A] SI unit to Z[mV/km/nT] (as in EDI) + _impUnitSI2EDI = old_div(1.,_impUnitEDI2SI) # ConvertZ[V/A] SI unit to Z[mV/km/nT] (as in EDI) # Properties filesList = None @@ -116,7 +126,7 @@ class EDIimporter: try: import osr except ImportError as e: - print 'Could not import osr, missing the gdal package\nCan not project coordinates' + print('Could not import osr, missing the gdal package\nCan not project coordinates') raise e # Coordinates convertor if self._2out is None: @@ -126,7 +136,7 @@ class EDIimporter: if self._outEPSG is None: # Find the UTM EPSG number Nnr = 700 if latD < 0.0 else 600 - utmZ = int(1+(longD+180.0)/6.0) + utmZ = int(1+old_div((longD+180.0),6.0)) self._outEPSG = 32000 + Nnr + utmZ out.ImportFromEPSG(self._outEPSG) self._2out = osr.CoordinateTransformation(src,out) diff --git a/SimPEG/MT/Utils/plotDataTypes.py b/SimPEG/MT/Utils/plotDataTypes.py index c0180f00..8a5646e9 100644 --- a/SimPEG/MT/Utils/plotDataTypes.py +++ b/SimPEG/MT/Utils/plotDataTypes.py @@ -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 from matplotlib import pyplot as plt, colors, numpy as np @@ -65,9 +72,9 @@ def plotIsoFreqNSDiff(ax,freq,arrayList,flag,par='abs',colorbar=True,cLevel=True x, y = arrayList[0]['x'][indUniFreq0],arrayList[0]['y'][indUniFreq0] if par == 'abs': if useLog: - zPlot = (np.log10(np.abs(arrayList[0][flag][indUniFreq0])) - np.log10(np.abs(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs(arrayList[1][flag][indUniFreq1])) + zPlot = old_div((np.log10(np.abs(arrayList[0][flag][indUniFreq0])) - np.log10(np.abs(arrayList[1][flag][indUniFreq1]))),np.log10(np.abs(arrayList[1][flag][indUniFreq1]))) else: - zPlot = (np.abs(arrayList[0][flag][indUniFreq0]) - np.abs(arrayList[1][flag][indUniFreq1]))/np.abs(arrayList[1][flag][indUniFreq1]) + zPlot = old_div((np.abs(arrayList[0][flag][indUniFreq0]) - np.abs(arrayList[1][flag][indUniFreq1])),np.abs(arrayList[1][flag][indUniFreq1])) if mask: maskInd = np.logical_or(np.abs(arrayList[0][flag][indUniFreq0])< 1e-3,np.abs(arrayList[1][flag][indUniFreq1]) < 1e-3) zPlot = np.ma.array(zPlot) @@ -80,9 +87,9 @@ def plotIsoFreqNSDiff(ax,freq,arrayList,flag,par='abs',colorbar=True,cLevel=True clevel = np.linspace(zPlot.min(),zPlot.max(),10) elif par == 'real': if useLog: - zPlot = (np.log10(np.real(arrayList[0][flag][indUniFreq0])) -np.log10(np.real(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs((np.real(arrayList[1][flag][indUniFreq1])))) + zPlot = old_div((np.log10(np.real(arrayList[0][flag][indUniFreq0])) -np.log10(np.real(arrayList[1][flag][indUniFreq1]))),np.log10(np.abs((np.real(arrayList[1][flag][indUniFreq1]))))) else: - zPlot = (np.real(arrayList[0][flag][indUniFreq0]) -np.real(arrayList[1][flag][indUniFreq1]))/np.abs((np.real(arrayList[1][flag][indUniFreq1]))) + zPlot = old_div((np.real(arrayList[0][flag][indUniFreq0]) -np.real(arrayList[1][flag][indUniFreq1])),np.abs((np.real(arrayList[1][flag][indUniFreq1])))) if mask: maskInd = np.logical_or(np.abs(np.real(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.real(arrayList[1][flag][indUniFreq1])) < 1e-3) zPlot = np.ma.array(zPlot) @@ -95,9 +102,9 @@ def plotIsoFreqNSDiff(ax,freq,arrayList,flag,par='abs',colorbar=True,cLevel=True clevel = np.linspace(zPlot.min(),zPlot.max(),10) elif par == 'imag': if useLog: - zPlot = (np.log10(np.imag(arrayList[0][flag][indUniFreq0])) -np.log10(np.imag(arrayList[1][flag][indUniFreq1])))/np.log10(np.abs((np.imag(arrayList[1][flag][indUniFreq1])))) + zPlot = old_div((np.log10(np.imag(arrayList[0][flag][indUniFreq0])) -np.log10(np.imag(arrayList[1][flag][indUniFreq1]))),np.log10(np.abs((np.imag(arrayList[1][flag][indUniFreq1]))))) else: - zPlot = (np.imag(arrayList[0][flag][indUniFreq0]) -np.imag(arrayList[1][flag][indUniFreq1]))/np.abs((np.imag(arrayList[1][flag][indUniFreq1]))) + zPlot = old_div((np.imag(arrayList[0][flag][indUniFreq0]) -np.imag(arrayList[1][flag][indUniFreq1])),np.abs((np.imag(arrayList[1][flag][indUniFreq1])))) if mask: maskInd = np.logical_or(np.abs(np.imag(arrayList[0][flag][indUniFreq0])) < 1e-3,np.abs(np.imag(arrayList[1][flag][indUniFreq1])) < 1e-3) zPlot = np.ma.array(zPlot) @@ -176,7 +183,7 @@ def plotIsoFreqNStipper(ax,freq,array,flag,par='abs',colorbar=True,colorNorm='Sy def plotIsoStaImpedance(ax,loc,array,flag,par='abs',pSym='s',pColor=None): - appResFact = 1/(8*np.pi**2*10**(-7)) + appResFact = old_div(1,(8*np.pi**2*10**(-7))) treshold = 1.0 # 1 meter indUniSta = np.sqrt(np.sum((rec2nd(array[['x','y']])-loc)**2,axis=1)) < treshold freq = array['freq'][indUniSta] @@ -188,9 +195,9 @@ def plotIsoStaImpedance(ax,loc,array,flag,par='abs',pSym='s',pColor=None): elif par == 'imag': zPlot = np.imag(array[flag][indUniSta]) elif par == 'res': - zPlot = (appResFact/freq)*np.abs(array[flag][indUniSta])**2 + zPlot = (old_div(appResFact,freq))*np.abs(array[flag][indUniSta])**2 elif par == 'phs': - zPlot = np.arctan2(array[flag][indUniSta].imag,array[flag][indUniSta].real)*(180/np.pi) + zPlot = np.arctan2(array[flag][indUniSta].imag,array[flag][indUniSta].real)*(old_div(180,np.pi)) if not pColor: if 'xx' in flag: @@ -211,10 +218,10 @@ def plotIsoStaImpedance(ax,loc,array,flag,par='abs',pSym='s',pColor=None): def plotPsudoSectNSimpedance(ax,sectDict,array,flag,par='abs',colorbar=True,colorNorm='None',cLevel=None,contour=True): - indSect = np.where(sectDict.values()[0]==array[sectDict.keys()[0]]) + indSect = np.where(list(sectDict.values())[0]==array[list(sectDict.keys())[0]]) # Define the plot axes - if 'x' in sectDict.keys()[0]: + if 'x' in list(sectDict.keys())[0]: x = array['y'][indSect] else: x = array['x'][indSect] @@ -231,7 +238,7 @@ def plotPsudoSectNSimpedance(ax,sectDict,array,flag,par='abs',colorbar=True,colo clevel = np.linspace(zPlot.min(),zPlot.max(),10,endpoint=True) elif par == 'ares': - zPlot = np.abs(array[flag][indSect])**2/(8*np.pi**2*10**(-7)*array['freq'][indSect]) + zPlot = old_div(np.abs(array[flag][indSect])**2,(8*np.pi**2*10**(-7)*array['freq'][indSect])) cmap = plt.get_cmap('RdYlBu')#seismic) if cLevel: zMax = np.log10(cLevel[1]) @@ -244,7 +251,7 @@ def plotPsudoSectNSimpedance(ax,sectDict,array,flag,par='abs',colorbar=True,colo plotNorm = colors.LogNorm() elif par == 'aphs': - zPlot = np.arctan2(array[flag][indSect].imag,array[flag][indSect].real)*(180/np.pi) + zPlot = np.arctan2(array[flag][indSect].imag,array[flag][indSect].real)*(old_div(180,np.pi)) cmap = plt.get_cmap('RdYlBu')#seismic) if cLevel: zMax = cLevel[1] @@ -307,14 +314,14 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color def sortInArr(arr): return np.sort(arr,order=['freq','x','y','z']) # Find the index for the slice - indSect0 = np.where(sectDict.values()[0]==arrayList[0][sectDict.keys()[0]]) - indSect1 = np.where(sectDict.values()[0]==arrayList[1][sectDict.keys()[0]]) + indSect0 = np.where(list(sectDict.values())[0]==arrayList[0][list(sectDict.keys())[0]]) + indSect1 = np.where(list(sectDict.values())[0]==arrayList[1][list(sectDict.keys())[0]]) # Extract and sort the mats arr0 = sortInArr(arrayList[0][indSect0]) arr1 = sortInArr(arrayList[1][indSect1]) # Define the plot axes - if 'x' in sectDict.keys()[0]: + if 'x' in list(sectDict.keys())[0]: x0 = arr0['y'] x1 = arr1['y'] else: @@ -326,20 +333,20 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color if par == 'abs': if useLog: - zPlot = (np.log10(np.abs(arr0[flag])) - np.log10(np.abs(arr1[flag])))/np.log10(np.abs(arr1[flag])) + zPlot = old_div((np.log10(np.abs(arr0[flag])) - np.log10(np.abs(arr1[flag]))),np.log10(np.abs(arr1[flag]))) else: - zPlot = (np.abs(arr0[flag]) - np.abs(arr1[flag]))/np.abs(arr1[flag]) + zPlot = old_div((np.abs(arr0[flag]) - np.abs(arr1[flag])),np.abs(arr1[flag])) if mask: maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3) zPlot = np.ma.array(zPlot) zPlot[maskInd] = mask cmap = plt.get_cmap('RdYlBu')#seismic) elif par == 'ares': - arF = 1/(8*np.pi**2*10**(-7)) + arF = old_div(1,(8*np.pi**2*10**(-7))) if useLog: - zPlot = (np.log10((arF/arr0['freq'])*np.abs(arr0[flag])**2) - np.log10((arF/arr1['freq'])*np.abs(arr1[flag])**2))/np.log10((arF/arr1['freq'])*np.abs(arr1[flag])**2) + zPlot = old_div((np.log10((old_div(arF,arr0['freq']))*np.abs(arr0[flag])**2) - np.log10((old_div(arF,arr1['freq']))*np.abs(arr1[flag])**2)),np.log10((old_div(arF,arr1['freq']))*np.abs(arr1[flag])**2)) else: - zPlot = ((arF/arr0['freq'])*np.abs(arr0[flag])**2 - (arF/arr1['freq'])*np.abs(arr1[flag])**2)/((arF/arr1['freq'])*np.abs(arr1[flag])**2) + zPlot = old_div(((old_div(arF,arr0['freq']))*np.abs(arr0[flag])**2 - (old_div(arF,arr1['freq']))*np.abs(arr1[flag])**2),((old_div(arF,arr1['freq']))*np.abs(arr1[flag])**2)) if mask: maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3) zPlot = np.ma.array(zPlot) @@ -348,9 +355,9 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color elif par == 'aphs': if useLog: - zPlot = (np.log10(np.arctan2(arr0[flag].imag,arr0[flag].real)*(180/np.pi)) - np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi)) )/np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi)) + zPlot = old_div((np.log10(np.arctan2(arr0[flag].imag,arr0[flag].real)*(old_div(180,np.pi))) - np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(old_div(180,np.pi))) ),np.log10(np.arctan2(arr1[flag].imag,arr1[flag].real)*(old_div(180,np.pi)))) else: - zPlot = ( np.arctan2(arr0[flag].imag,arr0[flag].real)*(180/np.pi) - np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi) )/(np.arctan2(arr1[flag].imag,arr1[flag].real)*(180/np.pi)) + zPlot = old_div(( np.arctan2(arr0[flag].imag,arr0[flag].real)*(old_div(180,np.pi)) - np.arctan2(arr1[flag].imag,arr1[flag].real)*(old_div(180,np.pi)) ),(np.arctan2(arr1[flag].imag,arr1[flag].real)*(old_div(180,np.pi)))) if mask: maskInd = np.logical_or(np.abs(arr0[flag])< 1e-3,np.abs(arr1[flag]) < 1e-3) zPlot = np.ma.array(zPlot) @@ -358,9 +365,9 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color cmap = plt.get_cmap('Spectral')#seismic) elif par == 'real': if useLog: - zPlot = (np.log10(arr0[flag].real) - np.log10(arr1[flag].real))/np.log10(arr1[flag].real) + zPlot = old_div((np.log10(arr0[flag].real) - np.log10(arr1[flag].real)),np.log10(arr1[flag].real)) else: - zPlot = (arr0[flag].real - arr1[flag].real)/arr1[flag].real + zPlot = old_div((arr0[flag].real - arr1[flag].real),arr1[flag].real) if mask: maskInd = np.logical_or(arr0[flag].real< 1e-3,arr1[flag].real < 1e-3) zPlot = np.ma.array(zPlot) @@ -369,9 +376,9 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color elif par == 'imag': if useLog: - zPlot = (np.log10(arr0[flag].imag) - np.log10(arr1[flag].imag))/np.log10(arr1[flag].imag) + zPlot = old_div((np.log10(arr0[flag].imag) - np.log10(arr1[flag].imag)),np.log10(arr1[flag].imag)) else: - zPlot = (arr0[flag].imag - arr1[flag].imag)/arr1[flag].imag + zPlot = old_div((arr0[flag].imag - arr1[flag].imag),arr1[flag].imag) if mask: maskInd = np.logical_or(arr0[flag].imag< 1e-3,arr1[flag].imag < 1e-3) zPlot = np.ma.array(zPlot) @@ -392,11 +399,11 @@ def plotPsudoSectNSDiff(ax,sectDict,arrayList,flag,par='abs',colorbar=True,color plotNorm = colors.SymLogNorm(np.abs(level).min(),linscale=0.1) elif colorNorm=='Lin': if cLevel: - level = np.arange(cLevel[0],cLevel[1]+.1,(cLevel[1] - cLevel[0])/50.) - clevel = np.arange(cLevel[0],cLevel[1]+.1,(cLevel[1] - cLevel[0])/10.) + level = np.arange(cLevel[0],cLevel[1]+.1,old_div((cLevel[1] - cLevel[0]),50.)) + clevel = np.arange(cLevel[0],cLevel[1]+.1,old_div((cLevel[1] - cLevel[0]),10.)) else: - level = np.arange(zPlot.min(),zPlot.max(),(zPlot.max() - zPlot.min())/50.) - clevel = np.arange(zPlot.min(),zPlot.max(),(zPlot.max() - zPlot.min())/10.) + level = np.arange(zPlot.min(),zPlot.max(),old_div((zPlot.max() - zPlot.min()),50.)) + clevel = np.arange(zPlot.min(),zPlot.max(),old_div((zPlot.max() - zPlot.min()),10.)) plotNorm = colors.Normalize() elif colorNorm=='Log': level = np.logspace(zMin-.125,zMax,(zMax-zMin)*8+1,endpoint=True) diff --git a/SimPEG/MT/Utils/sourceUtils.py b/SimPEG/MT/Utils/sourceUtils.py index 24b36bfe..2c7e26b4 100644 --- a/SimPEG/MT/Utils/sourceUtils.py +++ b/SimPEG/MT/Utils/sourceUtils.py @@ -1,3 +1,11 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import dict +from future import standard_library +standard_library.install_aliases() +from builtins import zip import SimPEG as simpeg, numpy as np def homo1DModelSource(mesh,freq,sigma_1d): @@ -90,7 +98,7 @@ def analytic1DModelSource(mesh,freq,sigma_1d): Eu, Ed, _, _ = getEHfields(mesh1d,sigma_1d,freq,mesh.vectorNz) # Make the fields into a dictionary of location and the fields e0_1d = Eu+Ed - E1dFieldDict = dict(zip(mesh.vectorNz,e0_1d)) + E1dFieldDict = dict(list(zip(mesh.vectorNz,e0_1d))) if mesh.dim == 1: eBG_px = simpeg.mkvc(e0_1d,2) eBG_py = -simpeg.mkvc(e0_1d,2) # added a minus to make the results in the correct quadrents. diff --git a/SimPEG/MT/Utils/srcUtils.py b/SimPEG/MT/Utils/srcUtils.py index a98cc5b2..1708e921 100644 --- a/SimPEG/MT/Utils/srcUtils.py +++ b/SimPEG/MT/Utils/srcUtils.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import SimPEG as simpeg, numpy as np def homo1DModelSource(mesh,freq,m_back): diff --git a/SimPEG/MT/__init__.py b/SimPEG/MT/__init__.py index b9f5536b..eda16280 100644 --- a/SimPEG/MT/__init__.py +++ b/SimPEG/MT/__init__.py @@ -1,5 +1,11 @@ -import Utils -from SurveyMT import Rx, Survey, Data -from FieldsMT import Fields1D_e, Fields3D_e -import Problem1D, Problem2D, Problem3D -import SrcMT \ No newline at end of file +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 . import Utils +from .SurveyMT import Rx, Survey, Data +from .FieldsMT import Fields1D_e, Fields3D_e +from . import Problem1D, Problem2D, Problem3D +from . import SrcMT \ No newline at end of file diff --git a/SimPEG/Maps.py b/SimPEG/Maps.py index 77e7e9a3..c327c204 100644 --- a/SimPEG/Maps.py +++ b/SimPEG/Maps.py @@ -1,23 +1,34 @@ -import Utils, numpy as np, scipy.sparse as sp +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 str +from builtins import range +from past.utils import old_div +from builtins import object +from . import Utils +import numpy as np, scipy.sparse as sp from scipy.sparse.linalg import LinearOperator -from Tests import checkDerivative -from PropMaps import PropMap, Property +from .Tests import checkDerivative +from .PropMaps import PropMap, Property from numpy.polynomial import polynomial from scipy.interpolate import UnivariateSpline import warnings +from future.utils import with_metaclass -class IdentityMap(object): +class IdentityMap(with_metaclass(Utils.SimPEGMetaClass, object)): """ SimPEG Map """ - __metaclass__ = Utils.SimPEGMetaClass def __init__(self, mesh=None, nP=None, **kwargs): Utils.setKwargs(self, **kwargs) if nP is not None: - assert type(nP) in [int, long], ' Number of parameters must be an integer.' + assert type(nP) in [int, int], ' Number of parameters must be an integer.' self.mesh = mesh self._nP = nP @@ -101,7 +112,7 @@ class IdentityMap(object): :return: passed the test? """ - print 'Testing %s' % str(self) + print('Testing %s' % str(self)) if m is None: m = abs(np.random.rand(self.nP)) if 'plotIt' not in kwargs: @@ -248,10 +259,10 @@ class ReciprocalMap(IdentityMap): """ def _transform(self, m): - return 1.0 / Utils.mkvc(m) + return old_div(1.0, Utils.mkvc(m)) def inverse(self, D): - return 1.0 / Utils.mkvc(m) + return old_div(1.0, Utils.mkvc(m)) def deriv(self, m): # TODO: if this is a tensor, you might have a problem. @@ -291,7 +302,7 @@ class LogMap(IdentityMap): deriv = np.zeros(mod.shape) tol = 1e-16 # zero ind = np.greater_equal(np.abs(mod),tol) - deriv[ind] = 1.0/mod[ind] + deriv[ind] = old_div(1.0,mod[ind]) return Utils.sdiag(deriv) def inverse(self, m): @@ -372,7 +383,7 @@ class SurjectVertical1D(IdentityMap): repNum = self.mesh.vnC[:self.mesh.dim-1].prod() repVec = sp.csr_matrix( (np.ones(repNum), - (range(repNum), np.zeros(repNum)) + (list(range(repNum)), np.zeros(repNum)) ), shape=(repNum, 1)) return sp.kron(sp.identity(self.nP), repVec) @@ -434,7 +445,7 @@ class Surject2Dto3D(IdentityMap): nC, nP = self.mesh.nC, self.nP P = sp.csr_matrix( (np.ones(nC), - (range(nC), inds) + (list(range(nC)), inds) ), shape=(nC, nP)) return P @@ -504,11 +515,11 @@ class InjectActiveCells(IdentityMap): else: self.valInactive = np.ones(self.nC) self.valInactive[self.indInactive] = valInactive.copy() - + self.valInactive[self.indActive] = 0 inds = np.nonzero(self.indActive)[0] - self.P = sp.csr_matrix((np.ones(inds.size),(inds, range(inds.size))), shape=(self.nC, self.nP)) + self.P = sp.csr_matrix((np.ones(inds.size),(inds, list(range(inds.size)))), shape=(self.nC, self.nP)) @property def shape(self): @@ -595,14 +606,14 @@ class ComplexMap(IdentityMap): @property def shape(self): - return (self.nP/2,self.nP) + return (old_div(self.nP,2),self.nP) def _transform(self, m): nC = self.mesh.nC return m[:nC] + m[nC:]*1j def deriv(self, m): - nC = self.nP/2 + nC = old_div(self.nP,2) shp = (nC, nC*2) def fwd(v): return v[:nC] + v[nC:]*1j @@ -647,7 +658,7 @@ class CircleMap(IdentityMap): sig1, sig2 = np.exp(sig1), np.exp(sig2) X = self.mesh.gridCC[:,0] Y = self.mesh.gridCC[:,1] - return sig1 + (sig2 - sig1)*(np.arctan(a*(np.sqrt((X-x)**2 + (Y-y)**2) - r))/np.pi + 0.5) + return sig1 + (sig2 - sig1)*(old_div(np.arctan(a*(np.sqrt((X-x)**2 + (Y-y)**2) - r)),np.pi) + 0.5) def deriv(self, m): a = self.slope @@ -657,11 +668,11 @@ class CircleMap(IdentityMap): X = self.mesh.gridCC[:,0] Y = self.mesh.gridCC[:,1] if self.logSigma: - g1 = -(np.arctan(a*(-r + np.sqrt((X - x)**2 + (Y - y)**2)))/np.pi + 0.5)*sig1 + sig1 - g2 = (np.arctan(a*(-r + np.sqrt((X - x)**2 + (Y - y)**2)))/np.pi + 0.5)*sig2 + g1 = -(old_div(np.arctan(a*(-r + np.sqrt((X - x)**2 + (Y - y)**2))),np.pi) + 0.5)*sig1 + sig1 + g2 = (old_div(np.arctan(a*(-r + np.sqrt((X - x)**2 + (Y - y)**2))),np.pi) + 0.5)*sig2 else: - g1 = -(np.arctan(a*(-r + np.sqrt((X - x)**2 + (Y - y)**2)))/np.pi + 0.5) + 1.0 - g2 = (np.arctan(a*(-r + np.sqrt((X - x)**2 + (Y - y)**2)))/np.pi + 0.5) + g1 = -(old_div(np.arctan(a*(-r + np.sqrt((X - x)**2 + (Y - y)**2))),np.pi) + 0.5) + 1.0 + g2 = (old_div(np.arctan(a*(-r + np.sqrt((X - x)**2 + (Y - y)**2))),np.pi) + 0.5) g3 = a*(-X + x)*(-sig1 + sig2)/(np.pi*(a**2*(-r + np.sqrt((X - x)**2 + (Y - y)**2))**2 + 1)*np.sqrt((X - x)**2 + (Y - y)**2)) g4 = a*(-Y + y)*(-sig1 + sig2)/(np.pi*(a**2*(-r + np.sqrt((X - x)**2 + (Y - y)**2))**2 + 1)*np.sqrt((X - x)**2 + (Y - y)**2)) g5 = -a*(-sig1 + sig2)/(np.pi*(a**2*(-r + np.sqrt((X - x)**2 + (Y - y)**2))**2 + 1)) @@ -695,7 +706,7 @@ class PolyMap(IdentityMap): self.actInd = actInd if getattr(self, 'actInd', None) is None: - self.actInd = range(self.mesh.nC) + self.actInd = list(range(self.mesh.nC)) self.nC = self.mesh.nC else: @@ -731,7 +742,7 @@ class PolyMap(IdentityMap): elif self.normal =='Y': f = polynomial.polyval(X, c) - Y else: - raise(Exception("Input for normal = X or Y or Z")) + raise Exception #3D elif self.mesh.dim == 3: X = self.mesh.gridCC[self.actInd,0] @@ -744,13 +755,13 @@ class PolyMap(IdentityMap): elif self.normal =='Z': f = polynomial.polyval2d(X, Y, c.reshape((self.order[0]+1,self.order[1]+1))) - Z else: - raise(Exception("Input for normal = X or Y or Z")) + raise Exception else: - raise(Exception("Only supports 2D")) + raise Exception - return sig1+(sig2-sig1)*(np.arctan(alpha*f)/np.pi+0.5) + return sig1+(sig2-sig1)*(old_div(np.arctan(alpha*f),np.pi)+0.5) def deriv(self, m): alpha = self.slope @@ -769,7 +780,7 @@ class PolyMap(IdentityMap): f = polynomial.polyval(X, c) - Y V = polynomial.polyvander(X, len(c)-1) else: - raise(Exception("Input for normal = X or Y or Z")) + raise Exception #3D elif self.mesh.dim == 3: X = self.mesh.gridCC[self.actInd,0] @@ -786,14 +797,14 @@ class PolyMap(IdentityMap): f = polynomial.polyval2d(X, Y, c.reshape((self.order[0]+1,self.order[1]+1))) - Z V = polynomial.polyvander2d(X, Y, self.order) else: - raise(Exception("Input for normal = X or Y or Z")) + raise Exception if self.logSigma: - g1 = -(np.arctan(alpha*f)/np.pi + 0.5)*sig1 + sig1 - g2 = (np.arctan(alpha*f)/np.pi + 0.5)*sig2 + g1 = -(old_div(np.arctan(alpha*f),np.pi) + 0.5)*sig1 + sig1 + g2 = (old_div(np.arctan(alpha*f),np.pi) + 0.5)*sig2 else: - g1 = -(np.arctan(alpha*f)/np.pi + 0.5) + 1.0 - g2 = (np.arctan(alpha*f)/np.pi + 0.5) + g1 = -(old_div(np.arctan(alpha*f),np.pi) + 0.5) + 1.0 + g2 = (old_div(np.arctan(alpha*f),np.pi) + 0.5) g3 = Utils.sdiag(alpha*(sig2-sig1)/(1.+(alpha*f)**2)/np.pi)*V @@ -834,7 +845,7 @@ class SplineMap(IdentityMap): elif self.mesh.dim == 3: return np.size(self.pts)*2+2 else: - raise(Exception("Only supports 2D and 3D")) + raise Exception def _transform(self, m): # Set model parameters @@ -853,7 +864,7 @@ class SplineMap(IdentityMap): elif self.normal =='Y': f = self.spl(X) - Y else: - raise(Exception("Input for normal = X or Y or Z")) + raise Exception # 3D: # Comments: @@ -868,7 +879,7 @@ class SplineMap(IdentityMap): npts = np.size(self.pts) if np.mod(c.size, 2): - raise(Exception("Put even points!")) + raise Exception self.spl = {"splb":UnivariateSpline(self.pts, c[:npts], k=self.order, s=0), "splt":UnivariateSpline(self.pts, c[npts:], k=self.order, s=0)} @@ -881,12 +892,12 @@ class SplineMap(IdentityMap): # elif self.normal =='Y': # elif self.normal =='Z': else: - raise(Exception("Input for normal = X or Y or Z")) + raise Exception else: - raise(Exception("Only supports 2D and 3D")) + raise Exception - return sig1+(sig2-sig1)*(np.arctan(alpha*f)/np.pi+0.5) + return sig1+(sig2-sig1)*(old_div(np.arctan(alpha*f),np.pi)+0.5) def deriv(self, m): alpha = self.slope @@ -903,7 +914,7 @@ class SplineMap(IdentityMap): elif self.normal =='Y': f = self.spl(X) - Y else: - raise(Exception("Input for normal = X or Y or Z")) + raise Exception #3D elif self.mesh.dim == 3: X = self.mesh.gridCC[:,0] @@ -917,14 +928,14 @@ class SplineMap(IdentityMap): # elif self.normal =='Y': # elif self.normal =='Z': else: - raise(Exception("Not Implemented for Y and Z, your turn :)")) + raise Exception if self.logSigma: - g1 = -(np.arctan(alpha*f)/np.pi + 0.5)*sig1 + sig1 - g2 = (np.arctan(alpha*f)/np.pi + 0.5)*sig2 + g1 = -(old_div(np.arctan(alpha*f),np.pi) + 0.5)*sig1 + sig1 + g2 = (old_div(np.arctan(alpha*f),np.pi) + 0.5)*sig2 else: - g1 = -(np.arctan(alpha*f)/np.pi + 0.5) + 1.0 - g2 = (np.arctan(alpha*f)/np.pi + 0.5) + g1 = -(old_div(np.arctan(alpha*f),np.pi) + 0.5) + 1.0 + g2 = (old_div(np.arctan(alpha*f),np.pi) + 0.5) if self.mesh.dim ==2: @@ -943,7 +954,7 @@ class SplineMap(IdentityMap): cb[i] = ctemp-dy spla = UnivariateSpline(self.pts, ca, k=self.order, s=0) splb = UnivariateSpline(self.pts, cb, k=self.order, s=0) - fderiv = (spla(X)-splb(X))/(2*dy) + fderiv = old_div((spla(X)-splb(X)),(2*dy)) g3[:,i] = Utils.sdiag(alpha*(sig2-sig1)/(1.+(alpha*f)**2)/np.pi)*fderiv elif self.mesh.dim==3: @@ -970,10 +981,10 @@ class SplineMap(IdentityMap): spltb = UnivariateSpline(self.pts, ca[self.npts:], k=self.order, s=0) flinesa = (self.spl["splt"](Y)-splta(Y))*(Z-zb)/(zt-zb) + splta(Y) - X flinesb = (self.spl["splt"](Y)-spltb(Y))*(Z-zb)/(zt-zb) + spltb(Y) - X - fderiv = (flinesa-flinesb)/(2*dy) + fderiv = old_div((flinesa-flinesb),(2*dy)) g3[:,i] = Utils.sdiag(alpha*(sig2-sig1)/(1.+(alpha*f)**2)/np.pi)*fderiv else : - raise(Exception("Not Implemented for Y and Z, your turn :)")) + raise Exception return sp.csr_matrix(np.c_[g1,g2,g3]) diff --git a/SimPEG/Mesh/BaseMesh.py b/SimPEG/Mesh/BaseMesh.py index 97394b68..149009f0 100644 --- a/SimPEG/Mesh/BaseMesh.py +++ b/SimPEG/Mesh/BaseMesh.py @@ -1,3 +1,11 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import range +from builtins import object import numpy as np from SimPEG import Utils diff --git a/SimPEG/Mesh/CurvilinearMesh.py b/SimPEG/Mesh/CurvilinearMesh.py index abc9ff3a..e809e71d 100644 --- a/SimPEG/Mesh/CurvilinearMesh.py +++ b/SimPEG/Mesh/CurvilinearMesh.py @@ -1,17 +1,26 @@ +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 from SimPEG import Utils, np -from BaseMesh import BaseRectangularMesh -from DiffOperators import DiffOperators -from InnerProducts import InnerProducts -from View import CurvView +from .BaseMesh import BaseRectangularMesh +from .DiffOperators import DiffOperators +from .InnerProducts import InnerProducts +from .View import CurvView +from future.utils import with_metaclass # Some helper functions. length2D = lambda x: (x[:, 0]**2 + x[:, 1]**2)**0.5 length3D = lambda x: (x[:, 0]**2 + x[:, 1]**2 + x[:, 2]**2)**0.5 -normalize2D = lambda x: x/np.kron(np.ones((1, 2)), Utils.mkvc(length2D(x), 2)) -normalize3D = lambda x: x/np.kron(np.ones((1, 3)), Utils.mkvc(length3D(x), 2)) +normalize2D = lambda x: old_div(x,np.kron(np.ones((1, 2)), Utils.mkvc(length2D(x), 2))) +normalize3D = lambda x: old_div(x,np.kron(np.ones((1, 3)), Utils.mkvc(length3D(x), 2))) -class CurvilinearMesh(BaseRectangularMesh, DiffOperators, InnerProducts, CurvView): +class CurvilinearMesh(with_metaclass(Utils.SimPEGMetaClass, type('NewBase', (BaseRectangularMesh, DiffOperators, InnerProducts, CurvView), {}))): """ CurvilinearMesh is a mesh class that deals with curvilinear meshes. @@ -26,8 +35,6 @@ class CurvilinearMesh(BaseRectangularMesh, DiffOperators, InnerProducts, CurvVie M.plotGrid(showIt=True) """ - __metaclass__ = Utils.SimPEGMetaClass - _meshType = 'Curv' def __init__(self, nodes): @@ -220,7 +227,7 @@ class CurvilinearMesh(BaseRectangularMesh, DiffOperators, InnerProducts, CurvVie Utils.volTetra(self.gridN, C, H, D, A) + # cutted edge bottom Utils.volTetra(self.gridN, C, G, H, F)) # cutted edge bottom - self._vol = (vol1 + vol2)/2 + self._vol = old_div((vol1 + vol2),2) return self._vol return locals() _vol = None @@ -282,9 +289,9 @@ class CurvilinearMesh(BaseRectangularMesh, DiffOperators, InnerProducts, CurvVie if self.dim == 2: return normalize2D(np.r_[self._normals[0], self._normals[1]]) elif self.dim == 3: - normal1 = (self._normals[0][0] + self._normals[0][1] + self._normals[0][2] + self._normals[0][3])/4 - normal2 = (self._normals[1][0] + self._normals[1][1] + self._normals[1][2] + self._normals[1][3])/4 - normal3 = (self._normals[2][0] + self._normals[2][1] + self._normals[2][2] + self._normals[2][3])/4 + normal1 = old_div((self._normals[0][0] + self._normals[0][1] + self._normals[0][2] + self._normals[0][3]),4) + normal2 = old_div((self._normals[1][0] + self._normals[1][1] + self._normals[1][2] + self._normals[1][3]),4) + normal3 = old_div((self._normals[2][0] + self._normals[2][1] + self._normals[2][2] + self._normals[2][3]),4) return normalize3D(np.r_[normal1, normal2, normal3]) return locals() _normals = None @@ -302,7 +309,7 @@ class CurvilinearMesh(BaseRectangularMesh, DiffOperators, InnerProducts, CurvVie A, B = Utils.indexCube('AB', self.vnC+1, np.array([self.nNx, self.nCy])) edge2 = xy[B, :] - xy[A, :] self._edge = np.r_[Utils.mkvc(length2D(edge1)), Utils.mkvc(length2D(edge2))] - self._tangents = np.r_[edge1, edge2]/np.c_[self._edge, self._edge] + self._tangents = old_div(np.r_[edge1, edge2],np.c_[self._edge, self._edge]) elif(self.dim == 3): xyz = self.gridN A, D = Utils.indexCube('AD', self.vnC+1, np.array([self.nCx, self.nNy, self.nNz])) @@ -312,7 +319,7 @@ class CurvilinearMesh(BaseRectangularMesh, DiffOperators, InnerProducts, CurvVie A, E = Utils.indexCube('AE', self.vnC+1, np.array([self.nNx, self.nNy, self.nCz])) edge3 = xyz[E, :] - xyz[A, :] self._edge = np.r_[Utils.mkvc(length3D(edge1)), Utils.mkvc(length3D(edge2)), Utils.mkvc(length3D(edge3))] - self._tangents = np.r_[edge1, edge2, edge3]/np.c_[self._edge, self._edge, self._edge] + self._tangents = old_div(np.r_[edge1, edge2, edge3],np.c_[self._edge, self._edge, self._edge]) return self._edge return locals() _edge = None @@ -333,10 +340,10 @@ class CurvilinearMesh(BaseRectangularMesh, DiffOperators, InnerProducts, CurvVie if __name__ == '__main__': nc = 5 - h1 = np.cumsum(np.r_[0, np.ones(nc)/(nc)]) + h1 = np.cumsum(np.r_[0, old_div(np.ones(nc),(nc))]) nc = 7 - h2 = np.cumsum(np.r_[0, np.ones(nc)/(nc)]) - h3 = np.cumsum(np.r_[0, np.ones(nc)/(nc)]) + h2 = np.cumsum(np.r_[0, old_div(np.ones(nc),(nc))]) + h3 = np.cumsum(np.r_[0, old_div(np.ones(nc),(nc))]) dee3 = True if dee3: X, Y, Z = Utils.ndgrid(h1, h2, h3, vector=False) @@ -345,4 +352,4 @@ if __name__ == '__main__': X, Y = Utils.ndgrid(h1, h2, vector=False) M = CurvilinearMesh([X, Y]) - print M.r(M.normals, 'F', 'Fx', 'V') + print(M.r(M.normals, 'F', 'Fx', 'V')) diff --git a/SimPEG/Mesh/CylMesh.py b/SimPEG/Mesh/CylMesh.py index f1258184..a5b10c55 100644 --- a/SimPEG/Mesh/CylMesh.py +++ b/SimPEG/Mesh/CylMesh.py @@ -1,10 +1,17 @@ +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 past.utils import old_div import numpy as np import scipy.sparse as sp from scipy.constants import pi from SimPEG.Utils import mkvc, ndgrid, sdiag, kron3, speye, spzeros, ddx, av, avExtrap -from TensorMesh import BaseTensorMesh, BaseRectangularMesh -from InnerProducts import InnerProducts -from View import CylView +from .TensorMesh import BaseTensorMesh, BaseRectangularMesh +from .InnerProducts import InnerProducts +from .View import CylView class CylMesh(BaseTensorMesh, BaseRectangularMesh, InnerProducts, CylView): @@ -31,7 +38,7 @@ class CylMesh(BaseTensorMesh, BaseRectangularMesh, InnerProducts, CylView): BaseTensorMesh.__init__(self, h, x0) assert self.hy.sum() == 2*np.pi, "The 2nd dimension must sum to 2*pi" if self.dim == 2: - print 'Warning, a disk mesh has not been tested thoroughly.' + print('Warning, a disk mesh has not been tested thoroughly.') cartesianOrigin = np.zeros(self.dim) if cartesianOrigin is None else cartesianOrigin assert len(cartesianOrigin) == self.dim, "cartesianOrigin must be the same length as the dimension of the mesh." self.cartesianOrigin = np.array(cartesianOrigin, dtype=float) @@ -193,7 +200,7 @@ class CylMesh(BaseTensorMesh, BaseRectangularMesh, InnerProducts, CylView): D1 = kron3(speye(self.nCz), speye(self.nCy), ddx(self.nCx)[:,1:]) S = self.r(self.area, 'F', 'Fx', 'V') V = self.vol - self._faceDivx = sdiag(1/V)*D1*sdiag(S) + self._faceDivx = sdiag(old_div(1,V))*D1*sdiag(S) return self._faceDivx @property @@ -205,7 +212,7 @@ class CylMesh(BaseTensorMesh, BaseRectangularMesh, InnerProducts, CylView): D2 = kron3(speye(self.nCz), ddx(self.nCy), speye(self.nCx)) S = self.r(self.area, 'F', 'Fy', 'V') V = self.vol - self._faceDivy = sdiag(1/V)*D2*sdiag(S) + self._faceDivy = sdiag(old_div(1,V))*D2*sdiag(S) return self._faceDivy @property @@ -215,7 +222,7 @@ class CylMesh(BaseTensorMesh, BaseRectangularMesh, InnerProducts, CylView): D3 = kron3(ddx(self.nCz), speye(self.nCy), speye(self.nCx)) S = self.r(self.area, 'F', 'Fz', 'V') V = self.vol - self._faceDivz = sdiag(1/V)*D3*sdiag(S) + self._faceDivz = sdiag(old_div(1,V))*D3*sdiag(S) return self._faceDivz @@ -254,7 +261,7 @@ class CylMesh(BaseTensorMesh, BaseRectangularMesh, InnerProducts, CylView): A = self.area E = self.edge #Edge curl operator - self._edgeCurl = sdiag(1/A)*sp.vstack((Dz, Dr))*sdiag(E) + self._edgeCurl = sdiag(old_div(1,A))*sp.vstack((Dz, Dr))*sdiag(E) return self._edgeCurl # @property @@ -355,7 +362,7 @@ class CylMesh(BaseTensorMesh, BaseRectangularMesh, InnerProducts, CylView): grid = getattr(Mrect, 'grid' + locTypeTo) # This is unit circle stuff, 0 to 2*pi, starting at x-axis, rotating counter clockwise in an x-y slice - theta = - np.arctan2(grid[:,0] - self.cartesianOrigin[0], grid[:,1] - self.cartesianOrigin[1]) + np.pi/2 + theta = - np.arctan2(grid[:,0] - self.cartesianOrigin[0], grid[:,1] - self.cartesianOrigin[1]) + old_div(np.pi,2) theta[theta < 0] += np.pi*2.0 r = ((grid[:,0] - self.cartesianOrigin[0])**2 + (grid[:,1] - self.cartesianOrigin[1])**2)**0.5 diff --git a/SimPEG/Mesh/DiffOperators.py b/SimPEG/Mesh/DiffOperators.py index b4a4b1ba..d08bb718 100644 --- a/SimPEG/Mesh/DiffOperators.py +++ b/SimPEG/Mesh/DiffOperators.py @@ -1,3 +1,11 @@ +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 builtins import object +from past.utils import old_div import numpy as np from scipy import sparse as sp from SimPEG.Utils import mkvc, sdiag, speye, kron3, spzeros, ddx, av, avExtrap @@ -145,7 +153,7 @@ class DiffOperators(object): # Compute areas of cell faces & volumes S = self.area V = self.vol - self._faceDiv = sdiag(1/V)*D*sdiag(S) + self._faceDiv = sdiag(old_div(1,V))*D*sdiag(S) return self._faceDiv return locals() @@ -169,7 +177,7 @@ class DiffOperators(object): # Compute areas of cell faces & volumes S = self.r(self.area, 'F', 'Fx', 'V') V = self.vol - self._faceDivx = sdiag(1/V)*D1*sdiag(S) + self._faceDivx = sdiag(old_div(1,V))*D1*sdiag(S) return self._faceDivx return locals() @@ -192,7 +200,7 @@ class DiffOperators(object): # Compute areas of cell faces & volumes S = self.r(self.area, 'F', 'Fy', 'V') V = self.vol - self._faceDivy = sdiag(1/V)*D2*sdiag(S) + self._faceDivy = sdiag(old_div(1,V))*D2*sdiag(S) return self._faceDivy return locals() @@ -212,7 +220,7 @@ class DiffOperators(object): # Compute areas of cell faces & volumes S = self.r(self.area, 'F', 'Fz', 'V') V = self.vol - self._faceDivz = sdiag(1/V)*D3*sdiag(S) + self._faceDivz = sdiag(old_div(1,V))*D3*sdiag(S) return self._faceDivz return locals() @@ -240,7 +248,7 @@ class DiffOperators(object): G = sp.vstack((D1, D2, D3), format="csr") # Compute lengths of cell edges L = self.edge - self._nodalGrad = sdiag(1/L)*G + self._nodalGrad = sdiag(old_div(1,L))*G return self._nodalGrad return locals() _nodalGrad = None @@ -251,23 +259,23 @@ class DiffOperators(object): def fget(self): if(self._nodalLaplacian is None): - print 'Warning: Laplacian has not been tested rigorously.' + print('Warning: Laplacian has not been tested rigorously.') # The number of cell centers in each direction n = self.vnC # Compute divergence operator on faces if(self.dim == 1): - D1 = sdiag(1./self.hx) * ddx(mesh.nCx) + D1 = sdiag(old_div(1.,self.hx)) * ddx(mesh.nCx) L = - D1.T*D1 elif(self.dim == 2): - D1 = sdiag(1./self.hx) * ddx(n[0]) - D2 = sdiag(1./self.hy) * ddx(n[1]) + D1 = sdiag(old_div(1.,self.hx)) * ddx(n[0]) + D2 = sdiag(old_div(1.,self.hy)) * ddx(n[1]) L1 = sp.kron(speye(n[1]+1), - D1.T * D1) L2 = sp.kron(- D2.T * D2, speye(n[0]+1)) L = L1 + L2 elif(self.dim == 3): - D1 = sdiag(1./self.hx) * ddx(n[0]) - D2 = sdiag(1./self.hy) * ddx(n[1]) - D3 = sdiag(1./self.hz) * ddx(n[2]) + D1 = sdiag(old_div(1.,self.hx)) * ddx(n[0]) + D2 = sdiag(old_div(1.,self.hy)) * ddx(n[1]) + D3 = sdiag(old_div(1.,self.hz)) * ddx(n[2]) L1 = kron3(speye(n[2]+1), speye(n[1]+1), - D1.T * D1) L2 = kron3(speye(n[2]+1), - D2.T * D2, speye(n[0]+1)) L3 = kron3(- D3.T * D3, speye(n[1]+1), speye(n[0]+1)) @@ -332,7 +340,7 @@ class DiffOperators(object): # Compute areas of cell faces & volumes S = self.area V = self.aveCC2F*self.vol # Average volume between adjacent cells - self._cellGrad = sdiag(S/V)*G + self._cellGrad = sdiag(old_div(S,V))*G return self._cellGrad return locals() _cellGrad = None @@ -359,7 +367,7 @@ class DiffOperators(object): # Compute areas of cell faces & volumes S = self.area V = self.aveCC2F*self.vol # Average volume between adjacent cells - self._cellGradBC = sdiag(S/V)*G + self._cellGradBC = sdiag(old_div(S,V))*G return self._cellGradBC return locals() _cellGradBC = None @@ -385,7 +393,7 @@ class DiffOperators(object): G1 = self._cellGradxStencil() # Compute areas of cell faces & volumes V = self.aveCC2F*self.vol - L = self.r(self.area/V, 'F','Fx', 'V') + L = self.r(old_div(self.area,V), 'F','Fx', 'V') self._cellGradx = sdiag(L)*G1 return self._cellGradx return locals() @@ -409,7 +417,7 @@ class DiffOperators(object): G2 = self._cellGradyStencil() # Compute areas of cell faces & volumes V = self.aveCC2F*self.vol - L = self.r(self.area/V, 'F','Fy', 'V') + L = self.r(old_div(self.area,V), 'F','Fy', 'V') self._cellGrady = sdiag(L)*G2 return self._cellGrady return locals() @@ -430,7 +438,7 @@ class DiffOperators(object): G3 = self._cellGradzStencil() # Compute areas of cell faces & volumes V = self.aveCC2F*self.vol - L = self.r(self.area/V, 'F','Fz', 'V') + L = self.r(old_div(self.area,V), 'F','Fz', 'V') self._cellGradz = sdiag(L)*G3 return self._cellGradz return locals() @@ -457,7 +465,7 @@ class DiffOperators(object): D21 = sp.kron(ddx(n[1]), speye(n[0])) D12 = sp.kron(speye(n[1]), ddx(n[0])) C = sp.hstack((-D21, D12), format="csr") - self._edgeCurl = C*sdiag(1/S) + self._edgeCurl = C*sdiag(old_div(1,S)) elif self.dim == 3: @@ -476,7 +484,7 @@ class DiffOperators(object): sp.hstack((D31, O2, -D13)), sp.hstack((-D21, D12, O3))), format="csr") - self._edgeCurl = sdiag(1/S)*(C*sdiag(L)) + self._edgeCurl = sdiag(old_div(1,S))*(C*sdiag(L)) return self._edgeCurl return locals() @@ -655,7 +663,7 @@ class DiffOperators(object): elif(self.dim == 2): return (0.5)*sp.hstack((self.aveFx2CC, self.aveFy2CC), format="csr") elif(self.dim == 3): - return (1./3.)*sp.hstack((self.aveFx2CC, self.aveFy2CC, self.aveFz2CC), format="csr") + return (old_div(1.,3.))*sp.hstack((self.aveFx2CC, self.aveFy2CC, self.aveFz2CC), format="csr") @property def aveF2CCV(self): @@ -727,7 +735,7 @@ class DiffOperators(object): elif(self.dim == 2): return 0.5*sp.hstack((self.aveEx2CC, self.aveEy2CC), format="csr") elif(self.dim == 3): - return (1./3)*sp.hstack((self.aveEx2CC, self.aveEy2CC, self.aveEz2CC), format="csr") + return (old_div(1.,3))*sp.hstack((self.aveEx2CC, self.aveEy2CC, self.aveEz2CC), format="csr") @property def aveE2CCV(self): diff --git a/SimPEG/Mesh/InnerProducts.py b/SimPEG/Mesh/InnerProducts.py index 0c08cdd3..e2e0f9a3 100644 --- a/SimPEG/Mesh/InnerProducts.py +++ b/SimPEG/Mesh/InnerProducts.py @@ -1,3 +1,11 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() +from builtins import range +from builtins import object from scipy import sparse as sp from SimPEG.Utils import * import numpy as np @@ -186,7 +194,7 @@ class InnerProducts(object): if tensorType == 0: dMdm = spzeros(n, 1) for i, p in enumerate(P): - dMdm = dMdm + sp.csr_matrix((p.T * (p * v), (range(n), np.zeros(n))), shape=(n,1)) + dMdm = dMdm + sp.csr_matrix((p.T * (p * v), (list(range(n)), np.zeros(n))), shape=(n,1)) if d == 1: if tensorType == 1: dMdm = spzeros(n, self.nC) @@ -288,7 +296,7 @@ class InnerProducts(object): """ posFx = 0 if xFace == 'fXm' else 1 IND = ii + posFx - PX = sp.csr_matrix((np.ones(M.nC), (range(M.nC), IND)), shape=(M.nC, M.nF)) + PX = sp.csr_matrix((np.ones(M.nC), (list(range(M.nC)), IND)), shape=(M.nC, M.nF)) return PX return Px @@ -350,7 +358,7 @@ class InnerProducts(object): IND = np.r_[ind1, ind2].flatten() - PXX = sp.csr_matrix((np.ones(2*M.nC), (range(2*M.nC), IND)), shape=(2*M.nC, M.nF)) + PXX = sp.csr_matrix((np.ones(2*M.nC), (list(range(2*M.nC)), IND)), shape=(2*M.nC, M.nF)) if M._meshType == 'Curv': I2x2 = inv2X2BlockDiagonal(getSubArray(fN1[0], [i + posFx, j]), getSubArray(fN1[1], [i + posFx, j]), @@ -407,7 +415,7 @@ class InnerProducts(object): IND = np.r_[ind1, ind2, ind3].flatten() - PXXX = sp.coo_matrix((np.ones(3*M.nC), (range(3*M.nC), IND)), shape=(3*M.nC, M.nF)).tocsr() + PXXX = sp.coo_matrix((np.ones(3*M.nC), (list(range(3*M.nC)), IND)), shape=(3*M.nC, M.nF)).tocsr() if M._meshType == 'Curv': I3x3 = inv3X3BlockDiagonal(getSubArray(fN1[0], [i + posX, j, k]), getSubArray(fN1[1], [i + posX, j, k]), getSubArray(fN1[2], [i + posX, j, k]), @@ -449,7 +457,7 @@ class InnerProducts(object): IND = np.r_[ind1, ind2].flatten() - PXX = sp.coo_matrix((np.ones(2*M.nC), (range(2*M.nC), IND)), shape=(2*M.nC, M.nE)).tocsr() + PXX = sp.coo_matrix((np.ones(2*M.nC), (list(range(2*M.nC)), IND)), shape=(2*M.nC, M.nE)).tocsr() if M._meshType == 'Curv': I2x2 = inv2X2BlockDiagonal(getSubArray(eT1[0], [i, j + posX]), getSubArray(eT1[1], [i, j + posX]), @@ -492,7 +500,7 @@ class InnerProducts(object): IND = np.r_[ind1, ind2, ind3].flatten() - PXXX = sp.coo_matrix((np.ones(3*M.nC), (range(3*M.nC), IND)), shape=(3*M.nC, M.nE)).tocsr() + PXXX = sp.coo_matrix((np.ones(3*M.nC), (list(range(3*M.nC)), IND)), shape=(3*M.nC, M.nE)).tocsr() if M._meshType == 'Curv': I3x3 = inv3X3BlockDiagonal(getSubArray(eT1[0], [i, j + posX[0], k + posX[1]]), getSubArray(eT1[1], [i, j + posX[0], k + posX[1]]), getSubArray(eT1[2], [i, j + posX[0], k + posX[1]]), diff --git a/SimPEG/Mesh/MeshIO.py b/SimPEG/Mesh/MeshIO.py index 0810f973..2b8fa518 100644 --- a/SimPEG/Mesh/MeshIO.py +++ b/SimPEG/Mesh/MeshIO.py @@ -1,3 +1,15 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import open +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import zip +from builtins import map +from builtins import object import numpy as np, os from SimPEG import Utils @@ -128,13 +140,13 @@ class TensorMeshIO(object): # Assign the model('s) to the object if models is not None: - for item in models.iteritems(): + for item in models.items(): # Convert numpy array vtkDoubleArr = numpy_to_vtk(item[1],deep=1) vtkDoubleArr.SetName(item[0]) vtkObj.GetCellData().AddArray(vtkDoubleArr) # Set the active scalar - vtkObj.GetCellData().SetActiveScalars(models.keys()[0]) + vtkObj.GetCellData().SetActiveScalars(list(models.keys())[0]) # vtkObj.Update() # Check the extension of the fileName @@ -162,7 +174,7 @@ class TensorMeshIO(object): :return: model with TensorMesh ordered """ f = open(fileName, 'r') - model = np.array(map(float, f.readlines())) + model = np.array(list(map(float, f.readlines()))) f.close() model = np.reshape(model, (mesh.nCz, mesh.nCx, mesh.nCy), order = 'F') model = model[::-1,:,:] @@ -265,7 +277,7 @@ class TreeMeshIO(object): # Assign the model('s) to the object if models is not None: # indUBCvector = np.argsort(cX0[np.argsort(np.concatenate((cX0[:,0:2],cX0[:,2:3].max() - cX0[:,2:3]),axis=1).view(','.join(3*['float'])),axis=0,order=('f2','f1','f0'))[:,0]].view(','.join(3*['float'])),axis=0,order=('f2','f1','f0'))[:,0] - for item in models.iteritems(): + for item in models.items(): # Save the data np.savetxt(item[0],item[1][ubcReorder],fmt='%3.5e') @@ -384,7 +396,7 @@ class TreeMeshIO(object): vtuObj.GetCellData().AddArray(refineLevelArr) # Assign the model('s) to the object if models is not None: - for item in models.iteritems(): + for item in models.items(): # Convert numpy array vtkDoubleArr = numpy_to_vtk(item[1],deep=1) vtkDoubleArr.SetName(item[0]) diff --git a/SimPEG/Mesh/TensorMesh.py b/SimPEG/Mesh/TensorMesh.py index 65b6d7e9..5f79575e 100644 --- a/SimPEG/Mesh/TensorMesh.py +++ b/SimPEG/Mesh/TensorMesh.py @@ -1,13 +1,22 @@ +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import unicode_literals +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import range +from past.utils import old_div from SimPEG import Utils, np, sp -from BaseMesh import BaseMesh, BaseRectangularMesh -from View import TensorView -from DiffOperators import DiffOperators -from InnerProducts import InnerProducts -from MeshIO import TensorMeshIO +from .BaseMesh import BaseMesh, BaseRectangularMesh +from .View import TensorView +from .DiffOperators import DiffOperators +from .InnerProducts import InnerProducts +from .MeshIO import TensorMeshIO +from future.utils import with_metaclass -class BaseTensorMesh(BaseMesh): - - __metaclass__ = Utils.SimPEGMetaClass +class BaseTensorMesh(with_metaclass(Utils.SimPEGMetaClass, BaseMesh)): _meshType = 'BASETENSOR' @@ -16,7 +25,7 @@ class BaseTensorMesh(BaseMesh): def __init__(self, h_in, x0_in=None): assert type(h_in) in [list, tuple], 'h_in must be a list' assert len(h_in) in [1,2,3], 'h_in must be of dimension 1, 2, or 3' - h = range(len(h_in)) + h = list(range(len(h_in))) for i, h_i in enumerate(h_in): if Utils.isScalar(h_i) and type(h_i) is not np.ndarray: # This gives you something over the unit cube. @@ -298,7 +307,7 @@ class BaseTensorMesh(BaseMesh): prop = np.ones(self.nC) if invProp: - prop = 1./prop + prop = old_div(1.,prop) if Utils.isScalar(prop): prop = prop*np.ones(self.nC) @@ -339,11 +348,11 @@ class BaseTensorMesh(BaseMesh): if tensorType == 0: Av = getattr(self, 'ave'+projType+'2CC') V = Utils.sdiag(self.vol) - ones = sp.csr_matrix((np.ones(self.nC), (range(self.nC), np.zeros(self.nC))), shape=(self.nC,1)) + ones = sp.csr_matrix((np.ones(self.nC), (list(range(self.nC)), np.zeros(self.nC))), shape=(self.nC,1)) if not invMat and not invProp: dMdprop = self.dim * Av.T * V * ones elif invMat and invProp: - dMdprop = self.dim * Utils.sdiag(MI.diagonal()**2) * Av.T * V * ones * Utils.sdiag(1./prop**2) + dMdprop = self.dim * Utils.sdiag(MI.diagonal()**2) * Av.T * V * ones * Utils.sdiag(old_div(1.,prop**2)) if tensorType == 1: Av = getattr(self, 'ave'+projType+'2CC') @@ -351,7 +360,7 @@ class BaseTensorMesh(BaseMesh): if not invMat and not invProp: dMdprop = self.dim * Av.T * V elif invMat and invProp: - dMdprop = self.dim * Utils.sdiag(MI.diagonal()**2) * Av.T * V * Utils.sdiag(1./prop**2) + dMdprop = self.dim * Utils.sdiag(MI.diagonal()**2) * Av.T * V * Utils.sdiag(old_div(1.,prop**2)) if tensorType == 2: # anisotropic Av = getattr(self, 'ave'+projType+'2CCV') @@ -359,12 +368,12 @@ class BaseTensorMesh(BaseMesh): if not invMat and not invProp: dMdprop = Av.T * V elif invMat and invProp: - dMdprop = Utils.sdiag(MI.diagonal()**2) * Av.T * V * Utils.sdiag(1./prop**2) + dMdprop = Utils.sdiag(MI.diagonal()**2) * Av.T * V * Utils.sdiag(old_div(1.,prop**2)) if dMdprop is not None: def innerProductDeriv(v=None): if v is None: - print 'Depreciation Warning: TensorMesh.innerProductDeriv. You should be supplying a vector. Use: sdiag(u)*dMdprop' + print('Depreciation Warning: TensorMesh.innerProductDeriv. You should be supplying a vector. Use: sdiag(u)*dMdprop') return dMdprop return Utils.sdiag(v) * dMdprop return innerProductDeriv @@ -373,7 +382,7 @@ class BaseTensorMesh(BaseMesh): -class TensorMesh(BaseTensorMesh, BaseRectangularMesh, TensorView, DiffOperators, InnerProducts, TensorMeshIO): +class TensorMesh(with_metaclass(Utils.SimPEGMetaClass, type('NewBase', (BaseTensorMesh, BaseRectangularMesh, TensorView, DiffOperators, InnerProducts, TensorMeshIO), {}))): """ TensorMesh is a mesh class that deals with tensor product meshes. @@ -403,8 +412,6 @@ class TensorMesh(BaseTensorMesh, BaseRectangularMesh, TensorView, DiffOperators, """ - __metaclass__ = Utils.SimPEGMetaClass - _meshType = 'TENSOR' def __init__(self, h_in, x0=None): diff --git a/SimPEG/Mesh/TreeMesh.py b/SimPEG/Mesh/TreeMesh.py index d994e3a5..829b78a0 100644 --- a/SimPEG/Mesh/TreeMesh.py +++ b/SimPEG/Mesh/TreeMesh.py @@ -1,3 +1,16 @@ +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import unicode_literals +from builtins import int +from builtins import dict +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import zip +from builtins import range +from builtins import object +from past.utils import old_div # ___ ___ ___ ___ ___ # /\ \ ___ /\__\ /\ \ /\ \ /\ \ # /::\ \ /\ \ /::| | /::\ \ /::\ \ /::\ \ @@ -92,15 +105,15 @@ from SimPEG import np, sp, Utils, Solver try: - import TreeUtils + from . import TreeUtils _IMPORT_TREEUTILS = True -except Exception, e: +except Exception as e: _IMPORT_TREEUTILS = False -from InnerProducts import InnerProducts -from TensorMesh import TensorMesh, BaseTensorMesh -from MeshIO import TreeMeshIO +from .InnerProducts import InnerProducts +from .TensorMesh import TensorMesh, BaseTensorMesh +from .MeshIO import TreeMeshIO import time MAX_BITS = 20 @@ -165,7 +178,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): @property def fill(self): """How filled is the mesh compared to a TensorMesh? As a fraction: [0,1].""" - return float(self.nC)/((2**self.maxLevel)**self.dim) + return old_div(float(self.nC),((2**self.maxLevel)**self.dim)) @property def maxLevel(self): @@ -408,7 +421,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): return TreeUtils.index(self.dim, MAX_BITS, self._levelBits, pointer[:-1], pointer[-1]) def _pointer(self, index): - assert type(index) in [int, long] + assert type(index) in [int, int] return TreeUtils.point(self.dim, MAX_BITS, self._levelBits, index) def __contains__(self, v): @@ -416,13 +429,13 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): def refine(self, function=None, recursive=True, cells=None, balance=True, verbose=False, _inRecursion=False): - if type(function) in [int, long]: + if type(function) in [int, int]: level = function function = lambda cell: level if not _inRecursion: self.__dirty__ = True - if verbose: print 'Refining Mesh' + if verbose: print('Refining Mesh') cells = cells if cells is not None else sorted(self._cells) recurse = [] @@ -433,14 +446,14 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): result = function(Cell(self, cell, p)) if type(result) is bool: do = result - elif type(result) in [int,long]: + elif type(result) in [int,int]: do = result > p[-1] else: raise Exception('You must tell the program what to refine. Use BOOL or INT (level)') if do: recurse += self._refineCell(cell, p) - if verbose: print ' ', time.time() - tic + if verbose: print(' ', time.time() - tic) if recursive and len(recurse) > 0: recurse += self.refine(function=function, recursive=True, cells=recurse, balance=balance, verbose=verbose, _inRecursion=True) @@ -451,13 +464,13 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): def corsen(self, function=None, recursive=True, cells=None, balance=True, verbose=False, _inRecursion=False): - if type(function) in [int, long]: + if type(function) in [int, int]: level = function function = lambda cell: level if not _inRecursion: self.__dirty__ = True - if verbose: print 'Corsening Mesh' + if verbose: print('Corsening Mesh') cells = cells if cells is not None else sorted(self._cells) recurse = [] @@ -469,14 +482,14 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): result = function(Cell(self, cell, p)) if type(result) is bool: do = result - elif type(result) in [int,long]: + elif type(result) in [int,int]: do = result < p[-1] else: raise Exception('You must tell the program what to corsen. Use BOOL or INT (level)') if do: recurse += self._corsenCell(cell, p) - if verbose: print ' ', time.time() - tic + if verbose: print(' ', time.time() - tic) if recursive and len(recurse) > 0: recurse += self.corsen(function=function, recursive=True, cells=recurse, balance=balance, verbose=verbose, _inRecursion=True) @@ -510,7 +523,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): return [parentInd] def _asPointer(self, ind): - if type(ind) in [int, long]: + if type(ind) in [int, int]: return self._pointer(ind) if type(ind) is list: assert len(ind) == (self.dim + 1), str(ind) +' is not valid pointer' @@ -521,7 +534,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): raise Exception def _asIndex(self, pointer): - if type(pointer) in [int, long]: + if type(pointer) in [int, int]: return pointer if type(pointer) is list: return self._index(pointer) @@ -577,7 +590,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): def _cellC(self, p): """Cell center of a single cell (without origin correction), given a pointer.""" - return (np.array(self._cellH(p))/2.0 + self._cellN(p)).tolist() + return (old_div(np.array(self._cellH(p)),2.0) + self._cellN(p)).tolist() def _levelWidth(self, level): return 2**(self.levels - level) @@ -623,7 +636,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): tic = time.time() if not _inRecursion: self.__dirty__ = True - if verbose: print 'Balancing Mesh:' + if verbose: print('Balancing Mesh:') cells = cells if cells is not None else sorted(self._cells) @@ -636,7 +649,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): p = self._asPointer(cell) if p[-1] == self.levels: continue - cs = range(6) + cs = list(range(6)) cs[0] = self._getNextCell(cell, direction=0, positive=False) cs[1] = self._getNextCell(cell, direction=0, positive=True) cs[2] = self._getNextCell(cell, direction=1, positive=False) @@ -655,10 +668,10 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): if do and cell in self: newCells = self._refineCell(cell) - recurse.update([_ for _ in cs if type(_) in [int, long]]) # only add the bigger ones! + recurse.update([_ for _ in cs if type(_) in [int, int]]) # only add the bigger ones! recurse.update(newCells) - if verbose: print ' ', len(cells), time.time() - tic + if verbose: print(' ', len(cells), time.time() - tic) if recursive and len(recurse) > 0: self.balance(cells=sorted(recurse), _inRecursion=True) @@ -865,10 +878,10 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): p = self._pointer(fx) n, h = self._cellN(p), self._cellH(p) if self.dim == 2: - gridFx.append( [n[0], n[1] + h[1]/2.0] ) + gridFx.append( [n[0], n[1] + old_div(h[1],2.0)] ) areaFx.append( h[1] ) elif self.dim == 3: - gridFx.append( [n[0], n[1] + h[1]/2.0, n[2] + h[2]/2.0] ) + gridFx.append( [n[0], n[1] + old_div(h[1],2.0), n[2] + old_div(h[2],2.0)] ) areaFx.append( h[1]*h[2] ) self._gridFx = np.array(gridFx) self._areaFxFull = np.array(areaFx) @@ -881,10 +894,10 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): p = self._pointer(fy) n, h = self._cellN(p), self._cellH(p) if self.dim == 2: - gridFy.append( [n[0] + h[0]/2.0, n[1]] ) + gridFy.append( [n[0] + old_div(h[0],2.0), n[1]] ) areaFy.append( h[0] ) elif self.dim == 3: - gridFy.append( [n[0] + h[0]/2.0, n[1], n[2] + h[2]/2.0] ) + gridFy.append( [n[0] + old_div(h[0],2.0), n[1], n[2] + old_div(h[2],2.0)] ) areaFy.append( h[0]*h[2] ) self._gridFy = np.array(gridFy) self._areaFyFull = np.array(areaFy) @@ -900,7 +913,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): self._fz2i[fz] = ii p = self._pointer(fz) n, h = self._cellN(p), self._cellH(p) - gridFz.append( [n[0] + h[0]/2.0, n[1] + h[1]/2.0, n[2]] ) + gridFz.append( [n[0] + old_div(h[0],2.0), n[1] + old_div(h[1],2.0), n[2]] ) areaFz.append(h[0]*h[1]) self._gridFz = np.array(gridFz) self._areaFzFull = np.array(areaFz) @@ -921,7 +934,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): self._ex2i[ex] = ii p = self._pointer(ex) n, h = self._cellN(p), self._cellH(p) - gridEx.append( [n[0] + h[0]/2.0, n[1], n[2]] ) + gridEx.append( [n[0] + old_div(h[0],2.0), n[1], n[2]] ) edgeEx.append( h[0] ) self._gridEx = np.array(gridEx) self._edgeExFull = np.array(edgeEx) @@ -933,7 +946,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): self._ey2i[ey] = ii p = self._pointer(ey) n, h = self._cellN(p), self._cellH(p) - gridEy.append( [n[0], n[1] + h[1]/2.0, n[2]] ) + gridEy.append( [n[0], n[1] + old_div(h[1],2.0), n[2]] ) edgeEy.append( h[1] ) self._gridEy = np.array(gridEy) self._edgeEyFull = np.array(edgeEy) @@ -945,7 +958,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): self._ez2i[ez] = ii p = self._pointer(ez) n, h = self._cellN(p), self._cellH(p) - gridEz.append( [n[0], n[1], n[2] + h[2]/2.0] ) + gridEz.append( [n[0], n[1], n[2] + old_div(h[2],2.0)] ) edgeEz.append( h[2] ) self._gridEz = np.array(gridEz) self._edgeEzFull = np.array(edgeEz) @@ -985,12 +998,12 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): chy1 = self._cellH([p[0] , p[1] + w, sl])[1] A = (chy0 + chy1) - self._hangingFx[self._fx2i[test ]] = ([self._fx2i[fx], chy0 / A], ) - self._hangingFx[self._fx2i[self._index([p[0] , p[1] + w, sl])]] = ([self._fx2i[fx], chy1 / A], ) + self._hangingFx[self._fx2i[test ]] = ([self._fx2i[fx], old_div(chy0, A)], ) + self._hangingFx[self._fx2i[self._index([p[0] , p[1] + w, sl])]] = ([self._fx2i[fx], old_div(chy1, A)], ) n0, n1 = fx, self._index([p[0], p[1] + 2*w, p[-1]]) self._hangingN[self._n2i[test ]] = ([self._n2i[n0], 1.0], ) - self._hangingN[self._n2i[self._index([p[0] , p[1] + w, sl])]] = ([self._n2i[n0], 1.0 - chy0 / A], [self._n2i[n1], 1.0 - chy1 / A]) + self._hangingN[self._n2i[self._index([p[0] , p[1] + w, sl])]] = ([self._n2i[n0], 1.0 - old_div(chy0, A)], [self._n2i[n1], 1.0 - old_div(chy1, A)]) self._hangingN[self._n2i[self._index([p[0] , p[1] + 2*w, sl])]] = ([self._n2i[n1], 1.0], ) elif self.dim == 3: @@ -1081,8 +1094,8 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): chx0 = self._cellH([p[0] , p[1] , sl])[0] chx1 = self._cellH([p[0] + w, p[1] , sl])[0] - self._hangingFy[self._fy2i[test ]] = ([self._fy2i[fy], chx0 / (chx0 + chx1)], ) - self._hangingFy[self._fy2i[self._index([p[0] + w, p[1] , sl])]] = ([self._fy2i[fy], chx1 / (chx0 + chx1)], ) + self._hangingFy[self._fy2i[test ]] = ([self._fy2i[fy], old_div(chx0, (chx0 + chx1))], ) + self._hangingFy[self._fy2i[self._index([p[0] + w, p[1] , sl])]] = ([self._fy2i[fy], old_div(chx1, (chx0 + chx1))], ) n0, n1 = fy, self._index([p[0] + 2*w, p[1], p[-1]]) self._hangingN[self._n2i[test ]] = ([self._n2i[n0], 1.0], ) @@ -1287,7 +1300,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): V += [1.0] ii += 1 if withHanging: - for hfkey in theHang.keys(): + for hfkey in list(theHang.keys()): hf = theHang[hfkey] I += [hfkey]*len(hf) J += [reducedInd[_[0]] for _ in hf] @@ -1343,7 +1356,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): S = np.r_[self._areaFxFull, self._areaFyFull] elif self.dim == 3: S = np.r_[self._areaFxFull, self._areaFyFull, self._areaFzFull] - self._faceDiv = Utils.sdiag(1.0/VOL)*D*Utils.sdiag(S)*R + self._faceDiv = Utils.sdiag(old_div(1.0,VOL))*D*Utils.sdiag(S)*R return self._faceDiv @property @@ -1418,12 +1431,12 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): Rf = self._deflationMatrix('F', withHanging=True, asOnes=False) Re = self._deflationMatrix('E') - Rf_ave = Utils.sdiag(1./Rf.sum(axis=0)) * Rf.T + Rf_ave = Utils.sdiag(old_div(1.,Rf.sum(axis=0))) * Rf.T C = sp.csr_matrix((V,(I,J)), shape=(self.ntF, self.ntE)) S = np.r_[self._areaFxFull, self._areaFyFull, self._areaFzFull] L = np.r_[self._edgeExFull, self._edgeEyFull, self._edgeEzFull] - self._edgeCurl = Rf_ave*Utils.sdiag(1.0/S)*C*Utils.sdiag(L)*Re + self._edgeCurl = Rf_ave*Utils.sdiag(old_div(1.0,S))*C*Utils.sdiag(L)*Re return self._edgeCurl @property @@ -1482,9 +1495,9 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): Rn = self._deflationMatrix('N') Re = self._deflationMatrix('E', withHanging=True, asOnes=False) - Re_ave = Utils.sdiag(1./Re.sum(axis=0)) * Re.T + Re_ave = Utils.sdiag(old_div(1.,Re.sum(axis=0))) * Re.T - self._nodalGrad = Re_ave*Utils.sdiag(1/L)*G*Rn + self._nodalGrad = Re_ave*Utils.sdiag(old_div(1,L))*G*Rn return self._nodalGrad @property @@ -1496,7 +1509,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): raise Exception('aveEx2CC not implemented in 2D') if self.dim == 3: - PM = [1./4.]*4 + PM = [old_div(1.,4.)]*4 for ii, ind in enumerate(self._sortedCells): p = self._pointer(ind) @@ -1530,7 +1543,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): raise NotImplementedError('aveEy2CC not implemented in 2D') if self.dim == 3: - PM = [1./4.]*4 # plus / plus + PM = [old_div(1.,4.)]*4 # plus / plus for ii, ind in enumerate(self._sortedCells): p = self._pointer(ind) @@ -1565,7 +1578,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): raise Exception('There are no z edges in 2D') if self.dim == 3: - PM = [1./4.]*4 # plus / plus + PM = [old_div(1.,4.)]*4 # plus / plus for ii, ind in enumerate(self._sortedCells): p = self._pointer(ind) @@ -1616,7 +1629,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): def aveFx2CC(self): if getattr(self, '_aveFx2CC', None) is None: I, J, V = [], [], [] - PM = [1./2.]*self.dim # 0.5, 0.5 + PM = [old_div(1.,2.)]*self.dim # 0.5, 0.5 for ii, ind in enumerate(self._sortedCells): p = self._pointer(ind) @@ -1649,7 +1662,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): def aveFy2CC(self): if getattr(self, '_aveFy2CC', None) is None: I, J, V = [], [], [] - PM = [1./2.]*2 # 0.5, 0.5 + PM = [old_div(1.,2.)]*2 # 0.5, 0.5 for ii, ind in enumerate(self._sortedCells): p = self._pointer(ind) @@ -1681,7 +1694,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): def aveFz2CC(self): if getattr(self, '_aveFz2CC', None) is None: I, J, V = [], [], [] - PM = [1./2.]*2 # 0.5, 0.5 + PM = [old_div(1.,2.)]*2 # 0.5, 0.5 for ii, ind in enumerate(self._sortedCells): p = self._pointer(ind) @@ -1729,7 +1742,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): def aveN2CC(self): if getattr(self, '_aveN2CC', None) is None: I, J, V = [], [], [] - PM = [1./2.**self.dim] * 2**self.dim + PM = [old_div(1.,2.**self.dim)] * 2**self.dim for ii, ind in enumerate(self._sortedCells): p = self._pointer(ind) @@ -1788,7 +1801,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): if self.dim == 3: IND = np.r_[ind1, ind2, ind3] - PXXX = sp.coo_matrix((np.ones(self.dim*self.nC), (range(self.dim*self.nC), IND)), shape=(self.dim*self.nC, self.ntF)).tocsr() + PXXX = sp.coo_matrix((np.ones(self.dim*self.nC), (list(range(self.dim*self.nC)), IND)), shape=(self.dim*self.nC, self.ntF)).tocsr() Rf = self._deflationMatrix('F', withHanging=True, asOnes=True) @@ -1824,7 +1837,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): IND = np.r_[ind1, ind2, ind3] - PXXX = sp.coo_matrix((np.ones(self.dim*self.nC), (range(self.dim*self.nC), IND)), shape=(self.dim*self.nC, self.ntE)).tocsr() + PXXX = sp.coo_matrix((np.ones(self.dim*self.nC), (list(range(self.dim*self.nC)), IND)), shape=(self.dim*self.nC, self.ntE)).tocsr() Re = self._deflationMatrix('E') @@ -1847,7 +1860,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): Ny = self.vectorNy Nz = self.vectorNz - pointers = range(self.dim) + pointers = list(range(self.dim)) Nx = np.r_[Nx[0] - TOL, Nx[1:-1], Nx[-1] + TOL] pointers[0] = np.searchsorted(Nx, locs[:,0]) Ny = np.r_[Ny[0] - TOL, Ny[1:-1], Ny[-1] + TOL] @@ -2022,13 +2035,13 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): ax.plot(self.gridCC[[0,-1],0], self.gridCC[[0,-1],1], 'ro') if nodes: ax.plot(self._gridN[:,0], self._gridN[:,1], 'ms') - ax.plot(self._gridN[self._hangingN.keys(),0], self._gridN[self._hangingN.keys(),1], 'ms', ms=10, mfc='none', mec='m') + ax.plot(self._gridN[list(self._hangingN.keys()),0], self._gridN[list(self._hangingN.keys()),1], 'ms', ms=10, mfc='none', mec='m') if facesX: ax.plot(self._gridFx[:,0], self._gridFx[:,1], 'g>') - ax.plot(self._gridFx[self._hangingFx.keys(),0], self._gridFx[self._hangingFx.keys(),1], 'gs', ms=10, mfc='none', mec='g') + ax.plot(self._gridFx[list(self._hangingFx.keys()),0], self._gridFx[list(self._hangingFx.keys()),1], 'gs', ms=10, mfc='none', mec='g') if facesY: ax.plot(self._gridFy[:,0], self._gridFy[:,1], 'g^') - ax.plot(self._gridFy[self._hangingFy.keys(),0], self._gridFy[self._hangingFy.keys(),1], 'gs', ms=10, mfc='none', mec='g') + ax.plot(self._gridFy[list(self._hangingFy.keys()),0], self._gridFy[list(self._hangingFy.keys()),1], 'gs', ms=10, mfc='none', mec='g') ax.set_xlabel('x1') ax.set_ylabel('x2') elif self.dim == 3: @@ -2040,56 +2053,56 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): if nodes: ax.plot(self._gridN[:,0], self._gridN[:,1], 'ms', zs=self._gridN[:,2]) - ax.plot(self._gridN[self._hangingN.keys(),0], self._gridN[self._hangingN.keys(),1], 'ms', ms=10, mfc='none', mec='m', zs=self._gridN[self._hangingN.keys(),2]) - for key in self._hangingN.keys(): + ax.plot(self._gridN[list(self._hangingN.keys()),0], self._gridN[list(self._hangingN.keys()),1], 'ms', ms=10, mfc='none', mec='m', zs=self._gridN[list(self._hangingN.keys()),2]) + for key in list(self._hangingN.keys()): for hf in self._hangingN[key]: ind = [key, hf[0]] ax.plot(self._gridN[ind,0], self._gridN[ind,1], 'm:', zs=self._gridN[ind,2]) if facesX: ax.plot(self._gridFx[:,0], self._gridFx[:,1], 'g>', zs=self._gridFx[:,2]) - ax.plot(self._gridFx[self._hangingFx.keys(),0], self._gridFx[self._hangingFx.keys(),1], 'gs', ms=10, mfc='none', mec='g', zs=self._gridFx[self._hangingFx.keys(),2]) - for key in self._hangingFx.keys(): + ax.plot(self._gridFx[list(self._hangingFx.keys()),0], self._gridFx[list(self._hangingFx.keys()),1], 'gs', ms=10, mfc='none', mec='g', zs=self._gridFx[list(self._hangingFx.keys()),2]) + for key in list(self._hangingFx.keys()): for hf in self._hangingFx[key]: ind = [key, hf[0]] ax.plot(self._gridFx[ind,0], self._gridFx[ind,1], 'g:', zs=self._gridFx[ind,2]) if facesY: ax.plot(self._gridFy[:,0], self._gridFy[:,1], 'g^', zs=self._gridFy[:,2]) - ax.plot(self._gridFy[self._hangingFy.keys(),0], self._gridFy[self._hangingFy.keys(),1], 'gs', ms=10, mfc='none', mec='g', zs=self._gridFy[self._hangingFy.keys(),2]) - for key in self._hangingFy.keys(): + ax.plot(self._gridFy[list(self._hangingFy.keys()),0], self._gridFy[list(self._hangingFy.keys()),1], 'gs', ms=10, mfc='none', mec='g', zs=self._gridFy[list(self._hangingFy.keys()),2]) + for key in list(self._hangingFy.keys()): for hf in self._hangingFy[key]: ind = [key, hf[0]] ax.plot(self._gridFy[ind,0], self._gridFy[ind,1], 'g:', zs=self._gridFy[ind,2]) if facesZ: ax.plot(self._gridFz[:,0], self._gridFz[:,1], 'g^', zs=self._gridFz[:,2]) - ax.plot(self._gridFz[self._hangingFz.keys(),0], self._gridFz[self._hangingFz.keys(),1], 'gs', ms=10, mfc='none', mec='g', zs=self._gridFz[self._hangingFz.keys(),2]) - for key in self._hangingFz.keys(): + ax.plot(self._gridFz[list(self._hangingFz.keys()),0], self._gridFz[list(self._hangingFz.keys()),1], 'gs', ms=10, mfc='none', mec='g', zs=self._gridFz[list(self._hangingFz.keys()),2]) + for key in list(self._hangingFz.keys()): for hf in self._hangingFz[key]: ind = [key, hf[0]] ax.plot(self._gridFz[ind,0], self._gridFz[ind,1], 'g:', zs=self._gridFz[ind,2]) if edgesX: ax.plot(self._gridEx[:,0], self._gridEx[:,1], 'k>', zs=self._gridEx[:,2]) - ax.plot(self._gridEx[self._hangingEx.keys(),0], self._gridEx[self._hangingEx.keys(),1], 'ks', ms=10, mfc='none', mec='k', zs=self._gridEx[self._hangingEx.keys(),2]) - for key in self._hangingEx.keys(): + ax.plot(self._gridEx[list(self._hangingEx.keys()),0], self._gridEx[list(self._hangingEx.keys()),1], 'ks', ms=10, mfc='none', mec='k', zs=self._gridEx[list(self._hangingEx.keys()),2]) + for key in list(self._hangingEx.keys()): for hf in self._hangingEx[key]: ind = [key, hf[0]] ax.plot(self._gridEx[ind,0], self._gridEx[ind,1], 'k:', zs=self._gridEx[ind,2]) if edgesY: ax.plot(self._gridEy[:,0], self._gridEy[:,1], 'k<', zs=self._gridEy[:,2]) - ax.plot(self._gridEy[self._hangingEy.keys(),0], self._gridEy[self._hangingEy.keys(),1], 'ks', ms=10, mfc='none', mec='k', zs=self._gridEy[self._hangingEy.keys(),2]) - for key in self._hangingEy.keys(): + ax.plot(self._gridEy[list(self._hangingEy.keys()),0], self._gridEy[list(self._hangingEy.keys()),1], 'ks', ms=10, mfc='none', mec='k', zs=self._gridEy[list(self._hangingEy.keys()),2]) + for key in list(self._hangingEy.keys()): for hf in self._hangingEy[key]: ind = [key, hf[0]] ax.plot(self._gridEy[ind,0], self._gridEy[ind,1], 'k:', zs=self._gridEy[ind,2]) if edgesZ: ax.plot(self._gridEz[:,0], self._gridEz[:,1], 'k^', zs=self._gridEz[:,2]) - ax.plot(self._gridEz[self._hangingEz.keys(),0], self._gridEz[self._hangingEz.keys(),1], 'ks', ms=10, mfc='none', mec='k', zs=self._gridEz[self._hangingEz.keys(),2]) - for key in self._hangingEz.keys(): + ax.plot(self._gridEz[list(self._hangingEz.keys()),0], self._gridEz[list(self._hangingEz.keys()),1], 'ks', ms=10, mfc='none', mec='k', zs=self._gridEz[list(self._hangingEz.keys()),2]) + for key in list(self._hangingEz.keys()): for hf in self._hangingEz[key]: ind = [key, hf[0]] ax.plot(self._gridEz[ind,0], self._gridEz[ind,1], 'k:', zs=self._gridEz[ind,2]) @@ -2152,8 +2165,8 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): import matplotlib.cm as cmx szSliceDim = len(getattr(self, 'h'+normal.lower())) #: Size of the sliced dimension - if ind is None: ind = int(szSliceDim/2) - assert type(ind) in [int, long], 'ind must be an integer' + if ind is None: ind = int(old_div(szSliceDim,2)) + assert type(ind) in [int, int], 'ind must be an integer' indLoc = getattr(self,'vectorCC'+normal.lower())[ind] normalInd = {'X':0,'Y':1,'Z':2}[normal] antiNormalInd = {'X':[1,2],'Y':[0,2],'Z':[0,1]}[normal] @@ -2235,19 +2248,19 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): def __getitem__(self, key): if isinstance( key, slice ) : #Get the start, stop, and step from the slice - return [self[ii] for ii in xrange(*key.indices(len(self)))] + return [self[ii] for ii in range(*key.indices(len(self)))] elif isinstance( key, int ) : if key < 0 : #Handle negative indices key += len( self ) if key >= len( self ) : - raise IndexError, "The index (%d) is out of range."%key + raise IndexError("The index (%d) is out of range."%key) self._numberCells() # no-op if numbered index = self._i2cc[key] pointer = self._asPointer(index) return Cell(self, index, pointer) else: - raise TypeError, "Invalid argument type." + raise TypeError("Invalid argument type.") class Cell(object): @@ -2333,7 +2346,7 @@ def SortGrid(grid, offset=0): def __ne__(self, other): return mycmp(self.obj, other.obj) != 0 - return sorted(range(offset,grid.shape[0]+offset), key=K) + return sorted(list(range(offset,grid.shape[0]+offset)), key=K) class TreeException(Exception): diff --git a/SimPEG/Mesh/View.py b/SimPEG/Mesh/View.py index 32e97539..0f6d96a8 100644 --- a/SimPEG/Mesh/View.py +++ b/SimPEG/Mesh/View.py @@ -1,11 +1,22 @@ +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import zip +from builtins import range +from builtins import object +from past.utils import old_div import numpy as np from SimPEG.Utils import mkvc try: import matplotlib.pyplot as plt import matplotlib from mpl_toolkits.mplot3d import Axes3D -except ImportError, e: - print 'Trouble importing matplotlib.' +except ImportError as e: + print('Trouble importing matplotlib.') class TensorView(object): @@ -128,7 +139,7 @@ class TensorView(object): # determine number oE slices in x and y dimension nX = np.ceil(np.sqrt(self.nCz)) - nY = np.ceil(self.nCz/nX) + nY = np.ceil(old_div(self.nCz,nX)) # allocate space for montage nCx = self.nCx @@ -228,8 +239,8 @@ class TensorView(object): assert type(grid) is bool, 'grid must be a boolean' szSliceDim = getattr(self, 'nC'+normal.lower()) #: Size of the sliced dimension - if ind is None: ind = int(szSliceDim/2) - assert type(ind) in [int, long], 'ind must be an integer' + if ind is None: ind = int(old_div(szSliceDim,2)) + assert type(ind) in [int, int], 'ind must be an integer' assert not (v.dtype == complex and view == 'vec'), 'Can not plot a complex vector.' # The slicing and plotting code!! @@ -362,8 +373,8 @@ class TensorView(object): # spaced vectors at the moment. So we will # Interpolate down to a regular mesh at the # smallest mesh size in this 2D slice. - nxi = int(self.hx.sum()/self.hx.min()) - nyi = int(self.hy.sum()/self.hy.min()) + nxi = int(old_div(self.hx.sum(),self.hx.min())) + nyi = int(old_div(self.hy.sum(),self.hy.min())) tMi = self.__class__([np.ones(nxi)*self.hx.sum()/nxi, np.ones(nyi)*self.hy.sum()/nyi], self.x0) P = self.getInterpolationMat(tMi.gridCC,'CC',zerosOutside=True) diff --git a/SimPEG/Mesh/__init__.py b/SimPEG/Mesh/__init__.py index 9aadfcba..e9cf67ae 100644 --- a/SimPEG/Mesh/__init__.py +++ b/SimPEG/Mesh/__init__.py @@ -1,5 +1,11 @@ -from TensorMesh import TensorMesh -from CylMesh import CylMesh -from CurvilinearMesh import CurvilinearMesh -from TreeMesh import TreeMesh -from BaseMesh import BaseMesh +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 .TensorMesh import TensorMesh +from .CylMesh import CylMesh +from .CurvilinearMesh import CurvilinearMesh +from .TreeMesh import TreeMesh +from .BaseMesh import BaseMesh diff --git a/SimPEG/Models.py b/SimPEG/Models.py index 65cfdeee..f9745bed 100644 --- a/SimPEG/Models.py +++ b/SimPEG/Models.py @@ -1,5 +1,11 @@ +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() import numpy as np -from Maps import * +from .Maps import * class Model(np.ndarray): diff --git a/SimPEG/Optimization.py b/SimPEG/Optimization.py index c66242aa..eddedc32 100644 --- a/SimPEG/Optimization.py +++ b/SimPEG/Optimization.py @@ -1,5 +1,16 @@ -import Utils, numpy as np, scipy.sparse as sp -from Utils.SolverUtils import * +from __future__ import print_function +from __future__ import absolute_import +from __future__ import division +from __future__ import unicode_literals +from builtins import super +from future import standard_library +standard_library.install_aliases() +from past.utils import old_div +from builtins import object +from . import Utils +import numpy as np, scipy.sparse as sp +from .Utils.SolverUtils import * +from future.utils import with_metaclass norm = np.linalg.norm @@ -78,13 +89,11 @@ class IterationPrinters(object): phi_m = {"title": "phi_m", "value": lambda M: M.parent.phi_m, "width": 10, "format": "%1.2e"} -class Minimize(object): +class Minimize(with_metaclass(Utils.SimPEGMetaClass, object)): """ Minimize is a general class for derivative based optimization. """ - __metaclass__ = Utils.SimPEGMetaClass - name = "General Optimization Algorithm" #: The name of the optimization algorithm maxIter = 20 #: Maximum number of iterations @@ -121,7 +130,7 @@ class Minimize(object): @callback.setter def callback(self, value): if self.callback is not None: - print 'The callback on the %s Optimization was replaced.' % self.__name__ + print('The callback on the %s Optimization was replaced.' % self.__name__) self._callback = value @@ -412,7 +421,7 @@ class Minimize(object): :return: (xt, breakCaught) numpy.ndarray, bool """ self.printDone(inLS=True) - print 'The linesearch got broken. Boo.' + print('The linesearch got broken. Boo.') return p, False @Utils.count @@ -493,14 +502,14 @@ class Remember(object): def _doEndIterationRemember(self, *args): for param in self._rememberThese: if type(param) is str: - if self.debug: print 'Remember is remembering: ' + param + if self.debug: print('Remember is remembering: ' + param) val = getattr(self, param, None) if val is None and getattr(self, 'parent', None) is not None: # Look to the parent for the param if not found here. val = getattr(self.parent, param, None) self._rememberList[param].append( val ) elif type(param) is tuple: - if self.debug: print 'Remember is remembering: ' + param[0] + if self.debug: print('Remember is remembering: ' + param[0]) self._rememberList[param[0]].append( param[1](self) ) @@ -587,19 +596,19 @@ class ProjectedGradient(Minimize, Remember): self.aSet_prev = self.activeSet(self.xc) allBoundsAreActive = sum(self.aSet_prev) == self.xc.size - if self.debug: print 'findSearchDirection: stopDoingPG: ', self.stopDoingPG - if self.debug: print 'findSearchDirection: explorePG: ', self.explorePG - if self.debug: print 'findSearchDirection: exploreCG: ', self.exploreCG - if self.debug: print 'findSearchDirection: aSet', np.sum(self.activeSet(self.xc)) - if self.debug: print 'findSearchDirection: bSet', np.sum(self.bindingSet(self.xc)) - if self.debug: print 'findSearchDirection: allBoundsAreActive: ', allBoundsAreActive + if self.debug: print('findSearchDirection: stopDoingPG: ', self.stopDoingPG) + if self.debug: print('findSearchDirection: explorePG: ', self.explorePG) + if self.debug: print('findSearchDirection: exploreCG: ', self.exploreCG) + if self.debug: print('findSearchDirection: aSet', np.sum(self.activeSet(self.xc))) + if self.debug: print('findSearchDirection: bSet', np.sum(self.bindingSet(self.xc))) + if self.debug: print('findSearchDirection: allBoundsAreActive: ', allBoundsAreActive) if self.explorePG or not self.exploreCG or allBoundsAreActive: - if self.debug: print 'findSearchDirection.PG: doingPG' + if self.debug: print('findSearchDirection.PG: doingPG') self._itType = 'SD' p = -self.g else: - if self.debug: print 'findSearchDirection.CG: doingCG' + if self.debug: print('findSearchDirection.CG: doingCG') # Reset the max decrease each time you do a CG iteration self.f_decrease_max = -np.inf @@ -611,7 +620,7 @@ class ProjectedGradient(Minimize, Remember): v = np.ones(shape[1]) i = np.where(iSet)[0] j = np.arange(shape[1]) - if self.debug: print 'findSearchDirection.CG: Z.shape', shape + if self.debug: print('findSearchDirection.CG: Z.shape', shape) Z = sp.csr_matrix((v, (i, j)), shape=shape) def reduceHess(v): @@ -649,9 +658,9 @@ class ProjectedGradient(Minimize, Remember): # if true go to CG # don't do too many steps of PG in a row. - if self.debug: print 'doEndIteration.ProjGrad, f_current_decrease: ', f_current_decrease - if self.debug: print 'doEndIteration.ProjGrad, f_decrease_max: ', self.f_decrease_max - if self.debug: print 'doEndIteration.ProjGrad, stopDoingSD: ', self.stopDoingPG + if self.debug: print('doEndIteration.ProjGrad, f_current_decrease: ', f_current_decrease) + if self.debug: print('doEndIteration.ProjGrad, f_decrease_max: ', self.f_decrease_max) + if self.debug: print('doEndIteration.ProjGrad, stopDoingSD: ', self.stopDoingPG) class BFGS(Minimize, Remember): @@ -694,10 +703,10 @@ class BFGS(Minimize, Remember): d = self.bfgsH0 * d #Assume that bfgsH0 is a SimPEG.Solver else: khat = 0 if nn is 0 else np.mod(n-nn+k,nn) - gamma = np.vdot(S[:,khat],d)/np.vdot(Y[:,khat],S[:,khat]) + gamma = old_div(np.vdot(S[:,khat],d),np.vdot(Y[:,khat],S[:,khat])) d = d - gamma*Y[:,khat] d = self.bfgsrec(k-1,n,nn,S,Y,d) - d = d + (gamma - np.vdot(Y[:,khat],d)/np.vdot(Y[:,khat],S[:,khat]))*S[:,khat] + d = d + (gamma - old_div(np.vdot(Y[:,khat],d),np.vdot(Y[:,khat],S[:,khat])))*S[:,khat] return d def findSearchDirection(self): @@ -837,7 +846,7 @@ class NewtonRoot(object): return out if len(out) > 1 else out[0] """ - if self.comments: print 'Newton Method:\n' + if self.comments: print('Newton Method:\n') self.iter = 0 while True: @@ -852,18 +861,18 @@ class NewtonRoot(object): xt = x + dh rt = fun(xt, return_g=False) - if self.comments and self.doLS: print '\tLinesearch:\n' + if self.comments and self.doLS: print('\tLinesearch:\n') # Enter Linesearch while True and self.doLS: - if self.comments: print '\t\tResid: %e\n'%norm(rt) + if self.comments: print('\t\tResid: %e\n'%norm(rt)) if norm(rt) <= norm(r) or norm(rt) < self.tol: break muLS = muLS*self.stepDcr LScnt = LScnt + 1 - print '.' + print('.') if LScnt > self.maxLS: - print 'Newton Method: Line search break.' + print('Newton Method: Line search break.') return None xt = x + muLS*dh rt = fun(xt, return_g=False) @@ -873,7 +882,7 @@ class NewtonRoot(object): if norm(rt) < self.tol: break if self.iter > self.maxIter: - print 'NewtonRoot stopped by maxIters (%d). norm: %4.4e' % (self.maxIter, norm(rt)) + print('NewtonRoot stopped by maxIters (%d). norm: %4.4e' % (self.maxIter, norm(rt))) break return x @@ -975,7 +984,7 @@ class ProjectedGNCG(BFGS, Minimize, Remember): if cgiter == 1: pc = dc else: - betak = rd / rdlast + betak = old_div(rd, rdlast) pc = dc + betak * pc # Form product Hessian*pc. @@ -983,12 +992,12 @@ class ProjectedGNCG(BFGS, Minimize, Remember): Hp = (1-Active)*Hp # Update delx and residual. - alphak = rd / np.dot(pc, Hp) + alphak = old_div(rd, np.dot(pc, Hp)) delx = delx + alphak*pc resid = resid - alphak*Hp rdlast = rd - if np.logical_or(norm(resid)/normResid0 <= self.tolCG, cgiter == self.maxIterCG): + if np.logical_or(old_div(norm(resid),normResid0) <= self.tolCG, cgiter == self.maxIterCG): cgFlag = 1 # End CG Iterations @@ -1008,4 +1017,4 @@ class ProjectedGNCG(BFGS, Minimize, Remember): indx = ((self.xc<=self.lower) & (delx < 0)) | ((self.xc>=self.upper) & (delx > 0)) delx[indx] = 0. - return delx \ No newline at end of file + return delx diff --git a/SimPEG/Problem.py b/SimPEG/Problem.py index f8520c5c..a439cbb6 100644 --- a/SimPEG/Problem.py +++ b/SimPEG/Problem.py @@ -1,15 +1,22 @@ -import Utils, Survey, Models, numpy as np, scipy.sparse as sp +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 object +from . import Utils, Survey, Models +import numpy as np, scipy.sparse as sp +from future.utils import with_metaclass Solver = Utils.SolverUtils.Solver -import Maps, Mesh -from Fields import Fields, TimeFields +from . import Maps, Mesh +from .Fields import Fields, TimeFields -class BaseProblem(object): +class BaseProblem(with_metaclass(Utils.SimPEGMetaClass, object)): """ Problem is the base class for all geophysical forward problems in SimPEG. """ - __metaclass__ = Utils.SimPEGMetaClass - counter = None #: A SimPEG.Utils.Counter object surveyPair = Survey.BaseSurvey #: A SimPEG.Survey Class diff --git a/SimPEG/PropMaps.py b/SimPEG/PropMaps.py index 34cad863..5209eede 100644 --- a/SimPEG/PropMaps.py +++ b/SimPEG/PropMaps.py @@ -1,4 +1,16 @@ -import Utils, Maps, numpy as np, scipy.sparse as sp +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import super +from builtins import dict +from future import standard_library +standard_library.install_aliases() +from builtins import range +from builtins import object +from . import Utils, Maps +import numpy as np, scipy.sparse as sp +from future.utils import with_metaclass class Property(object): @@ -99,9 +111,9 @@ class Property(object): return None inds = getattr(self.propMap, '%sIndex'%prop.name) if type(inds) is slice: - inds = range(*inds.indices(self.nP)) + inds = list(range(*inds.indices(self.nP))) nI, nP = len(inds),self.nP - return sp.csr_matrix((np.ones(nI), (range(nI), inds) ), shape=(nI, nP)) + return sp.csr_matrix((np.ones(nI), (list(range(nI)), inds) ), shape=(nI, nP)) return property(fget=fget) def _getModelMapProperty(self): @@ -126,7 +138,7 @@ class PropModel(object): index = getattr(self.propMap, '%sIndex'%name, None) if index is not None: if type(index) is slice: - inds += range(*index.indices(len(self.vector))) + inds += list(range(*index.indices(len(self.vector)))) else: inds += list(index) self._nP = len(set(inds)) @@ -190,9 +202,7 @@ class _PropMapMetaClass(type): return type('PropModel', (PropModel, ), attrs) -class PropMap(object): - __metaclass__ = _PropMapMetaClass - +class PropMap(with_metaclass(_PropMapMetaClass, object)): def __init__(self, mappings): """ PropMap takes a multi parameter model and maps it to the equivalent PropModel diff --git a/SimPEG/Regularization.py b/SimPEG/Regularization.py index 2ce5614c..dcbe7139 100644 --- a/SimPEG/Regularization.py +++ b/SimPEG/Regularization.py @@ -1,6 +1,15 @@ -import Utils, Maps, Mesh +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 object +from past.utils import old_div +from . import Utils, Maps, Mesh import numpy as np import scipy.sparse as sp +from future.utils import with_metaclass class RegularizationMesh(object): """ @@ -134,7 +143,7 @@ class RegularizationMesh(object): :return: averaging matrix from active x-faces to active cell centers """ if getattr(self, '_aveCC2Fx', None) is None: - self._aveCC2Fx = Utils.sdiag(1./(self.aveFx2CC.T).sum(1)) * self.aveFx2CC.T + self._aveCC2Fx = Utils.sdiag(old_div(1.,(self.aveFx2CC.T).sum(1))) * self.aveFx2CC.T return self._aveCC2Fx @property @@ -156,7 +165,7 @@ class RegularizationMesh(object): :return: averaging matrix from active y-faces to active cell centers """ if getattr(self, '_aveCC2Fy', None) is None: - self._aveCC2Fy = Utils.sdiag(1./(self.aveFy2CC.T).sum(1)) * self.aveFy2CC.T + self._aveCC2Fy = Utils.sdiag(old_div(1.,(self.aveFy2CC.T).sum(1))) * self.aveFy2CC.T return self._aveCC2Fy @property @@ -178,7 +187,7 @@ class RegularizationMesh(object): :return: averaging matrix from active z-faces to active cell centers """ if getattr(self, '_aveCC2Fz', None) is None: - self._aveCC2Fz = Utils.sdiag(1./(self.aveFz2CC.T).sum(1)) * self.aveFz2CC.T + self._aveCC2Fz = Utils.sdiag(old_div(1.,(self.aveFz2CC.T).sum(1))) * self.aveFz2CC.T return self._aveCC2Fz @property @@ -286,7 +295,7 @@ class RegularizationMesh(object): return self._cellDiffzStencil -class BaseRegularization(object): +class BaseRegularization(with_metaclass(Utils.SimPEGMetaClass, object)): """ **Base Regularization Class** @@ -296,8 +305,6 @@ class BaseRegularization(object): """ - __metaclass__ = Utils.SimPEGMetaClass - counter = None mapPair = Maps.IdentityMap #: A SimPEG.Map Class @@ -328,7 +335,7 @@ class BaseRegularization(object): @parent.setter def parent(self, p): if getattr(self,'_parent',None) is not None: - print 'Regularization has switched to a new parent!' + print('Regularization has switched to a new parent!') self._parent = p @property @@ -996,7 +1003,7 @@ class Sparse(Simple): def R(self, f_m , eps, exponent): # Eta scaling is important for mix-norms...do not mess with it - eta = (eps**(1.-exponent/2.))**0.5 - r = eta / (f_m**2.+ eps**2.)**((1.-exponent/2.)/2.) + eta = (eps**(1.-old_div(exponent,2.)))**0.5 + r = old_div(eta, (f_m**2.+ eps**2.)**(old_div((1.-old_div(exponent,2.)),2.))) return r diff --git a/SimPEG/Survey.py b/SimPEG/Survey.py index 65c46972..9c415157 100644 --- a/SimPEG/Survey.py +++ b/SimPEG/Survey.py @@ -1,4 +1,15 @@ -import Utils, numpy as np, scipy.sparse as sp, uuid +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import dict +from future import standard_library +standard_library.install_aliases() +from builtins import str +from builtins import object +from . import Utils +import numpy as np, scipy.sparse as sp, uuid +from future.utils import with_metaclass class BaseRx(object): """SimPEG Receiver Object""" @@ -201,11 +212,9 @@ class Data(object): indBot += rx.nD -class BaseSurvey(object): +class BaseSurvey(with_metaclass(Utils.SimPEGMetaClass, object)): """Survey holds the observed data, and the standard deviations.""" - __metaclass__ = Utils.SimPEGMetaClass - std = None #: Estimated Standard Deviations eps = None #: Estimated Noise Floor dobs = None #: Observed data @@ -239,7 +248,7 @@ class BaseSurvey(object): for src in sources: if getattr(src,'uid',None) is None: raise KeyError('Source does not have a uid: %s'%str(src)) - inds = map(lambda src: self._sourceOrder.get(src.uid, None), sources) + inds = [self._sourceOrder.get(src.uid, None) for src in sources] if None in inds: raise KeyError('Some of the sources specified are not in this survey. %s'%str(inds)) return inds diff --git a/SimPEG/Tests.py b/SimPEG/Tests.py index ea7a74e1..a5f60317 100644 --- a/SimPEG/Tests.py +++ b/SimPEG/Tests.py @@ -1,3 +1,12 @@ +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import range +from past.utils import old_div import numpy as np from numpy.linalg import norm from SimPEG.Utils import mkvc, sdiag, diagEst @@ -12,7 +21,7 @@ import inspect try: import getpass name = getpass.getuser()[0].upper() + getpass.getuser()[1:] -except Exception, e: +except Exception as e: name = 'You' happiness = ['The test be workin!', 'You get a gold star!', 'Yay passed!', 'Happy little convergence test!', 'That was easy!', 'Testing is important.', 'You are awesome.', 'Go Test Go!', 'Once upon a time, a happy little test passed.', 'And then everyone was happy.','Not just a pretty face '+name,'You deserve a pat on the back!','Well done '+name+'!', 'Awesome, '+name+', just awesome.'] sadness = ['No gold star for you.','Try again soon.','Thankfully, persistence is a great substitute for talent.','It might be easier to call this a feature...','Coffee break?', 'Boooooooo :(', 'Testing is important. Do it again.',"Did you put your clever trousers on today?",'Just think about a dancing dinosaur and life will get better!','You had so much promise '+name+', oh well...', name.upper()+' ERROR!','Get on it '+name+'!', 'You break it, you fix it.'] @@ -93,7 +102,7 @@ class OrderTest(unittest.TestCase): h1 = np.random.rand(nc)*nc*0.5 + nc*0.5 h2 = np.random.rand(nc)*nc*0.5 + nc*0.5 h3 = np.random.rand(nc)*nc*0.5 + nc*0.5 - h = [hi/np.sum(hi) for hi in [h1, h2, h3]] # normalize + h = [old_div(hi,np.sum(hi)) for hi in [h1, h2, h3]] # normalize else: raise Exception('Unexpected meshType') @@ -130,7 +139,7 @@ class OrderTest(unittest.TestCase): elif self.meshDimension == 3: X, Y, Z = Utils.exampleLrmGrid([nc, nc, nc], kwrd) self.M = CurvilinearMesh([X, Y, Z]) - return 1./nc + return old_div(1.,nc) elif 'Tree' in self._meshType: nc *= 2 @@ -140,11 +149,11 @@ class OrderTest(unittest.TestCase): h1 = np.random.rand(nc)*nc*0.5 + nc*0.5 h2 = np.random.rand(nc)*nc*0.5 + nc*0.5 h3 = np.random.rand(nc)*nc*0.5 + nc*0.5 - h = [hi/np.sum(hi) for hi in [h1, h2, h3]] # normalize + h = [old_div(hi,np.sum(hi)) for hi in [h1, h2, h3]] # normalize else: raise Exception('Unexpected meshType') - levels = int(np.log(nc)/np.log(2)) + levels = int(old_div(np.log(nc),np.log(2))) self.M = Tree(h[:self.meshDimension], levels=levels) def function(cell): if 'notatree' in self._meshType: @@ -195,25 +204,25 @@ class OrderTest(unittest.TestCase): max_h = self.setupMesh(nc) err = self.getError() if ii == 0: - print '' - print self._meshType + ': ' + self.name - print '_____________________________________________' - print ' h | error | e(i-1)/e(i) | order' - print '~~~~~~|~~~~~~~~~~~~~|~~~~~~~~~~~~~|~~~~~~~~~~' - print '%4i | %8.2e |' % (nc, err) + print('') + print(self._meshType + ': ' + self.name) + print('_____________________________________________') + print(' h | error | e(i-1)/e(i) | order') + print('~~~~~~|~~~~~~~~~~~~~|~~~~~~~~~~~~~|~~~~~~~~~~') + print('%4i | %8.2e |' % (nc, err)) else: - order.append(np.log(err/err_old)/np.log(max_h/max_h_old)) - print '%4i | %8.2e | %6.4f | %6.4f' % (nc, err, err_old/err, order[-1]) + order.append(old_div(np.log(old_div(err,err_old)),np.log(old_div(max_h,max_h_old)))) + print('%4i | %8.2e | %6.4f | %6.4f' % (nc, err, old_div(err_old,err), order[-1])) err_old = err max_h_old = max_h - print '---------------------------------------------' + print('---------------------------------------------') passTest = np.mean(np.array(order)) > self._tolerance*self._expectedOrder if passTest: - print happiness[np.random.randint(len(happiness))] + print(happiness[np.random.randint(len(happiness))]) else: - print 'Failed to pass test on ' + self._meshType + '.' - print sadness[np.random.randint(len(sadness))] - print '' + print('Failed to pass test on ' + self._meshType + '.') + print(sadness[np.random.randint(len(sadness))]) + print('') self.assertTrue(passTest) def Rosenbrock(x, return_g=True, return_H=True): @@ -258,8 +267,8 @@ def checkDerivative(fctn, x0, num=7, plotIt=True, dx=None, expectedOrder=2, tole Tests.checkDerivative(simplePass, np.random.randn(5)) """ - print "%s checkDerivative %s" % ('='*20, '='*20) - print "iter h |ft-f0| |ft-f0-h*J0*dx| Order\n%s" % ('-'*57) + print("%s checkDerivative %s" % ('='*20, '='*20)) + print("iter h |ft-f0| |ft-f0-h*J0*dx| Order\n%s" % ('-'*57)) f0, J0 = fctn(x0) @@ -288,9 +297,9 @@ def checkDerivative(fctn, x0, num=7, plotIt=True, dx=None, expectedOrder=2, tole # We assume it is a numpy.ndarray E1[i] = l2norm( ft - f0 - h[i]*J0.dot(dx) ) - order0 = np.log10(E0[:-1]/E0[1:]) - order1 = np.log10(E1[:-1]/E1[1:]) - print " %d %1.2e %1.3e %1.3e %1.3f" % (i, h[i], E0[i], E1[i], np.nan if i == 0 else order1[i-1]) + order0 = np.log10(old_div(E0[:-1],E0[1:])) + order1 = np.log10(old_div(E1[:-1],E1[1:])) + print(" %d %1.2e %1.3e %1.3e %1.3f" % (i, h[i], E0[i], E1[i], np.nan if i == 0 else order1[i-1])) # Ensure we are about precision order0 = order0[E0[1:] > eps] @@ -302,11 +311,11 @@ def checkDerivative(fctn, x0, num=7, plotIt=True, dx=None, expectedOrder=2, tole passTest = belowTol or correctOrder if passTest: - print "%s PASS! %s" % ('='*25, '='*25) - print happiness[np.random.randint(len(happiness))]+'\n' + print("%s PASS! %s" % ('='*25, '='*25)) + print(happiness[np.random.randint(len(happiness))]+'\n') else: - print "%s\n%s FAIL! %s\n%s" % ('*'*57, '<'*25, '>'*25, '*'*57) - print sadness[np.random.randint(len(sadness))]+'\n' + print("%s\n%s FAIL! %s\n%s" % ('*'*57, '<'*25, '>'*25, '*'*57)) + print(sadness[np.random.randint(len(sadness))]+'\n') if plotIt: diff --git a/SimPEG/Utils/CounterUtils.py b/SimPEG/Utils/CounterUtils.py index 9cd34d2c..c3b790b8 100644 --- a/SimPEG/Utils/CounterUtils.py +++ b/SimPEG/Utils/CounterUtils.py @@ -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) diff --git a/SimPEG/Utils/ModelBuilder.py b/SimPEG/Utils/ModelBuilder.py index 1f4aa47f..874cd714 100644 --- a/SimPEG/Utils/ModelBuilder.py +++ b/SimPEG/Utils/ModelBuilder.py @@ -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() # ----------------------------------------- diff --git a/SimPEG/Utils/SolverUtils.py b/SimPEG/Utils/SolverUtils.py index 28a1159d..94cdc177 100644 --- a/SimPEG/Utils/SolverUtils.py +++ b/SimPEG/Utils/SolverUtils.py @@ -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 diff --git a/SimPEG/Utils/__init__.py b/SimPEG/Utils/__init__.py index c7597fee..1e54eff2 100644 --- a/SimPEG/Utils/__init__.py +++ b/SimPEG/Utils/__init__.py @@ -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 * diff --git a/SimPEG/Utils/codeutils.py b/SimPEG/Utils/codeutils.py index 6151c540..d43436cc 100644 --- a/SimPEG/Utils/codeutils.py +++ b/SimPEG/Utils/codeutils.py @@ -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: diff --git a/SimPEG/Utils/coordutils.py b/SimPEG/Utils/coordutils.py index 260e1a3b..a5143d04 100644 --- a/SimPEG/Utils/coordutils.py +++ b/SimPEG/Utils/coordutils.py @@ -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) diff --git a/SimPEG/Utils/curvutils.py b/SimPEG/Utils/curvutils.py index f49d292f..469dfdca 100644 --- a/SimPEG/Utils/curvutils.py +++ b/SimPEG/Utils/curvutils.py @@ -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 diff --git a/SimPEG/Utils/interputils.py b/SimPEG/Utils/interputils.py index 16c7bf5e..457a65a8 100644 --- a/SimPEG/Utils/interputils.py +++ b/SimPEG/Utils/interputils.py @@ -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 diff --git a/SimPEG/Utils/io_utils.py b/SimPEG/Utils/io_utils.py index 323feb0c..0887d617 100644 --- a/SimPEG/Utils/io_utils.py +++ b/SimPEG/Utils/io_utils.py @@ -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() diff --git a/SimPEG/Utils/matutils.py b/SimPEG/Utils/matutils.py index 73f414b3..64036b6a 100644 --- a/SimPEG/Utils/matutils.py +++ b/SimPEG/Utils/matutils.py @@ -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 diff --git a/SimPEG/Utils/meshutils.py b/SimPEG/Utils/meshutils.py index c7ec1efd..b8d97764 100644 --- a/SimPEG/Utils/meshutils.py +++ b/SimPEG/Utils/meshutils.py @@ -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]> DC analytic test for Problem3D_N is passed" + print(">> DC analytic test for Problem3D_N is passed") else: passed = False - print ">> DC analytic test for Problem3D_N is failed" + print(">> DC analytic test for Problem3D_N is failed") self.assertTrue(passed) def test_Problem3D_CC(self): @@ -55,13 +62,13 @@ class DCProblemAnalyticTests(unittest.TestCase): problem.Solver = self.Solver problem.pair(self.survey) data = self.survey.dpred(self.sigma) - err= np.linalg.norm((data-self.data_anal)/self.data_anal)**2 / self.data_anal.size + err= old_div(np.linalg.norm(old_div((data-self.data_anal),self.data_anal))**2, self.data_anal.size) if err < 0.05: passed = True - print ">> DC analytic test for Problem3D_CC is passed" + print(">> DC analytic test for Problem3D_CC is passed") else: passed = False - print ">> DC analytic test for Problem3D_CC is failed" + print(">> DC analytic test for Problem3D_CC is failed") self.assertTrue(passed) if __name__ == '__main__': diff --git a/tests/em/static/test_DC_2D_jvecjtvecadj.py b/tests/em/static/test_DC_2D_jvecjtvecadj.py index b96529cf..da286cd9 100644 --- a/tests/em/static/test_DC_2D_jvecjtvecadj.py +++ b/tests/em/static/test_DC_2D_jvecjtvecadj.py @@ -1,3 +1,9 @@ +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() import unittest from SimPEG import * import SimPEG.EM.Static.DC as DC @@ -55,7 +61,7 @@ class DCProblem_2DTestsCC(unittest.TestCase): wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-10 - print 'Adjoint Test', np.abs(wtJv - vtJtw), passed + print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed) def test_dataObj(self): @@ -115,7 +121,7 @@ class DCProblemTestsN(unittest.TestCase): wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-8 - print 'Adjoint Test', np.abs(wtJv - vtJtw), passed + print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed) def test_dataObj(self): diff --git a/tests/em/static/test_DC_analytic.py b/tests/em/static/test_DC_analytic.py index b8ebfc81..f26cf074 100644 --- a/tests/em/static/test_DC_analytic.py +++ b/tests/em/static/test_DC_analytic.py @@ -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 unittest from SimPEG import Mesh, Utils, EM, Maps, np import SimPEG.EM.Static.DC as DC @@ -35,7 +42,7 @@ class DCProblemAnalyticTests(unittest.TestCase): try: from pymatsolver import MumpsSolver self.Solver = MumpsSolver - except ImportError, e: + except ImportError as e: self.Solver = SolverLU def test_Problem3D_N(self): @@ -43,13 +50,13 @@ class DCProblemAnalyticTests(unittest.TestCase): problem.Solver = self.Solver problem.pair(self.survey) data = self.survey.dpred(self.sigma) - err= np.linalg.norm(data-self.data_anal)/np.linalg.norm(self.data_anal) + err= old_div(np.linalg.norm(data-self.data_anal),np.linalg.norm(self.data_anal)) if err < 0.2: passed = True - print ">> DC analytic test for Problem3D_N is passed" + print(">> DC analytic test for Problem3D_N is passed") else: passed = False - print ">> DC analytic test for Problem3D_N is failed" + print(">> DC analytic test for Problem3D_N is failed") self.assertTrue(passed) def test_Problem3D_CC(self): @@ -57,13 +64,13 @@ class DCProblemAnalyticTests(unittest.TestCase): problem.Solver = self.Solver problem.pair(self.survey) data = self.survey.dpred(self.sigma) - err= np.linalg.norm(data-self.data_anal)/np.linalg.norm(self.data_anal) + err= old_div(np.linalg.norm(data-self.data_anal),np.linalg.norm(self.data_anal)) if err < 0.2: passed = True - print ">> DC analytic test for Problem3D_CC is passed" + print(">> DC analytic test for Problem3D_CC is passed") else: passed = False - print ">> DC analytic test for Problem3D_CC is failed" + print(">> DC analytic test for Problem3D_CC is failed") self.assertTrue(passed) if __name__ == '__main__': diff --git a/tests/em/static/test_DC_jvecjtvecadj.py b/tests/em/static/test_DC_jvecjtvecadj.py index 227d4614..7bc15875 100644 --- a/tests/em/static/test_DC_jvecjtvecadj.py +++ b/tests/em/static/test_DC_jvecjtvecadj.py @@ -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 unittest from SimPEG import * import SimPEG.EM.Static.DC as DC @@ -14,7 +21,7 @@ class DCProblemTestsCC(unittest.TestCase): cs = surveySize/nElecs/4 mesh = Mesh.TensorMesh([ - [(cs,10, -1.3),(cs,surveySize/cs),(cs,10, 1.3)], + [(cs,10, -1.3),(cs,old_div(surveySize,cs)),(cs,10, 1.3)], [(cs,3, -1.3),(cs,3,1.3)], # [(cs,5, -1.3),(cs,10)] ],'CN') @@ -55,7 +62,7 @@ class DCProblemTestsCC(unittest.TestCase): wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-10 - print 'Adjoint Test', np.abs(wtJv - vtJtw), passed + print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed) def test_dataObj(self): @@ -74,7 +81,7 @@ class DCProblemTestsN(unittest.TestCase): cs = surveySize/nElecs/4 mesh = Mesh.TensorMesh([ - [(cs,10, -1.3),(cs,surveySize/cs),(cs,10, 1.3)], + [(cs,10, -1.3),(cs,old_div(surveySize,cs)),(cs,10, 1.3)], [(cs,3, -1.3),(cs,3,1.3)], # [(cs,5, -1.3),(cs,10)] ],'CN') @@ -115,7 +122,7 @@ class DCProblemTestsN(unittest.TestCase): wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-8 - print 'Adjoint Test', np.abs(wtJv - vtJtw), passed + print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed) def test_dataObj(self): diff --git a/tests/em/static/test_IP_fwd.py b/tests/em/static/test_IP_fwd.py index 98bb7e90..9d5db608 100644 --- a/tests/em/static/test_IP_fwd.py +++ b/tests/em/static/test_IP_fwd.py @@ -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 unittest from SimPEG import Mesh, Utils, EM, Maps, np import SimPEG.EM.Static.DC as DC @@ -42,7 +49,7 @@ class IPProblemAnalyticTests(unittest.TestCase): try: from pymatsolver import MumpsSolver self.Solver = MumpsSolver - except ImportError, e: + except ImportError as e: self.Solver = SolverLU def test_Problem3D_N(self): @@ -59,13 +66,13 @@ class IPProblemAnalyticTests(unittest.TestCase): problemIP.pair(surveyIP) data_full = data0 - datainf data = surveyIP.dpred(self.eta) - err= np.linalg.norm((data-data_full)/data_full)**2 / data_full.size + err= old_div(np.linalg.norm(old_div((data-data_full),data_full))**2, data_full.size) if err < 0.05: passed = True - print ">> IP forward test for Problem3D_N is passed" + print(">> IP forward test for Problem3D_N is passed") else: passed = False - print ">> IP forward test for Problem3D_N is failed" + print(">> IP forward test for Problem3D_N is failed") self.assertTrue(passed) def test_Problem3D_CC(self): @@ -76,19 +83,19 @@ class IPProblemAnalyticTests(unittest.TestCase): data0 = self.surveyDC.dpred(self.sigma0) finf = problemDC.fields(self.sigmaInf) datainf = self.surveyDC.dpred(self.sigmaInf, f=finf) - problemIP = IP.Problem3D_CC(self.mesh, rho=1./self.sigmaInf, Ainv=problemDC.Ainv, f=finf) + problemIP = IP.Problem3D_CC(self.mesh, rho=old_div(1.,self.sigmaInf), Ainv=problemDC.Ainv, f=finf) problemIP.Solver = self.Solver surveyIP = IP.Survey([self.src]) problemIP.pair(surveyIP) data_full = data0 - datainf data = surveyIP.dpred(self.eta) - err= np.linalg.norm((data-data_full)/data_full)**2 / data_full.size + err= old_div(np.linalg.norm(old_div((data-data_full),data_full))**2, data_full.size) if err < 0.05: passed = True - print ">> IP forward test for Problem3D_CC is passed" + print(">> IP forward test for Problem3D_CC is passed") else: passed = False - print ">> IP forward test for Problem3D_CC is failed" + print(">> IP forward test for Problem3D_CC is failed") self.assertTrue(passed) if __name__ == '__main__': diff --git a/tests/em/static/test_IP_jvecjtvecadj.py b/tests/em/static/test_IP_jvecjtvecadj.py index 7a455784..2d999449 100644 --- a/tests/em/static/test_IP_jvecjtvecadj.py +++ b/tests/em/static/test_IP_jvecjtvecadj.py @@ -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 unittest from SimPEG import * import SimPEG.EM.Static.DC as DC @@ -15,7 +22,7 @@ class IPProblemTestsCC(unittest.TestCase): cs = surveySize/nElecs/4 mesh = Mesh.TensorMesh([ - [(cs,10, -1.3),(cs,surveySize/cs),(cs,10, 1.3)], + [(cs,10, -1.3),(cs,old_div(surveySize,cs)),(cs,10, 1.3)], [(cs,3, -1.3),(cs,3,1.3)], # [(cs,5, -1.3),(cs,10)] ],'CN') @@ -23,7 +30,7 @@ class IPProblemTestsCC(unittest.TestCase): srcList = DC.Utils.WennerSrcList(nElecs, aSpacing, in2D=True) survey = IP.Survey(srcList) sigma = np.ones(mesh.nC) - problem = IP.Problem3D_CC(mesh, rho=1./sigma) + problem = IP.Problem3D_CC(mesh, rho=old_div(1.,sigma)) problem.pair(survey) mSynth = np.ones(mesh.nC)*0.1 survey.makeSyntheticData(mSynth) @@ -55,7 +62,7 @@ class IPProblemTestsCC(unittest.TestCase): wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-10 - print 'Adjoint Test', np.abs(wtJv - vtJtw), passed + print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed) def test_dataObj(self): @@ -74,7 +81,7 @@ class IPProblemTestsN(unittest.TestCase): cs = surveySize/nElecs/4 mesh = Mesh.TensorMesh([ - [(cs,10, -1.3),(cs,surveySize/cs),(cs,10, 1.3)], + [(cs,10, -1.3),(cs,old_div(surveySize,cs)),(cs,10, 1.3)], [(cs,3, -1.3),(cs,3,1.3)], # [(cs,5, -1.3),(cs,10)] ],'CN') @@ -114,7 +121,7 @@ class IPProblemTestsN(unittest.TestCase): wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-8 - print 'Adjoint Test', np.abs(wtJv - vtJtw), passed + print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed) def test_dataObj(self): diff --git a/tests/em/static/test_SIP_jvecjtvecadj.py b/tests/em/static/test_SIP_jvecjtvecadj.py index 7cdb6def..39049b77 100644 --- a/tests/em/static/test_SIP_jvecjtvecadj.py +++ b/tests/em/static/test_SIP_jvecjtvecadj.py @@ -1,3 +1,11 @@ +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from past.utils import old_div import unittest from SimPEG import * import SimPEG @@ -37,10 +45,10 @@ class IPProblemTestsCC(unittest.TestCase): src = SIP.Src.Dipole([rx], Aloc, Bloc) survey = SIP.Survey([src]) colemap = [("eta", Maps.IdentityMap(mesh)), ("taui", Maps.IdentityMap(mesh))] - problem = SIP.Problem3D_CC(mesh, rho=1./sigma, mapping=colemap) + problem = SIP.Problem3D_CC(mesh, rho=old_div(1.,sigma), mapping=colemap) problem.Solver = MumpsSolver problem.pair(survey) - mSynth = np.r_[eta, 1./tau] + mSynth = np.r_[eta, old_div(1.,tau)] survey.makeSyntheticData(mSynth) # Now set up the problem to do some minimization dmis = DataMisfit.l2_DataMisfit(survey) @@ -70,7 +78,7 @@ class IPProblemTestsCC(unittest.TestCase): wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-10 - print 'Adjoint Test', np.abs(wtJv - vtJtw), passed + print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed) def test_dataObj(self): @@ -112,7 +120,7 @@ class IPProblemTestsN(unittest.TestCase): problem = SIP.Problem3D_N(mesh, sigma=sigma, mapping=colemap) problem.Solver = MumpsSolver problem.pair(survey) - mSynth = np.r_[eta, 1./tau] + mSynth = np.r_[eta, old_div(1.,tau)] survey.makeSyntheticData(mSynth) # Now set up the problem to do some minimization dmis = DataMisfit.l2_DataMisfit(survey) @@ -142,7 +150,7 @@ class IPProblemTestsN(unittest.TestCase): wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-8 - print 'Adjoint Test', np.abs(wtJv - vtJtw), passed + print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed) def test_dataObj(self): @@ -189,7 +197,7 @@ class IPProblemTestsN_air(unittest.TestCase): problem = SIP.Problem3D_N(mesh, sigma=sigma, mapping=colemap) problem.Solver = MumpsSolver problem.pair(survey) - mSynth = np.r_[eta[~airind], 1./tau[~airind]] + mSynth = np.r_[eta[~airind], old_div(1.,tau[~airind])] survey.makeSyntheticData(mSynth) # Now set up the problem to do some minimization dmis = DataMisfit.l2_DataMisfit(survey) @@ -220,7 +228,7 @@ class IPProblemTestsN_air(unittest.TestCase): wtJv = w.dot(self.p.Jvec(self.m0, v)) vtJtw = v.dot(self.p.Jtvec(self.m0, w)) passed = np.abs(wtJv - vtJtw) < 1e-8 - print 'Adjoint Test', np.abs(wtJv - vtJtw), passed + print('Adjoint Test', np.abs(wtJv - vtJtw), passed) self.assertTrue(passed) def test_dataObj(self): diff --git a/tests/em/tdem/__init__.py b/tests/em/tdem/__init__.py index 38d84328..6d1d3c1c 100644 --- a/tests/em/tdem/__init__.py +++ b/tests/em/tdem/__init__.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() if __name__ == '__main__': import os import glob diff --git a/tests/em/tdem/test_TDEM_b_DerivAdjoint.py b/tests/em/tdem/test_TDEM_b_DerivAdjoint.py index 30630d8d..11f10ae8 100644 --- a/tests/em/tdem/test_TDEM_b_DerivAdjoint.py +++ b/tests/em/tdem/test_TDEM_b_DerivAdjoint.py @@ -1,3 +1,11 @@ +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 builtins import range +from past.utils import old_div import unittest from SimPEG import * from SimPEG import EM @@ -35,7 +43,7 @@ class TDEM_bDerivTests(unittest.TestCase): try: from pymatsolver import MumpsSolver self.prb.Solver = MumpsSolver - except ImportError, e: + except ImportError as e: self.prb.Solver = SolverLU self.sigma = np.ones(mesh.nCz)*1e-8 @@ -58,7 +66,7 @@ class TDEM_bDerivTests(unittest.TestCase): V1 = Ahu[:,'b',1] V2 = 1./prb.timeSteps[0]*prb.MfMui*u[:,'b',0] - self.assertLess(np.linalg.norm(V1-V2)/np.linalg.norm(V2), 1.e-6) + self.assertLess(old_div(np.linalg.norm(V1-V2),np.linalg.norm(V2)), 1.e-6) V1 = Ahu[:,'e',1] return np.linalg.norm(V1) < 1.e-6 @@ -70,12 +78,12 @@ class TDEM_bDerivTests(unittest.TestCase): V1 = Ahu[:,'b',i] V2 = 1.0/dt*prb.MfMui*u[:,'b', i-1] # print np.linalg.norm(V1), np.linalg.norm(V2) - self.assertLess(np.linalg.norm(V1)/np.linalg.norm(V2), 1.e-6) + self.assertLess(old_div(np.linalg.norm(V1),np.linalg.norm(V2)), 1.e-6) V1 = Ahu[:,'e',i] V2 = prb.MeSigma*u[:,'e',i] # print np.linalg.norm(V1), np.linalg.norm(V2) - return np.linalg.norm(V1)/np.linalg.norm(V2), 1.e-6 + return old_div(np.linalg.norm(V1),np.linalg.norm(V2)), 1.e-6 def test_AhVecVSMat_OneTS(self): @@ -95,7 +103,7 @@ class TDEM_bDerivTests(unittest.TestCase): u1 = A*f.tovec() u2 = prb._AhVec(sigma,f).tovec() - self.assertTrue(np.linalg.norm(u1-u2)/np.linalg.norm(u1)<1e-12) + self.assertTrue(old_div(np.linalg.norm(u1-u2),np.linalg.norm(u1))<1e-12) def test_solveAhVSMat_OneTS(self): prb = self.prb @@ -155,7 +163,7 @@ class TDEM_bDerivTests(unittest.TestCase): h = 0.01 derChk = lambda m: [self.prb._AhVec(m, f).tovec(), lambda mx: self.prb.Gvec(sigma, mx, u=f).tovec()] - print '\ntest_DerivG' + print('\ntest_DerivG') passed = Tests.checkDerivative(derChk, sigma, plotIt=False, dx=dm, num=4, eps=1e-20) return passed @@ -170,8 +178,8 @@ class TDEM_bDerivTests(unittest.TestCase): f = prb.fields(sigma) derChk = lambda m: [self.prb.fields(m).tovec(), lambda mx: -prb.solveAh(sigma, prb.Gvec(sigma, mx, u=f)).tovec()] - print '\n' - print 'test_Deriv_dUdM' + print('\n') + print('test_Deriv_dUdM') Tests.checkDerivative(derChk, sigma, plotIt=False, dx=dm, num=4, eps=1e-20) def test_Deriv_J(self): @@ -186,8 +194,8 @@ class TDEM_bDerivTests(unittest.TestCase): derChk = lambda m: [prb.survey.dpred(m), lambda mx: prb.Jvec(sigma, mx)] - print '\n' - print 'test_Deriv_J' + print('\n') + print('test_Deriv_J') Tests.checkDerivative(derChk, sigma, plotIt=False, dx=d_sig, num=4, eps=1e-20) def test_projectAdjoint(self): @@ -207,7 +215,7 @@ class TDEM_bDerivTests(unittest.TestCase): V1 = d_vec.dot(survey.evalDeriv(None, v=f).tovec()) V2 = f.tovec().dot(survey.evalDeriv(None, v=d, adjoint=True).tovec()) - self.assertTrue((V1-V2)/np.abs(V1) < tol) + self.assertTrue(old_div((V1-V2),np.abs(V1)) < tol) def test_adjointAhVsAht(self): prb = self.prb @@ -226,7 +234,7 @@ class TDEM_bDerivTests(unittest.TestCase): V1 = f2.tovec().dot(prb._AhVec(sigma, f1).tovec()) V2 = f1.tovec().dot(prb._AhtVec(sigma, f2).tovec()) - self.assertTrue(np.abs(V1-V2)/np.abs(V1) < tol) + self.assertTrue(old_div(np.abs(V1-V2),np.abs(V1)) < tol) # def test_solveAhtVsAhtVec(self): # prb = self.prb @@ -291,7 +299,7 @@ class TDEM_bDerivTests(unittest.TestCase): V1 = m.dot(prb.Gtvec(sigma, v, u)) V2 = v.tovec().dot(prb.Gvec(sigma, m, u).tovec()) - self.assertTrue(np.abs(V1-V2)/np.abs(V1) < tol) + self.assertTrue(old_div(np.abs(V1-V2),np.abs(V1)) < tol) def test_adjointJvecVsJtvec(self): mesh = self.mesh @@ -303,8 +311,8 @@ class TDEM_bDerivTests(unittest.TestCase): V1 = d.dot(prb.Jvec(sigma, m)) V2 = m.dot(prb.Jtvec(sigma, d)) - passed = np.abs(V1-V2)/np.abs(V1) < tol - print 'AdjointTest', V1, V2, passed + passed = old_div(np.abs(V1-V2),np.abs(V1)) < tol + print('AdjointTest', V1, V2, passed) self.assertTrue(passed) diff --git a/tests/em/tdem/test_TDEM_b_MultiSrc_DerivAdjoint.py b/tests/em/tdem/test_TDEM_b_MultiSrc_DerivAdjoint.py index 8f3ebcc1..3681acc8 100644 --- a/tests/em/tdem/test_TDEM_b_MultiSrc_DerivAdjoint.py +++ b/tests/em/tdem/test_TDEM_b_MultiSrc_DerivAdjoint.py @@ -1,3 +1,11 @@ +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 builtins import range +from past.utils import old_div import unittest from SimPEG import * from SimPEG import EM @@ -36,7 +44,7 @@ class TDEM_bDerivTests(unittest.TestCase): try: from pymatsolver import MumpsSolver self.prb.Solver = MumpsSolver - except ImportError, e: + except ImportError as e: self.prb.Solver = SolverLU self.sigma = np.ones(mesh.nCz)*1e-8 @@ -59,7 +67,7 @@ class TDEM_bDerivTests(unittest.TestCase): h = 0.01 derChk = lambda m: [self.prb._AhVec(m, f).tovec(), lambda mx: self.prb.Gvec(sigma, mx, u=f).tovec()] - print '\ntest_DerivG' + print('\ntest_DerivG') Tests.checkDerivative(derChk, sigma, plotIt=False, dx=dm, num=4, eps=1e-20) def test_Deriv_dUdM(self): @@ -73,8 +81,8 @@ class TDEM_bDerivTests(unittest.TestCase): f = prb.fields(sigma) derChk = lambda m: [self.prb.fields(m).tovec(), lambda mx: -prb.solveAh(sigma, prb.Gvec(sigma, mx, u=f)).tovec()] - print '\n' - print 'test_Deriv_dUdM' + print('\n') + print('test_Deriv_dUdM') Tests.checkDerivative(derChk, sigma, plotIt=False, dx=dm, num=4, eps=1e-20) def test_Deriv_J(self): @@ -89,8 +97,8 @@ class TDEM_bDerivTests(unittest.TestCase): derChk = lambda m: [prb.survey.dpred(m), lambda mx: prb.Jvec(sigma, mx)] - print '\n' - print 'test_Deriv_J' + print('\n') + print('test_Deriv_J') Tests.checkDerivative(derChk, sigma, plotIt=False, dx=d_sig, num=4, eps=1e-20) def test_projectAdjoint(self): @@ -111,7 +119,7 @@ class TDEM_bDerivTests(unittest.TestCase): V1 = d_vec.dot(survey.evalDeriv(None, v=f).tovec()) V2 = np.sum((f.tovec())*(survey.evalDeriv(None, v=d, adjoint=True).tovec())) - self.assertTrue((V1-V2)/np.abs(V1) < 1e-6) + self.assertTrue(old_div((V1-V2),np.abs(V1)) < 1e-6) def test_adjointGvecVsGtvec(self): mesh = self.mesh @@ -132,7 +140,7 @@ class TDEM_bDerivTests(unittest.TestCase): V1 = m.dot(prb.Gtvec(sigma, v, u)) V2 = np.sum(v.tovec()*prb.Gvec(sigma, m, u).tovec()) - self.assertTrue(np.abs(V1-V2)/np.abs(V1) <1e-6) + self.assertTrue(old_div(np.abs(V1-V2),np.abs(V1)) <1e-6) def test_adjointJvecVsJtvec(self): mesh = self.mesh @@ -144,8 +152,8 @@ class TDEM_bDerivTests(unittest.TestCase): V1 = d.dot(prb.Jvec(sigma, m)) V2 = m.dot(prb.Jtvec(sigma, d)) - print 'AdjointTest', V1, V2 - self.assertTrue(np.abs(V1-V2)/np.abs(V1) < 1e-6) + print('AdjointTest', V1, V2) + self.assertTrue(old_div(np.abs(V1-V2),np.abs(V1)) < 1e-6) diff --git a/tests/em/tdem/test_TDEM_combos.py b/tests/em/tdem/test_TDEM_combos.py index 926cdf23..448407d9 100644 --- a/tests/em/tdem/test_TDEM_combos.py +++ b/tests/em/tdem/test_TDEM_combos.py @@ -1,3 +1,11 @@ +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 builtins import range +from past.utils import old_div import unittest from SimPEG import * from SimPEG import EM @@ -34,7 +42,7 @@ def getProb(meshType='CYL',rxTypes='bx,bz',nSrc=1): try: from pymatsolver import MumpsSolver prb.Solver = MumpsSolver - except ImportError, e: + except ImportError as e: prb.Solver = SolverLU sigma = np.ones(mesh.nCz)*1e-8 @@ -57,8 +65,8 @@ def dotestAdjoint(prb, mesh, sigma): V1 = d.dot(prb.Jvec(sigma, m)) V2 = m.dot(prb.Jtvec(sigma, d)) - print 'AdjointTest', V1, V2 - return np.abs(V1-V2)/np.abs(V1), 1e-6 + print('AdjointTest', V1, V2) + return old_div(np.abs(V1-V2),np.abs(V1)), 1e-6 class TDEM_bDerivTests(unittest.TestCase): diff --git a/tests/em/tdem/test_TDEM_forward_Analytic.py b/tests/em/tdem/test_TDEM_forward_Analytic.py index 7748b5fc..6c553531 100644 --- a/tests/em/tdem/test_TDEM_forward_Analytic.py +++ b/tests/em/tdem/test_TDEM_forward_Analytic.py @@ -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 unittest from SimPEG import * from SimPEG import EM @@ -6,7 +13,7 @@ import matplotlib.pyplot as plt try: from pymatsolver import MumpsSolver -except ImportError, e: +except ImportError as e: MumpsSolver = SolverLU @@ -49,8 +56,8 @@ def halfSpaceProblemAnaDiff(meshType, sig_half=1e-2, rxOffset=50., bounds=None, bz_calc = survey.dpred(sigma) ind = np.logical_and(rx.times > bounds[0],rx.times < bounds[1]) - log10diff = np.linalg.norm(np.log10(np.abs(bz_calc[ind])) - np.log10(np.abs(bz_ana[ind])))/np.linalg.norm(np.log10(np.abs(bz_ana[ind]))) - print 'Difference: ', log10diff + log10diff = old_div(np.linalg.norm(np.log10(np.abs(bz_calc[ind])) - np.log10(np.abs(bz_ana[ind]))),np.linalg.norm(np.log10(np.abs(bz_ana[ind])))) + print('Difference: ', log10diff) if showIt == True: plt.loglog(rx.times[bz_calc>0], bz_calc[bz_calc>0], 'r', rx.times[bz_calc<0], -bz_calc[bz_calc<0], 'r--') diff --git a/tests/examples/__init__.py b/tests/examples/__init__.py index 38d84328..6d1d3c1c 100644 --- a/tests/examples/__init__.py +++ b/tests/examples/__init__.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() if __name__ == '__main__': import os import glob diff --git a/tests/examples/test_examples.py b/tests/examples/test_examples.py index edb5600c..9db47e18 100644 --- a/tests/examples/test_examples.py +++ b/tests/examples/test_examples.py @@ -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 dict +from future import standard_library +standard_library.install_aliases() import unittest import sys import os @@ -6,7 +13,7 @@ import numpy as np class compareInitFiles(unittest.TestCase): def test_compareInitFiles(self): - print 'Checking that __init__.py up-to-date in SimPEG/Examples' + print('Checking that __init__.py up-to-date in SimPEG/Examples') fName = os.path.abspath(__file__) ExamplesDir = os.path.sep.join(fName.split(os.path.sep)[:-3] + ['SimPEG', 'Examples']) @@ -17,7 +24,7 @@ class compareInitFiles(unittest.TestCase): setdiff = set(pyfiles) - set(Examples.__examples__) - print ' Any missing files? ', setdiff + print(' Any missing files? ', setdiff) didpass = (setdiff == set()) @@ -25,7 +32,7 @@ class compareInitFiles(unittest.TestCase): def get(test): def test_func(self): - print '\nTesting %s.run(plotIt=False)\n'%test + print('\nTesting %s.run(plotIt=False)\n'%test) getattr(Examples, test).run(plotIt=False) self.assertTrue(True) return test_func diff --git a/tests/flow/__init__.py b/tests/flow/__init__.py index 38d84328..6d1d3c1c 100644 --- a/tests/flow/__init__.py +++ b/tests/flow/__init__.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() if __name__ == '__main__': import os import glob diff --git a/tests/flow/test_Richards.py b/tests/flow/test_Richards.py index f67ec71d..a1d6e152 100644 --- a/tests/flow/test_Richards.py +++ b/tests/flow/test_Richards.py @@ -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 int +from future import standard_library +standard_library.install_aliases() import unittest from SimPEG import * from SimPEG.Tests import OrderTest, checkDerivative @@ -6,7 +13,7 @@ from SimPEG.FLOW import Richards try: from pymatsolver import MumpsSolver Solver = MumpsSolver -except Exception, e: +except Exception as e: pass @@ -120,14 +127,14 @@ class RichardsTests1D(unittest.TestCase): zJv = z.dot(self.prob.Jtvec(self.Ks,v,f=Hs)) tol = TOL*(10**int(np.log10(np.abs(zJv)))) passed = np.abs(vJz - zJv) < tol - print 'Richards Adjoint Test - PressureHead' - print '%4.4e === %4.4e, diff=%4.4e < %4.e'%(vJz, zJv,np.abs(vJz - zJv),tol) + print('Richards Adjoint Test - PressureHead') + print('%4.4e === %4.4e, diff=%4.4e < %4.e'%(vJz, zJv,np.abs(vJz - zJv),tol)) self.assertTrue(passed,True) def test_Sensitivity(self): mTrue = self.Ks*np.ones(self.M.nC) derChk = lambda m: [self.survey.dpred(m), lambda v: self.prob.Jvec(m, v)] - print 'Testing Richards Derivative' + print('Testing Richards Derivative') passed = checkDerivative(derChk, mTrue, num=4, plotIt=False) self.assertTrue(passed,True) @@ -136,7 +143,7 @@ class RichardsTests1D(unittest.TestCase): mTrue = self.Ks*np.ones(self.M.nC) J = self.prob.Jfull(mTrue) derChk = lambda m: [self.survey.dpred(m), J] - print 'Testing Richards Derivative FULL' + print('Testing Richards Derivative FULL') passed = checkDerivative(derChk, mTrue, num=4, plotIt=False) self.assertTrue(passed,True) @@ -192,14 +199,14 @@ class RichardsTests2D(unittest.TestCase): zJv = z.dot(self.prob.Jtvec(self.Ks,v,f=Hs)) tol = TOL*(10**int(np.log10(np.abs(zJv)))) passed = np.abs(vJz - zJv) < tol - print '2D: Richards Adjoint Test - PressureHead' - print '%4.4e === %4.4e, diff=%4.4e < %4.e'%(vJz, zJv,np.abs(vJz - zJv),tol) + print('2D: Richards Adjoint Test - PressureHead') + print('%4.4e === %4.4e, diff=%4.4e < %4.e'%(vJz, zJv,np.abs(vJz - zJv),tol)) self.assertTrue(passed,True) def test_Sensitivity(self): mTrue = self.Ks*np.ones(self.M.nC) derChk = lambda m: [self.survey.dpred(m), lambda v: self.prob.Jvec(m, v)] - print '2D: Testing Richards Derivative' + print('2D: Testing Richards Derivative') passed = checkDerivative(derChk, mTrue, num=3, plotIt=False) self.assertTrue(passed,True) @@ -207,7 +214,7 @@ class RichardsTests2D(unittest.TestCase): mTrue = self.Ks*np.ones(self.M.nC) J = self.prob.Jfull(mTrue) derChk = lambda m: [self.survey.dpred(m), J] - print '2D: Testing Richards Derivative FULL' + print('2D: Testing Richards Derivative FULL') passed = checkDerivative(derChk, mTrue, num=4, plotIt=False) self.assertTrue(passed,True) @@ -264,14 +271,14 @@ class RichardsTests3D(unittest.TestCase): zJv = z.dot(self.prob.Jtvec(self.Ks,v,f=Hs)) tol = TOL*(10**int(np.log10(np.abs(zJv)))) passed = np.abs(vJz - zJv) < tol - print '3D: Richards Adjoint Test - PressureHead' - print '%4.4e === %4.4e, diff=%4.4e < %4.e'%(vJz, zJv,np.abs(vJz - zJv),tol) + print('3D: Richards Adjoint Test - PressureHead') + print('%4.4e === %4.4e, diff=%4.4e < %4.e'%(vJz, zJv,np.abs(vJz - zJv),tol)) self.assertTrue(passed,True) def test_Sensitivity(self): mTrue = self.Ks*np.ones(self.M.nC) derChk = lambda m: [self.survey.dpred(m), lambda v: self.prob.Jvec(m, v)] - print '3D: Testing Richards Derivative' + print('3D: Testing Richards Derivative') passed = checkDerivative(derChk, mTrue, num=4, plotIt=False) self.assertTrue(passed,True) diff --git a/tests/mesh/__init__.py b/tests/mesh/__init__.py index 38d84328..6d1d3c1c 100644 --- a/tests/mesh/__init__.py +++ b/tests/mesh/__init__.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() if __name__ == '__main__': import os import glob diff --git a/tests/mesh/test_CurvilinearMesh.py b/tests/mesh/test_CurvilinearMesh.py index 42e3d877..a9a9efa3 100644 --- a/tests/mesh/test_CurvilinearMesh.py +++ b/tests/mesh/test_CurvilinearMesh.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import numpy as np import unittest from SimPEG.Mesh import TensorMesh, CurvilinearMesh diff --git a/tests/mesh/test_MeshIO.py b/tests/mesh/test_MeshIO.py index e8dc0748..9cdb0409 100644 --- a/tests/mesh/test_MeshIO.py +++ b/tests/mesh/test_MeshIO.py @@ -1,3 +1,9 @@ +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() import numpy as np import unittest, os import SimPEG as simpeg @@ -35,7 +41,7 @@ class TestTensorMeshIO(unittest.TestCase): vec2UBC = mesh.readModelUBC('arange2.txt') assert np.sum(vec + 1 - vec2UBC) == 0 - print 'IO of UBC tensor mesh files is working' + print('IO of UBC tensor mesh files is working') os.remove('temp.msh') os.remove('arange.txt') os.remove('arange2.txt') @@ -54,7 +60,7 @@ class TestTensorMeshIO(unittest.TestCase): vecVTK = models['arange.txt'] assert np.sum(vec - vecVTK) == 0 - print 'IO of VTR tensor mesh files is working' + print('IO of VTR tensor mesh files is working') os.remove('temp.vtr') @@ -83,7 +89,7 @@ class TestOcTreeMeshIO(unittest.TestCase): assert np.sum(mesh.gridCC - meshUBC.gridCC) == 0 assert np.sum(vec - vecUBC) == 0 assert np.all(np.array(mesh.h) - np.array(meshUBC.h) == 0) - print 'IO of UBC octree files is working' + print('IO of UBC octree files is working') os.remove('temp.msh') os.remove('arange.txt') @@ -91,7 +97,7 @@ class TestOcTreeMeshIO(unittest.TestCase): mesh = self.mesh vec = np.arange(mesh.nC) mesh.writeVTK('temp.vtu',{'arange':vec}) - print 'Writing of VTU files is working' + print('Writing of VTU files is working') os.remove('temp.vtu') diff --git a/tests/mesh/test_Mixed_boundaryPoisson.py b/tests/mesh/test_Mixed_boundaryPoisson.py index 3aa1dbcd..f9064f91 100644 --- a/tests/mesh/test_Mixed_boundaryPoisson.py +++ b/tests/mesh/test_Mixed_boundaryPoisson.py @@ -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 numpy as np import scipy.sparse as sp import unittest @@ -37,15 +44,15 @@ def getxBCyBC_CC(mesh, alpha, beta, gamma): # h_xm, h_xp = mesh.gridCC[fCCxm], mesh.gridCC[fCCxp] h_xm, h_xp = mesh.hx[0], mesh.hx[-1] - a_xm = gamma_xm/(0.5*alpha_xm-beta_xm/h_xm) - b_xm = (0.5*alpha_xm+beta_xm/h_xm)/(0.5*alpha_xm-beta_xm/h_xm) - a_xp = gamma_xp/(0.5*alpha_xp-beta_xp/h_xp) - b_xp = (0.5*alpha_xp+beta_xp/h_xp)/(0.5*alpha_xp-beta_xp/h_xp) + a_xm = old_div(gamma_xm,(0.5*alpha_xm-old_div(beta_xm,h_xm))) + b_xm = old_div((0.5*alpha_xm+old_div(beta_xm,h_xm)),(0.5*alpha_xm-old_div(beta_xm,h_xm))) + a_xp = old_div(gamma_xp,(0.5*alpha_xp-old_div(beta_xp,h_xp))) + b_xp = old_div((0.5*alpha_xp+old_div(beta_xp,h_xp)),(0.5*alpha_xp-old_div(beta_xp,h_xp))) xBC_xm = 0.5*a_xm xBC_xp = 0.5*a_xp/b_xp yBC_xm = 0.5*(1.-b_xm) - yBC_xp = 0.5*(1.-1./b_xp) + yBC_xp = 0.5*(1.-old_div(1.,b_xp)) xBC = np.r_[xBC_xm, xBC_xp] yBC = np.r_[yBC_xm, yBC_xp] @@ -68,24 +75,24 @@ def getxBCyBC_CC(mesh, alpha, beta, gamma): h_xm, h_xp = mesh.hx[0]*np.ones_like(alpha_xm), mesh.hx[-1]*np.ones_like(alpha_xp) h_ym, h_yp = mesh.hy[0]*np.ones_like(alpha_ym), mesh.hy[-1]*np.ones_like(alpha_yp) - a_xm = gamma_xm/(0.5*alpha_xm-beta_xm/h_xm) - b_xm = (0.5*alpha_xm+beta_xm/h_xm)/(0.5*alpha_xm-beta_xm/h_xm) - a_xp = gamma_xp/(0.5*alpha_xp-beta_xp/h_xp) - b_xp = (0.5*alpha_xp+beta_xp/h_xp)/(0.5*alpha_xp-beta_xp/h_xp) + a_xm = old_div(gamma_xm,(0.5*alpha_xm-old_div(beta_xm,h_xm))) + b_xm = old_div((0.5*alpha_xm+old_div(beta_xm,h_xm)),(0.5*alpha_xm-old_div(beta_xm,h_xm))) + a_xp = old_div(gamma_xp,(0.5*alpha_xp-old_div(beta_xp,h_xp))) + b_xp = old_div((0.5*alpha_xp+old_div(beta_xp,h_xp)),(0.5*alpha_xp-old_div(beta_xp,h_xp))) - a_ym = gamma_ym/(0.5*alpha_ym-beta_ym/h_ym) - b_ym = (0.5*alpha_ym+beta_ym/h_ym)/(0.5*alpha_ym-beta_ym/h_ym) - a_yp = gamma_yp/(0.5*alpha_yp-beta_yp/h_yp) - b_yp = (0.5*alpha_yp+beta_yp/h_yp)/(0.5*alpha_yp-beta_yp/h_yp) + a_ym = old_div(gamma_ym,(0.5*alpha_ym-old_div(beta_ym,h_ym))) + b_ym = old_div((0.5*alpha_ym+old_div(beta_ym,h_ym)),(0.5*alpha_ym-old_div(beta_ym,h_ym))) + a_yp = old_div(gamma_yp,(0.5*alpha_yp-old_div(beta_yp,h_yp))) + b_yp = old_div((0.5*alpha_yp+old_div(beta_yp,h_yp)),(0.5*alpha_yp-old_div(beta_yp,h_yp))) xBC_xm = 0.5*a_xm xBC_xp = 0.5*a_xp/b_xp yBC_xm = 0.5*(1.-b_xm) - yBC_xp = 0.5*(1.-1./b_xp) + yBC_xp = 0.5*(1.-old_div(1.,b_xp)) xBC_ym = 0.5*a_ym xBC_yp = 0.5*a_yp/b_yp yBC_ym = 0.5*(1.-b_ym) - yBC_yp = 0.5*(1.-1./b_yp) + yBC_yp = 0.5*(1.-old_div(1.,b_yp)) sortindsfx = np.argsort(np.r_[np.arange(mesh.nFx)[fxm], np.arange(mesh.nFx)[fxp]]) sortindsfy = np.argsort(np.r_[np.arange(mesh.nFy)[fym], np.arange(mesh.nFy)[fyp]]) @@ -120,33 +127,33 @@ def getxBCyBC_CC(mesh, alpha, beta, gamma): h_ym, h_yp = mesh.hy[0]*np.ones_like(alpha_ym), mesh.hy[-1]*np.ones_like(alpha_yp) h_zm, h_zp = mesh.hz[0]*np.ones_like(alpha_zm), mesh.hz[-1]*np.ones_like(alpha_zp) - a_xm = gamma_xm/(0.5*alpha_xm-beta_xm/h_xm) - b_xm = (0.5*alpha_xm+beta_xm/h_xm)/(0.5*alpha_xm-beta_xm/h_xm) - a_xp = gamma_xp/(0.5*alpha_xp-beta_xp/h_xp) - b_xp = (0.5*alpha_xp+beta_xp/h_xp)/(0.5*alpha_xp-beta_xp/h_xp) + a_xm = old_div(gamma_xm,(0.5*alpha_xm-old_div(beta_xm,h_xm))) + b_xm = old_div((0.5*alpha_xm+old_div(beta_xm,h_xm)),(0.5*alpha_xm-old_div(beta_xm,h_xm))) + a_xp = old_div(gamma_xp,(0.5*alpha_xp-old_div(beta_xp,h_xp))) + b_xp = old_div((0.5*alpha_xp+old_div(beta_xp,h_xp)),(0.5*alpha_xp-old_div(beta_xp,h_xp))) - a_ym = gamma_ym/(0.5*alpha_ym-beta_ym/h_ym) - b_ym = (0.5*alpha_ym+beta_ym/h_ym)/(0.5*alpha_ym-beta_ym/h_ym) - a_yp = gamma_yp/(0.5*alpha_yp-beta_yp/h_yp) - b_yp = (0.5*alpha_yp+beta_yp/h_yp)/(0.5*alpha_yp-beta_yp/h_yp) + a_ym = old_div(gamma_ym,(0.5*alpha_ym-old_div(beta_ym,h_ym))) + b_ym = old_div((0.5*alpha_ym+old_div(beta_ym,h_ym)),(0.5*alpha_ym-old_div(beta_ym,h_ym))) + a_yp = old_div(gamma_yp,(0.5*alpha_yp-old_div(beta_yp,h_yp))) + b_yp = old_div((0.5*alpha_yp+old_div(beta_yp,h_yp)),(0.5*alpha_yp-old_div(beta_yp,h_yp))) - a_zm = gamma_zm/(0.5*alpha_zm-beta_zm/h_zm) - b_zm = (0.5*alpha_zm+beta_zm/h_zm)/(0.5*alpha_zm-beta_zm/h_zm) - a_zp = gamma_zp/(0.5*alpha_zp-beta_zp/h_zp) - b_zp = (0.5*alpha_zp+beta_zp/h_zp)/(0.5*alpha_zp-beta_zp/h_zp) + a_zm = old_div(gamma_zm,(0.5*alpha_zm-old_div(beta_zm,h_zm))) + b_zm = old_div((0.5*alpha_zm+old_div(beta_zm,h_zm)),(0.5*alpha_zm-old_div(beta_zm,h_zm))) + a_zp = old_div(gamma_zp,(0.5*alpha_zp-old_div(beta_zp,h_zp))) + b_zp = old_div((0.5*alpha_zp+old_div(beta_zp,h_zp)),(0.5*alpha_zp-old_div(beta_zp,h_zp))) xBC_xm = 0.5*a_xm xBC_xp = 0.5*a_xp/b_xp yBC_xm = 0.5*(1.-b_xm) - yBC_xp = 0.5*(1.-1./b_xp) + yBC_xp = 0.5*(1.-old_div(1.,b_xp)) xBC_ym = 0.5*a_ym xBC_yp = 0.5*a_yp/b_yp yBC_ym = 0.5*(1.-b_ym) - yBC_yp = 0.5*(1.-1./b_yp) + yBC_yp = 0.5*(1.-old_div(1.,b_yp)) xBC_zm = 0.5*a_zm xBC_zp = 0.5*a_zp/b_zp yBC_zm = 0.5*(1.-b_zm) - yBC_zp = 0.5*(1.-1./b_zp) + yBC_zp = 0.5*(1.-old_div(1.,b_zp)) sortindsfx = np.argsort(np.r_[np.arange(mesh.nFx)[fxm], np.arange(mesh.nFx)[fxp]]) sortindsfy = np.argsort(np.r_[np.arange(mesh.nFy)[fym], np.arange(mesh.nFy)[fyp]]) @@ -201,8 +208,8 @@ class Test1D_InhomogeneousMixed(Tests.OrderTest): sigma = np.ones(self.M.nC) - Mfrho = self.M.getFaceInnerProduct(1./sigma) - MfrhoI = self.M.getFaceInnerProduct(1./sigma, invMat=True) + Mfrho = self.M.getFaceInnerProduct(old_div(1.,sigma)) + MfrhoI = self.M.getFaceInnerProduct(old_div(1.,sigma), invMat=True) V = Utils.sdiag(self.M.vol) Div = V*self.M.faceDiv P_BC, B = self.M.getBCProjWF_simple() @@ -224,7 +231,7 @@ class Test1D_InhomogeneousMixed(Tests.OrderTest): def test_order(self): - print "==== Testing Mixed boudary conduction for CC-problem ====" + print("==== Testing Mixed boudary conduction for CC-problem ====") self.name = "1D" self.myTest = 'xc' self.orderTest() @@ -284,8 +291,8 @@ class Test2D_InhomogeneousMixed(Tests.OrderTest): sigma = np.ones(self.M.nC) - Mfrho = self.M.getFaceInnerProduct(1./sigma) - MfrhoI = self.M.getFaceInnerProduct(1./sigma, invMat=True) + Mfrho = self.M.getFaceInnerProduct(old_div(1.,sigma)) + MfrhoI = self.M.getFaceInnerProduct(old_div(1.,sigma), invMat=True) V = Utils.sdiag(self.M.vol) Div = V*self.M.faceDiv P_BC, B = self.M.getBCProjWF_simple() @@ -305,7 +312,7 @@ class Test2D_InhomogeneousMixed(Tests.OrderTest): def test_order(self): - print "==== Testing Mixed boudary conduction for CC-problem ====" + print("==== Testing Mixed boudary conduction for CC-problem ====") self.name = "2D" self.myTest = 'xc' self.orderTest() @@ -378,8 +385,8 @@ class Test3D_InhomogeneousMixed(Tests.OrderTest): sigma = np.ones(self.M.nC) - Mfrho = self.M.getFaceInnerProduct(1./sigma) - MfrhoI = self.M.getFaceInnerProduct(1./sigma, invMat=True) + Mfrho = self.M.getFaceInnerProduct(old_div(1.,sigma)) + MfrhoI = self.M.getFaceInnerProduct(old_div(1.,sigma), invMat=True) V = Utils.sdiag(self.M.vol) Div = V*self.M.faceDiv P_BC, B = self.M.getBCProjWF_simple() @@ -400,7 +407,7 @@ class Test3D_InhomogeneousMixed(Tests.OrderTest): def test_order(self): - print "==== Testing Mixed boudary conduction for CC-problem ====" + print("==== Testing Mixed boudary conduction for CC-problem ====") self.name = "3D" self.myTest = 'xc' self.orderTest() diff --git a/tests/mesh/test_TreeInterpolation.py b/tests/mesh/test_TreeInterpolation.py index 90860959..9782c92d 100644 --- a/tests/mesh/test_TreeInterpolation.py +++ b/tests/mesh/test_TreeInterpolation.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import numpy as np import unittest from SimPEG import Utils, Tests diff --git a/tests/mesh/test_TreeMesh.py b/tests/mesh/test_TreeMesh.py index afad27d1..4469371a 100644 --- a/tests/mesh/test_TreeMesh.py +++ b/tests/mesh/test_TreeMesh.py @@ -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 from SimPEG import Mesh, Tests from SimPEG.Mesh.TreeMesh import CellLookUpException import numpy as np @@ -12,13 +19,13 @@ class TestSimpleQuadTree(unittest.TestCase): nc = 8 h1 = np.random.rand(nc)*nc*0.5 + nc*0.5 h2 = np.random.rand(nc)*nc*0.5 + nc*0.5 - h = [hi/np.sum(hi) for hi in [h1, h2]] # normalize + h = [old_div(hi,np.sum(hi)) for hi in [h1, h2]] # normalize M = Mesh.TreeMesh(h) M._refineCell([0,0,0]) M._refineCell([0,0,1]) M.number() # M.plotGrid(showIt=True) - print M + print(M) assert M.nhFx == 2 assert M.nFx == 9 @@ -60,7 +67,7 @@ class TestSimpleQuadTree(unittest.TestCase): nc = 8 h1 = np.random.rand(nc)*nc*0.5 + nc*0.5 h2 = np.random.rand(nc)*nc*0.5 + nc*0.5 - h = [hi/np.sum(hi) for hi in [h1, h2]] # normalize + h = [old_div(hi,np.sum(hi)) for hi in [h1, h2]] # normalize M = Mesh.TreeMesh(h) M._refineCell([0,0,0]) M._refineCell([0,0,1]) @@ -138,7 +145,7 @@ class TestOcTree(unittest.TestCase): h1 = np.random.rand(nc)*nc*0.5 + nc*0.5 h2 = np.random.rand(nc)*nc*0.5 + nc*0.5 h3 = np.random.rand(nc)*nc*0.5 + nc*0.5 - h = [hi/np.sum(hi) for hi in [h1, h2, h3]] # normalize + h = [old_div(hi,np.sum(hi)) for hi in [h1, h2, h3]] # normalize M = Mesh.TreeMesh(h, levels=3) M._refineCell([0,0,0,0]) M._refineCell([0,0,0,1]) diff --git a/tests/mesh/test_TreeOperators.py b/tests/mesh/test_TreeOperators.py index c16f6b23..760bfddc 100644 --- a/tests/mesh/test_TreeOperators.py +++ b/tests/mesh/test_TreeOperators.py @@ -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 import unittest from SimPEG import Utils, Tests @@ -183,14 +190,14 @@ class TestTreeInnerProducts(Tests.OrderTest): Gc = self.M.gridCC if self.sigmaTest == 1: sigma = np.c_[call(sigma1, Gc)] - analytic = 647./360 # Found using sympy. + analytic = old_div(647.,360) # Found using sympy. elif self.sigmaTest == 3: sigma = np.r_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc)] - analytic = 37./12 # Found using sympy. + analytic = old_div(37.,12) # Found using sympy. elif self.sigmaTest == 6: sigma = np.c_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc), call(sigma4, Gc), call(sigma5, Gc), call(sigma6, Gc)] - analytic = 69881./21600 # Found using sympy. + analytic = old_div(69881.,21600) # Found using sympy. if self.location == 'edges': cart = lambda g: np.c_[call(ex, g), call(ey, g), call(ez, g)] @@ -328,13 +335,13 @@ class TestTreeInnerProducts2D(Tests.OrderTest): Gc = self.M.gridCC if self.sigmaTest == 1: sigma = np.c_[call(sigma1, Gc)] - analytic = 144877./360 # Found using sympy. z=5 + analytic = old_div(144877.,360) # Found using sympy. z=5 elif self.sigmaTest == 2: sigma = np.c_[call(sigma1, Gc), call(sigma2, Gc)] - analytic = 189959./120 # Found using sympy. z=5 + analytic = old_div(189959.,120) # Found using sympy. z=5 elif self.sigmaTest == 3: sigma = np.r_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc)] - analytic = 781427./360 # Found using sympy. z=5 + analytic = old_div(781427.,360) # Found using sympy. z=5 if self.location == 'edges': cart = lambda g: np.c_[call(ex, g), call(ey, g)] diff --git a/tests/mesh/test_basemesh.py b/tests/mesh/test_basemesh.py index 788314d4..fbd9aa73 100644 --- a/tests/mesh/test_basemesh.py +++ b/tests/mesh/test_basemesh.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import unittest import sys from SimPEG.Mesh.BaseMesh import BaseRectangularMesh diff --git a/tests/mesh/test_boundaryPoisson.py b/tests/mesh/test_boundaryPoisson.py index 1accb578..456edcb9 100644 --- a/tests/mesh/test_boundaryPoisson.py +++ b/tests/mesh/test_boundaryPoisson.py @@ -1,3 +1,9 @@ +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() import numpy as np import scipy.sparse as sp import unittest @@ -55,12 +61,12 @@ class Test1D_InhomogeneousDirichlet(Tests.OrderTest): #TODO: fix the null space solver = SolverCG(A, maxiter=1000) xc = solver * (rhs) - print 'ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print('ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs)) err = np.linalg.norm((xc-xc_ana), np.inf) elif self.myTest == 'xcJ': #TODO: fix the null space xc = Solver(A) * (rhs) - print np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print(np.linalg.norm(Utils.mkvc(A*xc) - rhs)) j = McI*(G*xc + P*phi_bc) err = np.linalg.norm((j-j_ana), np.inf) @@ -218,16 +224,16 @@ class Test1D_InhomogeneousNeumann(Tests.OrderTest): xc, info = sp.linalg.minres(A, rhs, tol = 1e-6) err = np.linalg.norm((xc-xc_ana), np.inf) if info > 0: - print 'Solve does not work well' - print 'ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print('Solve does not work well') + print('ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs)) elif self.myTest == 'xcJ': #TODO: fix the null space xc, info = sp.linalg.minres(A, rhs, tol = 1e-6) j = McI*(G*xc + P*phi_bc) err = np.linalg.norm((Pin*j-Pin*j_ana), np.inf) if info > 0: - print 'Solve does not work well' - print 'ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print('Solve does not work well') + print('ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs)) return err def test_orderJ(self): @@ -305,16 +311,16 @@ class Test2D_InhomogeneousNeumann(Tests.OrderTest): xc, info = sp.linalg.minres(A, rhs, tol = 1e-6) err = np.linalg.norm((xc-xc_ana), np.inf) if info > 0: - print 'Solve does not work well' - print 'ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print('Solve does not work well') + print('ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs)) elif self.myTest == 'xcJ': #TODO: fix the null space xc, info = sp.linalg.minres(A, rhs, tol = 1e-6) j = McI*(G*xc + P*phi_bc) err = np.linalg.norm((Pin*j-Pin*j_ana), np.inf) if info > 0: - print 'Solve does not work well' - print 'ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print('Solve does not work well') + print('ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs)) return err def test_orderJ(self): @@ -382,16 +388,16 @@ class Test1D_InhomogeneousMixed(Tests.OrderTest): xc, info = sp.linalg.minres(A, rhs, tol = 1e-6) err = np.linalg.norm((xc-xc_ana), np.inf) if info > 0: - print 'Solve does not work well' - print 'ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print('Solve does not work well') + print('ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs)) elif self.myTest == 'xcJ': #TODO: fix the null space xc, info = sp.linalg.minres(A, rhs, tol = 1e-6) j = McI*(G*xc + P*phi_bc) err = np.linalg.norm((Pin*j-Pin*j_ana), np.inf) if info > 0: - print 'Solve does not work well' - print 'ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print('Solve does not work well') + print('ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs)) return err def test_orderJ(self): @@ -469,16 +475,16 @@ class Test2D_InhomogeneousMixed(Tests.OrderTest): xc, info = sp.linalg.minres(A, rhs, tol = 1e-6) err = np.linalg.norm((xc-xc_ana), np.inf) if info > 0: - print 'Solve does not work well' - print 'ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print('Solve does not work well') + print('ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs)) elif self.myTest == 'xcJ': #TODO: fix the null space xc, info = sp.linalg.minres(A, rhs, tol = 1e-6) j = McI*(G*xc + P*phi_bc) err = np.linalg.norm((Pin*j-Pin*j_ana), np.inf) if info > 0: - print 'Solve does not work well' - print 'ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs) + print('Solve does not work well') + print('ACCURACY', np.linalg.norm(Utils.mkvc(A*xc) - rhs)) return err def test_orderJ(self): diff --git a/tests/mesh/test_cylMesh.py b/tests/mesh/test_cylMesh.py index c7cd44ae..0b485b5f 100644 --- a/tests/mesh/test_cylMesh.py +++ b/tests/mesh/test_cylMesh.py @@ -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 unittest import sys from SimPEG import * @@ -135,7 +142,7 @@ class TestCyl2DMesh(unittest.TestCase): def test_getInterpMatCartMesh_Cells(self): Mr = Mesh.TensorMesh([100,100,2], x0='CC0') - Mc = Mesh.CylMesh([np.ones(10)/5,1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) + Mc = Mesh.CylMesh([old_div(np.ones(10),5),1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) mc = np.arange(Mc.nC) xr = np.linspace(0,0.4,50) @@ -149,7 +156,7 @@ class TestCyl2DMesh(unittest.TestCase): def test_getInterpMatCartMesh_Cells2Nodes(self): Mr = Mesh.TensorMesh([100,100,2], x0='CC0') - Mc = Mesh.CylMesh([np.ones(10)/5,1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) + Mc = Mesh.CylMesh([old_div(np.ones(10),5),1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) mc = np.arange(Mc.nC) xr = np.linspace(0,0.4,50) @@ -163,7 +170,7 @@ class TestCyl2DMesh(unittest.TestCase): def test_getInterpMatCartMesh_Faces(self): Mr = Mesh.TensorMesh([100,100,2], x0='CC0') - Mc = Mesh.CylMesh([np.ones(10)/5,1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) + Mc = Mesh.CylMesh([old_div(np.ones(10),5),1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) Pf = Mc.getInterpolationMatCartMesh(Mr, 'F') mf = np.ones(Mc.nF) @@ -194,7 +201,7 @@ class TestCyl2DMesh(unittest.TestCase): def test_getInterpMatCartMesh_Faces2Edges(self): Mr = Mesh.TensorMesh([100,100,2], x0='CC0') - Mc = Mesh.CylMesh([np.ones(10)/5,1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) + Mc = Mesh.CylMesh([old_div(np.ones(10),5),1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) Pf2e = Mc.getInterpolationMatCartMesh(Mr, 'F', locTypeTo='E') mf = np.ones(Mc.nF) @@ -225,7 +232,7 @@ class TestCyl2DMesh(unittest.TestCase): def test_getInterpMatCartMesh_Edges(self): Mr = Mesh.TensorMesh([100,100,2], x0='CC0') - Mc = Mesh.CylMesh([np.ones(10)/5,1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) + Mc = Mesh.CylMesh([old_div(np.ones(10),5),1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) Pe = Mc.getInterpolationMatCartMesh(Mr, 'E') me = np.ones(Mc.nE) @@ -256,7 +263,7 @@ class TestCyl2DMesh(unittest.TestCase): def test_getInterpMatCartMesh_Edges2Faces(self): Mr = Mesh.TensorMesh([100,100,2], x0='CC0') - Mc = Mesh.CylMesh([np.ones(10)/5,1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) + Mc = Mesh.CylMesh([old_div(np.ones(10),5),1,10],x0='0C0',cartesianOrigin=[-0.2,-0.2,0]) Pe2f = Mc.getInterpolationMatCartMesh(Mr, 'E', locTypeTo='F') me = np.ones(Mc.nE) @@ -302,7 +309,7 @@ class TestFaceDiv2D(Tests.OrderTest): funR = lambda r, z: np.sin(2.*np.pi*r) funZ = lambda r, z: np.sin(2.*np.pi*z) - sol = lambda r, t, z: (2*np.pi*r*np.cos(2*np.pi*r) + np.sin(2*np.pi*r))/r + 2*np.pi*np.cos(2*np.pi*z) + sol = lambda r, t, z: old_div((2*np.pi*r*np.cos(2*np.pi*r) + np.sin(2*np.pi*r)),r) + 2*np.pi*np.cos(2*np.pi*z) Fc = cylF2(self.M, funR, funZ) Fc = np.c_[Fc[:,0],np.zeros(self.M.nF),Fc[:,1]] @@ -339,7 +346,7 @@ class TestEdgeCurl2D(Tests.OrderTest): funT = lambda r, t, z: np.sin(2.*np.pi*z) solR = lambda r, z: -2.0*np.pi*np.cos(2.0*np.pi*z) - solZ = lambda r, z: np.sin(2.0*np.pi*z)/r + solZ = lambda r, z: old_div(np.sin(2.0*np.pi*z),r) E = call3(funT, self.M.gridEy) @@ -466,7 +473,7 @@ class TestCyl3DMesh(unittest.TestCase): def test_vectorsN(self): v = np.r_[0, 1, 2, 2.5] self.assertTrue(np.linalg.norm((v-self.mesh.vectorNx)) == 0) - v = np.r_[np.pi/2, 1.5*np.pi] + v = np.r_[old_div(np.pi,2), 1.5*np.pi] self.assertTrue(np.linalg.norm((v-self.mesh.vectorNy)) == 0) v = np.r_[0, 2, 3] self.assertTrue(np.linalg.norm((v-self.mesh.vectorNz)) == 0) diff --git a/tests/mesh/test_innerProduct.py b/tests/mesh/test_innerProduct.py index cebecf2b..7e66d672 100644 --- a/tests/mesh/test_innerProduct.py +++ b/tests/mesh/test_innerProduct.py @@ -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 import unittest from SimPEG import Utils, Tests @@ -28,14 +35,14 @@ class TestInnerProducts(Tests.OrderTest): Gc = self.M.gridCC if self.sigmaTest == 1: sigma = np.c_[call(sigma1, Gc)] - analytic = 647./360 # Found using sympy. + analytic = old_div(647.,360) # Found using sympy. elif self.sigmaTest == 3: sigma = np.r_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc)] - analytic = 37./12 # Found using sympy. + analytic = old_div(37.,12) # Found using sympy. elif self.sigmaTest == 6: sigma = np.c_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc), call(sigma4, Gc), call(sigma5, Gc), call(sigma6, Gc)] - analytic = 69881./21600 # Found using sympy. + analytic = old_div(69881.,21600) # Found using sympy. if self.location == 'edges': cart = lambda g: np.c_[call(ex, g), call(ey, g), call(ez, g)] @@ -173,13 +180,13 @@ class TestInnerProducts2D(Tests.OrderTest): Gc = self.M.gridCC if self.sigmaTest == 1: sigma = np.c_[call(sigma1, Gc)] - analytic = 144877./360 # Found using sympy. z=5 + analytic = old_div(144877.,360) # Found using sympy. z=5 elif self.sigmaTest == 2: sigma = np.c_[call(sigma1, Gc), call(sigma2, Gc)] - analytic = 189959./120 # Found using sympy. z=5 + analytic = old_div(189959.,120) # Found using sympy. z=5 elif self.sigmaTest == 3: sigma = np.r_[call(sigma1, Gc), call(sigma2, Gc), call(sigma3, Gc)] - analytic = 781427./360 # Found using sympy. z=5 + analytic = old_div(781427.,360) # Found using sympy. z=5 if self.location == 'edges': cart = lambda g: np.c_[call(ex, g), call(ey, g)] @@ -312,12 +319,12 @@ class TestInnerProducts1D(Tests.OrderTest): Gc = self.M.gridCC sigma = call(sigma1, Gc) - analytic = 128011./5 # Found using sympy. y=12, z=5 + analytic = old_div(128011.,5) # Found using sympy. y=12, z=5 if self.location == 'faces': F = call(ex, self.M.gridFx) if self.invProp: - A = self.M.getFaceInnerProduct(1/sigma, invProp=True) + A = self.M.getFaceInnerProduct(old_div(1,sigma), invProp=True) else: A = self.M.getFaceInnerProduct(sigma) numeric = F.T.dot(A.dot(F)) diff --git a/tests/mesh/test_innerProductDerivs.py b/tests/mesh/test_innerProductDerivs.py index 41ba5dcd..a0b9f037 100644 --- a/tests/mesh/test_innerProductDerivs.py +++ b/tests/mesh/test_innerProductDerivs.py @@ -1,3 +1,9 @@ +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() import numpy as np import unittest from SimPEG import * @@ -21,7 +27,7 @@ class TestInnerProductsDerivs(unittest.TestCase): M = mesh.getFaceInnerProduct(sig, invProp=invProp, invMat=invMat) Md = mesh.getFaceInnerProductDeriv(sig, invProp=invProp, invMat=invMat, doFast=fast) return M*v, Md(v) - print meshType, 'Face', h, rep, fast, ('harmonic' if invProp and invMat else 'standard') + print(meshType, 'Face', h, rep, fast, ('harmonic' if invProp and invMat else 'standard')) return Tests.checkDerivative(fun, sig, num=5, plotIt=False) def doTestEdge(self, h, rep, fast, meshType, invProp=False, invMat=False): @@ -40,7 +46,7 @@ class TestInnerProductsDerivs(unittest.TestCase): M = mesh.getEdgeInnerProduct(sig, invProp=invProp, invMat=invMat) Md = mesh.getEdgeInnerProductDeriv(sig, invProp=invProp, invMat=invMat, doFast=fast) return M*v, Md(v) - print meshType, 'Edge', h, rep, fast, ('harmonic' if invProp and invMat else 'standard') + print(meshType, 'Edge', h, rep, fast, ('harmonic' if invProp and invMat else 'standard')) return Tests.checkDerivative(fun, sig, num=5, plotIt=False) def test_FaceIP_1D_float(self): diff --git a/tests/mesh/test_interpolation.py b/tests/mesh/test_interpolation.py index a6804950..935cf865 100644 --- a/tests/mesh/test_interpolation.py +++ b/tests/mesh/test_interpolation.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import numpy as np import unittest from SimPEG.Utils import mkvc diff --git a/tests/mesh/test_operators.py b/tests/mesh/test_operators.py index 3b99345c..b6c1174a 100644 --- a/tests/mesh/test_operators.py +++ b/tests/mesh/test_operators.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import numpy as np import unittest from SimPEG.Tests import OrderTest diff --git a/tests/mesh/test_tensorMesh.py b/tests/mesh/test_tensorMesh.py index dd5f461c..a45263d5 100644 --- a/tests/mesh/test_tensorMesh.py +++ b/tests/mesh/test_tensorMesh.py @@ -1,3 +1,9 @@ +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() import numpy as np import unittest from SimPEG.Mesh import TensorMesh @@ -61,9 +67,9 @@ class BasicTensorMeshTests(unittest.TestCase): self.assertTrue(M.nC == 1) def test_printing(self): - print TensorMesh([10]) - print TensorMesh([10,10]) - print TensorMesh([10,10,10]) + print(TensorMesh([10])) + print(TensorMesh([10,10])) + print(TensorMesh([10,10,10])) def test_centering(self): M1d = TensorMesh([10], 'C') diff --git a/tests/mt/__init__.py b/tests/mt/__init__.py index 420388ef..1ed1862b 100644 --- a/tests/mt/__init__.py +++ b/tests/mt/__init__.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() import os import glob import unittest diff --git a/tests/mt/test_ApparentResistivityAnalytic.py b/tests/mt/test_ApparentResistivityAnalytic.py index 2a3b1ba9..04d530b2 100644 --- a/tests/mt/test_ApparentResistivityAnalytic.py +++ b/tests/mt/test_ApparentResistivityAnalytic.py @@ -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 unittest from SimPEG import * from SimPEG import MT @@ -5,8 +12,8 @@ from SimPEG import MT TOL = 1e-6 def appResPhs(freq,z): - app_res = ((1./(8e-7*np.pi**2))/freq)*np.abs(z)**2 - app_phs = np.arctan2(-z.imag,z.real)*(180/np.pi) + app_res = (old_div((old_div(1.,(8e-7*np.pi**2))),freq))*np.abs(z)**2 + app_phs = np.arctan2(-z.imag,z.real)*(old_div(180,np.pi)) return app_res, app_phs def appResNorm(sigmaHalf): @@ -21,13 +28,13 @@ def appResNorm(sigmaHalf): Z = [] for freq in freqs: Ed, Eu, Hd, Hu = MT.Utils.getEHfields(m1d,sigma,freq,np.array([200])) - Z.append((Ed + Eu)/(Hd + Hu)) + Z.append(old_div((Ed + Eu),(Hd + Hu))) Zarr = np.concatenate(Z) app_r, app_p = appResPhs(freqs,Zarr) - return np.linalg.norm(np.abs(app_r - np.ones(nFreq)/sigmaHalf)) / np.log10(sigmaHalf) + return old_div(np.linalg.norm(np.abs(app_r - old_div(np.ones(nFreq),sigmaHalf))), np.log10(sigmaHalf)) class TestAnalytics(unittest.TestCase): diff --git a/tests/mt/test_Problem1D_againstAnalyticHalfspace.py b/tests/mt/test_Problem1D_againstAnalyticHalfspace.py index dcfb7978..2a0ca034 100644 --- a/tests/mt/test_Problem1D_againstAnalyticHalfspace.py +++ b/tests/mt/test_Problem1D_againstAnalyticHalfspace.py @@ -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 unittest import SimPEG as simpeg from SimPEG import MT @@ -44,8 +51,8 @@ def setupSurvey(sigmaHalf,tD=True): def getAppResPhs(MTdata): # Make impedance def appResPhs(freq,z): - app_res = ((1./(8e-7*np.pi**2))/freq)*np.abs(z)**2 - app_phs = np.arctan2(z.imag,z.real)*(180/np.pi) + app_res = (old_div((old_div(1.,(8e-7*np.pi**2))),freq))*np.abs(z)**2 + app_phs = np.arctan2(z.imag,z.real)*(old_div(180,np.pi)) return app_res, app_phs zList = [] for src in MTdata.survey.srcList: @@ -75,7 +82,7 @@ def appRes_TotalFieldNorm(sigmaHalf): # Calculate the app res and phs app_r = np.array(getAppResPhs(data))[:,0] - return np.linalg.norm(np.abs(app_r - np.ones(survey.nFreq)/sigmaHalf)*sigmaHalf) + return np.linalg.norm(np.abs(app_r - old_div(np.ones(survey.nFreq),sigmaHalf))*sigmaHalf) def appPhs_TotalFieldNorm(sigmaHalf): @@ -93,7 +100,7 @@ def appPhs_TotalFieldNorm(sigmaHalf): # Calculate the app phs app_p = np.array(getAppResPhs(data))[:,1] - return np.linalg.norm(np.abs(app_p - np.ones(survey.nFreq)*45)/ 45) + return np.linalg.norm(old_div(np.abs(app_p - np.ones(survey.nFreq)*45), 45)) def appRes_psFieldNorm(sigmaHalf): @@ -111,7 +118,7 @@ def appRes_psFieldNorm(sigmaHalf): # Calculate the app res and phs app_r = np.array(getAppResPhs(data))[:,0] - return np.linalg.norm(np.abs(app_r - np.ones(survey.nFreq)/sigmaHalf)*sigmaHalf) + return np.linalg.norm(np.abs(app_r - old_div(np.ones(survey.nFreq),sigmaHalf))*sigmaHalf) def appPhs_psFieldNorm(sigmaHalf): @@ -129,7 +136,7 @@ def appPhs_psFieldNorm(sigmaHalf): # Calculate the app phs app_p = np.array(getAppResPhs(data))[:,1] - return np.linalg.norm(np.abs(app_p - np.ones(survey.nFreq)*45)/ 45) + return np.linalg.norm(old_div(np.abs(app_p - np.ones(survey.nFreq)*45), 45)) class TestAnalytics(unittest.TestCase): diff --git a/tests/mt/test_Problem1D_totalDvsPSvsAnalytic.py b/tests/mt/test_Problem1D_totalDvsPSvsAnalytic.py index 2a2e82fd..dfdbcac1 100644 --- a/tests/mt/test_Problem1D_totalDvsPSvsAnalytic.py +++ b/tests/mt/test_Problem1D_totalDvsPSvsAnalytic.py @@ -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 unittest import SimPEG as simpeg from SimPEG import MT @@ -50,8 +57,8 @@ def setupSurvey(sigmaHalf,tD=True): def getAppResPhs(MTdata): # Make impedance def appResPhs(freq,z): - app_res = ((1./(8e-7*np.pi**2))/freq)*np.abs(z)**2 - app_phs = np.arctan2(z.imag,z.real)*(180/np.pi) + app_res = (old_div((old_div(1.,(8e-7*np.pi**2))),freq))*np.abs(z)**2 + app_phs = np.arctan2(z.imag,z.real)*(old_div(180,np.pi)) return app_res, app_phs zList = [] for src in MTdata.survey.srcList: @@ -76,7 +83,7 @@ def calculateAnalyticSolution(srcList,mesh,model): # Scale the solution # anaE = (anaEtemp/anaEtemp[-1])#.conj() # anaH = (anaHtemp/anaEtemp[-1])#.conj() - anaZ = anaE/anaH + anaZ = old_div(anaE,anaH) for rx in src.rxList: data1D[src,rx] = getattr(anaZ, rx.projComp) return data1D @@ -94,7 +101,7 @@ def dataMis_AnalyticTotalDomain(sigmaHalf): # dataTDObj = MT.DataMT.DataMT(surveyTD, surveyTD.dpred(sigma)) dataTD = surveyTD.dpred(sigma) dataAna = simpeg.mkvc(dataAnaObj) - return np.all((dataTD - dataAna)/dataAna < 2.) + return np.all(old_div((dataTD - dataAna),dataAna) < 2.) # surveyTD.dtrue = -simpeg.mkvc(dataAna,2) # surveyTD.dobs = -simpeg.mkvc(dataAna,2) # surveyTD.Wd = np.ones(surveyTD.dtrue.shape) #/(np.abs(surveyTD.dtrue)*0.01) @@ -117,7 +124,7 @@ def dataMis_AnalyticPrimarySecondary(sigmaHalf): dataPS = surveyPS.dpred(sigmaPS) dataAna = simpeg.mkvc(dataAnaObj) - return np.all((dataPS - dataAna)/dataAna < 2.) + return np.all(old_div((dataPS - dataAna),dataAna) < 2.) diff --git a/tests/mt/test_Problem3D_againstAnalytic.py b/tests/mt/test_Problem3D_againstAnalytic.py index 602dbaeb..e834bded 100644 --- a/tests/mt/test_Problem3D_againstAnalytic.py +++ b/tests/mt/test_Problem3D_againstAnalytic.py @@ -1,3 +1,12 @@ +from __future__ import print_function +from __future__ import division +from __future__ import unicode_literals +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import str +from past.utils import old_div # Test functions from glob import glob import numpy as np, sys, os, time, scipy, subprocess @@ -146,8 +155,8 @@ def setupSimpegMTfwd_eForm_ps(inputSetup,comp='Imp',singleFreq=False,expMap=True def getAppResPhs(MTdata): # Make impedance def appResPhs(freq,z): - app_res = ((1./(8e-7*np.pi**2))/freq)*np.abs(z)**2 - app_phs = np.arctan2(z.imag,z.real)*(180/np.pi) + app_res = (old_div((old_div(1.,(8e-7*np.pi**2))),freq))*np.abs(z)**2 + app_phs = np.arctan2(z.imag,z.real)*(old_div(180,np.pi)) return app_res, app_phs recData = MTdata.toRecArray('Complex') return appResPhs(recData['freq'],recData['zxy']), appResPhs(recData['freq'],recData['zyx']) @@ -155,7 +164,7 @@ def getAppResPhs(MTdata): def JvecAdjointTest(inputSetup,comp='All',freq=False): (M, freqs, sig, sigBG, rx_loc) = inputSetup survey, problem = setupSimpegMTfwd_eForm_ps(inputSetup,comp='All',singleFreq=freq) - print 'Adjoint test of eForm primary/secondary for {:s} comp at {:s}\n'.format(comp,str(survey.freqs)) + print('Adjoint test of eForm primary/secondary for {:s} comp at {:s}\n'.format(comp,str(survey.freqs))) m = sig u = problem.fields(m) @@ -167,15 +176,15 @@ def JvecAdjointTest(inputSetup,comp='All',freq=False): vJw = v.ravel().dot(problem.Jvec(m, w, u)) wJtv = w.ravel().dot(problem.Jtvec(m, v, u)) tol = np.max([TOL*(10**int(np.log10(np.abs(vJw)))),FLR]) - print ' vJw wJtv vJw - wJtv tol abs(vJw - wJtv) < tol' - print vJw, wJtv, vJw - wJtv, tol, np.abs(vJw - wJtv) < tol + print(' vJw wJtv vJw - wJtv tol abs(vJw - wJtv) < tol') + print(vJw, wJtv, vJw - wJtv, tol, np.abs(vJw - wJtv) < tol) return np.abs(vJw - wJtv) < tol # Test the Jvec derivative def DerivJvecTest(inputSetup,comp='All',freq=False,expMap=True): (M, freqs, sig, sigBG, rx_loc) = inputSetup survey, problem = setupSimpegMTfwd_eForm_ps(inputSetup,comp=comp,singleFreq=freq,expMap=expMap) - print 'Derivative test of Jvec for eForm primary/secondary for {:s} comp at {:s}\n'.format(comp,survey.freqs) + print('Derivative test of Jvec for eForm primary/secondary for {:s} comp at {:s}\n'.format(comp,survey.freqs)) # problem.mapping = simpeg.Maps.ExpMap(problem.mesh) # problem.sigmaPrimary = np.log(sigBG) x0 = np.log(sigBG) @@ -192,7 +201,7 @@ def DerivJvecTest(inputSetup,comp='All',freq=False,expMap=True): def DerivProjfieldsTest(inputSetup,comp='All',freq=False): survey, problem = setupSimpegMTfwd_eForm_ps(inputSetup,comp,freq) - print 'Derivative test of data projection for eFormulation primary/secondary\n\n' + print('Derivative test of data projection for eFormulation primary/secondary\n\n') # problem.mapping = simpeg.Maps.ExpMap(problem.mesh) # Initate things for the derivs Test src = survey.srcList[0] @@ -203,13 +212,13 @@ def DerivProjfieldsTest(inputSetup,comp='All',freq=False): u0 = np.vstack((simpeg.mkvc(u0x,2),simpeg.mkvc(u0y,2))) f0 = problem.fieldsPair(survey.mesh,survey) # u0 = np.hstack((simpeg.mkvc(u0_px,2),simpeg.mkvc(u0_py,2))) - f0[src,'e_pxSolution'] = u0[:len(u0)/2]#u0x - f0[src,'e_pySolution'] = u0[len(u0)/2::]#u0y + f0[src,'e_pxSolution'] = u0[:old_div(len(u0),2)]#u0x + f0[src,'e_pySolution'] = u0[old_div(len(u0),2)::]#u0y def fun(u): f = problem.fieldsPair(survey.mesh,survey) - f[src,'e_pxSolution'] = u[:len(u)/2] - f[src,'e_pySolution'] = u[len(u)/2::] + f[src,'e_pxSolution'] = u[:old_div(len(u),2)] + f[src,'e_pySolution'] = u[old_div(len(u),2)::] return rx.eval(src,survey.mesh,f), lambda t: rx.evalDeriv(src,survey.mesh,f0,simpeg.mkvc(t,2)) return simpeg.Tests.checkDerivative(fun, u0, num=3, plotIt=False, eps=FLR) @@ -221,15 +230,15 @@ def appResPhsHalfspace_eFrom_ps_Norm(sigmaHalf,appR=True,expMap=False): label = 'phase' # Make the survey and the problem survey, problem = setupSimpegMTfwd_eForm_ps(halfSpace(sigmaHalf),expMap=expMap) - print 'Apperent {:s} test of eFormulation primary/secondary at {:g}\n\n'.format(label,sigmaHalf) + print('Apperent {:s} test of eFormulation primary/secondary at {:g}\n\n'.format(label,sigmaHalf)) data = problem.dataPair(survey,survey.dpred(problem.curModel)) # Calculate the app phs app_rpxy, app_rpyx = np.array(getAppResPhs(data)) if appR: - return np.all(np.abs(app_rpxy[0,:] - 1./sigmaHalf) * sigmaHalf < .4) + return np.all(np.abs(app_rpxy[0,:] - old_div(1.,sigmaHalf)) * sigmaHalf < .4) else: - return np.all(np.abs(app_rpxy[1,:] + 135) / 135 < .4) + return np.all(old_div(np.abs(app_rpxy[1,:] + 135), 135) < .4) class TestAnalytics(unittest.TestCase): diff --git a/tests/utils/__init__.py b/tests/utils/__init__.py index 38d84328..6d1d3c1c 100644 --- a/tests/utils/__init__.py +++ b/tests/utils/__init__.py @@ -1,3 +1,9 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from future import standard_library +standard_library.install_aliases() if __name__ == '__main__': import os import glob diff --git a/tests/utils/test_Zero.py b/tests/utils/test_Zero.py index 7b3c6e5d..be3b442c 100644 --- a/tests/utils/test_Zero.py +++ b/tests/utils/test_Zero.py @@ -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 unittest from SimPEG.Utils import Zero, Identity, sdiag, mkvc from SimPEG import np, sp @@ -19,7 +26,7 @@ class Tests(unittest.TestCase): assert z - 3 -z == -3 assert 3*z == 0 assert z*3 == 0 - assert z/3 == 0 + assert old_div(z,3) == 0 a = 1 a += z @@ -27,7 +34,7 @@ class Tests(unittest.TestCase): a = 1 a += z assert a == 1 - self.assertRaises(ZeroDivisionError, lambda:3/z) + self.assertRaises(ZeroDivisionError, lambda:old_div(3,z)) assert mkvc(z) == 0 assert sdiag(z)*a == 0 @@ -68,12 +75,12 @@ class Tests(unittest.TestCase): assert 3 - -o == 4 assert 3 - o == 2 - assert o/2 == 0 - assert o/2. == 0.5 - assert -o/2 == -1 - assert -o/2. == -0.5 - assert 2/o == 2 - assert 2/-o == -2 + assert old_div(o,2) == 0 + assert old_div(o,2.) == 0.5 + assert old_div(-o,2) == -1 + assert old_div(-o,2.) == -0.5 + assert old_div(2,o) == 2 + assert old_div(2,-o) == -2 def test_mat_one(self): @@ -87,9 +94,9 @@ class Tests(unittest.TestCase): check(o * S, [[2,0],[0,3]]) check(S * -o, [[-2,0],[0,-3]]) check(-o * S, [[-2,0],[0,-3]]) - check(S/o, [[2,0],[0,3]]) - check(S/-o, [[-2,0],[0,-3]]) - self.assertRaises(NotImplementedError, lambda:o/S) + check(old_div(S,o), [[2,0],[0,3]]) + check(old_div(S,-o), [[-2,0],[0,-3]]) + self.assertRaises(NotImplementedError, lambda:old_div(o,S)) check(S + o, [[3,0],[0,4]]) check(o + S, [[3,0],[0,4]]) @@ -114,10 +121,10 @@ class Tests(unittest.TestCase): assert np.all(1+n == o+n) assert np.all(n-1 == n-o) assert np.all(1-n == o-n) - assert np.all(n/1 == n/o) - assert np.all(n/-1 == n/-o) - assert np.all(1/n == o/n) - assert np.all(-1/n == -o/n) + assert np.all(old_div(n,1) == old_div(n,o)) + assert np.all(old_div(n,-1) == old_div(n,-o)) + assert np.all(old_div(1,n) == old_div(o,n)) + assert np.all(old_div(-1,n) == old_div(-o,n)) assert np.all(n*1 == n*o) assert np.all(n*-1 == n*-o) assert np.all(1*n == o*n) diff --git a/tests/utils/test_coordutils.py b/tests/utils/test_coordutils.py index 24f8451c..abd79286 100644 --- a/tests/utils/test_coordutils.py +++ b/tests/utils/test_coordutils.py @@ -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 unittest, os import numpy as np from SimPEG import Utils @@ -9,11 +16,11 @@ class coorUtilsTest(unittest.TestCase): def test_rotationMatrixFromNormals(self): np.random.seed(0) v0 = np.random.rand(3) - v0 *= 1./np.linalg.norm(v0) + v0 *= old_div(1.,np.linalg.norm(v0)) np.random.seed(5) v1 = np.random.rand(3) - v1 *= 1./np.linalg.norm(v1) + v1 *= old_div(1.,np.linalg.norm(v1)) Rf = Utils.coordutils.rotationMatrixFromNormals(v0,v1) Ri = Utils.coordutils.rotationMatrixFromNormals(v1,v0) @@ -24,11 +31,11 @@ class coorUtilsTest(unittest.TestCase): def test_rotatePointsFromNormals(self): np.random.seed(10) v0 = np.random.rand(3) - v0*= 1./np.linalg.norm(v0) + v0*= old_div(1.,np.linalg.norm(v0)) np.random.seed(15) v1 = np.random.rand(3) - v1*= 1./np.linalg.norm(v1) + v1*= old_div(1.,np.linalg.norm(v1)) v2 = Utils.mkvc(Utils.coordutils.rotatePointsFromNormals(Utils.mkvc(v0,2).T,v0,v1)) @@ -37,11 +44,11 @@ class coorUtilsTest(unittest.TestCase): def test_rotateMatrixFromNormals(self): np.random.seed(20) n0 = np.random.rand(3) - n0 *= 1./np.linalg.norm(n0) + n0 *= old_div(1.,np.linalg.norm(n0)) np.random.seed(25) n1 = np.random.rand(3) - n1 *= 1./np.linalg.norm(n1) + n1 *= old_div(1.,np.linalg.norm(n1)) np.random.seed(30) scale = np.random.rand(100,1) @@ -49,7 +56,7 @@ class coorUtilsTest(unittest.TestCase): XYZ1 = scale * n1 XYZ2 = Utils.coordutils.rotatePointsFromNormals(XYZ0,n0,n1) - self.assertTrue(np.linalg.norm(Utils.mkvc(XYZ1) - Utils.mkvc(XYZ2))/np.linalg.norm(Utils.mkvc(XYZ1)) < tol) + self.assertTrue(old_div(np.linalg.norm(Utils.mkvc(XYZ1) - Utils.mkvc(XYZ2)),np.linalg.norm(Utils.mkvc(XYZ1))) < tol) if __name__ == '__main__': unittest.main() diff --git a/tests/utils/test_utils.py b/tests/utils/test_utils.py index fe9e07c4..684f2490 100644 --- a/tests/utils/test_utils.py +++ b/tests/utils/test_utils.py @@ -1,3 +1,12 @@ +from __future__ import unicode_literals +from __future__ import print_function +from __future__ import division +from __future__ import absolute_import +from builtins import int +from future import standard_library +standard_library.install_aliases() +from builtins import range +from builtins import object import unittest from SimPEG.Utils import * from SimPEG import Mesh, np, sp @@ -220,7 +229,7 @@ class TestSequenceFunctions(unittest.TestCase): def test_isScalar(self): self.assertTrue(isScalar(1.)) self.assertTrue(isScalar(1)) - self.assertTrue(isScalar(long(1))) + self.assertTrue(isScalar(int(1))) self.assertTrue(isScalar(np.r_[1.])) self.assertTrue(isScalar(np.r_[1]))