id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
230,300
orbingol/NURBS-Python
geomdl/visualization/vtk_helpers.py
create_actor_hexahedron
def create_actor_hexahedron(grid, color, **kwargs): """ Creates a VTK actor for rendering voxels using hexahedron elements. :param grid: grid :type grid: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) # Create hexahedron elements points = vtk.vtkPoints() hexarray = vtk.vtkCellArray() for j, pt in enumerate(grid): tmp = vtk.vtkHexahedron() fb = pt[0] for i, v in enumerate(fb): points.InsertNextPoint(v) tmp.GetPointIds().SetId(i, i + (j * 8)) ft = pt[-1] for i, v in enumerate(ft): points.InsertNextPoint(v) tmp.GetPointIds().SetId(i + 4, i + 4 + (j * 8)) hexarray.InsertNextCell(tmp) # Create an unstructured grid object and add points & hexahedron elements ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.SetCells(tmp.GetCellType(), hexarray) # ugrid.InsertNextCell(tmp.GetCellType(), tmp.GetPointIds()) # Map unstructured grid to the graphics primitives mapper = vtk.vtkDataSetMapper() mapper.SetInputDataObject(ugrid) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) # Return the actor return actor
python
def create_actor_hexahedron(grid, color, **kwargs): """ Creates a VTK actor for rendering voxels using hexahedron elements. :param grid: grid :type grid: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) # Create hexahedron elements points = vtk.vtkPoints() hexarray = vtk.vtkCellArray() for j, pt in enumerate(grid): tmp = vtk.vtkHexahedron() fb = pt[0] for i, v in enumerate(fb): points.InsertNextPoint(v) tmp.GetPointIds().SetId(i, i + (j * 8)) ft = pt[-1] for i, v in enumerate(ft): points.InsertNextPoint(v) tmp.GetPointIds().SetId(i + 4, i + 4 + (j * 8)) hexarray.InsertNextCell(tmp) # Create an unstructured grid object and add points & hexahedron elements ugrid = vtk.vtkUnstructuredGrid() ugrid.SetPoints(points) ugrid.SetCells(tmp.GetCellType(), hexarray) # ugrid.InsertNextCell(tmp.GetCellType(), tmp.GetPointIds()) # Map unstructured grid to the graphics primitives mapper = vtk.vtkDataSetMapper() mapper.SetInputDataObject(ugrid) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) # Return the actor return actor
[ "def", "create_actor_hexahedron", "(", "grid", ",", "color", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "array_name", "=", "kwargs", ".", "get", "(", "'name'", ",", "\"\"", ")", "array_index", "=", "kwargs", ".", "get", "(", "'index'", ",", "0", ")", "# Create hexahedron elements", "points", "=", "vtk", ".", "vtkPoints", "(", ")", "hexarray", "=", "vtk", ".", "vtkCellArray", "(", ")", "for", "j", ",", "pt", "in", "enumerate", "(", "grid", ")", ":", "tmp", "=", "vtk", ".", "vtkHexahedron", "(", ")", "fb", "=", "pt", "[", "0", "]", "for", "i", ",", "v", "in", "enumerate", "(", "fb", ")", ":", "points", ".", "InsertNextPoint", "(", "v", ")", "tmp", ".", "GetPointIds", "(", ")", ".", "SetId", "(", "i", ",", "i", "+", "(", "j", "*", "8", ")", ")", "ft", "=", "pt", "[", "-", "1", "]", "for", "i", ",", "v", "in", "enumerate", "(", "ft", ")", ":", "points", ".", "InsertNextPoint", "(", "v", ")", "tmp", ".", "GetPointIds", "(", ")", ".", "SetId", "(", "i", "+", "4", ",", "i", "+", "4", "+", "(", "j", "*", "8", ")", ")", "hexarray", ".", "InsertNextCell", "(", "tmp", ")", "# Create an unstructured grid object and add points & hexahedron elements", "ugrid", "=", "vtk", ".", "vtkUnstructuredGrid", "(", ")", "ugrid", ".", "SetPoints", "(", "points", ")", "ugrid", ".", "SetCells", "(", "tmp", ".", "GetCellType", "(", ")", ",", "hexarray", ")", "# ugrid.InsertNextCell(tmp.GetCellType(), tmp.GetPointIds())", "# Map unstructured grid to the graphics primitives", "mapper", "=", "vtk", ".", "vtkDataSetMapper", "(", ")", "mapper", ".", "SetInputDataObject", "(", "ugrid", ")", "mapper", ".", "SetArrayName", "(", "array_name", ")", "mapper", ".", "SetArrayId", "(", "array_index", ")", "# Create an actor and set its properties", "actor", "=", "vtk", ".", "vtkActor", "(", ")", "actor", ".", "SetMapper", "(", "mapper", ")", "actor", ".", "GetProperty", "(", ")", ".", "SetColor", "(", "*", "color", ")", "# Return the actor", "return", "actor" ]
Creates a VTK actor for rendering voxels using hexahedron elements. :param grid: grid :type grid: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor
[ "Creates", "a", "VTK", "actor", "for", "rendering", "voxels", "using", "hexahedron", "elements", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/vtk_helpers.py#L289-L336
230,301
orbingol/NURBS-Python
geomdl/visualization/vtk_helpers.py
create_actor_delaunay
def create_actor_delaunay(pts, color, **kwargs): """ Creates a VTK actor for rendering triangulated plots using Delaunay triangulation. Keyword Arguments: * ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False* :param pts: points :type pts: vtkFloatArray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) use_delaunay3d = kwargs.get("d3d", False) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create a PolyData object and add points polydata = vtk.vtkPolyData() polydata.SetPoints(points) # Apply Delaunay triangulation on the poly data object triangulation = vtk.vtkDelaunay3D() if use_delaunay3d else vtk.vtkDelaunay2D() triangulation.SetInputData(polydata) # Map triangulated surface to the graphics primitives mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(triangulation.GetOutputPort()) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) # Return the actor return actor
python
def create_actor_delaunay(pts, color, **kwargs): """ Creates a VTK actor for rendering triangulated plots using Delaunay triangulation. Keyword Arguments: * ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False* :param pts: points :type pts: vtkFloatArray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor """ # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) use_delaunay3d = kwargs.get("d3d", False) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create a PolyData object and add points polydata = vtk.vtkPolyData() polydata.SetPoints(points) # Apply Delaunay triangulation on the poly data object triangulation = vtk.vtkDelaunay3D() if use_delaunay3d else vtk.vtkDelaunay2D() triangulation.SetInputData(polydata) # Map triangulated surface to the graphics primitives mapper = vtk.vtkDataSetMapper() mapper.SetInputConnection(triangulation.GetOutputPort()) mapper.SetArrayName(array_name) mapper.SetArrayId(array_index) # Create an actor and set its properties actor = vtk.vtkActor() actor.SetMapper(mapper) actor.GetProperty().SetColor(*color) # Return the actor return actor
[ "def", "create_actor_delaunay", "(", "pts", ",", "color", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "array_name", "=", "kwargs", ".", "get", "(", "'name'", ",", "\"\"", ")", "array_index", "=", "kwargs", ".", "get", "(", "'index'", ",", "0", ")", "use_delaunay3d", "=", "kwargs", ".", "get", "(", "\"d3d\"", ",", "False", ")", "# Create points", "points", "=", "vtk", ".", "vtkPoints", "(", ")", "points", ".", "SetData", "(", "pts", ")", "# Create a PolyData object and add points", "polydata", "=", "vtk", ".", "vtkPolyData", "(", ")", "polydata", ".", "SetPoints", "(", "points", ")", "# Apply Delaunay triangulation on the poly data object", "triangulation", "=", "vtk", ".", "vtkDelaunay3D", "(", ")", "if", "use_delaunay3d", "else", "vtk", ".", "vtkDelaunay2D", "(", ")", "triangulation", ".", "SetInputData", "(", "polydata", ")", "# Map triangulated surface to the graphics primitives", "mapper", "=", "vtk", ".", "vtkDataSetMapper", "(", ")", "mapper", ".", "SetInputConnection", "(", "triangulation", ".", "GetOutputPort", "(", ")", ")", "mapper", ".", "SetArrayName", "(", "array_name", ")", "mapper", ".", "SetArrayId", "(", "array_index", ")", "# Create an actor and set its properties", "actor", "=", "vtk", ".", "vtkActor", "(", ")", "actor", ".", "SetMapper", "(", "mapper", ")", "actor", ".", "GetProperty", "(", ")", ".", "SetColor", "(", "*", "color", ")", "# Return the actor", "return", "actor" ]
Creates a VTK actor for rendering triangulated plots using Delaunay triangulation. Keyword Arguments: * ``d3d``: flag to choose between Delaunay2D (``False``) and Delaunay3D (``True``). *Default: False* :param pts: points :type pts: vtkFloatArray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor
[ "Creates", "a", "VTK", "actor", "for", "rendering", "triangulated", "plots", "using", "Delaunay", "triangulation", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/vtk_helpers.py#L339-L381
230,302
orbingol/NURBS-Python
geomdl/compatibility.py
flip_ctrlpts_u
def flip_ctrlpts_u(ctrlpts, size_u, size_v): """ Flips a list of 1-dimensional control points from u-row order to v-row order. **u-row order**: each row corresponds to a list of u values **v-row order**: each row corresponds to a list of v values :param ctrlpts: control points in u-row order :type ctrlpts: list, tuple :param size_u: size in u-direction :type size_u: int :param size_v: size in v-direction :type size_v: int :return: control points in v-row order :rtype: list """ new_ctrlpts = [] for i in range(0, size_u): for j in range(0, size_v): temp = [float(c) for c in ctrlpts[i + (j * size_u)]] new_ctrlpts.append(temp) return new_ctrlpts
python
def flip_ctrlpts_u(ctrlpts, size_u, size_v): """ Flips a list of 1-dimensional control points from u-row order to v-row order. **u-row order**: each row corresponds to a list of u values **v-row order**: each row corresponds to a list of v values :param ctrlpts: control points in u-row order :type ctrlpts: list, tuple :param size_u: size in u-direction :type size_u: int :param size_v: size in v-direction :type size_v: int :return: control points in v-row order :rtype: list """ new_ctrlpts = [] for i in range(0, size_u): for j in range(0, size_v): temp = [float(c) for c in ctrlpts[i + (j * size_u)]] new_ctrlpts.append(temp) return new_ctrlpts
[ "def", "flip_ctrlpts_u", "(", "ctrlpts", ",", "size_u", ",", "size_v", ")", ":", "new_ctrlpts", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "size_u", ")", ":", "for", "j", "in", "range", "(", "0", ",", "size_v", ")", ":", "temp", "=", "[", "float", "(", "c", ")", "for", "c", "in", "ctrlpts", "[", "i", "+", "(", "j", "*", "size_u", ")", "]", "]", "new_ctrlpts", ".", "append", "(", "temp", ")", "return", "new_ctrlpts" ]
Flips a list of 1-dimensional control points from u-row order to v-row order. **u-row order**: each row corresponds to a list of u values **v-row order**: each row corresponds to a list of v values :param ctrlpts: control points in u-row order :type ctrlpts: list, tuple :param size_u: size in u-direction :type size_u: int :param size_v: size in v-direction :type size_v: int :return: control points in v-row order :rtype: list
[ "Flips", "a", "list", "of", "1", "-", "dimensional", "control", "points", "from", "u", "-", "row", "order", "to", "v", "-", "row", "order", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/compatibility.py#L11-L33
230,303
orbingol/NURBS-Python
geomdl/compatibility.py
generate_ctrlptsw
def generate_ctrlptsw(ctrlpts): """ Generates weighted control points from unweighted ones in 1-D. This function #. Takes in a 1-D control points list whose coordinates are organized in (x, y, z, w) format #. converts into (x*w, y*w, z*w, w) format #. Returns the result :param ctrlpts: 1-D control points (P) :type ctrlpts: list :return: 1-D weighted control points (Pw) :rtype: list """ # Multiply control points by weight new_ctrlpts = [] for cpt in ctrlpts: temp = [float(pt * cpt[-1]) for pt in cpt] temp[-1] = float(cpt[-1]) new_ctrlpts.append(temp) return new_ctrlpts
python
def generate_ctrlptsw(ctrlpts): """ Generates weighted control points from unweighted ones in 1-D. This function #. Takes in a 1-D control points list whose coordinates are organized in (x, y, z, w) format #. converts into (x*w, y*w, z*w, w) format #. Returns the result :param ctrlpts: 1-D control points (P) :type ctrlpts: list :return: 1-D weighted control points (Pw) :rtype: list """ # Multiply control points by weight new_ctrlpts = [] for cpt in ctrlpts: temp = [float(pt * cpt[-1]) for pt in cpt] temp[-1] = float(cpt[-1]) new_ctrlpts.append(temp) return new_ctrlpts
[ "def", "generate_ctrlptsw", "(", "ctrlpts", ")", ":", "# Multiply control points by weight", "new_ctrlpts", "=", "[", "]", "for", "cpt", "in", "ctrlpts", ":", "temp", "=", "[", "float", "(", "pt", "*", "cpt", "[", "-", "1", "]", ")", "for", "pt", "in", "cpt", "]", "temp", "[", "-", "1", "]", "=", "float", "(", "cpt", "[", "-", "1", "]", ")", "new_ctrlpts", ".", "append", "(", "temp", ")", "return", "new_ctrlpts" ]
Generates weighted control points from unweighted ones in 1-D. This function #. Takes in a 1-D control points list whose coordinates are organized in (x, y, z, w) format #. converts into (x*w, y*w, z*w, w) format #. Returns the result :param ctrlpts: 1-D control points (P) :type ctrlpts: list :return: 1-D weighted control points (Pw) :rtype: list
[ "Generates", "weighted", "control", "points", "from", "unweighted", "ones", "in", "1", "-", "D", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/compatibility.py#L86-L107
230,304
orbingol/NURBS-Python
geomdl/compatibility.py
generate_ctrlpts_weights
def generate_ctrlpts_weights(ctrlpts): """ Generates unweighted control points from weighted ones in 1-D. This function #. Takes in 1-D control points list whose coordinates are organized in (x*w, y*w, z*w, w) format #. Converts the input control points list into (x, y, z, w) format #. Returns the result :param ctrlpts: 1-D control points (P) :type ctrlpts: list :return: 1-D weighted control points (Pw) :rtype: list """ # Divide control points by weight new_ctrlpts = [] for cpt in ctrlpts: temp = [float(pt / cpt[-1]) for pt in cpt] temp[-1] = float(cpt[-1]) new_ctrlpts.append(temp) return new_ctrlpts
python
def generate_ctrlpts_weights(ctrlpts): """ Generates unweighted control points from weighted ones in 1-D. This function #. Takes in 1-D control points list whose coordinates are organized in (x*w, y*w, z*w, w) format #. Converts the input control points list into (x, y, z, w) format #. Returns the result :param ctrlpts: 1-D control points (P) :type ctrlpts: list :return: 1-D weighted control points (Pw) :rtype: list """ # Divide control points by weight new_ctrlpts = [] for cpt in ctrlpts: temp = [float(pt / cpt[-1]) for pt in cpt] temp[-1] = float(cpt[-1]) new_ctrlpts.append(temp) return new_ctrlpts
[ "def", "generate_ctrlpts_weights", "(", "ctrlpts", ")", ":", "# Divide control points by weight", "new_ctrlpts", "=", "[", "]", "for", "cpt", "in", "ctrlpts", ":", "temp", "=", "[", "float", "(", "pt", "/", "cpt", "[", "-", "1", "]", ")", "for", "pt", "in", "cpt", "]", "temp", "[", "-", "1", "]", "=", "float", "(", "cpt", "[", "-", "1", "]", ")", "new_ctrlpts", ".", "append", "(", "temp", ")", "return", "new_ctrlpts" ]
Generates unweighted control points from weighted ones in 1-D. This function #. Takes in 1-D control points list whose coordinates are organized in (x*w, y*w, z*w, w) format #. Converts the input control points list into (x, y, z, w) format #. Returns the result :param ctrlpts: 1-D control points (P) :type ctrlpts: list :return: 1-D weighted control points (Pw) :rtype: list
[ "Generates", "unweighted", "control", "points", "from", "weighted", "ones", "in", "1", "-", "D", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/compatibility.py#L139-L160
230,305
orbingol/NURBS-Python
geomdl/compatibility.py
combine_ctrlpts_weights
def combine_ctrlpts_weights(ctrlpts, weights=None): """ Multiplies control points by the weights to generate weighted control points. This function is dimension agnostic, i.e. control points can be in any dimension but weights should be 1D. The ``weights`` function parameter can be set to None to let the function generate a weights vector composed of 1.0 values. This feature can be used to convert B-Spline basis to NURBS basis. :param ctrlpts: unweighted control points :type ctrlpts: list, tuple :param weights: weights vector; if set to None, a weights vector of 1.0s will be automatically generated :type weights: list, tuple or None :return: weighted control points :rtype: list """ if weights is None: weights = [1.0 for _ in range(len(ctrlpts))] ctrlptsw = [] for pt, w in zip(ctrlpts, weights): temp = [float(c * w) for c in pt] temp.append(float(w)) ctrlptsw.append(temp) return ctrlptsw
python
def combine_ctrlpts_weights(ctrlpts, weights=None): """ Multiplies control points by the weights to generate weighted control points. This function is dimension agnostic, i.e. control points can be in any dimension but weights should be 1D. The ``weights`` function parameter can be set to None to let the function generate a weights vector composed of 1.0 values. This feature can be used to convert B-Spline basis to NURBS basis. :param ctrlpts: unweighted control points :type ctrlpts: list, tuple :param weights: weights vector; if set to None, a weights vector of 1.0s will be automatically generated :type weights: list, tuple or None :return: weighted control points :rtype: list """ if weights is None: weights = [1.0 for _ in range(len(ctrlpts))] ctrlptsw = [] for pt, w in zip(ctrlpts, weights): temp = [float(c * w) for c in pt] temp.append(float(w)) ctrlptsw.append(temp) return ctrlptsw
[ "def", "combine_ctrlpts_weights", "(", "ctrlpts", ",", "weights", "=", "None", ")", ":", "if", "weights", "is", "None", ":", "weights", "=", "[", "1.0", "for", "_", "in", "range", "(", "len", "(", "ctrlpts", ")", ")", "]", "ctrlptsw", "=", "[", "]", "for", "pt", ",", "w", "in", "zip", "(", "ctrlpts", ",", "weights", ")", ":", "temp", "=", "[", "float", "(", "c", "*", "w", ")", "for", "c", "in", "pt", "]", "temp", ".", "append", "(", "float", "(", "w", ")", ")", "ctrlptsw", ".", "append", "(", "temp", ")", "return", "ctrlptsw" ]
Multiplies control points by the weights to generate weighted control points. This function is dimension agnostic, i.e. control points can be in any dimension but weights should be 1D. The ``weights`` function parameter can be set to None to let the function generate a weights vector composed of 1.0 values. This feature can be used to convert B-Spline basis to NURBS basis. :param ctrlpts: unweighted control points :type ctrlpts: list, tuple :param weights: weights vector; if set to None, a weights vector of 1.0s will be automatically generated :type weights: list, tuple or None :return: weighted control points :rtype: list
[ "Multiplies", "control", "points", "by", "the", "weights", "to", "generate", "weighted", "control", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/compatibility.py#L190-L214
230,306
orbingol/NURBS-Python
geomdl/compatibility.py
separate_ctrlpts_weights
def separate_ctrlpts_weights(ctrlptsw): """ Divides weighted control points by weights to generate unweighted control points and weights vector. This function is dimension agnostic, i.e. control points can be in any dimension but the last element of the array should indicate the weight. :param ctrlptsw: weighted control points :type ctrlptsw: list, tuple :return: unweighted control points and weights vector :rtype: list """ ctrlpts = [] weights = [] for ptw in ctrlptsw: temp = [float(pw / ptw[-1]) for pw in ptw[:-1]] ctrlpts.append(temp) weights.append(ptw[-1]) return [ctrlpts, weights]
python
def separate_ctrlpts_weights(ctrlptsw): """ Divides weighted control points by weights to generate unweighted control points and weights vector. This function is dimension agnostic, i.e. control points can be in any dimension but the last element of the array should indicate the weight. :param ctrlptsw: weighted control points :type ctrlptsw: list, tuple :return: unweighted control points and weights vector :rtype: list """ ctrlpts = [] weights = [] for ptw in ctrlptsw: temp = [float(pw / ptw[-1]) for pw in ptw[:-1]] ctrlpts.append(temp) weights.append(ptw[-1]) return [ctrlpts, weights]
[ "def", "separate_ctrlpts_weights", "(", "ctrlptsw", ")", ":", "ctrlpts", "=", "[", "]", "weights", "=", "[", "]", "for", "ptw", "in", "ctrlptsw", ":", "temp", "=", "[", "float", "(", "pw", "/", "ptw", "[", "-", "1", "]", ")", "for", "pw", "in", "ptw", "[", ":", "-", "1", "]", "]", "ctrlpts", ".", "append", "(", "temp", ")", "weights", ".", "append", "(", "ptw", "[", "-", "1", "]", ")", "return", "[", "ctrlpts", ",", "weights", "]" ]
Divides weighted control points by weights to generate unweighted control points and weights vector. This function is dimension agnostic, i.e. control points can be in any dimension but the last element of the array should indicate the weight. :param ctrlptsw: weighted control points :type ctrlptsw: list, tuple :return: unweighted control points and weights vector :rtype: list
[ "Divides", "weighted", "control", "points", "by", "weights", "to", "generate", "unweighted", "control", "points", "and", "weights", "vector", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/compatibility.py#L217-L235
230,307
orbingol/NURBS-Python
geomdl/compatibility.py
flip_ctrlpts2d_file
def flip_ctrlpts2d_file(file_in='', file_out='ctrlpts_flip.txt'): """ Flips u and v directions of a 2D control points file and saves flipped coordinates to a file. :param file_in: name of the input file (to be read) :type file_in: str :param file_out: name of the output file (to be saved) :type file_out: str :raises IOError: an error occurred reading or writing the file """ # Read control points ctrlpts2d, size_u, size_v = _read_ctrltps2d_file(file_in) # Flip control points array new_ctrlpts2d = flip_ctrlpts2d(ctrlpts2d, size_u, size_v) # Save new control points _save_ctrlpts2d_file(new_ctrlpts2d, size_u, size_v, file_out)
python
def flip_ctrlpts2d_file(file_in='', file_out='ctrlpts_flip.txt'): """ Flips u and v directions of a 2D control points file and saves flipped coordinates to a file. :param file_in: name of the input file (to be read) :type file_in: str :param file_out: name of the output file (to be saved) :type file_out: str :raises IOError: an error occurred reading or writing the file """ # Read control points ctrlpts2d, size_u, size_v = _read_ctrltps2d_file(file_in) # Flip control points array new_ctrlpts2d = flip_ctrlpts2d(ctrlpts2d, size_u, size_v) # Save new control points _save_ctrlpts2d_file(new_ctrlpts2d, size_u, size_v, file_out)
[ "def", "flip_ctrlpts2d_file", "(", "file_in", "=", "''", ",", "file_out", "=", "'ctrlpts_flip.txt'", ")", ":", "# Read control points", "ctrlpts2d", ",", "size_u", ",", "size_v", "=", "_read_ctrltps2d_file", "(", "file_in", ")", "# Flip control points array", "new_ctrlpts2d", "=", "flip_ctrlpts2d", "(", "ctrlpts2d", ",", "size_u", ",", "size_v", ")", "# Save new control points", "_save_ctrlpts2d_file", "(", "new_ctrlpts2d", ",", "size_u", ",", "size_v", ",", "file_out", ")" ]
Flips u and v directions of a 2D control points file and saves flipped coordinates to a file. :param file_in: name of the input file (to be read) :type file_in: str :param file_out: name of the output file (to be saved) :type file_out: str :raises IOError: an error occurred reading or writing the file
[ "Flips", "u", "and", "v", "directions", "of", "a", "2D", "control", "points", "file", "and", "saves", "flipped", "coordinates", "to", "a", "file", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/compatibility.py#L238-L254
230,308
orbingol/NURBS-Python
geomdl/compatibility.py
generate_ctrlptsw2d_file
def generate_ctrlptsw2d_file(file_in='', file_out='ctrlptsw.txt'): """ Generates weighted control points from unweighted ones in 2-D. This function #. Takes in a 2-D control points file whose coordinates are organized in (x, y, z, w) format #. Converts into (x*w, y*w, z*w, w) format #. Saves the result to a file Therefore, the resultant file could be a direct input of the NURBS.Surface class. :param file_in: name of the input file (to be read) :type file_in: str :param file_out: name of the output file (to be saved) :type file_out: str :raises IOError: an error occurred reading or writing the file """ # Read control points ctrlpts2d, size_u, size_v = _read_ctrltps2d_file(file_in) # Multiply control points by weight new_ctrlpts2d = generate_ctrlptsw2d(ctrlpts2d) # Save new control points _save_ctrlpts2d_file(new_ctrlpts2d, size_u, size_v, file_out)
python
def generate_ctrlptsw2d_file(file_in='', file_out='ctrlptsw.txt'): """ Generates weighted control points from unweighted ones in 2-D. This function #. Takes in a 2-D control points file whose coordinates are organized in (x, y, z, w) format #. Converts into (x*w, y*w, z*w, w) format #. Saves the result to a file Therefore, the resultant file could be a direct input of the NURBS.Surface class. :param file_in: name of the input file (to be read) :type file_in: str :param file_out: name of the output file (to be saved) :type file_out: str :raises IOError: an error occurred reading or writing the file """ # Read control points ctrlpts2d, size_u, size_v = _read_ctrltps2d_file(file_in) # Multiply control points by weight new_ctrlpts2d = generate_ctrlptsw2d(ctrlpts2d) # Save new control points _save_ctrlpts2d_file(new_ctrlpts2d, size_u, size_v, file_out)
[ "def", "generate_ctrlptsw2d_file", "(", "file_in", "=", "''", ",", "file_out", "=", "'ctrlptsw.txt'", ")", ":", "# Read control points", "ctrlpts2d", ",", "size_u", ",", "size_v", "=", "_read_ctrltps2d_file", "(", "file_in", ")", "# Multiply control points by weight", "new_ctrlpts2d", "=", "generate_ctrlptsw2d", "(", "ctrlpts2d", ")", "# Save new control points", "_save_ctrlpts2d_file", "(", "new_ctrlpts2d", ",", "size_u", ",", "size_v", ",", "file_out", ")" ]
Generates weighted control points from unweighted ones in 2-D. This function #. Takes in a 2-D control points file whose coordinates are organized in (x, y, z, w) format #. Converts into (x*w, y*w, z*w, w) format #. Saves the result to a file Therefore, the resultant file could be a direct input of the NURBS.Surface class. :param file_in: name of the input file (to be read) :type file_in: str :param file_out: name of the output file (to be saved) :type file_out: str :raises IOError: an error occurred reading or writing the file
[ "Generates", "weighted", "control", "points", "from", "unweighted", "ones", "in", "2", "-", "D", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/compatibility.py#L257-L281
230,309
orbingol/NURBS-Python
geomdl/visualization/VisVTK.py
VisConfig.keypress_callback
def keypress_callback(self, obj, ev): """ VTK callback for keypress events. Keypress events: * ``e``: exit the application * ``p``: pick object (hover the mouse and then press to pick) * ``f``: fly to point (click somewhere in the window and press to fly) * ``r``: reset the camera * ``s`` and ``w``: switch between solid and wireframe modes * ``b``: change background color * ``m``: change color of the picked object * ``d``: print debug information (of picked object, point, etc.) * ``h``: change object visibility * ``n``: reset object visibility * ``arrow keys``: pan the model Please refer to `vtkInteractorStyle <https://vtk.org/doc/nightly/html/classvtkInteractorStyle.html>`_ class reference for more details. :param obj: render window interactor :type obj: vtkRenderWindowInteractor :param ev: event name :type ev: str """ key = obj.GetKeySym() # pressed key (as str) render_window = obj.GetRenderWindow() # vtkRenderWindow renderer = render_window.GetRenderers().GetFirstRenderer() # vtkRenderer picker = obj.GetPicker() # vtkPropPicker actor = picker.GetActor() # vtkActor # Custom keypress events if key == 'Up': camera = renderer.GetActiveCamera() # vtkCamera camera.Pitch(2.5) if key == 'Down': camera = renderer.GetActiveCamera() # vtkCamera camera.Pitch(-2.5) if key == 'Left': camera = renderer.GetActiveCamera() # vtkCamera camera.Yaw(-2.5) if key == 'Right': camera = renderer.GetActiveCamera() # vtkCamera camera.Yaw(2.5) if key == 'b': if self._bg_id >= len(self._bg): self._bg_id = 0 renderer.SetBackground(*self._bg[self._bg_id]) self._bg_id += 1 if key == 'm': if actor is not None: actor.GetProperty().SetColor(random(), random(), random()) if key == 'd': if actor is not None: print("Name:", actor.GetMapper().GetArrayName()) print("Index:", actor.GetMapper().GetArrayId()) print("Selected point:", picker.GetSelectionPoint()[0:2]) print("# of visible actors:", renderer.VisibleActorCount()) if key == 'h': if actor is not None: actor.SetVisibility(not actor.GetVisibility()) if key == 'n': actors = renderer.GetActors() # vtkActorCollection for actor in actors: actor.VisibilityOn() # Update render window render_window.Render()
python
def keypress_callback(self, obj, ev): """ VTK callback for keypress events. Keypress events: * ``e``: exit the application * ``p``: pick object (hover the mouse and then press to pick) * ``f``: fly to point (click somewhere in the window and press to fly) * ``r``: reset the camera * ``s`` and ``w``: switch between solid and wireframe modes * ``b``: change background color * ``m``: change color of the picked object * ``d``: print debug information (of picked object, point, etc.) * ``h``: change object visibility * ``n``: reset object visibility * ``arrow keys``: pan the model Please refer to `vtkInteractorStyle <https://vtk.org/doc/nightly/html/classvtkInteractorStyle.html>`_ class reference for more details. :param obj: render window interactor :type obj: vtkRenderWindowInteractor :param ev: event name :type ev: str """ key = obj.GetKeySym() # pressed key (as str) render_window = obj.GetRenderWindow() # vtkRenderWindow renderer = render_window.GetRenderers().GetFirstRenderer() # vtkRenderer picker = obj.GetPicker() # vtkPropPicker actor = picker.GetActor() # vtkActor # Custom keypress events if key == 'Up': camera = renderer.GetActiveCamera() # vtkCamera camera.Pitch(2.5) if key == 'Down': camera = renderer.GetActiveCamera() # vtkCamera camera.Pitch(-2.5) if key == 'Left': camera = renderer.GetActiveCamera() # vtkCamera camera.Yaw(-2.5) if key == 'Right': camera = renderer.GetActiveCamera() # vtkCamera camera.Yaw(2.5) if key == 'b': if self._bg_id >= len(self._bg): self._bg_id = 0 renderer.SetBackground(*self._bg[self._bg_id]) self._bg_id += 1 if key == 'm': if actor is not None: actor.GetProperty().SetColor(random(), random(), random()) if key == 'd': if actor is not None: print("Name:", actor.GetMapper().GetArrayName()) print("Index:", actor.GetMapper().GetArrayId()) print("Selected point:", picker.GetSelectionPoint()[0:2]) print("# of visible actors:", renderer.VisibleActorCount()) if key == 'h': if actor is not None: actor.SetVisibility(not actor.GetVisibility()) if key == 'n': actors = renderer.GetActors() # vtkActorCollection for actor in actors: actor.VisibilityOn() # Update render window render_window.Render()
[ "def", "keypress_callback", "(", "self", ",", "obj", ",", "ev", ")", ":", "key", "=", "obj", ".", "GetKeySym", "(", ")", "# pressed key (as str)", "render_window", "=", "obj", ".", "GetRenderWindow", "(", ")", "# vtkRenderWindow", "renderer", "=", "render_window", ".", "GetRenderers", "(", ")", ".", "GetFirstRenderer", "(", ")", "# vtkRenderer", "picker", "=", "obj", ".", "GetPicker", "(", ")", "# vtkPropPicker", "actor", "=", "picker", ".", "GetActor", "(", ")", "# vtkActor", "# Custom keypress events", "if", "key", "==", "'Up'", ":", "camera", "=", "renderer", ".", "GetActiveCamera", "(", ")", "# vtkCamera", "camera", ".", "Pitch", "(", "2.5", ")", "if", "key", "==", "'Down'", ":", "camera", "=", "renderer", ".", "GetActiveCamera", "(", ")", "# vtkCamera", "camera", ".", "Pitch", "(", "-", "2.5", ")", "if", "key", "==", "'Left'", ":", "camera", "=", "renderer", ".", "GetActiveCamera", "(", ")", "# vtkCamera", "camera", ".", "Yaw", "(", "-", "2.5", ")", "if", "key", "==", "'Right'", ":", "camera", "=", "renderer", ".", "GetActiveCamera", "(", ")", "# vtkCamera", "camera", ".", "Yaw", "(", "2.5", ")", "if", "key", "==", "'b'", ":", "if", "self", ".", "_bg_id", ">=", "len", "(", "self", ".", "_bg", ")", ":", "self", ".", "_bg_id", "=", "0", "renderer", ".", "SetBackground", "(", "*", "self", ".", "_bg", "[", "self", ".", "_bg_id", "]", ")", "self", ".", "_bg_id", "+=", "1", "if", "key", "==", "'m'", ":", "if", "actor", "is", "not", "None", ":", "actor", ".", "GetProperty", "(", ")", ".", "SetColor", "(", "random", "(", ")", ",", "random", "(", ")", ",", "random", "(", ")", ")", "if", "key", "==", "'d'", ":", "if", "actor", "is", "not", "None", ":", "print", "(", "\"Name:\"", ",", "actor", ".", "GetMapper", "(", ")", ".", "GetArrayName", "(", ")", ")", "print", "(", "\"Index:\"", ",", "actor", ".", "GetMapper", "(", ")", ".", "GetArrayId", "(", ")", ")", "print", "(", "\"Selected point:\"", ",", "picker", ".", "GetSelectionPoint", "(", ")", "[", "0", ":", "2", "]", ")", "print", "(", "\"# of visible actors:\"", ",", "renderer", ".", "VisibleActorCount", "(", ")", ")", "if", "key", "==", "'h'", ":", "if", "actor", "is", "not", "None", ":", "actor", ".", "SetVisibility", "(", "not", "actor", ".", "GetVisibility", "(", ")", ")", "if", "key", "==", "'n'", ":", "actors", "=", "renderer", ".", "GetActors", "(", ")", "# vtkActorCollection", "for", "actor", "in", "actors", ":", "actor", ".", "VisibilityOn", "(", ")", "# Update render window", "render_window", ".", "Render", "(", ")" ]
VTK callback for keypress events. Keypress events: * ``e``: exit the application * ``p``: pick object (hover the mouse and then press to pick) * ``f``: fly to point (click somewhere in the window and press to fly) * ``r``: reset the camera * ``s`` and ``w``: switch between solid and wireframe modes * ``b``: change background color * ``m``: change color of the picked object * ``d``: print debug information (of picked object, point, etc.) * ``h``: change object visibility * ``n``: reset object visibility * ``arrow keys``: pan the model Please refer to `vtkInteractorStyle <https://vtk.org/doc/nightly/html/classvtkInteractorStyle.html>`_ class reference for more details. :param obj: render window interactor :type obj: vtkRenderWindowInteractor :param ev: event name :type ev: str
[ "VTK", "callback", "for", "keypress", "events", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/VisVTK.py#L46-L112
230,310
orbingol/NURBS-Python
geomdl/_voxelize.py
generate_voxel_grid
def generate_voxel_grid(bbox, szval, use_cubes=False): """ Generates the voxel grid with the desired size. :param bbox: bounding box :type bbox: list, tuple :param szval: size in x-, y-, z-directions :type szval: list, tuple :param use_cubes: use cube voxels instead of cuboid ones :type use_cubes: bool :return: voxel grid :rtype: list """ # Input validation if szval[0] <= 1 or szval[1] <= 1 or szval[2] <= 1: raise GeomdlException("Size values must be bigger than 1", data=dict(sizevals=szval)) # Find step size for each direction steps = [float(bbox[1][idx] - bbox[0][idx]) / float(szval[idx] - 1) for idx in range(0, 3)] # It is possible to use cubes instead of cuboids if use_cubes: min_val = min(*steps) steps = [min_val for _ in range(0, 3)] # Find range in each direction ranges = [list(linalg.frange(bbox[0][idx], bbox[1][idx], steps[idx])) for idx in range(0, 3)] voxel_grid = [] for u in ranges[0]: for v in ranges[1]: for w in ranges[2]: bbmin = [u, v, w] bbmax = [k + l for k, l in zip(bbmin, steps)] voxel_grid.append([bbmin, bbmax]) return voxel_grid
python
def generate_voxel_grid(bbox, szval, use_cubes=False): """ Generates the voxel grid with the desired size. :param bbox: bounding box :type bbox: list, tuple :param szval: size in x-, y-, z-directions :type szval: list, tuple :param use_cubes: use cube voxels instead of cuboid ones :type use_cubes: bool :return: voxel grid :rtype: list """ # Input validation if szval[0] <= 1 or szval[1] <= 1 or szval[2] <= 1: raise GeomdlException("Size values must be bigger than 1", data=dict(sizevals=szval)) # Find step size for each direction steps = [float(bbox[1][idx] - bbox[0][idx]) / float(szval[idx] - 1) for idx in range(0, 3)] # It is possible to use cubes instead of cuboids if use_cubes: min_val = min(*steps) steps = [min_val for _ in range(0, 3)] # Find range in each direction ranges = [list(linalg.frange(bbox[0][idx], bbox[1][idx], steps[idx])) for idx in range(0, 3)] voxel_grid = [] for u in ranges[0]: for v in ranges[1]: for w in ranges[2]: bbmin = [u, v, w] bbmax = [k + l for k, l in zip(bbmin, steps)] voxel_grid.append([bbmin, bbmax]) return voxel_grid
[ "def", "generate_voxel_grid", "(", "bbox", ",", "szval", ",", "use_cubes", "=", "False", ")", ":", "# Input validation", "if", "szval", "[", "0", "]", "<=", "1", "or", "szval", "[", "1", "]", "<=", "1", "or", "szval", "[", "2", "]", "<=", "1", ":", "raise", "GeomdlException", "(", "\"Size values must be bigger than 1\"", ",", "data", "=", "dict", "(", "sizevals", "=", "szval", ")", ")", "# Find step size for each direction", "steps", "=", "[", "float", "(", "bbox", "[", "1", "]", "[", "idx", "]", "-", "bbox", "[", "0", "]", "[", "idx", "]", ")", "/", "float", "(", "szval", "[", "idx", "]", "-", "1", ")", "for", "idx", "in", "range", "(", "0", ",", "3", ")", "]", "# It is possible to use cubes instead of cuboids", "if", "use_cubes", ":", "min_val", "=", "min", "(", "*", "steps", ")", "steps", "=", "[", "min_val", "for", "_", "in", "range", "(", "0", ",", "3", ")", "]", "# Find range in each direction", "ranges", "=", "[", "list", "(", "linalg", ".", "frange", "(", "bbox", "[", "0", "]", "[", "idx", "]", ",", "bbox", "[", "1", "]", "[", "idx", "]", ",", "steps", "[", "idx", "]", ")", ")", "for", "idx", "in", "range", "(", "0", ",", "3", ")", "]", "voxel_grid", "=", "[", "]", "for", "u", "in", "ranges", "[", "0", "]", ":", "for", "v", "in", "ranges", "[", "1", "]", ":", "for", "w", "in", "ranges", "[", "2", "]", ":", "bbmin", "=", "[", "u", ",", "v", ",", "w", "]", "bbmax", "=", "[", "k", "+", "l", "for", "k", ",", "l", "in", "zip", "(", "bbmin", ",", "steps", ")", "]", "voxel_grid", ".", "append", "(", "[", "bbmin", ",", "bbmax", "]", ")", "return", "voxel_grid" ]
Generates the voxel grid with the desired size. :param bbox: bounding box :type bbox: list, tuple :param szval: size in x-, y-, z-directions :type szval: list, tuple :param use_cubes: use cube voxels instead of cuboid ones :type use_cubes: bool :return: voxel grid :rtype: list
[ "Generates", "the", "voxel", "grid", "with", "the", "desired", "size", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_voxelize.py#L49-L83
230,311
orbingol/NURBS-Python
geomdl/_exchange.py
process_template
def process_template(file_src): """ Process Jinja2 template input :param file_src: file contents :type file_src: str """ def tmpl_sqrt(x): """ Square-root of 'x' """ return math.sqrt(x) def tmpl_cubert(x): """ Cube-root of 'x' """ return x ** (1.0 / 3.0) if x >= 0 else -(-x) ** (1.0 / 3.0) def tmpl_pow(x, y): """ 'x' to the power 'y' """ return math.pow(x, y) # Check if it is possible to import 'jinja2' try: import jinja2 except ImportError: raise GeomdlException("Please install 'jinja2' package to use templated input: pip install jinja2") # Replace jinja2 template tags for compatibility fsrc = file_src.replace("{%", "<%").replace("%}", "%>").replace("{{", "<{").replace("}}", "}>") # Generate Jinja2 environment env = jinja2.Environment( loader=jinja2.BaseLoader(), trim_blocks=True, block_start_string='<%', block_end_string='%>', variable_start_string='<{', variable_end_string='}>' ).from_string(fsrc) # Load custom functions into the Jinja2 environment template_funcs = dict( knot_vector=utilities.generate_knot_vector, sqrt=tmpl_sqrt, cubert=tmpl_cubert, pow=tmpl_pow, ) for k, v in template_funcs.items(): env.globals[k] = v # Process Jinja2 template functions & variables inside the input file return env.render()
python
def process_template(file_src): """ Process Jinja2 template input :param file_src: file contents :type file_src: str """ def tmpl_sqrt(x): """ Square-root of 'x' """ return math.sqrt(x) def tmpl_cubert(x): """ Cube-root of 'x' """ return x ** (1.0 / 3.0) if x >= 0 else -(-x) ** (1.0 / 3.0) def tmpl_pow(x, y): """ 'x' to the power 'y' """ return math.pow(x, y) # Check if it is possible to import 'jinja2' try: import jinja2 except ImportError: raise GeomdlException("Please install 'jinja2' package to use templated input: pip install jinja2") # Replace jinja2 template tags for compatibility fsrc = file_src.replace("{%", "<%").replace("%}", "%>").replace("{{", "<{").replace("}}", "}>") # Generate Jinja2 environment env = jinja2.Environment( loader=jinja2.BaseLoader(), trim_blocks=True, block_start_string='<%', block_end_string='%>', variable_start_string='<{', variable_end_string='}>' ).from_string(fsrc) # Load custom functions into the Jinja2 environment template_funcs = dict( knot_vector=utilities.generate_knot_vector, sqrt=tmpl_sqrt, cubert=tmpl_cubert, pow=tmpl_pow, ) for k, v in template_funcs.items(): env.globals[k] = v # Process Jinja2 template functions & variables inside the input file return env.render()
[ "def", "process_template", "(", "file_src", ")", ":", "def", "tmpl_sqrt", "(", "x", ")", ":", "\"\"\" Square-root of 'x' \"\"\"", "return", "math", ".", "sqrt", "(", "x", ")", "def", "tmpl_cubert", "(", "x", ")", ":", "\"\"\" Cube-root of 'x' \"\"\"", "return", "x", "**", "(", "1.0", "/", "3.0", ")", "if", "x", ">=", "0", "else", "-", "(", "-", "x", ")", "**", "(", "1.0", "/", "3.0", ")", "def", "tmpl_pow", "(", "x", ",", "y", ")", ":", "\"\"\" 'x' to the power 'y' \"\"\"", "return", "math", ".", "pow", "(", "x", ",", "y", ")", "# Check if it is possible to import 'jinja2'", "try", ":", "import", "jinja2", "except", "ImportError", ":", "raise", "GeomdlException", "(", "\"Please install 'jinja2' package to use templated input: pip install jinja2\"", ")", "# Replace jinja2 template tags for compatibility", "fsrc", "=", "file_src", ".", "replace", "(", "\"{%\"", ",", "\"<%\"", ")", ".", "replace", "(", "\"%}\"", ",", "\"%>\"", ")", ".", "replace", "(", "\"{{\"", ",", "\"<{\"", ")", ".", "replace", "(", "\"}}\"", ",", "\"}>\"", ")", "# Generate Jinja2 environment", "env", "=", "jinja2", ".", "Environment", "(", "loader", "=", "jinja2", ".", "BaseLoader", "(", ")", ",", "trim_blocks", "=", "True", ",", "block_start_string", "=", "'<%'", ",", "block_end_string", "=", "'%>'", ",", "variable_start_string", "=", "'<{'", ",", "variable_end_string", "=", "'}>'", ")", ".", "from_string", "(", "fsrc", ")", "# Load custom functions into the Jinja2 environment", "template_funcs", "=", "dict", "(", "knot_vector", "=", "utilities", ".", "generate_knot_vector", ",", "sqrt", "=", "tmpl_sqrt", ",", "cubert", "=", "tmpl_cubert", ",", "pow", "=", "tmpl_pow", ",", ")", "for", "k", ",", "v", "in", "template_funcs", ".", "items", "(", ")", ":", "env", ".", "globals", "[", "k", "]", "=", "v", "# Process Jinja2 template functions & variables inside the input file", "return", "env", ".", "render", "(", ")" ]
Process Jinja2 template input :param file_src: file contents :type file_src: str
[ "Process", "Jinja2", "template", "input" ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_exchange.py#L21-L67
230,312
orbingol/NURBS-Python
geomdl/_exchange.py
import_surf_mesh
def import_surf_mesh(file_name): """ Generates a NURBS surface object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS surface :rtype: NURBS.Surface """ raw_content = read_file(file_name) raw_content = raw_content.split("\n") content = [] for rc in raw_content: temp = rc.strip().split() content.append(temp) # 1st line defines the dimension and it must be 3 if int(content[0][0]) != 3: raise TypeError("Input mesh '" + str(file_name) + "' must be 3-dimensional") # Create a NURBS surface instance and fill with the data read from mesh file surf = shortcuts.generate_surface(rational=True) # 2nd line is the degrees surf.degree_u = int(content[1][0]) surf.degree_v = int(content[1][1]) # 3rd line is the number of weighted control points in u and v directions dim_u = int(content[2][0]) dim_v = int(content[2][1]) # Starting from 6th line, we have the weighted control points ctrlpts_end = 5 + (dim_u * dim_v) ctrlpts_mesh = content[5:ctrlpts_end] # mesh files have the control points in u-row order format ctrlpts = compatibility.flip_ctrlpts_u(ctrlpts_mesh, dim_u, dim_v) # mesh files store control points in format (x, y, z, w) ctrlptsw = compatibility.generate_ctrlptsw(ctrlpts) # Set control points surf.set_ctrlpts(ctrlptsw, dim_u, dim_v) # 4th and 5th lines are knot vectors surf.knotvector_u = [float(u) for u in content[3]] surf.knotvector_v = [float(v) for v in content[4]] # Return the surface instance return surf
python
def import_surf_mesh(file_name): """ Generates a NURBS surface object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS surface :rtype: NURBS.Surface """ raw_content = read_file(file_name) raw_content = raw_content.split("\n") content = [] for rc in raw_content: temp = rc.strip().split() content.append(temp) # 1st line defines the dimension and it must be 3 if int(content[0][0]) != 3: raise TypeError("Input mesh '" + str(file_name) + "' must be 3-dimensional") # Create a NURBS surface instance and fill with the data read from mesh file surf = shortcuts.generate_surface(rational=True) # 2nd line is the degrees surf.degree_u = int(content[1][0]) surf.degree_v = int(content[1][1]) # 3rd line is the number of weighted control points in u and v directions dim_u = int(content[2][0]) dim_v = int(content[2][1]) # Starting from 6th line, we have the weighted control points ctrlpts_end = 5 + (dim_u * dim_v) ctrlpts_mesh = content[5:ctrlpts_end] # mesh files have the control points in u-row order format ctrlpts = compatibility.flip_ctrlpts_u(ctrlpts_mesh, dim_u, dim_v) # mesh files store control points in format (x, y, z, w) ctrlptsw = compatibility.generate_ctrlptsw(ctrlpts) # Set control points surf.set_ctrlpts(ctrlptsw, dim_u, dim_v) # 4th and 5th lines are knot vectors surf.knotvector_u = [float(u) for u in content[3]] surf.knotvector_v = [float(v) for v in content[4]] # Return the surface instance return surf
[ "def", "import_surf_mesh", "(", "file_name", ")", ":", "raw_content", "=", "read_file", "(", "file_name", ")", "raw_content", "=", "raw_content", ".", "split", "(", "\"\\n\"", ")", "content", "=", "[", "]", "for", "rc", "in", "raw_content", ":", "temp", "=", "rc", ".", "strip", "(", ")", ".", "split", "(", ")", "content", ".", "append", "(", "temp", ")", "# 1st line defines the dimension and it must be 3", "if", "int", "(", "content", "[", "0", "]", "[", "0", "]", ")", "!=", "3", ":", "raise", "TypeError", "(", "\"Input mesh '\"", "+", "str", "(", "file_name", ")", "+", "\"' must be 3-dimensional\"", ")", "# Create a NURBS surface instance and fill with the data read from mesh file", "surf", "=", "shortcuts", ".", "generate_surface", "(", "rational", "=", "True", ")", "# 2nd line is the degrees", "surf", ".", "degree_u", "=", "int", "(", "content", "[", "1", "]", "[", "0", "]", ")", "surf", ".", "degree_v", "=", "int", "(", "content", "[", "1", "]", "[", "1", "]", ")", "# 3rd line is the number of weighted control points in u and v directions", "dim_u", "=", "int", "(", "content", "[", "2", "]", "[", "0", "]", ")", "dim_v", "=", "int", "(", "content", "[", "2", "]", "[", "1", "]", ")", "# Starting from 6th line, we have the weighted control points", "ctrlpts_end", "=", "5", "+", "(", "dim_u", "*", "dim_v", ")", "ctrlpts_mesh", "=", "content", "[", "5", ":", "ctrlpts_end", "]", "# mesh files have the control points in u-row order format", "ctrlpts", "=", "compatibility", ".", "flip_ctrlpts_u", "(", "ctrlpts_mesh", ",", "dim_u", ",", "dim_v", ")", "# mesh files store control points in format (x, y, z, w)", "ctrlptsw", "=", "compatibility", ".", "generate_ctrlptsw", "(", "ctrlpts", ")", "# Set control points", "surf", ".", "set_ctrlpts", "(", "ctrlptsw", ",", "dim_u", ",", "dim_v", ")", "# 4th and 5th lines are knot vectors", "surf", ".", "knotvector_u", "=", "[", "float", "(", "u", ")", "for", "u", "in", "content", "[", "3", "]", "]", "surf", ".", "knotvector_v", "=", "[", "float", "(", "v", ")", "for", "v", "in", "content", "[", "4", "]", "]", "# Return the surface instance", "return", "surf" ]
Generates a NURBS surface object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS surface :rtype: NURBS.Surface
[ "Generates", "a", "NURBS", "surface", "object", "from", "a", "mesh", "file", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_exchange.py#L102-L150
230,313
orbingol/NURBS-Python
geomdl/_exchange.py
import_vol_mesh
def import_vol_mesh(file_name): """ Generates a NURBS volume object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS volume :rtype: NURBS.Volume """ raw_content = read_file(file_name) raw_content = raw_content.split("\n") content = [] for rc in raw_content: temp = rc.strip().split() content.append(temp) # 1st line defines the dimension and it must be 3 if int(content[0][0]) != 3: raise TypeError("Input mesh '" + str(file_name) + "' must be 3-dimensional") # Create a NURBS surface instance and fill with the data read from mesh file vol = shortcuts.generate_volume(rational=True) # 2nd line is the degrees vol.degree_u = int(content[1][0]) vol.degree_v = int(content[1][1]) vol.degree_w = int(content[1][2]) # 3rd line is the number of weighted control points in u, v, w directions dim_u = int(content[2][0]) dim_v = int(content[2][1]) dim_w = int(content[2][2]) # Starting from 7th line, we have the weighted control points surf_cpts = dim_u * dim_v ctrlpts_end = 6 + (surf_cpts * dim_w) ctrlpts_mesh = content[6:ctrlpts_end] # mesh files have the control points in u-row order format ctrlpts = [] for i in range(dim_w - 1): ctrlpts += compatibility.flip_ctrlpts_u(ctrlpts_mesh[surf_cpts * i:surf_cpts * (i + 1)], dim_u, dim_v) # mesh files store control points in format (x, y, z, w) ctrlptsw = compatibility.generate_ctrlptsw(ctrlpts) # Set control points vol.set_ctrlpts(ctrlptsw, dim_u, dim_v, dim_w) # 4th, 5th and 6th lines are knot vectors vol.knotvector_u = [float(u) for u in content[3]] vol.knotvector_v = [float(v) for v in content[4]] vol.knotvector_w = [float(w) for w in content[5]] # Return the volume instance return vol
python
def import_vol_mesh(file_name): """ Generates a NURBS volume object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS volume :rtype: NURBS.Volume """ raw_content = read_file(file_name) raw_content = raw_content.split("\n") content = [] for rc in raw_content: temp = rc.strip().split() content.append(temp) # 1st line defines the dimension and it must be 3 if int(content[0][0]) != 3: raise TypeError("Input mesh '" + str(file_name) + "' must be 3-dimensional") # Create a NURBS surface instance and fill with the data read from mesh file vol = shortcuts.generate_volume(rational=True) # 2nd line is the degrees vol.degree_u = int(content[1][0]) vol.degree_v = int(content[1][1]) vol.degree_w = int(content[1][2]) # 3rd line is the number of weighted control points in u, v, w directions dim_u = int(content[2][0]) dim_v = int(content[2][1]) dim_w = int(content[2][2]) # Starting from 7th line, we have the weighted control points surf_cpts = dim_u * dim_v ctrlpts_end = 6 + (surf_cpts * dim_w) ctrlpts_mesh = content[6:ctrlpts_end] # mesh files have the control points in u-row order format ctrlpts = [] for i in range(dim_w - 1): ctrlpts += compatibility.flip_ctrlpts_u(ctrlpts_mesh[surf_cpts * i:surf_cpts * (i + 1)], dim_u, dim_v) # mesh files store control points in format (x, y, z, w) ctrlptsw = compatibility.generate_ctrlptsw(ctrlpts) # Set control points vol.set_ctrlpts(ctrlptsw, dim_u, dim_v, dim_w) # 4th, 5th and 6th lines are knot vectors vol.knotvector_u = [float(u) for u in content[3]] vol.knotvector_v = [float(v) for v in content[4]] vol.knotvector_w = [float(w) for w in content[5]] # Return the volume instance return vol
[ "def", "import_vol_mesh", "(", "file_name", ")", ":", "raw_content", "=", "read_file", "(", "file_name", ")", "raw_content", "=", "raw_content", ".", "split", "(", "\"\\n\"", ")", "content", "=", "[", "]", "for", "rc", "in", "raw_content", ":", "temp", "=", "rc", ".", "strip", "(", ")", ".", "split", "(", ")", "content", ".", "append", "(", "temp", ")", "# 1st line defines the dimension and it must be 3", "if", "int", "(", "content", "[", "0", "]", "[", "0", "]", ")", "!=", "3", ":", "raise", "TypeError", "(", "\"Input mesh '\"", "+", "str", "(", "file_name", ")", "+", "\"' must be 3-dimensional\"", ")", "# Create a NURBS surface instance and fill with the data read from mesh file", "vol", "=", "shortcuts", ".", "generate_volume", "(", "rational", "=", "True", ")", "# 2nd line is the degrees", "vol", ".", "degree_u", "=", "int", "(", "content", "[", "1", "]", "[", "0", "]", ")", "vol", ".", "degree_v", "=", "int", "(", "content", "[", "1", "]", "[", "1", "]", ")", "vol", ".", "degree_w", "=", "int", "(", "content", "[", "1", "]", "[", "2", "]", ")", "# 3rd line is the number of weighted control points in u, v, w directions", "dim_u", "=", "int", "(", "content", "[", "2", "]", "[", "0", "]", ")", "dim_v", "=", "int", "(", "content", "[", "2", "]", "[", "1", "]", ")", "dim_w", "=", "int", "(", "content", "[", "2", "]", "[", "2", "]", ")", "# Starting from 7th line, we have the weighted control points", "surf_cpts", "=", "dim_u", "*", "dim_v", "ctrlpts_end", "=", "6", "+", "(", "surf_cpts", "*", "dim_w", ")", "ctrlpts_mesh", "=", "content", "[", "6", ":", "ctrlpts_end", "]", "# mesh files have the control points in u-row order format", "ctrlpts", "=", "[", "]", "for", "i", "in", "range", "(", "dim_w", "-", "1", ")", ":", "ctrlpts", "+=", "compatibility", ".", "flip_ctrlpts_u", "(", "ctrlpts_mesh", "[", "surf_cpts", "*", "i", ":", "surf_cpts", "*", "(", "i", "+", "1", ")", "]", ",", "dim_u", ",", "dim_v", ")", "# mesh files store control points in format (x, y, z, w)", "ctrlptsw", "=", "compatibility", ".", "generate_ctrlptsw", "(", "ctrlpts", ")", "# Set control points", "vol", ".", "set_ctrlpts", "(", "ctrlptsw", ",", "dim_u", ",", "dim_v", ",", "dim_w", ")", "# 4th, 5th and 6th lines are knot vectors", "vol", ".", "knotvector_u", "=", "[", "float", "(", "u", ")", "for", "u", "in", "content", "[", "3", "]", "]", "vol", ".", "knotvector_v", "=", "[", "float", "(", "v", ")", "for", "v", "in", "content", "[", "4", "]", "]", "vol", ".", "knotvector_w", "=", "[", "float", "(", "w", ")", "for", "w", "in", "content", "[", "5", "]", "]", "# Return the volume instance", "return", "vol" ]
Generates a NURBS volume object from a mesh file. :param file_name: input mesh file :type file_name: str :return: a NURBS volume :rtype: NURBS.Volume
[ "Generates", "a", "NURBS", "volume", "object", "from", "a", "mesh", "file", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_exchange.py#L153-L207
230,314
orbingol/NURBS-Python
geomdl/exchange.py
import_txt
def import_txt(file_name, two_dimensional=False, **kwargs): """ Reads control points from a text file and generates a 1-dimensional list of control points. The following code examples illustrate importing different types of text files for curves and surfaces: .. code-block:: python :linenos: # Import curve control points from a text file curve_ctrlpts = exchange.import_txt(file_name="control_points.txt") # Import surface control points from a text file (1-dimensional file) surf_ctrlpts = exchange.import_txt(file_name="control_points.txt") # Import surface control points from a text file (2-dimensional file) surf_ctrlpts, size_u, size_v = exchange.import_txt(file_name="control_points.txt", two_dimensional=True) If argument ``jinja2=True`` is set, then the input file is processed as a `Jinja2 <http://jinja.pocoo.org/>`_ template. You can also use the following convenience template functions which correspond to the given mathematical equations: * ``sqrt(x)``: :math:`\\sqrt{x}` * ``cubert(x)``: :math:`\\sqrt[3]{x}` * ``pow(x, y)``: :math:`x^{y}` You may set the file delimiters using the keyword arguments ``separator`` and ``col_separator``, respectively. ``separator`` is the delimiter between the coordinates of the control points. It could be comma ``1, 2, 3`` or space ``1 2 3`` or something else. ``col_separator`` is the delimiter between the control points and is only valid when ``two_dimensional`` is ``True``. Assuming that ``separator`` is set to space, then ``col_operator`` could be semi-colon ``1 2 3; 4 5 6`` or pipe ``1 2 3| 4 5 6`` or comma ``1 2 3, 4 5 6`` or something else. The defaults for ``separator`` and ``col_separator`` are *comma (,)* and *semi-colon (;)*, respectively. The following code examples illustrate the usage of the keyword arguments discussed above. .. code-block:: python :linenos: # Import curve control points from a text file delimited with space curve_ctrlpts = exchange.import_txt(file_name="control_points.txt", separator=" ") # Import surface control points from a text file (2-dimensional file) w/ space and comma delimiters surf_ctrlpts, size_u, size_v = exchange.import_txt(file_name="control_points.txt", two_dimensional=True, separator=" ", col_separator=",") Please note that this function does not check whether the user set delimiters to the same value or not. :param file_name: file name of the text file :type file_name: str :param two_dimensional: type of the text file :type two_dimensional: bool :return: list of control points, if two_dimensional, then also returns size in u- and v-directions :rtype: list :raises GeomdlException: an error occurred reading the file """ # Read file content = exch.read_file(file_name) # Are we using a Jinja2 template? j2tmpl = kwargs.get('jinja2', False) if j2tmpl: content = exch.process_template(content) # File delimiters col_sep = kwargs.get('col_separator', ";") sep = kwargs.get('separator', ",") return exch.import_text_data(content, sep, col_sep, two_dimensional)
python
def import_txt(file_name, two_dimensional=False, **kwargs): """ Reads control points from a text file and generates a 1-dimensional list of control points. The following code examples illustrate importing different types of text files for curves and surfaces: .. code-block:: python :linenos: # Import curve control points from a text file curve_ctrlpts = exchange.import_txt(file_name="control_points.txt") # Import surface control points from a text file (1-dimensional file) surf_ctrlpts = exchange.import_txt(file_name="control_points.txt") # Import surface control points from a text file (2-dimensional file) surf_ctrlpts, size_u, size_v = exchange.import_txt(file_name="control_points.txt", two_dimensional=True) If argument ``jinja2=True`` is set, then the input file is processed as a `Jinja2 <http://jinja.pocoo.org/>`_ template. You can also use the following convenience template functions which correspond to the given mathematical equations: * ``sqrt(x)``: :math:`\\sqrt{x}` * ``cubert(x)``: :math:`\\sqrt[3]{x}` * ``pow(x, y)``: :math:`x^{y}` You may set the file delimiters using the keyword arguments ``separator`` and ``col_separator``, respectively. ``separator`` is the delimiter between the coordinates of the control points. It could be comma ``1, 2, 3`` or space ``1 2 3`` or something else. ``col_separator`` is the delimiter between the control points and is only valid when ``two_dimensional`` is ``True``. Assuming that ``separator`` is set to space, then ``col_operator`` could be semi-colon ``1 2 3; 4 5 6`` or pipe ``1 2 3| 4 5 6`` or comma ``1 2 3, 4 5 6`` or something else. The defaults for ``separator`` and ``col_separator`` are *comma (,)* and *semi-colon (;)*, respectively. The following code examples illustrate the usage of the keyword arguments discussed above. .. code-block:: python :linenos: # Import curve control points from a text file delimited with space curve_ctrlpts = exchange.import_txt(file_name="control_points.txt", separator=" ") # Import surface control points from a text file (2-dimensional file) w/ space and comma delimiters surf_ctrlpts, size_u, size_v = exchange.import_txt(file_name="control_points.txt", two_dimensional=True, separator=" ", col_separator=",") Please note that this function does not check whether the user set delimiters to the same value or not. :param file_name: file name of the text file :type file_name: str :param two_dimensional: type of the text file :type two_dimensional: bool :return: list of control points, if two_dimensional, then also returns size in u- and v-directions :rtype: list :raises GeomdlException: an error occurred reading the file """ # Read file content = exch.read_file(file_name) # Are we using a Jinja2 template? j2tmpl = kwargs.get('jinja2', False) if j2tmpl: content = exch.process_template(content) # File delimiters col_sep = kwargs.get('col_separator', ";") sep = kwargs.get('separator', ",") return exch.import_text_data(content, sep, col_sep, two_dimensional)
[ "def", "import_txt", "(", "file_name", ",", "two_dimensional", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Read file", "content", "=", "exch", ".", "read_file", "(", "file_name", ")", "# Are we using a Jinja2 template?", "j2tmpl", "=", "kwargs", ".", "get", "(", "'jinja2'", ",", "False", ")", "if", "j2tmpl", ":", "content", "=", "exch", ".", "process_template", "(", "content", ")", "# File delimiters", "col_sep", "=", "kwargs", ".", "get", "(", "'col_separator'", ",", "\";\"", ")", "sep", "=", "kwargs", ".", "get", "(", "'separator'", ",", "\",\"", ")", "return", "exch", ".", "import_text_data", "(", "content", ",", "sep", ",", "col_sep", ",", "two_dimensional", ")" ]
Reads control points from a text file and generates a 1-dimensional list of control points. The following code examples illustrate importing different types of text files for curves and surfaces: .. code-block:: python :linenos: # Import curve control points from a text file curve_ctrlpts = exchange.import_txt(file_name="control_points.txt") # Import surface control points from a text file (1-dimensional file) surf_ctrlpts = exchange.import_txt(file_name="control_points.txt") # Import surface control points from a text file (2-dimensional file) surf_ctrlpts, size_u, size_v = exchange.import_txt(file_name="control_points.txt", two_dimensional=True) If argument ``jinja2=True`` is set, then the input file is processed as a `Jinja2 <http://jinja.pocoo.org/>`_ template. You can also use the following convenience template functions which correspond to the given mathematical equations: * ``sqrt(x)``: :math:`\\sqrt{x}` * ``cubert(x)``: :math:`\\sqrt[3]{x}` * ``pow(x, y)``: :math:`x^{y}` You may set the file delimiters using the keyword arguments ``separator`` and ``col_separator``, respectively. ``separator`` is the delimiter between the coordinates of the control points. It could be comma ``1, 2, 3`` or space ``1 2 3`` or something else. ``col_separator`` is the delimiter between the control points and is only valid when ``two_dimensional`` is ``True``. Assuming that ``separator`` is set to space, then ``col_operator`` could be semi-colon ``1 2 3; 4 5 6`` or pipe ``1 2 3| 4 5 6`` or comma ``1 2 3, 4 5 6`` or something else. The defaults for ``separator`` and ``col_separator`` are *comma (,)* and *semi-colon (;)*, respectively. The following code examples illustrate the usage of the keyword arguments discussed above. .. code-block:: python :linenos: # Import curve control points from a text file delimited with space curve_ctrlpts = exchange.import_txt(file_name="control_points.txt", separator=" ") # Import surface control points from a text file (2-dimensional file) w/ space and comma delimiters surf_ctrlpts, size_u, size_v = exchange.import_txt(file_name="control_points.txt", two_dimensional=True, separator=" ", col_separator=",") Please note that this function does not check whether the user set delimiters to the same value or not. :param file_name: file name of the text file :type file_name: str :param two_dimensional: type of the text file :type two_dimensional: bool :return: list of control points, if two_dimensional, then also returns size in u- and v-directions :rtype: list :raises GeomdlException: an error occurred reading the file
[ "Reads", "control", "points", "from", "a", "text", "file", "and", "generates", "a", "1", "-", "dimensional", "list", "of", "control", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L21-L89
230,315
orbingol/NURBS-Python
geomdl/exchange.py
export_txt
def export_txt(obj, file_name, two_dimensional=False, **kwargs): """ Exports control points as a text file. For curves the output is always a list of control points. For surfaces, it is possible to generate a 2-dimensional control point output file using ``two_dimensional``. Please see :py:func:`.exchange.import_txt()` for detailed description of the keyword arguments. :param obj: a spline geometry object :type obj: abstract.SplineGeometry :param file_name: file name of the text file to be saved :type file_name: str :param two_dimensional: type of the text file (only works for Surface objects) :type two_dimensional: bool :raises GeomdlException: an error occurred writing the file """ # Check if the user has set any control points if obj.ctrlpts is None or len(obj.ctrlpts) == 0: raise exch.GeomdlException("There are no control points to save!") # Check the usage of two_dimensional flag if obj.pdimension == 1 and two_dimensional: # Silently ignore two_dimensional flag two_dimensional = False # File delimiters col_sep = kwargs.get('col_separator', ";") sep = kwargs.get('separator', ",") content = exch.export_text_data(obj, sep, col_sep, two_dimensional) return exch.write_file(file_name, content)
python
def export_txt(obj, file_name, two_dimensional=False, **kwargs): """ Exports control points as a text file. For curves the output is always a list of control points. For surfaces, it is possible to generate a 2-dimensional control point output file using ``two_dimensional``. Please see :py:func:`.exchange.import_txt()` for detailed description of the keyword arguments. :param obj: a spline geometry object :type obj: abstract.SplineGeometry :param file_name: file name of the text file to be saved :type file_name: str :param two_dimensional: type of the text file (only works for Surface objects) :type two_dimensional: bool :raises GeomdlException: an error occurred writing the file """ # Check if the user has set any control points if obj.ctrlpts is None or len(obj.ctrlpts) == 0: raise exch.GeomdlException("There are no control points to save!") # Check the usage of two_dimensional flag if obj.pdimension == 1 and two_dimensional: # Silently ignore two_dimensional flag two_dimensional = False # File delimiters col_sep = kwargs.get('col_separator', ";") sep = kwargs.get('separator', ",") content = exch.export_text_data(obj, sep, col_sep, two_dimensional) return exch.write_file(file_name, content)
[ "def", "export_txt", "(", "obj", ",", "file_name", ",", "two_dimensional", "=", "False", ",", "*", "*", "kwargs", ")", ":", "# Check if the user has set any control points", "if", "obj", ".", "ctrlpts", "is", "None", "or", "len", "(", "obj", ".", "ctrlpts", ")", "==", "0", ":", "raise", "exch", ".", "GeomdlException", "(", "\"There are no control points to save!\"", ")", "# Check the usage of two_dimensional flag", "if", "obj", ".", "pdimension", "==", "1", "and", "two_dimensional", ":", "# Silently ignore two_dimensional flag", "two_dimensional", "=", "False", "# File delimiters", "col_sep", "=", "kwargs", ".", "get", "(", "'col_separator'", ",", "\";\"", ")", "sep", "=", "kwargs", ".", "get", "(", "'separator'", ",", "\",\"", ")", "content", "=", "exch", ".", "export_text_data", "(", "obj", ",", "sep", ",", "col_sep", ",", "two_dimensional", ")", "return", "exch", ".", "write_file", "(", "file_name", ",", "content", ")" ]
Exports control points as a text file. For curves the output is always a list of control points. For surfaces, it is possible to generate a 2-dimensional control point output file using ``two_dimensional``. Please see :py:func:`.exchange.import_txt()` for detailed description of the keyword arguments. :param obj: a spline geometry object :type obj: abstract.SplineGeometry :param file_name: file name of the text file to be saved :type file_name: str :param two_dimensional: type of the text file (only works for Surface objects) :type two_dimensional: bool :raises GeomdlException: an error occurred writing the file
[ "Exports", "control", "points", "as", "a", "text", "file", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L93-L123
230,316
orbingol/NURBS-Python
geomdl/exchange.py
import_csv
def import_csv(file_name, **kwargs): """ Reads control points from a CSV file and generates a 1-dimensional list of control points. It is possible to use a different value separator via ``separator`` keyword argument. The following code segment illustrates the usage of ``separator`` keyword argument. .. code-block:: python :linenos: # By default, import_csv uses 'comma' as the value separator ctrlpts = exchange.import_csv("control_points.csv") # Alternatively, it is possible to import a file containing tab-separated values ctrlpts = exchange.import_csv("control_points.csv", separator="\\t") The only difference of this function from :py:func:`.exchange.import_txt()` is skipping the first line of the input file which generally contains the column headings. :param file_name: file name of the text file :type file_name: str :return: list of control points :rtype: list :raises GeomdlException: an error occurred reading the file """ # File delimiters sep = kwargs.get('separator', ",") content = exch.read_file(file_name, skip_lines=1) return exch.import_text_data(content, sep)
python
def import_csv(file_name, **kwargs): """ Reads control points from a CSV file and generates a 1-dimensional list of control points. It is possible to use a different value separator via ``separator`` keyword argument. The following code segment illustrates the usage of ``separator`` keyword argument. .. code-block:: python :linenos: # By default, import_csv uses 'comma' as the value separator ctrlpts = exchange.import_csv("control_points.csv") # Alternatively, it is possible to import a file containing tab-separated values ctrlpts = exchange.import_csv("control_points.csv", separator="\\t") The only difference of this function from :py:func:`.exchange.import_txt()` is skipping the first line of the input file which generally contains the column headings. :param file_name: file name of the text file :type file_name: str :return: list of control points :rtype: list :raises GeomdlException: an error occurred reading the file """ # File delimiters sep = kwargs.get('separator', ",") content = exch.read_file(file_name, skip_lines=1) return exch.import_text_data(content, sep)
[ "def", "import_csv", "(", "file_name", ",", "*", "*", "kwargs", ")", ":", "# File delimiters", "sep", "=", "kwargs", ".", "get", "(", "'separator'", ",", "\",\"", ")", "content", "=", "exch", ".", "read_file", "(", "file_name", ",", "skip_lines", "=", "1", ")", "return", "exch", ".", "import_text_data", "(", "content", ",", "sep", ")" ]
Reads control points from a CSV file and generates a 1-dimensional list of control points. It is possible to use a different value separator via ``separator`` keyword argument. The following code segment illustrates the usage of ``separator`` keyword argument. .. code-block:: python :linenos: # By default, import_csv uses 'comma' as the value separator ctrlpts = exchange.import_csv("control_points.csv") # Alternatively, it is possible to import a file containing tab-separated values ctrlpts = exchange.import_csv("control_points.csv", separator="\\t") The only difference of this function from :py:func:`.exchange.import_txt()` is skipping the first line of the input file which generally contains the column headings. :param file_name: file name of the text file :type file_name: str :return: list of control points :rtype: list :raises GeomdlException: an error occurred reading the file
[ "Reads", "control", "points", "from", "a", "CSV", "file", "and", "generates", "a", "1", "-", "dimensional", "list", "of", "control", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L127-L155
230,317
orbingol/NURBS-Python
geomdl/exchange.py
export_csv
def export_csv(obj, file_name, point_type='evalpts', **kwargs): """ Exports control points or evaluated points as a CSV file. :param obj: a spline geometry object :type obj: abstract.SplineGeometry :param file_name: output file name :type file_name: str :param point_type: ``ctrlpts`` for control points or ``evalpts`` for evaluated points :type point_type: str :raises GeomdlException: an error occurred writing the file """ if not 0 < obj.pdimension < 3: raise exch.GeomdlException("Input object should be a curve or a surface") # Pick correct points from the object if point_type == 'ctrlpts': points = obj.ctrlptsw if obj.rational else obj.ctrlpts elif point_type == 'evalpts': points = obj.evalpts else: raise exch.GeomdlException("Please choose a valid point type option. Possible types: ctrlpts, evalpts") # Prepare CSV header dim = len(points[0]) line = "dim " for i in range(dim-1): line += str(i + 1) + ", dim " line += str(dim) + "\n" # Prepare values for pt in points: line += ",".join([str(p) for p in pt]) + "\n" # Write to file return exch.write_file(file_name, line)
python
def export_csv(obj, file_name, point_type='evalpts', **kwargs): """ Exports control points or evaluated points as a CSV file. :param obj: a spline geometry object :type obj: abstract.SplineGeometry :param file_name: output file name :type file_name: str :param point_type: ``ctrlpts`` for control points or ``evalpts`` for evaluated points :type point_type: str :raises GeomdlException: an error occurred writing the file """ if not 0 < obj.pdimension < 3: raise exch.GeomdlException("Input object should be a curve or a surface") # Pick correct points from the object if point_type == 'ctrlpts': points = obj.ctrlptsw if obj.rational else obj.ctrlpts elif point_type == 'evalpts': points = obj.evalpts else: raise exch.GeomdlException("Please choose a valid point type option. Possible types: ctrlpts, evalpts") # Prepare CSV header dim = len(points[0]) line = "dim " for i in range(dim-1): line += str(i + 1) + ", dim " line += str(dim) + "\n" # Prepare values for pt in points: line += ",".join([str(p) for p in pt]) + "\n" # Write to file return exch.write_file(file_name, line)
[ "def", "export_csv", "(", "obj", ",", "file_name", ",", "point_type", "=", "'evalpts'", ",", "*", "*", "kwargs", ")", ":", "if", "not", "0", "<", "obj", ".", "pdimension", "<", "3", ":", "raise", "exch", ".", "GeomdlException", "(", "\"Input object should be a curve or a surface\"", ")", "# Pick correct points from the object", "if", "point_type", "==", "'ctrlpts'", ":", "points", "=", "obj", ".", "ctrlptsw", "if", "obj", ".", "rational", "else", "obj", ".", "ctrlpts", "elif", "point_type", "==", "'evalpts'", ":", "points", "=", "obj", ".", "evalpts", "else", ":", "raise", "exch", ".", "GeomdlException", "(", "\"Please choose a valid point type option. Possible types: ctrlpts, evalpts\"", ")", "# Prepare CSV header", "dim", "=", "len", "(", "points", "[", "0", "]", ")", "line", "=", "\"dim \"", "for", "i", "in", "range", "(", "dim", "-", "1", ")", ":", "line", "+=", "str", "(", "i", "+", "1", ")", "+", "\", dim \"", "line", "+=", "str", "(", "dim", ")", "+", "\"\\n\"", "# Prepare values", "for", "pt", "in", "points", ":", "line", "+=", "\",\"", ".", "join", "(", "[", "str", "(", "p", ")", "for", "p", "in", "pt", "]", ")", "+", "\"\\n\"", "# Write to file", "return", "exch", ".", "write_file", "(", "file_name", ",", "line", ")" ]
Exports control points or evaluated points as a CSV file. :param obj: a spline geometry object :type obj: abstract.SplineGeometry :param file_name: output file name :type file_name: str :param point_type: ``ctrlpts`` for control points or ``evalpts`` for evaluated points :type point_type: str :raises GeomdlException: an error occurred writing the file
[ "Exports", "control", "points", "or", "evaluated", "points", "as", "a", "CSV", "file", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L159-L193
230,318
orbingol/NURBS-Python
geomdl/exchange.py
import_cfg
def import_cfg(file_name, **kwargs): """ Imports curves and surfaces from files in libconfig format. .. note:: Requires `libconf <https://pypi.org/project/libconf/>`_ package. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spline geometries :rtype: list :raises GeomdlException: an error occurred writing the file """ def callback(data): return libconf.loads(data) # Check if it is possible to import 'libconf' try: import libconf except ImportError: raise exch.GeomdlException("Please install 'libconf' package to use libconfig format: pip install libconf") # Get keyword arguments delta = kwargs.get('delta', -1.0) use_template = kwargs.get('jinja2', False) # Read file file_src = exch.read_file(file_name) # Import data return exch.import_dict_str(file_src=file_src, delta=delta, callback=callback, tmpl=use_template)
python
def import_cfg(file_name, **kwargs): """ Imports curves and surfaces from files in libconfig format. .. note:: Requires `libconf <https://pypi.org/project/libconf/>`_ package. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spline geometries :rtype: list :raises GeomdlException: an error occurred writing the file """ def callback(data): return libconf.loads(data) # Check if it is possible to import 'libconf' try: import libconf except ImportError: raise exch.GeomdlException("Please install 'libconf' package to use libconfig format: pip install libconf") # Get keyword arguments delta = kwargs.get('delta', -1.0) use_template = kwargs.get('jinja2', False) # Read file file_src = exch.read_file(file_name) # Import data return exch.import_dict_str(file_src=file_src, delta=delta, callback=callback, tmpl=use_template)
[ "def", "import_cfg", "(", "file_name", ",", "*", "*", "kwargs", ")", ":", "def", "callback", "(", "data", ")", ":", "return", "libconf", ".", "loads", "(", "data", ")", "# Check if it is possible to import 'libconf'", "try", ":", "import", "libconf", "except", "ImportError", ":", "raise", "exch", ".", "GeomdlException", "(", "\"Please install 'libconf' package to use libconfig format: pip install libconf\"", ")", "# Get keyword arguments", "delta", "=", "kwargs", ".", "get", "(", "'delta'", ",", "-", "1.0", ")", "use_template", "=", "kwargs", ".", "get", "(", "'jinja2'", ",", "False", ")", "# Read file", "file_src", "=", "exch", ".", "read_file", "(", "file_name", ")", "# Import data", "return", "exch", ".", "import_dict_str", "(", "file_src", "=", "file_src", ",", "delta", "=", "delta", ",", "callback", "=", "callback", ",", "tmpl", "=", "use_template", ")" ]
Imports curves and surfaces from files in libconfig format. .. note:: Requires `libconf <https://pypi.org/project/libconf/>`_ package. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spline geometries :rtype: list :raises GeomdlException: an error occurred writing the file
[ "Imports", "curves", "and", "surfaces", "from", "files", "in", "libconfig", "format", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L197-L229
230,319
orbingol/NURBS-Python
geomdl/exchange.py
export_cfg
def export_cfg(obj, file_name): """ Exports curves and surfaces in libconfig format. .. note:: Requires `libconf <https://pypi.org/project/libconf/>`_ package. Libconfig format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file """ def callback(data): return libconf.dumps(data) # Check if it is possible to import 'libconf' try: import libconf except ImportError: raise exch.GeomdlException("Please install 'libconf' package to use libconfig format: pip install libconf") # Export data exported_data = exch.export_dict_str(obj=obj, callback=callback) # Write to file return exch.write_file(file_name, exported_data)
python
def export_cfg(obj, file_name): """ Exports curves and surfaces in libconfig format. .. note:: Requires `libconf <https://pypi.org/project/libconf/>`_ package. Libconfig format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file """ def callback(data): return libconf.dumps(data) # Check if it is possible to import 'libconf' try: import libconf except ImportError: raise exch.GeomdlException("Please install 'libconf' package to use libconfig format: pip install libconf") # Export data exported_data = exch.export_dict_str(obj=obj, callback=callback) # Write to file return exch.write_file(file_name, exported_data)
[ "def", "export_cfg", "(", "obj", ",", "file_name", ")", ":", "def", "callback", "(", "data", ")", ":", "return", "libconf", ".", "dumps", "(", "data", ")", "# Check if it is possible to import 'libconf'", "try", ":", "import", "libconf", "except", "ImportError", ":", "raise", "exch", ".", "GeomdlException", "(", "\"Please install 'libconf' package to use libconfig format: pip install libconf\"", ")", "# Export data", "exported_data", "=", "exch", ".", "export_dict_str", "(", "obj", "=", "obj", ",", "callback", "=", "callback", ")", "# Write to file", "return", "exch", ".", "write_file", "(", "file_name", ",", "exported_data", ")" ]
Exports curves and surfaces in libconfig format. .. note:: Requires `libconf <https://pypi.org/project/libconf/>`_ package. Libconfig format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file
[ "Exports", "curves", "and", "surfaces", "in", "libconfig", "format", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L233-L262
230,320
orbingol/NURBS-Python
geomdl/exchange.py
import_yaml
def import_yaml(file_name, **kwargs): """ Imports curves and surfaces from files in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spline geometries :rtype: list :raises GeomdlException: an error occurred reading the file """ def callback(data): yaml = YAML() return yaml.load(data) # Check if it is possible to import 'ruamel.yaml' try: from ruamel.yaml import YAML except ImportError: raise exch.GeomdlException("Please install 'ruamel.yaml' package to use YAML format: pip install ruamel.yaml") # Get keyword arguments delta = kwargs.get('delta', -1.0) use_template = kwargs.get('jinja2', False) # Read file file_src = exch.read_file(file_name) # Import data return exch.import_dict_str(file_src=file_src, delta=delta, callback=callback, tmpl=use_template)
python
def import_yaml(file_name, **kwargs): """ Imports curves and surfaces from files in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spline geometries :rtype: list :raises GeomdlException: an error occurred reading the file """ def callback(data): yaml = YAML() return yaml.load(data) # Check if it is possible to import 'ruamel.yaml' try: from ruamel.yaml import YAML except ImportError: raise exch.GeomdlException("Please install 'ruamel.yaml' package to use YAML format: pip install ruamel.yaml") # Get keyword arguments delta = kwargs.get('delta', -1.0) use_template = kwargs.get('jinja2', False) # Read file file_src = exch.read_file(file_name) # Import data return exch.import_dict_str(file_src=file_src, delta=delta, callback=callback, tmpl=use_template)
[ "def", "import_yaml", "(", "file_name", ",", "*", "*", "kwargs", ")", ":", "def", "callback", "(", "data", ")", ":", "yaml", "=", "YAML", "(", ")", "return", "yaml", ".", "load", "(", "data", ")", "# Check if it is possible to import 'ruamel.yaml'", "try", ":", "from", "ruamel", ".", "yaml", "import", "YAML", "except", "ImportError", ":", "raise", "exch", ".", "GeomdlException", "(", "\"Please install 'ruamel.yaml' package to use YAML format: pip install ruamel.yaml\"", ")", "# Get keyword arguments", "delta", "=", "kwargs", ".", "get", "(", "'delta'", ",", "-", "1.0", ")", "use_template", "=", "kwargs", ".", "get", "(", "'jinja2'", ",", "False", ")", "# Read file", "file_src", "=", "exch", ".", "read_file", "(", "file_name", ")", "# Import data", "return", "exch", ".", "import_dict_str", "(", "file_src", "=", "file_src", ",", "delta", "=", "delta", ",", "callback", "=", "callback", ",", "tmpl", "=", "use_template", ")" ]
Imports curves and surfaces from files in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spline geometries :rtype: list :raises GeomdlException: an error occurred reading the file
[ "Imports", "curves", "and", "surfaces", "from", "files", "in", "YAML", "format", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L266-L299
230,321
orbingol/NURBS-Python
geomdl/exchange.py
export_yaml
def export_yaml(obj, file_name): """ Exports curves and surfaces in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file """ def callback(data): # Ref: https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string stream = StringIO() yaml = YAML() yaml.dump(data, stream) return stream.getvalue() # Check if it is possible to import 'ruamel.yaml' try: from ruamel.yaml import YAML except ImportError: raise exch.GeomdlException("Please install 'ruamel.yaml' package to use YAML format: pip install ruamel.yaml") # Export data exported_data = exch.export_dict_str(obj=obj, callback=callback) # Write to file return exch.write_file(file_name, exported_data)
python
def export_yaml(obj, file_name): """ Exports curves and surfaces in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file """ def callback(data): # Ref: https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string stream = StringIO() yaml = YAML() yaml.dump(data, stream) return stream.getvalue() # Check if it is possible to import 'ruamel.yaml' try: from ruamel.yaml import YAML except ImportError: raise exch.GeomdlException("Please install 'ruamel.yaml' package to use YAML format: pip install ruamel.yaml") # Export data exported_data = exch.export_dict_str(obj=obj, callback=callback) # Write to file return exch.write_file(file_name, exported_data)
[ "def", "export_yaml", "(", "obj", ",", "file_name", ")", ":", "def", "callback", "(", "data", ")", ":", "# Ref: https://yaml.readthedocs.io/en/latest/example.html#output-of-dump-as-a-string", "stream", "=", "StringIO", "(", ")", "yaml", "=", "YAML", "(", ")", "yaml", ".", "dump", "(", "data", ",", "stream", ")", "return", "stream", ".", "getvalue", "(", ")", "# Check if it is possible to import 'ruamel.yaml'", "try", ":", "from", "ruamel", ".", "yaml", "import", "YAML", "except", "ImportError", ":", "raise", "exch", ".", "GeomdlException", "(", "\"Please install 'ruamel.yaml' package to use YAML format: pip install ruamel.yaml\"", ")", "# Export data", "exported_data", "=", "exch", ".", "export_dict_str", "(", "obj", "=", "obj", ",", "callback", "=", "callback", ")", "# Write to file", "return", "exch", ".", "write_file", "(", "file_name", ",", "exported_data", ")" ]
Exports curves and surfaces in YAML format. .. note:: Requires `ruamel.yaml <https://pypi.org/project/ruamel.yaml/>`_ package. YAML format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file
[ "Exports", "curves", "and", "surfaces", "in", "YAML", "format", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L303-L336
230,322
orbingol/NURBS-Python
geomdl/exchange.py
import_json
def import_json(file_name, **kwargs): """ Imports curves and surfaces from files in JSON format. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spline geometries :rtype: list :raises GeomdlException: an error occurred reading the file """ def callback(data): return json.loads(data) # Get keyword arguments delta = kwargs.get('delta', -1.0) use_template = kwargs.get('jinja2', False) # Read file file_src = exch.read_file(file_name) # Import data return exch.import_dict_str(file_src=file_src, delta=delta, callback=callback, tmpl=use_template)
python
def import_json(file_name, **kwargs): """ Imports curves and surfaces from files in JSON format. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spline geometries :rtype: list :raises GeomdlException: an error occurred reading the file """ def callback(data): return json.loads(data) # Get keyword arguments delta = kwargs.get('delta', -1.0) use_template = kwargs.get('jinja2', False) # Read file file_src = exch.read_file(file_name) # Import data return exch.import_dict_str(file_src=file_src, delta=delta, callback=callback, tmpl=use_template)
[ "def", "import_json", "(", "file_name", ",", "*", "*", "kwargs", ")", ":", "def", "callback", "(", "data", ")", ":", "return", "json", ".", "loads", "(", "data", ")", "# Get keyword arguments", "delta", "=", "kwargs", ".", "get", "(", "'delta'", ",", "-", "1.0", ")", "use_template", "=", "kwargs", ".", "get", "(", "'jinja2'", ",", "False", ")", "# Read file", "file_src", "=", "exch", ".", "read_file", "(", "file_name", ")", "# Import data", "return", "exch", ".", "import_dict_str", "(", "file_src", "=", "file_src", ",", "delta", "=", "delta", ",", "callback", "=", "callback", ",", "tmpl", "=", "use_template", ")" ]
Imports curves and surfaces from files in JSON format. Use ``jinja2=True`` to activate Jinja2 template processing. Please refer to the documentation for details. :param file_name: name of the input file :type file_name: str :return: a list of rational spline geometries :rtype: list :raises GeomdlException: an error occurred reading the file
[ "Imports", "curves", "and", "surfaces", "from", "files", "in", "JSON", "format", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L340-L362
230,323
orbingol/NURBS-Python
geomdl/exchange.py
export_json
def export_json(obj, file_name): """ Exports curves and surfaces in JSON format. JSON format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file """ def callback(data): return json.dumps(data, indent=4) # Export data exported_data = exch.export_dict_str(obj=obj, callback=callback) # Write to file return exch.write_file(file_name, exported_data)
python
def export_json(obj, file_name): """ Exports curves and surfaces in JSON format. JSON format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file """ def callback(data): return json.dumps(data, indent=4) # Export data exported_data = exch.export_dict_str(obj=obj, callback=callback) # Write to file return exch.write_file(file_name, exported_data)
[ "def", "export_json", "(", "obj", ",", "file_name", ")", ":", "def", "callback", "(", "data", ")", ":", "return", "json", ".", "dumps", "(", "data", ",", "indent", "=", "4", ")", "# Export data", "exported_data", "=", "exch", ".", "export_dict_str", "(", "obj", "=", "obj", ",", "callback", "=", "callback", ")", "# Write to file", "return", "exch", ".", "write_file", "(", "file_name", ",", "exported_data", ")" ]
Exports curves and surfaces in JSON format. JSON format is also used by the `geomdl command-line application <https://github.com/orbingol/geomdl-cli>`_ as a way to input shape data from the command line. :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: name of the output file :type file_name: str :raises GeomdlException: an error occurred writing the file
[ "Exports", "curves", "and", "surfaces", "in", "JSON", "format", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L366-L385
230,324
orbingol/NURBS-Python
geomdl/exchange.py
import_obj
def import_obj(file_name, **kwargs): """ Reads .obj files and generates faces. Keyword Arguments: * ``callback``: reference to the function that processes the faces for customized output The structure of the callback function is shown below: .. code-block:: python def my_callback_function(face_list): # "face_list" will be a list of elements.Face class instances # The function should return a list return list() :param file_name: file name :type file_name: str :return: output of the callback function (default is a list of faces) :rtype: list """ def default_callback(face_list): return face_list # Keyword arguments callback_func = kwargs.get('callback', default_callback) # Read and process the input file content = exch.read_file(file_name) content_arr = content.split("\n") # Initialize variables on_face = False vertices = [] triangles = [] faces = [] # Index values vert_idx = 1 tri_idx = 1 face_idx = 1 # Loop through the data for carr in content_arr: carr = carr.strip() data = carr.split(" ") data = [d.strip() for d in data] if data[0] == "v": if on_face: on_face = not on_face face = elements.Face(*triangles, id=face_idx) faces.append(face) face_idx += 1 vertices[:] = [] triangles[:] = [] vert_idx = 1 tri_idx = 1 vertex = elements.Vertex(*data[1:], id=vert_idx) vertices.append(vertex) vert_idx += 1 if data[0] == "f": on_face = True triangle = elements.Triangle(*[vertices[int(fidx) - 1] for fidx in data[1:]], id=tri_idx) triangles.append(triangle) tri_idx += 1 # Process he final face if triangles: face = elements.Face(*triangles, id=face_idx) faces.append(face) # Return the output of the callback function return callback_func(faces)
python
def import_obj(file_name, **kwargs): """ Reads .obj files and generates faces. Keyword Arguments: * ``callback``: reference to the function that processes the faces for customized output The structure of the callback function is shown below: .. code-block:: python def my_callback_function(face_list): # "face_list" will be a list of elements.Face class instances # The function should return a list return list() :param file_name: file name :type file_name: str :return: output of the callback function (default is a list of faces) :rtype: list """ def default_callback(face_list): return face_list # Keyword arguments callback_func = kwargs.get('callback', default_callback) # Read and process the input file content = exch.read_file(file_name) content_arr = content.split("\n") # Initialize variables on_face = False vertices = [] triangles = [] faces = [] # Index values vert_idx = 1 tri_idx = 1 face_idx = 1 # Loop through the data for carr in content_arr: carr = carr.strip() data = carr.split(" ") data = [d.strip() for d in data] if data[0] == "v": if on_face: on_face = not on_face face = elements.Face(*triangles, id=face_idx) faces.append(face) face_idx += 1 vertices[:] = [] triangles[:] = [] vert_idx = 1 tri_idx = 1 vertex = elements.Vertex(*data[1:], id=vert_idx) vertices.append(vertex) vert_idx += 1 if data[0] == "f": on_face = True triangle = elements.Triangle(*[vertices[int(fidx) - 1] for fidx in data[1:]], id=tri_idx) triangles.append(triangle) tri_idx += 1 # Process he final face if triangles: face = elements.Face(*triangles, id=face_idx) faces.append(face) # Return the output of the callback function return callback_func(faces)
[ "def", "import_obj", "(", "file_name", ",", "*", "*", "kwargs", ")", ":", "def", "default_callback", "(", "face_list", ")", ":", "return", "face_list", "# Keyword arguments", "callback_func", "=", "kwargs", ".", "get", "(", "'callback'", ",", "default_callback", ")", "# Read and process the input file", "content", "=", "exch", ".", "read_file", "(", "file_name", ")", "content_arr", "=", "content", ".", "split", "(", "\"\\n\"", ")", "# Initialize variables", "on_face", "=", "False", "vertices", "=", "[", "]", "triangles", "=", "[", "]", "faces", "=", "[", "]", "# Index values", "vert_idx", "=", "1", "tri_idx", "=", "1", "face_idx", "=", "1", "# Loop through the data", "for", "carr", "in", "content_arr", ":", "carr", "=", "carr", ".", "strip", "(", ")", "data", "=", "carr", ".", "split", "(", "\" \"", ")", "data", "=", "[", "d", ".", "strip", "(", ")", "for", "d", "in", "data", "]", "if", "data", "[", "0", "]", "==", "\"v\"", ":", "if", "on_face", ":", "on_face", "=", "not", "on_face", "face", "=", "elements", ".", "Face", "(", "*", "triangles", ",", "id", "=", "face_idx", ")", "faces", ".", "append", "(", "face", ")", "face_idx", "+=", "1", "vertices", "[", ":", "]", "=", "[", "]", "triangles", "[", ":", "]", "=", "[", "]", "vert_idx", "=", "1", "tri_idx", "=", "1", "vertex", "=", "elements", ".", "Vertex", "(", "*", "data", "[", "1", ":", "]", ",", "id", "=", "vert_idx", ")", "vertices", ".", "append", "(", "vertex", ")", "vert_idx", "+=", "1", "if", "data", "[", "0", "]", "==", "\"f\"", ":", "on_face", "=", "True", "triangle", "=", "elements", ".", "Triangle", "(", "*", "[", "vertices", "[", "int", "(", "fidx", ")", "-", "1", "]", "for", "fidx", "in", "data", "[", "1", ":", "]", "]", ",", "id", "=", "tri_idx", ")", "triangles", ".", "append", "(", "triangle", ")", "tri_idx", "+=", "1", "# Process he final face", "if", "triangles", ":", "face", "=", "elements", ".", "Face", "(", "*", "triangles", ",", "id", "=", "face_idx", ")", "faces", ".", "append", "(", "face", ")", "# Return the output of the callback function", "return", "callback_func", "(", "faces", ")" ]
Reads .obj files and generates faces. Keyword Arguments: * ``callback``: reference to the function that processes the faces for customized output The structure of the callback function is shown below: .. code-block:: python def my_callback_function(face_list): # "face_list" will be a list of elements.Face class instances # The function should return a list return list() :param file_name: file name :type file_name: str :return: output of the callback function (default is a list of faces) :rtype: list
[ "Reads", ".", "obj", "files", "and", "generates", "faces", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange.py#L389-L460
230,325
orbingol/NURBS-Python
geomdl/multi.py
select_color
def select_color(cpcolor, evalcolor, idx=0): """ Selects item color for plotting. :param cpcolor: color for control points grid item :type cpcolor: str, list, tuple :param evalcolor: color for evaluated points grid item :type evalcolor: str, list, tuple :param idx: index of the current geometry object :type idx: int :return: a list of color values :rtype: list """ # Random colors by default color = utilities.color_generator() # Constant color for control points grid if isinstance(cpcolor, str): color[0] = cpcolor # User-defined color for control points grid if isinstance(cpcolor, (list, tuple)): color[0] = cpcolor[idx] # Constant color for evaluated points grid if isinstance(evalcolor, str): color[1] = evalcolor # User-defined color for evaluated points grid if isinstance(evalcolor, (list, tuple)): color[1] = evalcolor[idx] return color
python
def select_color(cpcolor, evalcolor, idx=0): """ Selects item color for plotting. :param cpcolor: color for control points grid item :type cpcolor: str, list, tuple :param evalcolor: color for evaluated points grid item :type evalcolor: str, list, tuple :param idx: index of the current geometry object :type idx: int :return: a list of color values :rtype: list """ # Random colors by default color = utilities.color_generator() # Constant color for control points grid if isinstance(cpcolor, str): color[0] = cpcolor # User-defined color for control points grid if isinstance(cpcolor, (list, tuple)): color[0] = cpcolor[idx] # Constant color for evaluated points grid if isinstance(evalcolor, str): color[1] = evalcolor # User-defined color for evaluated points grid if isinstance(evalcolor, (list, tuple)): color[1] = evalcolor[idx] return color
[ "def", "select_color", "(", "cpcolor", ",", "evalcolor", ",", "idx", "=", "0", ")", ":", "# Random colors by default", "color", "=", "utilities", ".", "color_generator", "(", ")", "# Constant color for control points grid", "if", "isinstance", "(", "cpcolor", ",", "str", ")", ":", "color", "[", "0", "]", "=", "cpcolor", "# User-defined color for control points grid", "if", "isinstance", "(", "cpcolor", ",", "(", "list", ",", "tuple", ")", ")", ":", "color", "[", "0", "]", "=", "cpcolor", "[", "idx", "]", "# Constant color for evaluated points grid", "if", "isinstance", "(", "evalcolor", ",", "str", ")", ":", "color", "[", "1", "]", "=", "evalcolor", "# User-defined color for evaluated points grid", "if", "isinstance", "(", "evalcolor", ",", "(", "list", ",", "tuple", ")", ")", ":", "color", "[", "1", "]", "=", "evalcolor", "[", "idx", "]", "return", "color" ]
Selects item color for plotting. :param cpcolor: color for control points grid item :type cpcolor: str, list, tuple :param evalcolor: color for evaluated points grid item :type evalcolor: str, list, tuple :param idx: index of the current geometry object :type idx: int :return: a list of color values :rtype: list
[ "Selects", "item", "color", "for", "plotting", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/multi.py#L1080-L1111
230,326
orbingol/NURBS-Python
geomdl/multi.py
process_tessellate
def process_tessellate(elem, update_delta, delta, **kwargs): """ Tessellates surfaces. .. note:: Helper function required for ``multiprocessing`` :param elem: surface :type elem: abstract.Surface :param update_delta: flag to control evaluation delta updates :type update_delta: bool :param delta: evaluation delta :type delta: list, tuple :return: updated surface :rtype: abstract.Surface """ if update_delta: elem.delta = delta elem.evaluate() elem.tessellate(**kwargs) return elem
python
def process_tessellate(elem, update_delta, delta, **kwargs): """ Tessellates surfaces. .. note:: Helper function required for ``multiprocessing`` :param elem: surface :type elem: abstract.Surface :param update_delta: flag to control evaluation delta updates :type update_delta: bool :param delta: evaluation delta :type delta: list, tuple :return: updated surface :rtype: abstract.Surface """ if update_delta: elem.delta = delta elem.evaluate() elem.tessellate(**kwargs) return elem
[ "def", "process_tessellate", "(", "elem", ",", "update_delta", ",", "delta", ",", "*", "*", "kwargs", ")", ":", "if", "update_delta", ":", "elem", ".", "delta", "=", "delta", "elem", ".", "evaluate", "(", ")", "elem", ".", "tessellate", "(", "*", "*", "kwargs", ")", "return", "elem" ]
Tessellates surfaces. .. note:: Helper function required for ``multiprocessing`` :param elem: surface :type elem: abstract.Surface :param update_delta: flag to control evaluation delta updates :type update_delta: bool :param delta: evaluation delta :type delta: list, tuple :return: updated surface :rtype: abstract.Surface
[ "Tessellates", "surfaces", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/multi.py#L1114-L1132
230,327
orbingol/NURBS-Python
geomdl/multi.py
process_elements_surface
def process_elements_surface(elem, mconf, colorval, idx, force_tsl, update_delta, delta, reset_names): """ Processes visualization elements for surfaces. .. note:: Helper function required for ``multiprocessing`` :param elem: surface :type elem: abstract.Surface :param mconf: visualization module configuration :type mconf: dict :param colorval: color values :type colorval: tuple :param idx: index of the surface :type idx: int :param force_tsl: flag to force re-tessellation :type force_tsl: bool :param update_delta: flag to update surface delta :type update_delta: bool :param delta: new surface evaluation delta :type delta: list, tuple :param reset_names: flag to reset names :type reset_names: bool :return: visualization element (as a dict) :rtype: list """ if idx < 0: lock.acquire() idx = counter.value counter.value += 1 lock.release() if update_delta: elem.delta = delta elem.evaluate() # Reset element name if reset_names: elem.name = "surface" # Fix element name if elem.name == "surface" and idx >= 0: elem.name = elem.name + " " + str(idx) # Color selection color = select_color(colorval[0], colorval[1], idx=idx) # Initialize the return list rl = [] # Add control points if mconf['ctrlpts'] == 'points': ret = dict(ptsarr=elem.ctrlpts, name=(elem.name, "(CP)"), color=color[0], plot_type='ctrlpts', idx=idx) rl.append(ret) # Add control points as quads if mconf['ctrlpts'] == 'quads': qtsl = tessellate.QuadTessellate() qtsl.tessellate(elem.ctrlpts, size_u=elem.ctrlpts_size_u, size_v=elem.ctrlpts_size_v) ret = dict(ptsarr=[qtsl.vertices, qtsl.faces], name=(elem.name, "(CP)"), color=color[0], plot_type='ctrlpts', idx=idx) rl.append(ret) # Add surface points if mconf['evalpts'] == 'points': ret = dict(ptsarr=elem.evalpts, name=(elem.name, idx), color=color[1], plot_type='evalpts', idx=idx) rl.append(ret) # Add surface points as quads if mconf['evalpts'] == 'quads': qtsl = tessellate.QuadTessellate() qtsl.tessellate(elem.evalpts, size_u=elem.sample_size_u, size_v=elem.sample_size_v) ret = dict(ptsarr=[qtsl.vertices, qtsl.faces], name=elem.name, color=color[1], plot_type='evalpts', idx=idx) rl.append(ret) # Add surface points as vertices and triangles if mconf['evalpts'] == 'triangles': elem.tessellate(force=force_tsl) ret = dict(ptsarr=[elem.tessellator.vertices, elem.tessellator.faces], name=elem.name, color=color[1], plot_type='evalpts', idx=idx) rl.append(ret) # Add the trim curves for itc, trim in enumerate(elem.trims): ret = dict(ptsarr=elem.evaluate_list(trim.evalpts), name=("trim", itc), color=colorval[2], plot_type='trimcurve', idx=idx) rl.append(ret) # Return the list return rl
python
def process_elements_surface(elem, mconf, colorval, idx, force_tsl, update_delta, delta, reset_names): """ Processes visualization elements for surfaces. .. note:: Helper function required for ``multiprocessing`` :param elem: surface :type elem: abstract.Surface :param mconf: visualization module configuration :type mconf: dict :param colorval: color values :type colorval: tuple :param idx: index of the surface :type idx: int :param force_tsl: flag to force re-tessellation :type force_tsl: bool :param update_delta: flag to update surface delta :type update_delta: bool :param delta: new surface evaluation delta :type delta: list, tuple :param reset_names: flag to reset names :type reset_names: bool :return: visualization element (as a dict) :rtype: list """ if idx < 0: lock.acquire() idx = counter.value counter.value += 1 lock.release() if update_delta: elem.delta = delta elem.evaluate() # Reset element name if reset_names: elem.name = "surface" # Fix element name if elem.name == "surface" and idx >= 0: elem.name = elem.name + " " + str(idx) # Color selection color = select_color(colorval[0], colorval[1], idx=idx) # Initialize the return list rl = [] # Add control points if mconf['ctrlpts'] == 'points': ret = dict(ptsarr=elem.ctrlpts, name=(elem.name, "(CP)"), color=color[0], plot_type='ctrlpts', idx=idx) rl.append(ret) # Add control points as quads if mconf['ctrlpts'] == 'quads': qtsl = tessellate.QuadTessellate() qtsl.tessellate(elem.ctrlpts, size_u=elem.ctrlpts_size_u, size_v=elem.ctrlpts_size_v) ret = dict(ptsarr=[qtsl.vertices, qtsl.faces], name=(elem.name, "(CP)"), color=color[0], plot_type='ctrlpts', idx=idx) rl.append(ret) # Add surface points if mconf['evalpts'] == 'points': ret = dict(ptsarr=elem.evalpts, name=(elem.name, idx), color=color[1], plot_type='evalpts', idx=idx) rl.append(ret) # Add surface points as quads if mconf['evalpts'] == 'quads': qtsl = tessellate.QuadTessellate() qtsl.tessellate(elem.evalpts, size_u=elem.sample_size_u, size_v=elem.sample_size_v) ret = dict(ptsarr=[qtsl.vertices, qtsl.faces], name=elem.name, color=color[1], plot_type='evalpts', idx=idx) rl.append(ret) # Add surface points as vertices and triangles if mconf['evalpts'] == 'triangles': elem.tessellate(force=force_tsl) ret = dict(ptsarr=[elem.tessellator.vertices, elem.tessellator.faces], name=elem.name, color=color[1], plot_type='evalpts', idx=idx) rl.append(ret) # Add the trim curves for itc, trim in enumerate(elem.trims): ret = dict(ptsarr=elem.evaluate_list(trim.evalpts), name=("trim", itc), color=colorval[2], plot_type='trimcurve', idx=idx) rl.append(ret) # Return the list return rl
[ "def", "process_elements_surface", "(", "elem", ",", "mconf", ",", "colorval", ",", "idx", ",", "force_tsl", ",", "update_delta", ",", "delta", ",", "reset_names", ")", ":", "if", "idx", "<", "0", ":", "lock", ".", "acquire", "(", ")", "idx", "=", "counter", ".", "value", "counter", ".", "value", "+=", "1", "lock", ".", "release", "(", ")", "if", "update_delta", ":", "elem", ".", "delta", "=", "delta", "elem", ".", "evaluate", "(", ")", "# Reset element name", "if", "reset_names", ":", "elem", ".", "name", "=", "\"surface\"", "# Fix element name", "if", "elem", ".", "name", "==", "\"surface\"", "and", "idx", ">=", "0", ":", "elem", ".", "name", "=", "elem", ".", "name", "+", "\" \"", "+", "str", "(", "idx", ")", "# Color selection", "color", "=", "select_color", "(", "colorval", "[", "0", "]", ",", "colorval", "[", "1", "]", ",", "idx", "=", "idx", ")", "# Initialize the return list", "rl", "=", "[", "]", "# Add control points", "if", "mconf", "[", "'ctrlpts'", "]", "==", "'points'", ":", "ret", "=", "dict", "(", "ptsarr", "=", "elem", ".", "ctrlpts", ",", "name", "=", "(", "elem", ".", "name", ",", "\"(CP)\"", ")", ",", "color", "=", "color", "[", "0", "]", ",", "plot_type", "=", "'ctrlpts'", ",", "idx", "=", "idx", ")", "rl", ".", "append", "(", "ret", ")", "# Add control points as quads", "if", "mconf", "[", "'ctrlpts'", "]", "==", "'quads'", ":", "qtsl", "=", "tessellate", ".", "QuadTessellate", "(", ")", "qtsl", ".", "tessellate", "(", "elem", ".", "ctrlpts", ",", "size_u", "=", "elem", ".", "ctrlpts_size_u", ",", "size_v", "=", "elem", ".", "ctrlpts_size_v", ")", "ret", "=", "dict", "(", "ptsarr", "=", "[", "qtsl", ".", "vertices", ",", "qtsl", ".", "faces", "]", ",", "name", "=", "(", "elem", ".", "name", ",", "\"(CP)\"", ")", ",", "color", "=", "color", "[", "0", "]", ",", "plot_type", "=", "'ctrlpts'", ",", "idx", "=", "idx", ")", "rl", ".", "append", "(", "ret", ")", "# Add surface points", "if", "mconf", "[", "'evalpts'", "]", "==", "'points'", ":", "ret", "=", "dict", "(", "ptsarr", "=", "elem", ".", "evalpts", ",", "name", "=", "(", "elem", ".", "name", ",", "idx", ")", ",", "color", "=", "color", "[", "1", "]", ",", "plot_type", "=", "'evalpts'", ",", "idx", "=", "idx", ")", "rl", ".", "append", "(", "ret", ")", "# Add surface points as quads", "if", "mconf", "[", "'evalpts'", "]", "==", "'quads'", ":", "qtsl", "=", "tessellate", ".", "QuadTessellate", "(", ")", "qtsl", ".", "tessellate", "(", "elem", ".", "evalpts", ",", "size_u", "=", "elem", ".", "sample_size_u", ",", "size_v", "=", "elem", ".", "sample_size_v", ")", "ret", "=", "dict", "(", "ptsarr", "=", "[", "qtsl", ".", "vertices", ",", "qtsl", ".", "faces", "]", ",", "name", "=", "elem", ".", "name", ",", "color", "=", "color", "[", "1", "]", ",", "plot_type", "=", "'evalpts'", ",", "idx", "=", "idx", ")", "rl", ".", "append", "(", "ret", ")", "# Add surface points as vertices and triangles", "if", "mconf", "[", "'evalpts'", "]", "==", "'triangles'", ":", "elem", ".", "tessellate", "(", "force", "=", "force_tsl", ")", "ret", "=", "dict", "(", "ptsarr", "=", "[", "elem", ".", "tessellator", ".", "vertices", ",", "elem", ".", "tessellator", ".", "faces", "]", ",", "name", "=", "elem", ".", "name", ",", "color", "=", "color", "[", "1", "]", ",", "plot_type", "=", "'evalpts'", ",", "idx", "=", "idx", ")", "rl", ".", "append", "(", "ret", ")", "# Add the trim curves", "for", "itc", ",", "trim", "in", "enumerate", "(", "elem", ".", "trims", ")", ":", "ret", "=", "dict", "(", "ptsarr", "=", "elem", ".", "evaluate_list", "(", "trim", ".", "evalpts", ")", ",", "name", "=", "(", "\"trim\"", ",", "itc", ")", ",", "color", "=", "colorval", "[", "2", "]", ",", "plot_type", "=", "'trimcurve'", ",", "idx", "=", "idx", ")", "rl", ".", "append", "(", "ret", ")", "# Return the list", "return", "rl" ]
Processes visualization elements for surfaces. .. note:: Helper function required for ``multiprocessing`` :param elem: surface :type elem: abstract.Surface :param mconf: visualization module configuration :type mconf: dict :param colorval: color values :type colorval: tuple :param idx: index of the surface :type idx: int :param force_tsl: flag to force re-tessellation :type force_tsl: bool :param update_delta: flag to update surface delta :type update_delta: bool :param delta: new surface evaluation delta :type delta: list, tuple :param reset_names: flag to reset names :type reset_names: bool :return: visualization element (as a dict) :rtype: list
[ "Processes", "visualization", "elements", "for", "surfaces", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/multi.py#L1135-L1224
230,328
orbingol/NURBS-Python
geomdl/helpers.py
find_span_binsearch
def find_span_binsearch(degree, knot_vector, num_ctrlpts, knot, **kwargs): """ Finds the span of the knot over the input knot vector using binary search. Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller. The NURBS Book states that the knot span index always starts from zero, i.e. for a knot vector [0, 0, 1, 1]; if FindSpan returns 1, then the knot is between the interval [0, 1). :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param num_ctrlpts: number of control points, :math:`n + 1` :type num_ctrlpts: int :param knot: knot or parameter, :math:`u` :type knot: float :return: knot span :rtype: int """ # Get tolerance value tol = kwargs.get('tol', 10e-6) # In The NURBS Book; number of knots = m + 1, number of control points = n + 1, p = degree # All knot vectors should follow the rule: m = p + n + 1 n = num_ctrlpts - 1 if abs(knot_vector[n + 1] - knot) <= tol: return n # Set max and min positions of the array to be searched low = degree high = num_ctrlpts # The division could return a float value which makes it impossible to use as an array index mid = (low + high) / 2 # Direct int casting would cause numerical errors due to discarding the significand figures (digits after the dot) # The round function could return unexpected results, so we add the floating point with some small number # This addition would solve the issues caused by the division operation and how Python stores float numbers. # E.g. round(13/2) = 6 (expected to see 7) mid = int(round(mid + tol)) # Search for the span while (knot < knot_vector[mid]) or (knot >= knot_vector[mid + 1]): if knot < knot_vector[mid]: high = mid else: low = mid mid = int((low + high) / 2) return mid
python
def find_span_binsearch(degree, knot_vector, num_ctrlpts, knot, **kwargs): """ Finds the span of the knot over the input knot vector using binary search. Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller. The NURBS Book states that the knot span index always starts from zero, i.e. for a knot vector [0, 0, 1, 1]; if FindSpan returns 1, then the knot is between the interval [0, 1). :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param num_ctrlpts: number of control points, :math:`n + 1` :type num_ctrlpts: int :param knot: knot or parameter, :math:`u` :type knot: float :return: knot span :rtype: int """ # Get tolerance value tol = kwargs.get('tol', 10e-6) # In The NURBS Book; number of knots = m + 1, number of control points = n + 1, p = degree # All knot vectors should follow the rule: m = p + n + 1 n = num_ctrlpts - 1 if abs(knot_vector[n + 1] - knot) <= tol: return n # Set max and min positions of the array to be searched low = degree high = num_ctrlpts # The division could return a float value which makes it impossible to use as an array index mid = (low + high) / 2 # Direct int casting would cause numerical errors due to discarding the significand figures (digits after the dot) # The round function could return unexpected results, so we add the floating point with some small number # This addition would solve the issues caused by the division operation and how Python stores float numbers. # E.g. round(13/2) = 6 (expected to see 7) mid = int(round(mid + tol)) # Search for the span while (knot < knot_vector[mid]) or (knot >= knot_vector[mid + 1]): if knot < knot_vector[mid]: high = mid else: low = mid mid = int((low + high) / 2) return mid
[ "def", "find_span_binsearch", "(", "degree", ",", "knot_vector", ",", "num_ctrlpts", ",", "knot", ",", "*", "*", "kwargs", ")", ":", "# Get tolerance value", "tol", "=", "kwargs", ".", "get", "(", "'tol'", ",", "10e-6", ")", "# In The NURBS Book; number of knots = m + 1, number of control points = n + 1, p = degree", "# All knot vectors should follow the rule: m = p + n + 1", "n", "=", "num_ctrlpts", "-", "1", "if", "abs", "(", "knot_vector", "[", "n", "+", "1", "]", "-", "knot", ")", "<=", "tol", ":", "return", "n", "# Set max and min positions of the array to be searched", "low", "=", "degree", "high", "=", "num_ctrlpts", "# The division could return a float value which makes it impossible to use as an array index", "mid", "=", "(", "low", "+", "high", ")", "/", "2", "# Direct int casting would cause numerical errors due to discarding the significand figures (digits after the dot)", "# The round function could return unexpected results, so we add the floating point with some small number", "# This addition would solve the issues caused by the division operation and how Python stores float numbers.", "# E.g. round(13/2) = 6 (expected to see 7)", "mid", "=", "int", "(", "round", "(", "mid", "+", "tol", ")", ")", "# Search for the span", "while", "(", "knot", "<", "knot_vector", "[", "mid", "]", ")", "or", "(", "knot", ">=", "knot_vector", "[", "mid", "+", "1", "]", ")", ":", "if", "knot", "<", "knot_vector", "[", "mid", "]", ":", "high", "=", "mid", "else", ":", "low", "=", "mid", "mid", "=", "int", "(", "(", "low", "+", "high", ")", "/", "2", ")", "return", "mid" ]
Finds the span of the knot over the input knot vector using binary search. Implementation of Algorithm A2.1 from The NURBS Book by Piegl & Tiller. The NURBS Book states that the knot span index always starts from zero, i.e. for a knot vector [0, 0, 1, 1]; if FindSpan returns 1, then the knot is between the interval [0, 1). :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param num_ctrlpts: number of control points, :math:`n + 1` :type num_ctrlpts: int :param knot: knot or parameter, :math:`u` :type knot: float :return: knot span :rtype: int
[ "Finds", "the", "span", "of", "the", "knot", "over", "the", "input", "knot", "vector", "using", "binary", "search", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L20-L68
230,329
orbingol/NURBS-Python
geomdl/helpers.py
find_span_linear
def find_span_linear(degree, knot_vector, num_ctrlpts, knot, **kwargs): """ Finds the span of a single knot over the knot vector using linear search. Alternative implementation for the Algorithm A2.1 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param num_ctrlpts: number of control points, :math:`n + 1` :type num_ctrlpts: int :param knot: knot or parameter, :math:`u` :type knot: float :return: knot span :rtype: int """ span = 0 # Knot span index starts from zero while span < num_ctrlpts and knot_vector[span] <= knot: span += 1 return span - 1
python
def find_span_linear(degree, knot_vector, num_ctrlpts, knot, **kwargs): """ Finds the span of a single knot over the knot vector using linear search. Alternative implementation for the Algorithm A2.1 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param num_ctrlpts: number of control points, :math:`n + 1` :type num_ctrlpts: int :param knot: knot or parameter, :math:`u` :type knot: float :return: knot span :rtype: int """ span = 0 # Knot span index starts from zero while span < num_ctrlpts and knot_vector[span] <= knot: span += 1 return span - 1
[ "def", "find_span_linear", "(", "degree", ",", "knot_vector", ",", "num_ctrlpts", ",", "knot", ",", "*", "*", "kwargs", ")", ":", "span", "=", "0", "# Knot span index starts from zero", "while", "span", "<", "num_ctrlpts", "and", "knot_vector", "[", "span", "]", "<=", "knot", ":", "span", "+=", "1", "return", "span", "-", "1" ]
Finds the span of a single knot over the knot vector using linear search. Alternative implementation for the Algorithm A2.1 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param num_ctrlpts: number of control points, :math:`n + 1` :type num_ctrlpts: int :param knot: knot or parameter, :math:`u` :type knot: float :return: knot span :rtype: int
[ "Finds", "the", "span", "of", "a", "single", "knot", "over", "the", "knot", "vector", "using", "linear", "search", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L71-L91
230,330
orbingol/NURBS-Python
geomdl/helpers.py
find_spans
def find_spans(degree, knot_vector, num_ctrlpts, knots, func=find_span_linear): """ Finds spans of a list of knots over the knot vector. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param num_ctrlpts: number of control points, :math:`n + 1` :type num_ctrlpts: int :param knots: list of knots or parameters :type knots: list, tuple :param func: function for span finding, e.g. linear or binary search :return: list of spans :rtype: list """ spans = [] for knot in knots: spans.append(func(degree, knot_vector, num_ctrlpts, knot)) return spans
python
def find_spans(degree, knot_vector, num_ctrlpts, knots, func=find_span_linear): """ Finds spans of a list of knots over the knot vector. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param num_ctrlpts: number of control points, :math:`n + 1` :type num_ctrlpts: int :param knots: list of knots or parameters :type knots: list, tuple :param func: function for span finding, e.g. linear or binary search :return: list of spans :rtype: list """ spans = [] for knot in knots: spans.append(func(degree, knot_vector, num_ctrlpts, knot)) return spans
[ "def", "find_spans", "(", "degree", ",", "knot_vector", ",", "num_ctrlpts", ",", "knots", ",", "func", "=", "find_span_linear", ")", ":", "spans", "=", "[", "]", "for", "knot", "in", "knots", ":", "spans", ".", "append", "(", "func", "(", "degree", ",", "knot_vector", ",", "num_ctrlpts", ",", "knot", ")", ")", "return", "spans" ]
Finds spans of a list of knots over the knot vector. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param num_ctrlpts: number of control points, :math:`n + 1` :type num_ctrlpts: int :param knots: list of knots or parameters :type knots: list, tuple :param func: function for span finding, e.g. linear or binary search :return: list of spans :rtype: list
[ "Finds", "spans", "of", "a", "list", "of", "knots", "over", "the", "knot", "vector", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L94-L112
230,331
orbingol/NURBS-Python
geomdl/helpers.py
find_multiplicity
def find_multiplicity(knot, knot_vector, **kwargs): """ Finds knot multiplicity over the knot vector. Keyword Arguments: * ``tol``: tolerance (delta) value for equality checking :param knot: knot or parameter, :math:`u` :type knot: float :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :return: knot multiplicity, :math:`s` :rtype: int """ # Get tolerance value tol = kwargs.get('tol', 10e-8) mult = 0 # initial multiplicity for kv in knot_vector: if abs(knot - kv) <= tol: mult += 1 return mult
python
def find_multiplicity(knot, knot_vector, **kwargs): """ Finds knot multiplicity over the knot vector. Keyword Arguments: * ``tol``: tolerance (delta) value for equality checking :param knot: knot or parameter, :math:`u` :type knot: float :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :return: knot multiplicity, :math:`s` :rtype: int """ # Get tolerance value tol = kwargs.get('tol', 10e-8) mult = 0 # initial multiplicity for kv in knot_vector: if abs(knot - kv) <= tol: mult += 1 return mult
[ "def", "find_multiplicity", "(", "knot", ",", "knot_vector", ",", "*", "*", "kwargs", ")", ":", "# Get tolerance value", "tol", "=", "kwargs", ".", "get", "(", "'tol'", ",", "10e-8", ")", "mult", "=", "0", "# initial multiplicity", "for", "kv", "in", "knot_vector", ":", "if", "abs", "(", "knot", "-", "kv", ")", "<=", "tol", ":", "mult", "+=", "1", "return", "mult" ]
Finds knot multiplicity over the knot vector. Keyword Arguments: * ``tol``: tolerance (delta) value for equality checking :param knot: knot or parameter, :math:`u` :type knot: float :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :return: knot multiplicity, :math:`s` :rtype: int
[ "Finds", "knot", "multiplicity", "over", "the", "knot", "vector", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L115-L137
230,332
orbingol/NURBS-Python
geomdl/helpers.py
basis_function
def basis_function(degree, knot_vector, span, knot): """ Computes the non-vanishing basis functions for a single parameter. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param span: knot span, :math:`i` :type span: int :param knot: knot or parameter, :math:`u` :type knot: float :return: basis functions :rtype: list """ left = [0.0 for _ in range(degree + 1)] right = [0.0 for _ in range(degree + 1)] N = [1.0 for _ in range(degree + 1)] # N[0] = 1.0 by definition for j in range(1, degree + 1): left[j] = knot - knot_vector[span + 1 - j] right[j] = knot_vector[span + j] - knot saved = 0.0 for r in range(0, j): temp = N[r] / (right[r + 1] + left[j - r]) N[r] = saved + right[r + 1] * temp saved = left[j - r] * temp N[j] = saved return N
python
def basis_function(degree, knot_vector, span, knot): """ Computes the non-vanishing basis functions for a single parameter. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param span: knot span, :math:`i` :type span: int :param knot: knot or parameter, :math:`u` :type knot: float :return: basis functions :rtype: list """ left = [0.0 for _ in range(degree + 1)] right = [0.0 for _ in range(degree + 1)] N = [1.0 for _ in range(degree + 1)] # N[0] = 1.0 by definition for j in range(1, degree + 1): left[j] = knot - knot_vector[span + 1 - j] right[j] = knot_vector[span + j] - knot saved = 0.0 for r in range(0, j): temp = N[r] / (right[r + 1] + left[j - r]) N[r] = saved + right[r + 1] * temp saved = left[j - r] * temp N[j] = saved return N
[ "def", "basis_function", "(", "degree", ",", "knot_vector", ",", "span", ",", "knot", ")", ":", "left", "=", "[", "0.0", "for", "_", "in", "range", "(", "degree", "+", "1", ")", "]", "right", "=", "[", "0.0", "for", "_", "in", "range", "(", "degree", "+", "1", ")", "]", "N", "=", "[", "1.0", "for", "_", "in", "range", "(", "degree", "+", "1", ")", "]", "# N[0] = 1.0 by definition", "for", "j", "in", "range", "(", "1", ",", "degree", "+", "1", ")", ":", "left", "[", "j", "]", "=", "knot", "-", "knot_vector", "[", "span", "+", "1", "-", "j", "]", "right", "[", "j", "]", "=", "knot_vector", "[", "span", "+", "j", "]", "-", "knot", "saved", "=", "0.0", "for", "r", "in", "range", "(", "0", ",", "j", ")", ":", "temp", "=", "N", "[", "r", "]", "/", "(", "right", "[", "r", "+", "1", "]", "+", "left", "[", "j", "-", "r", "]", ")", "N", "[", "r", "]", "=", "saved", "+", "right", "[", "r", "+", "1", "]", "*", "temp", "saved", "=", "left", "[", "j", "-", "r", "]", "*", "temp", "N", "[", "j", "]", "=", "saved", "return", "N" ]
Computes the non-vanishing basis functions for a single parameter. Implementation of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param span: knot span, :math:`i` :type span: int :param knot: knot or parameter, :math:`u` :type knot: float :return: basis functions :rtype: list
[ "Computes", "the", "non", "-", "vanishing", "basis", "functions", "for", "a", "single", "parameter", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L140-L170
230,333
orbingol/NURBS-Python
geomdl/helpers.py
basis_functions
def basis_functions(degree, knot_vector, spans, knots): """ Computes the non-vanishing basis functions for a list of parameters. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param spans: list of knot spans :type spans: list, tuple :param knots: list of knots or parameters :type knots: list, tuple :return: basis functions :rtype: list """ basis = [] for span, knot in zip(spans, knots): basis.append(basis_function(degree, knot_vector, span, knot)) return basis
python
def basis_functions(degree, knot_vector, spans, knots): """ Computes the non-vanishing basis functions for a list of parameters. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param spans: list of knot spans :type spans: list, tuple :param knots: list of knots or parameters :type knots: list, tuple :return: basis functions :rtype: list """ basis = [] for span, knot in zip(spans, knots): basis.append(basis_function(degree, knot_vector, span, knot)) return basis
[ "def", "basis_functions", "(", "degree", ",", "knot_vector", ",", "spans", ",", "knots", ")", ":", "basis", "=", "[", "]", "for", "span", ",", "knot", "in", "zip", "(", "spans", ",", "knots", ")", ":", "basis", ".", "append", "(", "basis_function", "(", "degree", ",", "knot_vector", ",", "span", ",", "knot", ")", ")", "return", "basis" ]
Computes the non-vanishing basis functions for a list of parameters. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param spans: list of knot spans :type spans: list, tuple :param knots: list of knots or parameters :type knots: list, tuple :return: basis functions :rtype: list
[ "Computes", "the", "non", "-", "vanishing", "basis", "functions", "for", "a", "list", "of", "parameters", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L173-L190
230,334
orbingol/NURBS-Python
geomdl/helpers.py
basis_function_all
def basis_function_all(degree, knot_vector, span, knot): """ Computes all non-zero basis functions of all degrees from 0 up to the input degree for a single parameter. A slightly modified version of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param span: knot span, :math:`i` :type span: int :param knot: knot or parameter, :math:`u` :type knot: float :return: basis functions :rtype: list """ N = [[None for _ in range(degree + 1)] for _ in range(degree + 1)] for i in range(0, degree + 1): bfuns = basis_function(i, knot_vector, span, knot) for j in range(0, i + 1): N[j][i] = bfuns[j] return N
python
def basis_function_all(degree, knot_vector, span, knot): """ Computes all non-zero basis functions of all degrees from 0 up to the input degree for a single parameter. A slightly modified version of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param span: knot span, :math:`i` :type span: int :param knot: knot or parameter, :math:`u` :type knot: float :return: basis functions :rtype: list """ N = [[None for _ in range(degree + 1)] for _ in range(degree + 1)] for i in range(0, degree + 1): bfuns = basis_function(i, knot_vector, span, knot) for j in range(0, i + 1): N[j][i] = bfuns[j] return N
[ "def", "basis_function_all", "(", "degree", ",", "knot_vector", ",", "span", ",", "knot", ")", ":", "N", "=", "[", "[", "None", "for", "_", "in", "range", "(", "degree", "+", "1", ")", "]", "for", "_", "in", "range", "(", "degree", "+", "1", ")", "]", "for", "i", "in", "range", "(", "0", ",", "degree", "+", "1", ")", ":", "bfuns", "=", "basis_function", "(", "i", ",", "knot_vector", ",", "span", ",", "knot", ")", "for", "j", "in", "range", "(", "0", ",", "i", "+", "1", ")", ":", "N", "[", "j", "]", "[", "i", "]", "=", "bfuns", "[", "j", "]", "return", "N" ]
Computes all non-zero basis functions of all degrees from 0 up to the input degree for a single parameter. A slightly modified version of Algorithm A2.2 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param span: knot span, :math:`i` :type span: int :param knot: knot or parameter, :math:`u` :type knot: float :return: basis functions :rtype: list
[ "Computes", "all", "non", "-", "zero", "basis", "functions", "of", "all", "degrees", "from", "0", "up", "to", "the", "input", "degree", "for", "a", "single", "parameter", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L193-L214
230,335
orbingol/NURBS-Python
geomdl/helpers.py
basis_functions_ders
def basis_functions_ders(degree, knot_vector, spans, knots, order): """ Computes derivatives of the basis functions for a list of parameters. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param spans: list of knot spans :type spans: list, tuple :param knots: list of knots or parameters :type knots: list, tuple :param order: order of the derivative :type order: int :return: derivatives of the basis functions :rtype: list """ basis_ders = [] for span, knot in zip(spans, knots): basis_ders.append(basis_function_ders(degree, knot_vector, span, knot, order)) return basis_ders
python
def basis_functions_ders(degree, knot_vector, spans, knots, order): """ Computes derivatives of the basis functions for a list of parameters. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param spans: list of knot spans :type spans: list, tuple :param knots: list of knots or parameters :type knots: list, tuple :param order: order of the derivative :type order: int :return: derivatives of the basis functions :rtype: list """ basis_ders = [] for span, knot in zip(spans, knots): basis_ders.append(basis_function_ders(degree, knot_vector, span, knot, order)) return basis_ders
[ "def", "basis_functions_ders", "(", "degree", ",", "knot_vector", ",", "spans", ",", "knots", ",", "order", ")", ":", "basis_ders", "=", "[", "]", "for", "span", ",", "knot", "in", "zip", "(", "spans", ",", "knots", ")", ":", "basis_ders", ".", "append", "(", "basis_function_ders", "(", "degree", ",", "knot_vector", ",", "span", ",", "knot", ",", "order", ")", ")", "return", "basis_ders" ]
Computes derivatives of the basis functions for a list of parameters. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector, :math:`U` :type knot_vector: list, tuple :param spans: list of knot spans :type spans: list, tuple :param knots: list of knots or parameters :type knots: list, tuple :param order: order of the derivative :type order: int :return: derivatives of the basis functions :rtype: list
[ "Computes", "derivatives", "of", "the", "basis", "functions", "for", "a", "list", "of", "parameters", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L307-L326
230,336
orbingol/NURBS-Python
geomdl/helpers.py
basis_function_one
def basis_function_one(degree, knot_vector, span, knot): """ Computes the value of a basis function for a single parameter. Implementation of Algorithm 2.4 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector :type knot_vector: list, tuple :param span: knot span, :math:`i` :type span: int :param knot: knot or parameter, :math:`u` :type knot: float :return: basis function, :math:`N_{i,p}` :rtype: float """ # Special case at boundaries if (span == 0 and knot == knot_vector[0]) or \ (span == len(knot_vector) - degree - 2) and knot == knot_vector[len(knot_vector) - 1]: return 1.0 # Knot is outside of span range if knot < knot_vector[span] or knot >= knot_vector[span + degree + 1]: return 0.0 N = [0.0 for _ in range(degree + span + 1)] # Initialize the zeroth degree basis functions for j in range(0, degree + 1): if knot_vector[span + j] <= knot < knot_vector[span + j + 1]: N[j] = 1.0 # Computing triangular table of basis functions for k in range(1, degree + 1): # Detecting zeros saves computations saved = 0.0 if N[0] != 0.0: saved = ((knot - knot_vector[span]) * N[0]) / (knot_vector[span + k] - knot_vector[span]) for j in range(0, degree - k + 1): Uleft = knot_vector[span + j + 1] Uright = knot_vector[span + j + k + 1] # Zero detection if N[j + 1] == 0.0: N[j] = saved saved = 0.0 else: temp = N[j + 1] / (Uright - Uleft) N[j] = saved + (Uright - knot) * temp saved = (knot - Uleft) * temp return N[0]
python
def basis_function_one(degree, knot_vector, span, knot): """ Computes the value of a basis function for a single parameter. Implementation of Algorithm 2.4 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector :type knot_vector: list, tuple :param span: knot span, :math:`i` :type span: int :param knot: knot or parameter, :math:`u` :type knot: float :return: basis function, :math:`N_{i,p}` :rtype: float """ # Special case at boundaries if (span == 0 and knot == knot_vector[0]) or \ (span == len(knot_vector) - degree - 2) and knot == knot_vector[len(knot_vector) - 1]: return 1.0 # Knot is outside of span range if knot < knot_vector[span] or knot >= knot_vector[span + degree + 1]: return 0.0 N = [0.0 for _ in range(degree + span + 1)] # Initialize the zeroth degree basis functions for j in range(0, degree + 1): if knot_vector[span + j] <= knot < knot_vector[span + j + 1]: N[j] = 1.0 # Computing triangular table of basis functions for k in range(1, degree + 1): # Detecting zeros saves computations saved = 0.0 if N[0] != 0.0: saved = ((knot - knot_vector[span]) * N[0]) / (knot_vector[span + k] - knot_vector[span]) for j in range(0, degree - k + 1): Uleft = knot_vector[span + j + 1] Uright = knot_vector[span + j + k + 1] # Zero detection if N[j + 1] == 0.0: N[j] = saved saved = 0.0 else: temp = N[j + 1] / (Uright - Uleft) N[j] = saved + (Uright - knot) * temp saved = (knot - Uleft) * temp return N[0]
[ "def", "basis_function_one", "(", "degree", ",", "knot_vector", ",", "span", ",", "knot", ")", ":", "# Special case at boundaries", "if", "(", "span", "==", "0", "and", "knot", "==", "knot_vector", "[", "0", "]", ")", "or", "(", "span", "==", "len", "(", "knot_vector", ")", "-", "degree", "-", "2", ")", "and", "knot", "==", "knot_vector", "[", "len", "(", "knot_vector", ")", "-", "1", "]", ":", "return", "1.0", "# Knot is outside of span range", "if", "knot", "<", "knot_vector", "[", "span", "]", "or", "knot", ">=", "knot_vector", "[", "span", "+", "degree", "+", "1", "]", ":", "return", "0.0", "N", "=", "[", "0.0", "for", "_", "in", "range", "(", "degree", "+", "span", "+", "1", ")", "]", "# Initialize the zeroth degree basis functions", "for", "j", "in", "range", "(", "0", ",", "degree", "+", "1", ")", ":", "if", "knot_vector", "[", "span", "+", "j", "]", "<=", "knot", "<", "knot_vector", "[", "span", "+", "j", "+", "1", "]", ":", "N", "[", "j", "]", "=", "1.0", "# Computing triangular table of basis functions", "for", "k", "in", "range", "(", "1", ",", "degree", "+", "1", ")", ":", "# Detecting zeros saves computations", "saved", "=", "0.0", "if", "N", "[", "0", "]", "!=", "0.0", ":", "saved", "=", "(", "(", "knot", "-", "knot_vector", "[", "span", "]", ")", "*", "N", "[", "0", "]", ")", "/", "(", "knot_vector", "[", "span", "+", "k", "]", "-", "knot_vector", "[", "span", "]", ")", "for", "j", "in", "range", "(", "0", ",", "degree", "-", "k", "+", "1", ")", ":", "Uleft", "=", "knot_vector", "[", "span", "+", "j", "+", "1", "]", "Uright", "=", "knot_vector", "[", "span", "+", "j", "+", "k", "+", "1", "]", "# Zero detection", "if", "N", "[", "j", "+", "1", "]", "==", "0.0", ":", "N", "[", "j", "]", "=", "saved", "saved", "=", "0.0", "else", ":", "temp", "=", "N", "[", "j", "+", "1", "]", "/", "(", "Uright", "-", "Uleft", ")", "N", "[", "j", "]", "=", "saved", "+", "(", "Uright", "-", "knot", ")", "*", "temp", "saved", "=", "(", "knot", "-", "Uleft", ")", "*", "temp", "return", "N", "[", "0", "]" ]
Computes the value of a basis function for a single parameter. Implementation of Algorithm 2.4 from The NURBS Book by Piegl & Tiller. :param degree: degree, :math:`p` :type degree: int :param knot_vector: knot vector :type knot_vector: list, tuple :param span: knot span, :math:`i` :type span: int :param knot: knot or parameter, :math:`u` :type knot: float :return: basis function, :math:`N_{i,p}` :rtype: float
[ "Computes", "the", "value", "of", "a", "basis", "function", "for", "a", "single", "parameter", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/helpers.py#L329-L381
230,337
orbingol/NURBS-Python
geomdl/visualization/VisMPL.py
VisConfig.set_axes_equal
def set_axes_equal(ax): """ Sets equal aspect ratio across the three axes of a 3D plot. Contributed by Xuefeng Zhao. :param ax: a Matplotlib axis, e.g., as output from plt.gca(). """ bounds = [ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()] ranges = [abs(bound[1] - bound[0]) for bound in bounds] centers = [np.mean(bound) for bound in bounds] radius = 0.5 * max(ranges) lower_limits = centers - radius upper_limits = centers + radius ax.set_xlim3d([lower_limits[0], upper_limits[0]]) ax.set_ylim3d([lower_limits[1], upper_limits[1]]) ax.set_zlim3d([lower_limits[2], upper_limits[2]])
python
def set_axes_equal(ax): """ Sets equal aspect ratio across the three axes of a 3D plot. Contributed by Xuefeng Zhao. :param ax: a Matplotlib axis, e.g., as output from plt.gca(). """ bounds = [ax.get_xlim3d(), ax.get_ylim3d(), ax.get_zlim3d()] ranges = [abs(bound[1] - bound[0]) for bound in bounds] centers = [np.mean(bound) for bound in bounds] radius = 0.5 * max(ranges) lower_limits = centers - radius upper_limits = centers + radius ax.set_xlim3d([lower_limits[0], upper_limits[0]]) ax.set_ylim3d([lower_limits[1], upper_limits[1]]) ax.set_zlim3d([lower_limits[2], upper_limits[2]])
[ "def", "set_axes_equal", "(", "ax", ")", ":", "bounds", "=", "[", "ax", ".", "get_xlim3d", "(", ")", ",", "ax", ".", "get_ylim3d", "(", ")", ",", "ax", ".", "get_zlim3d", "(", ")", "]", "ranges", "=", "[", "abs", "(", "bound", "[", "1", "]", "-", "bound", "[", "0", "]", ")", "for", "bound", "in", "bounds", "]", "centers", "=", "[", "np", ".", "mean", "(", "bound", ")", "for", "bound", "in", "bounds", "]", "radius", "=", "0.5", "*", "max", "(", "ranges", ")", "lower_limits", "=", "centers", "-", "radius", "upper_limits", "=", "centers", "+", "radius", "ax", ".", "set_xlim3d", "(", "[", "lower_limits", "[", "0", "]", ",", "upper_limits", "[", "0", "]", "]", ")", "ax", ".", "set_ylim3d", "(", "[", "lower_limits", "[", "1", "]", ",", "upper_limits", "[", "1", "]", "]", ")", "ax", ".", "set_zlim3d", "(", "[", "lower_limits", "[", "2", "]", ",", "upper_limits", "[", "2", "]", "]", ")" ]
Sets equal aspect ratio across the three axes of a 3D plot. Contributed by Xuefeng Zhao. :param ax: a Matplotlib axis, e.g., as output from plt.gca().
[ "Sets", "equal", "aspect", "ratio", "across", "the", "three", "axes", "of", "a", "3D", "plot", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/VisMPL.py#L88-L103
230,338
orbingol/NURBS-Python
geomdl/visualization/VisMPL.py
VisSurface.animate
def animate(self, **kwargs): """ Animates the surface. This function only animates the triangulated surface. There will be no other elements, such as control points grid or bounding box. Keyword arguments: * ``colormap``: applies colormap to the surface Colormaps are a visualization feature of Matplotlib. They can be used for several types of surface plots via the following import statement: ``from matplotlib import cm`` The following link displays the list of Matplolib colormaps and some examples on colormaps: https://matplotlib.org/tutorials/colors/colormaps.html """ # Calling parent render function super(VisSurface, self).render(**kwargs) # Colormaps surf_cmaps = kwargs.get('colormap', None) # Initialize variables tri_idxs = [] vert_coords = [] trisurf_params = [] frames = [] frames_tris = [] num_vertices = 0 # Start plotting of the surface and the control points grid fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi) ax = Axes3D(fig) # Start plotting surf_count = 0 for plot in self._plots: # Plot evaluated points if plot['type'] == 'evalpts' and self.vconf.display_evalpts: # Use internal triangulation algorithm instead of Qhull (MPL default) verts = plot['ptsarr'][0] tris = plot['ptsarr'][1] # Extract zero-indexed vertex number list tri_idxs += [[ti + num_vertices for ti in tri.data] for tri in tris] # Extract vertex coordinates vert_coords += [vert.data for vert in verts] # Update number of vertices num_vertices = len(vert_coords) # Determine the color or the colormap of the triangulated plot params = {} if surf_cmaps: try: params['cmap'] = surf_cmaps[surf_count] surf_count += 1 except IndexError: params['color'] = plot['color'] else: params['color'] = plot['color'] trisurf_params += [params for _ in range(len(tris))] # Pre-processing for the animation pts = np.array(vert_coords, dtype=self.vconf.dtype) # Create the frames (Artists) for tidx, pidx in zip(tri_idxs, trisurf_params): frames_tris.append(tidx) # Create MPL Triangulation object triangulation = mpltri.Triangulation(pts[:, 0], pts[:, 1], triangles=frames_tris) # Use custom Triangulation object and the choice of color/colormap to plot the surface p3df = ax.plot_trisurf(triangulation, pts[:, 2], alpha=self.vconf.alpha, **pidx) # Add to frames list frames.append([p3df]) # Create MPL ArtistAnimation ani = animation.ArtistAnimation(fig, frames, interval=100, blit=True, repeat_delay=1000) # Remove axes if not self.vconf.display_axes: plt.axis('off') # Set axes equal if self.vconf.axes_equal: self.vconf.set_axes_equal(ax) # Axis labels if self.vconf.display_labels: ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # Process keyword arguments fig_filename = kwargs.get('fig_save_as', None) fig_display = kwargs.get('display_plot', True) # Display the plot if fig_display: plt.show() else: fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename # Save the figure self.vconf.save_figure_as(fig, fig_filename) # Return the figure object return fig
python
def animate(self, **kwargs): """ Animates the surface. This function only animates the triangulated surface. There will be no other elements, such as control points grid or bounding box. Keyword arguments: * ``colormap``: applies colormap to the surface Colormaps are a visualization feature of Matplotlib. They can be used for several types of surface plots via the following import statement: ``from matplotlib import cm`` The following link displays the list of Matplolib colormaps and some examples on colormaps: https://matplotlib.org/tutorials/colors/colormaps.html """ # Calling parent render function super(VisSurface, self).render(**kwargs) # Colormaps surf_cmaps = kwargs.get('colormap', None) # Initialize variables tri_idxs = [] vert_coords = [] trisurf_params = [] frames = [] frames_tris = [] num_vertices = 0 # Start plotting of the surface and the control points grid fig = plt.figure(figsize=self.vconf.figure_size, dpi=self.vconf.figure_dpi) ax = Axes3D(fig) # Start plotting surf_count = 0 for plot in self._plots: # Plot evaluated points if plot['type'] == 'evalpts' and self.vconf.display_evalpts: # Use internal triangulation algorithm instead of Qhull (MPL default) verts = plot['ptsarr'][0] tris = plot['ptsarr'][1] # Extract zero-indexed vertex number list tri_idxs += [[ti + num_vertices for ti in tri.data] for tri in tris] # Extract vertex coordinates vert_coords += [vert.data for vert in verts] # Update number of vertices num_vertices = len(vert_coords) # Determine the color or the colormap of the triangulated plot params = {} if surf_cmaps: try: params['cmap'] = surf_cmaps[surf_count] surf_count += 1 except IndexError: params['color'] = plot['color'] else: params['color'] = plot['color'] trisurf_params += [params for _ in range(len(tris))] # Pre-processing for the animation pts = np.array(vert_coords, dtype=self.vconf.dtype) # Create the frames (Artists) for tidx, pidx in zip(tri_idxs, trisurf_params): frames_tris.append(tidx) # Create MPL Triangulation object triangulation = mpltri.Triangulation(pts[:, 0], pts[:, 1], triangles=frames_tris) # Use custom Triangulation object and the choice of color/colormap to plot the surface p3df = ax.plot_trisurf(triangulation, pts[:, 2], alpha=self.vconf.alpha, **pidx) # Add to frames list frames.append([p3df]) # Create MPL ArtistAnimation ani = animation.ArtistAnimation(fig, frames, interval=100, blit=True, repeat_delay=1000) # Remove axes if not self.vconf.display_axes: plt.axis('off') # Set axes equal if self.vconf.axes_equal: self.vconf.set_axes_equal(ax) # Axis labels if self.vconf.display_labels: ax.set_xlabel('x') ax.set_ylabel('y') ax.set_zlabel('z') # Process keyword arguments fig_filename = kwargs.get('fig_save_as', None) fig_display = kwargs.get('display_plot', True) # Display the plot if fig_display: plt.show() else: fig_filename = self.vconf.figure_image_filename if fig_filename is None else fig_filename # Save the figure self.vconf.save_figure_as(fig, fig_filename) # Return the figure object return fig
[ "def", "animate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "# Calling parent render function", "super", "(", "VisSurface", ",", "self", ")", ".", "render", "(", "*", "*", "kwargs", ")", "# Colormaps", "surf_cmaps", "=", "kwargs", ".", "get", "(", "'colormap'", ",", "None", ")", "# Initialize variables", "tri_idxs", "=", "[", "]", "vert_coords", "=", "[", "]", "trisurf_params", "=", "[", "]", "frames", "=", "[", "]", "frames_tris", "=", "[", "]", "num_vertices", "=", "0", "# Start plotting of the surface and the control points grid", "fig", "=", "plt", ".", "figure", "(", "figsize", "=", "self", ".", "vconf", ".", "figure_size", ",", "dpi", "=", "self", ".", "vconf", ".", "figure_dpi", ")", "ax", "=", "Axes3D", "(", "fig", ")", "# Start plotting", "surf_count", "=", "0", "for", "plot", "in", "self", ".", "_plots", ":", "# Plot evaluated points", "if", "plot", "[", "'type'", "]", "==", "'evalpts'", "and", "self", ".", "vconf", ".", "display_evalpts", ":", "# Use internal triangulation algorithm instead of Qhull (MPL default)", "verts", "=", "plot", "[", "'ptsarr'", "]", "[", "0", "]", "tris", "=", "plot", "[", "'ptsarr'", "]", "[", "1", "]", "# Extract zero-indexed vertex number list", "tri_idxs", "+=", "[", "[", "ti", "+", "num_vertices", "for", "ti", "in", "tri", ".", "data", "]", "for", "tri", "in", "tris", "]", "# Extract vertex coordinates", "vert_coords", "+=", "[", "vert", ".", "data", "for", "vert", "in", "verts", "]", "# Update number of vertices", "num_vertices", "=", "len", "(", "vert_coords", ")", "# Determine the color or the colormap of the triangulated plot", "params", "=", "{", "}", "if", "surf_cmaps", ":", "try", ":", "params", "[", "'cmap'", "]", "=", "surf_cmaps", "[", "surf_count", "]", "surf_count", "+=", "1", "except", "IndexError", ":", "params", "[", "'color'", "]", "=", "plot", "[", "'color'", "]", "else", ":", "params", "[", "'color'", "]", "=", "plot", "[", "'color'", "]", "trisurf_params", "+=", "[", "params", "for", "_", "in", "range", "(", "len", "(", "tris", ")", ")", "]", "# Pre-processing for the animation", "pts", "=", "np", ".", "array", "(", "vert_coords", ",", "dtype", "=", "self", ".", "vconf", ".", "dtype", ")", "# Create the frames (Artists)", "for", "tidx", ",", "pidx", "in", "zip", "(", "tri_idxs", ",", "trisurf_params", ")", ":", "frames_tris", ".", "append", "(", "tidx", ")", "# Create MPL Triangulation object", "triangulation", "=", "mpltri", ".", "Triangulation", "(", "pts", "[", ":", ",", "0", "]", ",", "pts", "[", ":", ",", "1", "]", ",", "triangles", "=", "frames_tris", ")", "# Use custom Triangulation object and the choice of color/colormap to plot the surface", "p3df", "=", "ax", ".", "plot_trisurf", "(", "triangulation", ",", "pts", "[", ":", ",", "2", "]", ",", "alpha", "=", "self", ".", "vconf", ".", "alpha", ",", "*", "*", "pidx", ")", "# Add to frames list", "frames", ".", "append", "(", "[", "p3df", "]", ")", "# Create MPL ArtistAnimation", "ani", "=", "animation", ".", "ArtistAnimation", "(", "fig", ",", "frames", ",", "interval", "=", "100", ",", "blit", "=", "True", ",", "repeat_delay", "=", "1000", ")", "# Remove axes", "if", "not", "self", ".", "vconf", ".", "display_axes", ":", "plt", ".", "axis", "(", "'off'", ")", "# Set axes equal", "if", "self", ".", "vconf", ".", "axes_equal", ":", "self", ".", "vconf", ".", "set_axes_equal", "(", "ax", ")", "# Axis labels", "if", "self", ".", "vconf", ".", "display_labels", ":", "ax", ".", "set_xlabel", "(", "'x'", ")", "ax", ".", "set_ylabel", "(", "'y'", ")", "ax", ".", "set_zlabel", "(", "'z'", ")", "# Process keyword arguments", "fig_filename", "=", "kwargs", ".", "get", "(", "'fig_save_as'", ",", "None", ")", "fig_display", "=", "kwargs", ".", "get", "(", "'display_plot'", ",", "True", ")", "# Display the plot", "if", "fig_display", ":", "plt", ".", "show", "(", ")", "else", ":", "fig_filename", "=", "self", ".", "vconf", ".", "figure_image_filename", "if", "fig_filename", "is", "None", "else", "fig_filename", "# Save the figure", "self", ".", "vconf", ".", "save_figure_as", "(", "fig", ",", "fig_filename", ")", "# Return the figure object", "return", "fig" ]
Animates the surface. This function only animates the triangulated surface. There will be no other elements, such as control points grid or bounding box. Keyword arguments: * ``colormap``: applies colormap to the surface Colormaps are a visualization feature of Matplotlib. They can be used for several types of surface plots via the following import statement: ``from matplotlib import cm`` The following link displays the list of Matplolib colormaps and some examples on colormaps: https://matplotlib.org/tutorials/colors/colormaps.html
[ "Animates", "the", "surface", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/VisMPL.py#L298-L402
230,339
orbingol/NURBS-Python
geomdl/_operations.py
tangent_curve_single_list
def tangent_curve_single_list(obj, param_list, normalize): """ Evaluates the curve tangent vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = tangent_curve_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
python
def tangent_curve_single_list(obj, param_list, normalize): """ Evaluates the curve tangent vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = tangent_curve_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
[ "def", "tangent_curve_single_list", "(", "obj", ",", "param_list", ",", "normalize", ")", ":", "ret_vector", "=", "[", "]", "for", "param", "in", "param_list", ":", "temp", "=", "tangent_curve_single", "(", "obj", ",", "param", ",", "normalize", ")", "ret_vector", ".", "append", "(", "temp", ")", "return", "tuple", "(", "ret_vector", ")" ]
Evaluates the curve tangent vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "curve", "tangent", "vectors", "at", "the", "given", "list", "of", "parameter", "values", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L41-L57
230,340
orbingol/NURBS-Python
geomdl/_operations.py
normal_curve_single
def normal_curve_single(obj, u, normalize): """ Evaluates the curve normal vector at the input parameter, u. Curve normal is calculated from the 2nd derivative of the curve at the input parameter, u. The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself. :param obj: input curve :type obj: abstract.Curve :param u: parameter :type u: float :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ # 2nd derivative of the curve gives the normal ders = obj.derivatives(u, 2) point = ders[0] vector = linalg.vector_normalize(ders[2]) if normalize else ders[2] return tuple(point), tuple(vector)
python
def normal_curve_single(obj, u, normalize): """ Evaluates the curve normal vector at the input parameter, u. Curve normal is calculated from the 2nd derivative of the curve at the input parameter, u. The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself. :param obj: input curve :type obj: abstract.Curve :param u: parameter :type u: float :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ # 2nd derivative of the curve gives the normal ders = obj.derivatives(u, 2) point = ders[0] vector = linalg.vector_normalize(ders[2]) if normalize else ders[2] return tuple(point), tuple(vector)
[ "def", "normal_curve_single", "(", "obj", ",", "u", ",", "normalize", ")", ":", "# 2nd derivative of the curve gives the normal", "ders", "=", "obj", ".", "derivatives", "(", "u", ",", "2", ")", "point", "=", "ders", "[", "0", "]", "vector", "=", "linalg", ".", "vector_normalize", "(", "ders", "[", "2", "]", ")", "if", "normalize", "else", "ders", "[", "2", "]", "return", "tuple", "(", "point", ")", ",", "tuple", "(", "vector", ")" ]
Evaluates the curve normal vector at the input parameter, u. Curve normal is calculated from the 2nd derivative of the curve at the input parameter, u. The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself. :param obj: input curve :type obj: abstract.Curve :param u: parameter :type u: float :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "curve", "normal", "vector", "at", "the", "input", "parameter", "u", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L60-L81
230,341
orbingol/NURBS-Python
geomdl/_operations.py
normal_curve_single_list
def normal_curve_single_list(obj, param_list, normalize): """ Evaluates the curve normal vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = normal_curve_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
python
def normal_curve_single_list(obj, param_list, normalize): """ Evaluates the curve normal vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = normal_curve_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
[ "def", "normal_curve_single_list", "(", "obj", ",", "param_list", ",", "normalize", ")", ":", "ret_vector", "=", "[", "]", "for", "param", "in", "param_list", ":", "temp", "=", "normal_curve_single", "(", "obj", ",", "param", ",", "normalize", ")", "ret_vector", ".", "append", "(", "temp", ")", "return", "tuple", "(", "ret_vector", ")" ]
Evaluates the curve normal vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "curve", "normal", "vectors", "at", "the", "given", "list", "of", "parameter", "values", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L84-L100
230,342
orbingol/NURBS-Python
geomdl/_operations.py
binormal_curve_single
def binormal_curve_single(obj, u, normalize): """ Evaluates the curve binormal vector at the given u parameter. Curve binormal is the cross product of the normal and the tangent vectors. The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself. :param obj: input curve :type obj: abstract.Curve :param u: parameter :type u: float :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ # Cross product of tangent and normal vectors gives binormal vector tan_vector = tangent_curve_single(obj, u, normalize) norm_vector = normal_curve_single(obj, u, normalize) point = tan_vector[0] vector = linalg.vector_cross(tan_vector[1], norm_vector[1]) vector = linalg.vector_normalize(vector) if normalize else vector return tuple(point), tuple(vector)
python
def binormal_curve_single(obj, u, normalize): """ Evaluates the curve binormal vector at the given u parameter. Curve binormal is the cross product of the normal and the tangent vectors. The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself. :param obj: input curve :type obj: abstract.Curve :param u: parameter :type u: float :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ # Cross product of tangent and normal vectors gives binormal vector tan_vector = tangent_curve_single(obj, u, normalize) norm_vector = normal_curve_single(obj, u, normalize) point = tan_vector[0] vector = linalg.vector_cross(tan_vector[1], norm_vector[1]) vector = linalg.vector_normalize(vector) if normalize else vector return tuple(point), tuple(vector)
[ "def", "binormal_curve_single", "(", "obj", ",", "u", ",", "normalize", ")", ":", "# Cross product of tangent and normal vectors gives binormal vector", "tan_vector", "=", "tangent_curve_single", "(", "obj", ",", "u", ",", "normalize", ")", "norm_vector", "=", "normal_curve_single", "(", "obj", ",", "u", ",", "normalize", ")", "point", "=", "tan_vector", "[", "0", "]", "vector", "=", "linalg", ".", "vector_cross", "(", "tan_vector", "[", "1", "]", ",", "norm_vector", "[", "1", "]", ")", "vector", "=", "linalg", ".", "vector_normalize", "(", "vector", ")", "if", "normalize", "else", "vector", "return", "tuple", "(", "point", ")", ",", "tuple", "(", "vector", ")" ]
Evaluates the curve binormal vector at the given u parameter. Curve binormal is the cross product of the normal and the tangent vectors. The output returns a list containing the starting point (i.e. origin) of the vector and the vector itself. :param obj: input curve :type obj: abstract.Curve :param u: parameter :type u: float :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "curve", "binormal", "vector", "at", "the", "given", "u", "parameter", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L103-L126
230,343
orbingol/NURBS-Python
geomdl/_operations.py
binormal_curve_single_list
def binormal_curve_single_list(obj, param_list, normalize): """ Evaluates the curve binormal vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = binormal_curve_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
python
def binormal_curve_single_list(obj, param_list, normalize): """ Evaluates the curve binormal vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = binormal_curve_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
[ "def", "binormal_curve_single_list", "(", "obj", ",", "param_list", ",", "normalize", ")", ":", "ret_vector", "=", "[", "]", "for", "param", "in", "param_list", ":", "temp", "=", "binormal_curve_single", "(", "obj", ",", "param", ",", "normalize", ")", "ret_vector", ".", "append", "(", "temp", ")", "return", "tuple", "(", "ret_vector", ")" ]
Evaluates the curve binormal vectors at the given list of parameter values. :param obj: input curve :type obj: abstract.Curve :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "curve", "binormal", "vectors", "at", "the", "given", "list", "of", "parameter", "values", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L129-L145
230,344
orbingol/NURBS-Python
geomdl/_operations.py
tangent_surface_single_list
def tangent_surface_single_list(obj, param_list, normalize): """ Evaluates the surface tangent vectors at the given list of parameter values. :param obj: input surface :type obj: abstract.Surface :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = tangent_surface_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
python
def tangent_surface_single_list(obj, param_list, normalize): """ Evaluates the surface tangent vectors at the given list of parameter values. :param obj: input surface :type obj: abstract.Surface :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = tangent_surface_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
[ "def", "tangent_surface_single_list", "(", "obj", ",", "param_list", ",", "normalize", ")", ":", "ret_vector", "=", "[", "]", "for", "param", "in", "param_list", ":", "temp", "=", "tangent_surface_single", "(", "obj", ",", "param", ",", "normalize", ")", "ret_vector", ".", "append", "(", "temp", ")", "return", "tuple", "(", "ret_vector", ")" ]
Evaluates the surface tangent vectors at the given list of parameter values. :param obj: input surface :type obj: abstract.Surface :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "surface", "tangent", "vectors", "at", "the", "given", "list", "of", "parameter", "values", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L172-L188
230,345
orbingol/NURBS-Python
geomdl/_operations.py
normal_surface_single_list
def normal_surface_single_list(obj, param_list, normalize): """ Evaluates the surface normal vectors at the given list of parameter values. :param obj: input surface :type obj: abstract.Surface :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = normal_surface_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
python
def normal_surface_single_list(obj, param_list, normalize): """ Evaluates the surface normal vectors at the given list of parameter values. :param obj: input surface :type obj: abstract.Surface :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple """ ret_vector = [] for param in param_list: temp = normal_surface_single(obj, param, normalize) ret_vector.append(temp) return tuple(ret_vector)
[ "def", "normal_surface_single_list", "(", "obj", ",", "param_list", ",", "normalize", ")", ":", "ret_vector", "=", "[", "]", "for", "param", "in", "param_list", ":", "temp", "=", "normal_surface_single", "(", "obj", ",", "param", ",", "normalize", ")", "ret_vector", ".", "append", "(", "temp", ")", "return", "tuple", "(", "ret_vector", ")" ]
Evaluates the surface normal vectors at the given list of parameter values. :param obj: input surface :type obj: abstract.Surface :param param_list: parameter list :type param_list: list or tuple :param normalize: if True, the returned vector is converted to a unit vector :type normalize: bool :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "surface", "normal", "vectors", "at", "the", "given", "list", "of", "parameter", "values", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L215-L231
230,346
orbingol/NURBS-Python
geomdl/_operations.py
find_ctrlpts_curve
def find_ctrlpts_curve(t, curve, **kwargs): """ Finds the control points involved in the evaluation of the curve point defined by the input parameter. This function uses a modified version of the algorithm *A3.1 CurvePoint* from The NURBS Book by Piegl & Tiller. :param t: parameter :type t: float :param curve: input curve object :type curve: abstract.Curve :return: 1-dimensional control points array :rtype: list """ # Get keyword arguments span_func = kwargs.get('find_span_func', helpers.find_span_linear) # Find spans and the constant index span = span_func(curve.degree, curve.knotvector, len(curve.ctrlpts), t) idx = span - curve.degree # Find control points involved in evaluation of the curve point at the input parameter curve_ctrlpts = [() for _ in range(curve.degree + 1)] for i in range(0, curve.degree + 1): curve_ctrlpts[i] = curve.ctrlpts[idx + i] # Return control points array return curve_ctrlpts
python
def find_ctrlpts_curve(t, curve, **kwargs): """ Finds the control points involved in the evaluation of the curve point defined by the input parameter. This function uses a modified version of the algorithm *A3.1 CurvePoint* from The NURBS Book by Piegl & Tiller. :param t: parameter :type t: float :param curve: input curve object :type curve: abstract.Curve :return: 1-dimensional control points array :rtype: list """ # Get keyword arguments span_func = kwargs.get('find_span_func', helpers.find_span_linear) # Find spans and the constant index span = span_func(curve.degree, curve.knotvector, len(curve.ctrlpts), t) idx = span - curve.degree # Find control points involved in evaluation of the curve point at the input parameter curve_ctrlpts = [() for _ in range(curve.degree + 1)] for i in range(0, curve.degree + 1): curve_ctrlpts[i] = curve.ctrlpts[idx + i] # Return control points array return curve_ctrlpts
[ "def", "find_ctrlpts_curve", "(", "t", ",", "curve", ",", "*", "*", "kwargs", ")", ":", "# Get keyword arguments", "span_func", "=", "kwargs", ".", "get", "(", "'find_span_func'", ",", "helpers", ".", "find_span_linear", ")", "# Find spans and the constant index", "span", "=", "span_func", "(", "curve", ".", "degree", ",", "curve", ".", "knotvector", ",", "len", "(", "curve", ".", "ctrlpts", ")", ",", "t", ")", "idx", "=", "span", "-", "curve", ".", "degree", "# Find control points involved in evaluation of the curve point at the input parameter", "curve_ctrlpts", "=", "[", "(", ")", "for", "_", "in", "range", "(", "curve", ".", "degree", "+", "1", ")", "]", "for", "i", "in", "range", "(", "0", ",", "curve", ".", "degree", "+", "1", ")", ":", "curve_ctrlpts", "[", "i", "]", "=", "curve", ".", "ctrlpts", "[", "idx", "+", "i", "]", "# Return control points array", "return", "curve_ctrlpts" ]
Finds the control points involved in the evaluation of the curve point defined by the input parameter. This function uses a modified version of the algorithm *A3.1 CurvePoint* from The NURBS Book by Piegl & Tiller. :param t: parameter :type t: float :param curve: input curve object :type curve: abstract.Curve :return: 1-dimensional control points array :rtype: list
[ "Finds", "the", "control", "points", "involved", "in", "the", "evaluation", "of", "the", "curve", "point", "defined", "by", "the", "input", "parameter", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L234-L259
230,347
orbingol/NURBS-Python
geomdl/_operations.py
find_ctrlpts_surface
def find_ctrlpts_surface(t_u, t_v, surf, **kwargs): """ Finds the control points involved in the evaluation of the surface point defined by the input parameter pair. This function uses a modified version of the algorithm *A3.5 SurfacePoint* from The NURBS Book by Piegl & Tiller. :param t_u: parameter on the u-direction :type t_u: float :param t_v: parameter on the v-direction :type t_v: float :param surf: input surface :type surf: abstract.Surface :return: 2-dimensional control points array :rtype: list """ # Get keyword arguments span_func = kwargs.get('find_span_func', helpers.find_span_linear) # Find spans span_u = span_func(surf.degree_u, surf.knotvector_u, surf.ctrlpts_size_u, t_u) span_v = span_func(surf.degree_v, surf.knotvector_v, surf.ctrlpts_size_v, t_v) # Constant indices idx_u = span_u - surf.degree_u idx_v = span_v - surf.degree_v # Find control points involved in evaluation of the surface point at the input parameter pair (u, v) surf_ctrlpts = [[] for _ in range(surf.degree_u + 1)] for k in range(surf.degree_u + 1): temp = [() for _ in range(surf.degree_v + 1)] for l in range(surf.degree_v + 1): temp[l] = surf.ctrlpts2d[idx_u + k][idx_v + l] surf_ctrlpts[k] = temp # Return 2-dimensional control points array return surf_ctrlpts
python
def find_ctrlpts_surface(t_u, t_v, surf, **kwargs): """ Finds the control points involved in the evaluation of the surface point defined by the input parameter pair. This function uses a modified version of the algorithm *A3.5 SurfacePoint* from The NURBS Book by Piegl & Tiller. :param t_u: parameter on the u-direction :type t_u: float :param t_v: parameter on the v-direction :type t_v: float :param surf: input surface :type surf: abstract.Surface :return: 2-dimensional control points array :rtype: list """ # Get keyword arguments span_func = kwargs.get('find_span_func', helpers.find_span_linear) # Find spans span_u = span_func(surf.degree_u, surf.knotvector_u, surf.ctrlpts_size_u, t_u) span_v = span_func(surf.degree_v, surf.knotvector_v, surf.ctrlpts_size_v, t_v) # Constant indices idx_u = span_u - surf.degree_u idx_v = span_v - surf.degree_v # Find control points involved in evaluation of the surface point at the input parameter pair (u, v) surf_ctrlpts = [[] for _ in range(surf.degree_u + 1)] for k in range(surf.degree_u + 1): temp = [() for _ in range(surf.degree_v + 1)] for l in range(surf.degree_v + 1): temp[l] = surf.ctrlpts2d[idx_u + k][idx_v + l] surf_ctrlpts[k] = temp # Return 2-dimensional control points array return surf_ctrlpts
[ "def", "find_ctrlpts_surface", "(", "t_u", ",", "t_v", ",", "surf", ",", "*", "*", "kwargs", ")", ":", "# Get keyword arguments", "span_func", "=", "kwargs", ".", "get", "(", "'find_span_func'", ",", "helpers", ".", "find_span_linear", ")", "# Find spans", "span_u", "=", "span_func", "(", "surf", ".", "degree_u", ",", "surf", ".", "knotvector_u", ",", "surf", ".", "ctrlpts_size_u", ",", "t_u", ")", "span_v", "=", "span_func", "(", "surf", ".", "degree_v", ",", "surf", ".", "knotvector_v", ",", "surf", ".", "ctrlpts_size_v", ",", "t_v", ")", "# Constant indices", "idx_u", "=", "span_u", "-", "surf", ".", "degree_u", "idx_v", "=", "span_v", "-", "surf", ".", "degree_v", "# Find control points involved in evaluation of the surface point at the input parameter pair (u, v)", "surf_ctrlpts", "=", "[", "[", "]", "for", "_", "in", "range", "(", "surf", ".", "degree_u", "+", "1", ")", "]", "for", "k", "in", "range", "(", "surf", ".", "degree_u", "+", "1", ")", ":", "temp", "=", "[", "(", ")", "for", "_", "in", "range", "(", "surf", ".", "degree_v", "+", "1", ")", "]", "for", "l", "in", "range", "(", "surf", ".", "degree_v", "+", "1", ")", ":", "temp", "[", "l", "]", "=", "surf", ".", "ctrlpts2d", "[", "idx_u", "+", "k", "]", "[", "idx_v", "+", "l", "]", "surf_ctrlpts", "[", "k", "]", "=", "temp", "# Return 2-dimensional control points array", "return", "surf_ctrlpts" ]
Finds the control points involved in the evaluation of the surface point defined by the input parameter pair. This function uses a modified version of the algorithm *A3.5 SurfacePoint* from The NURBS Book by Piegl & Tiller. :param t_u: parameter on the u-direction :type t_u: float :param t_v: parameter on the v-direction :type t_v: float :param surf: input surface :type surf: abstract.Surface :return: 2-dimensional control points array :rtype: list
[ "Finds", "the", "control", "points", "involved", "in", "the", "evaluation", "of", "the", "surface", "point", "defined", "by", "the", "input", "parameter", "pair", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L262-L296
230,348
orbingol/NURBS-Python
geomdl/_operations.py
link_curves
def link_curves(*args, **kwargs): """ Links the input curves together. The end control point of the curve k has to be the same with the start control point of the curve k + 1. Keyword Arguments: * ``tol``: tolerance value for checking equality. *Default: 10e-8* * ``validate``: flag to enable input validation. *Default: False* :return: a tuple containing knot vector, control points, weights vector and knots """ # Get keyword arguments tol = kwargs.get('tol', 10e-8) validate = kwargs.get('validate', False) # Validate input if validate: for idx in range(len(args) - 1): if linalg.point_distance(args[idx].ctrlpts[-1], args[idx + 1].ctrlpts[0]) > tol: raise GeomdlException("Curve #" + str(idx) + " and Curve #" + str(idx + 1) + " don't touch each other") kv = [] # new knot vector cpts = [] # new control points array wgts = [] # new weights array kv_connected = [] # superfluous knots to be removed pdomain_end = 0 # Loop though the curves for arg in args: # Process knot vectors if not kv: kv += list(arg.knotvector[:-(arg.degree + 1)]) # get rid of the last superfluous knot to maintain split curve notation cpts += list(arg.ctrlpts) # Process control points if arg.rational: wgts += list(arg.weights) else: tmp_w = [1.0 for _ in range(arg.ctrlpts_size)] wgts += tmp_w else: tmp_kv = [pdomain_end + k for k in arg.knotvector[1:-(arg.degree + 1)]] kv += tmp_kv cpts += list(arg.ctrlpts[1:]) # Process control points if arg.rational: wgts += list(arg.weights[1:]) else: tmp_w = [1.0 for _ in range(arg.ctrlpts_size - 1)] wgts += tmp_w pdomain_end += arg.knotvector[-1] kv_connected.append(pdomain_end) # Fix curve by appending the last knot to the end kv += [pdomain_end for _ in range(arg.degree + 1)] # Remove the last knot from knot insertion list kv_connected.pop() return kv, cpts, wgts, kv_connected
python
def link_curves(*args, **kwargs): """ Links the input curves together. The end control point of the curve k has to be the same with the start control point of the curve k + 1. Keyword Arguments: * ``tol``: tolerance value for checking equality. *Default: 10e-8* * ``validate``: flag to enable input validation. *Default: False* :return: a tuple containing knot vector, control points, weights vector and knots """ # Get keyword arguments tol = kwargs.get('tol', 10e-8) validate = kwargs.get('validate', False) # Validate input if validate: for idx in range(len(args) - 1): if linalg.point_distance(args[idx].ctrlpts[-1], args[idx + 1].ctrlpts[0]) > tol: raise GeomdlException("Curve #" + str(idx) + " and Curve #" + str(idx + 1) + " don't touch each other") kv = [] # new knot vector cpts = [] # new control points array wgts = [] # new weights array kv_connected = [] # superfluous knots to be removed pdomain_end = 0 # Loop though the curves for arg in args: # Process knot vectors if not kv: kv += list(arg.knotvector[:-(arg.degree + 1)]) # get rid of the last superfluous knot to maintain split curve notation cpts += list(arg.ctrlpts) # Process control points if arg.rational: wgts += list(arg.weights) else: tmp_w = [1.0 for _ in range(arg.ctrlpts_size)] wgts += tmp_w else: tmp_kv = [pdomain_end + k for k in arg.knotvector[1:-(arg.degree + 1)]] kv += tmp_kv cpts += list(arg.ctrlpts[1:]) # Process control points if arg.rational: wgts += list(arg.weights[1:]) else: tmp_w = [1.0 for _ in range(arg.ctrlpts_size - 1)] wgts += tmp_w pdomain_end += arg.knotvector[-1] kv_connected.append(pdomain_end) # Fix curve by appending the last knot to the end kv += [pdomain_end for _ in range(arg.degree + 1)] # Remove the last knot from knot insertion list kv_connected.pop() return kv, cpts, wgts, kv_connected
[ "def", "link_curves", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Get keyword arguments", "tol", "=", "kwargs", ".", "get", "(", "'tol'", ",", "10e-8", ")", "validate", "=", "kwargs", ".", "get", "(", "'validate'", ",", "False", ")", "# Validate input", "if", "validate", ":", "for", "idx", "in", "range", "(", "len", "(", "args", ")", "-", "1", ")", ":", "if", "linalg", ".", "point_distance", "(", "args", "[", "idx", "]", ".", "ctrlpts", "[", "-", "1", "]", ",", "args", "[", "idx", "+", "1", "]", ".", "ctrlpts", "[", "0", "]", ")", ">", "tol", ":", "raise", "GeomdlException", "(", "\"Curve #\"", "+", "str", "(", "idx", ")", "+", "\" and Curve #\"", "+", "str", "(", "idx", "+", "1", ")", "+", "\" don't touch each other\"", ")", "kv", "=", "[", "]", "# new knot vector", "cpts", "=", "[", "]", "# new control points array", "wgts", "=", "[", "]", "# new weights array", "kv_connected", "=", "[", "]", "# superfluous knots to be removed", "pdomain_end", "=", "0", "# Loop though the curves", "for", "arg", "in", "args", ":", "# Process knot vectors", "if", "not", "kv", ":", "kv", "+=", "list", "(", "arg", ".", "knotvector", "[", ":", "-", "(", "arg", ".", "degree", "+", "1", ")", "]", ")", "# get rid of the last superfluous knot to maintain split curve notation", "cpts", "+=", "list", "(", "arg", ".", "ctrlpts", ")", "# Process control points", "if", "arg", ".", "rational", ":", "wgts", "+=", "list", "(", "arg", ".", "weights", ")", "else", ":", "tmp_w", "=", "[", "1.0", "for", "_", "in", "range", "(", "arg", ".", "ctrlpts_size", ")", "]", "wgts", "+=", "tmp_w", "else", ":", "tmp_kv", "=", "[", "pdomain_end", "+", "k", "for", "k", "in", "arg", ".", "knotvector", "[", "1", ":", "-", "(", "arg", ".", "degree", "+", "1", ")", "]", "]", "kv", "+=", "tmp_kv", "cpts", "+=", "list", "(", "arg", ".", "ctrlpts", "[", "1", ":", "]", ")", "# Process control points", "if", "arg", ".", "rational", ":", "wgts", "+=", "list", "(", "arg", ".", "weights", "[", "1", ":", "]", ")", "else", ":", "tmp_w", "=", "[", "1.0", "for", "_", "in", "range", "(", "arg", ".", "ctrlpts_size", "-", "1", ")", "]", "wgts", "+=", "tmp_w", "pdomain_end", "+=", "arg", ".", "knotvector", "[", "-", "1", "]", "kv_connected", ".", "append", "(", "pdomain_end", ")", "# Fix curve by appending the last knot to the end", "kv", "+=", "[", "pdomain_end", "for", "_", "in", "range", "(", "arg", ".", "degree", "+", "1", ")", "]", "# Remove the last knot from knot insertion list", "kv_connected", ".", "pop", "(", ")", "return", "kv", ",", "cpts", ",", "wgts", ",", "kv_connected" ]
Links the input curves together. The end control point of the curve k has to be the same with the start control point of the curve k + 1. Keyword Arguments: * ``tol``: tolerance value for checking equality. *Default: 10e-8* * ``validate``: flag to enable input validation. *Default: False* :return: a tuple containing knot vector, control points, weights vector and knots
[ "Links", "the", "input", "curves", "together", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_operations.py#L299-L357
230,349
orbingol/NURBS-Python
geomdl/operations.py
add_dimension
def add_dimension(obj, **kwargs): """ Elevates the spatial dimension of the spline geometry. If you pass ``inplace=True`` keyword argument, the input will be updated. Otherwise, this function does not change the input but returns a new instance with the updated data. :param obj: spline geometry :type obj: abstract.SplineGeometry :return: updated spline geometry :rtype: abstract.SplineGeometry """ if not isinstance(obj, abstract.SplineGeometry): raise GeomdlException("Can only operate on spline geometry objects") # Keyword arguments inplace = kwargs.get('inplace', False) array_init = kwargs.get('array_init', [[] for _ in range(len(obj.ctrlpts))]) offset_value = kwargs.get('offset', 0.0) # Update control points new_ctrlpts = array_init for idx, point in enumerate(obj.ctrlpts): temp = [float(p) for p in point[0:obj.dimension]] temp.append(offset_value) new_ctrlpts[idx] = temp if inplace: obj.ctrlpts = new_ctrlpts return obj else: ret = copy.deepcopy(obj) ret.ctrlpts = new_ctrlpts return ret
python
def add_dimension(obj, **kwargs): """ Elevates the spatial dimension of the spline geometry. If you pass ``inplace=True`` keyword argument, the input will be updated. Otherwise, this function does not change the input but returns a new instance with the updated data. :param obj: spline geometry :type obj: abstract.SplineGeometry :return: updated spline geometry :rtype: abstract.SplineGeometry """ if not isinstance(obj, abstract.SplineGeometry): raise GeomdlException("Can only operate on spline geometry objects") # Keyword arguments inplace = kwargs.get('inplace', False) array_init = kwargs.get('array_init', [[] for _ in range(len(obj.ctrlpts))]) offset_value = kwargs.get('offset', 0.0) # Update control points new_ctrlpts = array_init for idx, point in enumerate(obj.ctrlpts): temp = [float(p) for p in point[0:obj.dimension]] temp.append(offset_value) new_ctrlpts[idx] = temp if inplace: obj.ctrlpts = new_ctrlpts return obj else: ret = copy.deepcopy(obj) ret.ctrlpts = new_ctrlpts return ret
[ "def", "add_dimension", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "abstract", ".", "SplineGeometry", ")", ":", "raise", "GeomdlException", "(", "\"Can only operate on spline geometry objects\"", ")", "# Keyword arguments", "inplace", "=", "kwargs", ".", "get", "(", "'inplace'", ",", "False", ")", "array_init", "=", "kwargs", ".", "get", "(", "'array_init'", ",", "[", "[", "]", "for", "_", "in", "range", "(", "len", "(", "obj", ".", "ctrlpts", ")", ")", "]", ")", "offset_value", "=", "kwargs", ".", "get", "(", "'offset'", ",", "0.0", ")", "# Update control points", "new_ctrlpts", "=", "array_init", "for", "idx", ",", "point", "in", "enumerate", "(", "obj", ".", "ctrlpts", ")", ":", "temp", "=", "[", "float", "(", "p", ")", "for", "p", "in", "point", "[", "0", ":", "obj", ".", "dimension", "]", "]", "temp", ".", "append", "(", "offset_value", ")", "new_ctrlpts", "[", "idx", "]", "=", "temp", "if", "inplace", ":", "obj", ".", "ctrlpts", "=", "new_ctrlpts", "return", "obj", "else", ":", "ret", "=", "copy", ".", "deepcopy", "(", "obj", ")", "ret", ".", "ctrlpts", "=", "new_ctrlpts", "return", "ret" ]
Elevates the spatial dimension of the spline geometry. If you pass ``inplace=True`` keyword argument, the input will be updated. Otherwise, this function does not change the input but returns a new instance with the updated data. :param obj: spline geometry :type obj: abstract.SplineGeometry :return: updated spline geometry :rtype: abstract.SplineGeometry
[ "Elevates", "the", "spatial", "dimension", "of", "the", "spline", "geometry", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L877-L909
230,350
orbingol/NURBS-Python
geomdl/operations.py
split_curve
def split_curve(obj, param, **kwargs): """ Splits the curve at the input parametric coordinate. This method splits the curve into two pieces at the given parametric coordinate, generates two different curve objects and returns them. It does not modify the input curve. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: Curve to be split :type obj: abstract.Curve :param param: parameter :type param: float :return: a list of curve segments :rtype: list """ # Validate input if not isinstance(obj, abstract.Curve): raise GeomdlException("Input shape must be an instance of abstract.Curve class") if param == obj.knotvector[0] or param == obj.knotvector[-1]: raise GeomdlException("Cannot split on the corner points") # Keyword arguments span_func = kwargs.get('find_span_func', helpers.find_span_linear) # FindSpan implementation insert_knot_func = kwargs.get('insert_knot_func', insert_knot) # Knot insertion algorithm # Find multiplicity of the knot and define how many times we need to add the knot ks = span_func(obj.degree, obj.knotvector, len(obj.ctrlpts), param) - obj.degree + 1 s = helpers.find_multiplicity(param, obj.knotvector) r = obj.degree - s # Create backups of the original curve temp_obj = copy.deepcopy(obj) # Insert knot insert_knot_func(temp_obj, [param], num=[r], check_num=False) # Knot vectors knot_span = span_func(temp_obj.degree, temp_obj.knotvector, len(temp_obj.ctrlpts), param) + 1 curve1_kv = list(temp_obj.knotvector[0:knot_span]) curve1_kv.append(param) curve2_kv = list(temp_obj.knotvector[knot_span:]) for _ in range(0, temp_obj.degree + 1): curve2_kv.insert(0, param) # Control points (use Pw if rational) cpts = temp_obj.ctrlptsw if obj.rational else temp_obj.ctrlpts curve1_ctrlpts = cpts[0:ks + r] curve2_ctrlpts = cpts[ks + r - 1:] # Create a new curve for the first half curve1 = temp_obj.__class__() curve1.degree = temp_obj.degree curve1.set_ctrlpts(curve1_ctrlpts) curve1.knotvector = curve1_kv # Create another curve fot the second half curve2 = temp_obj.__class__() curve2.degree = temp_obj.degree curve2.set_ctrlpts(curve2_ctrlpts) curve2.knotvector = curve2_kv # Return the split curves ret_val = [curve1, curve2] return ret_val
python
def split_curve(obj, param, **kwargs): """ Splits the curve at the input parametric coordinate. This method splits the curve into two pieces at the given parametric coordinate, generates two different curve objects and returns them. It does not modify the input curve. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: Curve to be split :type obj: abstract.Curve :param param: parameter :type param: float :return: a list of curve segments :rtype: list """ # Validate input if not isinstance(obj, abstract.Curve): raise GeomdlException("Input shape must be an instance of abstract.Curve class") if param == obj.knotvector[0] or param == obj.knotvector[-1]: raise GeomdlException("Cannot split on the corner points") # Keyword arguments span_func = kwargs.get('find_span_func', helpers.find_span_linear) # FindSpan implementation insert_knot_func = kwargs.get('insert_knot_func', insert_knot) # Knot insertion algorithm # Find multiplicity of the knot and define how many times we need to add the knot ks = span_func(obj.degree, obj.knotvector, len(obj.ctrlpts), param) - obj.degree + 1 s = helpers.find_multiplicity(param, obj.knotvector) r = obj.degree - s # Create backups of the original curve temp_obj = copy.deepcopy(obj) # Insert knot insert_knot_func(temp_obj, [param], num=[r], check_num=False) # Knot vectors knot_span = span_func(temp_obj.degree, temp_obj.knotvector, len(temp_obj.ctrlpts), param) + 1 curve1_kv = list(temp_obj.knotvector[0:knot_span]) curve1_kv.append(param) curve2_kv = list(temp_obj.knotvector[knot_span:]) for _ in range(0, temp_obj.degree + 1): curve2_kv.insert(0, param) # Control points (use Pw if rational) cpts = temp_obj.ctrlptsw if obj.rational else temp_obj.ctrlpts curve1_ctrlpts = cpts[0:ks + r] curve2_ctrlpts = cpts[ks + r - 1:] # Create a new curve for the first half curve1 = temp_obj.__class__() curve1.degree = temp_obj.degree curve1.set_ctrlpts(curve1_ctrlpts) curve1.knotvector = curve1_kv # Create another curve fot the second half curve2 = temp_obj.__class__() curve2.degree = temp_obj.degree curve2.set_ctrlpts(curve2_ctrlpts) curve2.knotvector = curve2_kv # Return the split curves ret_val = [curve1, curve2] return ret_val
[ "def", "split_curve", "(", "obj", ",", "param", ",", "*", "*", "kwargs", ")", ":", "# Validate input", "if", "not", "isinstance", "(", "obj", ",", "abstract", ".", "Curve", ")", ":", "raise", "GeomdlException", "(", "\"Input shape must be an instance of abstract.Curve class\"", ")", "if", "param", "==", "obj", ".", "knotvector", "[", "0", "]", "or", "param", "==", "obj", ".", "knotvector", "[", "-", "1", "]", ":", "raise", "GeomdlException", "(", "\"Cannot split on the corner points\"", ")", "# Keyword arguments", "span_func", "=", "kwargs", ".", "get", "(", "'find_span_func'", ",", "helpers", ".", "find_span_linear", ")", "# FindSpan implementation", "insert_knot_func", "=", "kwargs", ".", "get", "(", "'insert_knot_func'", ",", "insert_knot", ")", "# Knot insertion algorithm", "# Find multiplicity of the knot and define how many times we need to add the knot", "ks", "=", "span_func", "(", "obj", ".", "degree", ",", "obj", ".", "knotvector", ",", "len", "(", "obj", ".", "ctrlpts", ")", ",", "param", ")", "-", "obj", ".", "degree", "+", "1", "s", "=", "helpers", ".", "find_multiplicity", "(", "param", ",", "obj", ".", "knotvector", ")", "r", "=", "obj", ".", "degree", "-", "s", "# Create backups of the original curve", "temp_obj", "=", "copy", ".", "deepcopy", "(", "obj", ")", "# Insert knot", "insert_knot_func", "(", "temp_obj", ",", "[", "param", "]", ",", "num", "=", "[", "r", "]", ",", "check_num", "=", "False", ")", "# Knot vectors", "knot_span", "=", "span_func", "(", "temp_obj", ".", "degree", ",", "temp_obj", ".", "knotvector", ",", "len", "(", "temp_obj", ".", "ctrlpts", ")", ",", "param", ")", "+", "1", "curve1_kv", "=", "list", "(", "temp_obj", ".", "knotvector", "[", "0", ":", "knot_span", "]", ")", "curve1_kv", ".", "append", "(", "param", ")", "curve2_kv", "=", "list", "(", "temp_obj", ".", "knotvector", "[", "knot_span", ":", "]", ")", "for", "_", "in", "range", "(", "0", ",", "temp_obj", ".", "degree", "+", "1", ")", ":", "curve2_kv", ".", "insert", "(", "0", ",", "param", ")", "# Control points (use Pw if rational)", "cpts", "=", "temp_obj", ".", "ctrlptsw", "if", "obj", ".", "rational", "else", "temp_obj", ".", "ctrlpts", "curve1_ctrlpts", "=", "cpts", "[", "0", ":", "ks", "+", "r", "]", "curve2_ctrlpts", "=", "cpts", "[", "ks", "+", "r", "-", "1", ":", "]", "# Create a new curve for the first half", "curve1", "=", "temp_obj", ".", "__class__", "(", ")", "curve1", ".", "degree", "=", "temp_obj", ".", "degree", "curve1", ".", "set_ctrlpts", "(", "curve1_ctrlpts", ")", "curve1", ".", "knotvector", "=", "curve1_kv", "# Create another curve fot the second half", "curve2", "=", "temp_obj", ".", "__class__", "(", ")", "curve2", ".", "degree", "=", "temp_obj", ".", "degree", "curve2", ".", "set_ctrlpts", "(", "curve2_ctrlpts", ")", "curve2", ".", "knotvector", "=", "curve2_kv", "# Return the split curves", "ret_val", "=", "[", "curve1", ",", "curve2", "]", "return", "ret_val" ]
Splits the curve at the input parametric coordinate. This method splits the curve into two pieces at the given parametric coordinate, generates two different curve objects and returns them. It does not modify the input curve. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: Curve to be split :type obj: abstract.Curve :param param: parameter :type param: float :return: a list of curve segments :rtype: list
[ "Splits", "the", "curve", "at", "the", "input", "parametric", "coordinate", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L913-L979
230,351
orbingol/NURBS-Python
geomdl/operations.py
decompose_curve
def decompose_curve(obj, **kwargs): """ Decomposes the curve into Bezier curve segments of the same degree. This operation does not modify the input curve, instead it returns the split curve segments. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: Curve to be decomposed :type obj: abstract.Curve :return: a list of Bezier segments :rtype: list """ if not isinstance(obj, abstract.Curve): raise GeomdlException("Input shape must be an instance of abstract.Curve class") multi_curve = [] curve = copy.deepcopy(obj) knots = curve.knotvector[curve.degree + 1:-(curve.degree + 1)] while knots: knot = knots[0] curves = split_curve(curve, param=knot, **kwargs) multi_curve.append(curves[0]) curve = curves[1] knots = curve.knotvector[curve.degree + 1:-(curve.degree + 1)] multi_curve.append(curve) return multi_curve
python
def decompose_curve(obj, **kwargs): """ Decomposes the curve into Bezier curve segments of the same degree. This operation does not modify the input curve, instead it returns the split curve segments. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: Curve to be decomposed :type obj: abstract.Curve :return: a list of Bezier segments :rtype: list """ if not isinstance(obj, abstract.Curve): raise GeomdlException("Input shape must be an instance of abstract.Curve class") multi_curve = [] curve = copy.deepcopy(obj) knots = curve.knotvector[curve.degree + 1:-(curve.degree + 1)] while knots: knot = knots[0] curves = split_curve(curve, param=knot, **kwargs) multi_curve.append(curves[0]) curve = curves[1] knots = curve.knotvector[curve.degree + 1:-(curve.degree + 1)] multi_curve.append(curve) return multi_curve
[ "def", "decompose_curve", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "abstract", ".", "Curve", ")", ":", "raise", "GeomdlException", "(", "\"Input shape must be an instance of abstract.Curve class\"", ")", "multi_curve", "=", "[", "]", "curve", "=", "copy", ".", "deepcopy", "(", "obj", ")", "knots", "=", "curve", ".", "knotvector", "[", "curve", ".", "degree", "+", "1", ":", "-", "(", "curve", ".", "degree", "+", "1", ")", "]", "while", "knots", ":", "knot", "=", "knots", "[", "0", "]", "curves", "=", "split_curve", "(", "curve", ",", "param", "=", "knot", ",", "*", "*", "kwargs", ")", "multi_curve", ".", "append", "(", "curves", "[", "0", "]", ")", "curve", "=", "curves", "[", "1", "]", "knots", "=", "curve", ".", "knotvector", "[", "curve", ".", "degree", "+", "1", ":", "-", "(", "curve", ".", "degree", "+", "1", ")", "]", "multi_curve", ".", "append", "(", "curve", ")", "return", "multi_curve" ]
Decomposes the curve into Bezier curve segments of the same degree. This operation does not modify the input curve, instead it returns the split curve segments. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: Curve to be decomposed :type obj: abstract.Curve :return: a list of Bezier segments :rtype: list
[ "Decomposes", "the", "curve", "into", "Bezier", "curve", "segments", "of", "the", "same", "degree", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L983-L1011
230,352
orbingol/NURBS-Python
geomdl/operations.py
length_curve
def length_curve(obj): """ Computes the approximate length of the parametric curve. Uses the following equation to compute the approximate length: .. math:: \\sum_{i=0}^{n-1} \\sqrt{P_{i + 1}^2-P_{i}^2} where :math:`n` is number of evaluated curve points and :math:`P` is the n-dimensional point. :param obj: input curve :type obj: abstract.Curve :return: length :rtype: float """ if not isinstance(obj, abstract.Curve): raise GeomdlException("Input shape must be an instance of abstract.Curve class") length = 0.0 evalpts = obj.evalpts num_evalpts = len(obj.evalpts) for idx in range(num_evalpts - 1): length += linalg.point_distance(evalpts[idx], evalpts[idx + 1]) return length
python
def length_curve(obj): """ Computes the approximate length of the parametric curve. Uses the following equation to compute the approximate length: .. math:: \\sum_{i=0}^{n-1} \\sqrt{P_{i + 1}^2-P_{i}^2} where :math:`n` is number of evaluated curve points and :math:`P` is the n-dimensional point. :param obj: input curve :type obj: abstract.Curve :return: length :rtype: float """ if not isinstance(obj, abstract.Curve): raise GeomdlException("Input shape must be an instance of abstract.Curve class") length = 0.0 evalpts = obj.evalpts num_evalpts = len(obj.evalpts) for idx in range(num_evalpts - 1): length += linalg.point_distance(evalpts[idx], evalpts[idx + 1]) return length
[ "def", "length_curve", "(", "obj", ")", ":", "if", "not", "isinstance", "(", "obj", ",", "abstract", ".", "Curve", ")", ":", "raise", "GeomdlException", "(", "\"Input shape must be an instance of abstract.Curve class\"", ")", "length", "=", "0.0", "evalpts", "=", "obj", ".", "evalpts", "num_evalpts", "=", "len", "(", "obj", ".", "evalpts", ")", "for", "idx", "in", "range", "(", "num_evalpts", "-", "1", ")", ":", "length", "+=", "linalg", ".", "point_distance", "(", "evalpts", "[", "idx", "]", ",", "evalpts", "[", "idx", "+", "1", "]", ")", "return", "length" ]
Computes the approximate length of the parametric curve. Uses the following equation to compute the approximate length: .. math:: \\sum_{i=0}^{n-1} \\sqrt{P_{i + 1}^2-P_{i}^2} where :math:`n` is number of evaluated curve points and :math:`P` is the n-dimensional point. :param obj: input curve :type obj: abstract.Curve :return: length :rtype: float
[ "Computes", "the", "approximate", "length", "of", "the", "parametric", "curve", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1054-L1078
230,353
orbingol/NURBS-Python
geomdl/operations.py
split_surface_u
def split_surface_u(obj, param, **kwargs): """ Splits the surface at the input parametric coordinate on the u-direction. This method splits the surface into two pieces at the given parametric coordinate on the u-direction, generates two different surface objects and returns them. It does not modify the input surface. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: surface :type obj: abstract.Surface :param param: parameter for the u-direction :type param: float :return: a list of surface patches :rtype: list """ # Validate input if not isinstance(obj, abstract.Surface): raise GeomdlException("Input shape must be an instance of abstract.Surface class") if param == obj.knotvector_u[0] or param == obj.knotvector_u[-1]: raise GeomdlException("Cannot split on the edge") # Keyword arguments span_func = kwargs.get('find_span_func', helpers.find_span_linear) # FindSpan implementation insert_knot_func = kwargs.get('insert_knot_func', insert_knot) # Knot insertion algorithm # Find multiplicity of the knot ks = span_func(obj.degree_u, obj.knotvector_u, obj.ctrlpts_size_u, param) - obj.degree_u + 1 s = helpers.find_multiplicity(param, obj.knotvector_u) r = obj.degree_u - s # Create backups of the original surface temp_obj = copy.deepcopy(obj) # Split the original surface insert_knot_func(temp_obj, [param, None], num=[r, 0], check_num=False) # Knot vectors knot_span = span_func(temp_obj.degree_u, temp_obj.knotvector_u, temp_obj.ctrlpts_size_u, param) + 1 surf1_kv = list(temp_obj.knotvector_u[0:knot_span]) surf1_kv.append(param) surf2_kv = list(temp_obj.knotvector_u[knot_span:]) for _ in range(0, temp_obj.degree_u + 1): surf2_kv.insert(0, param) # Control points surf1_ctrlpts = temp_obj.ctrlpts2d[0:ks + r] surf2_ctrlpts = temp_obj.ctrlpts2d[ks + r - 1:] # Create a new surface for the first half surf1 = temp_obj.__class__() surf1.degree_u = temp_obj.degree_u surf1.degree_v = temp_obj.degree_v surf1.ctrlpts2d = surf1_ctrlpts surf1.knotvector_u = surf1_kv surf1.knotvector_v = temp_obj.knotvector_v # Create another surface fot the second half surf2 = temp_obj.__class__() surf2.degree_u = temp_obj.degree_u surf2.degree_v = temp_obj.degree_v surf2.ctrlpts2d = surf2_ctrlpts surf2.knotvector_u = surf2_kv surf2.knotvector_v = temp_obj.knotvector_v # Return the new surfaces ret_val = [surf1, surf2] return ret_val
python
def split_surface_u(obj, param, **kwargs): """ Splits the surface at the input parametric coordinate on the u-direction. This method splits the surface into two pieces at the given parametric coordinate on the u-direction, generates two different surface objects and returns them. It does not modify the input surface. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: surface :type obj: abstract.Surface :param param: parameter for the u-direction :type param: float :return: a list of surface patches :rtype: list """ # Validate input if not isinstance(obj, abstract.Surface): raise GeomdlException("Input shape must be an instance of abstract.Surface class") if param == obj.knotvector_u[0] or param == obj.knotvector_u[-1]: raise GeomdlException("Cannot split on the edge") # Keyword arguments span_func = kwargs.get('find_span_func', helpers.find_span_linear) # FindSpan implementation insert_knot_func = kwargs.get('insert_knot_func', insert_knot) # Knot insertion algorithm # Find multiplicity of the knot ks = span_func(obj.degree_u, obj.knotvector_u, obj.ctrlpts_size_u, param) - obj.degree_u + 1 s = helpers.find_multiplicity(param, obj.knotvector_u) r = obj.degree_u - s # Create backups of the original surface temp_obj = copy.deepcopy(obj) # Split the original surface insert_knot_func(temp_obj, [param, None], num=[r, 0], check_num=False) # Knot vectors knot_span = span_func(temp_obj.degree_u, temp_obj.knotvector_u, temp_obj.ctrlpts_size_u, param) + 1 surf1_kv = list(temp_obj.knotvector_u[0:knot_span]) surf1_kv.append(param) surf2_kv = list(temp_obj.knotvector_u[knot_span:]) for _ in range(0, temp_obj.degree_u + 1): surf2_kv.insert(0, param) # Control points surf1_ctrlpts = temp_obj.ctrlpts2d[0:ks + r] surf2_ctrlpts = temp_obj.ctrlpts2d[ks + r - 1:] # Create a new surface for the first half surf1 = temp_obj.__class__() surf1.degree_u = temp_obj.degree_u surf1.degree_v = temp_obj.degree_v surf1.ctrlpts2d = surf1_ctrlpts surf1.knotvector_u = surf1_kv surf1.knotvector_v = temp_obj.knotvector_v # Create another surface fot the second half surf2 = temp_obj.__class__() surf2.degree_u = temp_obj.degree_u surf2.degree_v = temp_obj.degree_v surf2.ctrlpts2d = surf2_ctrlpts surf2.knotvector_u = surf2_kv surf2.knotvector_v = temp_obj.knotvector_v # Return the new surfaces ret_val = [surf1, surf2] return ret_val
[ "def", "split_surface_u", "(", "obj", ",", "param", ",", "*", "*", "kwargs", ")", ":", "# Validate input", "if", "not", "isinstance", "(", "obj", ",", "abstract", ".", "Surface", ")", ":", "raise", "GeomdlException", "(", "\"Input shape must be an instance of abstract.Surface class\"", ")", "if", "param", "==", "obj", ".", "knotvector_u", "[", "0", "]", "or", "param", "==", "obj", ".", "knotvector_u", "[", "-", "1", "]", ":", "raise", "GeomdlException", "(", "\"Cannot split on the edge\"", ")", "# Keyword arguments", "span_func", "=", "kwargs", ".", "get", "(", "'find_span_func'", ",", "helpers", ".", "find_span_linear", ")", "# FindSpan implementation", "insert_knot_func", "=", "kwargs", ".", "get", "(", "'insert_knot_func'", ",", "insert_knot", ")", "# Knot insertion algorithm", "# Find multiplicity of the knot", "ks", "=", "span_func", "(", "obj", ".", "degree_u", ",", "obj", ".", "knotvector_u", ",", "obj", ".", "ctrlpts_size_u", ",", "param", ")", "-", "obj", ".", "degree_u", "+", "1", "s", "=", "helpers", ".", "find_multiplicity", "(", "param", ",", "obj", ".", "knotvector_u", ")", "r", "=", "obj", ".", "degree_u", "-", "s", "# Create backups of the original surface", "temp_obj", "=", "copy", ".", "deepcopy", "(", "obj", ")", "# Split the original surface", "insert_knot_func", "(", "temp_obj", ",", "[", "param", ",", "None", "]", ",", "num", "=", "[", "r", ",", "0", "]", ",", "check_num", "=", "False", ")", "# Knot vectors", "knot_span", "=", "span_func", "(", "temp_obj", ".", "degree_u", ",", "temp_obj", ".", "knotvector_u", ",", "temp_obj", ".", "ctrlpts_size_u", ",", "param", ")", "+", "1", "surf1_kv", "=", "list", "(", "temp_obj", ".", "knotvector_u", "[", "0", ":", "knot_span", "]", ")", "surf1_kv", ".", "append", "(", "param", ")", "surf2_kv", "=", "list", "(", "temp_obj", ".", "knotvector_u", "[", "knot_span", ":", "]", ")", "for", "_", "in", "range", "(", "0", ",", "temp_obj", ".", "degree_u", "+", "1", ")", ":", "surf2_kv", ".", "insert", "(", "0", ",", "param", ")", "# Control points", "surf1_ctrlpts", "=", "temp_obj", ".", "ctrlpts2d", "[", "0", ":", "ks", "+", "r", "]", "surf2_ctrlpts", "=", "temp_obj", ".", "ctrlpts2d", "[", "ks", "+", "r", "-", "1", ":", "]", "# Create a new surface for the first half", "surf1", "=", "temp_obj", ".", "__class__", "(", ")", "surf1", ".", "degree_u", "=", "temp_obj", ".", "degree_u", "surf1", ".", "degree_v", "=", "temp_obj", ".", "degree_v", "surf1", ".", "ctrlpts2d", "=", "surf1_ctrlpts", "surf1", ".", "knotvector_u", "=", "surf1_kv", "surf1", ".", "knotvector_v", "=", "temp_obj", ".", "knotvector_v", "# Create another surface fot the second half", "surf2", "=", "temp_obj", ".", "__class__", "(", ")", "surf2", ".", "degree_u", "=", "temp_obj", ".", "degree_u", "surf2", ".", "degree_v", "=", "temp_obj", ".", "degree_v", "surf2", ".", "ctrlpts2d", "=", "surf2_ctrlpts", "surf2", ".", "knotvector_u", "=", "surf2_kv", "surf2", ".", "knotvector_v", "=", "temp_obj", ".", "knotvector_v", "# Return the new surfaces", "ret_val", "=", "[", "surf1", ",", "surf2", "]", "return", "ret_val" ]
Splits the surface at the input parametric coordinate on the u-direction. This method splits the surface into two pieces at the given parametric coordinate on the u-direction, generates two different surface objects and returns them. It does not modify the input surface. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: surface :type obj: abstract.Surface :param param: parameter for the u-direction :type param: float :return: a list of surface patches :rtype: list
[ "Splits", "the", "surface", "at", "the", "input", "parametric", "coordinate", "on", "the", "u", "-", "direction", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1082-L1151
230,354
orbingol/NURBS-Python
geomdl/operations.py
decompose_surface
def decompose_surface(obj, **kwargs): """ Decomposes the surface into Bezier surface patches of the same degree. This operation does not modify the input surface, instead it returns the surface patches. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: surface :type obj: abstract.Surface :return: a list of Bezier patches :rtype: list """ def decompose(srf, idx, split_func_list, **kws): srf_list = [] knots = srf.knotvector[idx][srf.degree[idx] + 1:-(srf.degree[idx] + 1)] while knots: knot = knots[0] srfs = split_func_list[idx](srf, param=knot, **kws) srf_list.append(srfs[0]) srf = srfs[1] knots = srf.knotvector[idx][srf.degree[idx] + 1:-(srf.degree[idx] + 1)] srf_list.append(srf) return srf_list # Validate input if not isinstance(obj, abstract.Surface): raise GeomdlException("Input shape must be an instance of abstract.Surface class") # Get keyword arguments decompose_dir = kwargs.get('decompose_dir', 'uv') # possible directions: u, v, uv if "decompose_dir" in kwargs: kwargs.pop("decompose_dir") # List of split functions split_funcs = [split_surface_u, split_surface_v] # Work with an identical copy surf = copy.deepcopy(obj) # Only u-direction if decompose_dir == 'u': return decompose(surf, 0, split_funcs, **kwargs) # Only v-direction if decompose_dir == 'v': return decompose(surf, 1, split_funcs, **kwargs) # Both u- and v-directions if decompose_dir == 'uv': multi_surf = [] # Process u-direction surfs_u = decompose(surf, 0, split_funcs, **kwargs) # Process v-direction for sfu in surfs_u: multi_surf += decompose(sfu, 1, split_funcs, **kwargs) return multi_surf else: raise GeomdlException("Cannot decompose in " + str(decompose_dir) + " direction. Acceptable values: u, v, uv")
python
def decompose_surface(obj, **kwargs): """ Decomposes the surface into Bezier surface patches of the same degree. This operation does not modify the input surface, instead it returns the surface patches. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: surface :type obj: abstract.Surface :return: a list of Bezier patches :rtype: list """ def decompose(srf, idx, split_func_list, **kws): srf_list = [] knots = srf.knotvector[idx][srf.degree[idx] + 1:-(srf.degree[idx] + 1)] while knots: knot = knots[0] srfs = split_func_list[idx](srf, param=knot, **kws) srf_list.append(srfs[0]) srf = srfs[1] knots = srf.knotvector[idx][srf.degree[idx] + 1:-(srf.degree[idx] + 1)] srf_list.append(srf) return srf_list # Validate input if not isinstance(obj, abstract.Surface): raise GeomdlException("Input shape must be an instance of abstract.Surface class") # Get keyword arguments decompose_dir = kwargs.get('decompose_dir', 'uv') # possible directions: u, v, uv if "decompose_dir" in kwargs: kwargs.pop("decompose_dir") # List of split functions split_funcs = [split_surface_u, split_surface_v] # Work with an identical copy surf = copy.deepcopy(obj) # Only u-direction if decompose_dir == 'u': return decompose(surf, 0, split_funcs, **kwargs) # Only v-direction if decompose_dir == 'v': return decompose(surf, 1, split_funcs, **kwargs) # Both u- and v-directions if decompose_dir == 'uv': multi_surf = [] # Process u-direction surfs_u = decompose(surf, 0, split_funcs, **kwargs) # Process v-direction for sfu in surfs_u: multi_surf += decompose(sfu, 1, split_funcs, **kwargs) return multi_surf else: raise GeomdlException("Cannot decompose in " + str(decompose_dir) + " direction. Acceptable values: u, v, uv")
[ "def", "decompose_surface", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "def", "decompose", "(", "srf", ",", "idx", ",", "split_func_list", ",", "*", "*", "kws", ")", ":", "srf_list", "=", "[", "]", "knots", "=", "srf", ".", "knotvector", "[", "idx", "]", "[", "srf", ".", "degree", "[", "idx", "]", "+", "1", ":", "-", "(", "srf", ".", "degree", "[", "idx", "]", "+", "1", ")", "]", "while", "knots", ":", "knot", "=", "knots", "[", "0", "]", "srfs", "=", "split_func_list", "[", "idx", "]", "(", "srf", ",", "param", "=", "knot", ",", "*", "*", "kws", ")", "srf_list", ".", "append", "(", "srfs", "[", "0", "]", ")", "srf", "=", "srfs", "[", "1", "]", "knots", "=", "srf", ".", "knotvector", "[", "idx", "]", "[", "srf", ".", "degree", "[", "idx", "]", "+", "1", ":", "-", "(", "srf", ".", "degree", "[", "idx", "]", "+", "1", ")", "]", "srf_list", ".", "append", "(", "srf", ")", "return", "srf_list", "# Validate input", "if", "not", "isinstance", "(", "obj", ",", "abstract", ".", "Surface", ")", ":", "raise", "GeomdlException", "(", "\"Input shape must be an instance of abstract.Surface class\"", ")", "# Get keyword arguments", "decompose_dir", "=", "kwargs", ".", "get", "(", "'decompose_dir'", ",", "'uv'", ")", "# possible directions: u, v, uv", "if", "\"decompose_dir\"", "in", "kwargs", ":", "kwargs", ".", "pop", "(", "\"decompose_dir\"", ")", "# List of split functions", "split_funcs", "=", "[", "split_surface_u", ",", "split_surface_v", "]", "# Work with an identical copy", "surf", "=", "copy", ".", "deepcopy", "(", "obj", ")", "# Only u-direction", "if", "decompose_dir", "==", "'u'", ":", "return", "decompose", "(", "surf", ",", "0", ",", "split_funcs", ",", "*", "*", "kwargs", ")", "# Only v-direction", "if", "decompose_dir", "==", "'v'", ":", "return", "decompose", "(", "surf", ",", "1", ",", "split_funcs", ",", "*", "*", "kwargs", ")", "# Both u- and v-directions", "if", "decompose_dir", "==", "'uv'", ":", "multi_surf", "=", "[", "]", "# Process u-direction", "surfs_u", "=", "decompose", "(", "surf", ",", "0", ",", "split_funcs", ",", "*", "*", "kwargs", ")", "# Process v-direction", "for", "sfu", "in", "surfs_u", ":", "multi_surf", "+=", "decompose", "(", "sfu", ",", "1", ",", "split_funcs", ",", "*", "*", "kwargs", ")", "return", "multi_surf", "else", ":", "raise", "GeomdlException", "(", "\"Cannot decompose in \"", "+", "str", "(", "decompose_dir", ")", "+", "\" direction. Acceptable values: u, v, uv\"", ")" ]
Decomposes the surface into Bezier surface patches of the same degree. This operation does not modify the input surface, instead it returns the surface patches. Keyword Arguments: * ``find_span_func``: FindSpan implementation. *Default:* :func:`.helpers.find_span_linear` * ``insert_knot_func``: knot insertion algorithm implementation. *Default:* :func:`.operations.insert_knot` :param obj: surface :type obj: abstract.Surface :return: a list of Bezier patches :rtype: list
[ "Decomposes", "the", "surface", "into", "Bezier", "surface", "patches", "of", "the", "same", "degree", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1234-L1293
230,355
orbingol/NURBS-Python
geomdl/operations.py
tangent
def tangent(obj, params, **kwargs): """ Evaluates the tangent vector of the curves or surfaces at the input parameter values. This function is designed to evaluate tangent vectors of the B-Spline and NURBS shapes at single or multiple parameter positions. :param obj: input shape :type obj: abstract.Curve or abstract.Surface :param params: parameters :type params: float, list or tuple :return: a list containing "point" and "vector" pairs :rtype: tuple """ normalize = kwargs.get('normalize', True) if isinstance(obj, abstract.Curve): if isinstance(params, (list, tuple)): return ops.tangent_curve_single_list(obj, params, normalize) else: return ops.tangent_curve_single(obj, params, normalize) if isinstance(obj, abstract.Surface): if isinstance(params[0], float): return ops.tangent_surface_single(obj, params, normalize) else: return ops.tangent_surface_single_list(obj, params, normalize)
python
def tangent(obj, params, **kwargs): """ Evaluates the tangent vector of the curves or surfaces at the input parameter values. This function is designed to evaluate tangent vectors of the B-Spline and NURBS shapes at single or multiple parameter positions. :param obj: input shape :type obj: abstract.Curve or abstract.Surface :param params: parameters :type params: float, list or tuple :return: a list containing "point" and "vector" pairs :rtype: tuple """ normalize = kwargs.get('normalize', True) if isinstance(obj, abstract.Curve): if isinstance(params, (list, tuple)): return ops.tangent_curve_single_list(obj, params, normalize) else: return ops.tangent_curve_single(obj, params, normalize) if isinstance(obj, abstract.Surface): if isinstance(params[0], float): return ops.tangent_surface_single(obj, params, normalize) else: return ops.tangent_surface_single_list(obj, params, normalize)
[ "def", "tangent", "(", "obj", ",", "params", ",", "*", "*", "kwargs", ")", ":", "normalize", "=", "kwargs", ".", "get", "(", "'normalize'", ",", "True", ")", "if", "isinstance", "(", "obj", ",", "abstract", ".", "Curve", ")", ":", "if", "isinstance", "(", "params", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "ops", ".", "tangent_curve_single_list", "(", "obj", ",", "params", ",", "normalize", ")", "else", ":", "return", "ops", ".", "tangent_curve_single", "(", "obj", ",", "params", ",", "normalize", ")", "if", "isinstance", "(", "obj", ",", "abstract", ".", "Surface", ")", ":", "if", "isinstance", "(", "params", "[", "0", "]", ",", "float", ")", ":", "return", "ops", ".", "tangent_surface_single", "(", "obj", ",", "params", ",", "normalize", ")", "else", ":", "return", "ops", ".", "tangent_surface_single_list", "(", "obj", ",", "params", ",", "normalize", ")" ]
Evaluates the tangent vector of the curves or surfaces at the input parameter values. This function is designed to evaluate tangent vectors of the B-Spline and NURBS shapes at single or multiple parameter positions. :param obj: input shape :type obj: abstract.Curve or abstract.Surface :param params: parameters :type params: float, list or tuple :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "tangent", "vector", "of", "the", "curves", "or", "surfaces", "at", "the", "input", "parameter", "values", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1392-L1415
230,356
orbingol/NURBS-Python
geomdl/operations.py
normal
def normal(obj, params, **kwargs): """ Evaluates the normal vector of the curves or surfaces at the input parameter values. This function is designed to evaluate normal vectors of the B-Spline and NURBS shapes at single or multiple parameter positions. :param obj: input geometry :type obj: abstract.Curve or abstract.Surface :param params: parameters :type params: float, list or tuple :return: a list containing "point" and "vector" pairs :rtype: tuple """ normalize = kwargs.get('normalize', True) if isinstance(obj, abstract.Curve): if isinstance(params, (list, tuple)): return ops.normal_curve_single_list(obj, params, normalize) else: return ops.normal_curve_single(obj, params, normalize) if isinstance(obj, abstract.Surface): if isinstance(params[0], float): return ops.normal_surface_single(obj, params, normalize) else: return ops.normal_surface_single_list(obj, params, normalize)
python
def normal(obj, params, **kwargs): """ Evaluates the normal vector of the curves or surfaces at the input parameter values. This function is designed to evaluate normal vectors of the B-Spline and NURBS shapes at single or multiple parameter positions. :param obj: input geometry :type obj: abstract.Curve or abstract.Surface :param params: parameters :type params: float, list or tuple :return: a list containing "point" and "vector" pairs :rtype: tuple """ normalize = kwargs.get('normalize', True) if isinstance(obj, abstract.Curve): if isinstance(params, (list, tuple)): return ops.normal_curve_single_list(obj, params, normalize) else: return ops.normal_curve_single(obj, params, normalize) if isinstance(obj, abstract.Surface): if isinstance(params[0], float): return ops.normal_surface_single(obj, params, normalize) else: return ops.normal_surface_single_list(obj, params, normalize)
[ "def", "normal", "(", "obj", ",", "params", ",", "*", "*", "kwargs", ")", ":", "normalize", "=", "kwargs", ".", "get", "(", "'normalize'", ",", "True", ")", "if", "isinstance", "(", "obj", ",", "abstract", ".", "Curve", ")", ":", "if", "isinstance", "(", "params", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "ops", ".", "normal_curve_single_list", "(", "obj", ",", "params", ",", "normalize", ")", "else", ":", "return", "ops", ".", "normal_curve_single", "(", "obj", ",", "params", ",", "normalize", ")", "if", "isinstance", "(", "obj", ",", "abstract", ".", "Surface", ")", ":", "if", "isinstance", "(", "params", "[", "0", "]", ",", "float", ")", ":", "return", "ops", ".", "normal_surface_single", "(", "obj", ",", "params", ",", "normalize", ")", "else", ":", "return", "ops", ".", "normal_surface_single_list", "(", "obj", ",", "params", ",", "normalize", ")" ]
Evaluates the normal vector of the curves or surfaces at the input parameter values. This function is designed to evaluate normal vectors of the B-Spline and NURBS shapes at single or multiple parameter positions. :param obj: input geometry :type obj: abstract.Curve or abstract.Surface :param params: parameters :type params: float, list or tuple :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "normal", "vector", "of", "the", "curves", "or", "surfaces", "at", "the", "input", "parameter", "values", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1419-L1442
230,357
orbingol/NURBS-Python
geomdl/operations.py
binormal
def binormal(obj, params, **kwargs): """ Evaluates the binormal vector of the curves or surfaces at the input parameter values. This function is designed to evaluate binormal vectors of the B-Spline and NURBS shapes at single or multiple parameter positions. :param obj: input shape :type obj: abstract.Curve or abstract.Surface :param params: parameters :type params: float, list or tuple :return: a list containing "point" and "vector" pairs :rtype: tuple """ normalize = kwargs.get('normalize', True) if isinstance(obj, abstract.Curve): if isinstance(params, (list, tuple)): return ops.binormal_curve_single_list(obj, params, normalize) else: return ops.binormal_curve_single(obj, params, normalize) if isinstance(obj, abstract.Surface): raise GeomdlException("Binormal vector evaluation for the surfaces is not implemented!")
python
def binormal(obj, params, **kwargs): """ Evaluates the binormal vector of the curves or surfaces at the input parameter values. This function is designed to evaluate binormal vectors of the B-Spline and NURBS shapes at single or multiple parameter positions. :param obj: input shape :type obj: abstract.Curve or abstract.Surface :param params: parameters :type params: float, list or tuple :return: a list containing "point" and "vector" pairs :rtype: tuple """ normalize = kwargs.get('normalize', True) if isinstance(obj, abstract.Curve): if isinstance(params, (list, tuple)): return ops.binormal_curve_single_list(obj, params, normalize) else: return ops.binormal_curve_single(obj, params, normalize) if isinstance(obj, abstract.Surface): raise GeomdlException("Binormal vector evaluation for the surfaces is not implemented!")
[ "def", "binormal", "(", "obj", ",", "params", ",", "*", "*", "kwargs", ")", ":", "normalize", "=", "kwargs", ".", "get", "(", "'normalize'", ",", "True", ")", "if", "isinstance", "(", "obj", ",", "abstract", ".", "Curve", ")", ":", "if", "isinstance", "(", "params", ",", "(", "list", ",", "tuple", ")", ")", ":", "return", "ops", ".", "binormal_curve_single_list", "(", "obj", ",", "params", ",", "normalize", ")", "else", ":", "return", "ops", ".", "binormal_curve_single", "(", "obj", ",", "params", ",", "normalize", ")", "if", "isinstance", "(", "obj", ",", "abstract", ".", "Surface", ")", ":", "raise", "GeomdlException", "(", "\"Binormal vector evaluation for the surfaces is not implemented!\"", ")" ]
Evaluates the binormal vector of the curves or surfaces at the input parameter values. This function is designed to evaluate binormal vectors of the B-Spline and NURBS shapes at single or multiple parameter positions. :param obj: input shape :type obj: abstract.Curve or abstract.Surface :param params: parameters :type params: float, list or tuple :return: a list containing "point" and "vector" pairs :rtype: tuple
[ "Evaluates", "the", "binormal", "vector", "of", "the", "curves", "or", "surfaces", "at", "the", "input", "parameter", "values", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1446-L1466
230,358
orbingol/NURBS-Python
geomdl/operations.py
translate
def translate(obj, vec, **kwargs): """ Translates curves, surface or volumes by the input vector. Keyword Arguments: * ``inplace``: if False, operation applied to a copy of the object. *Default: False* :param obj: input geometry :type obj: abstract.SplineGeometry or multi.AbstractContainer :param vec: translation vector :type vec: list, tuple :return: translated geometry object """ # Input validity checks if not vec or not isinstance(vec, (tuple, list)): raise GeomdlException("The input must be a list or a tuple") # Input validity checks if len(vec) != obj.dimension: raise GeomdlException("The input vector must have " + str(obj.dimension) + " components") # Keyword arguments inplace = kwargs.get('inplace', False) if not inplace: geom = copy.deepcopy(obj) else: geom = obj # Translate control points for g in geom: new_ctrlpts = [] for pt in g.ctrlpts: temp = [v + vec[i] for i, v in enumerate(pt)] new_ctrlpts.append(temp) g.ctrlpts = new_ctrlpts return geom
python
def translate(obj, vec, **kwargs): """ Translates curves, surface or volumes by the input vector. Keyword Arguments: * ``inplace``: if False, operation applied to a copy of the object. *Default: False* :param obj: input geometry :type obj: abstract.SplineGeometry or multi.AbstractContainer :param vec: translation vector :type vec: list, tuple :return: translated geometry object """ # Input validity checks if not vec or not isinstance(vec, (tuple, list)): raise GeomdlException("The input must be a list or a tuple") # Input validity checks if len(vec) != obj.dimension: raise GeomdlException("The input vector must have " + str(obj.dimension) + " components") # Keyword arguments inplace = kwargs.get('inplace', False) if not inplace: geom = copy.deepcopy(obj) else: geom = obj # Translate control points for g in geom: new_ctrlpts = [] for pt in g.ctrlpts: temp = [v + vec[i] for i, v in enumerate(pt)] new_ctrlpts.append(temp) g.ctrlpts = new_ctrlpts return geom
[ "def", "translate", "(", "obj", ",", "vec", ",", "*", "*", "kwargs", ")", ":", "# Input validity checks", "if", "not", "vec", "or", "not", "isinstance", "(", "vec", ",", "(", "tuple", ",", "list", ")", ")", ":", "raise", "GeomdlException", "(", "\"The input must be a list or a tuple\"", ")", "# Input validity checks", "if", "len", "(", "vec", ")", "!=", "obj", ".", "dimension", ":", "raise", "GeomdlException", "(", "\"The input vector must have \"", "+", "str", "(", "obj", ".", "dimension", ")", "+", "\" components\"", ")", "# Keyword arguments", "inplace", "=", "kwargs", ".", "get", "(", "'inplace'", ",", "False", ")", "if", "not", "inplace", ":", "geom", "=", "copy", ".", "deepcopy", "(", "obj", ")", "else", ":", "geom", "=", "obj", "# Translate control points", "for", "g", "in", "geom", ":", "new_ctrlpts", "=", "[", "]", "for", "pt", "in", "g", ".", "ctrlpts", ":", "temp", "=", "[", "v", "+", "vec", "[", "i", "]", "for", "i", ",", "v", "in", "enumerate", "(", "pt", ")", "]", "new_ctrlpts", ".", "append", "(", "temp", ")", "g", ".", "ctrlpts", "=", "new_ctrlpts", "return", "geom" ]
Translates curves, surface or volumes by the input vector. Keyword Arguments: * ``inplace``: if False, operation applied to a copy of the object. *Default: False* :param obj: input geometry :type obj: abstract.SplineGeometry or multi.AbstractContainer :param vec: translation vector :type vec: list, tuple :return: translated geometry object
[ "Translates", "curves", "surface", "or", "volumes", "by", "the", "input", "vector", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1470-L1506
230,359
orbingol/NURBS-Python
geomdl/operations.py
scale
def scale(obj, multiplier, **kwargs): """ Scales curves, surfaces or volumes by the input multiplier. Keyword Arguments: * ``inplace``: if False, operation applied to a copy of the object. *Default: False* :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractGeometry :param multiplier: scaling multiplier :type multiplier: float :return: scaled geometry object """ # Input validity checks if not isinstance(multiplier, (int, float)): raise GeomdlException("The multiplier must be a float or an integer") # Keyword arguments inplace = kwargs.get('inplace', False) if not inplace: geom = copy.deepcopy(obj) else: geom = obj # Scale control points for g in geom: new_ctrlpts = [[] for _ in range(g.ctrlpts_size)] for idx, pts in enumerate(g.ctrlpts): new_ctrlpts[idx] = [p * float(multiplier) for p in pts] g.ctrlpts = new_ctrlpts return geom
python
def scale(obj, multiplier, **kwargs): """ Scales curves, surfaces or volumes by the input multiplier. Keyword Arguments: * ``inplace``: if False, operation applied to a copy of the object. *Default: False* :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractGeometry :param multiplier: scaling multiplier :type multiplier: float :return: scaled geometry object """ # Input validity checks if not isinstance(multiplier, (int, float)): raise GeomdlException("The multiplier must be a float or an integer") # Keyword arguments inplace = kwargs.get('inplace', False) if not inplace: geom = copy.deepcopy(obj) else: geom = obj # Scale control points for g in geom: new_ctrlpts = [[] for _ in range(g.ctrlpts_size)] for idx, pts in enumerate(g.ctrlpts): new_ctrlpts[idx] = [p * float(multiplier) for p in pts] g.ctrlpts = new_ctrlpts return geom
[ "def", "scale", "(", "obj", ",", "multiplier", ",", "*", "*", "kwargs", ")", ":", "# Input validity checks", "if", "not", "isinstance", "(", "multiplier", ",", "(", "int", ",", "float", ")", ")", ":", "raise", "GeomdlException", "(", "\"The multiplier must be a float or an integer\"", ")", "# Keyword arguments", "inplace", "=", "kwargs", ".", "get", "(", "'inplace'", ",", "False", ")", "if", "not", "inplace", ":", "geom", "=", "copy", ".", "deepcopy", "(", "obj", ")", "else", ":", "geom", "=", "obj", "# Scale control points", "for", "g", "in", "geom", ":", "new_ctrlpts", "=", "[", "[", "]", "for", "_", "in", "range", "(", "g", ".", "ctrlpts_size", ")", "]", "for", "idx", ",", "pts", "in", "enumerate", "(", "g", ".", "ctrlpts", ")", ":", "new_ctrlpts", "[", "idx", "]", "=", "[", "p", "*", "float", "(", "multiplier", ")", "for", "p", "in", "pts", "]", "g", ".", "ctrlpts", "=", "new_ctrlpts", "return", "geom" ]
Scales curves, surfaces or volumes by the input multiplier. Keyword Arguments: * ``inplace``: if False, operation applied to a copy of the object. *Default: False* :param obj: input geometry :type obj: abstract.SplineGeometry, multi.AbstractGeometry :param multiplier: scaling multiplier :type multiplier: float :return: scaled geometry object
[ "Scales", "curves", "surfaces", "or", "volumes", "by", "the", "input", "multiplier", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/operations.py#L1607-L1638
230,360
orbingol/NURBS-Python
geomdl/voxelize.py
voxelize
def voxelize(obj, **kwargs): """ Generates binary voxel representation of the surfaces and volumes. Keyword Arguments: * ``grid_size``: size of the voxel grid. *Default: (8, 8, 8)* * ``padding``: voxel padding for in-outs finding. *Default: 10e-8* * ``use_cubes``: use cube voxels instead of cuboid ones. *Default: False* * ``num_procs``: number of concurrent processes for voxelization. *Default: 1* :param obj: input surface(s) or volume(s) :type obj: abstract.Surface or abstract.Volume :return: voxel grid and filled information :rtype: tuple """ # Get keyword arguments grid_size = kwargs.pop('grid_size', (8, 8, 8)) use_cubes = kwargs.pop('use_cubes', False) num_procs = kwargs.get('num_procs', 1) if not isinstance(grid_size, (list, tuple)): raise TypeError("Grid size must be a list or a tuple of integers") # Initialize result arrays grid = [] filled = [] # Should also work with multi surfaces and volumes for o in obj: # Generate voxel grid grid_temp = vxl.generate_voxel_grid(o.bbox, grid_size, use_cubes=use_cubes) args = [grid_temp, o.evalpts] # Find in-outs filled_temp = vxl.find_inouts_mp(*args, **kwargs) if num_procs > 1 else vxl.find_inouts_st(*args, **kwargs) # Add to result arrays grid += grid_temp filled += filled_temp # Return result arrays return grid, filled
python
def voxelize(obj, **kwargs): """ Generates binary voxel representation of the surfaces and volumes. Keyword Arguments: * ``grid_size``: size of the voxel grid. *Default: (8, 8, 8)* * ``padding``: voxel padding for in-outs finding. *Default: 10e-8* * ``use_cubes``: use cube voxels instead of cuboid ones. *Default: False* * ``num_procs``: number of concurrent processes for voxelization. *Default: 1* :param obj: input surface(s) or volume(s) :type obj: abstract.Surface or abstract.Volume :return: voxel grid and filled information :rtype: tuple """ # Get keyword arguments grid_size = kwargs.pop('grid_size', (8, 8, 8)) use_cubes = kwargs.pop('use_cubes', False) num_procs = kwargs.get('num_procs', 1) if not isinstance(grid_size, (list, tuple)): raise TypeError("Grid size must be a list or a tuple of integers") # Initialize result arrays grid = [] filled = [] # Should also work with multi surfaces and volumes for o in obj: # Generate voxel grid grid_temp = vxl.generate_voxel_grid(o.bbox, grid_size, use_cubes=use_cubes) args = [grid_temp, o.evalpts] # Find in-outs filled_temp = vxl.find_inouts_mp(*args, **kwargs) if num_procs > 1 else vxl.find_inouts_st(*args, **kwargs) # Add to result arrays grid += grid_temp filled += filled_temp # Return result arrays return grid, filled
[ "def", "voxelize", "(", "obj", ",", "*", "*", "kwargs", ")", ":", "# Get keyword arguments", "grid_size", "=", "kwargs", ".", "pop", "(", "'grid_size'", ",", "(", "8", ",", "8", ",", "8", ")", ")", "use_cubes", "=", "kwargs", ".", "pop", "(", "'use_cubes'", ",", "False", ")", "num_procs", "=", "kwargs", ".", "get", "(", "'num_procs'", ",", "1", ")", "if", "not", "isinstance", "(", "grid_size", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"Grid size must be a list or a tuple of integers\"", ")", "# Initialize result arrays", "grid", "=", "[", "]", "filled", "=", "[", "]", "# Should also work with multi surfaces and volumes", "for", "o", "in", "obj", ":", "# Generate voxel grid", "grid_temp", "=", "vxl", ".", "generate_voxel_grid", "(", "o", ".", "bbox", ",", "grid_size", ",", "use_cubes", "=", "use_cubes", ")", "args", "=", "[", "grid_temp", ",", "o", ".", "evalpts", "]", "# Find in-outs", "filled_temp", "=", "vxl", ".", "find_inouts_mp", "(", "*", "args", ",", "*", "*", "kwargs", ")", "if", "num_procs", ">", "1", "else", "vxl", ".", "find_inouts_st", "(", "*", "args", ",", "*", "*", "kwargs", ")", "# Add to result arrays", "grid", "+=", "grid_temp", "filled", "+=", "filled_temp", "# Return result arrays", "return", "grid", ",", "filled" ]
Generates binary voxel representation of the surfaces and volumes. Keyword Arguments: * ``grid_size``: size of the voxel grid. *Default: (8, 8, 8)* * ``padding``: voxel padding for in-outs finding. *Default: 10e-8* * ``use_cubes``: use cube voxels instead of cuboid ones. *Default: False* * ``num_procs``: number of concurrent processes for voxelization. *Default: 1* :param obj: input surface(s) or volume(s) :type obj: abstract.Surface or abstract.Volume :return: voxel grid and filled information :rtype: tuple
[ "Generates", "binary", "voxel", "representation", "of", "the", "surfaces", "and", "volumes", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/voxelize.py#L16-L56
230,361
orbingol/NURBS-Python
geomdl/voxelize.py
convert_bb_to_faces
def convert_bb_to_faces(voxel_grid): """ Converts a voxel grid defined by min and max coordinates to a voxel grid defined by faces. :param voxel_grid: voxel grid defined by the bounding box of all voxels :return: voxel grid with face data """ new_vg = [] for v in voxel_grid: # Vertices p1 = v[0] p2 = [v[1][0], v[0][1], v[0][2]] p3 = [v[1][0], v[1][1], v[0][2]] p4 = [v[0][0], v[1][1], v[0][2]] p5 = [v[0][0], v[0][1], v[1][2]] p6 = [v[1][0], v[0][1], v[1][2]] p7 = v[1] p8 = [v[0][0], v[1][1], v[1][2]] # Faces fb = [p1, p2, p3, p4] # bottom face ft = [p5, p6, p7, p8] # top face fs1 = [p1, p2, p6, p5] # side face 1 fs2 = [p2, p3, p7, p6] # side face 2 fs3 = [p3, p4, p8, p7] # side face 3 fs4 = [p1, p4, p8, p5] # side face 4 # Append to return list new_vg.append([fb, fs1, fs2, fs3, fs4, ft]) return new_vg
python
def convert_bb_to_faces(voxel_grid): """ Converts a voxel grid defined by min and max coordinates to a voxel grid defined by faces. :param voxel_grid: voxel grid defined by the bounding box of all voxels :return: voxel grid with face data """ new_vg = [] for v in voxel_grid: # Vertices p1 = v[0] p2 = [v[1][0], v[0][1], v[0][2]] p3 = [v[1][0], v[1][1], v[0][2]] p4 = [v[0][0], v[1][1], v[0][2]] p5 = [v[0][0], v[0][1], v[1][2]] p6 = [v[1][0], v[0][1], v[1][2]] p7 = v[1] p8 = [v[0][0], v[1][1], v[1][2]] # Faces fb = [p1, p2, p3, p4] # bottom face ft = [p5, p6, p7, p8] # top face fs1 = [p1, p2, p6, p5] # side face 1 fs2 = [p2, p3, p7, p6] # side face 2 fs3 = [p3, p4, p8, p7] # side face 3 fs4 = [p1, p4, p8, p5] # side face 4 # Append to return list new_vg.append([fb, fs1, fs2, fs3, fs4, ft]) return new_vg
[ "def", "convert_bb_to_faces", "(", "voxel_grid", ")", ":", "new_vg", "=", "[", "]", "for", "v", "in", "voxel_grid", ":", "# Vertices", "p1", "=", "v", "[", "0", "]", "p2", "=", "[", "v", "[", "1", "]", "[", "0", "]", ",", "v", "[", "0", "]", "[", "1", "]", ",", "v", "[", "0", "]", "[", "2", "]", "]", "p3", "=", "[", "v", "[", "1", "]", "[", "0", "]", ",", "v", "[", "1", "]", "[", "1", "]", ",", "v", "[", "0", "]", "[", "2", "]", "]", "p4", "=", "[", "v", "[", "0", "]", "[", "0", "]", ",", "v", "[", "1", "]", "[", "1", "]", ",", "v", "[", "0", "]", "[", "2", "]", "]", "p5", "=", "[", "v", "[", "0", "]", "[", "0", "]", ",", "v", "[", "0", "]", "[", "1", "]", ",", "v", "[", "1", "]", "[", "2", "]", "]", "p6", "=", "[", "v", "[", "1", "]", "[", "0", "]", ",", "v", "[", "0", "]", "[", "1", "]", ",", "v", "[", "1", "]", "[", "2", "]", "]", "p7", "=", "v", "[", "1", "]", "p8", "=", "[", "v", "[", "0", "]", "[", "0", "]", ",", "v", "[", "1", "]", "[", "1", "]", ",", "v", "[", "1", "]", "[", "2", "]", "]", "# Faces", "fb", "=", "[", "p1", ",", "p2", ",", "p3", ",", "p4", "]", "# bottom face", "ft", "=", "[", "p5", ",", "p6", ",", "p7", ",", "p8", "]", "# top face", "fs1", "=", "[", "p1", ",", "p2", ",", "p6", ",", "p5", "]", "# side face 1", "fs2", "=", "[", "p2", ",", "p3", ",", "p7", ",", "p6", "]", "# side face 2", "fs3", "=", "[", "p3", ",", "p4", ",", "p8", ",", "p7", "]", "# side face 3", "fs4", "=", "[", "p1", ",", "p4", ",", "p8", ",", "p5", "]", "# side face 4", "# Append to return list", "new_vg", ".", "append", "(", "[", "fb", ",", "fs1", ",", "fs2", ",", "fs3", ",", "fs4", ",", "ft", "]", ")", "return", "new_vg" ]
Converts a voxel grid defined by min and max coordinates to a voxel grid defined by faces. :param voxel_grid: voxel grid defined by the bounding box of all voxels :return: voxel grid with face data
[ "Converts", "a", "voxel", "grid", "defined", "by", "min", "and", "max", "coordinates", "to", "a", "voxel", "grid", "defined", "by", "faces", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/voxelize.py#L59-L85
230,362
orbingol/NURBS-Python
geomdl/voxelize.py
save_voxel_grid
def save_voxel_grid(voxel_grid, file_name): """ Saves binary voxel grid as a binary file. The binary file is structured in little-endian unsigned int format. :param voxel_grid: binary voxel grid :type voxel_grid: list, tuple :param file_name: file name to save :type file_name: str """ try: with open(file_name, 'wb') as fp: for voxel in voxel_grid: fp.write(struct.pack("<I", voxel)) except IOError as e: print("An error occurred: {}".format(e.args[-1])) raise e except Exception: raise
python
def save_voxel_grid(voxel_grid, file_name): """ Saves binary voxel grid as a binary file. The binary file is structured in little-endian unsigned int format. :param voxel_grid: binary voxel grid :type voxel_grid: list, tuple :param file_name: file name to save :type file_name: str """ try: with open(file_name, 'wb') as fp: for voxel in voxel_grid: fp.write(struct.pack("<I", voxel)) except IOError as e: print("An error occurred: {}".format(e.args[-1])) raise e except Exception: raise
[ "def", "save_voxel_grid", "(", "voxel_grid", ",", "file_name", ")", ":", "try", ":", "with", "open", "(", "file_name", ",", "'wb'", ")", "as", "fp", ":", "for", "voxel", "in", "voxel_grid", ":", "fp", ".", "write", "(", "struct", ".", "pack", "(", "\"<I\"", ",", "voxel", ")", ")", "except", "IOError", "as", "e", ":", "print", "(", "\"An error occurred: {}\"", ".", "format", "(", "e", ".", "args", "[", "-", "1", "]", ")", ")", "raise", "e", "except", "Exception", ":", "raise" ]
Saves binary voxel grid as a binary file. The binary file is structured in little-endian unsigned int format. :param voxel_grid: binary voxel grid :type voxel_grid: list, tuple :param file_name: file name to save :type file_name: str
[ "Saves", "binary", "voxel", "grid", "as", "a", "binary", "file", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/voxelize.py#L89-L107
230,363
orbingol/NURBS-Python
geomdl/linalg.py
vector_cross
def vector_cross(vector1, vector2): """ Computes the cross-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the cross product :rtype: tuple """ try: if vector1 is None or len(vector1) == 0 or vector2 is None or len(vector2) == 0: raise ValueError("Input vectors cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise if not 1 < len(vector1) <= 3 or not 1 < len(vector2) <= 3: raise ValueError("The input vectors should contain 2 or 3 elements") # Convert 2-D to 3-D, if necessary if len(vector1) == 2: v1 = [float(v) for v in vector1] + [0.0] else: v1 = vector1 if len(vector2) == 2: v2 = [float(v) for v in vector2] + [0.0] else: v2 = vector2 # Compute cross product vector_out = [(v1[1] * v2[2]) - (v1[2] * v2[1]), (v1[2] * v2[0]) - (v1[0] * v2[2]), (v1[0] * v2[1]) - (v1[1] * v2[0])] # Return the cross product of the input vectors return vector_out
python
def vector_cross(vector1, vector2): """ Computes the cross-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the cross product :rtype: tuple """ try: if vector1 is None or len(vector1) == 0 or vector2 is None or len(vector2) == 0: raise ValueError("Input vectors cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise if not 1 < len(vector1) <= 3 or not 1 < len(vector2) <= 3: raise ValueError("The input vectors should contain 2 or 3 elements") # Convert 2-D to 3-D, if necessary if len(vector1) == 2: v1 = [float(v) for v in vector1] + [0.0] else: v1 = vector1 if len(vector2) == 2: v2 = [float(v) for v in vector2] + [0.0] else: v2 = vector2 # Compute cross product vector_out = [(v1[1] * v2[2]) - (v1[2] * v2[1]), (v1[2] * v2[0]) - (v1[0] * v2[2]), (v1[0] * v2[1]) - (v1[1] * v2[0])] # Return the cross product of the input vectors return vector_out
[ "def", "vector_cross", "(", "vector1", ",", "vector2", ")", ":", "try", ":", "if", "vector1", "is", "None", "or", "len", "(", "vector1", ")", "==", "0", "or", "vector2", "is", "None", "or", "len", "(", "vector2", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Input vectors cannot be empty\"", ")", "except", "TypeError", "as", "e", ":", "print", "(", "\"An error occurred: {}\"", ".", "format", "(", "e", ".", "args", "[", "-", "1", "]", ")", ")", "raise", "TypeError", "(", "\"Input must be a list or tuple\"", ")", "except", "Exception", ":", "raise", "if", "not", "1", "<", "len", "(", "vector1", ")", "<=", "3", "or", "not", "1", "<", "len", "(", "vector2", ")", "<=", "3", ":", "raise", "ValueError", "(", "\"The input vectors should contain 2 or 3 elements\"", ")", "# Convert 2-D to 3-D, if necessary", "if", "len", "(", "vector1", ")", "==", "2", ":", "v1", "=", "[", "float", "(", "v", ")", "for", "v", "in", "vector1", "]", "+", "[", "0.0", "]", "else", ":", "v1", "=", "vector1", "if", "len", "(", "vector2", ")", "==", "2", ":", "v2", "=", "[", "float", "(", "v", ")", "for", "v", "in", "vector2", "]", "+", "[", "0.0", "]", "else", ":", "v2", "=", "vector2", "# Compute cross product", "vector_out", "=", "[", "(", "v1", "[", "1", "]", "*", "v2", "[", "2", "]", ")", "-", "(", "v1", "[", "2", "]", "*", "v2", "[", "1", "]", ")", ",", "(", "v1", "[", "2", "]", "*", "v2", "[", "0", "]", ")", "-", "(", "v1", "[", "0", "]", "*", "v2", "[", "2", "]", ")", ",", "(", "v1", "[", "0", "]", "*", "v2", "[", "1", "]", ")", "-", "(", "v1", "[", "1", "]", "*", "v2", "[", "0", "]", ")", "]", "# Return the cross product of the input vectors", "return", "vector_out" ]
Computes the cross-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the cross product :rtype: tuple
[ "Computes", "the", "cross", "-", "product", "of", "the", "input", "vectors", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L20-L59
230,364
orbingol/NURBS-Python
geomdl/linalg.py
vector_dot
def vector_dot(vector1, vector2): """ Computes the dot-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the dot product :rtype: float """ try: if vector1 is None or len(vector1) == 0 or vector2 is None or len(vector2) == 0: raise ValueError("Input vectors cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise # Compute dot product prod = 0.0 for v1, v2 in zip(vector1, vector2): prod += v1 * v2 # Return the dot product of the input vectors return prod
python
def vector_dot(vector1, vector2): """ Computes the dot-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the dot product :rtype: float """ try: if vector1 is None or len(vector1) == 0 or vector2 is None or len(vector2) == 0: raise ValueError("Input vectors cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise # Compute dot product prod = 0.0 for v1, v2 in zip(vector1, vector2): prod += v1 * v2 # Return the dot product of the input vectors return prod
[ "def", "vector_dot", "(", "vector1", ",", "vector2", ")", ":", "try", ":", "if", "vector1", "is", "None", "or", "len", "(", "vector1", ")", "==", "0", "or", "vector2", "is", "None", "or", "len", "(", "vector2", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Input vectors cannot be empty\"", ")", "except", "TypeError", "as", "e", ":", "print", "(", "\"An error occurred: {}\"", ".", "format", "(", "e", ".", "args", "[", "-", "1", "]", ")", ")", "raise", "TypeError", "(", "\"Input must be a list or tuple\"", ")", "except", "Exception", ":", "raise", "# Compute dot product", "prod", "=", "0.0", "for", "v1", ",", "v2", "in", "zip", "(", "vector1", ",", "vector2", ")", ":", "prod", "+=", "v1", "*", "v2", "# Return the dot product of the input vectors", "return", "prod" ]
Computes the dot-product of the input vectors. :param vector1: input vector 1 :type vector1: list, tuple :param vector2: input vector 2 :type vector2: list, tuple :return: result of the dot product :rtype: float
[ "Computes", "the", "dot", "-", "product", "of", "the", "input", "vectors", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L62-L87
230,365
orbingol/NURBS-Python
geomdl/linalg.py
vector_sum
def vector_sum(vector1, vector2, coeff=1.0): """ Sums the vectors. This function computes the result of the vector operation :math:`\\overline{v}_{1} + c * \\overline{v}_{2}`, where :math:`\\overline{v}_{1}` is ``vector1``, :math:`\\overline{v}_{2}` is ``vector2`` and :math:`c` is ``coeff``. :param vector1: vector 1 :type vector1: list, tuple :param vector2: vector 2 :type vector2: list, tuple :param coeff: multiplier for vector 2 :type coeff: float :return: updated vector :rtype: list """ summed_vector = [v1 + (coeff * v2) for v1, v2 in zip(vector1, vector2)] return summed_vector
python
def vector_sum(vector1, vector2, coeff=1.0): """ Sums the vectors. This function computes the result of the vector operation :math:`\\overline{v}_{1} + c * \\overline{v}_{2}`, where :math:`\\overline{v}_{1}` is ``vector1``, :math:`\\overline{v}_{2}` is ``vector2`` and :math:`c` is ``coeff``. :param vector1: vector 1 :type vector1: list, tuple :param vector2: vector 2 :type vector2: list, tuple :param coeff: multiplier for vector 2 :type coeff: float :return: updated vector :rtype: list """ summed_vector = [v1 + (coeff * v2) for v1, v2 in zip(vector1, vector2)] return summed_vector
[ "def", "vector_sum", "(", "vector1", ",", "vector2", ",", "coeff", "=", "1.0", ")", ":", "summed_vector", "=", "[", "v1", "+", "(", "coeff", "*", "v2", ")", "for", "v1", ",", "v2", "in", "zip", "(", "vector1", ",", "vector2", ")", "]", "return", "summed_vector" ]
Sums the vectors. This function computes the result of the vector operation :math:`\\overline{v}_{1} + c * \\overline{v}_{2}`, where :math:`\\overline{v}_{1}` is ``vector1``, :math:`\\overline{v}_{2}` is ``vector2`` and :math:`c` is ``coeff``. :param vector1: vector 1 :type vector1: list, tuple :param vector2: vector 2 :type vector2: list, tuple :param coeff: multiplier for vector 2 :type coeff: float :return: updated vector :rtype: list
[ "Sums", "the", "vectors", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L106-L122
230,366
orbingol/NURBS-Python
geomdl/linalg.py
vector_normalize
def vector_normalize(vector_in, decimals=18): """ Generates a unit vector from the input. :param vector_in: vector to be normalized :type vector_in: list, tuple :param decimals: number of significands :type decimals: int :return: the normalized vector (i.e. the unit vector) :rtype: list """ try: if vector_in is None or len(vector_in) == 0: raise ValueError("Input vector cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise # Calculate magnitude of the vector magnitude = vector_magnitude(vector_in) # Normalize the vector if magnitude > 0: vector_out = [] for vin in vector_in: vector_out.append(vin / magnitude) # Return the normalized vector and consider the number of significands return [float(("{:." + str(decimals) + "f}").format(vout)) for vout in vector_out] else: raise ValueError("The magnitude of the vector is zero")
python
def vector_normalize(vector_in, decimals=18): """ Generates a unit vector from the input. :param vector_in: vector to be normalized :type vector_in: list, tuple :param decimals: number of significands :type decimals: int :return: the normalized vector (i.e. the unit vector) :rtype: list """ try: if vector_in is None or len(vector_in) == 0: raise ValueError("Input vector cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise # Calculate magnitude of the vector magnitude = vector_magnitude(vector_in) # Normalize the vector if magnitude > 0: vector_out = [] for vin in vector_in: vector_out.append(vin / magnitude) # Return the normalized vector and consider the number of significands return [float(("{:." + str(decimals) + "f}").format(vout)) for vout in vector_out] else: raise ValueError("The magnitude of the vector is zero")
[ "def", "vector_normalize", "(", "vector_in", ",", "decimals", "=", "18", ")", ":", "try", ":", "if", "vector_in", "is", "None", "or", "len", "(", "vector_in", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Input vector cannot be empty\"", ")", "except", "TypeError", "as", "e", ":", "print", "(", "\"An error occurred: {}\"", ".", "format", "(", "e", ".", "args", "[", "-", "1", "]", ")", ")", "raise", "TypeError", "(", "\"Input must be a list or tuple\"", ")", "except", "Exception", ":", "raise", "# Calculate magnitude of the vector", "magnitude", "=", "vector_magnitude", "(", "vector_in", ")", "# Normalize the vector", "if", "magnitude", ">", "0", ":", "vector_out", "=", "[", "]", "for", "vin", "in", "vector_in", ":", "vector_out", ".", "append", "(", "vin", "/", "magnitude", ")", "# Return the normalized vector and consider the number of significands", "return", "[", "float", "(", "(", "\"{:.\"", "+", "str", "(", "decimals", ")", "+", "\"f}\"", ")", ".", "format", "(", "vout", ")", ")", "for", "vout", "in", "vector_out", "]", "else", ":", "raise", "ValueError", "(", "\"The magnitude of the vector is zero\"", ")" ]
Generates a unit vector from the input. :param vector_in: vector to be normalized :type vector_in: list, tuple :param decimals: number of significands :type decimals: int :return: the normalized vector (i.e. the unit vector) :rtype: list
[ "Generates", "a", "unit", "vector", "from", "the", "input", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L125-L156
230,367
orbingol/NURBS-Python
geomdl/linalg.py
vector_generate
def vector_generate(start_pt, end_pt, normalize=False): """ Generates a vector from 2 input points. :param start_pt: start point of the vector :type start_pt: list, tuple :param end_pt: end point of the vector :type end_pt: list, tuple :param normalize: if True, the generated vector is normalized :type normalize: bool :return: a vector from start_pt to end_pt :rtype: list """ try: if start_pt is None or len(start_pt) == 0 or end_pt is None or len(end_pt) == 0: raise ValueError("Input points cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise ret_vec = [] for sp, ep in zip(start_pt, end_pt): ret_vec.append(ep - sp) if normalize: ret_vec = vector_normalize(ret_vec) return ret_vec
python
def vector_generate(start_pt, end_pt, normalize=False): """ Generates a vector from 2 input points. :param start_pt: start point of the vector :type start_pt: list, tuple :param end_pt: end point of the vector :type end_pt: list, tuple :param normalize: if True, the generated vector is normalized :type normalize: bool :return: a vector from start_pt to end_pt :rtype: list """ try: if start_pt is None or len(start_pt) == 0 or end_pt is None or len(end_pt) == 0: raise ValueError("Input points cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise ret_vec = [] for sp, ep in zip(start_pt, end_pt): ret_vec.append(ep - sp) if normalize: ret_vec = vector_normalize(ret_vec) return ret_vec
[ "def", "vector_generate", "(", "start_pt", ",", "end_pt", ",", "normalize", "=", "False", ")", ":", "try", ":", "if", "start_pt", "is", "None", "or", "len", "(", "start_pt", ")", "==", "0", "or", "end_pt", "is", "None", "or", "len", "(", "end_pt", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Input points cannot be empty\"", ")", "except", "TypeError", "as", "e", ":", "print", "(", "\"An error occurred: {}\"", ".", "format", "(", "e", ".", "args", "[", "-", "1", "]", ")", ")", "raise", "TypeError", "(", "\"Input must be a list or tuple\"", ")", "except", "Exception", ":", "raise", "ret_vec", "=", "[", "]", "for", "sp", ",", "ep", "in", "zip", "(", "start_pt", ",", "end_pt", ")", ":", "ret_vec", ".", "append", "(", "ep", "-", "sp", ")", "if", "normalize", ":", "ret_vec", "=", "vector_normalize", "(", "ret_vec", ")", "return", "ret_vec" ]
Generates a vector from 2 input points. :param start_pt: start point of the vector :type start_pt: list, tuple :param end_pt: end point of the vector :type end_pt: list, tuple :param normalize: if True, the generated vector is normalized :type normalize: bool :return: a vector from start_pt to end_pt :rtype: list
[ "Generates", "a", "vector", "from", "2", "input", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L159-L186
230,368
orbingol/NURBS-Python
geomdl/linalg.py
vector_magnitude
def vector_magnitude(vector_in): """ Computes the magnitude of the input vector. :param vector_in: input vector :type vector_in: list, tuple :return: magnitude of the vector :rtype: float """ sq_sum = 0.0 for vin in vector_in: sq_sum += vin**2 return math.sqrt(sq_sum)
python
def vector_magnitude(vector_in): """ Computes the magnitude of the input vector. :param vector_in: input vector :type vector_in: list, tuple :return: magnitude of the vector :rtype: float """ sq_sum = 0.0 for vin in vector_in: sq_sum += vin**2 return math.sqrt(sq_sum)
[ "def", "vector_magnitude", "(", "vector_in", ")", ":", "sq_sum", "=", "0.0", "for", "vin", "in", "vector_in", ":", "sq_sum", "+=", "vin", "**", "2", "return", "math", ".", "sqrt", "(", "sq_sum", ")" ]
Computes the magnitude of the input vector. :param vector_in: input vector :type vector_in: list, tuple :return: magnitude of the vector :rtype: float
[ "Computes", "the", "magnitude", "of", "the", "input", "vector", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L223-L234
230,369
orbingol/NURBS-Python
geomdl/linalg.py
vector_angle_between
def vector_angle_between(vector1, vector2, **kwargs): """ Computes the angle between the two input vectors. If the keyword argument ``degrees`` is set to *True*, then the angle will be in degrees. Otherwise, it will be in radians. By default, ``degrees`` is set to *True*. :param vector1: vector :type vector1: list, tuple :param vector2: vector :type vector2: list, tuple :return: angle between the vectors :rtype: float """ degrees = kwargs.get('degrees', True) magn1 = vector_magnitude(vector1) magn2 = vector_magnitude(vector2) acos_val = vector_dot(vector1, vector2) / (magn1 * magn2) angle_radians = math.acos(acos_val) if degrees: return math.degrees(angle_radians) else: return angle_radians
python
def vector_angle_between(vector1, vector2, **kwargs): """ Computes the angle between the two input vectors. If the keyword argument ``degrees`` is set to *True*, then the angle will be in degrees. Otherwise, it will be in radians. By default, ``degrees`` is set to *True*. :param vector1: vector :type vector1: list, tuple :param vector2: vector :type vector2: list, tuple :return: angle between the vectors :rtype: float """ degrees = kwargs.get('degrees', True) magn1 = vector_magnitude(vector1) magn2 = vector_magnitude(vector2) acos_val = vector_dot(vector1, vector2) / (magn1 * magn2) angle_radians = math.acos(acos_val) if degrees: return math.degrees(angle_radians) else: return angle_radians
[ "def", "vector_angle_between", "(", "vector1", ",", "vector2", ",", "*", "*", "kwargs", ")", ":", "degrees", "=", "kwargs", ".", "get", "(", "'degrees'", ",", "True", ")", "magn1", "=", "vector_magnitude", "(", "vector1", ")", "magn2", "=", "vector_magnitude", "(", "vector2", ")", "acos_val", "=", "vector_dot", "(", "vector1", ",", "vector2", ")", "/", "(", "magn1", "*", "magn2", ")", "angle_radians", "=", "math", ".", "acos", "(", "acos_val", ")", "if", "degrees", ":", "return", "math", ".", "degrees", "(", "angle_radians", ")", "else", ":", "return", "angle_radians" ]
Computes the angle between the two input vectors. If the keyword argument ``degrees`` is set to *True*, then the angle will be in degrees. Otherwise, it will be in radians. By default, ``degrees`` is set to *True*. :param vector1: vector :type vector1: list, tuple :param vector2: vector :type vector2: list, tuple :return: angle between the vectors :rtype: float
[ "Computes", "the", "angle", "between", "the", "two", "input", "vectors", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L237-L258
230,370
orbingol/NURBS-Python
geomdl/linalg.py
vector_is_zero
def vector_is_zero(vector_in, tol=10e-8): """ Checks if the input vector is a zero vector. :param vector_in: input vector :type vector_in: list, tuple :param tol: tolerance value :type tol: float :return: True if the input vector is zero, False otherwise :rtype: bool """ if not isinstance(vector_in, (list, tuple)): raise TypeError("Input vector must be a list or a tuple") res = [False for _ in range(len(vector_in))] for idx in range(len(vector_in)): if abs(vector_in[idx]) < tol: res[idx] = True return all(res)
python
def vector_is_zero(vector_in, tol=10e-8): """ Checks if the input vector is a zero vector. :param vector_in: input vector :type vector_in: list, tuple :param tol: tolerance value :type tol: float :return: True if the input vector is zero, False otherwise :rtype: bool """ if not isinstance(vector_in, (list, tuple)): raise TypeError("Input vector must be a list or a tuple") res = [False for _ in range(len(vector_in))] for idx in range(len(vector_in)): if abs(vector_in[idx]) < tol: res[idx] = True return all(res)
[ "def", "vector_is_zero", "(", "vector_in", ",", "tol", "=", "10e-8", ")", ":", "if", "not", "isinstance", "(", "vector_in", ",", "(", "list", ",", "tuple", ")", ")", ":", "raise", "TypeError", "(", "\"Input vector must be a list or a tuple\"", ")", "res", "=", "[", "False", "for", "_", "in", "range", "(", "len", "(", "vector_in", ")", ")", "]", "for", "idx", "in", "range", "(", "len", "(", "vector_in", ")", ")", ":", "if", "abs", "(", "vector_in", "[", "idx", "]", ")", "<", "tol", ":", "res", "[", "idx", "]", "=", "True", "return", "all", "(", "res", ")" ]
Checks if the input vector is a zero vector. :param vector_in: input vector :type vector_in: list, tuple :param tol: tolerance value :type tol: float :return: True if the input vector is zero, False otherwise :rtype: bool
[ "Checks", "if", "the", "input", "vector", "is", "a", "zero", "vector", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L261-L278
230,371
orbingol/NURBS-Python
geomdl/linalg.py
point_translate
def point_translate(point_in, vector_in): """ Translates the input points using the input vector. :param point_in: input point :type point_in: list, tuple :param vector_in: input vector :type vector_in: list, tuple :return: translated point :rtype: list """ try: if point_in is None or len(point_in) == 0 or vector_in is None or len(vector_in) == 0: raise ValueError("Input arguments cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise # Translate the point using the input vector point_out = [coord + comp for coord, comp in zip(point_in, vector_in)] return point_out
python
def point_translate(point_in, vector_in): """ Translates the input points using the input vector. :param point_in: input point :type point_in: list, tuple :param vector_in: input vector :type vector_in: list, tuple :return: translated point :rtype: list """ try: if point_in is None or len(point_in) == 0 or vector_in is None or len(vector_in) == 0: raise ValueError("Input arguments cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Input must be a list or tuple") except Exception: raise # Translate the point using the input vector point_out = [coord + comp for coord, comp in zip(point_in, vector_in)] return point_out
[ "def", "point_translate", "(", "point_in", ",", "vector_in", ")", ":", "try", ":", "if", "point_in", "is", "None", "or", "len", "(", "point_in", ")", "==", "0", "or", "vector_in", "is", "None", "or", "len", "(", "vector_in", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Input arguments cannot be empty\"", ")", "except", "TypeError", "as", "e", ":", "print", "(", "\"An error occurred: {}\"", ".", "format", "(", "e", ".", "args", "[", "-", "1", "]", ")", ")", "raise", "TypeError", "(", "\"Input must be a list or tuple\"", ")", "except", "Exception", ":", "raise", "# Translate the point using the input vector", "point_out", "=", "[", "coord", "+", "comp", "for", "coord", ",", "comp", "in", "zip", "(", "point_in", ",", "vector_in", ")", "]", "return", "point_out" ]
Translates the input points using the input vector. :param point_in: input point :type point_in: list, tuple :param vector_in: input vector :type vector_in: list, tuple :return: translated point :rtype: list
[ "Translates", "the", "input", "points", "using", "the", "input", "vector", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L281-L303
230,372
orbingol/NURBS-Python
geomdl/linalg.py
point_distance
def point_distance(pt1, pt2): """ Computes distance between two points. :param pt1: point 1 :type pt1: list, tuple :param pt2: point 2 :type pt2: list, tuple :return: distance between input points :rtype: float """ if len(pt1) != len(pt2): raise ValueError("The input points should have the same dimension") dist_vector = vector_generate(pt1, pt2, normalize=False) distance = vector_magnitude(dist_vector) return distance
python
def point_distance(pt1, pt2): """ Computes distance between two points. :param pt1: point 1 :type pt1: list, tuple :param pt2: point 2 :type pt2: list, tuple :return: distance between input points :rtype: float """ if len(pt1) != len(pt2): raise ValueError("The input points should have the same dimension") dist_vector = vector_generate(pt1, pt2, normalize=False) distance = vector_magnitude(dist_vector) return distance
[ "def", "point_distance", "(", "pt1", ",", "pt2", ")", ":", "if", "len", "(", "pt1", ")", "!=", "len", "(", "pt2", ")", ":", "raise", "ValueError", "(", "\"The input points should have the same dimension\"", ")", "dist_vector", "=", "vector_generate", "(", "pt1", ",", "pt2", ",", "normalize", "=", "False", ")", "distance", "=", "vector_magnitude", "(", "dist_vector", ")", "return", "distance" ]
Computes distance between two points. :param pt1: point 1 :type pt1: list, tuple :param pt2: point 2 :type pt2: list, tuple :return: distance between input points :rtype: float
[ "Computes", "distance", "between", "two", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L306-L321
230,373
orbingol/NURBS-Python
geomdl/linalg.py
point_mid
def point_mid(pt1, pt2): """ Computes the midpoint of the input points. :param pt1: point 1 :type pt1: list, tuple :param pt2: point 2 :type pt2: list, tuple :return: midpoint :rtype: list """ if len(pt1) != len(pt2): raise ValueError("The input points should have the same dimension") dist_vector = vector_generate(pt1, pt2, normalize=False) half_dist_vector = vector_multiply(dist_vector, 0.5) return point_translate(pt1, half_dist_vector)
python
def point_mid(pt1, pt2): """ Computes the midpoint of the input points. :param pt1: point 1 :type pt1: list, tuple :param pt2: point 2 :type pt2: list, tuple :return: midpoint :rtype: list """ if len(pt1) != len(pt2): raise ValueError("The input points should have the same dimension") dist_vector = vector_generate(pt1, pt2, normalize=False) half_dist_vector = vector_multiply(dist_vector, 0.5) return point_translate(pt1, half_dist_vector)
[ "def", "point_mid", "(", "pt1", ",", "pt2", ")", ":", "if", "len", "(", "pt1", ")", "!=", "len", "(", "pt2", ")", ":", "raise", "ValueError", "(", "\"The input points should have the same dimension\"", ")", "dist_vector", "=", "vector_generate", "(", "pt1", ",", "pt2", ",", "normalize", "=", "False", ")", "half_dist_vector", "=", "vector_multiply", "(", "dist_vector", ",", "0.5", ")", "return", "point_translate", "(", "pt1", ",", "half_dist_vector", ")" ]
Computes the midpoint of the input points. :param pt1: point 1 :type pt1: list, tuple :param pt2: point 2 :type pt2: list, tuple :return: midpoint :rtype: list
[ "Computes", "the", "midpoint", "of", "the", "input", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L324-L339
230,374
orbingol/NURBS-Python
geomdl/linalg.py
matrix_transpose
def matrix_transpose(m): """ Transposes the input matrix. The input matrix :math:`m` is a 2-dimensional array. :param m: input matrix with dimensions :math:`(n \\times m)` :type m: list, tuple :return: transpose matrix with dimensions :math:`(m \\times n)` :rtype: list """ num_cols = len(m) num_rows = len(m[0]) m_t = [] for i in range(num_rows): temp = [] for j in range(num_cols): temp.append(m[j][i]) m_t.append(temp) return m_t
python
def matrix_transpose(m): """ Transposes the input matrix. The input matrix :math:`m` is a 2-dimensional array. :param m: input matrix with dimensions :math:`(n \\times m)` :type m: list, tuple :return: transpose matrix with dimensions :math:`(m \\times n)` :rtype: list """ num_cols = len(m) num_rows = len(m[0]) m_t = [] for i in range(num_rows): temp = [] for j in range(num_cols): temp.append(m[j][i]) m_t.append(temp) return m_t
[ "def", "matrix_transpose", "(", "m", ")", ":", "num_cols", "=", "len", "(", "m", ")", "num_rows", "=", "len", "(", "m", "[", "0", "]", ")", "m_t", "=", "[", "]", "for", "i", "in", "range", "(", "num_rows", ")", ":", "temp", "=", "[", "]", "for", "j", "in", "range", "(", "num_cols", ")", ":", "temp", ".", "append", "(", "m", "[", "j", "]", "[", "i", "]", ")", "m_t", ".", "append", "(", "temp", ")", "return", "m_t" ]
Transposes the input matrix. The input matrix :math:`m` is a 2-dimensional array. :param m: input matrix with dimensions :math:`(n \\times m)` :type m: list, tuple :return: transpose matrix with dimensions :math:`(m \\times n)` :rtype: list
[ "Transposes", "the", "input", "matrix", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L342-L360
230,375
orbingol/NURBS-Python
geomdl/linalg.py
triangle_center
def triangle_center(tri, uv=False): """ Computes the center of mass of the input triangle. :param tri: triangle object :type tri: elements.Triangle :param uv: if True, then finds parametric position of the center of mass :type uv: bool :return: center of mass of the triangle :rtype: tuple """ if uv: data = [t.uv for t in tri] mid = [0.0, 0.0] else: data = tri.vertices mid = [0.0, 0.0, 0.0] for vert in data: mid = [m + v for m, v in zip(mid, vert)] mid = [float(m) / 3.0 for m in mid] return tuple(mid)
python
def triangle_center(tri, uv=False): """ Computes the center of mass of the input triangle. :param tri: triangle object :type tri: elements.Triangle :param uv: if True, then finds parametric position of the center of mass :type uv: bool :return: center of mass of the triangle :rtype: tuple """ if uv: data = [t.uv for t in tri] mid = [0.0, 0.0] else: data = tri.vertices mid = [0.0, 0.0, 0.0] for vert in data: mid = [m + v for m, v in zip(mid, vert)] mid = [float(m) / 3.0 for m in mid] return tuple(mid)
[ "def", "triangle_center", "(", "tri", ",", "uv", "=", "False", ")", ":", "if", "uv", ":", "data", "=", "[", "t", ".", "uv", "for", "t", "in", "tri", "]", "mid", "=", "[", "0.0", ",", "0.0", "]", "else", ":", "data", "=", "tri", ".", "vertices", "mid", "=", "[", "0.0", ",", "0.0", ",", "0.0", "]", "for", "vert", "in", "data", ":", "mid", "=", "[", "m", "+", "v", "for", "m", ",", "v", "in", "zip", "(", "mid", ",", "vert", ")", "]", "mid", "=", "[", "float", "(", "m", ")", "/", "3.0", "for", "m", "in", "mid", "]", "return", "tuple", "(", "mid", ")" ]
Computes the center of mass of the input triangle. :param tri: triangle object :type tri: elements.Triangle :param uv: if True, then finds parametric position of the center of mass :type uv: bool :return: center of mass of the triangle :rtype: tuple
[ "Computes", "the", "center", "of", "mass", "of", "the", "input", "triangle", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L396-L415
230,376
orbingol/NURBS-Python
geomdl/linalg.py
lu_decomposition
def lu_decomposition(matrix_a): """ LU-Factorization method using Doolittle's Method for solution of linear systems. Decomposes the matrix :math:`A` such that :math:`A = LU`. The input matrix is represented by a list or a tuple. The input matrix is **2-dimensional**, i.e. list of lists of integers and/or floats. :param matrix_a: Input matrix (must be a square matrix) :type matrix_a: list, tuple :return: a tuple containing matrices L and U :rtype: tuple """ # Check if the 2-dimensional input matrix is a square matrix q = len(matrix_a) for idx, m_a in enumerate(matrix_a): if len(m_a) != q: raise ValueError("The input must be a square matrix. " + "Row " + str(idx + 1) + " has a size of " + str(len(m_a)) + ".") # Return L and U matrices return _linalg.doolittle(matrix_a)
python
def lu_decomposition(matrix_a): """ LU-Factorization method using Doolittle's Method for solution of linear systems. Decomposes the matrix :math:`A` such that :math:`A = LU`. The input matrix is represented by a list or a tuple. The input matrix is **2-dimensional**, i.e. list of lists of integers and/or floats. :param matrix_a: Input matrix (must be a square matrix) :type matrix_a: list, tuple :return: a tuple containing matrices L and U :rtype: tuple """ # Check if the 2-dimensional input matrix is a square matrix q = len(matrix_a) for idx, m_a in enumerate(matrix_a): if len(m_a) != q: raise ValueError("The input must be a square matrix. " + "Row " + str(idx + 1) + " has a size of " + str(len(m_a)) + ".") # Return L and U matrices return _linalg.doolittle(matrix_a)
[ "def", "lu_decomposition", "(", "matrix_a", ")", ":", "# Check if the 2-dimensional input matrix is a square matrix", "q", "=", "len", "(", "matrix_a", ")", "for", "idx", ",", "m_a", "in", "enumerate", "(", "matrix_a", ")", ":", "if", "len", "(", "m_a", ")", "!=", "q", ":", "raise", "ValueError", "(", "\"The input must be a square matrix. \"", "+", "\"Row \"", "+", "str", "(", "idx", "+", "1", ")", "+", "\" has a size of \"", "+", "str", "(", "len", "(", "m_a", ")", ")", "+", "\".\"", ")", "# Return L and U matrices", "return", "_linalg", ".", "doolittle", "(", "matrix_a", ")" ]
LU-Factorization method using Doolittle's Method for solution of linear systems. Decomposes the matrix :math:`A` such that :math:`A = LU`. The input matrix is represented by a list or a tuple. The input matrix is **2-dimensional**, i.e. list of lists of integers and/or floats. :param matrix_a: Input matrix (must be a square matrix) :type matrix_a: list, tuple :return: a tuple containing matrices L and U :rtype: tuple
[ "LU", "-", "Factorization", "method", "using", "Doolittle", "s", "Method", "for", "solution", "of", "linear", "systems", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L441-L462
230,377
orbingol/NURBS-Python
geomdl/linalg.py
forward_substitution
def forward_substitution(matrix_l, matrix_b): """ Forward substitution method for the solution of linear systems. Solves the equation :math:`Ly = b` using forward substitution method where :math:`L` is a lower triangular matrix and :math:`b` is a column matrix. :param matrix_l: L, lower triangular matrix :type matrix_l: list, tuple :param matrix_b: b, column matrix :type matrix_b: list, tuple :return: y, column matrix :rtype: list """ q = len(matrix_b) matrix_y = [0.0 for _ in range(q)] matrix_y[0] = float(matrix_b[0]) / float(matrix_l[0][0]) for i in range(1, q): matrix_y[i] = float(matrix_b[i]) - sum([matrix_l[i][j] * matrix_y[j] for j in range(0, i)]) matrix_y[i] /= float(matrix_l[i][i]) return matrix_y
python
def forward_substitution(matrix_l, matrix_b): """ Forward substitution method for the solution of linear systems. Solves the equation :math:`Ly = b` using forward substitution method where :math:`L` is a lower triangular matrix and :math:`b` is a column matrix. :param matrix_l: L, lower triangular matrix :type matrix_l: list, tuple :param matrix_b: b, column matrix :type matrix_b: list, tuple :return: y, column matrix :rtype: list """ q = len(matrix_b) matrix_y = [0.0 for _ in range(q)] matrix_y[0] = float(matrix_b[0]) / float(matrix_l[0][0]) for i in range(1, q): matrix_y[i] = float(matrix_b[i]) - sum([matrix_l[i][j] * matrix_y[j] for j in range(0, i)]) matrix_y[i] /= float(matrix_l[i][i]) return matrix_y
[ "def", "forward_substitution", "(", "matrix_l", ",", "matrix_b", ")", ":", "q", "=", "len", "(", "matrix_b", ")", "matrix_y", "=", "[", "0.0", "for", "_", "in", "range", "(", "q", ")", "]", "matrix_y", "[", "0", "]", "=", "float", "(", "matrix_b", "[", "0", "]", ")", "/", "float", "(", "matrix_l", "[", "0", "]", "[", "0", "]", ")", "for", "i", "in", "range", "(", "1", ",", "q", ")", ":", "matrix_y", "[", "i", "]", "=", "float", "(", "matrix_b", "[", "i", "]", ")", "-", "sum", "(", "[", "matrix_l", "[", "i", "]", "[", "j", "]", "*", "matrix_y", "[", "j", "]", "for", "j", "in", "range", "(", "0", ",", "i", ")", "]", ")", "matrix_y", "[", "i", "]", "/=", "float", "(", "matrix_l", "[", "i", "]", "[", "i", "]", ")", "return", "matrix_y" ]
Forward substitution method for the solution of linear systems. Solves the equation :math:`Ly = b` using forward substitution method where :math:`L` is a lower triangular matrix and :math:`b` is a column matrix. :param matrix_l: L, lower triangular matrix :type matrix_l: list, tuple :param matrix_b: b, column matrix :type matrix_b: list, tuple :return: y, column matrix :rtype: list
[ "Forward", "substitution", "method", "for", "the", "solution", "of", "linear", "systems", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L465-L484
230,378
orbingol/NURBS-Python
geomdl/linalg.py
backward_substitution
def backward_substitution(matrix_u, matrix_y): """ Backward substitution method for the solution of linear systems. Solves the equation :math:`Ux = y` using backward substitution method where :math:`U` is a upper triangular matrix and :math:`y` is a column matrix. :param matrix_u: U, upper triangular matrix :type matrix_u: list, tuple :param matrix_y: y, column matrix :type matrix_y: list, tuple :return: x, column matrix :rtype: list """ q = len(matrix_y) matrix_x = [0.0 for _ in range(q)] matrix_x[q - 1] = float(matrix_y[q - 1]) / float(matrix_u[q - 1][q - 1]) for i in range(q - 2, -1, -1): matrix_x[i] = float(matrix_y[i]) - sum([matrix_u[i][j] * matrix_x[j] for j in range(i, q)]) matrix_x[i] /= float(matrix_u[i][i]) return matrix_x
python
def backward_substitution(matrix_u, matrix_y): """ Backward substitution method for the solution of linear systems. Solves the equation :math:`Ux = y` using backward substitution method where :math:`U` is a upper triangular matrix and :math:`y` is a column matrix. :param matrix_u: U, upper triangular matrix :type matrix_u: list, tuple :param matrix_y: y, column matrix :type matrix_y: list, tuple :return: x, column matrix :rtype: list """ q = len(matrix_y) matrix_x = [0.0 for _ in range(q)] matrix_x[q - 1] = float(matrix_y[q - 1]) / float(matrix_u[q - 1][q - 1]) for i in range(q - 2, -1, -1): matrix_x[i] = float(matrix_y[i]) - sum([matrix_u[i][j] * matrix_x[j] for j in range(i, q)]) matrix_x[i] /= float(matrix_u[i][i]) return matrix_x
[ "def", "backward_substitution", "(", "matrix_u", ",", "matrix_y", ")", ":", "q", "=", "len", "(", "matrix_y", ")", "matrix_x", "=", "[", "0.0", "for", "_", "in", "range", "(", "q", ")", "]", "matrix_x", "[", "q", "-", "1", "]", "=", "float", "(", "matrix_y", "[", "q", "-", "1", "]", ")", "/", "float", "(", "matrix_u", "[", "q", "-", "1", "]", "[", "q", "-", "1", "]", ")", "for", "i", "in", "range", "(", "q", "-", "2", ",", "-", "1", ",", "-", "1", ")", ":", "matrix_x", "[", "i", "]", "=", "float", "(", "matrix_y", "[", "i", "]", ")", "-", "sum", "(", "[", "matrix_u", "[", "i", "]", "[", "j", "]", "*", "matrix_x", "[", "j", "]", "for", "j", "in", "range", "(", "i", ",", "q", ")", "]", ")", "matrix_x", "[", "i", "]", "/=", "float", "(", "matrix_u", "[", "i", "]", "[", "i", "]", ")", "return", "matrix_x" ]
Backward substitution method for the solution of linear systems. Solves the equation :math:`Ux = y` using backward substitution method where :math:`U` is a upper triangular matrix and :math:`y` is a column matrix. :param matrix_u: U, upper triangular matrix :type matrix_u: list, tuple :param matrix_y: y, column matrix :type matrix_y: list, tuple :return: x, column matrix :rtype: list
[ "Backward", "substitution", "method", "for", "the", "solution", "of", "linear", "systems", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L487-L506
230,379
orbingol/NURBS-Python
geomdl/linalg.py
linspace
def linspace(start, stop, num, decimals=18): """ Returns a list of evenly spaced numbers over a specified interval. Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py :param start: starting value :type start: float :param stop: end value :type stop: float :param num: number of samples to generate :type num: int :param decimals: number of significands :type decimals: int :return: a list of equally spaced numbers :rtype: list """ start = float(start) stop = float(stop) if abs(start - stop) <= 10e-8: return [start] num = int(num) if num > 1: div = num - 1 delta = stop - start return [float(("{:." + str(decimals) + "f}").format((start + (float(x) * float(delta) / float(div))))) for x in range(num)] return [float(("{:." + str(decimals) + "f}").format(start))]
python
def linspace(start, stop, num, decimals=18): """ Returns a list of evenly spaced numbers over a specified interval. Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py :param start: starting value :type start: float :param stop: end value :type stop: float :param num: number of samples to generate :type num: int :param decimals: number of significands :type decimals: int :return: a list of equally spaced numbers :rtype: list """ start = float(start) stop = float(stop) if abs(start - stop) <= 10e-8: return [start] num = int(num) if num > 1: div = num - 1 delta = stop - start return [float(("{:." + str(decimals) + "f}").format((start + (float(x) * float(delta) / float(div))))) for x in range(num)] return [float(("{:." + str(decimals) + "f}").format(start))]
[ "def", "linspace", "(", "start", ",", "stop", ",", "num", ",", "decimals", "=", "18", ")", ":", "start", "=", "float", "(", "start", ")", "stop", "=", "float", "(", "stop", ")", "if", "abs", "(", "start", "-", "stop", ")", "<=", "10e-8", ":", "return", "[", "start", "]", "num", "=", "int", "(", "num", ")", "if", "num", ">", "1", ":", "div", "=", "num", "-", "1", "delta", "=", "stop", "-", "start", "return", "[", "float", "(", "(", "\"{:.\"", "+", "str", "(", "decimals", ")", "+", "\"f}\"", ")", ".", "format", "(", "(", "start", "+", "(", "float", "(", "x", ")", "*", "float", "(", "delta", ")", "/", "float", "(", "div", ")", ")", ")", ")", ")", "for", "x", "in", "range", "(", "num", ")", "]", "return", "[", "float", "(", "(", "\"{:.\"", "+", "str", "(", "decimals", ")", "+", "\"f}\"", ")", ".", "format", "(", "start", ")", ")", "]" ]
Returns a list of evenly spaced numbers over a specified interval. Inspired from Numpy's linspace function: https://github.com/numpy/numpy/blob/master/numpy/core/function_base.py :param start: starting value :type start: float :param stop: end value :type stop: float :param num: number of samples to generate :type num: int :param decimals: number of significands :type decimals: int :return: a list of equally spaced numbers :rtype: list
[ "Returns", "a", "list", "of", "evenly", "spaced", "numbers", "over", "a", "specified", "interval", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L509-L535
230,380
orbingol/NURBS-Python
geomdl/linalg.py
convex_hull
def convex_hull(points): """ Returns points on convex hull in counterclockwise order according to Graham's scan algorithm. Reference: https://gist.github.com/arthur-e/5cf52962341310f438e96c1f3c3398b8 .. note:: This implementation only works in 2-dimensional space. :param points: list of 2-dimensional points :type points: list, tuple :return: convex hull of the input points :rtype: list """ turn_left, turn_right, turn_none = (1, -1, 0) def cmp(a, b): return (a > b) - (a < b) def turn(p, q, r): return cmp((q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1]), 0) def keep_left(hull, r): while len(hull) > 1 and turn(hull[-2], hull[-1], r) != turn_left: hull.pop() if not len(hull) or hull[-1] != r: hull.append(r) return hull points = sorted(points) l = reduce(keep_left, points, []) u = reduce(keep_left, reversed(points), []) return l.extend(u[i] for i in range(1, len(u) - 1)) or l
python
def convex_hull(points): """ Returns points on convex hull in counterclockwise order according to Graham's scan algorithm. Reference: https://gist.github.com/arthur-e/5cf52962341310f438e96c1f3c3398b8 .. note:: This implementation only works in 2-dimensional space. :param points: list of 2-dimensional points :type points: list, tuple :return: convex hull of the input points :rtype: list """ turn_left, turn_right, turn_none = (1, -1, 0) def cmp(a, b): return (a > b) - (a < b) def turn(p, q, r): return cmp((q[0] - p[0])*(r[1] - p[1]) - (r[0] - p[0])*(q[1] - p[1]), 0) def keep_left(hull, r): while len(hull) > 1 and turn(hull[-2], hull[-1], r) != turn_left: hull.pop() if not len(hull) or hull[-1] != r: hull.append(r) return hull points = sorted(points) l = reduce(keep_left, points, []) u = reduce(keep_left, reversed(points), []) return l.extend(u[i] for i in range(1, len(u) - 1)) or l
[ "def", "convex_hull", "(", "points", ")", ":", "turn_left", ",", "turn_right", ",", "turn_none", "=", "(", "1", ",", "-", "1", ",", "0", ")", "def", "cmp", "(", "a", ",", "b", ")", ":", "return", "(", "a", ">", "b", ")", "-", "(", "a", "<", "b", ")", "def", "turn", "(", "p", ",", "q", ",", "r", ")", ":", "return", "cmp", "(", "(", "q", "[", "0", "]", "-", "p", "[", "0", "]", ")", "*", "(", "r", "[", "1", "]", "-", "p", "[", "1", "]", ")", "-", "(", "r", "[", "0", "]", "-", "p", "[", "0", "]", ")", "*", "(", "q", "[", "1", "]", "-", "p", "[", "1", "]", ")", ",", "0", ")", "def", "keep_left", "(", "hull", ",", "r", ")", ":", "while", "len", "(", "hull", ")", ">", "1", "and", "turn", "(", "hull", "[", "-", "2", "]", ",", "hull", "[", "-", "1", "]", ",", "r", ")", "!=", "turn_left", ":", "hull", ".", "pop", "(", ")", "if", "not", "len", "(", "hull", ")", "or", "hull", "[", "-", "1", "]", "!=", "r", ":", "hull", ".", "append", "(", "r", ")", "return", "hull", "points", "=", "sorted", "(", "points", ")", "l", "=", "reduce", "(", "keep_left", ",", "points", ",", "[", "]", ")", "u", "=", "reduce", "(", "keep_left", ",", "reversed", "(", "points", ")", ",", "[", "]", ")", "return", "l", ".", "extend", "(", "u", "[", "i", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "u", ")", "-", "1", ")", ")", "or", "l" ]
Returns points on convex hull in counterclockwise order according to Graham's scan algorithm. Reference: https://gist.github.com/arthur-e/5cf52962341310f438e96c1f3c3398b8 .. note:: This implementation only works in 2-dimensional space. :param points: list of 2-dimensional points :type points: list, tuple :return: convex hull of the input points :rtype: list
[ "Returns", "points", "on", "convex", "hull", "in", "counterclockwise", "order", "according", "to", "Graham", "s", "scan", "algorithm", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L565-L595
230,381
orbingol/NURBS-Python
geomdl/linalg.py
is_left
def is_left(point0, point1, point2): """ Tests if a point is Left|On|Right of an infinite line. Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html .. note:: This implementation only works in 2-dimensional space. :param point0: Point P0 :param point1: Point P1 :param point2: Point P2 :return: >0 for P2 left of the line through P0 and P1 =0 for P2 on the line <0 for P2 right of the line """ return ((point1[0] - point0[0]) * (point2[1] - point0[1])) - ((point2[0] - point0[0]) * (point1[1] - point0[1]))
python
def is_left(point0, point1, point2): """ Tests if a point is Left|On|Right of an infinite line. Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html .. note:: This implementation only works in 2-dimensional space. :param point0: Point P0 :param point1: Point P1 :param point2: Point P2 :return: >0 for P2 left of the line through P0 and P1 =0 for P2 on the line <0 for P2 right of the line """ return ((point1[0] - point0[0]) * (point2[1] - point0[1])) - ((point2[0] - point0[0]) * (point1[1] - point0[1]))
[ "def", "is_left", "(", "point0", ",", "point1", ",", "point2", ")", ":", "return", "(", "(", "point1", "[", "0", "]", "-", "point0", "[", "0", "]", ")", "*", "(", "point2", "[", "1", "]", "-", "point0", "[", "1", "]", ")", ")", "-", "(", "(", "point2", "[", "0", "]", "-", "point0", "[", "0", "]", ")", "*", "(", "point1", "[", "1", "]", "-", "point0", "[", "1", "]", ")", ")" ]
Tests if a point is Left|On|Right of an infinite line. Ported from the C++ version: on http://geomalgorithms.com/a03-_inclusion.html .. note:: This implementation only works in 2-dimensional space. :param point0: Point P0 :param point1: Point P1 :param point2: Point P2 :return: >0 for P2 left of the line through P0 and P1 =0 for P2 on the line <0 for P2 right of the line
[ "Tests", "if", "a", "point", "is", "Left|On|Right", "of", "an", "infinite", "line", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L598-L613
230,382
orbingol/NURBS-Python
geomdl/linalg.py
wn_poly
def wn_poly(point, vertices): """ Winding number test for a point in a polygon. Ported from the C++ version: http://geomalgorithms.com/a03-_inclusion.html .. note:: This implementation only works in 2-dimensional space. :param point: point to be tested :type point: list, tuple :param vertices: vertex points of a polygon vertices[n+1] with vertices[n] = vertices[0] :type vertices: list, tuple :return: True if the point is inside the input polygon, False otherwise :rtype: bool """ wn = 0 # the winding number counter v_size = len(vertices) - 1 # loop through all edges of the polygon for i in range(v_size): # edge from V[i] to V[i+1] if vertices[i][1] <= point[1]: # start y <= P.y if vertices[i + 1][1] > point[1]: # an upward crossing if is_left(vertices[i], vertices[i + 1], point) > 0: # P left of edge wn += 1 # have a valid up intersect else: # start y > P.y (no test needed) if vertices[i + 1][1] <= point[1]: # a downward crossing if is_left(vertices[i], vertices[i + 1], point) < 0: # P right of edge wn -= 1 # have a valid down intersect # return wn return bool(wn)
python
def wn_poly(point, vertices): """ Winding number test for a point in a polygon. Ported from the C++ version: http://geomalgorithms.com/a03-_inclusion.html .. note:: This implementation only works in 2-dimensional space. :param point: point to be tested :type point: list, tuple :param vertices: vertex points of a polygon vertices[n+1] with vertices[n] = vertices[0] :type vertices: list, tuple :return: True if the point is inside the input polygon, False otherwise :rtype: bool """ wn = 0 # the winding number counter v_size = len(vertices) - 1 # loop through all edges of the polygon for i in range(v_size): # edge from V[i] to V[i+1] if vertices[i][1] <= point[1]: # start y <= P.y if vertices[i + 1][1] > point[1]: # an upward crossing if is_left(vertices[i], vertices[i + 1], point) > 0: # P left of edge wn += 1 # have a valid up intersect else: # start y > P.y (no test needed) if vertices[i + 1][1] <= point[1]: # a downward crossing if is_left(vertices[i], vertices[i + 1], point) < 0: # P right of edge wn -= 1 # have a valid down intersect # return wn return bool(wn)
[ "def", "wn_poly", "(", "point", ",", "vertices", ")", ":", "wn", "=", "0", "# the winding number counter", "v_size", "=", "len", "(", "vertices", ")", "-", "1", "# loop through all edges of the polygon", "for", "i", "in", "range", "(", "v_size", ")", ":", "# edge from V[i] to V[i+1]", "if", "vertices", "[", "i", "]", "[", "1", "]", "<=", "point", "[", "1", "]", ":", "# start y <= P.y", "if", "vertices", "[", "i", "+", "1", "]", "[", "1", "]", ">", "point", "[", "1", "]", ":", "# an upward crossing", "if", "is_left", "(", "vertices", "[", "i", "]", ",", "vertices", "[", "i", "+", "1", "]", ",", "point", ")", ">", "0", ":", "# P left of edge", "wn", "+=", "1", "# have a valid up intersect", "else", ":", "# start y > P.y (no test needed)", "if", "vertices", "[", "i", "+", "1", "]", "[", "1", "]", "<=", "point", "[", "1", "]", ":", "# a downward crossing", "if", "is_left", "(", "vertices", "[", "i", "]", ",", "vertices", "[", "i", "+", "1", "]", ",", "point", ")", "<", "0", ":", "# P right of edge", "wn", "-=", "1", "# have a valid down intersect", "# return wn", "return", "bool", "(", "wn", ")" ]
Winding number test for a point in a polygon. Ported from the C++ version: http://geomalgorithms.com/a03-_inclusion.html .. note:: This implementation only works in 2-dimensional space. :param point: point to be tested :type point: list, tuple :param vertices: vertex points of a polygon vertices[n+1] with vertices[n] = vertices[0] :type vertices: list, tuple :return: True if the point is inside the input polygon, False otherwise :rtype: bool
[ "Winding", "number", "test", "for", "a", "point", "in", "a", "polygon", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/linalg.py#L616-L644
230,383
orbingol/NURBS-Python
geomdl/construct.py
construct_surface
def construct_surface(direction, *args, **kwargs): """ Generates surfaces from curves. Arguments: * ``args``: a list of curve instances Keyword Arguments (optional): * ``degree``: degree of the 2nd parametric direction * ``knotvector``: knot vector of the 2nd parametric direction * ``rational``: flag to generate rational surfaces :param direction: the direction that the input curves lies, i.e. u or v :type direction: str :return: Surface constructed from the curves on the given parametric direction """ # Input validation possible_dirs = ['u', 'v'] if direction not in possible_dirs: raise GeomdlException("Possible direction values: " + ", ".join([val for val in possible_dirs]), data=dict(input_dir=direction)) size_other = len(args) if size_other < 2: raise GeomdlException("You need to input at least 2 curves") # Get keyword arguments degree_other = kwargs.get('degree', 2) knotvector_other = kwargs.get('knotvector', knotvector.generate(degree_other, size_other)) rational = kwargs.get('rational', args[0].rational) # Construct the control points of the new surface degree = args[0].degree num_ctrlpts = args[0].ctrlpts_size new_ctrlpts = [] new_weights = [] for idx, arg in enumerate(args): if degree != arg.degree: raise GeomdlException("Input curves must have the same degrees", data=dict(idx=idx, degree=degree, degree_arg=arg.degree)) if num_ctrlpts != arg.ctrlpts_size: raise GeomdlException("Input curves must have the same number of control points", data=dict(idx=idx, size=num_ctrlpts, size_arg=arg.ctrlpts_size)) new_ctrlpts += list(arg.ctrlpts) if rational: if arg.weights is None: raise GeomdlException("Expecting a rational curve", data=dict(idx=idx, rational=rational, rational_arg=arg.rational)) new_weights += list(arg.weights) # Set variables w.r.t. input direction if direction == 'u': degree_u = degree_other degree_v = degree knotvector_u = knotvector_other knotvector_v = args[0].knotvector size_u = size_other size_v = num_ctrlpts else: degree_u = degree degree_v = degree_other knotvector_u = args[0].knotvector knotvector_v = knotvector_other size_u = num_ctrlpts size_v = size_other if rational: ctrlptsw = compatibility.combine_ctrlpts_weights(new_ctrlpts, new_weights) ctrlptsw = compatibility.flip_ctrlpts_u(ctrlptsw, size_u, size_v) new_ctrlpts, new_weights = compatibility.separate_ctrlpts_weights(ctrlptsw) else: new_ctrlpts = compatibility.flip_ctrlpts_u(new_ctrlpts, size_u, size_v) # Generate the surface ns = shortcuts.generate_surface(rational) ns.degree_u = degree_u ns.degree_v = degree_v ns.ctrlpts_size_u = size_u ns.ctrlpts_size_v = size_v ns.ctrlpts = new_ctrlpts if rational: ns.weights = new_weights ns.knotvector_u = knotvector_u ns.knotvector_v = knotvector_v # Return constructed surface return ns
python
def construct_surface(direction, *args, **kwargs): """ Generates surfaces from curves. Arguments: * ``args``: a list of curve instances Keyword Arguments (optional): * ``degree``: degree of the 2nd parametric direction * ``knotvector``: knot vector of the 2nd parametric direction * ``rational``: flag to generate rational surfaces :param direction: the direction that the input curves lies, i.e. u or v :type direction: str :return: Surface constructed from the curves on the given parametric direction """ # Input validation possible_dirs = ['u', 'v'] if direction not in possible_dirs: raise GeomdlException("Possible direction values: " + ", ".join([val for val in possible_dirs]), data=dict(input_dir=direction)) size_other = len(args) if size_other < 2: raise GeomdlException("You need to input at least 2 curves") # Get keyword arguments degree_other = kwargs.get('degree', 2) knotvector_other = kwargs.get('knotvector', knotvector.generate(degree_other, size_other)) rational = kwargs.get('rational', args[0].rational) # Construct the control points of the new surface degree = args[0].degree num_ctrlpts = args[0].ctrlpts_size new_ctrlpts = [] new_weights = [] for idx, arg in enumerate(args): if degree != arg.degree: raise GeomdlException("Input curves must have the same degrees", data=dict(idx=idx, degree=degree, degree_arg=arg.degree)) if num_ctrlpts != arg.ctrlpts_size: raise GeomdlException("Input curves must have the same number of control points", data=dict(idx=idx, size=num_ctrlpts, size_arg=arg.ctrlpts_size)) new_ctrlpts += list(arg.ctrlpts) if rational: if arg.weights is None: raise GeomdlException("Expecting a rational curve", data=dict(idx=idx, rational=rational, rational_arg=arg.rational)) new_weights += list(arg.weights) # Set variables w.r.t. input direction if direction == 'u': degree_u = degree_other degree_v = degree knotvector_u = knotvector_other knotvector_v = args[0].knotvector size_u = size_other size_v = num_ctrlpts else: degree_u = degree degree_v = degree_other knotvector_u = args[0].knotvector knotvector_v = knotvector_other size_u = num_ctrlpts size_v = size_other if rational: ctrlptsw = compatibility.combine_ctrlpts_weights(new_ctrlpts, new_weights) ctrlptsw = compatibility.flip_ctrlpts_u(ctrlptsw, size_u, size_v) new_ctrlpts, new_weights = compatibility.separate_ctrlpts_weights(ctrlptsw) else: new_ctrlpts = compatibility.flip_ctrlpts_u(new_ctrlpts, size_u, size_v) # Generate the surface ns = shortcuts.generate_surface(rational) ns.degree_u = degree_u ns.degree_v = degree_v ns.ctrlpts_size_u = size_u ns.ctrlpts_size_v = size_v ns.ctrlpts = new_ctrlpts if rational: ns.weights = new_weights ns.knotvector_u = knotvector_u ns.knotvector_v = knotvector_v # Return constructed surface return ns
[ "def", "construct_surface", "(", "direction", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "# Input validation", "possible_dirs", "=", "[", "'u'", ",", "'v'", "]", "if", "direction", "not", "in", "possible_dirs", ":", "raise", "GeomdlException", "(", "\"Possible direction values: \"", "+", "\", \"", ".", "join", "(", "[", "val", "for", "val", "in", "possible_dirs", "]", ")", ",", "data", "=", "dict", "(", "input_dir", "=", "direction", ")", ")", "size_other", "=", "len", "(", "args", ")", "if", "size_other", "<", "2", ":", "raise", "GeomdlException", "(", "\"You need to input at least 2 curves\"", ")", "# Get keyword arguments", "degree_other", "=", "kwargs", ".", "get", "(", "'degree'", ",", "2", ")", "knotvector_other", "=", "kwargs", ".", "get", "(", "'knotvector'", ",", "knotvector", ".", "generate", "(", "degree_other", ",", "size_other", ")", ")", "rational", "=", "kwargs", ".", "get", "(", "'rational'", ",", "args", "[", "0", "]", ".", "rational", ")", "# Construct the control points of the new surface", "degree", "=", "args", "[", "0", "]", ".", "degree", "num_ctrlpts", "=", "args", "[", "0", "]", ".", "ctrlpts_size", "new_ctrlpts", "=", "[", "]", "new_weights", "=", "[", "]", "for", "idx", ",", "arg", "in", "enumerate", "(", "args", ")", ":", "if", "degree", "!=", "arg", ".", "degree", ":", "raise", "GeomdlException", "(", "\"Input curves must have the same degrees\"", ",", "data", "=", "dict", "(", "idx", "=", "idx", ",", "degree", "=", "degree", ",", "degree_arg", "=", "arg", ".", "degree", ")", ")", "if", "num_ctrlpts", "!=", "arg", ".", "ctrlpts_size", ":", "raise", "GeomdlException", "(", "\"Input curves must have the same number of control points\"", ",", "data", "=", "dict", "(", "idx", "=", "idx", ",", "size", "=", "num_ctrlpts", ",", "size_arg", "=", "arg", ".", "ctrlpts_size", ")", ")", "new_ctrlpts", "+=", "list", "(", "arg", ".", "ctrlpts", ")", "if", "rational", ":", "if", "arg", ".", "weights", "is", "None", ":", "raise", "GeomdlException", "(", "\"Expecting a rational curve\"", ",", "data", "=", "dict", "(", "idx", "=", "idx", ",", "rational", "=", "rational", ",", "rational_arg", "=", "arg", ".", "rational", ")", ")", "new_weights", "+=", "list", "(", "arg", ".", "weights", ")", "# Set variables w.r.t. input direction", "if", "direction", "==", "'u'", ":", "degree_u", "=", "degree_other", "degree_v", "=", "degree", "knotvector_u", "=", "knotvector_other", "knotvector_v", "=", "args", "[", "0", "]", ".", "knotvector", "size_u", "=", "size_other", "size_v", "=", "num_ctrlpts", "else", ":", "degree_u", "=", "degree", "degree_v", "=", "degree_other", "knotvector_u", "=", "args", "[", "0", "]", ".", "knotvector", "knotvector_v", "=", "knotvector_other", "size_u", "=", "num_ctrlpts", "size_v", "=", "size_other", "if", "rational", ":", "ctrlptsw", "=", "compatibility", ".", "combine_ctrlpts_weights", "(", "new_ctrlpts", ",", "new_weights", ")", "ctrlptsw", "=", "compatibility", ".", "flip_ctrlpts_u", "(", "ctrlptsw", ",", "size_u", ",", "size_v", ")", "new_ctrlpts", ",", "new_weights", "=", "compatibility", ".", "separate_ctrlpts_weights", "(", "ctrlptsw", ")", "else", ":", "new_ctrlpts", "=", "compatibility", ".", "flip_ctrlpts_u", "(", "new_ctrlpts", ",", "size_u", ",", "size_v", ")", "# Generate the surface", "ns", "=", "shortcuts", ".", "generate_surface", "(", "rational", ")", "ns", ".", "degree_u", "=", "degree_u", "ns", ".", "degree_v", "=", "degree_v", "ns", ".", "ctrlpts_size_u", "=", "size_u", "ns", ".", "ctrlpts_size_v", "=", "size_v", "ns", ".", "ctrlpts", "=", "new_ctrlpts", "if", "rational", ":", "ns", ".", "weights", "=", "new_weights", "ns", ".", "knotvector_u", "=", "knotvector_u", "ns", ".", "knotvector_v", "=", "knotvector_v", "# Return constructed surface", "return", "ns" ]
Generates surfaces from curves. Arguments: * ``args``: a list of curve instances Keyword Arguments (optional): * ``degree``: degree of the 2nd parametric direction * ``knotvector``: knot vector of the 2nd parametric direction * ``rational``: flag to generate rational surfaces :param direction: the direction that the input curves lies, i.e. u or v :type direction: str :return: Surface constructed from the curves on the given parametric direction
[ "Generates", "surfaces", "from", "curves", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/construct.py#L16-L100
230,384
orbingol/NURBS-Python
geomdl/construct.py
extract_curves
def extract_curves(psurf, **kwargs): """ Extracts curves from a surface. The return value is a ``dict`` object containing the following keys: * ``u``: the curves which generate u-direction (or which lie on the v-direction) * ``v``: the curves which generate v-direction (or which lie on the u-direction) As an example; if a curve lies on the u-direction, then its knotvector is equal to surface's knotvector on the v-direction and vice versa. The curve extraction process can be controlled via ``extract_u`` and ``extract_v`` boolean keyword arguments. :param psurf: input surface :type psurf: abstract.Surface :return: extracted curves :rtype: dict """ if psurf.pdimension != 2: raise GeomdlException("The input should be a spline surface") if len(psurf) != 1: raise GeomdlException("Can only operate on single spline surfaces") # Get keyword arguments extract_u = kwargs.get('extract_u', True) extract_v = kwargs.get('extract_v', True) # Get data from the surface object surf_data = psurf.data rational = surf_data['rational'] degree_u = surf_data['degree'][0] degree_v = surf_data['degree'][1] kv_u = surf_data['knotvector'][0] kv_v = surf_data['knotvector'][1] size_u = surf_data['size'][0] size_v = surf_data['size'][1] cpts = surf_data['control_points'] # Determine object type obj = shortcuts.generate_curve(rational) # v-direction crvlist_v = [] if extract_v: for u in range(size_u): curve = obj.__class__() curve.degree = degree_v curve.set_ctrlpts([cpts[v + (size_v * u)] for v in range(size_v)]) curve.knotvector = kv_v crvlist_v.append(curve) # u-direction crvlist_u = [] if extract_u: for v in range(size_v): curve = obj.__class__() curve.degree = degree_u curve.set_ctrlpts([cpts[v + (size_v * u)] for u in range(size_u)]) curve.knotvector = kv_u crvlist_u.append(curve) # Return shapes as a dict object return dict(u=crvlist_u, v=crvlist_v)
python
def extract_curves(psurf, **kwargs): """ Extracts curves from a surface. The return value is a ``dict`` object containing the following keys: * ``u``: the curves which generate u-direction (or which lie on the v-direction) * ``v``: the curves which generate v-direction (or which lie on the u-direction) As an example; if a curve lies on the u-direction, then its knotvector is equal to surface's knotvector on the v-direction and vice versa. The curve extraction process can be controlled via ``extract_u`` and ``extract_v`` boolean keyword arguments. :param psurf: input surface :type psurf: abstract.Surface :return: extracted curves :rtype: dict """ if psurf.pdimension != 2: raise GeomdlException("The input should be a spline surface") if len(psurf) != 1: raise GeomdlException("Can only operate on single spline surfaces") # Get keyword arguments extract_u = kwargs.get('extract_u', True) extract_v = kwargs.get('extract_v', True) # Get data from the surface object surf_data = psurf.data rational = surf_data['rational'] degree_u = surf_data['degree'][0] degree_v = surf_data['degree'][1] kv_u = surf_data['knotvector'][0] kv_v = surf_data['knotvector'][1] size_u = surf_data['size'][0] size_v = surf_data['size'][1] cpts = surf_data['control_points'] # Determine object type obj = shortcuts.generate_curve(rational) # v-direction crvlist_v = [] if extract_v: for u in range(size_u): curve = obj.__class__() curve.degree = degree_v curve.set_ctrlpts([cpts[v + (size_v * u)] for v in range(size_v)]) curve.knotvector = kv_v crvlist_v.append(curve) # u-direction crvlist_u = [] if extract_u: for v in range(size_v): curve = obj.__class__() curve.degree = degree_u curve.set_ctrlpts([cpts[v + (size_v * u)] for u in range(size_u)]) curve.knotvector = kv_u crvlist_u.append(curve) # Return shapes as a dict object return dict(u=crvlist_u, v=crvlist_v)
[ "def", "extract_curves", "(", "psurf", ",", "*", "*", "kwargs", ")", ":", "if", "psurf", ".", "pdimension", "!=", "2", ":", "raise", "GeomdlException", "(", "\"The input should be a spline surface\"", ")", "if", "len", "(", "psurf", ")", "!=", "1", ":", "raise", "GeomdlException", "(", "\"Can only operate on single spline surfaces\"", ")", "# Get keyword arguments", "extract_u", "=", "kwargs", ".", "get", "(", "'extract_u'", ",", "True", ")", "extract_v", "=", "kwargs", ".", "get", "(", "'extract_v'", ",", "True", ")", "# Get data from the surface object", "surf_data", "=", "psurf", ".", "data", "rational", "=", "surf_data", "[", "'rational'", "]", "degree_u", "=", "surf_data", "[", "'degree'", "]", "[", "0", "]", "degree_v", "=", "surf_data", "[", "'degree'", "]", "[", "1", "]", "kv_u", "=", "surf_data", "[", "'knotvector'", "]", "[", "0", "]", "kv_v", "=", "surf_data", "[", "'knotvector'", "]", "[", "1", "]", "size_u", "=", "surf_data", "[", "'size'", "]", "[", "0", "]", "size_v", "=", "surf_data", "[", "'size'", "]", "[", "1", "]", "cpts", "=", "surf_data", "[", "'control_points'", "]", "# Determine object type", "obj", "=", "shortcuts", ".", "generate_curve", "(", "rational", ")", "# v-direction", "crvlist_v", "=", "[", "]", "if", "extract_v", ":", "for", "u", "in", "range", "(", "size_u", ")", ":", "curve", "=", "obj", ".", "__class__", "(", ")", "curve", ".", "degree", "=", "degree_v", "curve", ".", "set_ctrlpts", "(", "[", "cpts", "[", "v", "+", "(", "size_v", "*", "u", ")", "]", "for", "v", "in", "range", "(", "size_v", ")", "]", ")", "curve", ".", "knotvector", "=", "kv_v", "crvlist_v", ".", "append", "(", "curve", ")", "# u-direction", "crvlist_u", "=", "[", "]", "if", "extract_u", ":", "for", "v", "in", "range", "(", "size_v", ")", ":", "curve", "=", "obj", ".", "__class__", "(", ")", "curve", ".", "degree", "=", "degree_u", "curve", ".", "set_ctrlpts", "(", "[", "cpts", "[", "v", "+", "(", "size_v", "*", "u", ")", "]", "for", "u", "in", "range", "(", "size_u", ")", "]", ")", "curve", ".", "knotvector", "=", "kv_u", "crvlist_u", ".", "append", "(", "curve", ")", "# Return shapes as a dict object", "return", "dict", "(", "u", "=", "crvlist_u", ",", "v", "=", "crvlist_v", ")" ]
Extracts curves from a surface. The return value is a ``dict`` object containing the following keys: * ``u``: the curves which generate u-direction (or which lie on the v-direction) * ``v``: the curves which generate v-direction (or which lie on the u-direction) As an example; if a curve lies on the u-direction, then its knotvector is equal to surface's knotvector on the v-direction and vice versa. The curve extraction process can be controlled via ``extract_u`` and ``extract_v`` boolean keyword arguments. :param psurf: input surface :type psurf: abstract.Surface :return: extracted curves :rtype: dict
[ "Extracts", "curves", "from", "a", "surface", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/construct.py#L208-L270
230,385
orbingol/NURBS-Python
geomdl/construct.py
extract_surfaces
def extract_surfaces(pvol): """ Extracts surfaces from a volume. :param pvol: input volume :type pvol: abstract.Volume :return: extracted surface :rtype: dict """ if pvol.pdimension != 3: raise GeomdlException("The input should be a spline volume") if len(pvol) != 1: raise GeomdlException("Can only operate on single spline volumes") # Get data from the volume object vol_data = pvol.data rational = vol_data['rational'] degree_u = vol_data['degree'][0] degree_v = vol_data['degree'][1] degree_w = vol_data['degree'][2] kv_u = vol_data['knotvector'][0] kv_v = vol_data['knotvector'][1] kv_w = vol_data['knotvector'][2] size_u = vol_data['size'][0] size_v = vol_data['size'][1] size_w = vol_data['size'][2] cpts = vol_data['control_points'] # Determine object type obj = shortcuts.generate_surface(rational) # u-v plane surflist_uv = [] for w in range(size_w): surf = obj.__class__() surf.degree_u = degree_u surf.degree_v = degree_v surf.ctrlpts_size_u = size_u surf.ctrlpts_size_v = size_v surf.ctrlpts2d = [[cpts[v + (size_v * (u + (size_u * w)))] for v in range(size_v)] for u in range(size_u)] surf.knotvector_u = kv_u surf.knotvector_v = kv_v surflist_uv.append(surf) # u-w plane surflist_uw = [] for v in range(size_v): surf = obj.__class__() surf.degree_u = degree_u surf.degree_v = degree_w surf.ctrlpts_size_u = size_u surf.ctrlpts_size_v = size_w surf.ctrlpts2d = [[cpts[v + (size_v * (u + (size_u * w)))] for w in range(size_w)] for u in range(size_u)] surf.knotvector_u = kv_u surf.knotvector_v = kv_w surflist_uw.append(surf) # v-w plane surflist_vw = [] for u in range(size_u): surf = obj.__class__() surf.degree_u = degree_v surf.degree_v = degree_w surf.ctrlpts_size_u = size_v surf.ctrlpts_size_v = size_w surf.ctrlpts2d = [[cpts[v + (size_v * (u + (size_u * w)))] for w in range(size_w)] for v in range(size_v)] surf.knotvector_u = kv_v surf.knotvector_v = kv_w surflist_vw.append(surf) # Return shapes as a dict object return dict(uv=surflist_uv, uw=surflist_uw, vw=surflist_vw)
python
def extract_surfaces(pvol): """ Extracts surfaces from a volume. :param pvol: input volume :type pvol: abstract.Volume :return: extracted surface :rtype: dict """ if pvol.pdimension != 3: raise GeomdlException("The input should be a spline volume") if len(pvol) != 1: raise GeomdlException("Can only operate on single spline volumes") # Get data from the volume object vol_data = pvol.data rational = vol_data['rational'] degree_u = vol_data['degree'][0] degree_v = vol_data['degree'][1] degree_w = vol_data['degree'][2] kv_u = vol_data['knotvector'][0] kv_v = vol_data['knotvector'][1] kv_w = vol_data['knotvector'][2] size_u = vol_data['size'][0] size_v = vol_data['size'][1] size_w = vol_data['size'][2] cpts = vol_data['control_points'] # Determine object type obj = shortcuts.generate_surface(rational) # u-v plane surflist_uv = [] for w in range(size_w): surf = obj.__class__() surf.degree_u = degree_u surf.degree_v = degree_v surf.ctrlpts_size_u = size_u surf.ctrlpts_size_v = size_v surf.ctrlpts2d = [[cpts[v + (size_v * (u + (size_u * w)))] for v in range(size_v)] for u in range(size_u)] surf.knotvector_u = kv_u surf.knotvector_v = kv_v surflist_uv.append(surf) # u-w plane surflist_uw = [] for v in range(size_v): surf = obj.__class__() surf.degree_u = degree_u surf.degree_v = degree_w surf.ctrlpts_size_u = size_u surf.ctrlpts_size_v = size_w surf.ctrlpts2d = [[cpts[v + (size_v * (u + (size_u * w)))] for w in range(size_w)] for u in range(size_u)] surf.knotvector_u = kv_u surf.knotvector_v = kv_w surflist_uw.append(surf) # v-w plane surflist_vw = [] for u in range(size_u): surf = obj.__class__() surf.degree_u = degree_v surf.degree_v = degree_w surf.ctrlpts_size_u = size_v surf.ctrlpts_size_v = size_w surf.ctrlpts2d = [[cpts[v + (size_v * (u + (size_u * w)))] for w in range(size_w)] for v in range(size_v)] surf.knotvector_u = kv_v surf.knotvector_v = kv_w surflist_vw.append(surf) # Return shapes as a dict object return dict(uv=surflist_uv, uw=surflist_uw, vw=surflist_vw)
[ "def", "extract_surfaces", "(", "pvol", ")", ":", "if", "pvol", ".", "pdimension", "!=", "3", ":", "raise", "GeomdlException", "(", "\"The input should be a spline volume\"", ")", "if", "len", "(", "pvol", ")", "!=", "1", ":", "raise", "GeomdlException", "(", "\"Can only operate on single spline volumes\"", ")", "# Get data from the volume object", "vol_data", "=", "pvol", ".", "data", "rational", "=", "vol_data", "[", "'rational'", "]", "degree_u", "=", "vol_data", "[", "'degree'", "]", "[", "0", "]", "degree_v", "=", "vol_data", "[", "'degree'", "]", "[", "1", "]", "degree_w", "=", "vol_data", "[", "'degree'", "]", "[", "2", "]", "kv_u", "=", "vol_data", "[", "'knotvector'", "]", "[", "0", "]", "kv_v", "=", "vol_data", "[", "'knotvector'", "]", "[", "1", "]", "kv_w", "=", "vol_data", "[", "'knotvector'", "]", "[", "2", "]", "size_u", "=", "vol_data", "[", "'size'", "]", "[", "0", "]", "size_v", "=", "vol_data", "[", "'size'", "]", "[", "1", "]", "size_w", "=", "vol_data", "[", "'size'", "]", "[", "2", "]", "cpts", "=", "vol_data", "[", "'control_points'", "]", "# Determine object type", "obj", "=", "shortcuts", ".", "generate_surface", "(", "rational", ")", "# u-v plane", "surflist_uv", "=", "[", "]", "for", "w", "in", "range", "(", "size_w", ")", ":", "surf", "=", "obj", ".", "__class__", "(", ")", "surf", ".", "degree_u", "=", "degree_u", "surf", ".", "degree_v", "=", "degree_v", "surf", ".", "ctrlpts_size_u", "=", "size_u", "surf", ".", "ctrlpts_size_v", "=", "size_v", "surf", ".", "ctrlpts2d", "=", "[", "[", "cpts", "[", "v", "+", "(", "size_v", "*", "(", "u", "+", "(", "size_u", "*", "w", ")", ")", ")", "]", "for", "v", "in", "range", "(", "size_v", ")", "]", "for", "u", "in", "range", "(", "size_u", ")", "]", "surf", ".", "knotvector_u", "=", "kv_u", "surf", ".", "knotvector_v", "=", "kv_v", "surflist_uv", ".", "append", "(", "surf", ")", "# u-w plane", "surflist_uw", "=", "[", "]", "for", "v", "in", "range", "(", "size_v", ")", ":", "surf", "=", "obj", ".", "__class__", "(", ")", "surf", ".", "degree_u", "=", "degree_u", "surf", ".", "degree_v", "=", "degree_w", "surf", ".", "ctrlpts_size_u", "=", "size_u", "surf", ".", "ctrlpts_size_v", "=", "size_w", "surf", ".", "ctrlpts2d", "=", "[", "[", "cpts", "[", "v", "+", "(", "size_v", "*", "(", "u", "+", "(", "size_u", "*", "w", ")", ")", ")", "]", "for", "w", "in", "range", "(", "size_w", ")", "]", "for", "u", "in", "range", "(", "size_u", ")", "]", "surf", ".", "knotvector_u", "=", "kv_u", "surf", ".", "knotvector_v", "=", "kv_w", "surflist_uw", ".", "append", "(", "surf", ")", "# v-w plane", "surflist_vw", "=", "[", "]", "for", "u", "in", "range", "(", "size_u", ")", ":", "surf", "=", "obj", ".", "__class__", "(", ")", "surf", ".", "degree_u", "=", "degree_v", "surf", ".", "degree_v", "=", "degree_w", "surf", ".", "ctrlpts_size_u", "=", "size_v", "surf", ".", "ctrlpts_size_v", "=", "size_w", "surf", ".", "ctrlpts2d", "=", "[", "[", "cpts", "[", "v", "+", "(", "size_v", "*", "(", "u", "+", "(", "size_u", "*", "w", ")", ")", ")", "]", "for", "w", "in", "range", "(", "size_w", ")", "]", "for", "v", "in", "range", "(", "size_v", ")", "]", "surf", ".", "knotvector_u", "=", "kv_v", "surf", ".", "knotvector_v", "=", "kv_w", "surflist_vw", ".", "append", "(", "surf", ")", "# Return shapes as a dict object", "return", "dict", "(", "uv", "=", "surflist_uv", ",", "uw", "=", "surflist_uw", ",", "vw", "=", "surflist_vw", ")" ]
Extracts surfaces from a volume. :param pvol: input volume :type pvol: abstract.Volume :return: extracted surface :rtype: dict
[ "Extracts", "surfaces", "from", "a", "volume", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/construct.py#L273-L343
230,386
orbingol/NURBS-Python
geomdl/construct.py
extract_isosurface
def extract_isosurface(pvol): """ Extracts the largest isosurface from a volume. The following example illustrates one of the usage scenarios: .. code-block:: python :linenos: from geomdl import construct, multi from geomdl.visualization import VisMPL # Assuming that "myvol" variable stores your spline volume information isosrf = construct.extract_isosurface(myvol) # Create a surface container to store extracted isosurface msurf = multi.SurfaceContainer(isosrf) # Set visualization components msurf.vis = VisMPL.VisSurface(VisMPL.VisConfig(ctrlpts=False)) # Render isosurface msurf.render() :param pvol: input volume :type pvol: abstract.Volume :return: isosurface (as a tuple of surfaces) :rtype: tuple """ if pvol.pdimension != 3: raise GeomdlException("The input should be a spline volume") if len(pvol) != 1: raise GeomdlException("Can only operate on single spline volumes") # Extract surfaces from the parametric volume isosrf = extract_surfaces(pvol) # Return the isosurface return isosrf['uv'][0], isosrf['uv'][-1], isosrf['uw'][0], isosrf['uw'][-1], isosrf['vw'][0], isosrf['vw'][-1]
python
def extract_isosurface(pvol): """ Extracts the largest isosurface from a volume. The following example illustrates one of the usage scenarios: .. code-block:: python :linenos: from geomdl import construct, multi from geomdl.visualization import VisMPL # Assuming that "myvol" variable stores your spline volume information isosrf = construct.extract_isosurface(myvol) # Create a surface container to store extracted isosurface msurf = multi.SurfaceContainer(isosrf) # Set visualization components msurf.vis = VisMPL.VisSurface(VisMPL.VisConfig(ctrlpts=False)) # Render isosurface msurf.render() :param pvol: input volume :type pvol: abstract.Volume :return: isosurface (as a tuple of surfaces) :rtype: tuple """ if pvol.pdimension != 3: raise GeomdlException("The input should be a spline volume") if len(pvol) != 1: raise GeomdlException("Can only operate on single spline volumes") # Extract surfaces from the parametric volume isosrf = extract_surfaces(pvol) # Return the isosurface return isosrf['uv'][0], isosrf['uv'][-1], isosrf['uw'][0], isosrf['uw'][-1], isosrf['vw'][0], isosrf['vw'][-1]
[ "def", "extract_isosurface", "(", "pvol", ")", ":", "if", "pvol", ".", "pdimension", "!=", "3", ":", "raise", "GeomdlException", "(", "\"The input should be a spline volume\"", ")", "if", "len", "(", "pvol", ")", "!=", "1", ":", "raise", "GeomdlException", "(", "\"Can only operate on single spline volumes\"", ")", "# Extract surfaces from the parametric volume", "isosrf", "=", "extract_surfaces", "(", "pvol", ")", "# Return the isosurface", "return", "isosrf", "[", "'uv'", "]", "[", "0", "]", ",", "isosrf", "[", "'uv'", "]", "[", "-", "1", "]", ",", "isosrf", "[", "'uw'", "]", "[", "0", "]", ",", "isosrf", "[", "'uw'", "]", "[", "-", "1", "]", ",", "isosrf", "[", "'vw'", "]", "[", "0", "]", ",", "isosrf", "[", "'vw'", "]", "[", "-", "1", "]" ]
Extracts the largest isosurface from a volume. The following example illustrates one of the usage scenarios: .. code-block:: python :linenos: from geomdl import construct, multi from geomdl.visualization import VisMPL # Assuming that "myvol" variable stores your spline volume information isosrf = construct.extract_isosurface(myvol) # Create a surface container to store extracted isosurface msurf = multi.SurfaceContainer(isosrf) # Set visualization components msurf.vis = VisMPL.VisSurface(VisMPL.VisConfig(ctrlpts=False)) # Render isosurface msurf.render() :param pvol: input volume :type pvol: abstract.Volume :return: isosurface (as a tuple of surfaces) :rtype: tuple
[ "Extracts", "the", "largest", "isosurface", "from", "a", "volume", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/construct.py#L346-L383
230,387
orbingol/NURBS-Python
geomdl/trimming.py
check_trim_curve
def check_trim_curve(curve, parbox, **kwargs): """ Checks if the trim curve was closed and sense was set. :param curve: trim curve :param parbox: parameter space bounding box of the underlying surface :return: a tuple containing the status of the operation and list of extra trim curves generated :rtype: tuple """ def next_idx(edge_idx, direction): tmp = edge_idx + direction if tmp < 0: return 3 if tmp > 3: return 0 return tmp # Keyword arguments tol = kwargs.get('tol', 10e-8) # First, check if the curve is closed dist = linalg.point_distance(curve.evalpts[0], curve.evalpts[-1]) if dist <= tol: # Curve is closed return detect_sense(curve, tol), [] else: # Define start and end points of the trim curve pt_start = curve.evalpts[0] pt_end = curve.evalpts[-1] # Search for intersections idx_spt = -1 idx_ept = -1 for idx in range(len(parbox) - 1): if detect_intersection(parbox[idx], parbox[idx + 1], pt_start, tol): idx_spt = idx if detect_intersection(parbox[idx], parbox[idx + 1], pt_end, tol): idx_ept = idx # Check result of the intersection if idx_spt < 0 or idx_ept < 0: # Curve does not intersect any edges of the parametric space # TODO: Extrapolate the curve using the tangent vector and find intersections return False, [] else: # Get sense of the original curve c_sense = curve.opt_get('reversed') # If sense is None, then detect sense if c_sense is None: # Get evaluated points pts = curve.evalpts num_pts = len(pts) # Find sense tmp_sense = 0 for pti in range(1, num_pts - 1): tmp_sense = detect_ccw(pts[pti - 1], pts[pti], pts[pti + 1], tol) if tmp_sense != 0: break if tmp_sense == 0: tmp_sense2 = detect_ccw(pts[int(num_pts/3)], pts[int(2*num_pts/3)], pts[-int(num_pts/3)], tol) if tmp_sense2 != 0: tmp_sense = -tmp_sense2 else: # We cannot decide which region to trim. Therefore, ignore this curve. return False, [] c_sense = 0 if tmp_sense > 0 else 1 # Update sense of the original curve curve.opt = ['reversed', c_sense] # Generate a curve container and add the original curve cont = [curve] move_dir = -1 if c_sense == 0 else 1 # Curve intersects with the edges of the parametric space counter = 0 while counter < 4: if idx_ept == idx_spt: counter = 5 pt_start = curve.evalpts[0] else: # Find next index idx_ept = next_idx(idx_ept, move_dir) # Update tracked last point pt_start = parbox[idx_ept + 1 - c_sense] # Increment counter counter += 1 # Generate the curve segment crv = shortcuts.generate_curve() crv.degree = 1 crv.ctrlpts = [pt_end, pt_start] crv.knotvector = [0, 0, 1, 1] crv.opt = ['reversed', c_sense] pt_end = pt_start # Add it to the container cont.append(crv) # Update curve return True, cont
python
def check_trim_curve(curve, parbox, **kwargs): """ Checks if the trim curve was closed and sense was set. :param curve: trim curve :param parbox: parameter space bounding box of the underlying surface :return: a tuple containing the status of the operation and list of extra trim curves generated :rtype: tuple """ def next_idx(edge_idx, direction): tmp = edge_idx + direction if tmp < 0: return 3 if tmp > 3: return 0 return tmp # Keyword arguments tol = kwargs.get('tol', 10e-8) # First, check if the curve is closed dist = linalg.point_distance(curve.evalpts[0], curve.evalpts[-1]) if dist <= tol: # Curve is closed return detect_sense(curve, tol), [] else: # Define start and end points of the trim curve pt_start = curve.evalpts[0] pt_end = curve.evalpts[-1] # Search for intersections idx_spt = -1 idx_ept = -1 for idx in range(len(parbox) - 1): if detect_intersection(parbox[idx], parbox[idx + 1], pt_start, tol): idx_spt = idx if detect_intersection(parbox[idx], parbox[idx + 1], pt_end, tol): idx_ept = idx # Check result of the intersection if idx_spt < 0 or idx_ept < 0: # Curve does not intersect any edges of the parametric space # TODO: Extrapolate the curve using the tangent vector and find intersections return False, [] else: # Get sense of the original curve c_sense = curve.opt_get('reversed') # If sense is None, then detect sense if c_sense is None: # Get evaluated points pts = curve.evalpts num_pts = len(pts) # Find sense tmp_sense = 0 for pti in range(1, num_pts - 1): tmp_sense = detect_ccw(pts[pti - 1], pts[pti], pts[pti + 1], tol) if tmp_sense != 0: break if tmp_sense == 0: tmp_sense2 = detect_ccw(pts[int(num_pts/3)], pts[int(2*num_pts/3)], pts[-int(num_pts/3)], tol) if tmp_sense2 != 0: tmp_sense = -tmp_sense2 else: # We cannot decide which region to trim. Therefore, ignore this curve. return False, [] c_sense = 0 if tmp_sense > 0 else 1 # Update sense of the original curve curve.opt = ['reversed', c_sense] # Generate a curve container and add the original curve cont = [curve] move_dir = -1 if c_sense == 0 else 1 # Curve intersects with the edges of the parametric space counter = 0 while counter < 4: if idx_ept == idx_spt: counter = 5 pt_start = curve.evalpts[0] else: # Find next index idx_ept = next_idx(idx_ept, move_dir) # Update tracked last point pt_start = parbox[idx_ept + 1 - c_sense] # Increment counter counter += 1 # Generate the curve segment crv = shortcuts.generate_curve() crv.degree = 1 crv.ctrlpts = [pt_end, pt_start] crv.knotvector = [0, 0, 1, 1] crv.opt = ['reversed', c_sense] pt_end = pt_start # Add it to the container cont.append(crv) # Update curve return True, cont
[ "def", "check_trim_curve", "(", "curve", ",", "parbox", ",", "*", "*", "kwargs", ")", ":", "def", "next_idx", "(", "edge_idx", ",", "direction", ")", ":", "tmp", "=", "edge_idx", "+", "direction", "if", "tmp", "<", "0", ":", "return", "3", "if", "tmp", ">", "3", ":", "return", "0", "return", "tmp", "# Keyword arguments", "tol", "=", "kwargs", ".", "get", "(", "'tol'", ",", "10e-8", ")", "# First, check if the curve is closed", "dist", "=", "linalg", ".", "point_distance", "(", "curve", ".", "evalpts", "[", "0", "]", ",", "curve", ".", "evalpts", "[", "-", "1", "]", ")", "if", "dist", "<=", "tol", ":", "# Curve is closed", "return", "detect_sense", "(", "curve", ",", "tol", ")", ",", "[", "]", "else", ":", "# Define start and end points of the trim curve", "pt_start", "=", "curve", ".", "evalpts", "[", "0", "]", "pt_end", "=", "curve", ".", "evalpts", "[", "-", "1", "]", "# Search for intersections", "idx_spt", "=", "-", "1", "idx_ept", "=", "-", "1", "for", "idx", "in", "range", "(", "len", "(", "parbox", ")", "-", "1", ")", ":", "if", "detect_intersection", "(", "parbox", "[", "idx", "]", ",", "parbox", "[", "idx", "+", "1", "]", ",", "pt_start", ",", "tol", ")", ":", "idx_spt", "=", "idx", "if", "detect_intersection", "(", "parbox", "[", "idx", "]", ",", "parbox", "[", "idx", "+", "1", "]", ",", "pt_end", ",", "tol", ")", ":", "idx_ept", "=", "idx", "# Check result of the intersection", "if", "idx_spt", "<", "0", "or", "idx_ept", "<", "0", ":", "# Curve does not intersect any edges of the parametric space", "# TODO: Extrapolate the curve using the tangent vector and find intersections", "return", "False", ",", "[", "]", "else", ":", "# Get sense of the original curve", "c_sense", "=", "curve", ".", "opt_get", "(", "'reversed'", ")", "# If sense is None, then detect sense", "if", "c_sense", "is", "None", ":", "# Get evaluated points", "pts", "=", "curve", ".", "evalpts", "num_pts", "=", "len", "(", "pts", ")", "# Find sense", "tmp_sense", "=", "0", "for", "pti", "in", "range", "(", "1", ",", "num_pts", "-", "1", ")", ":", "tmp_sense", "=", "detect_ccw", "(", "pts", "[", "pti", "-", "1", "]", ",", "pts", "[", "pti", "]", ",", "pts", "[", "pti", "+", "1", "]", ",", "tol", ")", "if", "tmp_sense", "!=", "0", ":", "break", "if", "tmp_sense", "==", "0", ":", "tmp_sense2", "=", "detect_ccw", "(", "pts", "[", "int", "(", "num_pts", "/", "3", ")", "]", ",", "pts", "[", "int", "(", "2", "*", "num_pts", "/", "3", ")", "]", ",", "pts", "[", "-", "int", "(", "num_pts", "/", "3", ")", "]", ",", "tol", ")", "if", "tmp_sense2", "!=", "0", ":", "tmp_sense", "=", "-", "tmp_sense2", "else", ":", "# We cannot decide which region to trim. Therefore, ignore this curve.", "return", "False", ",", "[", "]", "c_sense", "=", "0", "if", "tmp_sense", ">", "0", "else", "1", "# Update sense of the original curve", "curve", ".", "opt", "=", "[", "'reversed'", ",", "c_sense", "]", "# Generate a curve container and add the original curve", "cont", "=", "[", "curve", "]", "move_dir", "=", "-", "1", "if", "c_sense", "==", "0", "else", "1", "# Curve intersects with the edges of the parametric space", "counter", "=", "0", "while", "counter", "<", "4", ":", "if", "idx_ept", "==", "idx_spt", ":", "counter", "=", "5", "pt_start", "=", "curve", ".", "evalpts", "[", "0", "]", "else", ":", "# Find next index", "idx_ept", "=", "next_idx", "(", "idx_ept", ",", "move_dir", ")", "# Update tracked last point", "pt_start", "=", "parbox", "[", "idx_ept", "+", "1", "-", "c_sense", "]", "# Increment counter", "counter", "+=", "1", "# Generate the curve segment", "crv", "=", "shortcuts", ".", "generate_curve", "(", ")", "crv", ".", "degree", "=", "1", "crv", ".", "ctrlpts", "=", "[", "pt_end", ",", "pt_start", "]", "crv", ".", "knotvector", "=", "[", "0", ",", "0", ",", "1", ",", "1", "]", "crv", ".", "opt", "=", "[", "'reversed'", ",", "c_sense", "]", "pt_end", "=", "pt_start", "# Add it to the container", "cont", ".", "append", "(", "crv", ")", "# Update curve", "return", "True", ",", "cont" ]
Checks if the trim curve was closed and sense was set. :param curve: trim curve :param parbox: parameter space bounding box of the underlying surface :return: a tuple containing the status of the operation and list of extra trim curves generated :rtype: tuple
[ "Checks", "if", "the", "trim", "curve", "was", "closed", "and", "sense", "was", "set", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/trimming.py#L174-L278
230,388
orbingol/NURBS-Python
geomdl/trimming.py
get_par_box
def get_par_box(domain, last=False): """ Returns the bounding box of the surface parametric domain in ccw direction. :param domain: parametric domain :type domain: list, tuple :param last: if True, adds the first vertex to the end of the return list :type last: bool :return: edges of the parametric domain :rtype: tuple """ u_range = domain[0] v_range = domain[1] verts = [(u_range[0], v_range[0]), (u_range[1], v_range[0]), (u_range[1], v_range[1]), (u_range[0], v_range[1])] if last: verts.append(verts[0]) return tuple(verts)
python
def get_par_box(domain, last=False): """ Returns the bounding box of the surface parametric domain in ccw direction. :param domain: parametric domain :type domain: list, tuple :param last: if True, adds the first vertex to the end of the return list :type last: bool :return: edges of the parametric domain :rtype: tuple """ u_range = domain[0] v_range = domain[1] verts = [(u_range[0], v_range[0]), (u_range[1], v_range[0]), (u_range[1], v_range[1]), (u_range[0], v_range[1])] if last: verts.append(verts[0]) return tuple(verts)
[ "def", "get_par_box", "(", "domain", ",", "last", "=", "False", ")", ":", "u_range", "=", "domain", "[", "0", "]", "v_range", "=", "domain", "[", "1", "]", "verts", "=", "[", "(", "u_range", "[", "0", "]", ",", "v_range", "[", "0", "]", ")", ",", "(", "u_range", "[", "1", "]", ",", "v_range", "[", "0", "]", ")", ",", "(", "u_range", "[", "1", "]", ",", "v_range", "[", "1", "]", ")", ",", "(", "u_range", "[", "0", "]", ",", "v_range", "[", "1", "]", ")", "]", "if", "last", ":", "verts", ".", "append", "(", "verts", "[", "0", "]", ")", "return", "tuple", "(", "verts", ")" ]
Returns the bounding box of the surface parametric domain in ccw direction. :param domain: parametric domain :type domain: list, tuple :param last: if True, adds the first vertex to the end of the return list :type last: bool :return: edges of the parametric domain :rtype: tuple
[ "Returns", "the", "bounding", "box", "of", "the", "surface", "parametric", "domain", "in", "ccw", "direction", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/trimming.py#L281-L296
230,389
orbingol/NURBS-Python
geomdl/trimming.py
detect_sense
def detect_sense(curve, tol): """ Detects the sense, i.e. clockwise or counter-clockwise, of the curve. :param curve: 2-dimensional trim curve :type curve: abstract.Curve :param tol: tolerance value :type tol: float :return: True if detection is successful, False otherwise :rtype: bool """ if curve.opt_get('reversed') is None: # Detect sense since it is unset pts = curve.evalpts num_pts = len(pts) for idx in range(1, num_pts - 1): sense = detect_ccw(pts[idx - 1], pts[idx], pts[idx + 1], tol) if sense < 0: # cw curve.opt = ['reversed', 0] return True elif sense > 0: # ccw curve.opt = ['reversed', 1] return True else: continue # One final test with random points to determine the orientation sense = detect_ccw(pts[int(num_pts/3)], pts[int(2*num_pts/3)], pts[-int(num_pts/3)], tol) if sense < 0: # cw curve.opt = ['reversed', 0] return True elif sense > 0: # ccw curve.opt = ['reversed', 1] return True else: # Cannot determine the sense return False else: # Don't touch the sense value as it has been already set return True
python
def detect_sense(curve, tol): """ Detects the sense, i.e. clockwise or counter-clockwise, of the curve. :param curve: 2-dimensional trim curve :type curve: abstract.Curve :param tol: tolerance value :type tol: float :return: True if detection is successful, False otherwise :rtype: bool """ if curve.opt_get('reversed') is None: # Detect sense since it is unset pts = curve.evalpts num_pts = len(pts) for idx in range(1, num_pts - 1): sense = detect_ccw(pts[idx - 1], pts[idx], pts[idx + 1], tol) if sense < 0: # cw curve.opt = ['reversed', 0] return True elif sense > 0: # ccw curve.opt = ['reversed', 1] return True else: continue # One final test with random points to determine the orientation sense = detect_ccw(pts[int(num_pts/3)], pts[int(2*num_pts/3)], pts[-int(num_pts/3)], tol) if sense < 0: # cw curve.opt = ['reversed', 0] return True elif sense > 0: # ccw curve.opt = ['reversed', 1] return True else: # Cannot determine the sense return False else: # Don't touch the sense value as it has been already set return True
[ "def", "detect_sense", "(", "curve", ",", "tol", ")", ":", "if", "curve", ".", "opt_get", "(", "'reversed'", ")", "is", "None", ":", "# Detect sense since it is unset", "pts", "=", "curve", ".", "evalpts", "num_pts", "=", "len", "(", "pts", ")", "for", "idx", "in", "range", "(", "1", ",", "num_pts", "-", "1", ")", ":", "sense", "=", "detect_ccw", "(", "pts", "[", "idx", "-", "1", "]", ",", "pts", "[", "idx", "]", ",", "pts", "[", "idx", "+", "1", "]", ",", "tol", ")", "if", "sense", "<", "0", ":", "# cw", "curve", ".", "opt", "=", "[", "'reversed'", ",", "0", "]", "return", "True", "elif", "sense", ">", "0", ":", "# ccw", "curve", ".", "opt", "=", "[", "'reversed'", ",", "1", "]", "return", "True", "else", ":", "continue", "# One final test with random points to determine the orientation", "sense", "=", "detect_ccw", "(", "pts", "[", "int", "(", "num_pts", "/", "3", ")", "]", ",", "pts", "[", "int", "(", "2", "*", "num_pts", "/", "3", ")", "]", ",", "pts", "[", "-", "int", "(", "num_pts", "/", "3", ")", "]", ",", "tol", ")", "if", "sense", "<", "0", ":", "# cw", "curve", ".", "opt", "=", "[", "'reversed'", ",", "0", "]", "return", "True", "elif", "sense", ">", "0", ":", "# ccw", "curve", ".", "opt", "=", "[", "'reversed'", ",", "1", "]", "return", "True", "else", ":", "# Cannot determine the sense", "return", "False", "else", ":", "# Don't touch the sense value as it has been already set", "return", "True" ]
Detects the sense, i.e. clockwise or counter-clockwise, of the curve. :param curve: 2-dimensional trim curve :type curve: abstract.Curve :param tol: tolerance value :type tol: float :return: True if detection is successful, False otherwise :rtype: bool
[ "Detects", "the", "sense", "i", ".", "e", ".", "clockwise", "or", "counter", "-", "clockwise", "of", "the", "curve", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/trimming.py#L299-L336
230,390
orbingol/NURBS-Python
geomdl/ray.py
intersect
def intersect(ray1, ray2, **kwargs): """ Finds intersection of 2 rays. This functions finds the parameter values for the 1st and 2nd input rays and returns a tuple of ``(parameter for ray1, parameter for ray2, intersection status)``. ``status`` value is a enum type which reports the case which the intersection operation encounters. The intersection operation can encounter 3 different cases: * Intersecting: This is the anticipated solution. Returns ``(t1, t2, RayIntersection.INTERSECT)`` * Colinear: The rays can be parallel or coincident. Returns ``(t1, t2, RayIntersection.COLINEAR)`` * Skew: The rays are neither parallel nor intersecting. Returns ``(t1, t2, RayIntersection.SKEW)`` For the colinear case, ``t1`` and ``t2`` are the parameter values that give the starting point of the ray2 and ray1, respectively. Therefore; .. code-block:: python ray1.eval(t1) == ray2.p ray2.eval(t2) == ray1.p Please note that this operation is only implemented for 2- and 3-dimensional rays. :param ray1: 1st ray :param ray2: 2nd ray :return: a tuple of the parameter (t) for ray1 and ray2, and status of the intersection :rtype: tuple """ if not isinstance(ray1, Ray) or not isinstance(ray2, Ray): raise TypeError("The input arguments must be instances of the Ray object") if ray1.dimension != ray2.dimension: raise ValueError("Dimensions of the input rays must be the same") # Keyword arguments tol = kwargs.get('tol', 10e-17) # Call intersection method if ray1.dimension == 2: return _intersect2d(ray1, ray2, tol) elif ray1.dimension == 3: return _intersect3d(ray1, ray2, tol) else: raise NotImplementedError("Intersection operation for the current type of rays has not been implemented yet")
python
def intersect(ray1, ray2, **kwargs): """ Finds intersection of 2 rays. This functions finds the parameter values for the 1st and 2nd input rays and returns a tuple of ``(parameter for ray1, parameter for ray2, intersection status)``. ``status`` value is a enum type which reports the case which the intersection operation encounters. The intersection operation can encounter 3 different cases: * Intersecting: This is the anticipated solution. Returns ``(t1, t2, RayIntersection.INTERSECT)`` * Colinear: The rays can be parallel or coincident. Returns ``(t1, t2, RayIntersection.COLINEAR)`` * Skew: The rays are neither parallel nor intersecting. Returns ``(t1, t2, RayIntersection.SKEW)`` For the colinear case, ``t1`` and ``t2`` are the parameter values that give the starting point of the ray2 and ray1, respectively. Therefore; .. code-block:: python ray1.eval(t1) == ray2.p ray2.eval(t2) == ray1.p Please note that this operation is only implemented for 2- and 3-dimensional rays. :param ray1: 1st ray :param ray2: 2nd ray :return: a tuple of the parameter (t) for ray1 and ray2, and status of the intersection :rtype: tuple """ if not isinstance(ray1, Ray) or not isinstance(ray2, Ray): raise TypeError("The input arguments must be instances of the Ray object") if ray1.dimension != ray2.dimension: raise ValueError("Dimensions of the input rays must be the same") # Keyword arguments tol = kwargs.get('tol', 10e-17) # Call intersection method if ray1.dimension == 2: return _intersect2d(ray1, ray2, tol) elif ray1.dimension == 3: return _intersect3d(ray1, ray2, tol) else: raise NotImplementedError("Intersection operation for the current type of rays has not been implemented yet")
[ "def", "intersect", "(", "ray1", ",", "ray2", ",", "*", "*", "kwargs", ")", ":", "if", "not", "isinstance", "(", "ray1", ",", "Ray", ")", "or", "not", "isinstance", "(", "ray2", ",", "Ray", ")", ":", "raise", "TypeError", "(", "\"The input arguments must be instances of the Ray object\"", ")", "if", "ray1", ".", "dimension", "!=", "ray2", ".", "dimension", ":", "raise", "ValueError", "(", "\"Dimensions of the input rays must be the same\"", ")", "# Keyword arguments", "tol", "=", "kwargs", ".", "get", "(", "'tol'", ",", "10e-17", ")", "# Call intersection method", "if", "ray1", ".", "dimension", "==", "2", ":", "return", "_intersect2d", "(", "ray1", ",", "ray2", ",", "tol", ")", "elif", "ray1", ".", "dimension", "==", "3", ":", "return", "_intersect3d", "(", "ray1", ",", "ray2", ",", "tol", ")", "else", ":", "raise", "NotImplementedError", "(", "\"Intersection operation for the current type of rays has not been implemented yet\"", ")" ]
Finds intersection of 2 rays. This functions finds the parameter values for the 1st and 2nd input rays and returns a tuple of ``(parameter for ray1, parameter for ray2, intersection status)``. ``status`` value is a enum type which reports the case which the intersection operation encounters. The intersection operation can encounter 3 different cases: * Intersecting: This is the anticipated solution. Returns ``(t1, t2, RayIntersection.INTERSECT)`` * Colinear: The rays can be parallel or coincident. Returns ``(t1, t2, RayIntersection.COLINEAR)`` * Skew: The rays are neither parallel nor intersecting. Returns ``(t1, t2, RayIntersection.SKEW)`` For the colinear case, ``t1`` and ``t2`` are the parameter values that give the starting point of the ray2 and ray1, respectively. Therefore; .. code-block:: python ray1.eval(t1) == ray2.p ray2.eval(t2) == ray1.p Please note that this operation is only implemented for 2- and 3-dimensional rays. :param ray1: 1st ray :param ray2: 2nd ray :return: a tuple of the parameter (t) for ray1 and ray2, and status of the intersection :rtype: tuple
[ "Finds", "intersection", "of", "2", "rays", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/ray.py#L107-L150
230,391
orbingol/NURBS-Python
geomdl/freeform.py
Freeform.evaluate
def evaluate(self, **kwargs): """ Sets points that form the geometry. Keyword Arguments: * ``points``: sets the points """ self._eval_points = kwargs.get('points', self._init_array()) self._dimension = len(self._eval_points[0])
python
def evaluate(self, **kwargs): """ Sets points that form the geometry. Keyword Arguments: * ``points``: sets the points """ self._eval_points = kwargs.get('points', self._init_array()) self._dimension = len(self._eval_points[0])
[ "def", "evaluate", "(", "self", ",", "*", "*", "kwargs", ")", ":", "self", ".", "_eval_points", "=", "kwargs", ".", "get", "(", "'points'", ",", "self", ".", "_init_array", "(", ")", ")", "self", ".", "_dimension", "=", "len", "(", "self", ".", "_eval_points", "[", "0", "]", ")" ]
Sets points that form the geometry. Keyword Arguments: * ``points``: sets the points
[ "Sets", "points", "that", "form", "the", "geometry", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/freeform.py#L20-L27
230,392
orbingol/NURBS-Python
geomdl/exchange_vtk.py
export_polydata
def export_polydata(obj, file_name, **kwargs): """ Exports control points or evaluated points in VTK Polydata format. Please see the following document for details: http://www.vtk.org/VTK/img/file-formats.pdf Keyword Arguments: * ``point_type``: **ctrlpts** for control points or **evalpts** for evaluated points * ``tessellate``: tessellates the points (works only for surfaces) :param obj: geometry object :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: output file name :type file_name: str :raises GeomdlException: an error occurred writing the file """ content = export_polydata_str(obj, **kwargs) return exch.write_file(file_name, content)
python
def export_polydata(obj, file_name, **kwargs): """ Exports control points or evaluated points in VTK Polydata format. Please see the following document for details: http://www.vtk.org/VTK/img/file-formats.pdf Keyword Arguments: * ``point_type``: **ctrlpts** for control points or **evalpts** for evaluated points * ``tessellate``: tessellates the points (works only for surfaces) :param obj: geometry object :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: output file name :type file_name: str :raises GeomdlException: an error occurred writing the file """ content = export_polydata_str(obj, **kwargs) return exch.write_file(file_name, content)
[ "def", "export_polydata", "(", "obj", ",", "file_name", ",", "*", "*", "kwargs", ")", ":", "content", "=", "export_polydata_str", "(", "obj", ",", "*", "*", "kwargs", ")", "return", "exch", ".", "write_file", "(", "file_name", ",", "content", ")" ]
Exports control points or evaluated points in VTK Polydata format. Please see the following document for details: http://www.vtk.org/VTK/img/file-formats.pdf Keyword Arguments: * ``point_type``: **ctrlpts** for control points or **evalpts** for evaluated points * ``tessellate``: tessellates the points (works only for surfaces) :param obj: geometry object :type obj: abstract.SplineGeometry, multi.AbstractContainer :param file_name: output file name :type file_name: str :raises GeomdlException: an error occurred writing the file
[ "Exports", "control", "points", "or", "evaluated", "points", "in", "VTK", "Polydata", "format", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/exchange_vtk.py#L125-L141
230,393
orbingol/NURBS-Python
geomdl/utilities.py
make_zigzag
def make_zigzag(points, num_cols): """ Converts linear sequence of points into a zig-zag shape. This function is designed to create input for the visualization software. It orders the points to draw a zig-zag shape which enables generating properly connected lines without any scanlines. Please see the below sketch on the functionality of the ``num_cols`` parameter:: num cols <-=============-> ------->>-------| |------<<-------| |------>>-------| -------<<-------| Please note that this function does not detect the ordering of the input points to detect the input points have already been processed to generate a zig-zag shape. :param points: list of points to be ordered :type points: list :param num_cols: number of elements in a row which the zig-zag is generated :type num_cols: int :return: re-ordered points :rtype: list """ new_points = [] points_size = len(points) forward = True idx = 0 rev_idx = -1 while idx < points_size: if forward: new_points.append(points[idx]) else: new_points.append(points[rev_idx]) rev_idx -= 1 idx += 1 if idx % num_cols == 0: forward = False if forward else True rev_idx = idx + num_cols - 1 return new_points
python
def make_zigzag(points, num_cols): """ Converts linear sequence of points into a zig-zag shape. This function is designed to create input for the visualization software. It orders the points to draw a zig-zag shape which enables generating properly connected lines without any scanlines. Please see the below sketch on the functionality of the ``num_cols`` parameter:: num cols <-=============-> ------->>-------| |------<<-------| |------>>-------| -------<<-------| Please note that this function does not detect the ordering of the input points to detect the input points have already been processed to generate a zig-zag shape. :param points: list of points to be ordered :type points: list :param num_cols: number of elements in a row which the zig-zag is generated :type num_cols: int :return: re-ordered points :rtype: list """ new_points = [] points_size = len(points) forward = True idx = 0 rev_idx = -1 while idx < points_size: if forward: new_points.append(points[idx]) else: new_points.append(points[rev_idx]) rev_idx -= 1 idx += 1 if idx % num_cols == 0: forward = False if forward else True rev_idx = idx + num_cols - 1 return new_points
[ "def", "make_zigzag", "(", "points", ",", "num_cols", ")", ":", "new_points", "=", "[", "]", "points_size", "=", "len", "(", "points", ")", "forward", "=", "True", "idx", "=", "0", "rev_idx", "=", "-", "1", "while", "idx", "<", "points_size", ":", "if", "forward", ":", "new_points", ".", "append", "(", "points", "[", "idx", "]", ")", "else", ":", "new_points", ".", "append", "(", "points", "[", "rev_idx", "]", ")", "rev_idx", "-=", "1", "idx", "+=", "1", "if", "idx", "%", "num_cols", "==", "0", ":", "forward", "=", "False", "if", "forward", "else", "True", "rev_idx", "=", "idx", "+", "num_cols", "-", "1", "return", "new_points" ]
Converts linear sequence of points into a zig-zag shape. This function is designed to create input for the visualization software. It orders the points to draw a zig-zag shape which enables generating properly connected lines without any scanlines. Please see the below sketch on the functionality of the ``num_cols`` parameter:: num cols <-=============-> ------->>-------| |------<<-------| |------>>-------| -------<<-------| Please note that this function does not detect the ordering of the input points to detect the input points have already been processed to generate a zig-zag shape. :param points: list of points to be ordered :type points: list :param num_cols: number of elements in a row which the zig-zag is generated :type num_cols: int :return: re-ordered points :rtype: list
[ "Converts", "linear", "sequence", "of", "points", "into", "a", "zig", "-", "zag", "shape", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/utilities.py#L40-L80
230,394
orbingol/NURBS-Python
geomdl/utilities.py
make_quad
def make_quad(points, size_u, size_v): """ Converts linear sequence of input points into a quad structure. :param points: list of points to be ordered :type points: list, tuple :param size_v: number of elements in a row :type size_v: int :param size_u: number of elements in a column :type size_u: int :return: re-ordered points :rtype: list """ # Start with generating a zig-zag shape in row direction and then take its reverse new_points = make_zigzag(points, size_v) new_points.reverse() # Start generating a zig-zag shape in col direction forward = True for row in range(0, size_v): temp = [] for col in range(0, size_u): temp.append(points[row + (col * size_v)]) if forward: forward = False else: forward = True temp.reverse() new_points += temp return new_points
python
def make_quad(points, size_u, size_v): """ Converts linear sequence of input points into a quad structure. :param points: list of points to be ordered :type points: list, tuple :param size_v: number of elements in a row :type size_v: int :param size_u: number of elements in a column :type size_u: int :return: re-ordered points :rtype: list """ # Start with generating a zig-zag shape in row direction and then take its reverse new_points = make_zigzag(points, size_v) new_points.reverse() # Start generating a zig-zag shape in col direction forward = True for row in range(0, size_v): temp = [] for col in range(0, size_u): temp.append(points[row + (col * size_v)]) if forward: forward = False else: forward = True temp.reverse() new_points += temp return new_points
[ "def", "make_quad", "(", "points", ",", "size_u", ",", "size_v", ")", ":", "# Start with generating a zig-zag shape in row direction and then take its reverse", "new_points", "=", "make_zigzag", "(", "points", ",", "size_v", ")", "new_points", ".", "reverse", "(", ")", "# Start generating a zig-zag shape in col direction", "forward", "=", "True", "for", "row", "in", "range", "(", "0", ",", "size_v", ")", ":", "temp", "=", "[", "]", "for", "col", "in", "range", "(", "0", ",", "size_u", ")", ":", "temp", ".", "append", "(", "points", "[", "row", "+", "(", "col", "*", "size_v", ")", "]", ")", "if", "forward", ":", "forward", "=", "False", "else", ":", "forward", "=", "True", "temp", ".", "reverse", "(", ")", "new_points", "+=", "temp", "return", "new_points" ]
Converts linear sequence of input points into a quad structure. :param points: list of points to be ordered :type points: list, tuple :param size_v: number of elements in a row :type size_v: int :param size_u: number of elements in a column :type size_u: int :return: re-ordered points :rtype: list
[ "Converts", "linear", "sequence", "of", "input", "points", "into", "a", "quad", "structure", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/utilities.py#L83-L112
230,395
orbingol/NURBS-Python
geomdl/utilities.py
make_quadtree
def make_quadtree(points, size_u, size_v, **kwargs): """ Generates a quadtree-like structure from surface control points. This function generates a 2-dimensional list of control point coordinates. Considering the object-oriented representation of a quadtree data structure, first dimension of the generated list corresponds to a list of *QuadTree* classes. Second dimension of the generated list corresponds to a *QuadTree* data structure. The first element of the 2nd dimension is the mid-point of the bounding box and the remaining elements are corner points of the bounding box organized in counter-clockwise order. To maintain stability for the data structure on the edges and corners, the function accepts ``extrapolate`` keyword argument. If it is *True*, then the function extrapolates the surface on the corners and edges to complete the quad-like structure for each control point. If it is *False*, no extrapolation will be applied. By default, ``extrapolate`` is set to *True*. Please note that this function's intention is not generating a real quadtree structure but reorganizing the control points in a very similar fashion to make them available for various geometric operations. :param points: 1-dimensional array of surface control points :type points: list, tuple :param size_u: number of control points on the u-direction :type size_u: int :param size_v: number of control points on the v-direction :type size_v: int :return: control points organized in a quadtree-like structure :rtype: tuple """ # Get keyword arguments extrapolate = kwargs.get('extrapolate', True) # Convert control points array into 2-dimensional form points2d = [] for i in range(0, size_u): row_list = [] for j in range(0, size_v): row_list.append(points[j + (i * size_v)]) points2d.append(row_list) # Traverse 2-dimensional control points to find neighbors qtree = [] for u in range(size_u): for v in range(size_v): temp = [points2d[u][v]] # Note: negative indexing actually works in Python, so we need explicit checking if u + 1 < size_u: temp.append(points2d[u+1][v]) else: if extrapolate: extrapolated_edge = linalg.vector_generate(points2d[u - 1][v], points2d[u][v]) translated_point = linalg.point_translate(points2d[u][v], extrapolated_edge) temp.append(translated_point) if v + 1 < size_v: temp.append(points2d[u][v+1]) else: if extrapolate: extrapolated_edge = linalg.vector_generate(points2d[u][v - 1], points2d[u][v]) translated_point = linalg.point_translate(points2d[u][v], extrapolated_edge) temp.append(translated_point) if u - 1 >= 0: temp.append(points2d[u-1][v]) else: if extrapolate: extrapolated_edge = linalg.vector_generate(points2d[u + 1][v], points2d[u][v]) translated_point = linalg.point_translate(points2d[u][v], extrapolated_edge) temp.append(translated_point) if v - 1 >= 0: temp.append(points2d[u][v-1]) else: if extrapolate: extrapolated_edge = linalg.vector_generate(points2d[u][v + 1], points2d[u][v]) translated_point = linalg.point_translate(points2d[u][v], extrapolated_edge) temp.append(translated_point) qtree.append(tuple(temp)) # Return generated quad-tree return tuple(qtree)
python
def make_quadtree(points, size_u, size_v, **kwargs): """ Generates a quadtree-like structure from surface control points. This function generates a 2-dimensional list of control point coordinates. Considering the object-oriented representation of a quadtree data structure, first dimension of the generated list corresponds to a list of *QuadTree* classes. Second dimension of the generated list corresponds to a *QuadTree* data structure. The first element of the 2nd dimension is the mid-point of the bounding box and the remaining elements are corner points of the bounding box organized in counter-clockwise order. To maintain stability for the data structure on the edges and corners, the function accepts ``extrapolate`` keyword argument. If it is *True*, then the function extrapolates the surface on the corners and edges to complete the quad-like structure for each control point. If it is *False*, no extrapolation will be applied. By default, ``extrapolate`` is set to *True*. Please note that this function's intention is not generating a real quadtree structure but reorganizing the control points in a very similar fashion to make them available for various geometric operations. :param points: 1-dimensional array of surface control points :type points: list, tuple :param size_u: number of control points on the u-direction :type size_u: int :param size_v: number of control points on the v-direction :type size_v: int :return: control points organized in a quadtree-like structure :rtype: tuple """ # Get keyword arguments extrapolate = kwargs.get('extrapolate', True) # Convert control points array into 2-dimensional form points2d = [] for i in range(0, size_u): row_list = [] for j in range(0, size_v): row_list.append(points[j + (i * size_v)]) points2d.append(row_list) # Traverse 2-dimensional control points to find neighbors qtree = [] for u in range(size_u): for v in range(size_v): temp = [points2d[u][v]] # Note: negative indexing actually works in Python, so we need explicit checking if u + 1 < size_u: temp.append(points2d[u+1][v]) else: if extrapolate: extrapolated_edge = linalg.vector_generate(points2d[u - 1][v], points2d[u][v]) translated_point = linalg.point_translate(points2d[u][v], extrapolated_edge) temp.append(translated_point) if v + 1 < size_v: temp.append(points2d[u][v+1]) else: if extrapolate: extrapolated_edge = linalg.vector_generate(points2d[u][v - 1], points2d[u][v]) translated_point = linalg.point_translate(points2d[u][v], extrapolated_edge) temp.append(translated_point) if u - 1 >= 0: temp.append(points2d[u-1][v]) else: if extrapolate: extrapolated_edge = linalg.vector_generate(points2d[u + 1][v], points2d[u][v]) translated_point = linalg.point_translate(points2d[u][v], extrapolated_edge) temp.append(translated_point) if v - 1 >= 0: temp.append(points2d[u][v-1]) else: if extrapolate: extrapolated_edge = linalg.vector_generate(points2d[u][v + 1], points2d[u][v]) translated_point = linalg.point_translate(points2d[u][v], extrapolated_edge) temp.append(translated_point) qtree.append(tuple(temp)) # Return generated quad-tree return tuple(qtree)
[ "def", "make_quadtree", "(", "points", ",", "size_u", ",", "size_v", ",", "*", "*", "kwargs", ")", ":", "# Get keyword arguments", "extrapolate", "=", "kwargs", ".", "get", "(", "'extrapolate'", ",", "True", ")", "# Convert control points array into 2-dimensional form", "points2d", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "size_u", ")", ":", "row_list", "=", "[", "]", "for", "j", "in", "range", "(", "0", ",", "size_v", ")", ":", "row_list", ".", "append", "(", "points", "[", "j", "+", "(", "i", "*", "size_v", ")", "]", ")", "points2d", ".", "append", "(", "row_list", ")", "# Traverse 2-dimensional control points to find neighbors", "qtree", "=", "[", "]", "for", "u", "in", "range", "(", "size_u", ")", ":", "for", "v", "in", "range", "(", "size_v", ")", ":", "temp", "=", "[", "points2d", "[", "u", "]", "[", "v", "]", "]", "# Note: negative indexing actually works in Python, so we need explicit checking", "if", "u", "+", "1", "<", "size_u", ":", "temp", ".", "append", "(", "points2d", "[", "u", "+", "1", "]", "[", "v", "]", ")", "else", ":", "if", "extrapolate", ":", "extrapolated_edge", "=", "linalg", ".", "vector_generate", "(", "points2d", "[", "u", "-", "1", "]", "[", "v", "]", ",", "points2d", "[", "u", "]", "[", "v", "]", ")", "translated_point", "=", "linalg", ".", "point_translate", "(", "points2d", "[", "u", "]", "[", "v", "]", ",", "extrapolated_edge", ")", "temp", ".", "append", "(", "translated_point", ")", "if", "v", "+", "1", "<", "size_v", ":", "temp", ".", "append", "(", "points2d", "[", "u", "]", "[", "v", "+", "1", "]", ")", "else", ":", "if", "extrapolate", ":", "extrapolated_edge", "=", "linalg", ".", "vector_generate", "(", "points2d", "[", "u", "]", "[", "v", "-", "1", "]", ",", "points2d", "[", "u", "]", "[", "v", "]", ")", "translated_point", "=", "linalg", ".", "point_translate", "(", "points2d", "[", "u", "]", "[", "v", "]", ",", "extrapolated_edge", ")", "temp", ".", "append", "(", "translated_point", ")", "if", "u", "-", "1", ">=", "0", ":", "temp", ".", "append", "(", "points2d", "[", "u", "-", "1", "]", "[", "v", "]", ")", "else", ":", "if", "extrapolate", ":", "extrapolated_edge", "=", "linalg", ".", "vector_generate", "(", "points2d", "[", "u", "+", "1", "]", "[", "v", "]", ",", "points2d", "[", "u", "]", "[", "v", "]", ")", "translated_point", "=", "linalg", ".", "point_translate", "(", "points2d", "[", "u", "]", "[", "v", "]", ",", "extrapolated_edge", ")", "temp", ".", "append", "(", "translated_point", ")", "if", "v", "-", "1", ">=", "0", ":", "temp", ".", "append", "(", "points2d", "[", "u", "]", "[", "v", "-", "1", "]", ")", "else", ":", "if", "extrapolate", ":", "extrapolated_edge", "=", "linalg", ".", "vector_generate", "(", "points2d", "[", "u", "]", "[", "v", "+", "1", "]", ",", "points2d", "[", "u", "]", "[", "v", "]", ")", "translated_point", "=", "linalg", ".", "point_translate", "(", "points2d", "[", "u", "]", "[", "v", "]", ",", "extrapolated_edge", ")", "temp", ".", "append", "(", "translated_point", ")", "qtree", ".", "append", "(", "tuple", "(", "temp", ")", ")", "# Return generated quad-tree", "return", "tuple", "(", "qtree", ")" ]
Generates a quadtree-like structure from surface control points. This function generates a 2-dimensional list of control point coordinates. Considering the object-oriented representation of a quadtree data structure, first dimension of the generated list corresponds to a list of *QuadTree* classes. Second dimension of the generated list corresponds to a *QuadTree* data structure. The first element of the 2nd dimension is the mid-point of the bounding box and the remaining elements are corner points of the bounding box organized in counter-clockwise order. To maintain stability for the data structure on the edges and corners, the function accepts ``extrapolate`` keyword argument. If it is *True*, then the function extrapolates the surface on the corners and edges to complete the quad-like structure for each control point. If it is *False*, no extrapolation will be applied. By default, ``extrapolate`` is set to *True*. Please note that this function's intention is not generating a real quadtree structure but reorganizing the control points in a very similar fashion to make them available for various geometric operations. :param points: 1-dimensional array of surface control points :type points: list, tuple :param size_u: number of control points on the u-direction :type size_u: int :param size_v: number of control points on the v-direction :type size_v: int :return: control points organized in a quadtree-like structure :rtype: tuple
[ "Generates", "a", "quadtree", "-", "like", "structure", "from", "surface", "control", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/utilities.py#L115-L189
230,396
orbingol/NURBS-Python
geomdl/utilities.py
evaluate_bounding_box
def evaluate_bounding_box(ctrlpts): """ Computes the minimum bounding box of the point set. The (minimum) bounding box is the smallest enclosure in which all the input points lie. :param ctrlpts: points :type ctrlpts: list, tuple :return: bounding box in the format [min, max] :rtype: tuple """ # Estimate dimension from the first element of the control points dimension = len(ctrlpts[0]) # Evaluate bounding box bbmin = [float('inf') for _ in range(0, dimension)] bbmax = [float('-inf') for _ in range(0, dimension)] for cpt in ctrlpts: for i, arr in enumerate(zip(cpt, bbmin)): if arr[0] < arr[1]: bbmin[i] = arr[0] for i, arr in enumerate(zip(cpt, bbmax)): if arr[0] > arr[1]: bbmax[i] = arr[0] return tuple(bbmin), tuple(bbmax)
python
def evaluate_bounding_box(ctrlpts): """ Computes the minimum bounding box of the point set. The (minimum) bounding box is the smallest enclosure in which all the input points lie. :param ctrlpts: points :type ctrlpts: list, tuple :return: bounding box in the format [min, max] :rtype: tuple """ # Estimate dimension from the first element of the control points dimension = len(ctrlpts[0]) # Evaluate bounding box bbmin = [float('inf') for _ in range(0, dimension)] bbmax = [float('-inf') for _ in range(0, dimension)] for cpt in ctrlpts: for i, arr in enumerate(zip(cpt, bbmin)): if arr[0] < arr[1]: bbmin[i] = arr[0] for i, arr in enumerate(zip(cpt, bbmax)): if arr[0] > arr[1]: bbmax[i] = arr[0] return tuple(bbmin), tuple(bbmax)
[ "def", "evaluate_bounding_box", "(", "ctrlpts", ")", ":", "# Estimate dimension from the first element of the control points", "dimension", "=", "len", "(", "ctrlpts", "[", "0", "]", ")", "# Evaluate bounding box", "bbmin", "=", "[", "float", "(", "'inf'", ")", "for", "_", "in", "range", "(", "0", ",", "dimension", ")", "]", "bbmax", "=", "[", "float", "(", "'-inf'", ")", "for", "_", "in", "range", "(", "0", ",", "dimension", ")", "]", "for", "cpt", "in", "ctrlpts", ":", "for", "i", ",", "arr", "in", "enumerate", "(", "zip", "(", "cpt", ",", "bbmin", ")", ")", ":", "if", "arr", "[", "0", "]", "<", "arr", "[", "1", "]", ":", "bbmin", "[", "i", "]", "=", "arr", "[", "0", "]", "for", "i", ",", "arr", "in", "enumerate", "(", "zip", "(", "cpt", ",", "bbmax", ")", ")", ":", "if", "arr", "[", "0", "]", ">", "arr", "[", "1", "]", ":", "bbmax", "[", "i", "]", "=", "arr", "[", "0", "]", "return", "tuple", "(", "bbmin", ")", ",", "tuple", "(", "bbmax", ")" ]
Computes the minimum bounding box of the point set. The (minimum) bounding box is the smallest enclosure in which all the input points lie. :param ctrlpts: points :type ctrlpts: list, tuple :return: bounding box in the format [min, max] :rtype: tuple
[ "Computes", "the", "minimum", "bounding", "box", "of", "the", "point", "set", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/utilities.py#L192-L216
230,397
orbingol/NURBS-Python
geomdl/_tessellate.py
make_triangle_mesh
def make_triangle_mesh(points, size_u, size_v, **kwargs): """ Generates a triangular mesh from an array of points. This function generates a triangular mesh for a NURBS or B-Spline surface on its parametric space. The input is the surface points and the number of points on the parametric dimensions u and v, indicated as row and column sizes in the function signature. This function should operate correctly if row and column sizes are input correctly, no matter what the points are v-ordered or u-ordered. Please see the documentation of ``ctrlpts`` and ``ctrlpts2d`` properties of the Surface class for more details on point ordering for the surfaces. This function accepts the following keyword arguments: * ``vertex_spacing``: Defines the size of the triangles via setting the jump value between points * ``trims``: List of trim curves passed to the tessellation function * ``tessellate_func``: Function called for tessellation. *Default:* :func:`.tessellate.surface_tessellate` * ``tessellate_args``: Arguments passed to the tessellation function (as a dict) The tessellation function is designed to generate triangles from 4 vertices. It takes 4 :py:class:`.Vertex` objects, index values for setting the triangle and vertex IDs and additional parameters as its function arguments. It returns a tuple of :py:class:`.Vertex` and :py:class:`.Triangle` object lists generated from the input vertices. A default triangle generator is provided as a prototype for implementation in the source code. The return value of this function is a tuple containing two lists. First one is the list of vertices and the second one is the list of triangles. :param points: input points :type points: list, tuple :param size_u: number of elements on the u-direction :type size_u: int :param size_v: number of elements on the v-direction :type size_v: int :return: a tuple containing lists of vertices and triangles :rtype: tuple """ def fix_numbering(vertex_list, triangle_list): # Initialize variables final_vertices = [] # Get all vertices inside the triangle list tri_vertex_ids = [] for tri in triangle_list: for td in tri.data: if td not in tri_vertex_ids: tri_vertex_ids.append(td) # Find vertices used in triangles seen_vertices = [] for vertex in vertex_list: if vertex.id in tri_vertex_ids and vertex.id not in seen_vertices: final_vertices.append(vertex) seen_vertices.append(vertex.id) # Fix vertex numbering (automatically fixes triangle vertex numbering) vert_new_id = 0 for vertex in final_vertices: vertex.id = vert_new_id vert_new_id += 1 return final_vertices, triangle_list # Vertex spacing for triangulation vertex_spacing = kwargs.get('vertex_spacing', 1) # defines the size of the triangles trim_curves = kwargs.get('trims', []) # Tessellation algorithm tsl_func = kwargs.get('tessellate_func') if tsl_func is None: tsl_func = surface_tessellate tsl_args = kwargs.get('tessellate_args', dict()) # Numbering vrt_idx = 0 # vertex index numbering start tri_idx = 0 # triangle index numbering start # Variable initialization u_jump = (1.0 / float(size_u - 1)) * vertex_spacing # for computing vertex parametric u value v_jump = (1.0 / float(size_v - 1)) * vertex_spacing # for computing vertex parametric v value varr_size_u = int(round((float(size_u) / float(vertex_spacing)) + 10e-8)) # vertex array size on the u-direction varr_size_v = int(round((float(size_v) / float(vertex_spacing)) + 10e-8)) # vertex array size on the v-direction # Generate vertices directly from input points (preliminary evaluation) vertices = [Vertex() for _ in range(varr_size_v * varr_size_u)] u = 0.0 for i in range(0, size_u, vertex_spacing): v = 0.0 for j in range(0, size_v, vertex_spacing): idx = j + (i * size_v) vertices[vrt_idx].id = vrt_idx vertices[vrt_idx].data = points[idx] vertices[vrt_idx].uv = [u, v] vrt_idx += 1 v += v_jump u += u_jump # # Organization of vertices in a quad element on the parametric space: # # v4 v3 # o-------o i # | | | # | | | # | | |_ _ _ # o-------o j # v1 v2 # # Generate triangles and final vertices triangles = [] for i in range(varr_size_u - 1): for j in range(varr_size_v - 1): # Find vertex indices for a quad element vertex1 = vertices[j + (i * varr_size_v)] vertex2 = vertices[j + ((i + 1) * varr_size_v)] vertex3 = vertices[j + 1 + ((i + 1) * varr_size_v)] vertex4 = vertices[j + 1 + (i * varr_size_v)] # Call tessellation function vlst, tlst = tsl_func(vertex1, vertex2, vertex3, vertex4, vrt_idx, tri_idx, trim_curves, tsl_args) # Add tessellation results to the return lists vertices += vlst triangles += tlst # Increment index values vrt_idx += len(vlst) tri_idx += len(tlst) # Fix vertex and triangle numbering (ID values) vertices, triangles = fix_numbering(vertices, triangles) return vertices, triangles
python
def make_triangle_mesh(points, size_u, size_v, **kwargs): """ Generates a triangular mesh from an array of points. This function generates a triangular mesh for a NURBS or B-Spline surface on its parametric space. The input is the surface points and the number of points on the parametric dimensions u and v, indicated as row and column sizes in the function signature. This function should operate correctly if row and column sizes are input correctly, no matter what the points are v-ordered or u-ordered. Please see the documentation of ``ctrlpts`` and ``ctrlpts2d`` properties of the Surface class for more details on point ordering for the surfaces. This function accepts the following keyword arguments: * ``vertex_spacing``: Defines the size of the triangles via setting the jump value between points * ``trims``: List of trim curves passed to the tessellation function * ``tessellate_func``: Function called for tessellation. *Default:* :func:`.tessellate.surface_tessellate` * ``tessellate_args``: Arguments passed to the tessellation function (as a dict) The tessellation function is designed to generate triangles from 4 vertices. It takes 4 :py:class:`.Vertex` objects, index values for setting the triangle and vertex IDs and additional parameters as its function arguments. It returns a tuple of :py:class:`.Vertex` and :py:class:`.Triangle` object lists generated from the input vertices. A default triangle generator is provided as a prototype for implementation in the source code. The return value of this function is a tuple containing two lists. First one is the list of vertices and the second one is the list of triangles. :param points: input points :type points: list, tuple :param size_u: number of elements on the u-direction :type size_u: int :param size_v: number of elements on the v-direction :type size_v: int :return: a tuple containing lists of vertices and triangles :rtype: tuple """ def fix_numbering(vertex_list, triangle_list): # Initialize variables final_vertices = [] # Get all vertices inside the triangle list tri_vertex_ids = [] for tri in triangle_list: for td in tri.data: if td not in tri_vertex_ids: tri_vertex_ids.append(td) # Find vertices used in triangles seen_vertices = [] for vertex in vertex_list: if vertex.id in tri_vertex_ids and vertex.id not in seen_vertices: final_vertices.append(vertex) seen_vertices.append(vertex.id) # Fix vertex numbering (automatically fixes triangle vertex numbering) vert_new_id = 0 for vertex in final_vertices: vertex.id = vert_new_id vert_new_id += 1 return final_vertices, triangle_list # Vertex spacing for triangulation vertex_spacing = kwargs.get('vertex_spacing', 1) # defines the size of the triangles trim_curves = kwargs.get('trims', []) # Tessellation algorithm tsl_func = kwargs.get('tessellate_func') if tsl_func is None: tsl_func = surface_tessellate tsl_args = kwargs.get('tessellate_args', dict()) # Numbering vrt_idx = 0 # vertex index numbering start tri_idx = 0 # triangle index numbering start # Variable initialization u_jump = (1.0 / float(size_u - 1)) * vertex_spacing # for computing vertex parametric u value v_jump = (1.0 / float(size_v - 1)) * vertex_spacing # for computing vertex parametric v value varr_size_u = int(round((float(size_u) / float(vertex_spacing)) + 10e-8)) # vertex array size on the u-direction varr_size_v = int(round((float(size_v) / float(vertex_spacing)) + 10e-8)) # vertex array size on the v-direction # Generate vertices directly from input points (preliminary evaluation) vertices = [Vertex() for _ in range(varr_size_v * varr_size_u)] u = 0.0 for i in range(0, size_u, vertex_spacing): v = 0.0 for j in range(0, size_v, vertex_spacing): idx = j + (i * size_v) vertices[vrt_idx].id = vrt_idx vertices[vrt_idx].data = points[idx] vertices[vrt_idx].uv = [u, v] vrt_idx += 1 v += v_jump u += u_jump # # Organization of vertices in a quad element on the parametric space: # # v4 v3 # o-------o i # | | | # | | | # | | |_ _ _ # o-------o j # v1 v2 # # Generate triangles and final vertices triangles = [] for i in range(varr_size_u - 1): for j in range(varr_size_v - 1): # Find vertex indices for a quad element vertex1 = vertices[j + (i * varr_size_v)] vertex2 = vertices[j + ((i + 1) * varr_size_v)] vertex3 = vertices[j + 1 + ((i + 1) * varr_size_v)] vertex4 = vertices[j + 1 + (i * varr_size_v)] # Call tessellation function vlst, tlst = tsl_func(vertex1, vertex2, vertex3, vertex4, vrt_idx, tri_idx, trim_curves, tsl_args) # Add tessellation results to the return lists vertices += vlst triangles += tlst # Increment index values vrt_idx += len(vlst) tri_idx += len(tlst) # Fix vertex and triangle numbering (ID values) vertices, triangles = fix_numbering(vertices, triangles) return vertices, triangles
[ "def", "make_triangle_mesh", "(", "points", ",", "size_u", ",", "size_v", ",", "*", "*", "kwargs", ")", ":", "def", "fix_numbering", "(", "vertex_list", ",", "triangle_list", ")", ":", "# Initialize variables", "final_vertices", "=", "[", "]", "# Get all vertices inside the triangle list", "tri_vertex_ids", "=", "[", "]", "for", "tri", "in", "triangle_list", ":", "for", "td", "in", "tri", ".", "data", ":", "if", "td", "not", "in", "tri_vertex_ids", ":", "tri_vertex_ids", ".", "append", "(", "td", ")", "# Find vertices used in triangles", "seen_vertices", "=", "[", "]", "for", "vertex", "in", "vertex_list", ":", "if", "vertex", ".", "id", "in", "tri_vertex_ids", "and", "vertex", ".", "id", "not", "in", "seen_vertices", ":", "final_vertices", ".", "append", "(", "vertex", ")", "seen_vertices", ".", "append", "(", "vertex", ".", "id", ")", "# Fix vertex numbering (automatically fixes triangle vertex numbering)", "vert_new_id", "=", "0", "for", "vertex", "in", "final_vertices", ":", "vertex", ".", "id", "=", "vert_new_id", "vert_new_id", "+=", "1", "return", "final_vertices", ",", "triangle_list", "# Vertex spacing for triangulation", "vertex_spacing", "=", "kwargs", ".", "get", "(", "'vertex_spacing'", ",", "1", ")", "# defines the size of the triangles", "trim_curves", "=", "kwargs", ".", "get", "(", "'trims'", ",", "[", "]", ")", "# Tessellation algorithm", "tsl_func", "=", "kwargs", ".", "get", "(", "'tessellate_func'", ")", "if", "tsl_func", "is", "None", ":", "tsl_func", "=", "surface_tessellate", "tsl_args", "=", "kwargs", ".", "get", "(", "'tessellate_args'", ",", "dict", "(", ")", ")", "# Numbering", "vrt_idx", "=", "0", "# vertex index numbering start", "tri_idx", "=", "0", "# triangle index numbering start", "# Variable initialization", "u_jump", "=", "(", "1.0", "/", "float", "(", "size_u", "-", "1", ")", ")", "*", "vertex_spacing", "# for computing vertex parametric u value", "v_jump", "=", "(", "1.0", "/", "float", "(", "size_v", "-", "1", ")", ")", "*", "vertex_spacing", "# for computing vertex parametric v value", "varr_size_u", "=", "int", "(", "round", "(", "(", "float", "(", "size_u", ")", "/", "float", "(", "vertex_spacing", ")", ")", "+", "10e-8", ")", ")", "# vertex array size on the u-direction", "varr_size_v", "=", "int", "(", "round", "(", "(", "float", "(", "size_v", ")", "/", "float", "(", "vertex_spacing", ")", ")", "+", "10e-8", ")", ")", "# vertex array size on the v-direction", "# Generate vertices directly from input points (preliminary evaluation)", "vertices", "=", "[", "Vertex", "(", ")", "for", "_", "in", "range", "(", "varr_size_v", "*", "varr_size_u", ")", "]", "u", "=", "0.0", "for", "i", "in", "range", "(", "0", ",", "size_u", ",", "vertex_spacing", ")", ":", "v", "=", "0.0", "for", "j", "in", "range", "(", "0", ",", "size_v", ",", "vertex_spacing", ")", ":", "idx", "=", "j", "+", "(", "i", "*", "size_v", ")", "vertices", "[", "vrt_idx", "]", ".", "id", "=", "vrt_idx", "vertices", "[", "vrt_idx", "]", ".", "data", "=", "points", "[", "idx", "]", "vertices", "[", "vrt_idx", "]", ".", "uv", "=", "[", "u", ",", "v", "]", "vrt_idx", "+=", "1", "v", "+=", "v_jump", "u", "+=", "u_jump", "#", "# Organization of vertices in a quad element on the parametric space:", "#", "# v4 v3", "# o-------o i", "# | | |", "# | | |", "# | | |_ _ _", "# o-------o j", "# v1 v2", "#", "# Generate triangles and final vertices", "triangles", "=", "[", "]", "for", "i", "in", "range", "(", "varr_size_u", "-", "1", ")", ":", "for", "j", "in", "range", "(", "varr_size_v", "-", "1", ")", ":", "# Find vertex indices for a quad element", "vertex1", "=", "vertices", "[", "j", "+", "(", "i", "*", "varr_size_v", ")", "]", "vertex2", "=", "vertices", "[", "j", "+", "(", "(", "i", "+", "1", ")", "*", "varr_size_v", ")", "]", "vertex3", "=", "vertices", "[", "j", "+", "1", "+", "(", "(", "i", "+", "1", ")", "*", "varr_size_v", ")", "]", "vertex4", "=", "vertices", "[", "j", "+", "1", "+", "(", "i", "*", "varr_size_v", ")", "]", "# Call tessellation function", "vlst", ",", "tlst", "=", "tsl_func", "(", "vertex1", ",", "vertex2", ",", "vertex3", ",", "vertex4", ",", "vrt_idx", ",", "tri_idx", ",", "trim_curves", ",", "tsl_args", ")", "# Add tessellation results to the return lists", "vertices", "+=", "vlst", "triangles", "+=", "tlst", "# Increment index values", "vrt_idx", "+=", "len", "(", "vlst", ")", "tri_idx", "+=", "len", "(", "tlst", ")", "# Fix vertex and triangle numbering (ID values)", "vertices", ",", "triangles", "=", "fix_numbering", "(", "vertices", ",", "triangles", ")", "return", "vertices", ",", "triangles" ]
Generates a triangular mesh from an array of points. This function generates a triangular mesh for a NURBS or B-Spline surface on its parametric space. The input is the surface points and the number of points on the parametric dimensions u and v, indicated as row and column sizes in the function signature. This function should operate correctly if row and column sizes are input correctly, no matter what the points are v-ordered or u-ordered. Please see the documentation of ``ctrlpts`` and ``ctrlpts2d`` properties of the Surface class for more details on point ordering for the surfaces. This function accepts the following keyword arguments: * ``vertex_spacing``: Defines the size of the triangles via setting the jump value between points * ``trims``: List of trim curves passed to the tessellation function * ``tessellate_func``: Function called for tessellation. *Default:* :func:`.tessellate.surface_tessellate` * ``tessellate_args``: Arguments passed to the tessellation function (as a dict) The tessellation function is designed to generate triangles from 4 vertices. It takes 4 :py:class:`.Vertex` objects, index values for setting the triangle and vertex IDs and additional parameters as its function arguments. It returns a tuple of :py:class:`.Vertex` and :py:class:`.Triangle` object lists generated from the input vertices. A default triangle generator is provided as a prototype for implementation in the source code. The return value of this function is a tuple containing two lists. First one is the list of vertices and the second one is the list of triangles. :param points: input points :type points: list, tuple :param size_u: number of elements on the u-direction :type size_u: int :param size_v: number of elements on the v-direction :type size_v: int :return: a tuple containing lists of vertices and triangles :rtype: tuple
[ "Generates", "a", "triangular", "mesh", "from", "an", "array", "of", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_tessellate.py#L18-L148
230,398
orbingol/NURBS-Python
geomdl/_tessellate.py
polygon_triangulate
def polygon_triangulate(tri_idx, *args): """ Triangulates a monotone polygon defined by a list of vertices. The input vertices must form a convex polygon and must be arranged in counter-clockwise order. :param tri_idx: triangle numbering start value :type tri_idx: int :param args: list of Vertex objects :type args: Vertex :return: list of Triangle objects :rtype: list """ # Initialize variables tidx = 0 triangles = [] # Generate triangles for idx in range(1, len(args) - 1): tri = Triangle() tri.id = tri_idx + tidx tri.add_vertex(args[0], args[idx], args[idx + 1]) triangles.append(tri) tidx += 1 # Return generated triangles return triangles
python
def polygon_triangulate(tri_idx, *args): """ Triangulates a monotone polygon defined by a list of vertices. The input vertices must form a convex polygon and must be arranged in counter-clockwise order. :param tri_idx: triangle numbering start value :type tri_idx: int :param args: list of Vertex objects :type args: Vertex :return: list of Triangle objects :rtype: list """ # Initialize variables tidx = 0 triangles = [] # Generate triangles for idx in range(1, len(args) - 1): tri = Triangle() tri.id = tri_idx + tidx tri.add_vertex(args[0], args[idx], args[idx + 1]) triangles.append(tri) tidx += 1 # Return generated triangles return triangles
[ "def", "polygon_triangulate", "(", "tri_idx", ",", "*", "args", ")", ":", "# Initialize variables", "tidx", "=", "0", "triangles", "=", "[", "]", "# Generate triangles", "for", "idx", "in", "range", "(", "1", ",", "len", "(", "args", ")", "-", "1", ")", ":", "tri", "=", "Triangle", "(", ")", "tri", ".", "id", "=", "tri_idx", "+", "tidx", "tri", ".", "add_vertex", "(", "args", "[", "0", "]", ",", "args", "[", "idx", "]", ",", "args", "[", "idx", "+", "1", "]", ")", "triangles", ".", "append", "(", "tri", ")", "tidx", "+=", "1", "# Return generated triangles", "return", "triangles" ]
Triangulates a monotone polygon defined by a list of vertices. The input vertices must form a convex polygon and must be arranged in counter-clockwise order. :param tri_idx: triangle numbering start value :type tri_idx: int :param args: list of Vertex objects :type args: Vertex :return: list of Triangle objects :rtype: list
[ "Triangulates", "a", "monotone", "polygon", "defined", "by", "a", "list", "of", "vertices", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_tessellate.py#L151-L176
230,399
orbingol/NURBS-Python
geomdl/_tessellate.py
make_quad_mesh
def make_quad_mesh(points, size_u, size_v): """ Generates a mesh of quadrilateral elements. :param points: list of points :type points: list, tuple :param size_u: number of points on the u-direction (column) :type size_u: int :param size_v: number of points on the v-direction (row) :type size_v: int :return: a tuple containing lists of vertices and quads :rtype: tuple """ # Numbering vertex_idx = 0 quad_idx = 0 # Generate vertices vertices = [] for pt in points: vrt = Vertex(*pt, id=vertex_idx) vertices.append(vrt) vertex_idx += 1 # Generate quads quads = [] for i in range(0, size_u - 1): for j in range(0, size_v - 1): v1 = vertices[j + (size_v * i)] v2 = vertices[j + (size_v * (i + 1))] v3 = vertices[j + 1 + (size_v * (i + 1))] v4 = vertices[j + 1 + (size_v * i)] qd = Quad(v1, v2, v3, v4, id=quad_idx) quads.append(qd) quad_idx += 1 return vertices, quads
python
def make_quad_mesh(points, size_u, size_v): """ Generates a mesh of quadrilateral elements. :param points: list of points :type points: list, tuple :param size_u: number of points on the u-direction (column) :type size_u: int :param size_v: number of points on the v-direction (row) :type size_v: int :return: a tuple containing lists of vertices and quads :rtype: tuple """ # Numbering vertex_idx = 0 quad_idx = 0 # Generate vertices vertices = [] for pt in points: vrt = Vertex(*pt, id=vertex_idx) vertices.append(vrt) vertex_idx += 1 # Generate quads quads = [] for i in range(0, size_u - 1): for j in range(0, size_v - 1): v1 = vertices[j + (size_v * i)] v2 = vertices[j + (size_v * (i + 1))] v3 = vertices[j + 1 + (size_v * (i + 1))] v4 = vertices[j + 1 + (size_v * i)] qd = Quad(v1, v2, v3, v4, id=quad_idx) quads.append(qd) quad_idx += 1 return vertices, quads
[ "def", "make_quad_mesh", "(", "points", ",", "size_u", ",", "size_v", ")", ":", "# Numbering", "vertex_idx", "=", "0", "quad_idx", "=", "0", "# Generate vertices", "vertices", "=", "[", "]", "for", "pt", "in", "points", ":", "vrt", "=", "Vertex", "(", "*", "pt", ",", "id", "=", "vertex_idx", ")", "vertices", ".", "append", "(", "vrt", ")", "vertex_idx", "+=", "1", "# Generate quads", "quads", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "size_u", "-", "1", ")", ":", "for", "j", "in", "range", "(", "0", ",", "size_v", "-", "1", ")", ":", "v1", "=", "vertices", "[", "j", "+", "(", "size_v", "*", "i", ")", "]", "v2", "=", "vertices", "[", "j", "+", "(", "size_v", "*", "(", "i", "+", "1", ")", ")", "]", "v3", "=", "vertices", "[", "j", "+", "1", "+", "(", "size_v", "*", "(", "i", "+", "1", ")", ")", "]", "v4", "=", "vertices", "[", "j", "+", "1", "+", "(", "size_v", "*", "i", ")", "]", "qd", "=", "Quad", "(", "v1", ",", "v2", ",", "v3", ",", "v4", ",", "id", "=", "quad_idx", ")", "quads", ".", "append", "(", "qd", ")", "quad_idx", "+=", "1", "return", "vertices", ",", "quads" ]
Generates a mesh of quadrilateral elements. :param points: list of points :type points: list, tuple :param size_u: number of points on the u-direction (column) :type size_u: int :param size_v: number of points on the v-direction (row) :type size_v: int :return: a tuple containing lists of vertices and quads :rtype: tuple
[ "Generates", "a", "mesh", "of", "quadrilateral", "elements", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/_tessellate.py#L179-L214