Exemple #1
0
def main( argv ):
    
    import argparse
    
    parser = argparse.ArgumentParser( description = "Create GIMLi parameter mesh for a given datafile" )
        
    parser.add_argument("-v", "--verbose", dest = "verbose", action = "store_true"
                            , help = "Be verbose.", default = False )
    parser.add_argument("-o", "--output", dest = "outFileName"
                            , help = "File name for the resulting mesh. Default is [datafile.bms]"
                            , metavar = "File" )
    parser.add_argument("-d", "--dimension", dest = "dimension"
                            , help = "Dimension of the mesh to be created"
                            , type = int
                            , default = "2" )
    parser.add_argument("--paraDX", dest = "paraDX"
                            , help = "Horizontal distance between sensors, relative regarding sensor distance"
                            , type = float
                            , default = "1" )
    parser.add_argument("--paraDepth", dest = "paraDepth"
                            , help = "Maximum depth (absolute meter) for parametric domain, 0[default] means 0.4 * max sensor range"
                            , type = float
                            , default = "0" )
    parser.add_argument("--grid", dest = "grid"
                            , help = "Use a regular grid for parameter domain"
                            , action = "store_true"
                            , default = False )
    parser.add_argument("--paraDZ", dest = "paraDZ"
                            , help = "Vertical distance to the first depth layer, relative regarding sensor distance. For --grid only"
                            , type = float
                            , default = "1" )
    parser.add_argument("--nLayers", dest = "nLayers"
                            , help = "Number of depth layers [default = 11] For --grid only"
                            , type = int
                            , default = "11" )
                            
    parser.add_argument("--paraBoundary", dest = "paraBoundary"
                            , help = "Boundary offset for parameter domain in absolute sensor distance 2[default]"
                            , type = float
                            , default = "2" )
                            
    parser.add_argument( "--show", dest = "show"
                            , help = "Open a viewer window and show the mesh"
                            , action = "store_true"
                            , default = False )

    parser.add_argument( 'dataFileName' )

    options = parser.parse_args()
    
    # create default output filename
    if options.outFileName == None:
        options.outFileName = options.dataFileName.replace('.dat','') 
    
    if options.verbose: print( options )

    sensorPositions = pg.DataContainer( options.dataFileName ).sensorPositions()
    
    if options.verbose: print(( "Sensorcount = ", len( sensorPositions ) ))
    
    if options.dimension == 3:
        raise Exception
    
    swatch = pg.Stopwatch( True )
    if options.dimension == 2:
        
        mesh = createParaMesh2dGrid( sensors = sensorPositions, 
                                     paraDX = options.paraDX,
                                     paraDZ = options.paraDZ,
                                     paraDepth = options.paraDepth,
                                     nLayers = options.nLayers,
                                     boundary = -1,       
                                     paraBoundary = options.paraBoundary, 
                                     verbose = options.verbose, quality = 30.0, smooth = True)
    
    if options.verbose:
        print(( "generation takes ", swatch.duration(), " s" ))
        print( mesh )
        print(( "writing " + options.outFileName + '.bms' ))
    
    mesh.save( options.outFileName )
    
    if options.show:
        ax = showMesh( mesh, showLater = True  )
        drawModel( ax, mesh, mesh.cellMarker(), alpha = 0.2 )
        xl = ax.get_xlim()
        yl = ax.get_ylim()        
        dx = ( xl[1] - xl[0] ) * 0.01
        dy = ( yl[1] - yl[0] ) * 0.01

        ax.set_xlim( xl[ 0 ] - dx, xl[ 1 ] + dx )
        ax.set_ylim( yl[ 0 ] - dy, yl[ 1 ] + dy )
        
        drawSensors( ax, sensorPositions )
        
        plt.show() 
Exemple #2
0
    return 4.0

dirichletBC = [[1, 1.0], # left
               [grid.findBoundaryByMarker(2), 2.0], # right
               [grid.findBoundaryByMarker(3), lambda p: 3.0 + p[0]], # top
               [grid.findBoundaryByMarker(4), uDirichlet]] # bottom

"""
The BC are passed using the uBoundary keyword.
Note that showMesh returns the created figure axes ax while drawMesh plots on it and it can also be used as a class with plotting or decoration methods.
"""
u = solvePoisson(grid, f=1.,
                 uBoundary=dirichletBC)

ax = showMesh(grid, data=u, filled=True, colorBar=True,
              orientation='vertical', label='Solution $u$',
              levels=np.linspace(1.0, 4.0, 17), showLater=True)[0]

drawMesh(ax, grid)

ax.text( 0.0, 1.02, '$u=1$')
ax.text(-1.08, 0.0, '$u=2$', rotation='vertical')
ax.text( 0.0, -1.08, '$u=3+x$')
ax.text( 1.02, 0.0, '$u=4$', rotation='vertical')

ax.set_title('$\\nabla\cdot(1\\nabla u)=1$')

ax.set_xlim([-1.1, 1.1]) # some boundary for the text
ax.set_ylim([-1.1, 1.1])

"""
Exemple #3
0
#material?

u = solvePoisson(grid, f=1.,
                 uBoundary=[grid.findBoundaryByMarker(1,5), 0.0],
                 verbose=True)

"""
.. error::

    can we calculate analytical solution?

The result is drawn with the function showMesh.    
"""

ax = showMesh(grid, data=u, filled=True, showLater=True, colorBar=True, orientation='vertical', label='P1 Solution $u$')[0]
drawMesh(ax, grid)

"""
.. image:: PLOT2RST.current_figure
    :scale: 50

We repeat the computation with a spatially (H) refined version of the original grid.
"""

gridh2 = grid.createH2()

uh = solvePoisson(gridh2, f=1.,
                  uBoundary=[gridh2.findBoundaryByMarker(1,5), 0.0],
                  verbose=True)
for cell in mesh2.cells():
    cell.setMarker(1)

###############################################################################
# Finally, the grid and the unstructured mesh can be merged to single mesh for further
# modelling.

mesh3 = merge2Meshes(mesh1, mesh2)

###############################################################################
# Of course, you can treat the hybrid mesh like any other mesh and append a triangle
# boundary for example with :py:func:`pygimli.meshtools.grid.appendTriangleBoundary`.

mesh = appendTriangleBoundary(mesh3, -100., 100., quality=31,
                              smooth=True, marker=3, isSubSurface=True)

ax, cbar = showMesh(mesh, mesh.cellMarkers(),
                    cmap="summer",
                    label="Region marker")

drawMesh(ax, mesh)

ax, _ = showMesh(mesh, mesh.cellMarkers(),
                 logScale=False,
                 label="Region marker")

drawMesh(ax, mesh)
pg.wait()


mesh = createMesh(poly, quality=34, area=0.001, smooth=[0,10])
f = pg.RVector(mesh.cellCount(), 10)
a = pg.RVector(mesh.cellCount(), 0.1)

#Start FEM solution
swatch = pg.Stopwatch(True)

uDirichlet = [1, lambda p_: np.sin(np.arctan2(p_.center()[1],
                                              p_.center()[0]))/p_.center().abs()]

uFEM = solver.solvePoisson(mesh, a=a, f=f, uBoundary=uDirichlet)

print('FEM:', swatch.duration(True))

ax1, cbar = showMesh(mesh, data=uFEM,
                     nLevs=12, cMin=0, cMax=10, colorBar=True,
                     showLater=True)
drawMesh(ax1, mesh)


#print(min(u), max(u))
uAna = np.array(list(map(lambda p_: np.sin(np.arctan2(p_[1],
                                                      p_[0]))/p_.abs(),
                       mesh.positions())))

#drawStreamLines2(ax1, mesh, data=u)
#ax2,cbar = showMesh(mesh, data=(u+1e-6)/(ua+1e-6), filled=True, colorBar=True, showLater=True)
#showMesh(amesh)

print('---:', swatch.duration(True))
Exemple #6
0
                 verbose=True)

u -= solvePoisson(grid, a=1, b=k*k, f=pointSource,
                  duBoundary=neumannBC,
                  userData={'sourcePos': sourcePosB, 'k': k},
                  verbose=True)

#uAna = pg.RVector(map(lambda p__: uAnalytical(p__, sourcePosA, k), grid.positions()))
#uAna -= pg.RVector(map(lambda p__: uAnalytical(p__, sourcePosB, k), grid.positions()))

#err = (1.0 -u/uAna)*100.0

#print "error min max", min(err), max(err)

ax = showMesh(grid, data=u, filled=True, colorBar=True,
              orientation='horizontal', label='Solution $u$',
              showLater=True)[0]

drawMesh(ax, grid)

"""
Instead of the grid we want to add streamlines to the plot to show the gradients
of the solution.
"""

gridCoarse = pg.createGrid(x=np.linspace(-10.0, 10.0, 20), y=np.linspace(-15.0, .0, 20))
drawStreamLines2(ax, grid, u, coarseMesh=gridCoarse, color='Black')

"""
.. image:: PLOT2RST.current_figure
    :scale: 75
Exemple #7
0
for cell in mesh2.cells():
    cell.setMarker(1)

print(mesh2)
"""
.. lastcout::

Finally, the grid and the unstrcutured mesh can be merged to single mesh for further
modelling.
"""
mesh3 = merge2Meshes(mesh1, mesh2)

print(mesh3)

"""
.. lastcout::

Of course, you can treat the hybrid mesh like any other mesh and append a triangle
boundary for example with :py:func:`pygimli.meshtools.grid.appendTriangleBoundary`.
"""


mesh = appendTriangleBoundary(mesh3, -100., 100., quality=31, smooth=True, marker=3, isSubSurface=True)
showMesh(mesh, mesh.cellMarker(), cmap="summer", label="Region marker")
ax, _ = showMesh(mesh, mesh.cellMarker(), showLater=True, logScale=False, label="Region marker")
drawMesh(ax, mesh)
plt.xlim(40,60)
plt.ylim(-30, -20)
plt.show()

#Start FEM solution
swatch = pg.Stopwatch(True)

uDirichlet = [
    1, lambda p_: np.sin(np.arctan2(p_.center()[1],
                                    p_.center()[0])) / p_.center().abs()
]

uFEM = solver.solvePoisson(mesh, a=a, f=f, uBoundary=uDirichlet)

print('FEM:', swatch.duration(True))

ax1, cbar = showMesh(mesh,
                     data=uFEM,
                     nLevs=12,
                     cMin=0,
                     cMax=10,
                     colorBar=True,
                     showLater=True)
drawMesh(ax1, mesh)

#print(min(u), max(u))
uAna = np.array(
    list(
        map(lambda p_: np.sin(np.arctan2(p_[1], p_[0])) / p_.abs(),
            mesh.positions())))

#drawStreamLines2(ax1, mesh, data=u)
#ax2,cbar = showMesh(mesh, data=(u+1e-6)/(ua+1e-6), filled=True, colorBar=True, showLater=True)
#showMesh(amesh)
mesh3 = merge2Meshes(mesh1, mesh2)

###############################################################################
# Of course, you can treat the hybrid mesh like any other mesh and append a
# triangle boundary for example with the function
# :py:func:`pygimli.meshtools.grid.appendTriangleBoundary`.

mesh = appendTriangleBoundary(mesh3,
                              -100.,
                              100.,
                              quality=31,
                              smooth=True,
                              marker=3,
                              isSubSurface=True)

ax, cbar = showMesh(mesh,
                    mesh.cellMarkers(),
                    cmap="summer",
                    label="Region marker")

drawMesh(ax, mesh)

ax, _ = showMesh(mesh,
                 mesh.cellMarkers(),
                 logScale=False,
                 label="Region marker")

drawMesh(ax, mesh)
pg.wait()