def main( argv ): from optparse import OptionParser parser = OptionParser( "Curvefit - fits data in datafile with different curves\n usage: %prog [options] Datafile" ) parser.add_option("-v", "--verbose", dest = "verbose", action = "store_true" , help = "be verbose", default = False ) parser.add_option("-n", "--np", dest = "np", type = "int", default = 1 , help = "Number of polynomials" ) (options, args) = parser.parse_args() if len( args ) == 0: parser.print_help() print("Please add a datafile.") sys.exit( 2 ) else: datafile = args[ 0 ]; xy = g.RMatrix() g.loadMatrixCol( xy, datafile ); if options.verbose: print("data:", xy) # two coefficients and x-vector (first data column) f = FunctionModelling( options.np + 1, xy[ 0 ] ) # initialize inversion with data and forward operator and set options inv = g.RInversion( xy[ 1 ], f, True, True ); # constant absolute error of 0.01 (not necessary, only for chi^2) inv.setAbsoluteError( 0.01 ); # the problem is well-posed and does not need regularization inv.setLambda( 0 ); # actual inversion run yielding coefficient model coeff = inv.run(); # get actual response and write to file. g.save( inv.response(), "resp.out" ); # print result to screen and save coefficient vector to file s = "y = " + str( round( coeff[ 0 ] * 1000 ) /1000 ) for i in range( 1, options.np+1 ): s = s + " + " + str( round( coeff[ i ] *1000 ) / 1000 ) + " x^" + str( i ) print(s) g.save( coeff, "out.vec" ); P.plot( xy[0], xy[1], 'rx', xy[0], inv.response(), 'b-' ) P.title(s) P.xlabel("x"); P.ylabel("y"); P.legend(("measured", "fitted"),loc="upper left"); P.show()
def _createParameterContraintsLines(mesh, cMat, cWeight=None): """TODO Documentme.""" C = pg.RMatrix() if isinstance(cMat, pg.SparseMapMatrix): cMat.save('tmpC.matrix') pg.loadMatrixCol(C, 'tmpC.matrix') else: C = cMat cellList = dict() for c in mesh.cells(): pID = c.marker() if pID not in cellList: cellList[pID] = [] cellList[pID].append(c) paraCenter = dict() for pID, vals in list(cellList.items()): p = pg.RVector3(0.0, 0.0, 0.0) for c in vals: p += c.center() p /= float(len(vals)) paraCenter[pID] = p nConstraints = C[0].size() start = [] end = [] # swatch = pg.Stopwatch(True) # not used for i in range(0, int(nConstraints / 2)): # print i # if i == 3: break; idL = int(C[1][i * 2]) idR = int(C[1][i * 2 + 1]) p1 = paraCenter[idL] p2 = paraCenter[idR] if cWeight is not None: pa = pg.RVector3(p1 + (p2 - p1) / 2.0 * (1.0 - cWeight[i])) pb = pg.RVector3(p2 + (p1 - p2) / 2.0 * (1.0 - cWeight[i])) else: pa = p1 pb = p2 # print(i, idL, idR, p1, p2) start.append(pa) end.append(pb) # updateAxes_(ax) # not existing return start, end
def loadSIPallData(filename, outnumpy=False): """load SIP data with the columns ab/2,mn/2,rhoa and PHI with the corresponding frequencies in the first row.""" if outnumpy: A = N.loadtxt(filename) fr = A[0, 3:] ab2 = A[1:, 0] mn2 = A[1:, 1] rhoa = A[1:, 2] PHI = A[1:, 3:] else: A = pg.RMatrix() pg.loadMatrixCol(A, 'sch/dc.ves') ndata = A.cols() ab2 = A[0](1, ndata) mn2 = A[1](1, ndata) rhoa = A[2](1, ndata) PHI = pg.RMatrix() fr = [] for i in range(3, A.rows()): fr.append(A[i][0]) PHI.push_back(A[i](1, ndata)) return ab2, mn2, rhoa, PHI, fr
def loadmrsproject(mydir): """ load mrs project from given directory (zkernel.ve) (datacube.dat, KR/KI.bmat, zkernel.vec) """ if mydir is None: mydir = '.' if mydir[-1] != '/': mydir = mydir + '/' # load files from directory zvec = pg.Vector(mydir + 'zkernel.vec') KR = pg.Matrix(mydir + 'KR.bmat') KI = pg.Matrix(mydir + 'KI.bmat') A = pg.Matrix() pg.loadMatrixCol(A, mydir + 'datacube.dat') t = np.array(A[0]) # data datvec = pg.Vector() for i in range(1, len(A)): datvec = pg.cat(datvec, A[i]) # print len(A), len(t) return KR, KI, zvec, t, datvec
def loadmrsproject(mydir): """ load mrs project from given directory (zkernel.ve) (datacube.dat, KR/KI.bmat, zkernel.vec) """ if mydir is None: mydir = '.' if mydir[-1] != '/': mydir = mydir + '/' # load files from directory zvec = pg.RVector(mydir + 'zkernel.vec') KR = pg.RMatrix(mydir + 'KR.bmat') KI = pg.RMatrix(mydir + 'KI.bmat') A = pg.RMatrix() pg.loadMatrixCol(A, mydir + 'datacube.dat') t = N.array(A[0]) # data datvec = pg.RVector() for i in range(1, len(A)): datvec = pg.cat(datvec, A[i]) # print len(A), len(t) return KR, KI, zvec, t, datvec
def _createParameterContraintsLines(mesh, cMat, cWeight=None): """TODO Documentme.""" C = pg.RMatrix() if isinstance(cMat, pg.SparseMapMatrix): cMat.save('tmpC.matrix') pg.loadMatrixCol(C, 'tmpC.matrix') else: C = cMat paraMarker = mesh.cellMarkers() cellList = dict() for cID in range(len(paraMarker)): if cID not in cellList: cellList[cID] = [] cellList[cID].append(mesh.cell(cID)) paraCenter = dict() for cID, vals in list(cellList.items()): p = pg.RVector3(0.0, 0.0, 0.0) for c in vals: p += c.center() p /= float(len(vals)) paraCenter[cID] = p nConstraints = C[0].size() start = [] end = [] # swatch = pg.Stopwatch(True) # not used for i in range(0, int(nConstraints / 2)): # print i # if i == 1000: break; idL = int(C[1][i * 2]) idR = int(C[1][i * 2 + 1]) # leftCells = [] # rightCells = [] # for c, index in enumerate(paraMarker): # if idL == index: # leftCells.append(mesh.cell(c)) # if idR == index: # rightCells.append(mesh.cell(c)) # p1 = pg.RVector3(0.0,0.0); # for c in leftCells: # p1 += c.center() # p1 /= float(len(leftCells)) # p2 = pg.RVector3(0.0,0.0); # for c in rightCells: # p2 += c.center() # print cWeight[i] # p2 /= float(len(rightCells)) p1 = paraCenter[idL] p2 = paraCenter[idR] if cWeight is not None: pa = pg.RVector3(p1 + (p2 - p1) / 2.0 * (1.0 - cWeight[i])) pb = pg.RVector3(p2 + (p1 - p2) / 2.0 * (1.0 - cWeight[i])) else: pa = p1 pb = p2 start.append(pa) end.append(pb) # updateAxes_(ax) # not existing return start, end
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygimli as g import pylab as P from pygimli.utils.base import draw1dmodel nlay = 30 lam = 20. errPerc = 3. isBlocky = False abmnr=g.RMatrix() g.loadMatrixCol(abmnr,"sond1-100.ves") ab2 = abmnr[0] mn2 = abmnr[1] rhoa = abmnr[2] maxDep = max( ab2 ) / 2. print("Maximum depth estimated to ", maxDep) thk = g.RVector( nlay - 1, maxDep / ( nlay - 1 ) ) thk *= ( maxDep / sum( thk ) / 3 ) transRho = g.RTransLog() transRhoa = g.RTransLog() f=g.DC1dRhoModelling( thk, ab2, mn2 ) inv = g.RInversion( rhoa, f, True ) model = g.RVector( nlay, P.median( rhoa ) ) inv.setModel( model )
#!/usr/bin/env python # -*- coding: utf-8 -*- import pygimli as g import pylab as P from pygimli.utils.base import draw1dmodel nlay = 4 lam = 200. errPerc = 3. abmnr = g.RMatrix() g.loadMatrixCol(abmnr, "sond1-100.ves") ab2 = abmnr[0] mn2 = abmnr[1] rhoa = abmnr[2] transRho = g.RTransLogLU(1., 1000.) transThk = g.RTransLog() transRhoa = g.RTransLog() f = g.DC1dModelling(nlay, ab2, mn2) f.region(0).setTransModel(transThk) f.region(1).setTransModel(transRho) paraDepth = max(ab2) / 3 f.region(0).setStartValue(max(ab2) / 3. / nlay / 2.) f.region(1).setStartValue(P.median(rhoa)) model = f.createStartVector() model[nlay] *= 1.5
def createParameterContraintsLines(mesh, cMat, cWeight=None): """ What is this? """ C = pg.RMatrix() if isinstance(cMat, pg.DSparseMapMatrix): cMat.save('tmpC.matrix') pg.loadMatrixCol(C, 'tmpC.matrix') else: C = cMat paraMarker = mesh.cellMarker() cellList = dict() for cID in range(len(paraMarker)): if cID not in cellList: cellList[cID] = [] cellList[cID].append(mesh.cell(cID)) paraCenter = dict() for cID, vals in list(cellList.items()): p = pg.RVector3(0.0, 0.0, 0.0) for c in vals: p += c.center() p /= float(len(vals)) paraCenter[cID] = p nConstraints = C[0].size() start = [] end = [] # swatch = pg.Stopwatch(True) # not used for i in range(0, nConstraints / 2): # print i # if i == 1000: break; idL = int(C[1][i * 2]) idR = int(C[1][i * 2 + 1]) # leftCells = [] # rightCells = [] # for c, index in enumerate(paraMarker): # if idL == index: # leftCells.append(mesh.cell(c)) # if idR == index: # rightCells.append(mesh.cell(c)) # p1 = pg.RVector3(0.0,0.0); # for c in leftCells: # p1 += c.center() # p1 /= float(len(leftCells)) # p2 = pg.RVector3(0.0,0.0); # for c in rightCells: # p2 += c.center() # print cWeight[i] # p2 /= float(len(rightCells)) p1 = paraCenter[idL] p2 = paraCenter[idR] if cWeight is not None: pa = pg.RVector3(p1 + (p2 - p1) / 2.0 * (1.0 - cWeight[i])) pb = pg.RVector3(p2 + (p1 - p2) / 2.0 * (1.0 - cWeight[i])) else: pa = p1 pb = p2 start.append(pa) end.append(pb) # updateAxes_(axes) # not existing return start, end
def _createParameterContraintsLines(mesh, cMat, cWeights=None): """Create line segments representing constrains. """ C = None if isinstance(cMat, pg.matrix.SparseMapMatrix): tmp = pg.optImport('tempfile') _, tmpFile = tmp.mkstemp(suffix='.matrix') C = pg.Matrix() cMat.save(tmpFile) pg.loadMatrixCol(C, tmpFile) try: import os os.remove(tmpFile) except Exception as e: pg.error(e) print("can't remove:", tmpFile) else: C = cMat cellList = dict() for c in mesh.cells(): pID = c.marker() if pID not in cellList: cellList[pID] = [] cellList[pID].append(c) paraCenter = dict() for pID, vals in list(cellList.items()): p = pg.RVector3(0.0, 0.0, 0.0) for c in vals: p += c.center() p /= float(len(vals)) paraCenter[pID] = p nConstraints = cMat.rows() start = [] end = [] # swatch = pg.core.Stopwatch(True) # not used i = -1 while i < C[0].size(): cID = C[0][i] a = C[1][i] b = None if i < C[0].size() - 1: if C[0][i + 1] == cID: b = C[1][i + 1] i += 1 if b is not None: if cWeights[cID] > 0: p1 = paraCenter[a] p2 = paraCenter[b] if cWeights is not None: pa = pg.RVector3(p1 + (p2 - p1) / 2.0 * (1.0 - cWeights[cID])) pb = pg.RVector3(p2 + (p1 - p2) / 2.0 * (1.0 - cWeights[cID])) else: pa = p1 pb = p2 start.append(pa) end.append(pb) else: start.append(paraCenter[a]) end.append(paraCenter[a]) i += 1 return start, end
def main(argv): from optparse import OptionParser parser = OptionParser( "Curvefit - fits data in datafile with different curves\n usage: %prog [options] Datafile" ) parser.add_option("-v", "--verbose", dest="verbose", action="store_true", help="be verbose", default=False) parser.add_option("-n", "--np", dest="np", type="int", default=1, help="Number of polynomials") (options, args) = parser.parse_args() if len(args) == 0: parser.print_help() print("Please add a datafile.") sys.exit(2) else: datafile = args[0] xy = g.RMatrix() g.loadMatrixCol(xy, datafile) if options.verbose: print("data:", xy) # two coefficients and x-vector (first data column) f = FunctionModelling(options.np + 1, xy[0]) # initialize inversion with data and forward operator and set options inv = g.RInversion(xy[1], f, True, True) # constant absolute error of 0.01 (not necessary, only for chi^2) inv.setAbsoluteError(0.01) # the problem is well-posed and does not need regularization inv.setLambda(0) # actual inversion run yielding coefficient model coeff = inv.run() # get actual response and write to file. g.save(inv.response(), "resp.out") # print result to screen and save coefficient vector to file s = "y = " + str(round(coeff[0] * 1000) / 1000) for i in range(1, options.np + 1): s = s + " + " + str(round(coeff[i] * 1000) / 1000) + " x^" + str(i) print(s) g.save(coeff, "out.vec") P.plot(xy[0], xy[1], 'rx', xy[0], inv.response(), 'b-') P.title(s) P.xlabel("x") P.ylabel("y") P.legend(("measured", "fitted"), loc="upper left") P.show()