Exemple #1
0
def info_contour(cid):
    """Get contour structure information

    :param cid: contour or grid identifier

    :returns:
       dictionary representing contour length, total number of nodes, edges,
       number of edges in each subcontour and number of edges
       of each boundary type::

         {'Nnodes': int,
          'Nedges': int,
          'subcont': [list-of-int],    # edges number in each subcontour
          'btypes': {btype(int): int}  # boundary type: number of edges
          'length': float
         }

    """
    icheck(0, ACont2D())

    cont = flow.receiver.get_any_contour(cid).contour2()
    ret = {}
    ret['Nnodes'] = cont.n_vertices()
    ret['Nedges'] = cont.n_edges()

    sep = [Contour2(s) for s in c2core.quick_separate(cont.cdata)]
    ret['subcont'] = [s.n_edges() for s in sep]

    bt = cont.raw_data('bt')
    ret['btypes'] = {}
    for s in bt:
        if s not in ret['btypes']:
            ret['btypes'][s] = 1
        else:
            ret['btypes'][s] += 1
    ret['length'] = cont.length()
    return ret
Exemple #2
0
def info_grid(gid):
    """Get grid structure information

    :param gid: grid identifier

    :returns: dictionary which represents
       total number of nodes/cells/edges
       and number of cells of each type::

         {'Nnodes': int,
          'Ncells': int,
          'Nedges': int,
          'cell_types': {int: int}  # cell dimension: number of such cells
          }

    """
    icheck(0, Grid2D())
    grid = flow.receiver.get_grid2(gid)
    ret = {}
    ret['Nnodes'] = grid.n_vertices()
    ret['Ncells'] = grid.n_cells()
    ret['Nedges'] = grid.n_edges()
    ret['cell_types'] = grid.cell_types_info()
    return ret
Exemple #3
0
def connect_subcontours(sources, fix=[], close="no", shiftnext=True):
    """ Connects sequence of open contours into a single contour
    even if neighboring contours have no equal end points

    :param sources: list of open contour identifiers

    :param list-of-int fix: indicies of **sources** contours
        which could not be shifted or stretched.

    :param str close: last connection algorithm:
        ``no``, ``yes`` or ``force``

    :param bool shiftnext: if True then each next contour will be
        shifted to the end point of previous one, otherwise
        both contours will be stretched to match average end point.

    To connect given contours this procedure implements stretching
    and shifting of those ones not listed in **fix** list.
    If two adjacent source contours are marked as fixed but have no
    common end points an exception will be raised.

    If **close** is ``yes`` then last contour of **sources** will
    be connected with the first one with algorithm depending on
    **fix** and **shiftnext** options.

    If **close** is ``no``
    then ending contours will be left as they are. In that case resulting
    contour will be open until first and last points are exactly equal.

    **close** = ``force`` algorithm works like **close** = ``no`` but
    creates a section which explicitly connects first and last contours
    by a straight line.
    """
    icheck(0, UList(Cont2D()))
    icheck(1, UList(UInt(maxv=len(sources) - 1), maxlen=len(sources)))
    icheck(2, OneOf('no', 'yes', 'force'))
    icheck(3, Bool())

    args = {}
    args['src'] = sources
    args['fix'] = copy.deepcopy(fix)
    args['close'] = close
    args['shiftnext'] = shiftnext
    c = com.contcom.ConnectSubcontours(args)
    flow.exec_command(c)
    return c.added_contours2()[0]
Exemple #4
0
def add_circ_contour2(p0, p1, p2, n_arc, bnd=0):
    """Adds circle contour from given arc points.

    :param list-of-floats p0:

    :param list-of-floats p1:

    :param list-of-floats p2: circle arc points as [x, y] format

    :param int n_arc: partition of circle arc

    :param bnd: boundary identifier for contour.
       With the default value no boundary types will be set.

    :return:  Contour identifier

    """
    icheck(0, Point2D())
    icheck(1, Point2D(noteq=[p0]))
    icheck(2, Point2D(noteq=[p0, p1]))
    icheck(3, UInt(minv=3))
    icheck(4, ZType())

    p0, p1, p2 = map(float, p0), map(float, p1), map(float, p2)
    xb, yb = p1[0] - p0[0], p1[1] - p0[1]
    xc, yc = p2[0] - p0[0], p2[1] - p0[1]
    A11, A12 = 2.0 * xb, 2.0 * yb
    A21, A22 = 2.0 * xc, 2.0 * yc
    B1, B2 = xb * xb + yb * yb, xc * xc + yc * yc
    d = A11 * A22 - A12 * A21
    I11, I12, I21, I22 = A22 / d, -A12 / d, -A21 / d, A11 / d
    cx = I11 * B1 + I12 * B2
    cy = I21 * B1 + I22 * B2
    rad = math.sqrt((cx - xb) * (cx - xb) + (cy - yb) * (cy - yb))

    return add_circ_contour([cx + p0[0], cy + p0[1]], rad, n_arc, bnd)
Exemple #5
0
def export_grid_hmg(gid, fname, fmt='ascii', afields=[]):
    """Exports 2d grid to hybmesh native format.

      :param gid: single or list of grid identifiers

      :param str fname: output filename

      :param str fmt: output data format:

         * ``'ascii'`` - all fields will be saved as text fields,
         * ``'bin'`` - all fields will be saved in binary section,
         * ``'fbin'`` - only floating point fields will be saved
           in binary section.

      :param list-of-str afields: additional data which should be placed
          to output file.

      :returns: None

      To save additional data into grid file
      :ref:`user defined fields <udef-fields>`
      place any of these strings into **afields** list:

      * ``'cell-vertices'`` -- cell vertex connectivity. All vertices will
        be written in counterclockwise direction;
      * ``'cell-edges'`` -- cell edge connectivity. All edges will be written
        in counterclockwise direction.

      See :ref:`grid2d-file` for format description.

    """
    if fmt == "binary":
        fmt = "bin"
    if fmt == "fbinary":
        fmt = "fbin"
    icheck(0, UListOr1(Grid2D()))
    icheck(1, String())
    icheck(2, OneOf('ascii', 'bin', 'fbin'))
    icheck(3, UList(OneOf('cell-vertices', 'cell-edges')))

    names = gid if isinstance(gid, list) else [gid]
    grids = map(flow.receiver.get_grid2, names)
    cb = flow.interface.ask_for_callback()
    native_export.grid2_tofile(fname, grids, names, fmt, afields, cb)
Exemple #6
0
def move_geom(objs, dx, dy, dz=0.):
    """ Moves a list of objects

    :param objs: identifier or list of identifiers of moving objects

    :param float dx:

    :param float dy:

    :param float dz: shifts in x, y and z direction. Z moves take place only
       for 3d objects

    :returns: None
    """
    icheck(0, UListOr1(AObject()))
    icheck(1, Float())
    icheck(2, Float())
    icheck(3, Float())

    ob = objs if isinstance(objs, list) else [objs]
    c = com.objcom.MoveGeom({"names": ob, "dx": dx, "dy": dy, "dz": dz})
    flow.exec_command(c)
Exemple #7
0
def stripe(cont, partition, tip='no', bnd=0):
    """ Build a structured grid to the both sides of contour line

    :param cont: closed or open contour identifier

    :param ascending-list-of-double partition: partition perpendicular
       to source contour

    :param str tip: stripe endings meshing algorithm

       * ``"no"`` - no grid at endings
       * ``"radial"`` - radial grid at endings

    :param float-or-list-of-floats bnd: boundary types for input grid.
       List of four values provides respective values for bottom, left,
       right, top sides of resulting grid with respect to contour direction.

    :return: grid identifier

    Horizontal partition is taken from contour partition.
    Vertical partition is given by user with ``partition`` list parameter.
    If it starts with non zero value then grid will not contain
    contour nodes as its vertices.

    Use :func:`partition_segment` to define non-equidistant
    **partition** with any desired refinement if needed.
    """
    icheck(0, ACont2D())
    icheck(1, IncList(Float(grthan=0.0)))
    icheck(2, OneOf('no', 'radial'))
    icheck(3, ListOr1(ZType(), llen=4))

    bnd = bnd[:4] if isinstance(bnd, list) else [bnd, bnd, bnd, bnd]
    arg = {"source": cont, "partition": partition, "tip": tip, "bnd": bnd}
    c = com.gridcom.StripeGrid(arg)
    flow.exec_command(c)
    return c.added_grids2()[0]
Exemple #8
0
def triangulate_domain(domain, constr=[], pts=[], fill='3'):
    """Builds constrained triangulation within given domain

    :param domain: single or list of closed contours
        representing bounding domain

    :param constr: single or list of contours representing
        triangulation constraints

    :param pts: set of points in ``[len0, [x0, y0], ...]``
        format where ``x, y`` are coordinates of internal vertices
        which should be embedded into the resulting grid,
        ``len`` - size of adjacent cells
    :param str fill: if '3' then triangulates area; '4' runs
        recombination algorithm to make mostly quadrangular mesh

    :return: grid identifier

    A contour tree will be built using all closed contours
    passed as **domain** parameter. Only the interior parts
    of this tree will be meshed. Contours passed by **domain**
    should not intersect each other, but could intersect **constr**
    contours.
    **constr** could contain any set of closed and open contours.

    See details in :ref:`unstructured-meshing`.
    """
    icheck(0, UListOr1(ACont2D()))
    icheck(1, UListOr1(ACont2D()))
    icheck(2, CompoundList(Float(grthan=0.0), Point2D()))
    icheck(3, OneOf('3', '4'))

    if fill == '3':
        return _triquad(domain, constr, pts, '3')
    elif fill == '4':
        return _triquad(domain, constr, pts, '4')
Exemple #9
0
def rotate_geom(objs, angle, pc=[0.0, 0.0]):
    """ Rotates group of 2d objects

    :param objs: identifier or list of identifiers of rotating 2d objects

    :param float angle: degree of rotation. Positive angle corresponds to
       counterclockwise rotation

    :param list-of-float pc: center of rotation

    :returns: None
    """
    icheck(0, UListOr1(ACont2D()))
    icheck(1, Float())
    icheck(2, Point2D())
    ob = objs if isinstance(objs, list) else [objs]
    c = com.objcom.RotateGeom({"names": ob, "angle": angle, "p0": pc})
    flow.exec_command(c)
Exemple #10
0
def reflect_geom(objs, pnt1, pnt2):
    """ Makes a reflection of 2d geometry objects over a  given line

    :param objs: identifier or list of identifiers of 2d objects to reflect

    :param list-of-float pnt1:

    :param list-of-float pnt2: points in [x, y] format which define a line
        to reflect over

    :returns: None
    """
    icheck(0, UListOr1(ACont2D()))
    icheck(1, Point2D())
    icheck(2, Point2D(noteq=[pnt1]))

    ob = objs if isinstance(objs, list) else [objs]
    c = com.objcom.ReflectGeom({"names": ob, "p1": pnt1, "p2": pnt2})
    flow.exec_command(c)
Exemple #11
0
def extract_subcontours(source, plist, project_to="vertex"):
    """ Extracts singly connected subcontours from given contour.

        :param source: source contour identifier

        :param list-of-list-of-float plist: consecutive list of
           subcontours end points

        :param str project_to: defines projection rule for **plist** entries

           * ``"line"`` projects to closest point on the source contour
           * ``"vertex"`` projects to closest contour vertex
           * ``"corner"`` projects to closest contour corner vertex

        :returns: list of new contours identifiers

        Length of **plist** should be equal or greater than two.
        First and last points in **plist** define first and last points
        of **source** segment to extract.
        All internal points define internal division
        of this segment. Hence number of resulting subcontours will equal
        number of points in **plist** minus one.

        For closed **source** contour first and last **plist** points
        could coincide. In that case the sum of resulting subcontours
        will be equal to **source**.
    """
    icheck(0, ACont2D())
    icheck(1, List(Point2D(), minlen=2))
    icheck(2, OneOf("line", "vertex", "corner"))

    c = com.contcom.ExtractSubcontours({
        'src': source,
        'plist': plist,
        'project_to': project_to
    })
    flow.exec_command(c)
    return c.added_contours2()
Exemple #12
0
def stdout_verbosity(verb):
    icheck(0, OneOf(0, 1, 2, 3))
    flow.set_interface(flow.interface.reset(verb))
Exemple #13
0
def matched_partition(cont, step, influence, ref_conts=[], ref_pts=[],
                      angle0=30., power=3.):
    """ Makes a contour partition with respect to other
        contours partitions and given reference points

        :param cont: target contour.

        :param float step: default contour step size.

        :param float influence: influence radius of size conditions.

        :param ref_conts: list of contours which segmentation will
          be treated as target segmentation conditions.

        :param ref_pts: reference points given as
           ``[step0, [x0, y0], step1, [x1, y1], ...]`` list.

        :param float angle0: existing contour vertices which provide
           turns outside of ``[180 - angle0, 180 + angle0]`` degrees range
           will be preserved regardless of other options

        :param positive-float power: shows power of weight
           calculation function. As this parameter increases
           size transitions along contour become less smooth and more
           sensible to size conditions.

        See :ref:`matchedcontmeshing` for details.
    """
    icheck(0, ACont2D())
    icheck(1, Float(grthan=0.0))
    icheck(2, Float(grthan=0.0))
    icheck(3, UList(ACont2D()))
    icheck(4, CompoundList(Float(grthan=0.0), Point2D()))
    icheck(5, Float(within=[-1., 180., '[]']))
    icheck(6, Float(grthan=0.0))

    if not isinstance(ref_conts, list):
        ref_conts = [ref_conts]

    rp = []
    for i in range(len(ref_pts) / 2):
        rp.append(ref_pts[2 * i])
        rp.extend(ref_pts[2 * i + 1])

    args = {"base": cont,
            "cconts": ref_conts,
            "cpts": rp,
            "step": step,
            "infdist": influence,
            "angle0": angle0,
            "power": power
            }
    c = com.contcom.MatchedPartition(args)
    flow.exec_command(c)
    return c.added_contours2()[0]
Exemple #14
0
def add_unf_circ_grid(p0,
                      rad=1.0,
                      na=8,
                      nr=4,
                      coef=1.0,
                      is_trian=True,
                      custom_rads=[],
                      custom_arcs=[],
                      bnd=0):
    """Builds circular grid.

    :param list-of-floats p0: center coordinate as [x, y]

    :param float rad: radius

    :param int na:

    :param int nr: partitions of arc and radius respectively

    :param float coef: refinement coefficient:
         * ``coef = 1``: equidistant radius division
         * ``coef > 1``: refinement towards center of circle
         * ``0 < coef < 1``: refinement towards outer arc

    :param bool is_trian: True if center cell should be triangulated

    :param float-or-list-of-floats custom_rads:
        user defined radious partition

    :param float-or-list-of-floats custom_arcs:
        user defined arc partition

    :param int bnd: boundary type for outer contour

    :returns: created grid identifier

    Creates a radial grid with the center in **p0**.

    If **custom_rads** is given as a single value it will be used
    as a constant step along radial axis hence **nr** and **coef** arguments
    will be ignored. If it is given as a list of increasing values
    starting from zero
    then it is parsed as explicit radius partition. Hence the
    last entry of this list will be the radius of the resulting grid
    and **rad** parameter will also be ignored.

    If **custom_arcs** is given as a single value it shows the
    constant step along outer arc and **na** will be ignored.
    If it is an increasing list of floats, it shows partition of
    outer arc. It can be given in degrees or radians or any other
    relative units. Program treats **custom_arcs[-1]**-**custom_arcs[0]**
    difference as a full circle length and normalizes all other entries
    to this length. First and last entries of this array provides
    the same arc segment (last = first + 2*pi) hence to
    get partition of n segments you should define n+1 entries.

    Use :func:`partition_segment` to conveniently define **custom\_** fields
    if needed.
    """
    icheck(0, Point2D())
    icheck(1, Float(grthan=0.0))
    icheck(2, UInt(minv=3))
    icheck(3, UInt(minv=1))
    icheck(4, Float(grthan=0.0))
    icheck(5, Bool())
    icheck(6, Or(Float(grthan=0.0), IncList(Float())))
    icheck(7, Or(Float(grthan=0.0), IncList(Float())))
    icheck(8, ZType())

    custom_rads = custom_rads if isinstance(custom_rads, list)\
        else [custom_rads]
    custom_arcs = custom_arcs if isinstance(custom_arcs, list)\
        else [custom_arcs]
    c = com.gridcom.AddUnfCircGrid({
        "p0": p0,
        "rad": rad,
        "na": na,
        "nr": nr,
        "coef": coef,
        "is_trian": is_trian,
        "custom_r": custom_rads,
        "custom_a": custom_arcs,
        "bnd": bnd
    })
    flow.exec_command(c)
    return c.added_grids2()[0]
Exemple #15
0
def add_circ_rect_grid(p0, rad, step, sqrside=1.0, rcoef=1.0, algo="linear"):
    """ Creates quadrangular cell grid in a circular area.
    See details in :ref:`circrect_grid`.

    :param list-of-floats p0: center point of circle area in [x, y] format.

    :param positive-float rad: radius of circle area.

    :param positive-float step: approximate partition step of the outer
       boundary.

    :param positive-float sqrside: side of the inner square normalized by
       the circle radius. Values greater than 1.4 are not allowed.

    :param positive-float rcoef: radius direction refinement of
       the ring part of the grid.
       Values less then unity lead to refinement towards outer boundary.

    :param str algo: Algorithms of assembling the ring part of the grid.

       * ``'linear'`` - use weighted approach for each ray partition
       * ``'laplace'`` - use algebraic mapping for
         building each 45 degree sector.
       * ``'orthogonal_circ'`` - build orthogonal grid keeping
         uniform grid at outer circle
       * ``'orthogonal_rect'`` - build orthogonal grid keeping
         uniform grid at inner rectangle

    :return: new grid identifier

    """
    icheck(0, Point2D())
    icheck(1, Float(grthan=0.0))
    icheck(2, Float(grthan=0.0))
    icheck(3, Float(within=[0., 1.4, '[)']))
    icheck(4, Float(grthan=0.0))
    icheck(5, OneOf('linear', 'laplace', 'orthogonal_circ', 'orthogonal_rect'))

    # call
    args = {
        'algo': algo,
        'p0': p0,
        'rad': rad,
        'step': step,
        'sqrside': sqrside,
        'rcoef': rcoef
    }
    c = com.gridcom.AddCirc4Grid(args)
    flow.exec_command(c)
    return c.added_grids2()[0]
Exemple #16
0
def add_custom_rect_grid(algo,
                         left,
                         bottom,
                         right=None,
                         top=None,
                         hermite_tfi_w=[1.0, 1.0, 1.0, 1.0],
                         return_invalid=False):
    """ Creates rectangular grid on the basis of four curvilinear contours
    using contour vertices for partition.
    See details in :ref:`custom_rect_grid`.

    :param str algo: Algorithms of building:

       * ``'linear'`` - connects respective points of opposite
         contours by straight lines.
       * ``'linear_tfi'`` - linear transfinite interpolation
       * ``'hermite_tfi'`` - hermite transfinite interpolation
       * ``'inverse_laplace'`` -
       * ``'direct_laplace'`` - connects points using solution of
         laplace equation with Dirichlet boundary conditions;
       * ``'orthogonal'`` - builds orthogonal grid based on **left** and
         **bottom** partition.
         Partitions of **right** and **top** are ignored.

    :param left:

    :param bottom:

    :param right:

    :param top: identifiers of curvilinear domain sides.
       **right** and **top** could be ``None``. If so right and top
       boundaries will be created by translation of **left** and **bottom**.

    :param list-of-floats hermite_tfi_w:
       perpendicularity weights
       for **left**, **bottom**, **right**, **top** contours respectively
       for **algo** = ``'hermite_tfi'``

    :param bool return_invalid: if this flag is on
       then the procedure will return a grid even if it is not valid
       (has self-intersections). Such grids could be exported to
       simple formats (like vtk or tecplot) in order to detect
       bad regions and give user a hint of how to adopt
       input data to gain an acceptable result.

       .. warning:: Never use invalid grids for further operations.

    :return: new grid identifier

    """
    icheck(
        0,
        OneOf('linear', 'linear_tfi', 'hermite_tfi', 'inverse_laplace',
              'direct_laplace', 'orthogonal'))
    icheck(1, Cont2D())
    icheck(2, Cont2D())
    icheck(3, NoneOr(Cont2D()))
    icheck(4, NoneOr(Cont2D()))
    icheck(5, List(Float(), llen=4))
    icheck(6, Bool())

    # call
    args = {
        'algo': algo,
        'left': left,
        'right': right,
        'bot': bottom,
        'top': top,
        'her_w': hermite_tfi_w,
        'return_invalid': return_invalid
    }
    c = com.gridcom.AddCustomRectGrid(args)
    flow.exec_command(c)
    return c.added_grids2()[0]
Exemple #17
0
def add_unf_ring_grid(p0, radinner, radouter, na, nr, coef=1.0, bnd=0):
    """Builds ring grid

    :param list-of-floats p0: center coordinates as [x, y]

    :param float radinner:

    :param float radouter: inner and outer radii

    :param int na:

    :param int nr: arc and radius partition respectively

    :param float coef: refinement coefficient:
       * ``coef = 1``: equidistant radius division
       * ``coef > 1``: refinement towards center of circle
       * ``0 < coef < 1``: refinement towards outer arc

    :param int-or-list-of-int bnd: boundary types for inner and outer
       ring boundaries

    :return: created grid identifier

    """
    if radinner > radouter:
        radinner, radouter = radouter, radinner
    icheck(0, Point2D())
    icheck(1, Float(grthan=0.0))
    icheck(2, Float(grthan=0.0))
    icheck(3, UInt(minv=3))
    icheck(4, UInt(minv=1))
    icheck(5, Float(grthan=0.0))
    icheck(6, ListOr1(ZType(), llen=2))

    bnd = bnd[:2] if isinstance(bnd, list) else [bnd, bnd]
    c = com.gridcom.AddUnfRingGrid({
        "p0": p0,
        "radinner": radinner,
        "radouter": radouter,
        "na": na,
        "nr": nr,
        "coef": coef,
        "bnd": bnd
    })
    flow.exec_command(c)
    return c.added_grids2()[0]
Exemple #18
0
def add_unf_rect_grid(p0=[0, 0],
                      p1=[1, 1],
                      nx=3,
                      ny=3,
                      custom_x=[],
                      custom_y=[],
                      bnd=0):
    """Builds rectangular grid.

    :param list-of-floats p0:

    :param list-of-floats p1: bottom left, top right points in [x, y] format.

    :param int nx:

    :param int ny: partition in x and y directions.

    :param float-or-list-of-floats custom_x:

    :param float-or-list-of-floats custom_y: custom x and y coordinates

    :param int-or-list-of-int: boundary types for bottom, right, top, left
       rectangle sides

    :returns: created grid identifier

    Builds a grid in a rectangular area formed by points **p0** and **p1**.
    **nx** and **ny** provide grid partition in x and y direction.

    If **custom_x**/**custom_y** is given by a single float value
    than it shows a step size in respective direction,
    hence values given by **nx**/**ny** parameters will be omitted.

    If **custom_x**/**custom_y** is given by a list of increasing floats
    it explicitly shows the partition in respective direction.
    In the latter case the respective **p0**, **p1** coordinates
    will also be ignored.

    Use :func:`partition_segment` to conveniently define **custom\_** fields
    if needed.
    """
    icheck(0, Point2D())
    icheck(1, Point2D(grthan=p0))
    icheck(2, UInt(minv=1))
    icheck(3, UInt(minv=1))
    icheck(4, Or(Float(grthan=0.), IncList(Float())))
    icheck(5, Or(Float(grthan=0.), IncList(Float())))
    icheck(6, ListOr1(ZType(), llen=4))

    bnd = bnd[:4] if isinstance(bnd, list) else [bnd, bnd, bnd, bnd]
    custom_x = custom_x if isinstance(custom_x, list) else [custom_x]
    custom_y = custom_y if isinstance(custom_y, list) else [custom_y]
    c = com.gridcom.AddUnfRectGrid({
        "p0": p0,
        "p1": p1,
        "nx": nx,
        "ny": ny,
        "custom_x": custom_x,
        "custom_y": custom_y,
        "bnds": bnd
    })
    flow.exec_command(c)
    return c.added_grids2()[0]
Exemple #19
0
def get_point(obj,
              ind=None,
              vclosest=None,
              eclosest=None,
              cclosest=None,
              only_contour=True):
    """ Returns object point

    :param obj: grid or contour identifier

    :param int ind: index of point

    :param vclosest:

    :param eclosest:

    :param cclosest: point as [x, y] list

    :param bool only_contour: If that is true then if **objs** is a grid
       then respective grid contour will be used

    :returns: point as [x, y] list

    Only one of **ind**, **vclosest**, **eclosest**, **cclosest**
    arguments should be defined.

    If **ind** is defined then returns point at given index.

    If **vvlosest** point is defined then returns object vertex closest to
    this point.

    If **eclosest** point is defined then returns point owned by an
    object edge closest to input point.

    If **cclosest** point is defined then returns non straight line
    object contour vertex closest to input point.
    """
    icheck(0, ACont2D())
    icheck(1, NoneOr(UInt()))
    icheck(2, NoneOr(Point2D()))
    icheck(3, NoneOr(Point2D()))
    icheck(4, NoneOr(Point2D()))
    icheck(5, Bool())
    if ind is None and vclosest is None and eclosest is None and\
            cclosest is None:
        raise InvalidArgument("Define point location")

    try:
        tar = flow.receiver.get_contour2(obj)
    except KeyError:
        tar = flow.receiver.get_grid2(obj)
        if only_contour or cclosest is not None:
            tar = tar.contour()
    if cclosest is not None:
        tar = tar.deepcopy()
        c2core.simplify(tar.cdata, 0, False)
        vclosest = cclosest

    if vclosest is not None:
        return tar.closest_points([vclosest], "vertex")[0]
    elif eclosest is not None:
        return tar.closest_points([eclosest], "edge")[0]
    elif ind is not None:
        return tar.point_at(ind)
Exemple #20
0
def set_boundary_type(obj, btps=None, bfun=None, bdict=None):
    """ Mark geometrical object with boundary types.

    :param obj: geometric object identifier

    :param btps: single identifier for the whole object or list
       of identifiers for each boundary segment.

    :param  bfun: function which returns boundary type taking segment
       coordinates and old boundary type as arguments.

    :param bdict: {btype: [list-of-segment indicies]} dictionary
       which maps boundary type with object segments indicies

    Only one of **btps**, **bfun**, **bdict** arguments should be defined.

    **bfun** signature is:

       * ``(x0, y0, x1, y1, bt) -> btype`` for 2D objects, where
         *x0, y0, x1, y1* are edge end point coordinates,
         bt - old boundary type
       * ``(xc, yc, zc, bt) -> btype`` for 3D objects, where
         *xc, yc, zc* - approximate face center coordinates,
         bt - old boundary type

    If **obj** is a grid then only boundary segments will be passed
    to **bfun** function and **btps** list entries will
    be associated with boundary segments only.
    However **bdict** entries should contain global edge or face indicies.

    Example:

      .. literalinclude:: ../../testing/py/fromdoc/ex_setbtype.py
          :start-after: START OF EXAMPLE
          :end-before: END OF EXAMPLE

    """
    icheck(0, AObject())
    icheck(1, NoneOr(ListOr1(ZType())))
    icheck(3, NoneOr(Dict(ZType(), List(UInt()))))
    t = flow.receiver.whatis(obj)
    if t in ['g2', 'c2']:
        icheck(2, NoneOr(Func(narg=5)))
    else:
        icheck(2, NoneOr(Func(narg=4)))
    if [btps, bfun, bdict].count(None) != 2:
        raise InvalidArgument("One of [btps, bfun, bdict] should be not None")

    args = {'name': obj, 'whole': None, 'btypes': {}}

    if isinstance(btps, int):
        args['whole'] = btps
    elif bdict is not None:
        args['btypes'] = bdict
    else:
        g = flow.receiver.get_object(obj)
        if t == 'g2':
            if btps is not None:
                _setbt_args_g2g3btps(g, btps, args['btypes'])
            if bfun is not None:
                _setbt_args_g2bfun(g, bfun, args['btypes'])
        if t == 'g3':
            if btps is not None:
                _setbt_args_g2g3btps(g, btps, args['btypes'])
            if bfun is not None:
                _setbt_args_g3bfun(g, bfun, args['btypes'])
        if t == 'c2':
            if btps is not None:
                _setbt_args_c2s3btps(g, btps, args['btypes'])
            if bfun is not None:
                _setbt_args_c2bfun(g, bfun, args['btypes'])
        if t == 's3':
            if btps is not None:
                _setbt_args_c2s3btps(g, btps, args['btypes'])
            if bfun is not None:
                _setbt_args_s3bfun(g, bfun, args['btypes'])
    c = com.objcom.SetBType(args)
    flow.exec_command(c)
Exemple #21
0
def revolve_grid(obj,
                 p1,
                 p2,
                 n_phi=None,
                 phi=None,
                 btype1=0,
                 btype2=0,
                 merge_central=False):
    """ Creates 3D grid by revolution of 2D grid around a vector

    :param obj: 2d grid identifier

    :param p1:

    :param p2: points in [x, y] format which define vector of rotation

    :param int n_phi: partition along circular coordinate.
       If this parameter is defined then [0, 360] range will be divided
       into equal parts and full revolution solid will be build.

    :param list-of-floats phi: increasing vector defining
       custom partition of angular range.
       This parameter will be processed if **n_phi** is None.
       If the last value of **phi** is not equal to first one
       plus 360 degree than
       incomplete revolution solid will be built.

    :param btype1:

    :param btype2: boundary identifiers for surfaces which will be build
       as a result of incomplete rotation at end values of **phi** vector.

    :param bool merge_central: if rotation vector coincides
       with boundary edges of input grid then this parameter
       defines whether central cells derived from the revolution
       of respective boundary cells should be merged into one
       complex finite volume (True) or left as they are (False).

    :returns: 3D grid identifier

    All points of input grid should lie to the one side of rotation
    vector.

    Use :func:`partition_segment` to define non-equidistant
    **phi** with any desired refinement if needed.

    """
    icheck(0, Grid2D())
    icheck(1, Point2D())
    icheck(2, Point2D(noteq=p1))
    icheck(3, NoneOr(UInt(minv=3)))
    icheck(4, NoneOr(IncList(Float())))
    icheck(5, ZType())
    icheck(6, ZType())
    icheck(7, Bool())

    # calculate phi's
    if n_phi is None:
        inp_phi = copy.deepcopy(phi)
    else:
        inp_phi = []
        for i in range(n_phi + 1):
            inp_phi.append(360. * i / n_phi)

    c = com.grid3dcom.Revolve({
        "base": obj,
        "p1": p1,
        "p2": p2,
        "phi": inp_phi,
        "bt1": btype1,
        "bt2": btype2,
        "center_tri": not merge_central
    })
    flow.exec_command(c)
    return c.added_grids3()[0]
Exemple #22
0
def partition_contour(cont, algo, step=1., angle0=30., keep_bnd=False,
                      nedges=None, crosses=[], keep_pts=[],
                      start=None, end=None):
    """ Makes connected contour partition

    :param cont: Contour or grid identifier

    :param str algo: Partition algorithm:

       * ``'const'``: partition with defined constant step
       * ``'ref_points'``: partition with step function given by a
         set of values refered to basic points
       * ``'ref_weights'``: partition with step function given by a
         set of values refered to local contour [0, 1] coordinate
       * ``'ref_lengths'``: partition with step function given by a
         set of values refered to local contour length coordinate

    :param step: For ``algo='const'`` a float number defining
       partition step;

       For ``algo='ref_points'`` - list of step values and point coordinates
       given as
       ``[ step_0, [x_0, y_0], step_1, [x_1, y_1], ....]``.

       For ``algo='ref_weights'`` - list of step values and point normalized
       1d coordinates given as
       ``[ step_0, w_0, step_1, w_1, ....]``.

       For ``algo='ref_lengths'`` - list of step values and point 1d
       coordinates given as
       ``[ step_0, s_0, step_1, s_1, ....]``. Negative ``s_i`` shows
       length coordinate started from end point in reversed direction.


    :param float angle0: existing contour vertices which provide
       turns outside of ``[180 - angle0, 180 + angle0]`` degrees range
       will be preserved regardless of other options

    :param bool keep_bnd: if that is True than vertices which have different
       boundary features on their right and left sides will be preserved

    :param int nedges: if this parameter is not None then it provides
       exact number of edges in the resulting contour. To satisfy this
       condition **step** value will be multiplied by an appropriate factor.
       If it can not be satisfied (due to other restrictions)
       then an exception will be raised.

    :param crosses: represents set of contour which cross points with
       target contour will be present in resulting contour.

    :param keep_pts: list of points as ``[[x1, y1], [x2, y2], ...]`` list
       which should present in output partition.

    :param start:

    :param end: start and end points which define processing segment

    :returns: new contour identifier

    Points set defined by user for ``algo='ref_points'`` algorithm
    will not present in resulting contour (as well as points defined
    implicitly by other ``'ref_'`` algorithms). It just shows locations
    where step size of given length should be applied. If any point
    of this set is not located on the input contour then it will be
    projected to it.

    For constant stepping any contour including multiply connected ones
    could be passed. For ``ref_`` stepping only singly connected
    contours (open or closed) are allowed.

    If **start** and **end** points are defined then only segment between
    these points will be parted. Note that all closed contours are treated
    in counterclockwise direction. Given start/end points will be
    projected to closest contour vertices.

    ``ref_weights``, ``ref_lengths`` partition methods
    require definition of **start** point
    (To process whole contour ``end`` point could be omitted).

    Example:

      .. literalinclude:: ../../testing/py/fromdoc/ex_partcontour.py
          :start-after: vvvvvvvvvvvvvvvvvvvvvvvv
          :end-before: ^^^^^^^^^^^^^^^^^^^^^^^^

    See also: :ref:`simplecontmeshing`
    """
    if nedges <= 0:
        nedges = None
    icheck(0, ACont2D())
    icheck(1, OneOf("const", "ref_points", "ref_weights", "ref_lengths"))
    if algo == "const":
        icheck(2, Float(grthan=0.0))
    elif algo == "ref_points":
        icheck(2, CompoundList(Float(grthan=0.0),
                               Point2D(), minlen=2))
    elif algo == "ref_weights":
        icheck(2, CompoundList(Float(grthan=0.0),
                               Float(within=[-1, 1, '[]']), minlen=2))
    elif algo == "ref_lengths":
        icheck(2, CompoundList(Float(grthan=0.0), Float(), minlen=2))
    icheck(3, Float())
    icheck(4, Bool())
    icheck(5, NoneOr(UInt(minv=1)))
    icheck(6, List(ACont2D()))
    icheck(7, List(Point2D()))
    icheck(8, NoneOr(Point2D()))
    icheck(9, NoneOr(Point2D()))
    if start is None and algo in ['ref_weights', 'ref_lengths']:
        raise InvalidArgument("Define start point for %s partition" % algo)

    # prepare arguments for command
    if algo == "const":
        plain_step = [step]
    elif algo == "ref_points":
        plain_step = []
        for i in range(len(step) / 2):
            plain_step.append(step[2 * i])
            plain_step.extend(step[2 * i + 1])
    elif algo in ["ref_weights", "ref_lengths"]:
        plain_step = copy.deepcopy(step)
    sp, ep = None, None
    if start is not None:
        sp = [start[0], start[1]]
    if end is not None:
        ep = [end[0], end[1]]
    kp = []
    if keep_pts is not None:
        for p in keep_pts:
            kp.append([p[0], p[1]])

    args = {"algo": algo,
            "step": plain_step,
            "angle0": angle0,
            "keepbnd": keep_bnd,
            "base": cont,
            "nedges": nedges,
            "crosses": crosses,
            "start": sp,
            "end": ep,
            "keep_pts": kp}
    # call
    c = com.contcom.PartitionContour(args)
    flow.exec_command(c)
    return c.added_contours2()[0]
Exemple #23
0
def extrude_grid(obj, zcoords, bottombc=0, topbc=0, sidebc=None):
    """ Creates 3D grid by extrusion of 2D grid along z-axis

    :param obj: 2d grid identifier

    :param list-of-floats zcoords: increasing vector of z values
      which will be used to create 3d points

    :param bottombc:

    :param topbc: values which define boundary features of
      3d grid at ``z=min(zcoords)`` and ``z=max(zcoords)``
      surfaces respectively.
      Could be either a single boundary identifier for a whole
      surface or a function: ``(float x, float y, int cell_index)->bindex``
      which takes central cell point x, y
      coordinates and cell index as arguments and returns boundary type
      (see example below).

    :param sidebc: defines boundary features for side surfaces.

      * If None than boundary types will be taken from corresponding
        edges of 2D grid
      * If single boundary identifier then whole side surface will
        have same boundary type

    :returns: 3D grid identifier

    Use :func:`partition_segment` to define non-equidistant
    **zcoords** with any desired refinement.

    Example:

      .. literalinclude:: ../../testing/py/fromdoc/ex_extrude.py
          :start-after: vvvvvvvvvvvvvvvvvvvvvvvv
          :end-before: ^^^^^^^^^^^^^^^^^^^^^^^^
    """
    icheck(0, Grid2D())
    icheck(1, IncList(Float()))
    icheck(2, Or(ZType(), Func(nargs=3)))
    icheck(3, Or(ZType(), Func(nargs=3)))
    icheck(4, NoneOr(ZType()))

    # calculate boundary types
    if not isinstance(bottombc, int) or not isinstance(topbc, int):
        grid = flow.receiver.get_grid2(obj)
        cc_pnt = grid.raw_data('cell_center')
    if isinstance(bottombc, int):
        bbot = [bottombc]
    elif callable(bottombc):
        it = iter(cc_pnt)
        bbot = [bottombc(p[0], p[1], i) for i, p in enumerate(zip(it, it))]
    if isinstance(topbc, int):
        btop = [topbc]
    elif callable(topbc):
        it = iter(cc_pnt)
        btop = [topbc(p[0], p[1], i) for i, p in enumerate(zip(it, it))]
    if sidebc is None:
        bside = None
    elif isinstance(sidebc, int):
        bside = sidebc

    c = com.grid3dcom.ExtrudeZ({
        "base": obj,
        "zvals": copy.deepcopy(zcoords),
        "bside": bside,
        "btop": btop,
        "bbot": bbot
    })
    flow.exec_command(c)
    return c.added_grids3()[0]
Exemple #24
0
def build_boundary_grid1(cont,
                         partition,
                         direction,
                         pstart=None,
                         pend=None,
                         range_angles=[40, 125, 235, 275]):
    """Builds a singly-connected boundary grid near given contour.

    :param cont: source contour (or grid) identifier

    :param list-of-float partition: partition in perpendicular direction.

    :param str direction: 'left'/'right'

    :param pstart:

    :param pend: points in [x, y] format which define
      the exact segment of the contour for building grid.
      If both are None hence whole contour (or all subcontours) will be used.

    :param range_angles: list of 4 angle values (deg) which define algorithms
      for contour bends treatment.

    :returns: identifier of the newly created grid.

    This is a wrapper for a :func:`build_boundary_grid` with simplified
    interface. It allows to build a boundary grid with constant partition
    options using existing contour segmentation for horizontal stepping.
    """
    icheck(0, ACont2D())
    icheck(1, IncList(Float(), startfrom=0.0))
    icheck(2, OneOf('left', 'right'))
    icheck(3, NoneOr(Point2D()))
    icheck(4, NoneOr(Point2D(noteq=pstart)))
    icheck(5, IncList(Float(within=[0, 360, '[]'])))

    bo = BoundaryGridOptions(cont,
                             partition,
                             direction,
                             bnd_stepping='no',
                             range_angles=range_angles,
                             start_point=pstart,
                             end_point=pend)
    return build_boundary_grid([bo])
Exemple #25
0
def dims(gid):
    icheck(0, AObject())
    ob = flow.receiver.get_object(gid)
    return ob.dims()