BasicTools.Containers.Filters module

BasicTools.Containers.Filters.CheckIntegrity(GUI=False)[source]
def CheckIntegrity( GUI=False):
    """
    .. literalinclude:: ../../src/BasicTools/Containers/Filters.py
        :pyobject: CheckIntegrity
    """
    from BasicTools.Containers.UnstructuredMeshCreationTools import CreateCube
    nNodesX = 11
    nNodesY = 12
    nNodesZ = 13
    mesh = CreateCube(dimensions=[nNodesX,nNodesY,nNodesZ],origin=[0,0,0.], spacing=[1./(nNodesX-1),1./(nNodesY-1), 10./(nNodesZ-1)], ofTetras=True )
    print(mesh)

    class NOP():
        def __init__(self):
            self.cpt = 0

        def PreCondition(self,mesh):
            self.cpt = 0

        def __call__(self,mesh,node,ids):
            self.cpt += len(ids)

        def PostCondition(self,mesh):
            print("The counter is at {}".format(self.cpt) )

    ff = NodeFilter(mesh)
    ff.ApplyOnNodes(NOP())


    ff = NodeFilter(mesh,tags=["x0y0z0","x0y0z1",],tag="x1y0z0")
    ff.AddTag("x1y0z1")


    op = NOP()
    print(ff)
    ff.ApplyOnNodes(op)

    if op.cpt != 4:#pragma: no cover
        raise Exception("Error finding the point")

    ff.AddZone(lambda p: np.ones(p.shape[0])-1)

    op = NOP()
    print(ff)
    ff.ApplyOnNodes(op)
    if op.cpt != 4:#pragma: no cover
        raise Exception("Error finding the point")

    # example of counting the number of element in the eTag X0
    cpt = 0
    ff = ElementFilter(mesh)
    ff.AddTag("X0")
    for name, data, ids in ff:
        cpt += len(ids)

    if cpt != 264: # pragma: no cover
        raise
    print("Number of Element in tag X0 {}".format(cpt))

    cpt = 0
    ff = ElementFilter(mesh,nTags=["x1y0z1"],nTagsTreatment="leastonenode")
    for name,data,ids in ff:
        cpt += len(ids)

    if cpt != 6: # pragma: no cover
        raise
    print(f"Number of Element touching the node tag 'x1y0z1' {cpt}")

    mask = np.zeros(mesh.GetNumberOfElements(),dtype=bool)
    mask[0] = True
    ff = ElementFilter(mesh,mask=mask)
    for n,d,ids in ff:
        print(n,ids)
        if n != EN.Tetrahedron_4 or len(ids) != 1 :
            raise  # pragma: no cover
        if ids[0] != 0:
            raise  # pragma: no cover

    ff = ElementFilter(mesh, zone = lambda p: (p[:,2]-mesh.boundingMin[2]-0.001),zones=[])

    ff.GetFrozenFilter().GetFrozenFilter(mesh).ApplyOnElements(ElementFilterBaseOperator())

    ff = ElementFilter(mesh, zone = lambda p: (p[:,2]-mesh.boundingMin[2]-0.001),zones=[])
    for name,data,ids in ff:
        data.tags.CreateTag("ZZ0").SetIds(ids)

    ## to check if a filter can be used 2 times
    for name,data,ids in ff:
        data.tags.CreateTag("ZZ0O").SetIds(ids)


    # example of counting the number of element in the eTag ZZ0

    class OP(ElementCounter):
        def __init__(self):
            super(OP,self).__init__()

        def __call__(self,name,data,ids):
            super(OP,self).__call__(name,data,ids)
            print(name)

        def PostCondition(self,mesh):
            print("The counter is at {}".format(self.cpt) )

    op = OP()

    ff.SetZoneTreatment("allnodes")
    ff.ApplyOnElements(op)
    ff.zoneTreatment = "leastonenode"
    ff.ApplyOnElements(op)



    cpt = 0
    ff = ElementFilter(mesh,elementTypes=[], elementType=EN.Triangle_3)
    ff.SetElementTypes([EN.Triangle_3])
    print(ff)
    def MustFail(func,*args,**kwargs):
        try:
            func(*args,**kwargs)
        except:
            pass
        else:
            raise Exception("Error in the CheckIntegrity ")# pragma no cover

    MustFail(ff.SetZoneTreatment,"toto")
    ff.ApplyOnElements(op)

    MustFail(ComplementaryObject,filters=[ff,ff])

    ff.ApplyOnElements(op)

    f2 = ElementFilter(mesh,elementType=EN.Triangle_3)
    f2.AddTag("ZZ0")

    ff.SetDimensionality(2)

    op = f2.ApplyOnElements(OP())

    if op.cpt != (2*(nNodesX-1)*(nNodesY-1)) : # pragma: no cover
        raise Exception("Error in the number of elements in the tag = " + str(op.cpt)+ " must be " + str((2*(nNodesX-1)*(nNodesY-1))))

    IF = IntersectionElementFilter(mesh=mesh,filters=[ff,f2])
    IF.ApplyOnElements(OP())

    UF = UnionElementFilter(mesh=mesh,)
    UF.filters=[ff,f2]
    UF.ApplyOnElements(OP())
    print(UF.Complementary())
    NUF = UnionElementFilter(mesh=mesh,filters=[NodeFilter(mesh,etag="3D"),NodeFilter(mesh)])
    NUF.ApplyOnNodes(NOP())

    print("Number of Element in tag ZZ0 {}".format(op.cpt))
    print(mesh)

    if GUI: # pragma: no cover
        from BasicTools.Actions.OpenInParaView import OpenInParaView
        OpenInParaView(mesh=mesh)

    ff = ElementFilter(mesh,tag="Some")
    mesh.elements[EN.Tetrahedron_4].tags.CreateTag("Some").SetIds(list(range(4000)))


    from BasicTools.Helpers.Timer import Timer
    a = Timer("ElementFilterToImplicitField").Start()
    phi = ElementFilterToImplicitField(ff, pseudoDistance=50)
    a.Stop()
    print(a)

    from BasicTools.IO.XdmfWriter import WriteMeshToXdmf
    from BasicTools.Helpers.Tests import TestTempDir
    tempdir = TestTempDir.GetTempPath()

    WriteMeshToXdmf(tempdir+"test.xdmf",mesh, PointFields=[phi],PointFieldsNames=["Phi"] )

    return "ok"
class BasicTools.Containers.Filters.ComplementaryObject(mesh: UnstructuredMesh | None = None, filters=None)[source]

Bases: FilterOP

Class to generate the complementary part of a filter

GetIdsToTreat(data: ElementContainer) np.ndarray[source]

return the ids of the element selected by the filter for the ElementContainer

Parameters:

data (ElementContainer) – the elementContainer to work on

Returns:

the ids selected by the filter

Return type:

np.ndarray

Raises:

Exception – if the list contains more than one filter

class BasicTools.Containers.Filters.DifferenceElementFilter(mesh=None, filters=None)[source]

Bases: FilterOP

Specialized class to compute the difference between two filters

GetIdsToTreat(data: ElementContainer) np.ndarray[source]

return the ids of the element selected by the filter for the ElementContainer

Parameters:

data (ElementContainer) – the elementContainer to work on

Returns:

the ids selected by the filter

Return type:

np.ndarray

class BasicTools.Containers.Filters.ElementCounter[source]

Bases: ElementFilterBaseOperator

Basic ElementCounter operators

Usage:

numberOfElement = ElementFilter(myMesh,dimensionality=2).ApplyOnElements(ElementCounter()).cpt

PreCondition(mesh: UnstructuredMesh)[source]

function called at the beginning to reset the counter

class BasicTools.Containers.Filters.ElementFilter(mesh: UnstructuredMesh | None = None, dimensionality: int | None = None, elementTypes: List[str] | None = None, elementType: str | None = None, zoneTreatment: str = 'center', nTags: List[str] | None = None, nTagsTreatment: str = 'allnodes', **kwargs)[source]

Bases: Filter

Class for element filtering by dimensionality, zone, mask,elementType, and tag for the zones three types of treatments are possible:

if the the center of the element is inside the zone : self.zoneTreatment = “center” if all nodes of the element are inside the zone : self.zoneTreatment = “allnodes” if at least one node of the element is inside the zone: self.zoneTreatment = “leastonenode”

Parameters:
  • mesh (UnstructuredMesh, optional) – The mesh to be used

  • dimensionality (int, optional) – the dimensionality of the element to be included in this filter, by default None possible option are: -3 -2 -1 0 1 2 3 None the - sign is for the complementary part (-2 = all non 2D elements)

  • elementType (Optional[str], optional) – the name of a element type to be included in this filter, by default None

  • elementTypes (Optional[List[str]], optional) – a list of element type to be included in this filter, by default None

  • zoneTreatment (str, optional) – [“center” | “allnodes” | “leastonenode”], by default “center”

  • nTags (Optional[List[str]], optional) – a list of nodal tags names to use to extract elements

  • nTagsTreatment (str, optional) – [“allnodes” | “leastonenode”], by default “allnodes”

AddElementType(elementType: str)[source]

Add an element type to be included in this filter

Parameters:

elementType (str) – the name of an element type

ApplyOnElements(op: Callable)[source]

Apply the filter using an operator

Parameters:

op (Callable) – An instance of a callable object, the object can have the PreCondition function and/or the PostCondition function. Theses functions are called (if exist) (with the mesh as the first argument) before and after the main call ( op(mesh,nodes,ids) )

Returns:

return op after the application of the filter

Return type:

Callable

Complementary() ComplementaryObject[source]

Create a filter with the complementary part

Returns:

the new filter

Return type:

ComplementaryObject

GetFrozenFilter(mesh: UnstructuredMesh | None = None) FrozenFilter[source]

Generate a frozen filter. This is a filter with pre-evaluated ids. This class is useful when a repeated use of a filter is needed

Parameters:

mesh (Union[UnstructuredMesh], optional) – the mesh to pre evaluated the filter. If None we use the internal mesh stored in the filter, by default None

Returns:

A FrozenFilter pre-evaluated on the mesh

Return type:

FrozenFilter

Raises:
  • Exception – If the user tries to freeze a frozen filter on a different mesh

  • Exception – if no mesh is available

GetIdsToTreat(elements: ElementsContainer) np.ndarray | Collection[source]

Get the entities selected by this filter

Parameters:

elements (ElementsContainer) – Elements to treat

Returns:

The filtered entities

Return type:

Union[np.ndarray,Collection]

IsEquivalent(other: Any) bool[source]

To check if 2 element filter are equivalent ()

Parameters:

other (Any) – other object to check the equivalency

Returns:

True if the two filters are equal

Return type:

bool

SetDimensionality(dimensionality: int)[source]

Set the dimensionality of the elements to be treated

Parameters:

dim (int) – the dimensionality filter, [-3 -2 -1 0 1 2 3 or None] the - sign is for the complementary part (-2 = all non 2D elements). Set to None to reset (not to apply dimensionality as a criteria)

SetElementTypes(elementTypes: List[str])[source]

Set the names of the element types to be included in this filter

Parameters:

elementTypes (List[str]) – the list of element types

SetNTags(nTags: List[str])[source]

Set the names of the nodal tags (nTags) to be included in this filter

Parameters:

elementTypes (List[str]) – the list of element types

SetNTagsTreatment(nTagsTreatment: str)[source]

Set the way the elements are selected based on the nTags if all nodes of the element are inside the nTag : self.nTagsTreatment = “allnodes” if at least one node of the element is inside nTag: self.nTagsTreatment = “leastonenode”

Parameters:

nTagsTreatment (str) – [“allnodes” | “leastonenode”]

Raises:

Exception – if the nTagsTreatment string is not in [“allnodes”, “leastonenode”]

SetZoneTreatment(zoneTreatment: str)[source]

Set the way the elements are selected based on the position if the the center of the element is inside the zone : self.zoneTreatment = “center” if all nodes of the element are inside the zone : self.zoneTreatment = “allnodes” if at least one node of the element is inside the zone: self.zoneTreatment = “leastonenode”

Parameters:

zoneTreatment (str) – [“center” | “allnodes” | “leastonenode”]

Raises:

Exception – if the string is not permitted

class BasicTools.Containers.Filters.ElementFilterBaseOperator[source]

Bases: object

Template for the creation of operators

PostCondition(mesh) None[source]
PreCondition(mesh: UnstructuredMesh) None[source]

Condition executed at the beginning

Parameters:

mesh (UnstructuredMesh) – _description_

BasicTools.Containers.Filters.ElementFilterToImplicitField(elementFilter: ElementFilter, pseudoDistance: int = 2) np.ndarray[source]

Function to generate an iso zero level-set on the mesh to represent the shape of the filter. This discretized iso zero on the mesh cant always hold a ‘perfect’ representation of the filter, so a modified iso zero is created. An additional parameter pseudo-distance can be increased to create a pseudo distance. This field is created using the connectivity and not the real distances.

Parameters:
  • elementFilter (ElementFilter) – the element filter to process

  • pseudoDistance (int, optional) – the number of element to propagate the pseudo-distance, by default 2

Returns:

a field over the nodes with negative values inside the domain defined by the filter

Return type:

np.ndarray

class BasicTools.Containers.Filters.Filter(mesh: UnstructuredMesh | None = None, zones: List[Callable] | None = None, tags: List[str] | None = None, zone: Callable | None = None, tag: str | None = None, mask: ArrayLike | None = None)[source]

Bases: BaseOutputObject

Base class to construct node and element filters

Parameters:
  • mesh (Optional[UnstructuredMesh], optional) – The mesh to be used, by default None

  • zones (Optional[List[Callable]], optional) – a list of Callable (ImplicitGeometry for example), by default None

  • tags (Optional[List[str]], optional) – The tags used to filter the elements, by default None

  • zone (Optional[Callable], optional) – A Callable, by default None

  • tag (Optional[str], optional) – A tag, by default None

  • mask (Optional[ArrayLike], optional) – a boolean vector of the size of the object to filter, by default None

AddTag(tagName: str)[source]

Add a tagname to the list of tag to treat

Parameters:

tagName (str) – the tag name to be added

AddZone(zone: Callable)[source]

dd a zone to the list of zone to be treated by the filter

Parameters:

zone (Callable) – a callable object capable of taking one argument with the points positions, and returning a vector of size pos.shape[0] with negative values for the entities to be selected by the filter

IsEquivalent(other: Any) bool[source]

To check if 2 element filter are equivalent ()

Parameters:

other (Any) – other object to check the equivalency

Returns:

True if the two filters are equal

Return type:

bool

SetMesh(mesh: UnstructuredMesh)[source]

Set the mesh

Parameters:

mesh (UnstructuredMesh) – The mesh to be used

SetTags(tagNames: List[str])[source]

Set the tag list name to treat

Parameters:

tagNames (List[str]) – the list of string with the tag names

SetZones(zonesList: List[Callable])[source]

Set the zone list to treat

Parameters:

zonesList (List[Callable]) – The list of zone to be

intersect1D(first: ArrayLike | None, second: ArrayLike | None) np.ndarray | None[source]

Function to generate an intersection of two vectors (like np.intersect1d) but with the particularity of treat the case where the inputs can be None None represent a non filtered inputs,

Parameters:
  • first (ArrayLike|None) – first vector of indices

  • second (ArrayLike|None) – second vector of indices

Returns:

The intersection of two list

Return type:

Union[np.ndarray,None]

class BasicTools.Containers.Filters.FilterOP(mesh: UnstructuredMesh | None = None, filters: List[Filter | FilterOP] | None = None)[source]

Bases: BaseOutputObject

Base class to construct derived Filters (Union filters for example)

Parameters:
  • mesh (Optional[UnstructuredMesh], optional) – The mesh to work on, by default None

  • filters (List[Union[Filter,FilterOP]], optional) – the list of filters to use, by default None

ApplyOnElements(op: Callable)[source]

Function to apply the filter using an operator

Parameters:
  • op (Callable) –

  • op – An instance of a callable object, the object can have the PreCondition function and/or the post-condition function. Theses functions are called (if exist) (with the mesh as the first argument) before and after the main call ( op(name,elements,ids) )

Returns:

the operator passed

Return type:

Callable

ApplyOnNodes(op: Callable)[source]

Function to apply filter using an operator

Parameters:

op (Callable) – An instance of a callable object, the object can have the PreCondition function and/or the post-condition function. Theses functions are called (if exist) (with the mesh as the first argument) before and after the main call ( op(mesh,nodes,ids) )

Complementary() ComplementaryObject[source]

Return a filter with the complementary part this filter.

GetFrozenFilter(mesh=None) FrozenFilter[source]

Return a frozen filter

Parameters:

mesh (_type_, optional) – _description_, by default None

Returns:

the frozen filter

Return type:

FrozenFilter

Raises:
  • Exception – if this filter is a FrozenFilter and the user provide a different mesh

  • Exception – if no mesh is available to evaluate the filter

IsEquivalent(other: Any) bool[source]

To check if 2 element filter are equivalent ()

Parameters:

other (Any) – other object to check the equivalency

Returns:

True if the two filters are equal

Return type:

bool

SetMesh(mesh: UnstructuredMesh)[source]

Set the mesh, this will push the mesh to the internal filters

Parameters:

mesh (UnstructuredMesh) – The mesh to be used

property mesh
property zoneTreatment

Can’t recover the zoneTreatment for a FilterOP. But the user can set the zone treatment for the internal filters (with the setter)

class BasicTools.Containers.Filters.FrozenFilter(mesh=None, filters=None)[source]

Bases: FilterOP

Class to hold a pre-evaluated filter

Parameters:
  • mesh (Optional[UnstructuredMesh], optional) – The mesh to work on, by default None

  • filters (Union[Filter,FilterOP], optional) – the list with only one filter to use, by default None

GetIdsToTreat(elements: ElementsContainer) np.ndarray[source]

Return the ids stored fot eh elements. We use only the elements.elementType attribute to retrieve the ids/

Parameters:

elements (ElementsContainer) – _description_

Returns:

the ids to selected by this filter

Return type:

np.ndarray

IsEquivalent(other)[source]

To check if 2 element filter are equivalent ()

Parameters:

other (Any) – other object to check the equivalency

Returns:

True if the two filters are equal

Return type:

bool

SetIdsToTreatFor(elements: ElementsContainer, localIds: ArrayLike)[source]

Set the ids for a specific element type. this filter keeps a reference to elements internally

Parameters:
  • elements (ElementsContainer) – ElementsContainer to extract the element type

  • localIds (ArrayLike) – the ids to be stored

property mesh
class BasicTools.Containers.Filters.IdsAsNumpyMask(mesh=None, filters=None)[source]

Bases: FilterOP

Class to wrap the output ids of a filter into a numpy mask

Parameters:

FilterOP (_type_) – _description_

class BasicTools.Containers.Filters.IntersectionElementFilter(mesh=None, filters=None)[source]

Bases: FilterOP

Specialized class to compute the intersection of filters

GetIdsToTreat(data: ElementContainer) np.ndarray[source]

return the ids of the element selected by the filter for the ElementContainer

Parameters:

data (ElementContainer) – the elementContainer to work on

Returns:

the ids selected by the filter

Return type:

np.ndarray

class BasicTools.Containers.Filters.NodeFilter(mesh: UnstructuredMesh | None = None, etags: List[str] | None = None, etag: str | None = None, **kwargs)[source]

Bases: Filter

class for node filtering zone, tag, mask the rest of the parameter are passed to the constructor of the base class Filter

Parameters:
  • mesh (Optional[UnstructuredMesh], optional) – The mesh to be used, by default None

  • etags (Optional[List[str]], optional) – The element tags to be used to filter the nodes, by default None

  • etag (Optional[str], optional) – A element tag name to be used to filter the nodes, by default None

AddETag(tagName: str)[source]

Add a tagname to the list of tag to treat

Parameters:

tagName (str) – tag name to add

ApplyOnNodes(op: Callable)[source]

Apply the filter using an operator

Parameters:

op (Callable) – An instance of a callable object, the object can have the PreCondition function and/or the PostCondition function. Theses functions are called (if exist) (with the mesh as the first argument) before and after the main call ( op(mesh,nodes,ids) )

GetIdsToTreat(notUsed: Any = None) np.ndarray | Collection[source]

Get the nodes selected by this filter

Parameters:

notUsed (Any, optional) – Not Used, by default None

Returns:

The filtered entities

Return type:

Union[np.ndarray,Collection]

SetETags(tagNames: List[str])[source]

Set the tag list name to treat

Parameters:

tagNames (List[str]) – list of tag names

class BasicTools.Containers.Filters.PartialElementFilter(elementFilter, partitions: int, partitionNumber: int)[source]

Bases: FilterOP

Utility class to create a partition of a ElementFilter

Complementary()[source]

Complementary if this filter is a partial filter over the complementary. This means the complementary use the number of partition and the partition number to generate a partial filter.

Yields:

(str, ElementContainer, np.ndarray) – _description_

GetIdsToTreat(elements: ElementContainer) np.ndarray[source]

return the ids of the element selected by the filter for the ElementContainer

Parameters:

data (ElementContainer) – the elementContainer to work on

Returns:

the ids selected by the filter

Return type:

np.ndarray

Raises:

Exception – if the list contains more than one filter

class BasicTools.Containers.Filters.UnionElementFilter(mesh=None, filters=None)[source]

Bases: FilterOP

Specialized class to compute the union of filter (add)

GetIdsToTreat(data: ElementContainer) np.ndarray[source]

return the ids of the element selected by the filter for the ElementContainer

Parameters:

data (ElementContainer) – the elementContainer to work on

Returns:

the ids selected by the filter

Return type:

np.ndarray