From 45f5906554729cd456f94c584a44d35ac6cd2efa Mon Sep 17 00:00:00 2001 From: Cody Date: Thu, 21 Jul 2016 19:04:48 +0000 Subject: [PATCH] Migrated `%` string formating --- SimPEG/DCIP/DCIPUtils.py | 14 ++--- SimPEG/Directives.py | 28 +++++----- SimPEG/EM/FDEM/FieldsFDEM.py | 16 +++--- SimPEG/EM/FDEM/RxFDEM.py | 4 +- SimPEG/EM/Static/DC/FieldsDC.py | 6 +- SimPEG/EM/Static/DC/FieldsDC_2D.py | 6 +- SimPEG/EM/Static/DC/ProblemDC.py | 4 +- SimPEG/EM/Static/DC/ProblemDC_2D.py | 4 +- SimPEG/EM/Static/IP/ProblemIP.py | 4 +- SimPEG/EM/Static/SIP/ProblemSIP.py | 6 +- SimPEG/EM/TDEM/BaseTDEM.py | 20 +++---- SimPEG/EM/Utils/testingUtils.py | 4 +- .../Examples/EM_Schenkel_Morrison_Casing.py | 2 +- .../Examples/Mesh_Operators_CahnHilliard.py | 2 +- SimPEG/Examples/Mesh_QuadTree_FaceDiv.py | 6 +- SimPEG/Examples/__init__.py | 16 +++--- SimPEG/FLOW/Richards/Empirical.py | 2 +- SimPEG/FLOW/Richards/RichardsProblem.py | 2 +- SimPEG/Fields.py | 8 +-- SimPEG/Maps.py | 14 ++--- SimPEG/Mesh/BaseMesh.py | 2 +- SimPEG/Mesh/CurvilinearMesh.py | 4 +- SimPEG/Mesh/InnerProducts.py | 2 +- SimPEG/Mesh/MeshIO.py | 4 +- SimPEG/Mesh/TensorMesh.py | 8 +-- SimPEG/Mesh/TreeMesh.py | 8 +-- SimPEG/Mesh/View.py | 16 +++--- SimPEG/Optimization.py | 6 +- SimPEG/Problem.py | 2 +- SimPEG/PropMaps.py | 56 +++++++++---------- SimPEG/Survey.py | 12 ++-- SimPEG/Tests.py | 16 +++--- SimPEG/Utils/SolverUtils.py | 2 +- SimPEG/Utils/codeutils.py | 30 +++++----- SimPEG/Utils/curvutils.py | 2 +- SimPEG/Utils/matutils.py | 2 +- SimPEG/Utils/modelutils.py | 4 +- docs/conf.py | 2 +- docs/simpegdocs.py | 2 +- tests/base/test_regularization.py | 10 ++-- tests/docs/test_docs.py | 6 +- .../inverse/adjoint/test_FDEM_adjointEB.py | 2 +- .../inverse/adjoint/test_FDEM_adjointHJ.py | 2 +- .../fdem/inverse/derivs/test_FDEM_derivs.py | 2 +- tests/em/tdem/test_TDEM_forward_Analytic.py | 2 +- tests/examples/test_examples.py | 2 +- tests/flow/test_Richards.py | 6 +- 47 files changed, 190 insertions(+), 190 deletions(-) diff --git a/SimPEG/DCIP/DCIPUtils.py b/SimPEG/DCIP/DCIPUtils.py index 8e1ca5e9..5fc75d35 100644 --- a/SimPEG/DCIP/DCIPUtils.py +++ b/SimPEG/DCIP/DCIPUtils.py @@ -476,7 +476,7 @@ def writeUBC_DCobs(fileName, DCsurvey, dim, surveyType, iptype = 0): fid.write('! ' + surveyType + ' FORMAT\n') if iptype!=0: - fid.write('IPTYPE=%i\n'%iptype) + fid.write('IPTYPE={0:d}\n'.format(iptype)) else: fid.write('! ' + stype + ' FORMAT\n') @@ -512,7 +512,7 @@ def writeUBC_DCobs(fileName, DCsurvey, dim, surveyType, iptype = 0): if surveyType == 'SURFACE': - fid.writelines("%f " % ii for ii in mkvc(tx[0,:])) + fid.writelines("{0:f} ".format(ii) for ii in mkvc(tx[0,:])) M = M[:,0] N = N[:,0] @@ -521,7 +521,7 @@ def writeUBC_DCobs(fileName, DCsurvey, dim, surveyType, iptype = 0): # Flip sign for z-elevation to depth tx[2::2,:] = -tx[2::2,:] - fid.writelines("%e " % ii for ii in mkvc(tx[::2,:])) + fid.writelines("{0:e} ".format(ii) for ii in mkvc(tx[::2,:])) M = M[:,0::2] N = N[:,0::2] @@ -529,22 +529,22 @@ def writeUBC_DCobs(fileName, DCsurvey, dim, surveyType, iptype = 0): M[:,1::2] = -M[:,1::2] N[:,1::2] = -N[:,1::2] - fid.write('%i\n'% nD) + fid.write('{0:d}\n'.format(nD)) np.savetxt(fid, np.c_[ M, N , DCsurvey.dobs[count:count+nD], DCsurvey.std[count:count+nD] ], fmt='%f',delimiter=' ',newline='\n') if dim=='3D': if surveyType == 'SURFACE': - fid.writelines("%e " % ii for ii in mkvc(tx[0:2,:])) + fid.writelines("{0:e} ".format(ii) for ii in mkvc(tx[0:2,:])) M = M[:,0:2] N = N[:,0:2] if surveyType == 'GENERAL': - fid.writelines("%e " % ii for ii in mkvc(tx[0:3,:])) + fid.writelines("{0:e} ".format(ii) for ii in mkvc(tx[0:3,:])) - fid.write('%i\n'% nD) + fid.write('{0:d}\n'.format(nD)) np.savetxt(fid, np.c_[ M, N , DCsurvey.dobs[count:count+nD], DCsurvey.std[count:count+nD] ], fmt='%e',delimiter=' ',newline='\n') fid.write('\n') diff --git a/SimPEG/Directives.py b/SimPEG/Directives.py index 765711b7..6d4a5c13 100644 --- a/SimPEG/Directives.py +++ b/SimPEG/Directives.py @@ -15,7 +15,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 {0!s} has switched to a new inversion.'.format(self.__name__) self._inversion = i @property @@ -47,7 +47,7 @@ class DirectiveList(object): def __init__(self, *directives, **kwargs): self.dList = [] for d in directives: - assert isinstance(d, InversionDirective), 'All directives must be InversionDirectives not %s' % d.__name__ + assert isinstance(d, InversionDirective), 'All directives must be InversionDirectives not {0!s}'.format(d.__name__) self.dList.append(d) Utils.setKwargs(self, **kwargs) @@ -68,7 +68,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: {0!s} has switched to a new inversion.'.format(self.__name__) for d in self.dList: d.inversion = i self._inversion = i @@ -79,7 +79,7 @@ class DirectiveList(object): return directives = ['initialize', 'endIter', 'finish'] - assert ruleType in directives, 'Directive type must be in ["%s"]' % '", "'.join(directives) + assert ruleType in directives, 'Directive type must be in ["{0!s}"]'.format('", "'.join(directives)) for r in self.dList: getattr(r, ruleType)() @@ -141,7 +141,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: {0:d}'.format(self.opt.iter) self.invProb.beta /= self.coolingFactor @@ -181,7 +181,7 @@ class SaveEveryIteration(InversionDirective): def fileName(self): if getattr(self, '_fileName', None) is None: from datetime import datetime - self._fileName = '%s-%s'%(self.name, datetime.now().strftime('%Y-%m-%d-%H-%M')) + self._fileName = '{0!s}-{1!s}'.format(self.name, datetime.now().strftime('%Y-%m-%d-%H-%M')) return self._fileName @fileName.setter def fileName(self, value): @@ -192,31 +192,31 @@ 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: '###-{0!s}.npy'".format(self.fileName) def endIter(self): - np.save('%03d-%s' % (self.opt.iter, self.fileName), self.opt.xc) + np.save('{0:03d}-{1!s}'.format(self.opt.iter, self.fileName), self.opt.xc) 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: '###-{0!s}.txt'".format(self.fileName) f = open(self.fileName+'.txt', 'w') f.write(" # beta phi_d phi_m f\n") f.close() def endIter(self): f = open(self.fileName+'.txt', 'a') - f.write(' %3d %1.4e %1.4e %1.4e %1.4e\n'%(self.opt.iter, self.invProb.beta, self.invProb.phi_d, self.invProb.phi_m, self.opt.f)) + f.write(' {0:3d} {1:1.4e} {2:1.4e} {3:1.4e} {4:1.4e}\n'.format(self.opt.iter, self.invProb.beta, self.invProb.phi_d, self.invProb.phi_m, self.opt.f)) f.close() 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: '###-{0!s}.npz'".format(self.fileName) def endIter(self): # Save the data. @@ -328,7 +328,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: {0:d}'.format(self.opt.iter) self.invProb.beta /= self.coolingFactor @@ -340,11 +340,11 @@ class Update_IRLS(InversionDirective): phim_new = self.reg.eval(self.invProb.curModel) self.f_change = np.abs(self.f_old - phim_new) / self.f_old - print "Regularization decrease: %6.3e" % (self.f_change) + print "Regularization decrease: {0:6.3e}".format((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: {0:d}".format(self.maxIRLSiter) self.opt.stopNextIteration = True return diff --git a/SimPEG/EM/FDEM/FieldsFDEM.py b/SimPEG/EM/FDEM/FieldsFDEM.py index e0f54be2..b4d7d95c 100644 --- a/SimPEG/EM/FDEM/FieldsFDEM.py +++ b/SimPEG/EM/FDEM/FieldsFDEM.py @@ -42,7 +42,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) return self._ePrimary(solution,srcList) + self._eSecondary(solution,srcList) @@ -56,7 +56,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) return self._bPrimary(solution, srcList) + self._bSecondary(solution, srcList) @@ -70,7 +70,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) return self._hPrimary(solution, srcList) + self._hSecondary(solution, srcList) @@ -84,7 +84,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) return self._jPrimary(solution, srcList) + self._jSecondary(solution, srcList) @@ -100,7 +100,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) if adjoint: return self._eDeriv_u(src, v, adjoint), self._eDeriv_m(src, v, adjoint) @@ -118,7 +118,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) if adjoint: return self._bDeriv_u(src, v, adjoint), self._bDeriv_m(src, v, adjoint) @@ -136,7 +136,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) if adjoint: return self._hDeriv_u(src, v, adjoint), self._hDeriv_m(src, v, adjoint) @@ -154,7 +154,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) if adjoint: return self._jDeriv_u(src, v, adjoint), self._jDeriv_m(src, v, adjoint) diff --git a/SimPEG/EM/FDEM/RxFDEM.py b/SimPEG/EM/FDEM/RxFDEM.py index 13e2f291..0e997e8d 100644 --- a/SimPEG/EM/FDEM/RxFDEM.py +++ b/SimPEG/EM/FDEM/RxFDEM.py @@ -11,8 +11,8 @@ class BaseRx(SimPEG.Survey.BaseRx): """ def __init__(self, locs, orientation=None, component=None): - assert(orientation in ['x','y','z']), "Orientation %s not known. Orientation must be in 'x', 'y', 'z'. Arbitrary orientations have not yet been implemented."%orientation - assert(component in ['real', 'imag']), "'component' must be 'real' or 'imag', not %s"%component + assert(orientation in ['x','y','z']), "Orientation {0!s} not known. Orientation must be in 'x', 'y', 'z'. Arbitrary orientations have not yet been implemented.".format(orientation) + assert(component in ['real', 'imag']), "'component' must be 'real' or 'imag', not {0!s}".format(component) self.projComp = orientation self.component = component diff --git a/SimPEG/EM/Static/DC/FieldsDC.py b/SimPEG/EM/Static/DC/FieldsDC.py index 6fcea083..5a4f8e83 100644 --- a/SimPEG/EM/Static/DC/FieldsDC.py +++ b/SimPEG/EM/Static/DC/FieldsDC.py @@ -9,7 +9,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) if adjoint: return self._phiDeriv_u(src, v, adjoint=adjoint), self._phiDeriv_m(src, v, adjoint=adjoint) @@ -18,7 +18,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) if adjoint: return self._eDeriv_u(src, v, adjoint), self._eDeriv_m(src, v, adjoint) @@ -26,7 +26,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 {0!s} is not implemented'.format(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..9d729370 100644 --- a/SimPEG/EM/Static/DC/FieldsDC_2D.py +++ b/SimPEG/EM/Static/DC/FieldsDC_2D.py @@ -32,7 +32,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 {0!s} is not implemented'.format(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 +41,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 {0!s} is not implemented'.format(self.knownFields.keys()[0])) if adjoint: return self._eDeriv_u(kyInd, src, v, adjoint), self._eDeriv_m(kyInd, src, v, adjoint) @@ -49,7 +49,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 {0!s} is not implemented'.format(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..ae4f4de1 100644 --- a/SimPEG/EM/Static/DC/ProblemDC.py +++ b/SimPEG/EM/Static/DC/ProblemDC.py @@ -46,7 +46,7 @@ class BaseDCProblem(BaseEMProblem): du_dm_v = self.Ainv * ( - dA_dm_v + dRHS_dm_v ) for rx in src.rxList: - df_dmFun = getattr(f, '_%sDeriv'%rx.projField, None) + df_dmFun = getattr(f, '_{0!s}Deriv'.format(rx.projField), None) df_dm_v = df_dmFun(src, du_dm_v, v, adjoint=False) Jv[src, rx] = rx.evalDeriv(src, self.mesh, f, df_dm_v) return Utils.mkvc(Jv) @@ -69,7 +69,7 @@ class BaseDCProblem(BaseEMProblem): u_src = f[src, self._solutionType] for rx in src.rxList: PTv = rx.evalDeriv(src, self.mesh, f, v[src, rx], adjoint=True) # wrt f, need possibility wrt m - df_duTFun = getattr(f, '_%sDeriv'%rx.projField, None) + df_duTFun = getattr(f, '_{0!s}Deriv'.format(rx.projField), None) df_duT, df_dmT = df_duTFun(src, None, PTv, adjoint=True) ATinvdf_duT = self.Ainv * df_duT diff --git a/SimPEG/EM/Static/DC/ProblemDC_2D.py b/SimPEG/EM/Static/DC/ProblemDC_2D.py index 8e0561f9..91547955 100644 --- a/SimPEG/EM/Static/DC/ProblemDC_2D.py +++ b/SimPEG/EM/Static/DC/ProblemDC_2D.py @@ -60,7 +60,7 @@ class BaseDCProblem_2D(BaseEMProblem): dRHS_dm_v = self.getRHSDeriv(ky, src, v) du_dm_v = self.Ainv[iky] * ( - dA_dm_v + dRHS_dm_v ) for rx in src.rxList: - df_dmFun = getattr(f, '_%sDeriv'%rx.projField, None) + df_dmFun = getattr(f, '_{0!s}Deriv'.format(rx.projField), None) df_dm_v = df_dmFun(iky, src, du_dm_v, v, adjoint=False) # Trapezoidal intergration Jv1_temp = 1./np.pi*rx.evalDeriv(ky, src, self.mesh, f, df_dm_v) @@ -101,7 +101,7 @@ class BaseDCProblem_2D(BaseEMProblem): ky = self.kys[iky] AT = self.getA(ky) PTv = rx.evalDeriv(ky, src, self.mesh, f, v[src, rx], adjoint=True) # wrt f, need possibility wrt m - df_duTFun = getattr(f, '_%sDeriv'%rx.projField, None) + df_duTFun = getattr(f, '_{0!s}Deriv'.format(rx.projField), None) df_duT, df_dmT = df_duTFun(iky, src, None, PTv, adjoint=True) ATinvdf_duT = self.Ainv[iky] * df_duT diff --git a/SimPEG/EM/Static/IP/ProblemIP.py b/SimPEG/EM/Static/IP/ProblemIP.py index 77767452..833771f8 100644 --- a/SimPEG/EM/Static/IP/ProblemIP.py +++ b/SimPEG/EM/Static/IP/ProblemIP.py @@ -56,7 +56,7 @@ class BaseIPProblem(BaseEMProblem): du_dm_v = self.Ainv * ( - dA_dm_v + dRHS_dm_v ) for rx in src.rxList: - df_dmFun = getattr(f, '_%sDeriv'%rx.projField, None) + df_dmFun = getattr(f, '_{0!s}Deriv'.format(rx.projField), None) df_dm_v = df_dmFun(src, du_dm_v, v, adjoint=False) Jv[src, rx] = rx.evalDeriv(src, self.mesh, f, df_dm_v) # Conductivity (d u / d log sigma) @@ -83,7 +83,7 @@ class BaseIPProblem(BaseEMProblem): u_src = f[src, self._solutionType] for rx in src.rxList: PTv = rx.evalDeriv(src, self.mesh, f, v[src, rx], adjoint=True) # wrt f, need possibility wrt m - df_duTFun = getattr(f, '_%sDeriv'%rx.projField, None) + df_duTFun = getattr(f, '_{0!s}Deriv'.format(rx.projField), None) df_duT, df_dmT = df_duTFun(src, None, PTv, adjoint=True) ATinvdf_duT = self.Ainv * df_duT dA_dmT = self.getADeriv(u_src, ATinvdf_duT, adjoint=True) diff --git a/SimPEG/EM/Static/SIP/ProblemSIP.py b/SimPEG/EM/Static/SIP/ProblemSIP.py index 97be624d..3fee70f4 100644 --- a/SimPEG/EM/Static/SIP/ProblemSIP.py +++ b/SimPEG/EM/Static/SIP/ProblemSIP.py @@ -83,7 +83,7 @@ class BaseSIPProblem(BaseEMProblem): for rx in src.rxList: timeindex = rx.getTimeP(self.survey.times) if timeindex[tind]: - df_dmFun = getattr(f, '_%sDeriv'%rx.projField, None) + df_dmFun = getattr(f, '_{0!s}Deriv'.format(rx.projField), None) df_dm_v = df_dmFun(src, du_dm_v, v, adjoint=False) Jv[src, rx, t] = rx.evalDeriv(src, self.mesh, f, df_dm_v) @@ -122,7 +122,7 @@ class BaseSIPProblem(BaseEMProblem): for rx in src.rxList: timeindex = rx.getTimeP(self.survey.times) if timeindex[tind]: - df_dmFun = getattr(f, '_%sDeriv'%rx.projField, None) + df_dmFun = getattr(f, '_{0!s}Deriv'.format(rx.projField), None) df_dm_v0 = df_dmFun(src, du_dm_v0, v0, adjoint=False) df_dm_v1 = df_dmFun(src, du_dm_v1, v1, adjoint=False) Jv[src, rx, t] = rx.evalDeriv(src, self.mesh, f, df_dm_v0) @@ -153,7 +153,7 @@ class BaseSIPProblem(BaseEMProblem): timeindex = rx.getTimeP(self.survey.times) if timeindex[tind]: PTv = rx.evalDeriv(src, self.mesh, f, v[src, rx, t], adjoint=True) # wrt f, need possibility wrt m - df_duTFun = getattr(f, '_%sDeriv'%rx.projField, None) + df_duTFun = getattr(f, '_{0!s}Deriv'.format(rx.projField), None) df_duT, df_dmT = df_duTFun(src, None, PTv, adjoint=True) ATinvdf_duT = self.Ainv * df_duT dA_dmT = self.getADeriv(u_src, ATinvdf_duT, adjoint=True) diff --git a/SimPEG/EM/TDEM/BaseTDEM.py b/SimPEG/EM/TDEM/BaseTDEM.py index cb93ab40..8f18ff73 100644 --- a/SimPEG/EM/TDEM/BaseTDEM.py +++ b/SimPEG/EM/TDEM/BaseTDEM.py @@ -47,7 +47,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 '{0!s}\nCalculating fields(m)\n{1!s}'.format('*'*50, '*'*50) self.curModel = m # Create a fields storage object F = self._FieldsForward_pair(self.mesh, self.survey) @@ -55,7 +55,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 '{0!s}\nDone calculating fields(m)\n{1!s}'.format('*'*50, '*'*50) return F def forward(self, m, RHS, F=None): @@ -70,11 +70,11 @@ 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 = {0:e})'.format(dt) Ainv = self.Solver(A, **self.solverOpts) if self.verbose: print 'Done' rhs = RHS(tInd, F) - if self.verbose: print ' Solving... (tInd = %d)'%tInd + if self.verbose: print ' Solving... (tInd = {0:d})'.format(tInd) sol = Ainv * rhs if self.verbose: print ' Done...' if sol.ndim == 1: @@ -95,11 +95,11 @@ 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 = {0:e})'.format(dt) Ainv = self.Solver(A, **self.solverOpts) 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 = {0:d})'.format(tInd) sol = Ainv * rhs if self.verbose: print ' Done...' if sol.ndim == 1: @@ -123,14 +123,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 '{0!s}\nCalculating J(v)\n{1!s}'.format('*'*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 '{0!s}\nDone calculating J(v)\n{1!s}'.format('*'*50, '*'*50) return - mkvc(Jv) def Jtvec(self, m, v, f=None): @@ -148,7 +148,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 '{0!s}\nCalculating J^T(v)\n{1!s}'.format('*'*50, '*'*50) self.curModel = m if f is None: f = self.fields(m) @@ -159,6 +159,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 '{0!s}\nDone calculating J^T(v)\n{1!s}'.format('*'*50, '*'*50) return - mkvc(w) diff --git a/SimPEG/EM/Utils/testingUtils.py b/SimPEG/EM/Utils/testingUtils.py index 22c925b6..8f7a4f63 100644 --- a/SimPEG/EM/Utils/testingUtils.py +++ b/SimPEG/EM/Utils/testingUtils.py @@ -58,7 +58,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 {0!s} problem'.format((fdemType)) if fdemType == 'e': survey = EM.FDEM.Survey(Src) @@ -94,7 +94,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: {0!s}, {1!s} formulations - {2!s}'.format(fdemType1, fdemType2, comp) logsig = np.log(np.ones(mesh.nC)*CONDUCTIVITY) mu = np.ones(mesh.nC)*MU diff --git a/SimPEG/Examples/EM_Schenkel_Morrison_Casing.py b/SimPEG/Examples/EM_Schenkel_Morrison_Casing.py index 3e0b308c..7335cd29 100644 --- a/SimPEG/Examples/EM_Schenkel_Morrison_Casing.py +++ b/SimPEG/Examples/EM_Schenkel_Morrison_Casing.py @@ -110,7 +110,7 @@ def run(plotIt=True): # 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 'Mesh Extent xmax: {0:f},: zmin: {1:f}, zmax: {2:f}'.format(mesh.vectorCCx.max(), mesh.vectorCCz.min(), mesh.vectorCCz.max()) print 'Number of cells', mesh.nC if plotIt is True: diff --git a/SimPEG/Examples/Mesh_Operators_CahnHilliard.py b/SimPEG/Examples/Mesh_Operators_CahnHilliard.py index 8e42e617..ab371bb8 100644 --- a/SimPEG/Examples/Mesh_Operators_CahnHilliard.py +++ b/SimPEG/Examples/Mesh_Operators_CahnHilliard.py @@ -98,7 +98,7 @@ def run(plotIt=True, n=60): ii = int(ii) out = M.plotImage(PHIS[ii][1],ax=ax) ax.axis('off') - ax.set_title('Elapsed Time: %4.1f'%PHIS[ii][0]) + ax.set_title('Elapsed Time: {0:4.1f}'.format(PHIS[ii][0])) plt.show() if __name__ == '__main__': diff --git a/SimPEG/Examples/Mesh_QuadTree_FaceDiv.py b/SimPEG/Examples/Mesh_QuadTree_FaceDiv.py index 5bd67929..41aed62b 100644 --- a/SimPEG/Examples/Mesh_QuadTree_FaceDiv.py +++ b/SimPEG/Examples/Mesh_QuadTree_FaceDiv.py @@ -29,15 +29,15 @@ def run(plotIt=True, n=60): axes[0].set_ylim([-1,17]) for ii, loc in zip(range(M.nC),M.gridCC): - axes[0].text(loc[0]+0.2,loc[1],'%d'%ii, color='r') + axes[0].text(loc[0]+0.2,loc[1],'{0:d}'.format(ii), color='r') axes[0].plot(M.gridFx[:,0],M.gridFx[:,1], 'g>') for ii, loc in zip(range(M.nFx),M.gridFx): - axes[0].text(loc[0]+0.2,loc[1],'%d'%ii, color='g') + axes[0].text(loc[0]+0.2,loc[1],'{0:d}'.format(ii), color='g') axes[0].plot(M.gridFy[:,0],M.gridFy[:,1], 'm^') for ii, loc in zip(range(M.nFy),M.gridFy): - axes[0].text(loc[0]+0.2,loc[1]+0.2,'%d'%(ii+M.nFx), color='m') + axes[0].text(loc[0]+0.2,loc[1]+0.2,'{0:d}'.format((ii+M.nFx)), color='m') axes[1].spy(M.faceDiv) axes[1].set_title('Face Divergence') diff --git a/SimPEG/Examples/__init__.py b/SimPEG/Examples/__init__.py index 3c9cbca9..381fd098 100644 --- a/SimPEG/Examples/__init__.py +++ b/SimPEG/Examples/__init__.py @@ -59,7 +59,7 @@ if __name__ == '__main__': if line == "##### AUTOIMPORTS #####\n": inimports = not inimports if inimports: - out += '\n'.join(["import %s"%_ for _ in exfiles]) + out += '\n'.join(["import {0!s}".format(_) for _ in exfiles]) out += '\n\n__examples__ = ["' + '", "'.join(exfiles)+ '"]\n' out += '\n##### AUTOIMPORTS #####\n' f.close() @@ -76,11 +76,11 @@ if __name__ == '__main__': docstr = runFunction.__doc__ if docstr is None: - doc = '%s\n%s'%(name.replace('_',' '),'='*len(name)) + doc = '{0!s}\n{1!s}'.format(name.replace('_',' '), '='*len(name)) else: doc = '\n'.join([_[8:].rstrip() for _ in docstr.split('\n')]) - out = """.. _examples_%s: + out = """.. _examples_{0!s}: .. --------------------------------- .. .. .. @@ -90,21 +90,21 @@ if __name__ == '__main__': .. .. .. --------------------------------- .. -%s +{1!s} .. plot:: from SimPEG import Examples - Examples.%s.run() + Examples.{2!s}.run() -.. literalinclude:: ../../../SimPEG/Examples/%s.py +.. literalinclude:: ../../../SimPEG/Examples/{3!s}.py :language: python :linenos: -"""%(name,doc,name,name) +""".format(name, doc, name, name) rst = os.path.sep.join((filePath.split(os.path.sep)[:-3] + ['docs', 'content', 'examples', name + '.rst'])) - print 'Creating: %s.rst'%name + print 'Creating: {0!s}.rst'.format(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..eaf5bfa7 100644 --- a/SimPEG/FLOW/Richards/Empirical.py +++ b/SimPEG/FLOW/Richards/Empirical.py @@ -116,7 +116,7 @@ class RichardsMap(object): ax.semilogx(self.k(h, m), h) def _assertMatchesPair(self, pair): - assert isinstance(self, pair), "Mapping object must be an instance of a %s class."%(pair.__name__) + assert isinstance(self, pair), "Mapping object must be an instance of a {0!s} class.".format((pair.__name__)) diff --git a/SimPEG/FLOW/Richards/RichardsProblem.py b/SimPEG/FLOW/Richards/RichardsProblem.py index 2346f4da..3f85d8e7 100644 --- a/SimPEG/FLOW/Richards/RichardsProblem.py +++ b/SimPEG/FLOW/Richards/RichardsProblem.py @@ -140,7 +140,7 @@ class RichardsProblem(Problem.BaseTimeProblem): 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 ({0:4d}/{1:d} - {2:3.1f}% Done) {3:d} Iterations, {4:4.2f} seconds".format(ii+1, self.nT, 100.0*(ii+1)/self.nT, self.rootFinder.iter, time.time() - tic) return u @Utils.timeIt diff --git a/SimPEG/Fields.py b/SimPEG/Fields.py index 9baa32f8..f4ab48a9 100644 --- a/SimPEG/Fields.py +++ b/SimPEG/Fields.py @@ -37,7 +37,7 @@ class Fields(object): for f in self.knownFields: loc =self.knownFields[f] sz += np.array(self._storageShape(loc)).prod()*8.0/(1024**2) - return "%e MB"%sz + return "{0:e} MB".format(sz) def _storageShape(self, loc): nSrc = self.survey.nSrc @@ -84,12 +84,12 @@ class Fields(object): return if accessType=='set' and name not in self.knownFields: if name in self.aliasFields: - raise KeyError("Invalid field name (%s) for setter, you can't set an aliased property"%name) + raise KeyError("Invalid field name ({0!s}) for setter, you can't set an aliased property".format(name)) else: - raise KeyError('Invalid field name (%s) for setter'%name) + raise KeyError('Invalid field name ({0!s}) for setter'.format(name)) elif accessType=='get' and (name not in self.knownFields and name not in self.aliasFields): - raise KeyError('Invalid field name (%s) for getter'%name) + raise KeyError('Invalid field name ({0!s}) for getter'.format(name)) return name def _indexAndNameFromKey(self, key, accessType): diff --git a/SimPEG/Maps.py b/SimPEG/Maps.py index 77e7e9a3..ae20a215 100644 --- a/SimPEG/Maps.py +++ b/SimPEG/Maps.py @@ -101,7 +101,7 @@ class IdentityMap(object): :return: passed the test? """ - print 'Testing %s' % str(self) + print 'Testing {0!s}'.format(str(self)) if m is None: m = abs(np.random.rand(self.nP)) if 'plotIt' not in kwargs: @@ -111,21 +111,21 @@ class IdentityMap(object): def _assertMatchesPair(self, pair): assert (isinstance(self, pair) or isinstance(self, ComboMap) and isinstance(self.maps[0], pair) - ), "Mapping object must be an instance of a %s class."%(pair.__name__) + ), "Mapping object must be an instance of a {0!s} class.".format((pair.__name__)) def __mul__(self, val): if isinstance(val, IdentityMap): if not (self.shape[1] == '*' or val.shape[0] == '*') and not self.shape[1] == val.shape[0]: - raise ValueError('Dimension mismatch in %s and %s.' % (str(self), str(val))) + raise ValueError('Dimension mismatch in {0!s} and {1!s}.'.format(str(self), str(val))) return ComboMap([self, val]) elif isinstance(val, np.ndarray): if not self.shape[1] == '*' and not self.shape[1] == val.shape[0]: - raise ValueError('Dimension mismatch in %s and np.ndarray%s.' % (str(self), str(val.shape))) + raise ValueError('Dimension mismatch in {0!s} and np.ndarray{1!s}.'.format(str(self), str(val.shape))) return self._transform(val) raise Exception('Unrecognized data type to multiply. Try a map or a numpy.ndarray!') def __str__(self): - return "%s(%s,%s)" % (self.__class__.__name__, self.shape[0], self.shape[1]) + return "{0!s}({1!s},{2!s})".format(self.__class__.__name__, self.shape[0], self.shape[1]) class ComboMap(IdentityMap): @@ -140,7 +140,7 @@ class ComboMap(IdentityMap): if ii > 0 and not (self.shape[1] == '*' or m.shape[0] == '*') and not self.shape[1] == m.shape[0]: prev = self.maps[-1] errArgs = (prev.__class__.__name__, prev.shape[0], prev.shape[1], m.__class__.__name__, m.shape[0], m.shape[1]) - raise ValueError('Dimension mismatch in map[%s] (%s, %s) and map[%s] (%s, %s).' % errArgs) + raise ValueError('Dimension mismatch in map[{0!s}] ({1!s}, {2!s}) and map[{3!s}] ({4!s}, {5!s}).'.format(*errArgs)) if isinstance(m, ComboMap): self.maps += m.maps @@ -173,7 +173,7 @@ class ComboMap(IdentityMap): return deriv def __str__(self): - return 'ComboMap[%s](%s,%s)' % (' * '.join([m.__str__() for m in self.maps]), self.shape[0], self.shape[1]) + return 'ComboMap[{0!s}]({1!s},{2!s})'.format(' * '.join([m.__str__() for m in self.maps]), self.shape[0], self.shape[1]) class ExpMap(IdentityMap): diff --git a/SimPEG/Mesh/BaseMesh.py b/SimPEG/Mesh/BaseMesh.py index 97394b68..8710b9f8 100644 --- a/SimPEG/Mesh/BaseMesh.py +++ b/SimPEG/Mesh/BaseMesh.py @@ -522,7 +522,7 @@ class BaseRectangularMesh(BaseMesh): assert xType in outType, 'You cannot change type of components.' if type(x) == list: for i, xi in enumerate(x): - assert isinstance(x, np.ndarray), "x[%i] must be a numpy array" % i + assert isinstance(x, np.ndarray), "x[{0:d}] must be a numpy array".format(i) assert xi.size == x[0].size, "Number of elements in list must not change." x_array = np.ones((x.size, len(x))) diff --git a/SimPEG/Mesh/CurvilinearMesh.py b/SimPEG/Mesh/CurvilinearMesh.py index d3c0c5b9..e2ab516c 100644 --- a/SimPEG/Mesh/CurvilinearMesh.py +++ b/SimPEG/Mesh/CurvilinearMesh.py @@ -49,8 +49,8 @@ class CurvilinearMesh(BaseRectangularMesh, DiffOperators, InnerProducts, assert len(nodes) > 1, "len(node) must be greater than 1" for i, nodes_i in enumerate(nodes): - assert isinstance(nodes_i, np.ndarray), ("nodes[%i] is not a numpy array." % i) - assert nodes_i.shape == nodes[0].shape, ("nodes[%i] is not the same shape as nodes[0]" % i) + assert isinstance(nodes_i, np.ndarray), ("nodes[{0:d}] is not a numpy array.".format(i)) + assert nodes_i.shape == nodes[0].shape, ("nodes[{0:d}] is not the same shape as nodes[0]".format(i)) assert len(nodes[0].shape) == len(nodes), "Dimension mismatch" assert len(nodes[0].shape) > 1, "Not worth using Curv for a 1D mesh." diff --git a/SimPEG/Mesh/InnerProducts.py b/SimPEG/Mesh/InnerProducts.py index 0c08cdd3..e64f7abc 100644 --- a/SimPEG/Mesh/InnerProducts.py +++ b/SimPEG/Mesh/InnerProducts.py @@ -421,7 +421,7 @@ class InnerProducts(object): def _getEdgePx(M): """Returns a function for creating projection matrices""" def Px(xEdge): - assert xEdge == 'eX0', 'xEdge = %s, not eX0' % xEdge + assert xEdge == 'eX0', 'xEdge = {0!s}, not eX0'.format(xEdge) return sp.identity(M.nC) return Px diff --git a/SimPEG/Mesh/MeshIO.py b/SimPEG/Mesh/MeshIO.py index 0810f973..e4451e19 100644 --- a/SimPEG/Mesh/MeshIO.py +++ b/SimPEG/Mesh/MeshIO.py @@ -198,11 +198,11 @@ class TensorMeshIO(object): """ assert mesh.dim == 3 s = '' - s += '%i %i %i\n' %tuple(mesh.vnC) + s += '{0:d} {1:d} {2:d}\n'.format(*tuple(mesh.vnC)) origin = mesh.x0 + np.array([0,0,mesh.hz.sum()]) # Have to it in the same operation or use mesh.x0.copy(), otherwise the mesh.x0 is updated. origin.dtype = float - s += '%.2f %.2f %.2f\n' %tuple(origin) + s += '{0:.2f} {1:.2f} {2:.2f}\n'.format(*tuple(origin)) s += ('%.2f '*mesh.nCx+'\n')%tuple(mesh.hx) s += ('%.2f '*mesh.nCy+'\n')%tuple(mesh.hy) s += ('%.2f '*mesh.nCz+'\n')%tuple(mesh.hz[::-1]) diff --git a/SimPEG/Mesh/TensorMesh.py b/SimPEG/Mesh/TensorMesh.py index 65b6d7e9..8bf924d6 100644 --- a/SimPEG/Mesh/TensorMesh.py +++ b/SimPEG/Mesh/TensorMesh.py @@ -23,8 +23,8 @@ class BaseTensorMesh(BaseMesh): h_i = self._unitDimensions[i] * np.ones(int(h_i))/int(h_i) elif type(h_i) is list: h_i = Utils.meshTensor(h_i) - assert isinstance(h_i, np.ndarray), ("h[%i] is not a numpy array." % i) - assert len(h_i.shape) == 1, ("h[%i] must be a 1D numpy array." % i) + assert isinstance(h_i, np.ndarray), ("h[{0:d}] is not a numpy array.".format(i)) + assert len(h_i.shape) == 1, ("h[{0:d}] must be a 1D numpy array.".format(i)) h[i] = h_i[:] # make a copy. x0 = np.zeros(len(h)) @@ -41,7 +41,7 @@ class BaseTensorMesh(BaseMesh): elif x_i == 'N': x0[i] = -h_i.sum() else: - raise Exception("x0[%i] must be a scalar or '0' to be zero, 'C' to center, or 'N' to be negative." % i) + raise Exception("x0[{0:d}] must be a scalar or '0' to be zero, 'C' to center, or 'N' to be negative.".format(i)) if isinstance(self, BaseRectangularMesh): BaseRectangularMesh.__init__(self, np.array([x.size for x in h]), x0) @@ -239,7 +239,7 @@ class BaseTensorMesh(BaseMesh): 'CCVz' -> z-component of vector field defined on cell centers """ if self._meshType == 'CYL' and self.isSymmetric and locType in ['Ex','Ez','Fy']: - raise Exception('Symmetric CylMesh does not support %s interpolation, as this variable does not exist.' % locType) + raise Exception('Symmetric CylMesh does not support {0!s} interpolation, as this variable does not exist.'.format(locType)) loc = Utils.asArray_N_x_Dim(loc, self.dim) diff --git a/SimPEG/Mesh/TreeMesh.py b/SimPEG/Mesh/TreeMesh.py index d994e3a5..cf094377 100644 --- a/SimPEG/Mesh/TreeMesh.py +++ b/SimPEG/Mesh/TreeMesh.py @@ -177,7 +177,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): return l def __str__(self): - outStr = ' ---- %sTreeMesh ---- '%('Oc' if self.dim == 3 else 'Quad') + outStr = ' ---- {0!s}TreeMesh ---- '.format(('Oc' if self.dim == 3 else 'Quad')) def printH(hx, outStr=''): i = -1 while True: @@ -213,7 +213,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): outStr += printH(self.hy, outStr='\n hy:') outStr += printH(self.hz, outStr='\n hz:') outStr += '\n nC: {0:d}'.format(self.nC) - outStr += '\n Fill: %2.2f%%'%(self.fill*100) + outStr += '\n Fill: {0:2.2f}%'.format((self.fill*100)) return outStr @property @@ -2210,7 +2210,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): ax.set_xlabel('y' if normal == 'X' else 'x') ax.set_ylabel('y' if normal == 'Z' else 'z') - ax.set_title('Slice %d, %s = %4.2f' % (ind,normal,indLoc)) + ax.set_title('Slice {0:d}, {1!s} = {2:4.2f}'.format(ind, normal, indLoc)) if grid: _ = antiNormalInd @@ -2240,7 +2240,7 @@ class TreeMesh(BaseTensorMesh, InnerProducts, TreeMeshIO): 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 ({0:d}) is out of range.".format(key) self._numberCells() # no-op if numbered index = self._i2cc[key] diff --git a/SimPEG/Mesh/View.py b/SimPEG/Mesh/View.py index 32e97539..0549b3ba 100644 --- a/SimPEG/Mesh/View.py +++ b/SimPEG/Mesh/View.py @@ -171,7 +171,7 @@ class TensorView(object): iz = ix + iy*nX if iz < self.nCz: ax.text((ix+1)*(self.vectorNx[-1]-self.x0[0])-pad,(iy)*(self.vectorNy[-1]-self.x0[1])+pad, - '#%i'%iz,color=annotationColor,verticalalignment='bottom',horizontalalignment='right',size='x-large') + '#{0:d}'.format(iz),color=annotationColor,verticalalignment='bottom',horizontalalignment='right',size='x-large') ax.set_title(vType) if showIt: plt.show() @@ -221,10 +221,10 @@ class TensorView(object): vTypeOpts = ['CC', 'CCv','N','F','E','Fx','Fy','Fz','E','Ex','Ey','Ez'] # Some user error checking - assert vType in vTypeOpts, "vType must be in ['%s']" % "','".join(vTypeOpts) + assert vType in vTypeOpts, "vType must be in ['{0!s}']".format("','".join(vTypeOpts)) assert self.dim == 3, 'Must be a 3D mesh. Use plotImage.' - assert view in viewOpts, "view must be in ['%s']" % "','".join(viewOpts) - assert normal in normalOpts, "normal must be in ['%s']" % "','".join(normalOpts) + assert view in viewOpts, "view must be in ['{0!s}']".format("','".join(viewOpts)) + assert normal in normalOpts, "normal must be in ['{0!s}']".format("','".join(normalOpts)) assert type(grid) is bool, 'grid must be a boolean' szSliceDim = getattr(self, 'nC'+normal.lower()) #: Size of the sliced dimension @@ -295,7 +295,7 @@ class TensorView(object): ax.set_xlabel('y' if normal == 'X' else 'x') ax.set_ylabel('y' if normal == 'Z' else 'z') - ax.set_title('Slice %d' % ind) + ax.set_title('Slice {0:d}'.format(ind)) return out @@ -316,11 +316,11 @@ class TensorView(object): vTypeOptsV = ['CCv','F','E'] vTypeOpts = vTypeOptsCC + vTypeOptsV if view == 'vec': - assert vType in vTypeOptsV, "vType must be in ['%s'] when view='vec'" % "','".join(vTypeOptsV) - assert vType in vTypeOpts, "vType must be in ['%s']" % "','".join(vTypeOpts) + assert vType in vTypeOptsV, "vType must be in ['{0!s}'] when view='vec'".format("','".join(vTypeOptsV)) + assert vType in vTypeOpts, "vType must be in ['{0!s}']".format("','".join(vTypeOpts)) viewOpts = ['real','imag','abs','vec'] - assert view in viewOpts, "view must be in ['%s']" % "','".join(viewOpts) + assert view in viewOpts, "view must be in ['{0!s}']".format("','".join(viewOpts)) if ax is None: diff --git a/SimPEG/Optimization.py b/SimPEG/Optimization.py index c66242aa..3d220b9c 100644 --- a/SimPEG/Optimization.py +++ b/SimPEG/Optimization.py @@ -121,7 +121,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 {0!s} Optimization was replaced.'.format(self.__name__) self._callback = value @@ -855,7 +855,7 @@ class NewtonRoot(object): 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: {0:e}\n'.format(norm(rt)) if norm(rt) <= norm(r) or norm(rt) < self.tol: break @@ -873,7 +873,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 ({0:d}). norm: {1:4.4e}'.format(self.maxIter, norm(rt)) break return x diff --git a/SimPEG/Problem.py b/SimPEG/Problem.py index f8520c5c..964ebfae 100644 --- a/SimPEG/Problem.py +++ b/SimPEG/Problem.py @@ -49,7 +49,7 @@ class BaseProblem(object): def pair(self, d): """Bind a survey to this problem instance using pointers.""" - assert isinstance(d, self.surveyPair), "Data object must be an instance of a %s class."%(self.surveyPair.__name__) + assert isinstance(d, self.surveyPair), "Data object must be an instance of a {0!s} class.".format((self.surveyPair.__name__)) if d.ispaired: raise Exception("The survey object is already paired to a problem. Use survey.unpair()") self._survey = d diff --git a/SimPEG/PropMaps.py b/SimPEG/PropMaps.py index 34cad863..150f18db 100644 --- a/SimPEG/PropMaps.py +++ b/SimPEG/PropMaps.py @@ -19,85 +19,85 @@ class Property(object): return getattr(self, '_propertyLink', None) @propertyLink.setter def propertyLink(self, value): - assert type(value) is tuple and len(value) == 2 and type(value[0]) is str and issubclass(value[1], Maps.IdentityMap), 'Use format: ("%s", Maps.ReciprocalMap)'%self.name + assert type(value) is tuple and len(value) == 2 and type(value[0]) is str and issubclass(value[1], Maps.IdentityMap), 'Use format: ("{0!s}", Maps.ReciprocalMap)'.format(self.name) self._propertyLink = value def _getMapProperty(self): prop = self def fget(self): - return getattr(self, '_%sMap'%prop.name, None) + return getattr(self, '_{0!s}Map'.format(prop.name), None) def fset(self, val): if prop.propertyLink is not None: linkName, linkMap = prop.propertyLink - assert getattr(self, '%sMap'%linkName, None) is None, 'Cannot set both sides of a linked property.' + assert getattr(self, '{0!s}Map'.format(linkName), None) is None, 'Cannot set both sides of a linked property.' # TODO: Check if the mapping can be correct - setattr(self, '_%sMap'%prop.name, val) + setattr(self, '_{0!s}Map'.format(prop.name), val) return property(fget=fget, fset=fset, doc=prop.doc) def _getIndexProperty(self): prop = self def fget(self): - return getattr(self, '_%sIndex'%prop.name, slice(None)) + return getattr(self, '_{0!s}Index'.format(prop.name), slice(None)) def fset(self, val): - setattr(self, '_%sIndex'%prop.name, val) + setattr(self, '_{0!s}Index'.format(prop.name), val) return property(fget=fget, fset=fset, doc=prop.doc) def _getProperty(self): prop = self def fget(self): - mapping = getattr(self, '%sMap'%prop.name) + mapping = getattr(self, '{0!s}Map'.format(prop.name)) if mapping is None and prop.propertyLink is None: return prop.defaultVal if mapping is None and prop.propertyLink is not None: linkName, linkMapClass = prop.propertyLink linkMap = linkMapClass(None) - if getattr(self, '%sMap'%linkName, None) is None: + if getattr(self, '{0!s}Map'.format(linkName), None) is None: return prop.defaultVal - m = getattr(self, '%s'%linkName) + m = getattr(self, '{0!s}'.format(linkName)) return linkMap * m - m = getattr(self, '%sModel'%prop.name) + m = getattr(self, '{0!s}Model'.format(prop.name)) return mapping * m return property(fget=fget) def _getModelDerivProperty(self): prop = self def fget(self): - mapping = getattr(self, '%sMap'%prop.name) + mapping = getattr(self, '{0!s}Map'.format(prop.name)) if mapping is None and prop.propertyLink is None: return None if mapping is None and prop.propertyLink is not None: linkName, linkMapClass = prop.propertyLink - linkedMap = getattr(self, '%sMap'%linkName) + linkedMap = getattr(self, '{0!s}Map'.format(linkName)) if linkedMap is None: return None linkMap = linkMapClass(None) * linkedMap - m = getattr(self, '%sModel'%linkName) + m = getattr(self, '{0!s}Model'.format(linkName)) return linkMap.deriv( m ) - m = getattr(self, '%sModel'%prop.name) + m = getattr(self, '{0!s}Model'.format(prop.name)) return mapping.deriv( m ) return property(fget=fget) def _getModelProperty(self): prop = self def fget(self): - mapping = getattr(self, '%sMap'%prop.name) + mapping = getattr(self, '{0!s}Map'.format(prop.name)) if mapping is None: return None - index = getattr(self.propMap, '%sIndex'%prop.name) + index = getattr(self.propMap, '{0!s}Index'.format(prop.name)) return self.vector[index] return property(fget=fget) def _getModelProjProperty(self): prop = self def fget(self): - mapping = getattr(self, '%sMap'%prop.name) + mapping = getattr(self, '{0!s}Map'.format(prop.name)) if mapping is None: return None - inds = getattr(self.propMap, '%sIndex'%prop.name) + inds = getattr(self.propMap, '{0!s}Index'.format(prop.name)) if type(inds) is slice: inds = range(*inds.indices(self.nP)) nI, nP = len(inds),self.nP @@ -107,7 +107,7 @@ class Property(object): def _getModelMapProperty(self): prop = self def fget(self): - return getattr(self.propMap, '_%sMap'%prop.name, None) + return getattr(self.propMap, '_{0!s}Map'.format(prop.name), None) return property(fget=fget) @@ -123,7 +123,7 @@ class PropModel(object): inds = [] if getattr(self, '_nP', None) is None: for name in self.propMap._properties: - index = getattr(self.propMap, '%sIndex'%name, None) + index = getattr(self.propMap, '{0!s}Index'.format(name), None) if index is not None: if type(index) is slice: inds += range(*index.indices(len(self.vector))) @@ -163,9 +163,9 @@ class _PropMapMetaClass(type): if prop.defaultInvProp: defaultInvProps += [p] if prop.propertyLink is not None: - assert prop.propertyLink[0] in _properties, "You can only link to things that exist: '%s' is trying to link to '%s'"%(prop.name, prop.propertyLink[0]) + assert prop.propertyLink[0] in _properties, "You can only link to things that exist: '{0!s}' is trying to link to '{1!s}'".format(prop.name, prop.propertyLink[0]) if len(defaultInvProps) > 1: - raise Exception('You have more than one default inversion property: %s' % defaultInvProps) + raise Exception('You have more than one default inversion property: {0!s}'.format(defaultInvProps)) newClass = super(_PropMapMetaClass, cls).__new__(cls, name, bases, attrs) @@ -223,7 +223,7 @@ class PropMap(object): type(m[0]) is str and m[0] in self._properties and isinstance(m[1], Maps.IdentityMap) - for m in maps]), "Use signature: [%s]" % (', '.join(["('%s', %sMap)"%(p,p) for p in self._properties])) + for m in maps]), "Use signature: [{0!s}]".format((', '.join(["('{0!s}', {1!s}Map)".format(p, p) for p in self._properties]))) if slices is None: slices = dict() else: @@ -236,8 +236,8 @@ class PropMap(object): nP = 0 for name, mapping in maps: - setattr(self, '%sMap'%name, mapping) - setattr(self, '%sIndex'%name, slices.get(name, slice(nP, nP + mapping.nP))) + setattr(self, '{0!s}Map'.format(name), mapping) + setattr(self, '{0!s}Index'.format(name), slices.get(name, slice(nP, nP + mapping.nP))) nP += mapping.nP self.nP = nP @@ -250,12 +250,12 @@ class PropMap(object): def clearMaps(self): for name in self._properties: - setattr(self, '%sMap'%name, None) - setattr(self, '%sIndex'%name, None) + setattr(self, '{0!s}Map'.format(name), None) + setattr(self, '{0!s}Index'.format(name), None) def __call__(self, vec): return self.PropModel(self, vec) def __contains__(self, val): - activeMaps = [name for name in self._properties if getattr(self, '%sMap'%name) is not None] + activeMaps = [name for name in self._properties if getattr(self, '{0!s}Map'.format(name)) is not None] return val in activeMaps diff --git a/SimPEG/Survey.py b/SimPEG/Survey.py index 65c46972..0161d256 100644 --- a/SimPEG/Survey.py +++ b/SimPEG/Survey.py @@ -26,7 +26,7 @@ class BaseRx(object): def rxType(self, value): known = self.knownRxTypes if known is not None: - assert value in known, "rxType must be in ['%s']" % ("', '".join(known)) + assert value in known, "rxType must be in ['{0!s}']".format(("', '".join(known))) self._rxType = value @property @@ -125,7 +125,7 @@ class BaseSrc(object): def __init__(self, rxList, **kwargs): assert type(rxList) is list, 'rxList must be a list' for rx in rxList: - assert isinstance(rx, self.rxPair), 'rxList must be a %s'%self.rxPair.__name__ + assert isinstance(rx, self.rxPair), 'rxList must be a {0!s}'.format(self.rxPair.__name__) assert len(set(rxList)) == len(rxList), 'The rxList must be unique' self.uid = str(uuid.uuid4()) self.rxList = rxList @@ -227,7 +227,7 @@ class BaseSurvey(object): @srcList.setter def srcList(self, value): assert type(value) is list, 'srcList must be a list' - assert np.all([isinstance(src, self.srcPair) for src in value]), 'All sources must be instances of %s' % self.srcPair.__name__ + assert np.all([isinstance(src, self.srcPair) for src in value]), 'All sources must be instances of {0!s}'.format(self.srcPair.__name__) assert len(set(value)) == len(value), 'The srcList must be unique' self._srcList = value self._sourceOrder = dict() @@ -238,10 +238,10 @@ class BaseSurvey(object): sources = [sources] for src in sources: if getattr(src,'uid',None) is None: - raise KeyError('Source does not have a uid: %s'%str(src)) + raise KeyError('Source does not have a uid: {0!s}'.format(str(src))) inds = map(lambda src: self._sourceOrder.get(src.uid, None), sources) if None in inds: - raise KeyError('Some of the sources specified are not in this survey. %s'%str(inds)) + raise KeyError('Some of the sources specified are not in this survey. {0!s}'.format(str(inds))) return inds @property @@ -263,7 +263,7 @@ class BaseSurvey(object): def pair(self, p): """Bind a problem to this survey instance using pointers""" assert hasattr(p, 'surveyPair'), "Problem must have an attribute 'surveyPair'." - assert isinstance(self, p.surveyPair), "Problem requires survey object must be an instance of a %s class."%(p.surveyPair.__name__) + assert isinstance(self, p.surveyPair), "Problem requires survey object must be an instance of a {0!s} class.".format((p.surveyPair.__name__)) if p.ispaired: raise Exception("The problem object is already paired to a survey. Use prob.unpair()") self._prob = p diff --git a/SimPEG/Tests.py b/SimPEG/Tests.py index 4a392253..47ded465 100644 --- a/SimPEG/Tests.py +++ b/SimPEG/Tests.py @@ -199,10 +199,10 @@ class OrderTest(unittest.TestCase): print '_____________________________________________' print ' h | error | e(i-1)/e(i) | order' print '~~~~~~|~~~~~~~~~~~~~|~~~~~~~~~~~~~|~~~~~~~~~~' - print '%4i | %8.2e |' % (nc, err) + print '{0:4d} | {1:8.2e} |'.format(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]) + print '{0:4d} | {1:8.2e} | {2:6.4f} | {3:6.4f}'.format(nc, err, err_old/err, order[-1]) err_old = err max_h_old = max_h print '---------------------------------------------' @@ -257,8 +257,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 "{0!s} checkDerivative {1!s}".format('='*20, '='*20) + print "iter h |ft-f0| |ft-f0-h*J0*dx| Order\n{0!s}".format(('-'*57)) f0, J0 = fctn(x0) @@ -289,7 +289,7 @@ def checkDerivative(fctn, x0, num=7, plotIt=True, dx=None, expectedOrder=2, tole 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]) + print " {0:d} {1:1.2e} {2:1.3e} {3:1.3e} {4:1.3f}".format(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] @@ -301,10 +301,10 @@ 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 "{0!s} PASS! {1!s}".format('='*25, '='*25) print happiness[np.random.randint(len(happiness))]+'\n' else: - print "%s\n%s FAIL! %s\n%s" % ('*'*57, '<'*25, '>'*25, '*'*57) + print "{0!s}\n{1!s} FAIL! {2!s}\n{3!s}".format('*'*57, '<'*25, '>'*25, '*'*57) print sadness[np.random.randint(len(sadness))]+'\n' @@ -313,7 +313,7 @@ def checkDerivative(fctn, x0, num=7, plotIt=True, dx=None, expectedOrder=2, tole ax = ax or plt.subplot(111) ax.loglog(h, E0, 'b') ax.loglog(h, E1, 'g--') - ax.set_title('Check Derivative - %s' % ('PASSED :)' if passTest else 'FAILED :(')) + ax.set_title('Check Derivative - {0!s}'.format(('PASSED :)' if passTest else 'FAILED :('))) ax.set_xlabel('h') ax.set_ylabel('Error') leg = ax.legend(['$\mathcal{O}(h)$', '$\mathcal{O}(h^2)$'], loc='best', diff --git a/SimPEG/Utils/SolverUtils.py b/SimPEG/Utils/SolverUtils.py index 28a1159d..4ab28a58 100644 --- a/SimPEG/Utils/SolverUtils.py +++ b/SimPEG/Utils/SolverUtils.py @@ -8,7 +8,7 @@ def _checkAccuracy(A, b, X, accuracyTol): if nrm_b > 0: nrm /= nrm_b if nrm > accuracyTol: - msg = '### SolverWarning ###: Accuracy on solve is above tolerance: %e > %e' % (nrm, accuracyTol) + msg = '### SolverWarning ###: Accuracy on solve is above tolerance: {0:e} > {1:e}'.format(nrm, accuracyTol) print msg warnings.warn(msg, RuntimeWarning) diff --git a/SimPEG/Utils/codeutils.py b/SimPEG/Utils/codeutils.py index 6151c540..c7a4f3cd 100644 --- a/SimPEG/Utils/codeutils.py +++ b/SimPEG/Utils/codeutils.py @@ -32,7 +32,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 '{0!s} not found in {1!s} Class'.format(f, towrap.__name__) return type(towrap.__name__ + 'MemProfileWrap', (towrap,), attrs) @@ -65,7 +65,7 @@ def setKwargs(obj, ignore=None, **kwargs): if hasattr(obj, attr): setattr(obj, attr, kwargs[attr]) else: - raise Exception('%s attr is not recognized' % attr) + raise Exception('{0!s} attr is not recognized'.format(attr)) hook(obj,hook, silent=True) hook(obj,setKwargs, silent=True) @@ -74,7 +74,7 @@ def printTitles(obj, printers, name='Print Titles', pad=''): titles = '' widths = 0 for printer in printers: - titles += ('{:^%i}'%printer['width']).format(printer['title']) + '' + titles += ('{{:^{0:d}}}'.format(printer['width'])).format(printer['title']) + '' widths += printer['width'] print pad + "{0} {1} {0}".format('='*((widths-1-len(name))/2), name) print pad + titles @@ -83,7 +83,7 @@ def printTitles(obj, printers, name='Print Titles', pad=''): def printLine(obj, printers, pad=''): values = '' for printer in printers: - values += ('{:^%i}'%printer['width']).format(printer['format'] % printer['value'](obj)) + values += ('{{:^{0:d}}}'.format(printer['width'])).format(printer['format'] % printer['value'](obj)) print pad + values def checkStoppers(obj, stoppers): @@ -104,12 +104,12 @@ def checkStoppers(obj, stoppers): 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 + "{0!s}{1!s}{2!s}".format('-'*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 + "{0!s}{1!s}{2!s}".format('-'*25, done, '-'*25) def callHooks(match, mainFirst=False): """ @@ -144,14 +144,14 @@ def callHooks(match, mainFirst=False): extra = """ - If you have things that also need to run in the method %s, you can create a method:: + If you have things that also need to run in the method {0!s}, you can create a method:: - def _%s*(self, ... ): + def _{1!s}*(self, ... ): pass - Where the * can be any string. If present, _%s* will be called at the start of the default %s call. + Where the * can be any string. If present, _{2!s}* will be called at the start of the default {3!s} call. You may also completely overwrite this function. - """ % (match, match, match, match) + """.format(match, match, match, match) doc = wrapper.__doc__ wrapper.__doc__ = ('' if doc is None else doc) + extra return wrapper @@ -186,7 +186,7 @@ def asArray_N_x_Dim(pts, dim): elif len(pts.shape) == 1: pts = pts[:,np.newaxis] - assert pts.shape[1] == dim, "pts must be a column vector of shape (nPts, %d) not (%d, %d)" % ((dim,)+pts.shape) + assert pts.shape[1] == dim, "pts must be a column vector of shape (nPts, {0:d}) not ({1:d}, {2:d})".format(*((dim,)+pts.shape)) return pts @@ -207,17 +207,17 @@ def requires(var): .. note:: - To use survey.%s(), SimPEG requires that a problem be bound to the survey. + To use survey.{0!s}(), SimPEG requires that a problem be bound to the survey. If a problem has not been bound, an Exception will be raised. To bind a problem to the Data object:: survey.pair(myProblem) - """ % f.__name__ + """.format(f.__name__) else: extra = """ - To use *%s* method, SimPEG requires that the %s be specified. - """ % (f.__name__, var) + To use *{0!s}* method, SimPEG requires that the {1!s} be specified. + """.format(f.__name__, var) @wraps(f) def requiresVarWrapper(self,*args,**kwargs): if getattr(self, var, None) is None: diff --git a/SimPEG/Utils/curvutils.py b/SimPEG/Utils/curvutils.py index f49d292f..576bbf50 100644 --- a/SimPEG/Utils/curvutils.py +++ b/SimPEG/Utils/curvutils.py @@ -80,7 +80,7 @@ def indexCube(nodes, gridSize, n=None): # Make sure that we choose from the possible nodes. possibleNodes = 'ABCD' if gridSize.size == 2 else 'ABCDEFGH' for node in nodes: - assert node in possibleNodes, "Nodes must be chosen from: '%s'" % possibleNodes + assert node in possibleNodes, "Nodes must be chosen from: '{0!s}'".format(possibleNodes) dim = gridSize.size if n is None: n = gridSize - 1 diff --git a/SimPEG/Utils/matutils.py b/SimPEG/Utils/matutils.py index 73f414b3..da730342 100644 --- a/SimPEG/Utils/matutils.py +++ b/SimPEG/Utils/matutils.py @@ -278,7 +278,7 @@ class TensorType(object): else: raise Exception('Unexpected shape of tensor') def __str__(self): - return 'TensorType[%i]: %s' % (self._tt, self._tts) + return 'TensorType[{0:d}]: {1!s}'.format(self._tt, self._tts) def __eq__(self, v): return self._tt == v def __le__(self, v): return self._tt <= v def __ge__(self, v): return self._tt >= v diff --git a/SimPEG/Utils/modelutils.py b/SimPEG/Utils/modelutils.py index dad92fae..cebda894 100644 --- a/SimPEG/Utils/modelutils.py +++ b/SimPEG/Utils/modelutils.py @@ -26,7 +26,7 @@ def surface2ind_topo(mesh, topo, gridLoc='CC'): gridTopo = Ftopo(XY).reshape(mesh.vnN[:2], order='F') if mesh._meshType not in ['TENSOR', 'CYL', 'BASETENSOR']: - raise NotImplementedError('Nodal surface2ind_topo not implemented for %s mesh'%mesh._meshType) + raise NotImplementedError('Nodal surface2ind_topo not implemented for {0!s} mesh'.format(mesh._meshType)) Nz = mesh.vectorNz[1:] # TODO: this will only work for tensor meshes actind = np.array([False]*mesh.nC).reshape(mesh.vnC, order='F') @@ -47,7 +47,7 @@ def surface2ind_topo(mesh, topo, gridLoc='CC'): gridTopo = Ftopo(mesh.vectorNx) if mesh._meshType not in ['TENSOR', 'CYL', 'BASETENSOR']: - raise NotImplementedError('Nodal surface2ind_topo not implemented for %s mesh'%mesh._meshType) + raise NotImplementedError('Nodal surface2ind_topo not implemented for {0!s} mesh'.format(mesh._meshType)) Ny = mesh.vectorNy[1:] # TODO: this will only work for tensor meshes actind = np.array([False]*mesh.nC).reshape(mesh.vnC, order='F') diff --git a/docs/conf.py b/docs/conf.py index d696464d..9dd8611e 100644 --- a/docs/conf.py +++ b/docs/conf.py @@ -266,7 +266,7 @@ def _supress_nonlocal_image_warn(self, msg, node): from docutils.utils import get_source_line if not msg.startswith('nonlocal image URI found:'): - self._warnfunc(msg, '%s:%s' % get_source_line(node)) + self._warnfunc(msg, '{0!s}:{1!s}'.format(*get_source_line(node))) supress_nonlocal_image_warn() diff --git a/docs/simpegdocs.py b/docs/simpegdocs.py index 002df6bd..c245e7ed 100644 --- a/docs/simpegdocs.py +++ b/docs/simpegdocs.py @@ -54,7 +54,7 @@ class Images(webapp2.RequestHandler): class Redirect(webapp2.RequestHandler): def get(self): path = str(self.request.path).split(os.path.sep)[3:] - self.redirect(('/%s'%os.path.sep.join(path)), permanent=True) + self.redirect(('/{0!s}'.format(os.path.sep.join(path))), permanent=True) class MainPage(webapp2.RequestHandler): diff --git a/tests/base/test_regularization.py b/tests/base/test_regularization.py index 6dddfb74..c6d43122 100644 --- a/tests/base/test_regularization.py +++ b/tests/base/test_regularization.py @@ -28,14 +28,14 @@ class RegularizationTests(unittest.TestCase): for i, mesh in enumerate(self.meshlist): - print 'Testing %iD'%mesh.dim + print 'Testing {0:d}D'.format(mesh.dim) mapping = r.mapPair(mesh) reg = r(mesh, mapping=mapping) m = np.random.rand(mapping.nP) reg.mref = np.ones_like(m)*np.mean(m) - print 'Check: phi_m (mref) = %f' %reg.eval(reg.mref) + print 'Check: phi_m (mref) = {0:f}'.format(reg.eval(reg.mref)) passed = reg.eval(reg.mref) < TOL self.assertTrue(passed) @@ -56,7 +56,7 @@ class RegularizationTests(unittest.TestCase): for i, mesh in enumerate(self.meshlist): - print 'Testing Active Cells %iD'%(mesh.dim) + print 'Testing Active Cells {0:d}D'.format((mesh.dim)) if mesh.dim == 1: indActive = Utils.mkvc(mesh.gridCC <= 0.8) @@ -70,7 +70,7 @@ class RegularizationTests(unittest.TestCase): m = np.random.rand(mesh.nC)[indAct] reg.mref = np.ones_like(m)*np.mean(m) - print 'Check: phi_m (mref) = %f' %reg.eval(reg.mref) + print 'Check: phi_m (mref) = {0:f}'.format(reg.eval(reg.mref)) passed = reg.eval(reg.mref) < TOL self.assertTrue(passed) @@ -87,7 +87,7 @@ class RegularizationTests(unittest.TestCase): for i, mesh in enumerate(self.meshlist): - print 'Testing %iD'%mesh.dim + print 'Testing {0:d}D'.format(mesh.dim) # mapping = r.mapPair(mesh) # reg = r(mesh, mapping=mapping) diff --git a/tests/docs/test_docs.py b/tests/docs/test_docs.py index 9b986632..947fba51 100644 --- a/tests/docs/test_docs.py +++ b/tests/docs/test_docs.py @@ -14,9 +14,9 @@ class Doc_Test(unittest.TestCase): html_path = os.path.sep.join(self.path_to_docs.split(os.path.sep) + ['_build']+['html']) check = subprocess.call(["sphinx-build", "-nW", "-b", "html", "-d", - "%s"%(doctrees_path) , - "%s"%(self.path_to_docs), - "%s"%(html_path)]) + "{0!s}".format((doctrees_path)) , + "{0!s}".format((self.path_to_docs)), + "{0!s}".format((html_path))]) assert check == 0 # def test_latex(self): diff --git a/tests/em/fdem/inverse/adjoint/test_FDEM_adjointEB.py b/tests/em/fdem/inverse/adjoint/test_FDEM_adjointEB.py index 25762368..1b57871e 100644 --- a/tests/em/fdem/inverse/adjoint/test_FDEM_adjointEB.py +++ b/tests/em/fdem/inverse/adjoint/test_FDEM_adjointEB.py @@ -21,7 +21,7 @@ SrcList = ['RawVec', 'MagDipole'] #or 'MAgDipole_Bfield', 'CircularLoop', 'RawVe def adjointTest(fdemType, comp): prb = getFDEMProblem(fdemType, comp, SrcList, freq) - print 'Adjoint %s formulation - %s' % (fdemType, comp) + print 'Adjoint {0!s} formulation - {1!s}'.format(fdemType, comp) m = np.log(np.ones(prb.mapping.nP)*CONDUCTIVITY) mu = np.ones(prb.mesh.nC)*MU diff --git a/tests/em/fdem/inverse/adjoint/test_FDEM_adjointHJ.py b/tests/em/fdem/inverse/adjoint/test_FDEM_adjointHJ.py index c3fb3d37..1dd41c8a 100644 --- a/tests/em/fdem/inverse/adjoint/test_FDEM_adjointHJ.py +++ b/tests/em/fdem/inverse/adjoint/test_FDEM_adjointHJ.py @@ -21,7 +21,7 @@ SrcList = ['RawVec', 'MagDipole'] #or 'MAgDipole_Bfield', 'CircularLoop', 'RawVe def adjointTest(fdemType, comp): prb = getFDEMProblem(fdemType, comp, SrcList, freq) - print 'Adjoint %s formulation - %s' % (fdemType, comp) + print 'Adjoint {0!s} formulation - {1!s}'.format(fdemType, comp) m = np.log(np.ones(prb.mapping.nP)*CONDUCTIVITY) mu = np.ones(prb.mesh.nC)*MU diff --git a/tests/em/fdem/inverse/derivs/test_FDEM_derivs.py b/tests/em/fdem/inverse/derivs/test_FDEM_derivs.py index 0a2e8b82..10de6def 100644 --- a/tests/em/fdem/inverse/derivs/test_FDEM_derivs.py +++ b/tests/em/fdem/inverse/derivs/test_FDEM_derivs.py @@ -26,7 +26,7 @@ SrcType = ['MagDipole', 'RawVec'] #or 'MAgDipole_Bfield', 'CircularLoop', 'RawVe def derivTest(fdemType, comp): prb = getFDEMProblem(fdemType, comp, SrcType, freq) - print '%s formulation - %s' % (fdemType, comp) + print '{0!s} formulation - {1!s}'.format(fdemType, comp) x0 = np.log(np.ones(prb.mapping.nP)*CONDUCTIVITY) mu = np.log(np.ones(prb.mesh.nC)*MU) diff --git a/tests/em/tdem/test_TDEM_forward_Analytic.py b/tests/em/tdem/test_TDEM_forward_Analytic.py index 7748b5fc..8242f846 100644 --- a/tests/em/tdem/test_TDEM_forward_Analytic.py +++ b/tests/em/tdem/test_TDEM_forward_Analytic.py @@ -55,7 +55,7 @@ def halfSpaceProblemAnaDiff(meshType, sig_half=1e-2, rxOffset=50., bounds=None, 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--') plt.loglog(rx.times, abs(bz_ana), 'b*') - plt.title('sig_half = %e'%sig_half) + plt.title('sig_half = {0:e}'.format(sig_half)) plt.show() return log10diff diff --git a/tests/examples/test_examples.py b/tests/examples/test_examples.py index edb5600c..85e208b9 100644 --- a/tests/examples/test_examples.py +++ b/tests/examples/test_examples.py @@ -25,7 +25,7 @@ class compareInitFiles(unittest.TestCase): def get(test): def test_func(self): - print '\nTesting %s.run(plotIt=False)\n'%test + print '\nTesting {0!s}.run(plotIt=False)\n'.format(test) getattr(Examples, test).run(plotIt=False) self.assertTrue(True) return test_func diff --git a/tests/flow/test_Richards.py b/tests/flow/test_Richards.py index f67ec71d..50805ca9 100644 --- a/tests/flow/test_Richards.py +++ b/tests/flow/test_Richards.py @@ -121,7 +121,7 @@ class RichardsTests1D(unittest.TestCase): 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 '{0:4.4e} === {1:4.4e}, diff={2:4.4e} < {3:4e}'.format(vJz, zJv, np.abs(vJz - zJv), tol) self.assertTrue(passed,True) def test_Sensitivity(self): @@ -193,7 +193,7 @@ class RichardsTests2D(unittest.TestCase): 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 '{0:4.4e} === {1:4.4e}, diff={2:4.4e} < {3:4e}'.format(vJz, zJv, np.abs(vJz - zJv), tol) self.assertTrue(passed,True) def test_Sensitivity(self): @@ -265,7 +265,7 @@ class RichardsTests3D(unittest.TestCase): 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 '{0:4.4e} === {1:4.4e}, diff={2:4.4e} < {3:4e}'.format(vJz, zJv, np.abs(vJz - zJv), tol) self.assertTrue(passed,True) def test_Sensitivity(self):