コード例 #1
0
def testShapefunctions( ):
    poly = g.Mesh( 3 )
    n0 = poly.createNode( 0.0, 0.0, 0.0 )
    n1 = poly.createNode( 1.0, 0.0, 0.0 )
    n2 = poly.createNode( 0.0, 1.0, 0.0 )
    n3 = poly.createNode( 0.0, 0.0, 0.5 )

    poly.createTetrahedron( n0, n1, n2, n3 )
    prism = poly.createP2Mesh()
            
    
    u = g.RVector( prism.nodeCount(), 0.0 ) 
    u[ 5 ] = 1.0
    prism.addExportData( "u", u )
    
    #n3 = poly.createNode( 1.0, 1.0, 0.0 )
    #poly.createTriangle( n0, n1, n3 )
    #prism = g.createMesh3D( poly, g.asvector( np.linspace( 0, -1, 2 ) ) )
    #prism.exportVTK( "prism" )

    
    
    #mesh2 = g.createMesh2D( g.asvector( np.linspace( 0, 1, 10 ) ), 
                            #g.asvector( np.linspace( 0, 1, 10 ) ) )
                                
    #mesh2 = mesh2.createH2Mesh()
                            
    #g.interpolate( prism, mesh2 )
        
    #ax = g.viewer.showMesh( mesh2, mesh2.exportData('u'), filled = True, showLater = True )
        
    mesh3 = g.createMesh3D( g.asvector( np.linspace( 0, 1, 11 ) ), 
                            g.asvector( np.linspace( 0, 1, 11 ) ), 
                            g.asvector( np.linspace( 0, 1, 11 ) ) )

    grads = g.stdVectorRVector3( )
    c = prism.cell( 0 )
    uc = g.RVector( mesh3.nodeCount() )
    
    for n in mesh3.nodes():
        p = c.shape().xyz( n.pos() )
        
        if not c.shape().isInside( p ):
            grads.append( g.RVector3( 0.0, 0.0, 0.0 ) )
            uc[ n.id() ] = 0.0
            continue
        
        uc[ n.id() ] = c.pot( p, u )
        print uc[ n.id() ]
        gr = c.grad( p, u )
        grads.append( gr )
        
    g.interpolate( prism, mesh3 )
    mesh3.addExportData( 'ua', uc )

    mesh3.exportVTK( "prismHex", grads )
    
    
    P.show()
コード例 #2
0
def testShapefunctions():
    poly = g.Mesh(3)
    n0 = poly.createNode(0.0, 0.0, 0.0)
    n1 = poly.createNode(1.0, 0.0, 0.0)
    n2 = poly.createNode(0.0, 1.0, 0.0)
    n3 = poly.createNode(0.0, 0.0, 0.5)

    poly.createTetrahedron(n0, n1, n2, n3)
    prism = poly.createP2Mesh()

    u = g.RVector(prism.nodeCount(), 0.0)
    u[5] = 1.0
    prism.addExportData("u", u)

    #n3 = poly.createNode( 1.0, 1.0, 0.0 )
    #poly.createTriangle( n0, n1, n3 )
    #prism = g.createMesh3D( poly, g.asvector( np.linspace( 0, -1, 2 ) ) )
    #prism.exportVTK( "prism" )

    #mesh2 = g.createMesh2D( g.asvector( np.linspace( 0, 1, 10 ) ),
    #g.asvector( np.linspace( 0, 1, 10 ) ) )

    #mesh2 = mesh2.createH2Mesh()

    #g.interpolate( prism, mesh2 )

    #ax = g.viewer.showMesh( mesh2, mesh2.exportData('u'), filled = True, showLater = True )

    mesh3 = g.createMesh3D(g.asvector(np.linspace(0, 1, 11)),
                           g.asvector(np.linspace(0, 1, 11)),
                           g.asvector(np.linspace(0, 1, 11)))

    grads = g.stdVectorRVector3()
    c = prism.cell(0)
    uc = g.RVector(mesh3.nodeCount())

    for n in mesh3.nodes():
        p = c.shape().xyz(n.pos())

        if not c.shape().isInside(p):
            grads.append(g.RVector3(0.0, 0.0, 0.0))
            uc[n.id()] = 0.0
            continue

        uc[n.id()] = c.pot(p, u)
        print uc[n.id()]
        gr = c.grad(p, u)
        grads.append(gr)

    g.interpolate(prism, mesh3)
    mesh3.addExportData('ua', uc)

    mesh3.exportVTK("prismHex", grads)

    P.show()
コード例 #3
0
ファイル: fdem.py プロジェクト: wk1984/gimli
    def FOPsmooth(self, zvec):
        """
            Retrieve forward modelling operator using fixed layers
            (smooth inversion)

            Parameters
            ----------
            zvec : array
                ???
        """
        return pg.FDEM1dRhoModelling(pg.asvector(zvec),pg.asvector(self.freq()),pg.self.coilSpacing,-self.height)
コード例 #4
0
ファイル: fdem.py プロジェクト: wk1984/gimli
    def inv2D(self, nlay, lam=100., resL=1., resU=1000., thkL=1.,
              thkU=100., minErr=1.0):
        """
            2d LCI inversion class
        """

        if isinstance(nlay, int):
            modVec = pg.RVector(nlay*2 -1, 30.)
            cType = 0 # no reference model
        else:
            modVec = nlay
            cType = 10 # use this as referencemodel
            nlay = (len(modVec) + 1) / 2


        # init forward operator
        self.f2d = self.FOP2d(nlay)

        # transformations
        self.tD = pg.RTrans()
        self.tThk = pg.RTransLogLU(thkL, thkU)
        self.tRes = pg.RTransLogLU(resL, resU)

        for i in range(nlay-1): self.f2d.region(i).setTransModel(self.tThk)

        for i in range(nlay-1, nlay*2-1): self.f2d.region(i).setTransModel(self.tRes)

        # set constraints
        self.f2d.region(0).setConstraintType(cType)
        self.f2d.region(1).setConstraintType(cType)

        # collect data vector
        datvec = pg.RVector(0)

        for i in range(len(self.x)):
            datvec = pg.cat(datvec, self.datavec(i))

        # collect error vector
        errVec = []

        for i in range(len(self.x)):
            errVec.extend(np.maximum(self.ERR[i][self.activeFreq] * 0.701, minErr))
            errVec.extend(np.maximum(self.ERR[i][self.activeFreq] * 0.701, minErr))

        # generate starting model by repetition
        model = pg.asvector(np.repeat(modVec, len(self.x)))
        INV = pg.RInversion(datvec, self.f2d, self.tD)
        INV.setAbsoluteError(pg.asvector(errVec))
        INV.setLambda(lam)
        INV.setModel(model)
        INV.setReferenceModel(model)

        return INV
コード例 #5
0
ファイル: mrs.py プロジェクト: wk1984/gimli
    def response( self, par ):
        """ yield model response cube as vector """
        nl=self.nl_
        thk = par( 0, nl-1 )
        wc  = par( nl-1, 2*nl-1 )
        t2  = par( 2*nl-1, 3*nl-1 )
        zthk = np.cumsum(thk)
        zv = self.zv_
        lzv = len(zv)
        izvec = np.zeros(nl+1,np.int32)
        rzvec = np.zeros(nl+1)
        for i in range(nl-1):
            ii = (zv<zthk[i]).argmin()
            izvec[i+1] = ii
            if ii <= len(zv):
                rzvec[i+1]=(zthk[i]-zv[ii-1])/(zv[ii]-zv[ii-1])

        izvec[-1] = lzv-1
        A = np.zeros((self.nq_,self.nt_),dtype=complex)
        for i in range(nl):
            wcvec = np.zeros(lzv-1)
            wcvec[izvec[i]:izvec[i+1]] = wc[i]
            if izvec[i+1]<lzv: wcvec[izvec[i+1]-1]=wc[i]*rzvec[i+1]
            if izvec[i]>0: wcvec[izvec[i]-1]=wc[i]*(1-rzvec[i])
            amps=np.dot(self.K_,wcvec)
            for ii,a in enumerate(A): a += np.exp(-self.t_/t2[i])*amps[ii]

        return pg.asvector( np.abs(A).ravel() )
コード例 #6
0
ファイル: fdem.py プロジェクト: zhangwise/gimli
    def datavec(self, xpos=0):
        """
            Extract data vector (stack in and out phase) for given pos/no
        """

        ip, op, err = self.selectData(xpos)
        return pg.asvector(np.hstack((ip, op)))
コード例 #7
0
ファイル: utils.py プロジェクト: wk1984/gimli
def grange( start, end, dx = 0, n = 0, log = False ):
    '''
        Return RVector from start step-wise filled with dx until end reached [start, end]\n
        Or RVector is filled from start to end with n steps. [start, end] \n
        If nSteps set RVector can optionaly filled with logarithmic spacing.
    '''
    s = float( start )
    e = float( end )
    d = float( dx )

    if dx != 0:
        if end < start and dx > 0:
            print("grange: decreasing range but increasing dx, swap dx sign")
            d = -d
        if end > start and dx < 0:
            print("grange: increasing range but decreasing dx, swap dx sign")
            d = -d
        ret = pg.asvector( list(range( int( floor( abs( ( e - s ) / d ) ) + 1 ))) )
        ret *= d
        ret += s
        return ret;

    elif n > 0:
        if not log:
            return grange( start, end, dx = ( e - s ) / ( n - 1 ) )
        else:
            raise Exception( 'not yet implemented.' )

    else:
        raise Exception( 'Either dx or nSteps have to be given.' )
コード例 #8
0
ファイル: fdem.py プロジェクト: wk1984/gimli
    def datavec(self, xpos=0):
        """
            Extract data vector (stacking inphase and outphase) for given position or number
        """

        ip, op, err = self.selectData(xpos)
        return pg.asvector(np.hstack((ip, op)))
コード例 #9
0
ファイル: mrstools.py プロジェクト: wk1984/gimli
    def response( self, par ):
        """compute response function."""
        nl = self.nl_
        thk = par( 0, nl-1 )
        wc  = par( nl-1, 2*nl-1 )
        t2  = par( 2*nl-1, 3*nl-1 )
        zthk = N.cumsum(thk)
        zv = self.zv_
        lzv = len(zv)
        izvec = N.zeros( nl + 1, N.int32 )
        rzvec = N.zeros( nl + 1 )
        for i in range(nl-1):
            ii = ( zv<zthk[i] ).argmin()
            izvec[ i + 1 ] = ii
            if ii <= len(zv):
                rzvec[i+1] = ( zthk[i] - zv[ii-1] ) / ( zv[ii] - zv[ii-1] )
        izvec[-1] = lzv - 1
        A = N.zeros( (self.nq_, self.nt_), dtype=complex )
        for i in range(nl):
            wcvec = N.zeros(lzv-1)
            wcvec[ izvec[i]:izvec[i+1] ] = wc[i]
            if izvec[i+1] < lzv:
                wcvec[ izvec[i+1] - 1 ] = wc[i] * rzvec[ i + 1 ]
            if izvec[i] > 0:
                wcvec[ izvec[i] - 1 ] = wc[i] * ( 1 - rzvec[i] )
            amps = N.dot( self.KR_, wcvec ) + N.dot( self.KI_, wcvec ) * 1j
            for ii, a in enumerate(A):
                a += N.exp( -self.t_ / t2[i] ) * amps[ii]

        return pg.asvector( N.abs(A).ravel() )
コード例 #10
0
    def inv2D(self,
              nlay,
              lam=100.,
              resL=1.,
              resU=1000.,
              thkL=1.,
              thkU=100.,
              minErr=1.0):
        """2d LCI inversion class."""
        if isinstance(nlay, int):
            modVec = pg.RVector(nlay * 2 - 1, 30.)
            cType = 0  # no reference model
        else:
            modVec = nlay
            cType = 10  # use this as referencemodel
            nlay = (len(modVec) + 1) / 2

        # init forward operator
        self.f2d = self.FOP2d(nlay)

        # transformations
        self.transData = pg.RTrans()
        self.transThk = pg.RTransLogLU(thkL, thkU)
        self.transRes = pg.RTransLogLU(resL, resU)

        for i in range(nlay - 1):
            self.f2d.region(i).setTransModel(self.transThk)

        for i in range(nlay - 1, nlay * 2 - 1):
            self.f2d.region(i).setTransModel(self.transRes)

        # set constraints
        self.f2d.region(0).setConstraintType(cType)
        self.f2d.region(1).setConstraintType(cType)

        # collect data vector
        datvec = pg.RVector(0)

        for i in range(len(self.x)):
            datvec = pg.cat(datvec, self.datavec(i))

        # collect error vector
        if self.ERR is None:
            error = 1.0
        else:
            error = []
            for i in range(len(self.x)):
                err = np.maximum(self.ERR[i][self.activeFreq] * 0.701, minErr)
                error.extend(err)

        # generate starting model by repetition
        model = pg.asvector(np.repeat(modVec, len(self.x)))
        INV = pg.RInversion(datvec, self.f2d, self.transData)
        INV.setAbsoluteError(error)
        INV.setLambda(lam)
        INV.setModel(model)
        INV.setReferenceModel(model)

        return INV
コード例 #11
0
def hexahedron( p2 ):
    """
    """
    mesh = g.createMesh3D( g.asvector( np.linspace( 0, 1, 2 ) ), 
                           g.asvector( np.linspace( 0, 1, 2 ) ), 
                           g.asvector( np.linspace( 0, 1, 2 ) ) )

    mesh.node(0).setPos( g.RVector3( 0.0, 0.0, 0.5 ) )
    #mesh.rotate( g.RVector3( 10.0, 34.0, 45 ) )
    #mesh.scale( g.RVector3( 0.9, 0.8, 0.7 ) )

    #mesh.rotate( g.RVector3( 10.0, 34.0, 45 ) )
    #mesh.scale( g.RVector3( 1.0, 1.0, 5.0 ) )

    if p2: mesh = mesh.createP2()

    show( mesh )
コード例 #12
0
def DebyeDecomposition(fr,
                       phi,
                       maxfr=None,
                       tv=None,
                       verbose=False,
                       zero=False,
                       err=0.25e-3,
                       lam=10.,
                       blocky=False):
    """Debye decomposition of a phase spectrum."""
    if maxfr is not None:
        idx = (fr <= maxfr) & (phi >= 0.)
        phi1 = phi[idx]
        fr1 = fr[idx]
        print("using frequencies from ", N.min(fr), " to ", N.max(fr), "Hz")
    else:
        phi1 = phi
        fr1 = fr

    if tv is None:
        tmax = 1. / N.min(fr1) / 2. / N.pi * 4.
        tmin = 1. / N.max(fr1) / 2. / N.pi / 8.
        tvec = N.logspace(N.log10(tmin), N.log10(tmax), 30)
    else:
        tvec = tv

    f = DebyeModelling(fr1, tvec, zero=zero)
    tvec = f.t_
    tm = pg.trans.TransLog()
    start = pg.Vector(len(tvec), 1e-4)
    if zero:
        f.region(-1).setConstraintType(0)  # smoothness
        f.region(0).setConstraintType(1)  # smoothness
        f.region(1).setConstraintType(0)  # min length
        f.regionManager().setInterRegionConstraint(-1, 0, 1.)
        f.regionManager().setInterRegionConstraint(0, 1, 1.)
        f.region(-1).setTransModel(tm)
        f.region(0).setTransModel(tm)
        f.region(1).setTransModel(tm)
        f.region(-1).setModelControl(1000.)
        f.region(1).setModelControl(1000.)
    else:
        f.regionManager().setConstraintType(1)  # smoothness

    inv = pg.Inversion(pg.asvector(phi1 * 1e-3), f, verbose)
    inv.setAbsoluteError(pg.Vector(len(fr1), err))
    inv.setLambda(lam)
    inv.setModel(start)
    inv.setBlockyModel(blocky)
    if zero:
        inv.setReferenceModel(start)
    else:
        inv.setTransModel(tm)

    mvec = inv.run()
    resp = inv.response()

    return tvec, mvec, N.array(resp) * 1e3, idx
コード例 #13
0
ファイル: mrsves.py プロジェクト: wk1984/gimli
 def genMods( individual ):
     """ generate MRS and VES models from unit vector """
     model = pg.asvector( individual ) * ( self.lUB - self.lLB ) + self.lLB
     if self.logpar:
         model = pg.exp( model )
     
     modMRS = model(0,nlay*3-1)
     modVES = pg.cat(model(0,nlay-1),model(nlay*3-1,nlay*4-1))
     return modMRS, modVES
コード例 #14
0
ファイル: base.py プロジェクト: zhangwise/gimli
def numpy2gmat(nmat):
    """convert numpy.array into pygimli RMatrix.
    
    TODO implement correct rval
    """
    gmat = pg.RMatrix()
    for arr in nmat:
        gmat.push_back(pg.asvector(arr))
    return gmat
コード例 #15
0
def testCreateTriPrismMesh():
    poly = g.Mesh( 2 )
    n0 = poly.createNode( 0.0, 0.0, 0. )
    n1 = poly.createNode( 1.0, 0.0, 0. )
    n2 = poly.createNode( 0.0, 1.0, 0. )
    n3 = poly.createNode( 1.0, 1.0, 0. )
    poly.createEdge( n0, n1 )
    poly.createEdge( n1, n3 )
    poly.createEdge( n3, n2 )
    poly.createEdge( n2, n0 )
    
    mesh2 = g.Mesh( 2 )
    g.TriangleWrapper( poly, mesh2, "-pzeAfa0.01q34" );

    mesh3 = g.createMesh3D( mesh2, g.asvector( np.arange(0, -1, -0.1 ) ) )
    mesh3.setCellAttributes( g.asvector( range(0, mesh3.cellCount() ) ) )

    mesh3.save( "prism" )
    mesh3.exportVTK( "prism" )
コード例 #16
0
def testCreateTriPrismMesh():
    poly = g.Mesh(2)
    n0 = poly.createNode(0.0, 0.0, 0.)
    n1 = poly.createNode(1.0, 0.0, 0.)
    n2 = poly.createNode(0.0, 1.0, 0.)
    n3 = poly.createNode(1.0, 1.0, 0.)
    poly.createEdge(n0, n1)
    poly.createEdge(n1, n3)
    poly.createEdge(n3, n2)
    poly.createEdge(n2, n0)

    mesh2 = g.Mesh(2)
    g.TriangleWrapper(poly, mesh2, "-pzeAfa0.01q34")

    mesh3 = g.createMesh3D(mesh2, g.asvector(np.arange(0, -1, -0.1)))
    mesh3.setCellAttributes(g.asvector(range(0, mesh3.cellCount())))

    mesh3.save("prism")
    mesh3.exportVTK("prism")
コード例 #17
0
ファイル: mrs.py プロジェクト: wk1984/gimli
 def run(self,nlay=3,lam=10.,startvec=None,verbose=True,uncertainty=False,**kwargs):
     ''' even easier variant returning all in one call '''
     if self.INV is None:
         self.INV = self.createInv(nlay,lam,verbose,**kwargs)
     if startvec is not None:
         self.INV.setModel( pg.asvector( startvec ) )
     if verbose: print("Doing inversion...")
     self.model = np.array( self.INV.run() )
     if uncertainty:
         if verbose: print("Computing uncertainty...")
         self.modelL, self.modelU = iterateBounds( self.INV, dchi2=self.INV.chi2()/2, change=1.2 )
コード例 #18
0
ファイル: siptools.py プロジェクト: wk1984/gimli
    def __init__(self, fvec, tvec=None, zero = False, verbose = False):
        if tvec == None:
            tvec = N.logspace(-4, 0, 5)

        mesh = pg.createMesh1D(len(tvec))
        if zero:
            mesh.cell(0).setMarker(-1)
            mesh.cell(len(tvec)-1).setMarker(1)
        pg.ModellingBase.__init__(self, mesh, verbose)
        self.f_ = pg.asvector(fvec)
        self.t_ = tvec
        self.zero_ = zero
コード例 #19
0
ファイル: siptools.py プロジェクト: KristoferHellman/gimli
def read1resfile(filename, readsecond=False, dellast=True):
    """read Radic instrument res file containing a single spectrum."""
    f = open(filename, 'r')
    line = f.readline()
    fr = []
    rhoa = []
    phi = []
    drhoa = []
    dphi = []
    while True:
        line = f.readline()
        if string.rfind(line, 'Freq') > -1:
            break

    if readsecond:
        while True:
            if string.rfind(f.readline(), 'Freq') > -1:
                break

    while True:
        line = f.readline()
        b = line.split('\t')
        if len(b) < 5:
            break

        fr.append(string.atof(b[0]))
        rhoa.append(string.atof(b[1]))
        phi.append(-string.atof(b[2]) * P.pi / 180.)
        drhoa.append(string.atof(b[3]))
        dphi.append(string.atof(b[4]) * P.pi / 180.)

    f.close()
    if dellast:
        fr.pop(0)
        rhoa.pop(0)
        phi.pop(0)
        drhoa.pop(0)
        dphi.pop(0)

    return fr, rhoa, pg.asvector(phi), drhoa, pg.asvector(dphi)
コード例 #20
0
def read1resfile(filename, readsecond=False, dellast=True):
    """read Radic instrument res file containing a single spectrum."""
    f = open(filename, 'r')
    line = f.readline()
    fr = []
    rhoa = []
    phi = []
    drhoa = []
    dphi = []
    while True:
        line = f.readline()
        if line.rfind('Freq') > -1:
            break

    if readsecond:
        while True:
            if f.readline().rfind('Freq') > -1:
                break

    while True:
        line = f.readline()
        b = line.split('\t')
        if len(b) < 5:
            break

        fr.append(float(b[0]))
        rhoa.append(float(b[1]))
        phi.append(-float(b[2]) * P.pi / 180.)
        drhoa.append(float(b[3]))
        dphi.append(float(b[4]) * P.pi / 180.)

    f.close()
    if dellast:
        fr.pop(0)
        rhoa.pop(0)
        phi.pop(0)
        drhoa.pop(0)
        dphi.pop(0)

    return fr, rhoa, pg.asvector(phi), drhoa, pg.asvector(dphi)
コード例 #21
0
ファイル: em.py プロジェクト: wk1984/gimli
 def invBlock( self, xpos=0, nlay=2, noise=1.0, stmod=10., lam=100., lBound=1., uBound=0., verbose=False ):
     """yield gimli inversion instance for block inversion."""
     """ inv(xpos,nlay) where nlay can be a FOP or a number of layers """
     self.transThk = RTransLog()
     self.transRes = RTransLogLU( lBound, uBound )
     self.transData = RTrans()
     # EM forward operator
     if isinstance( nlay, FDEM1dModelling ):
         self.fop = nlay
     else:
         self.fop = self.FOP( nlay )
     
     data = self.datavec( xpos )
     
     self.fop.region(0).setTransModel( self.transThk )
     self.fop.region(1).setTransModel( self.transRes )
     
     if isinstance( noise, float ):
         noiseVec = RVector( len(data), noise)
     else:
         noiseVec = asvector( noise )
     
     # independent EM inversion
     self.inv = RInversion( data, self.fop, self.transData, verbose )
     if isinstance( stmod, float): # real model given
         model = RVector( nlay * 2 - 1, stmod )
         model[0] = 2.
     else:
         if len( stmod ) == nlay*2-1:
             model = asvector( stmod )
         else:
             model = RVector( nlay*2-1, 30. )
     
     self.inv.setAbsoluteError( noiseVec )
     self.inv.setLambda( lam )
     self.inv.setMarquardtScheme( 0.8 )
     self.inv.setModel( model )
     self.inv.setReferenceModel( model )
     return self.inv
コード例 #22
0
ファイル: siptools.py プロジェクト: KristoferHellman/gimli
def DebyeDecomposition(fr, phi, maxfr=None, tv=None, verbose=False,
                       zero=False, err=0.25e-3, lam=10., blocky=False):
    """Debye decomposition of a phase spectrum."""
    if maxfr is not None:
        idx = (fr <= maxfr) & (phi >= 0.)
        phi1 = phi[idx]
        fr1 = fr[idx]
        print("using frequencies from ", N.min(fr), " to ", N.max(fr), "Hz")
    else:
        phi1 = phi
        fr1 = fr

    if tv is None:
        tmax = 1. / N.min(fr1) / 2. / N.pi * 4.
        tmin = 1. / N.max(fr1) / 2. / N.pi / 8.
        tvec = N.logspace(N.log10(tmin), N.log10(tmax), 30)
    else:
        tvec = tv

    f = DebyeModelling(fr1, tvec, zero=zero)
    tvec = f.t_
    tm = pg.RTransLog()
    start = pg.RVector(len(tvec), 1e-4)
    if zero:
        f.region(-1).setConstraintType(0)  # smoothness
        f.region(0).setConstraintType(1)  # smoothness
        f.region(1).setConstraintType(0)  # min length
        f.regionManager().setInterRegionConstraint(-1, 0, 1.)
        f.regionManager().setInterRegionConstraint(0, 1, 1.)
        f.region(-1).setTransModel(tm)
        f.region(0).setTransModel(tm)
        f.region(1).setTransModel(tm)
        f.region(-1).setModelControl(1000.)
        f.region(1).setModelControl(1000.)
    else:
        f.regionManager().setConstraintType(1)  # smoothness

    inv = pg.RInversion(pg.asvector(phi1 * 1e-3), f, verbose)
    inv.setAbsoluteError(pg.RVector(len(fr1), err))
    inv.setLambda(lam)
    inv.setModel(start)
    inv.setBlockyModel(blocky)
    if zero:
        inv.setReferenceModel(start)
    else:
        inv.setTransModel(tm)

    mvec = inv.run()
    resp = inv.response()

    return tvec, mvec, N.array(resp) * 1e3, idx
コード例 #23
0
ファイル: siptools.py プロジェクト: wk1984/gimli
def ReadAndRemoveEM(filename, readsecond=False, doplot=False,
                    dellast=True, ePhi=0.5, ePerc=1., lam=2000.):
    """ Read res1file and remove EM effects using a double-Cole-Cole model
    fr,rhoa,phi,dphi = ReadAndRemoveEM(filename, readsecond/doplot bools)"""
    fr, rhoa, phi, drhoa, dphi = read1resfile(filename, readsecond,
                                              dellast=dellast)
    # forward problem
    mesh = pg.createMesh1D(1, 6) # 6 independent parameters
    f = DoubleColeColeModelling(mesh, pg.asvector(fr) , phi[2]/abs(phi[2]))
    f.regionManager().loadMap("region.control")
    model = f.createStartVector()
    # inversion
    inv = pg.RInversion(phi, f, True, False)
    inv.setAbsoluteError(phi * ePerc * 0.01 + ePhi / 1000.)
    inv.setRobustData(True)
#    inv.setCWeight(pg.RVector(6, 1.0)) # wozu war das denn gut?
    inv.setMarquardtScheme(0.8)
    inv.setLambda(lam)
    inv.setModel(model)
    erg = inv.run()
    inv.echoStatus()
    chi2 = inv.chi2()
    mod0 = pg.RVector(erg)
    mod0[ 0 ] = 0.0 # set IP term to zero to obtain pure EM term
    emphi = f(mod0)
    resid = (phi - emphi) * 1000.
    if doplot:
        s = "IP: m= " + str(rndig(erg[0])) + " t=" + str(rndig(erg[1]))  +  \
        " c =" + str(rndig(erg[2]))
        s = s + "  EM: m= " + str(rndig(erg[3])) + " t=" + str(rndig(erg[4])) +\
        " c =" + str(rndig(erg[5]))
        fig = P.figure(1)
        fig.clf()
        ax = P.subplot(111)
        P.errorbar(fr, phi*1000., yerr=dphi*1000., fmt='x-', label='measured')
        ax.set_xscale('log')
        P.semilogx(fr, f(mod0) * 1000., label='EM term (CC)')
        P.errorbar(fr, resid, yerr=dphi*1000., label='IP term')
        ax.set_yscale('log')
        P.xlim((min(fr), max(fr)))
        P.ylim((0.1, max(phi) * 1000.))
        P.xlabel('f in Hz')
        P.ylabel(r'-$\phi$ in mrad')
        P.grid(True)
        P.title(s)
        P.legend(loc=2)#('measured','2-cole-cole','residual'))
        fig.show()

    return N.array(fr), N.array(rhoa), N.array(resid), N.array(phi)*1e3, dphi, chi2, N.array(emphi)*1e3
コード例 #24
0
    def __init__(self, fvec, tvec=None, zero=False, verbose=False):

        if tvec is None:
            tvec = N.logspace(-4, 0, 5)

        mesh = pg.createMesh1D(len(tvec))

        if zero:
            mesh.cell(0).setMarker(-1)
            mesh.cell(len(tvec) - 1).setMarker(1)

        pg.ModellingBase.__init__(self, mesh, verbose)
        self.f_ = pg.asvector(fvec)
        self.t_ = tvec
        self.zero_ = zero
コード例 #25
0
ファイル: siptools.py プロジェクト: wk1984/gimli
def astausgleich(ab2org, mn2org, rhoaorg):
    """shifts the branches of a dc sounding to generate a matching curve."""
    ab2 = P.asarray(ab2org)
    mn2 = P.asarray(mn2org)
    rhoa = P.asarray(rhoaorg)
    um = P.unique(mn2)
    for i in range(len(um) - 1):
        r0, r1 = [], []
        ac = P.intersect1d(ab2[ mn2 == um[i] ], ab2[ mn2 == um[ i + 1 ] ])
        for a in ac:
            r0.append(rhoa[ (ab2 == a) * (mn2 == um[i]) ][0])
            r1.append(rhoa[ (ab2 == a) * (mn2 == um[i+1]) ][0])

        if len(r0) > 0:
            fak = P.mean(P.array(r0) / P.array(r1))
            print(fak)
            if P.isfinite(fak) and fak>0.:
                rhoa[ mn2 == um[ i + 1 ] ] *= fak

    return pg.asvector(rhoa)
コード例 #26
0
def makeSlmData(ab2, mn2, rhoa=None, filename=None):
    """generate a pygimli data container from ab/2 and mn/2 array."""
    data = pg.DataContainer()
    data.resize(len(ab2))
    pos = N.unique(N.hstack((ab2, mn2)))

    for elx in N.hstack((-pos[::-1], pos)):
        data.createElectrode(elx, 0., 0.)

    if filename is not None:
        f = open(filename, 'w')
        f.write(str(len(pos) * 2) + '\n#x y z\n')
        for elx in N.hstack((-pos[::-1], pos)):
            f.write(str(elx) + '\t0\t0\n')
            f.write(str(len(ab2)) + '\n#a\tb\tm\tn\tk\trhoa\n')

    lpos = len(pos)
    iab = pos.searchsorted(ab2)
    imn = pos.searchsorted(mn2)

    if (filename is not None) & (rhoa is None):
        rhoa = N.ones(len(ab2))

    for i in range(len(iab)):
        # print -pos[iab[i]], -pos[imn[i]], pos[imn[i]], pos[iab[i]]
        k = (ab2[i]**2 - mn2[i]**2) * N.pi / mn2[i] / 2.0
        if filename is not None:
            f.write(str(lpos - iab[i]) + '\t' + str(lpos + iab[i] + 1) + '\t')
            f.write(str(lpos - imn[i]) + '\t' + str(lpos + imn[i] + 1) + '\t')
            f.write(str(rndig(k, 4)) + '\t' + str(rhoa[i]) + '\n')
        data.createFourPointData(i, int(lpos - iab[i]), int(lpos + iab[i] + 1),
                                 int(lpos - imn[i]), int(lpos + imn[i] + 1))

    if filename is not None:
        f.close()

    data.set('rhoa', pg.asvector(rhoa))
    return data
コード例 #27
0
ファイル: siptools.py プロジェクト: KristoferHellman/gimli
def makeSlmData(ab2, mn2, rhoa=None, filename=None):
    """generate a pygimli data container from ab/2 and mn/2 array."""
    data = pg.DataContainer()
    data.resize(len(ab2))
    pos = N.unique(N.hstack((ab2, mn2)))

    for elx in N.hstack((-pos[::-1], pos)):
        data.createElectrode(elx, 0., 0.)

    if filename is not None:
        f = open(filename, 'w')
        f.write(str(len(pos) * 2) + '\n#x y z\n')
        for elx in N.hstack((-pos[::-1], pos)):
            f.write(str(elx) + '\t0\t0\n')
            f.write(str(len(ab2)) + '\n#a\tb\tm\tn\tk\trhoa\n')

    lpos = len(pos)
    iab = pos.searchsorted(ab2)
    imn = pos.searchsorted(mn2)

    if (filename is not None) & (rhoa is None):
        rhoa = N.ones(len(ab2))

    for i in range(len(iab)):
        #print -pos[iab[i]], -pos[imn[i]], pos[imn[i]], pos[iab[i]]
        k = (ab2[i]**2 - mn2[i]**2) * N.pi / mn2[i] / 2.0
        if filename is not None:
            f.write(str(lpos - iab[i]) + '\t' + str(lpos + iab[i] + 1) + '\t')
            f.write(str(lpos - imn[i]) + '\t' + str(lpos + imn[i] + 1) + '\t')
            f.write(str(rndig(k, 4)) + '\t' + str(rhoa[i]) + '\n')
        data.createFourPointData(i, int(lpos - iab[i]), int(lpos + iab[i] + 1),
                                 int(lpos - imn[i]), int(lpos + imn[i] + 1))

    if filename is not None:
        f.close()

    data.set('rhoa', pg.asvector(rhoa))
    return data
コード例 #28
0
ファイル: testShapePoly.py プロジェクト: ziogibom/gimli
def findMatrix(uN, dim, nCoeff, ptns, pascale, serendipity):
    fop = g.PolynomialModelling(dim, nCoeff, pnts)
    fop.setPascalsStyle(pascale)
    fop.setSerendipityStyle(serendipity)

    tmp = g.RPolynomialFunction(g.RVector(fop.polynomialFunction().size()))
    tmp.fill(fop.startModel())
    print("base:", tmp)

    G = P.zeros((len(pnts), len(tmp.elements())))

    for i, p in enumerate(pnts):
        for j, e in enumerate(tmp.elements()):
            G[i, j] = e(p)

    GI = P.inv(G)
    coef = P.dot(GI, uN)

    print(coef)
    print(P.dot(G, coef))
    tmp.fill(g.asvector(coef))
    print(coef, tmp)
    return tmp
コード例 #29
0
def findMatrix( uN, dim, nCoeff, ptns, pascale, serendipity ):
    fop = g.PolynomialModelling( dim, nCoeff, pnts )
    fop.setPascalsStyle( pascale )
    fop.setSerendipityStyle( serendipity )
    
    tmp = g.RPolynomialFunction( g.RVector( fop.polynomialFunction().size() ) )
    tmp.fill( fop.startModel() )
    print "base:", tmp
    
    G = P.zeros( ( len( pnts), len( tmp.elements() ) ) )
    
    for i, p in enumerate( pnts ):
        for j, e in enumerate( tmp.elements() ):
            G[i,j] = e( p )
    
    GI = P.inv( G )
    coef = P.dot( GI, uN )
    
    print coef
    print P.dot( G, coef )
    tmp.fill( g.asvector( coef ) )
    print coef, tmp
    return tmp
コード例 #30
0
ファイル: harmfit.py プロジェクト: KristoferHellman/gimli
def harmfit(y, x=None, error=None, nc=42, resample=None, lam=0.1,
            window=None, verbose=False, dosave=False,
            lineSearch=True, robust=False, maxiter=20):
    """HARMFIT - GIMLi based curve-fit by harmonic functions
        Parameters
        ----------
        y : 1d-array - values to be fitted

        x : 1d-array(len(y)) - data abscissa data. default: [0 .. len(y))

        error : 1d-array(len(y)) error of y. default (absolute error = 0.01)

        nc : int - Number of harmonic coefficients

        resample : 1d-array - resample y to x using fitting coeffients

        window : int - just fit data inside window bounds

        Returns
        -------
        response : 1d-array(len(resample) or len(x)) - smoothed values

        coefficients : 1d-array - fitting coefficients
    """
    if x is None:
        x = np.arange(len(y))
#    else:
#        if not isinstance(x, pg.RVector):
#            x = pg.asvector(x)
#
#    if not isinstance(y, pg.RVector):
#        y = pg.asvector(y)

    xToFit = None
    yToFit = None

    if window is not None:
        idx = pg.find((x >= window[0]) & (x < window[1]))
#        idx = getIndex(x , lambda v: v > window[0] and v < window[1])

        xToFit = x(idx)
        yToFit = y(idx)

        if error is not None:
            error = error(idx)
    else:
        xToFit = x
        yToFit = y

#    print xToFit
#    print yToFit
    fop = pg.HarmonicModelling(nc, xToFit, verbose)
    inv = pg.RInversion(yToFit, fop, verbose, dosave)
    if error is not None:
        inv.setAbsoluteError(error)
    else:
        inv.setAbsoluteError(0.01)

    inv.setMarquardtScheme(0.8)
    if error is not None:
        inv.stopAtChi1(True)
    inv.setLambda(lam)
    inv.setMaxIter(maxiter)
    inv.setLineSearch(lineSearch)
    inv.setRobustData(robust)
    # inv.setConstraintType(0)

    coeff = inv.run()
    print(inv.chi2())

    if resample is not None:
        if not isinstance(resample, pg.RVector):
            resample = pg.asvector(resample)

        ret = fop.response(coeff, resample)

        if window is not None:
            # print pg.find((resample < window[0]) | (resample >= window[1]))
            ret.setVal(0.0, pg.find((resample < window[0]) |
                                    (resample >= window[1])))
#            idx = getIndex(resample,
#                           lambda v: v <= window[0] or v >= window[1])
#            for i in idx: ret[i] = 0.0
        return ret, coeff
    else:
        return inv.response(), coeff
コード例 #31
0
ファイル: fdem.py プロジェクト: zhangwise/gimli
 def errorvec(self, xpos=0, minvalue=0.0):
     """
         Extract error vector for a give position or sounding number
     """
     ip, op, err = self.selectData(xpos)
     return pg.asvector(np.tile(np.maximum(err * 0.7071, minvalue), 2))
コード例 #32
0
ファイル: testShapePoly.py プロジェクト: ziogibom/gimli
    surf = ax1.plot_surface(X,
                            Y,
                            Z,
                            rstride=1,
                            cstride=1,
                            cmap=P.cm.jet,
                            linewidth=0)

    ax2.set_title(label + N.__str__())
    fig.colorbar(surf)


e1 = [1, -1]  # 1-r
e2 = [0, +1]  # r

E2_1R = g.RPolynomialFunction(g.asvector(e1))
E2_2R = g.RPolynomialFunction(g.asvector(e2))
E2_1S = g.RPolynomialFunction(g.RVector(), g.asvector(e1))
E2_2S = g.RPolynomialFunction(g.RVector(), g.asvector(e2))
E2_1T = g.RPolynomialFunction(g.RVector(), g.RVector(), g.asvector(e1))
E2_2T = g.RPolynomialFunction(g.RVector(), g.RVector(), g.asvector(e2))

E3_1R = E2_1R * (E2_1R - E2_2R)
E3_2R = E2_2R * (E2_2R - E2_1R)
E3_3R = 4. * (E2_1R * E2_2R)

E3_1S = E2_1S * (E2_1S - E2_2S)
E3_2S = E2_2S * (E2_2S - E2_1S)
E3_3S = 4. * (E2_1S * E2_2S)

E3_1T = E2_1T * (E2_1T - E2_2T)
コード例 #33
0
ファイル: FMM2layer.py プロジェクト: KristoferHellman/gimli
        tmpNodes = pg.commonNodes(n.cellSet())
        for nn in tmpNodes:
            if not upTags[nn.id()] and not downTags[nn.id()]:
                downwind.add(nn)
                downTags[nn.id()] = 1

    # start fast marching
    tic = time.time()
    while len(downwind) > 0:
        fastMarch(mesh, downwind, times, upTags, downTags)

    print(time.time() - tic, "s")

    # compare with analytical solution along the x axis
    x = np.arange(0., 100., 0.5)
    t = pg.interpolate(mesh, times, pg.asvector(x), x * 0., x * 0.)
    tdirect = x / v[0]  # direct wave
    alfa = asin(v[0] / v[1])  # critically refracted wave angle
    xreflec = tan(alfa) * zlay * 2.  # first critically refracted
    trefrac = (x - xreflec) / v[1] + xreflec * v[1] / v[0]**2
    tana = np.where(trefrac < tdirect, trefrac, tdirect)  # minimum of both
    print("min(dt)=",
          min(t - tana) * 1000,
          "ms max(dt)=",
          max(t - tana) * 1000,
          "ms")

    # plot traveltime field, a few lines
    fig = plt.figure()
    a = fig.add_subplot(211)
    drawMesh(a, mesh)
コード例 #34
0
ファイル: harmfit.py プロジェクト: zhangwise/gimli
def harmfit(y, x=None, error=None, nCoefficients=42, resample=None,
            window=None, verbose=False, dosave=False,
            lineSearch=True, robust=False, maxiter=20):
    """
        HARMFIT - GIMLi based curve-fit by harmonic functions
        y .. 1d-array(len(y)) values to be fitted
        x .. 1d-array(len(y)) abscissa data spacing. if not given: 1 * [0 .. len(y))
        error .. 1d-array(len(y))  data error of y (fit y into the range of error). if not given (absolute err = 1%)
        nCoefficients .. int Number of harmonic coefficients
        resample .. 1d-array(len(resample)) resample y based on fitting coeffients
        window .. just fit data inside window bounds
        return response, coefficients

        response .. 1d-array(len(y)) if no resample given, else 1d-array(len(resample))
        coefficients .. coefficients for harmic functions that fit y
    """
    if x is None:
        x = pg.asvector(np.arange(len(y)))
    else:
        if not isinstance(x, pg.RVector):
            x = pg.asvector(x)

    if not isinstance(y, pg.RVector):
        y = pg.asvector(y)

    xToFit = None
    yToFit = None

    if window is not None:
        idx = pg.find((x >= window[0]) & (x < window[1]))
        #idx = getIndex(x , lambda v: v > window[0] and v < window[1])

        xToFit = x(idx)
        yToFit = y(idx)

        if error is not None:
            error = error(idx)
    else:
        xToFit = x
        yToFit = y

#    print xToFit
#    print yToFit
    fop = pg.HarmonicModelling(nCoefficients, xToFit, verbose)
    inv = pg.RInversion(yToFit, fop, verbose, dosave)
    if error is not None:
        if not isinstance(error, pg.RVector):
            error = pg.asvector(error)

        inv.setRelativeError(error)
    else:
        inv.setAbsoluteError(0.01)

    inv.setLambda(000.0)
    inv.setLocalRegularization(True)
    inv.setMaxIter(maxiter)
    inv.setLineSearch(lineSearch)
    inv.setRobustData(robust)
    # inv.setConstraintType(0)

    coeff = inv.run()

    if resample is not None:
        if not isinstance(resample, pg.RVector):
            resample = pg.asvector(resample)

        ret = fop.response(coeff, resample)

#        print ret

        if window is not None:
            #            print resample
            #            print window[0], window[1]
            # print pg.find((resample < window[0]) | (resample >= window[1]))
            ret.setVal(
                0.0, pg.find(
                    (resample < window[0]) | (
                        resample >= window[1])))
#            idx = getIndex(resample, lambda v: v <= window[0] or v >= window[1])
#            for i in idx: ret[i] = 0.0
#        print ret
        # sys.exit
        return ret, coeff
    else:
        return inv.response(), coeff
コード例 #35
0
ファイル: fdem.py プロジェクト: KristoferHellman/gimli
    def invBlock(self, xpos=0, nlay=2, noise=1.0,
                 stmod=30., lam=100., lBound=0., uBound=0., verbose=False):
        """
            Yield gimli inversion instance for block inversion
            inv(xpos,nlay) where nlay can be a FOP or a number of layers

            Parameters
            ----------
            xpos : array

            nLay : int
                Number of layers of the model to be determined

            noise : float
                Absolute data err in percent

            stmod : float or pg.RVector
                Starting model

            lam : float
                Global regularization parameter lambda.

            lBound : float
                Lower boundary for the model

            uBound : float
                Upper boundary for the model. 0 means no upper booundary

            verbose : bool
                Be verbose
        """

        self.transThk = pg.RTransLog()
        self.transRes = pg.RTransLogLU(lBound, uBound)
        self.transData = pg.RTrans()

        # EM forward operator
        if isinstance(nlay, pg.FDEM1dModelling):
            self.fop = nlay
        else:
            self.fop = self.FOP(nlay)

        data = self.datavec(xpos)

        self.fop.region(0).setTransModel(self.transThk)
        self.fop.region(1).setTransModel(self.transRes)

        if isinstance(noise, float):
            noiseVec = pg.RVector(len(data), noise)
        else:
            noiseVec = pg.asvector(noise)

        # independent EM inversion
        self.inv = pg.RInversion(data, self.fop, self.transData, verbose)
        if isinstance(stmod, float):  # real model given
            model = pg.RVector(nlay * 2 - 1, stmod)
            model[0] = 2.
        else:
            if len(stmod) == nlay * 2 - 1:
                model = pg.asvector(stmod)
            else:
                model = pg.RVector(nlay * 2 - 1, 30.)

        self.inv.setAbsoluteError(noiseVec)
        self.inv.setLambda(lam)
        self.inv.setMarquardtScheme(0.8)
        self.inv.setDeltaPhiAbortPercent(0.5)
        self.inv.setModel(model)
        self.inv.setReferenceModel(model)
        return self.inv
コード例 #36
0
ファイル: first.py プロジェクト: jchavezolalla/gimli
    def response(self, par):
        y = pg.RVector(self.x_.size(), par[0])

        for i in range(1, self.nc_):
            y += pg.pow(self.x_, i) * par[i]
        return y

    def startModel(self):
        return pg.RVector(self.nc_, 0.5)


#!this is doku within

# evaluate f(x) = 1.1 + 2.1 * x
x = pg.asvector(np.arange(0., 10., 1))
"""
this is doku within
"""

y = 1.1 + 2.1 * x
"""
this is doku within
"""

print((x, y))

nP = 3
# two coefficients and x-vector (first data column)
fop = FunctionModelling(nP, x)
コード例 #37
0
ファイル: plot-1-polyfit.py プロジェクト: zhangwise/gimli
"""
Let us create some synthetic data for some x values
"""

x = np.arange(0., 10., 1)
y = 1.1 + 2.1 * x

"""
We now start by setting up the modelling operator, and inversion and run it.
"""

nP = 3

# two coefficients and x-vector (first data column)
fop = FunctionModelling(nP, pg.asvector(x))

# initialize inversion with data and forward operator and set options
inv = pg.RInversion(y, fop)

# constant absolute error of 0.01 is 1% (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()

print(coeff)
コード例 #38
0
def drawShapes( ax, mesh, u ):
    #ax.set_aspect( 'equal' )
    N = 11
    
    mesh3 = g.createMesh3D( g.asvector( np.linspace( 0, 1, N ) ), 
                            g.asvector( np.linspace( 0, 1, N ) ), 
                            g.asvector( np.linspace( 0, 1, N ) ) )
                            
    uc = g.RVector( mesh3.nodeCount(  ) )
    
    grads = g.stdVectorRVector3( )
    pnts = g.stdVectorRVector3( )
    
    c = mesh.cell( 0 )
    imax=g.find( u == max( u ) )[0]
    
    N = c.createShapeFunctions()[ imax ] 
    print imax, N
#    print imax, c.shape().createShapeFunctions()[imax]
    for i in range( c.nodeCount() ):
        print c.rst( i ), N( c.rst( i ) )
    
    # draw nodes
    for i in range( c.nodeCount() ):
        col = 'black'
        if i == imax:
            col = 'red'
            
        #ax.plot( [c.node( i ).pos()[0], c.node( i ).pos()[0] ], 
                 #[c.node( i ).pos()[1], c.node( i ).pos()[1] ],
                 #[c.node( i ).pos()[2], c.node( i ).pos()[2] ],
                #'.', markersize = 15, linewidth=0, color=col )
    
    newNode = []
    
    for i in range( mesh3.nodeCount(  ) ):
        p = c.shape().xyz( mesh3.node( i ).pos() )
        newNode.append( p )
        
        #ax.plot( p[0], p[1], '.', zorder=10, color='black', markersize = 1 )
        
        if not c.shape().isInside( p ): 
            uc[ i ] = -99.0
            grads.append( g.RVector3( 0.0, 0.0 ) )
            continue
          
        uc[ i ] = c.pot( p, u ) 
        gr = c.grad( p, u ).normalise()
        grads.append( gr )
        
        #ax.plot( [ p[ 0 ], p[ 0 ] + gr[ 0 ]*0.1 ], 
                 #[ p[ 1 ], p[ 1 ] + gr[ 1 ]*0.1 ], 
                 #[ p[ 2 ], p[ 2 ] + gr[ 2 ]*0.1 ], '-', color='black' )
    
        #pnts.append( p )
            
    #print len(pnts)
    #Z = np.ma.masked_where( uc == -99., uc )
    ##ax.plot( g.x(pnts), g.y(pnts), g.z(pnts), '.' )
    
    for i, n in enumerate( mesh3.nodes() ):
        n.setPos( newNode[ i ] )
        
    mesh3.addExportData( 'u', uc.setVal( 0.0, g.find( uc == -99 ) ) )
    name = 'cell' + str( c.nodeCount() ) + '-' + str( imax )
    print "write ", name
    mesh3.exportVTK( name, grads )
コード例 #39
0
ファイル: mrs.py プロジェクト: wk1984/gimli
 def genMod( self, individual ):
     model = pg.asvector( individual ) * ( self.lUB - self.lLB ) + self.lLB
     if self.logpar:
         return pg.exp( model )
     else:
         return model
コード例 #40
0
def harmfit(y,
            x=None,
            error=None,
            nc=42,
            resample=None,
            lam=0.1,
            window=None,
            verbose=False,
            dosave=False,
            lineSearch=True,
            robust=False,
            maxiter=20):
    """HARMFIT - GIMLi based curve-fit by harmonic functions
        Parameters
        ----------
        y : 1d-array - values to be fitted

        x : 1d-array(len(y)) - data abscissa data. default: [0 .. len(y))

        error : 1d-array(len(y)) error of y. default (absolute error = 0.01)

        nc : int - Number of harmonic coefficients

        resample : 1d-array - resample y to x using fitting coeffients

        window : int - just fit data inside window bounds

        Returns
        -------
        response : 1d-array(len(resample) or len(x)) - smoothed values

        coefficients : 1d-array - fitting coefficients
    """
    if x is None:
        x = np.arange(len(y))
#    else:
#        if not isinstance(x, pg.RVector):
#            x = pg.asvector(x)
#
#    if not isinstance(y, pg.RVector):
#        y = pg.asvector(y)

    xToFit = None
    yToFit = None

    if window is not None:
        idx = pg.find((x >= window[0]) & (x < window[1]))
        #        idx = getIndex(x , lambda v: v > window[0] and v < window[1])

        xToFit = x(idx)
        yToFit = y(idx)

        if error is not None:
            error = error(idx)
    else:
        xToFit = x
        yToFit = y

#    print xToFit
#    print yToFit
    fop = pg.HarmonicModelling(nc, xToFit, verbose)
    inv = pg.RInversion(yToFit, fop, verbose, dosave)
    if error is not None:
        inv.setAbsoluteError(error)
    else:
        inv.setAbsoluteError(0.01)

    inv.setMarquardtScheme(0.8)
    if error is not None:
        inv.stopAtChi1(True)
    inv.setLambda(lam)
    inv.setMaxIter(maxiter)
    inv.setLineSearch(lineSearch)
    inv.setRobustData(robust)
    # inv.setConstraintType(0)

    coeff = inv.run()
    print(inv.chi2())

    if resample is not None:
        if not isinstance(resample, pg.RVector):
            resample = pg.asvector(resample)

        ret = fop.response(coeff, resample)

        if window is not None:
            # print pg.find((resample < window[0]) | (resample >= window[1]))
            ret.setVal(
                0.0, pg.find((resample < window[0]) | (resample >= window[1])))
#            idx = getIndex(resample,
#                           lambda v: v <= window[0] or v >= window[1])
#            for i in idx: ret[i] = 0.0
        return ret, coeff
    else:
        return inv.response(), coeff
コード例 #41
0
def ReadAndRemoveEM(filename, readsecond=False, doplot=False,
                    dellast=True, ePhi=0.5, ePerc=1., lam=2000.):
    """
        Read res1file and remove EM effects using a double-Cole-Cole model
        fr,rhoa,phi,dphi = ReadAndRemoveEM(filename, readsecond/doplot bools)
    """
    fr, rhoa, phi, drhoa, dphi = read1resfile(filename,
                                              readsecond,
                                              dellast=dellast)
    # forward problem
    mesh = pg.createMesh1D(1, 6)  # 6 independent parameters
    f = DoubleColeColeModelling(mesh, pg.asvector(fr), phi[2] / abs(phi[2]))
    f.regionManager().loadMap("region.control")
    model = f.createStartVector()

    # inversion
    inv = pg.RInversion(phi, f, True, False)
    inv.setAbsoluteError(phi * ePerc * 0.01 + ePhi / 1000.)
    inv.setRobustData(True)

    # inv.setCWeight(pg.RVector(6, 1.0)) # wozu war das denn gut?
    inv.setMarquardtScheme(0.8)
    inv.setLambda(lam)
    inv.setModel(model)
    erg = inv.run()
    inv.echoStatus()
    chi2 = inv.chi2()
    mod0 = pg.RVector(erg)
    mod0[0] = 0.0  # set IP term to zero to obtain pure EM term
    emphi = f.response(mod0)
    resid = (phi - emphi) * 1000.

    if doplot:
        s = "IP: m= " + str(rndig(erg[0])) + " t=" + str(rndig(erg[1])) + \
            " c =" + str(rndig(erg[2]))
        s += "  EM: m= " + str(rndig(erg[3])) + " t=" + str(rndig(erg[4])) + \
            " c =" + str(rndig(erg[5]))
        fig = P.figure(1)
        fig.clf()
        ax = P.subplot(111)
        P.errorbar(
            fr,
            phi *
            1000.,
            yerr=dphi *
            1000.,
            fmt='x-',
            label='measured')
        ax.set_xscale('log')
        P.semilogx(fr, emphi * 1000., label='EM term (CC)')
        P.errorbar(fr, resid, yerr=dphi * 1000., label='IP term')
        ax.set_yscale('log')
        P.xlim((min(fr), max(fr)))
        P.ylim((0.1, max(phi) * 1000.))
        P.xlabel('f in Hz')
        P.ylabel(r'-$\phi$ in mrad')
        P.grid(True)
        P.title(s)
        P.legend(loc=2)  # ('measured','2-cole-cole','residual'))
        fig.show()

    return N.array(fr), N.array(rhoa), N.array(resid), N.array(
        phi) * 1e3, dphi, chi2, N.array(emphi) * 1e3
コード例 #42
0
ファイル: fdem.py プロジェクト: wensincai/gimli
    def invBlock(self, xpos=0, nlay=2, noise=1.0,
                 stmod=30., lam=100., lBound=0., uBound=0., verbose=False):
        """Create and return Gimli inversion instance for block inversion.

        Parameters
        ----------
        xpos : array
            position vector

        nLay : int
            Number of layers of the model to be determined OR
            vector of layer numbers OR forward operator

        noise : float
            Absolute data err in percent

        stmod : float or pg.Vector
            Starting model

        lam : float
            Global regularization parameter lambda.

        lBound : float
            Lower boundary for the model

        uBound : float
            Upper boundary for the model. 0 means no upper booundary

        verbose : bool
            Be verbose
        """
        self.transThk = pg.trans.TransLog()
        self.transRes = pg.trans.TransLogLU(lBound, uBound)
        self.transData = pg.trans.Trans()

        # EM forward operator
        if isinstance(nlay, pg.core.FDEM1dModelling):
            self.fop = nlay
        else:
            self.fop = self.FOP(nlay)

        data = self.datavec(xpos)

        self.fop.region(0).setTransModel(self.transThk)
        self.fop.region(1).setTransModel(self.transRes)

        if isinstance(noise, float):
            noiseVec = pg.Vector(len(data), noise)
        else:
            noiseVec = pg.asvector(noise)

        # independent EM inversion
        self.inv = pg.Inversion(data, self.fop, self.transData, verbose)
        if isinstance(stmod, float):  # real model given
            model = pg.Vector(nlay * 2 - 1, stmod)
            model[0] = 2.
        else:
            if len(stmod) == nlay * 2 - 1:
                model = pg.asvector(stmod)
            else:
                model = pg.Vector(nlay * 2 - 1, 30.)

        self.inv.setAbsoluteError(noiseVec)
        self.inv.setLambda(lam)
        self.inv.setMarquardtScheme(0.8)
        self.inv.setDeltaPhiAbortPercent(0.5)
        self.inv.setModel(model)
        self.inv.setReferenceModel(model)
        return self.inv
コード例 #43
0
        z[ i ] = N(p)
    
    Z = P.ma.masked_where( z == -99., z )
    Z = Z.reshape( Ny, Nx )
    
    ax2.contourf( X, Y, Z )
    ax2.set_aspect( 'equal' )
    surf = ax1.plot_surface( X, Y, Z, rstride = 1, cstride = 1, cmap=P.cm.jet,linewidth=0 )
    
    ax2.set_title( label + N.__str__() )
    fig.colorbar( surf )
    
e1 = [ 1, -1 ] # 1-r 
e2 = [ 0,  1 ] #   r

E2_1R = g.RPolynomialFunction( g.asvector( e1 ) )
E2_2R = g.RPolynomialFunction( g.asvector( e2 ) )
E2_1S = g.RPolynomialFunction( g.RVector(), g.asvector( e1 ) )
E2_2S = g.RPolynomialFunction( g.RVector(), g.asvector( e2 ) )
E2_1T = g.RPolynomialFunction( g.RVector(), g.RVector(), g.asvector( e1 ) )
E2_2T = g.RPolynomialFunction( g.RVector(), g.RVector(), g.asvector( e2 ) )

E3_1R = E2_1R * ( E2_1R - E2_2R )
E3_2R = E2_2R * ( E2_2R - E2_1R )
E3_3R = 4. * ( E2_1R * E2_2R )

E3_1S = E2_1S * ( E2_1S - E2_2S )
E3_2S = E2_2S * ( E2_2S - E2_1S )
E3_3S = 4. * ( E2_1S * E2_2S )

E3_1T = E2_1T * ( E2_1T - E2_2T )
コード例 #44
0
ファイル: fdem.py プロジェクト: gimli-org/gimli
    def invBlock(self, xpos=0, nlay=2, noise=1.0, show=True, stmod=30.,
                 lam=1000., lBound=0., uBound=0., verbose=False, **kwargs):
        """Create and return Gimli inversion instance for block inversion.

        Parameters
        ----------
        xpos : array
            position vector

        nLay : int
            Number of layers of the model to be determined OR
            vector of layer numbers OR forward operator

        noise : float
            Absolute data err in percent

        stmod : float or pg.Vector
            Starting model

        lam : float
            Global regularization parameter lambda.

        lBound : float
            Lower boundary for the model

        uBound : float
            Upper boundary for the model. 0 means no upper booundary

        verbose : bool
            Be verbose
        """
        # self.transThk = pg.trans.TransLog()
        # self.transRes = pg.trans.TransLogLU(lBound, uBound)
        # self.transData = pg.trans.Trans()
        self.transData = pg.trans.TransSymLog(tol=0.1)
        self.transLog = pg.trans.TransLog()

        useHEM = kwargs.pop("useHEM", False)
        # EM forward operator
        if isinstance(nlay, pg.core.FDEM1dModelling):
            self.fop = nlay
        else:
            self.fop = self.FOP(nlay, useHEM=useHEM)

        dataVec = self.datavec(xpos)

        # self.fop.region(0).setTransModel(self.transThk)
        # self.fop.region(1).setTransModel(self.transRes)

        if isinstance(noise, float):
            errorVec = pg.Vector(len(dataVec), noise)
        else:
            errorVec = pg.asvector(noise)

        # independent EM inversion

        if isinstance(stmod, float):  # real model given
            model = pg.Vector(nlay * 2 - 1, stmod)
            model[0] = 2.
        else:
            if len(stmod) == nlay * 2 - 1:
                model = stmod
            else:
                model = pg.Vector(nlay * 2 - 1, 30.)

            print("Model", model)
        if 1:
            from pygimli.frameworks import MarquardtInversion
            self.inv = MarquardtInversion(fop=self.fop, verbose=verbose,
                                          debug=True)
            self.inv.dataTrans = self.transData
            self.inv.modelTrans = self.transLog
            # self.dataTrans = self.transData
            self.model1d = self.inv.run(dataVec, np.abs(errorVec/dataVec),
                                        lam=lam, startModel=model, **kwargs)
            response = self.inv.response
        else:
            self.inv = pg.core.RInversion(data, self.fop, self.transData,
                                          verbose)
            self.inv.setAbsoluteError(errorVec)
            self.inv.setLambda(lam)
            self.inv.setMarquardtScheme(0.8)
            self.inv.setDeltaPhiAbortPercent(0.5)
            self.inv.setModel(model)
            self.model1d = self.inv.run()
            response = self.inv.response()

        if show:
            self.plotData(xpos=xpos, response=response)

        return self.model1d