Esempio n. 1
0
def case_1a(src_path, dst_path):

    opts = jigsawpy.jigsaw_jig_t()

    geom = jigsawpy.jigsaw_msh_t()
    mesh = jigsawpy.jigsaw_msh_t()

#------------------------------------ define JIGSAW geometry

    geom.mshID = "euclidean-mesh"
    geom.ndims = +3
    geom.vert3 = np.array([  # list of xy "node" coordinates
        ((0, 0, 0), 0),
        ((3, 0, 0), 0),
        ((3, 3, 0), 0),
        ((0, 3, 0), 0),
        ((0, 0, 3), 0),
        ((3, 0, 3), 0),
        ((3, 3, 3), 0),
        ((0, 3, 3), 0)],
        dtype=geom.VERT3_t)

    geom.tria3 = np.array([  # list of "tria" between points
        ((0, 1, 2), 0),
        ((0, 2, 3), 0),
        ((4, 5, 6), 0),
        ((4, 6, 7), 0),
        ((0, 1, 5), 0),
        ((0, 5, 4), 0),
        ((1, 2, 6), 0),
        ((1, 6, 5), 0),
        ((2, 3, 7), 0),
        ((2, 7, 6), 0),
        ((3, 7, 4), 0),
        ((3, 4, 0), 0)],
        dtype=geom.TRIA3_t)

#------------------------------------ build mesh via JIGSAW!

    print("Call libJIGSAW: case 1a.")

    opts.hfun_hmax = 0.08               # push HFUN limits

    opts.mesh_dims = +3                 # 3-dim. simplexes

    opts.mesh_top1 = True               # for sharp feat's
    opts.geom_feat = True

    jigsawpy.lib.jigsaw(opts, geom, mesh)

    scr3 = jigsawpy.triscr3(            # "quality" metric
        mesh.point["coord"],
        mesh.tria4["index"])

    print("Saving case_1a.vtk file.")

    jigsawpy.savevtk(os.path.join(
        dst_path, "case_1a.vtk"), mesh)

    return
Esempio n. 2
0
def case_8_(src_path, dst_path):

    opts = jigsawpy.jigsaw_jig_t()

    geom = jigsawpy.jigsaw_msh_t()
    mesh = jigsawpy.jigsaw_msh_t()

    #------------------------------------ make mesh using JIGSAW

    print("Call libJIGSAW: case 8a.")

    jigsawpy.loadmsh(os.path.join(src_path, "eight.msh"), geom)

    opts.hfun_hmax = 0.04  # set HFUN limits

    opts.mesh_kern = "delfront"  # DELFRONT kernel
    opts.mesh_dims = +3

    jigsawpy.lib.jigsaw(opts, geom, mesh)

    print("Saving case_8a.vtk file.")

    jigsawpy.savevtk(os.path.join(dst_path, "case_8a.vtk"), geom)

    print("Saving case_8b.vtk file.")

    jigsawpy.savevtk(os.path.join(dst_path, "case_8b.vtk"), mesh)

    return
Esempio n. 3
0
def case_7_(src_path, dst_path):

    opts = jigsawpy.jigsaw_jig_t()

    geom = jigsawpy.jigsaw_msh_t()
    mesh = jigsawpy.jigsaw_msh_t()

    #------------------------------------ make mesh using JIGSAW

    print("Call libJIGSAW: case 7a.")

    jigsawpy.loadmsh(os.path.join(src_path, "wheel.msh"), geom)

    opts.hfun_hmax = 0.03  # set HFUN limits

    opts.mesh_kern = "delfront"  # DELFRONT kernel
    opts.mesh_dims = +2

    opts.geom_feat = True
    opts.mesh_top1 = True
    opts.mesh_top2 = True

    jigsawpy.lib.jigsaw(opts, geom, mesh)

    print("Saving case_7a.vtk file.")

    jigsawpy.savevtk(os.path.join(dst_path, "case_7a.vtk"), geom)

    print("Saving case_7b.vtk file.")

    jigsawpy.savevtk(os.path.join(dst_path, "case_7b.vtk"), mesh)

    return
Esempio n. 4
0
def make_mesh():

    opts = jigsawpy.jigsaw_jig_t()  # jigsaw data structures
    geom = jigsawpy.jigsaw_msh_t()
    mesh = jigsawpy.jigsaw_msh_t()

    opts.geom_file = "tmp/geom.msh"  # setup jigsaw files
    opts.jcfg_file = "tmp/opts.jig"
    opts.mesh_file = "out/mesh.msh"

    geom.mshID = "ellipsoid-mesh"  # a simple "unit" sphere
    geom.radii = np.ones(+3)
    jigsawpy.savemsh(opts.geom_file, geom)

    opts.verbosity = +1  # setup user-defined opt
    opts.optm_iter = +512
    opts.optm_qtol = +1.E-08
    opts.optm_kern = "odt+dqdx"
    #   opts.optm_kern = "cvt+dqdx"

    ttic = time.time()

    jigsawpy.cmd.icosahedron(opts, 6, mesh)  # mesh with n bisections

    #   keep = mesh.tria3["IDtag"] == +1            # only keep single face?
    #   mesh.tria3 = mesh.tria3[keep]

    ttoc = time.time()

    print("CPUSEC =", (ttoc - ttic))

    jigsawpy.savevtk("mesh.vtk", mesh)  # to open in paraview...

    return
Esempio n. 5
0
def case_0a(src_path, dst_path):

    opts = jigsawpy.jigsaw_jig_t()

    geom = jigsawpy.jigsaw_msh_t()
    mesh = jigsawpy.jigsaw_msh_t()

#------------------------------------ define JIGSAW geometry

    geom.mshID = "euclidean-mesh"
    geom.ndims = +2
    geom.vert2 = np.array([   # list of xy "node" coordinate
        ((0, 0), 0),          # outer square
        ((9, 0), 0),
        ((9, 9), 0),
        ((0, 9), 0),
        ((4, 4), 0),          # inner square
        ((5, 4), 0),
        ((5, 5), 0),
        ((4, 5), 0)],
        dtype=geom.VERT2_t)

    geom.edge2 = np.array([   # list of "edges" between vert
        ((0, 1), 0),          # outer square
        ((1, 2), 0),
        ((2, 3), 0),
        ((3, 0), 0),
        ((4, 5), 0),          # inner square
        ((5, 6), 0),
        ((6, 7), 0),
        ((7, 4), 0)],
        dtype=geom.EDGE2_t)

#------------------------------------ build mesh via JIGSAW!

    print("Call libJIGSAW: case 0a.")

    opts.hfun_hmax = 0.05               # push HFUN limits

    opts.mesh_dims = +2                 # 2-dim. simplexes

    opts.optm_qlim = +.95

    opts.mesh_top1 = True               # for sharp feat's
    opts.geom_feat = True

    jigsawpy.lib.jigsaw(opts, geom, mesh)

    scr2 = jigsawpy.triscr2(            # "quality" metric
        mesh.point["coord"],
        mesh.tria3["index"])

    print("Saving case_0a.vtk file.")

    jigsawpy.savevtk(os.path.join(
        dst_path, "case_0a.vtk"), mesh)

    return
Esempio n. 6
0
def case_6_(src_path, dst_path):

    opts = jigsawpy.jigsaw_jig_t()

    geom = jigsawpy.jigsaw_msh_t()
    mesh = jigsawpy.jigsaw_msh_t()

    #------------------------------------ setup files for JIGSAW

    opts.geom_file = \
        os.path.join(src_path, "piece.msh")

    opts.jcfg_file = \
        os.path.join(dst_path, "piece.jig")

    opts.mesh_file = \
        os.path.join(dst_path, "piece.msh")

    #------------------------------------ make mesh using JIGSAW

    jigsawpy.loadmsh(opts.geom_file, geom)

    print("Saving case_6a.vtk file.")

    jigsawpy.savevtk(os.path.join(dst_path, "case_6a.vtk"), geom)

    opts.hfun_hmax = 0.03  # set HFUN limits

    opts.mesh_kern = "delfront"  # DELFRONT kernel
    opts.mesh_dims = +2

    jigsawpy.cmd.jigsaw(opts, mesh)

    print("Saving case_6b.vtk file.")

    jigsawpy.savevtk(os.path.join(dst_path, "case_6b.vtk"), mesh)

    #------------------------------------ make mesh using JIGSAW

    opts.hfun_hmax = 0.03  # set HFUN limits

    opts.mesh_kern = "delfront"  # DELFRONT kernel
    opts.mesh_dims = +2

    opts.geom_feat = True
    opts.mesh_top1 = True

    jigsawpy.cmd.jigsaw(opts, mesh)

    print("Saving case_6c.vtk file.")

    jigsawpy.savevtk(os.path.join(dst_path, "case_6c.vtk"), mesh)

    return
Esempio n. 7
0
def setgeom():

    geom = jigsawpy.jigsaw_msh_t()
    poly = jigsawpy.jigsaw_msh_t()

#------------------------------------ define JIGSAW geometry

    geom.mshID = "euclidean-mesh"
    
#------------------------------------ set watershed boundary

    print("BUILDING MESH GEOM.")

    filename = os.path.join(
        "data",
        "NHD_H_0204_HU4_Shape", "Shape", "WBDHU8.shp")

    loadshp(filename, poly, filt_WDBHU8)

    poly.point["coord"] *= np.pi / +180.

    addpoly(geom, poly, +1)

#------------------------------------ approx. stream network
    filename = os.path.join(
        "data", "namerica_rivers", "narivs.shp")

    loadshp(filename, poly, filt_narivs)

    poly.point["coord"] *= np.pi / +180.

    itag = innerto(poly.vert2["coord"], geom)

    keep = np.logical_and.reduce((
        itag[poly.edge2["index"][:, 0]] > +0,
        itag[poly.edge2["index"][:, 1]] > +0
    ))
    poly.edge2 = poly.edge2[keep]

    addline(geom, poly, +1)

#------------------------------------ proj. to local 2-plane
    proj = jigsawpy.jigsaw_prj_t()
    proj.prjID = "stereographic"
    proj.radii = FULL_SPHERE_RADIUS
    proj.xbase = PROJ_CENTRE[0] * np.pi / +180.
    proj.ybase = PROJ_CENTRE[1] * np.pi / +180.

    jigsawpy.project(geom, proj, "fwd")

    GEOM[0] = geom                      # save a "pointer"

    return geom
Esempio n. 8
0
def _jigsaw_hmat_worker(path, window, hmin, hmax, geom):
    geom = None
    raster = Raster(path)

    x = raster.get_x(window)
    y = raster.get_y(window)
    _y = np.repeat(np.min(y), len(x))
    _x = np.repeat(np.min(x), len(y))
    _tx = utm.from_latlon(_y, x)[0]
    _ty = np.flip(utm.from_latlon(y, _x)[1])
    hmat = jigsaw_msh_t()
    hmat.mshID = "euclidean-grid"
    hmat.ndims = +2
    hmat.xgrid = _tx.astype(jigsaw_msh_t.REALS_t)
    hmat.ygrid = _ty.astype(jigsaw_msh_t.REALS_t)
    hmat.value = np.flipud(
            raster.get_values(band=1, window=window)
            ).astype(jigsaw_msh_t.REALS_t)

    # init opts
    opts = jigsaw_jig_t()

    # additional configuration options
    opts.verbosity = 1
    opts.mesh_dims = 2
    opts.hfun_scal = 'absolute'
    opts.optm_tria = True

    if hmin is not None:
        opts.hfun_hmin = hmin
    else:
        opts.hfun_hmin = np.min(hmat.value)

    if hmax is not None:
        opts.hfun_hmax = hmax
    else:
        opts.hfun_hmax = np.max(hmat.value)

    # output mesh
    mesh = jigsaw_msh_t()

    # call jigsaw to create local mesh
    libsaw.jigsaw(
        opts,
        geom,
        mesh,
        hfun=hmat
    )
    breakpoint()
    return mesh
Esempio n. 9
0
def addline(geom, line, itag):
    """
    ADDLINE: push new open polyline LINE to mst_t obj. GEOM.

    The LINE.POINT + LINE.EDGE2 arrays are appended to GEOM.
    The new edges are assigned ID = ITAG.

    """
    # Authors: Darren Engwirda

    temp = jigsawpy.jigsaw_msh_t()

    temp.point = line.point
    temp.edge2 = line.edge2

    temp.edge2["IDtag"] = itag

    zipmesh(temp)                       # ensure compressed

    temp.edge2["index"] += geom.vert2.size

    geom.point = np.concatenate(
        (geom.vert2, temp.vert2), axis=0)
    geom.edge2 = np.concatenate(
        (geom.edge2, temp.edge2), axis=0)

    return
Esempio n. 10
0
 def geom(self):
     geom = jigsaw_msh_t()
     geom.vert2 = self.vert2
     geom.edge2 = self.edge2
     geom.ndim = self.ndim
     geom.mshID = self.mshID
     return geom
Esempio n. 11
0
def multipolygon_to_geom(multipolygon):
    assert isinstance(multipolygon, MultiPolygon)
    vert2 = list()
    for polygon in multipolygon:
        if np.all(
                np.asarray(polygon.exterior.coords).flatten() == float('inf')):
            msg = "PSLG seems to correspond to ellipsoidal mesh "
            msg += "which has not yet been implemented."
            raise NotImplementedError(msg)
        for x, y in polygon.exterior.coords[:-1]:
            vert2.append(((x, y), 0))
        for interior in polygon.interiors:
            for x, y in interior.coords[:-1]:
                vert2.append(((x, y), 0))
    vert2 = np.asarray(vert2, dtype=jigsaw_msh_t.VERT2_t)
    # edge2
    edge2 = list()
    for polygon in multipolygon:
        polygon = [polygon.exterior, *polygon.interiors]
        for linear_ring in polygon:
            _edge2 = list()
            for i in range(len(linear_ring.coords)-2):
                _edge2.append((i, i+1))
            _edge2.append((_edge2[-1][1], _edge2[0][0]))
            edge2.extend(
                [(e0+len(edge2), e1+len(edge2)) for e0, e1 in _edge2])
    edge2 = np.asarray(
        [((e0, e1), 0) for e0, e1 in edge2], dtype=jigsaw_msh_t.EDGE2_t)
    # geom
    geom = jigsaw_msh_t()
    geom.ndims = +2
    geom.mshID = 'euclidean-mesh'
    geom.vert2 = vert2
    geom.edge2 = edge2
    return geom
Esempio n. 12
0
def setinit():

    init = jigsawpy.jigsaw_msh_t()

    #------------------------------------ set initial conditions

    print("BUILDING MESH INIT.")

    filename = os.path.join(HERE, "..", "delaware_60_30_5_2", "tmp",
                            "mesh.msh")

    if os.path.isfile(filename):  # load from init.

        jigsawpy.loadmsh(filename, init)

    else:

        raise Exception("File not found: first run delaware_60_30_5_2"
                        " to form initial conditions!")

    geom = copy.deepcopy(GEOM[0])
    spac = copy.deepcopy(SPAC[0])

    zipnear(init, geom, spac, near=+1.E+01)

    return init
Esempio n. 13
0
def setspac():

    spac = jigsawpy.jigsaw_msh_t()

#------------------------------------ define spacing pattern

    xmid = -76.5 * np.pi / 180.0
    ymid = +39.5 * np.pi / 180.0

    spac.mshID = "ellipsoid-grid"
    spac.radii = np.full(
        3, FULL_SPHERE_RADIUS, dtype=spac.REALS_t)

    spac.xgrid = np.linspace(
        -1. * np.pi, +1. * np.pi, 720)

    spac.ygrid = np.linspace(
        -.5 * np.pi, +.5 * np.pi, 361)

    xmat, ymat = \
        np.meshgrid(spac.xgrid[:] , spac.ygrid[:])

    spac.value = +200. - 195. * np.exp(-(
        +12.5 * (xmat - xmid) ** 2 +
        +20.0 * (ymat - ymid) ** 2) ** 2)

    return spac
Esempio n. 14
0
def linegeo(line, nset, eset, nobj, last):
    """
    LINEGEO: read a geoJSON line into a jigsaw msh_t object.

    """
    # Authors: Darren Engwirda

    npts = len(line) - 0

    if (npts > 0):
#----------------------------------------- read LINE dataset
        temp = jigsaw_msh_t()
        temp.vert2 = np.zeros(
            (npts + 0), dtype=temp.VERT2_t)
        temp.edge2 = np.zeros(
            (npts - 1), dtype=temp.EDGE2_t)

        temp.edge2["IDtag"][:] = nobj

        nobj = nobj + 1

        indx = np.arange(0, npts - 1) + last

        last = last + npts

        temp.vert2["coord"] = line[+0::]

        temp.edge2["index"][:, 0] = indx + 0
        temp.edge2["index"][:, 1] = indx + 1

        nset.append(temp.vert2)
        eset.append(temp.edge2)

    return nobj, last
Esempio n. 15
0
 def get_jigsaw_msh_t(self, **kwargs):
     multipolygon = self.get_multipolygon(**kwargs)
     vert2 = list()
     for polygon in multipolygon:
         if np.all(
                 np.asarray(polygon.exterior.coords).flatten() == float(
                     'inf')):
             raise NotImplementedError("ellispoidal-mesh")
         for x, y in polygon.exterior.coords[:-1]:
             vert2.append(((x, y), 0))
         for interior in polygon.interiors:
             for x, y in interior.coords[:-1]:
                 vert2.append(((x, y), 0))
     vert2 = np.asarray(vert2, dtype=jigsaw_msh_t.VERT2_t)
     # edge2
     edge2 = list()
     for polygon in multipolygon:
         polygon = [polygon.exterior, *polygon.interiors]
         for linear_ring in polygon:
             _edge2 = list()
             for i in range(len(linear_ring.coords) - 2):
                 _edge2.append((i, i + 1))
             _edge2.append((_edge2[-1][1], _edge2[0][0]))
             edge2.extend([(e0 + len(edge2), e1 + len(edge2))
                           for e0, e1 in _edge2])
     edge2 = np.asarray([((e0, e1), 0) for e0, e1 in edge2],
                        dtype=jigsaw_msh_t.EDGE2_t)
     # geom
     geom = jigsaw_msh_t()
     geom.ndims = +2
     geom.mshID = 'euclidean-mesh' if self._ellipsoid is None \
         else 'ellipsoidal-mesh'
     geom.vert2 = vert2
     geom.edge2 = edge2
     return geom
Esempio n. 16
0
def jigsaw_driver(cellWidth, lon, lat):
    '''
    A function for building a jigsaw mesh

    Parameters
    ----------
    cellWidth : ndarray
        The size of each cell in the resulting mesh as a function of space

    lon, lat : ndarray
        The lon. and lat. of each point in the cellWidth array
    '''
    # Authors
    # -------
    # Mark Petersen, Phillip Wolfram, Xylar Asay-Davis

    # setup files for JIGSAW
    opts = jigsawpy.jigsaw_jig_t()
    opts.geom_file = 'mesh.msh'
    opts.jcfg_file = 'mesh.jig'
    opts.mesh_file = 'mesh-MESH.msh'
    opts.hfun_file = 'mesh-HFUN.msh'
           
    # save HFUN data to file
    hmat = jigsawpy.jigsaw_msh_t()
    hmat.mshID = 'ELLIPSOID-GRID'
    hmat.xgrid = numpy.radians(lon)
    hmat.ygrid = numpy.radians(lat)
    hmat.value = cellWidth
    jigsawpy.savemsh(opts.hfun_file, hmat)
   
    # define JIGSAW geometry
    geom = jigsawpy.jigsaw_msh_t()
    geom.mshID = 'ELLIPSOID-MESH'
    geom.radii = 6371.*numpy.ones(3, float)
    jigsawpy.savemsh(opts.geom_file, geom)
   
    # build mesh via JIGSAW!
    mesh = jigsawpy.jigsaw_msh_t()
    opts.hfun_scal = 'absolute'
    opts.hfun_hmax = float("inf") 
    opts.hfun_hmin = 0.0
    opts.mesh_dims = +2  # 2-dim. simplexes
    opts.optm_qlim = 0.9375
    opts.verbosity = +1
   
    jigsawpy.cmd.jigsaw(opts)
Esempio n. 17
0
def setinit():

    init = jigsawpy.jigsaw_msh_t()

    #------------------------------------ set initial conditions

    # just an empty msh_t object!

    return init
Esempio n. 18
0
 def mesh(self):
     mesh = jigsaw_msh_t()
     mesh.mshID = 'euclidean-mesh'
     mesh.ndims = 2
     mesh.vert2 = self.vert2
     mesh.tria3 = self.tria3
     mesh.quad4 = self.quad4
     # mesh.hexa8 = self.hexa8
     mesh.value = self.value
     return mesh
Esempio n. 19
0
def setgeom():

    geom = jigsawpy.jigsaw_msh_t()

    #------------------------------------ define JIGSAW geometry

    geom.mshID = "ellipsoid-mesh"
    geom.radii = np.full(3, FULL_SPHERE_RADIUS, dtype=geom.REALS_t)

    return geom
Esempio n. 20
0
def case_2_(src_path, dst_path):

    opts = jigsawpy.jigsaw_jig_t()

    mesh = jigsawpy.jigsaw_msh_t()

    #------------------------------------ setup files for JIGSAW

    opts.geom_file = \
        os.path.join(src_path, "lakes.msh")

    opts.jcfg_file = \
        os.path.join(dst_path, "lakes.jig")

    opts.mesh_file = \
        os.path.join(dst_path, "lakes.msh")

    #------------------------------------ make mesh using JIGSAW

    opts.mesh_kern = "delaunay"  # DELAUNAY kernel
    opts.mesh_dims = +2

    opts.mesh_top1 = True  # mesh sharp feat.
    opts.geom_feat = True

    opts.optm_iter = +0

    opts.hfun_hmax = 0.02

    jigsawpy.cmd.jigsaw(opts, mesh)

    print("Saving case_2a.vtk file.")

    jigsawpy.savevtk(os.path.join(dst_path, "case_2a.vtk"), mesh)

    #------------------------------------ make mesh using JIGSAW

    opts.mesh_kern = "delfront"  # DELFRONT kernel
    opts.mesh_dims = +2

    opts.mesh_top1 = True  # mesh sharp feat.
    opts.geom_feat = True

    opts.optm_iter = +0

    opts.hfun_hmax = 0.02

    jigsawpy.cmd.jigsaw(opts, mesh)

    print("Saving case_2b.vtk file.")

    jigsawpy.savevtk(os.path.join(dst_path, "case_2b.vtk"), mesh)

    return
Esempio n. 21
0
def setgeom():

    geom = jigsawpy.jigsaw_msh_t()

    #------------------------------------ define JIGSAW geometry

    print("BUILDING MESH GEOM.")

    geom.mshID = "ellipsoid-mesh"
    geom.radii = np.full(+3, FULL_SPHERE_RADIUS, dtype=geom.REALS_t)

    return geom
Esempio n. 22
0
    def _run_cmdsaw(self):
        msg = f'_run_cmdsaw()'
        self.logger.debug(msg)

        # init tmpfiles
        self.logger.debug(f'init tmpfiles')
        mesh_file = tempfile.NamedTemporaryFile(prefix=tmpdir, suffix='.msh')
        hmat_file = tempfile.NamedTemporaryFile(prefix=tmpdir, suffix='.msh')
        geom_file = tempfile.NamedTemporaryFile(prefix=tmpdir, suffix='.msh')
        jcfg_file = tempfile.NamedTemporaryFile(prefix=tmpdir, suffix='.jig')

        # dump data to tempfiles
        jigsawpy.savemsh(hmat_file.name, self.hfun)
        jigsawpy.savemsh(geom_file.name, self.geom)

        # init opts
        opts = jigsaw_jig_t()
        opts.mesh_file = mesh_file.name
        opts.hfun_file = hmat_file.name
        opts.geom_file = geom_file.name
        opts.jcfg_file = jcfg_file.name

        # additional configuration options
        opts.verbosity = self.verbosity
        opts.mesh_dims = +2  # NOTE: Hardcoded value
        opts.hfun_scal = 'absolute'
        opts.optm_tria = True  # NOTE: Hardcoded value
        opts.optm_qlim = self.optm_qlim

        if self.hmin_is_absolute_limit:
            opts.hfun_hmin = self.hmin
        else:
            opts.hfun_hmin = np.min(self.hfun.value)

        if self.hmax_is_absolute_limit:
            opts.hfun_hmax = self.hmax
        else:
            opts.hfun_hmax = np.max(self.hfun.value)

        # init outputmesh
        mesh = jigsaw_msh_t()

        # call jigsaw
        self.logger.debug('call cmdsaw')
        jigsawpy.cmd.jigsaw(opts, mesh)

        # cleanup temporary files
        for tmpfile in (mesh_file, hmat_file, geom_file, jcfg_file):
            del (tmpfile)

        self.__output_mesh = mesh
Esempio n. 23
0
    def geom(self):
        """
        This is the global geom
        """
        try:
            name = self.__geom_tmpfile.name
            geom = jigsaw_msh_t()
            loadmsh(name, geom)
            return geom

        except AttributeError:

            # jigsawpy.msh_t.jigsaw_msh_t
            if isinstance(self._geom, jigsaw_msh_t):
                self._logger.debug('self.geom:AttributeError:jigsaw_msh_t')
                self._geom.edge2 = geomesh.utils.edge2_from_msh_t(self._geom)
                geom = self._geom

            elif isinstance(self._geom, (Polygon, MultiPolygon)):
                msg = 'self.geom:AttributeError:(Polygon, MultiPolygon)'
                self._logger.debug(msg)
                geom = self._get_geom_from_shapely()

            # RasterCollection
            elif isinstance(
                self._geom,
                (
                    geomesh.Raster,
                    geomesh.RasterCollection
                )
                    ):
                msg = 'self.geom:AttributeError:(Raster, RasterCollection)'
                self._logger.debug(msg)
                geom = self._get_geom_from_raster()

            else:
                self._logger.debug('self.geom:AttributeError:Undefined')
                msg = f"Undefined handler for geom type {self._geom}"
                raise NotImplementedError(msg)

            tmpfile = tempfile.NamedTemporaryFile(
                prefix=geomesh.tmpdir, suffix='.msh')
            savemsh(tmpfile.name, geom)
            self.__geom_tmpfile = tmpfile
            # spherical mesh
            if self._radii is not None:
                geom.radii = self._radii
                geom.mshID = self._mshID
            return geom
Esempio n. 24
0
def jigsaw_gen_icos_grid(basename="mesh", level=4):

    # setup files for JIGSAW
    opts = jig.jigsaw_jig_t()
    icos = jig.jigsaw_msh_t()
    geom = jig.jigsaw_msh_t()

    opts.geom_file = basename + '.msh'
    opts.jcfg_file = basename + '.jig'
    opts.mesh_file = basename + '-MESH.msh'

    geom.mshID = "ellipsoid-mesh"
    geom.radii = np.full(3, 1.000E+000, dtype=geom.REALS_t)

    jig.savemsh(opts.geom_file, geom)

    opts.hfun_hmax = +1.
    opts.mesh_dims = +2  # 2-dim. simplexes
    opts.optm_iter = +512
    opts.optm_qtol = +1.0E-06

    jig.cmd.icosahedron(opts, level, icos)

    return opts.mesh_file
Esempio n. 25
0
def setspac():

    spac = jigsawpy.jigsaw_msh_t()

    #------------------------------------ define spacing pattern

    spac.mshID = "ellipsoid-grid"
    spac.radii = np.full(3, FULL_SPHERE_RADIUS, dtype=spac.REALS_t)

    spac.xgrid = np.linspace(-1. * np.pi, +1. * np.pi, 360)

    spac.ygrid = np.linspace(-.5 * np.pi, +.5 * np.pi, 180)

    spac.value = np.full((180, 360), +1.0E+002, dtype=spac.REALS_t)

    return spac
Esempio n. 26
0
def zipmesh(mesh, tags):
    """
    ZIPMESH: "zip" a mesh down to just the verts/edges/cells
    associated with the list of ID's in TAGS.

    Returns a new "zipped" msh_t object.

    """
    # Authors: Darren Engwirda

    mout = jigsawpy.jigsaw_msh_t()

    keep_cell = np.full(
        mesh.tria3.size, False, dtype=np.bool)
    keep_edge = np.full(
        mesh.edge2.size, False, dtype=np.bool)
    keep_vert = np.full(
        mesh.point.size, False, dtype=np.bool)

#------------------------------------ "flag" tagged entities
    for itag in tags:

        keep_cell[mesh.tria3["IDtag"] == itag] = True

    keep_vert[mesh.tria3[
        "index"][keep_cell].flatten()] = True

    keep_edge = np.logical_and.reduce((
        keep_vert[mesh.edge2["index"][:, 0]],
        keep_vert[mesh.edge2["index"][:, 1]])
    )

    mout.point = mesh.point[keep_vert]
    mout.edge2 = mesh.edge2[keep_edge]
    mout.tria3 = mesh.tria3[keep_cell]

#------------------------------------ update vertex indexing
    redo = \
        np.zeros(mesh.point.size, dtype=np.int32)

    redo[keep_vert] = \
        np.arange(0, np.count_nonzero(keep_vert))

    mout.edge2["index"] = redo[mout.edge2["index"]]
    mout.tria3["index"] = redo[mout.tria3["index"]]

    return mout
Esempio n. 27
0
    def run(self, sieve=None, quality_metric=1.05):

        hfun_msh_t = self.hfun.msh_t()

        output_mesh = jigsaw_msh_t()
        output_mesh.mshID = 'euclidean-mesh'
        output_mesh.ndims = 2

        self.opts.hfun_hmin = np.min(hfun_msh_t.value)
        self.opts.hfun_hmax = np.max(hfun_msh_t.value)
        self.opts.mesh_rad2 = float(quality_metric)

        geom_msh_t = self.geom.msh_t()

        # When the center of geom and hfun are NOT the same, utm
        # zones would be different for resulting msh_t.
        if geom_msh_t.crs != hfun_msh_t.crs:
            utils.reproject(hfun_msh_t, geom_msh_t.crs)
        output_mesh.crs = hfun_msh_t.crs

        _logger.info('Calling libsaw.jigsaw() ...')
        libsaw.jigsaw(self.opts,
                      geom_msh_t,
                      output_mesh,
                      init=hfun_msh_t if self._init is True else None,
                      hfun=hfun_msh_t)

        # post process
        if output_mesh.tria3['index'].shape[0] == 0:
            _err = 'ERROR: Jigsaw returned empty mesh.'
            _logger.error(_err)
            raise Exception(_err)

        if self._crs is not None:
            utils.reproject(output_mesh, self._crs)

        _logger.info('Finalizing mesh...')
        # Don't need to use ad-hoc fix since Jigsaw tiny element
        # issue is resolve. In case needed add a flag for remesh
        # since it's computationally expensive
        #        if self.opts.hfun_hmin > 0:
        #            output_mesh = utils.remesh_small_elements(
        #                self.opts, geom_msh_t, output_mesh, hfun_msh_t)
        utils.finalize_mesh(output_mesh, sieve)

        _logger.info('done!')
        return Mesh(output_mesh)
Esempio n. 28
0
def coreshp(data, nset, eset, nobj, last):
    """
    CORESHP: load a shape file into a jigsaw msh_t object.

    """
    # Authors: Darren Engwirda

    if (nlevels(data) > +1):

#---------------------------------- iterate into list lvl.
        for next in data:
            nobj, last = coreshp(
                next, nset, eset, nobj, last)

    else:

#---------------------------------- read last level coord.
        npts = len(data)

        temp = jigsaw_msh_t()
        temp.vert2 = np.zeros(
            (npts + 0), dtype=temp.VERT2_t)
        temp.edge2 = np.zeros(
            (npts - 1), dtype=temp.EDGE2_t)

        temp.edge2["IDtag"][:] = nobj

        nobj = nobj + 1

        indx = np.arange(0, npts - 1) + last

        last = last + npts

        temp.vert2["coord"][:, 0] = \
            [ipos[0] for ipos in data]

        temp.vert2["coord"][:, 1] = \
            [ipos[1] for ipos in data]

        temp.edge2["index"][:, 0] = indx + 0
        temp.edge2["index"][:, 1] = indx + 1

        nset.append(temp.vert2)
        eset.append(temp.edge2)

    return nobj, last
Esempio n. 29
0
def read_msh(msh_file):

    mesh = jigsawpy.jigsaw_msh_t()
    jigsawpy.loadmsh(msh_file, mesh)
    nn = len(mesh.point)
    lon_mesh = np.zeros(nn)
    lat_mesh = np.zeros(nn)
    for i in range(nn):
        lon_mesh[i] = mesh.point[i][0][0]
        lat_mesh[i] = mesh.point[i][0][1]

    ne = len(mesh.tria3)
    ect = np.zeros((ne, 3))
    for i in range(ne):
        ect[i, :] = mesh.tria3['index'][i][:]

    return lon_mesh, lat_mesh
Esempio n. 30
0
def polygeo(loop, nset, eset, nobj, last):
    """
    POLYGEO: read a geoJSON poly into a jigsaw msh_t object.

    """
    # Authors: Darren Engwirda

    npts = len(loop) - 1

    if (npts > +0):
#----------------------------------------- read LOOP dataset
        temp = jigsaw_msh_t()
        temp.vert2 = np.zeros(
            (npts + 0), dtype=temp.VERT2_t)
        temp.edge2 = np.zeros(
            (npts - 0), dtype=temp.EDGE2_t)

        temp.edge2["IDtag"][:] = nobj

        nobj = nobj + 1

        indx = np.arange(0, npts - 1) + last

        itop = last + npts - 1

        idx1 = np.full(
            npts, itop, dtype=np.int32)
        idx1[:-1] = indx + 0

        idx2 = np.full(
            npts, last, dtype=np.int32)
        idx2[:-1] = indx + 1

        last = last + npts

        temp.vert2["coord"] = loop[:-1:]

        temp.edge2["index"][:, 0] = idx1
        temp.edge2["index"][:, 1] = idx2

        nset.append(temp.vert2)
        eset.append(temp.edge2)

    return nobj, last