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
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
244,100
orbingol/NURBS-Python
setup.py
copy_files
def copy_files(src, ext, dst): """ Copies files with extensions "ext" from "src" to "dst" directory. """ src_path = os.path.join(os.path.dirname(__file__), src) dst_path = os.path.join(os.path.dirname(__file__), dst) file_list = os.listdir(src_path) for f in file_list: if f == '__init__.py': continue f_path = os.path.join(src_path, f) if os.path.isfile(f_path) and f.endswith(ext): shutil.copy(f_path, dst_path)
python
def copy_files(src, ext, dst): src_path = os.path.join(os.path.dirname(__file__), src) dst_path = os.path.join(os.path.dirname(__file__), dst) file_list = os.listdir(src_path) for f in file_list: if f == '__init__.py': continue f_path = os.path.join(src_path, f) if os.path.isfile(f_path) and f.endswith(ext): shutil.copy(f_path, dst_path)
[ "def", "copy_files", "(", "src", ",", "ext", ",", "dst", ")", ":", "src_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "src", ")", "dst_path", "=", "os", ".", "path", ".", "join", ...
Copies files with extensions "ext" from "src" to "dst" directory.
[ "Copies", "files", "with", "extensions", "ext", "from", "src", "to", "dst", "directory", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/setup.py#L155-L165
244,101
orbingol/NURBS-Python
setup.py
make_dir
def make_dir(project): """ Creates the project directory for compiled modules. """ project_path = os.path.join(os.path.dirname(__file__), project) # Delete the directory and the files inside it if os.path.exists(project_path): shutil.rmtree(project_path) # Create the directory os.mkdir(project_path) # We need a __init__.py file inside the directory with open(os.path.join(project_path, '__init__.py'), 'w') as fp: fp.write('__version__ = "' + str(get_property('__version__', 'geomdl')) + '"\n') fp.write('__author__ = "' + str(get_property('__author__', 'geomdl')) + '"\n') fp.write('__license__ = "' + str(get_property('__license__', 'geomdl')) + '"\n')
python
def make_dir(project): project_path = os.path.join(os.path.dirname(__file__), project) # Delete the directory and the files inside it if os.path.exists(project_path): shutil.rmtree(project_path) # Create the directory os.mkdir(project_path) # We need a __init__.py file inside the directory with open(os.path.join(project_path, '__init__.py'), 'w') as fp: fp.write('__version__ = "' + str(get_property('__version__', 'geomdl')) + '"\n') fp.write('__author__ = "' + str(get_property('__author__', 'geomdl')) + '"\n') fp.write('__license__ = "' + str(get_property('__license__', 'geomdl')) + '"\n')
[ "def", "make_dir", "(", "project", ")", ":", "project_path", "=", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "dirname", "(", "__file__", ")", ",", "project", ")", "# Delete the directory and the files inside it", "if", "os", ".", "path", ...
Creates the project directory for compiled modules.
[ "Creates", "the", "project", "directory", "for", "compiled", "modules", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/setup.py#L168-L180
244,102
orbingol/NURBS-Python
setup.py
in_argv
def in_argv(arg_list): """ Checks if any of the elements of the input list is in sys.argv array. """ for arg in sys.argv: for parg in arg_list: if parg == arg or arg.startswith(parg): return True return False
python
def in_argv(arg_list): for arg in sys.argv: for parg in arg_list: if parg == arg or arg.startswith(parg): return True return False
[ "def", "in_argv", "(", "arg_list", ")", ":", "for", "arg", "in", "sys", ".", "argv", ":", "for", "parg", "in", "arg_list", ":", "if", "parg", "==", "arg", "or", "arg", ".", "startswith", "(", "parg", ")", ":", "return", "True", "return", "False" ]
Checks if any of the elements of the input list is in sys.argv array.
[ "Checks", "if", "any", "of", "the", "elements", "of", "the", "input", "list", "is", "in", "sys", ".", "argv", "array", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/setup.py#L183-L189
244,103
orbingol/NURBS-Python
geomdl/knotvector.py
generate
def generate(degree, num_ctrlpts, **kwargs): """ Generates an equally spaced knot vector. It uses the following equality to generate knot vector: :math:`m = n + p + 1` where; * :math:`p`, degree * :math:`n + 1`, number of control points * :math:`m + 1`, number of knots Keyword Arguments: * ``clamped``: Flag to choose from clamped or unclamped knot vector options. *Default: True* :param degree: degree :type degree: int :param num_ctrlpts: number of control points :type num_ctrlpts: int :return: knot vector :rtype: list """ if degree == 0 or num_ctrlpts == 0: raise ValueError("Input values should be different than zero.") # Get keyword arguments clamped = kwargs.get('clamped', True) # Number of repetitions at the start and end of the array num_repeat = degree # Number of knots in the middle num_segments = num_ctrlpts - (degree + 1) if not clamped: # No repetitions at the start and end num_repeat = 0 # Should conform the rule: m = n + p + 1 num_segments = degree + num_ctrlpts - 1 # First knots knot_vector = [0.0 for _ in range(0, num_repeat)] # Middle knots knot_vector += linspace(0.0, 1.0, num_segments + 2) # Last knots knot_vector += [1.0 for _ in range(0, num_repeat)] # Return auto-generated knot vector return knot_vector
python
def generate(degree, num_ctrlpts, **kwargs): if degree == 0 or num_ctrlpts == 0: raise ValueError("Input values should be different than zero.") # Get keyword arguments clamped = kwargs.get('clamped', True) # Number of repetitions at the start and end of the array num_repeat = degree # Number of knots in the middle num_segments = num_ctrlpts - (degree + 1) if not clamped: # No repetitions at the start and end num_repeat = 0 # Should conform the rule: m = n + p + 1 num_segments = degree + num_ctrlpts - 1 # First knots knot_vector = [0.0 for _ in range(0, num_repeat)] # Middle knots knot_vector += linspace(0.0, 1.0, num_segments + 2) # Last knots knot_vector += [1.0 for _ in range(0, num_repeat)] # Return auto-generated knot vector return knot_vector
[ "def", "generate", "(", "degree", ",", "num_ctrlpts", ",", "*", "*", "kwargs", ")", ":", "if", "degree", "==", "0", "or", "num_ctrlpts", "==", "0", ":", "raise", "ValueError", "(", "\"Input values should be different than zero.\"", ")", "# Get keyword arguments", ...
Generates an equally spaced knot vector. It uses the following equality to generate knot vector: :math:`m = n + p + 1` where; * :math:`p`, degree * :math:`n + 1`, number of control points * :math:`m + 1`, number of knots Keyword Arguments: * ``clamped``: Flag to choose from clamped or unclamped knot vector options. *Default: True* :param degree: degree :type degree: int :param num_ctrlpts: number of control points :type num_ctrlpts: int :return: knot vector :rtype: list
[ "Generates", "an", "equally", "spaced", "knot", "vector", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/knotvector.py#L15-L65
244,104
orbingol/NURBS-Python
geomdl/knotvector.py
check
def check(degree, knot_vector, num_ctrlpts): """ Checks the validity of the input knot vector. Please refer to The NURBS Book (2nd Edition), p.50 for details. :param degree: degree of the curve or the surface :type degree: int :param knot_vector: knot vector to be checked :type knot_vector: list, tuple :param num_ctrlpts: number of control points :type num_ctrlpts: int :return: True if the knot vector is valid, False otherwise :rtype: bool """ try: if knot_vector is None or len(knot_vector) == 0: raise ValueError("Input knot vector cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Knot vector must be a list or tuple") except Exception: raise # Check the formula; m = p + n + 1 if len(knot_vector) != degree + num_ctrlpts + 1: return False # Check ascending order prev_knot = knot_vector[0] for knot in knot_vector: if prev_knot > knot: return False prev_knot = knot return True
python
def check(degree, knot_vector, num_ctrlpts): try: if knot_vector is None or len(knot_vector) == 0: raise ValueError("Input knot vector cannot be empty") except TypeError as e: print("An error occurred: {}".format(e.args[-1])) raise TypeError("Knot vector must be a list or tuple") except Exception: raise # Check the formula; m = p + n + 1 if len(knot_vector) != degree + num_ctrlpts + 1: return False # Check ascending order prev_knot = knot_vector[0] for knot in knot_vector: if prev_knot > knot: return False prev_knot = knot return True
[ "def", "check", "(", "degree", ",", "knot_vector", ",", "num_ctrlpts", ")", ":", "try", ":", "if", "knot_vector", "is", "None", "or", "len", "(", "knot_vector", ")", "==", "0", ":", "raise", "ValueError", "(", "\"Input knot vector cannot be empty\"", ")", "e...
Checks the validity of the input knot vector. Please refer to The NURBS Book (2nd Edition), p.50 for details. :param degree: degree of the curve or the surface :type degree: int :param knot_vector: knot vector to be checked :type knot_vector: list, tuple :param num_ctrlpts: number of control points :type num_ctrlpts: int :return: True if the knot vector is valid, False otherwise :rtype: bool
[ "Checks", "the", "validity", "of", "the", "input", "knot", "vector", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/knotvector.py#L99-L133
244,105
orbingol/NURBS-Python
geomdl/fitting.py
interpolate_curve
def interpolate_curve(points, degree, **kwargs): """ Curve interpolation through the data points. Please refer to Algorithm A9.1 on The NURBS Book (2nd Edition), pp.369-370 for details. Keyword Arguments: * ``centripetal``: activates centripetal parametrization method. *Default: False* :param points: data points :type points: list, tuple :param degree: degree of the output parametric curve :type degree: int :return: interpolated B-Spline curve :rtype: BSpline.Curve """ # Keyword arguments use_centripetal = kwargs.get('centripetal', False) # Number of control points num_points = len(points) # Get uk uk = compute_params_curve(points, use_centripetal) # Compute knot vector kv = compute_knot_vector(degree, num_points, uk) # Do global interpolation matrix_a = _build_coeff_matrix(degree, kv, uk, points) ctrlpts = ginterp(matrix_a, points) # Generate B-spline curve curve = BSpline.Curve() curve.degree = degree curve.ctrlpts = ctrlpts curve.knotvector = kv return curve
python
def interpolate_curve(points, degree, **kwargs): # Keyword arguments use_centripetal = kwargs.get('centripetal', False) # Number of control points num_points = len(points) # Get uk uk = compute_params_curve(points, use_centripetal) # Compute knot vector kv = compute_knot_vector(degree, num_points, uk) # Do global interpolation matrix_a = _build_coeff_matrix(degree, kv, uk, points) ctrlpts = ginterp(matrix_a, points) # Generate B-spline curve curve = BSpline.Curve() curve.degree = degree curve.ctrlpts = ctrlpts curve.knotvector = kv return curve
[ "def", "interpolate_curve", "(", "points", ",", "degree", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "use_centripetal", "=", "kwargs", ".", "get", "(", "'centripetal'", ",", "False", ")", "# Number of control points", "num_points", "=", "len", "("...
Curve interpolation through the data points. Please refer to Algorithm A9.1 on The NURBS Book (2nd Edition), pp.369-370 for details. Keyword Arguments: * ``centripetal``: activates centripetal parametrization method. *Default: False* :param points: data points :type points: list, tuple :param degree: degree of the output parametric curve :type degree: int :return: interpolated B-Spline curve :rtype: BSpline.Curve
[ "Curve", "interpolation", "through", "the", "data", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/fitting.py#L16-L53
244,106
orbingol/NURBS-Python
geomdl/fitting.py
interpolate_surface
def interpolate_surface(points, size_u, size_v, degree_u, degree_v, **kwargs): """ Surface interpolation through the data points. Please refer to the Algorithm A9.4 on The NURBS Book (2nd Edition), pp.380 for details. Keyword Arguments: * ``centripetal``: activates centripetal parametrization method. *Default: False* :param points: data points :type points: list, tuple :param size_u: number of data points on the u-direction :type size_u: int :param size_v: number of data points on the v-direction :type size_v: int :param degree_u: degree of the output surface for the u-direction :type degree_u: int :param degree_v: degree of the output surface for the v-direction :type degree_v: int :return: interpolated B-Spline surface :rtype: BSpline.Surface """ # Keyword arguments use_centripetal = kwargs.get('centripetal', False) # Get uk and vl uk, vl = compute_params_surface(points, size_u, size_v, use_centripetal) # Compute knot vectors kv_u = compute_knot_vector(degree_u, size_u, uk) kv_v = compute_knot_vector(degree_v, size_v, vl) # Do global interpolation on the u-direction ctrlpts_r = [] for v in range(size_v): pts = [points[v + (size_v * u)] for u in range(size_u)] matrix_a = _build_coeff_matrix(degree_u, kv_u, uk, pts) ctrlpts_r += ginterp(matrix_a, pts) # Do global interpolation on the v-direction ctrlpts = [] for u in range(size_u): pts = [ctrlpts_r[u + (size_u * v)] for v in range(size_v)] matrix_a = _build_coeff_matrix(degree_v, kv_v, vl, pts) ctrlpts += ginterp(matrix_a, pts) # Generate B-spline surface surf = BSpline.Surface() surf.degree_u = degree_u surf.degree_v = degree_v surf.ctrlpts_size_u = size_u surf.ctrlpts_size_v = size_v surf.ctrlpts = ctrlpts surf.knotvector_u = kv_u surf.knotvector_v = kv_v return surf
python
def interpolate_surface(points, size_u, size_v, degree_u, degree_v, **kwargs): # Keyword arguments use_centripetal = kwargs.get('centripetal', False) # Get uk and vl uk, vl = compute_params_surface(points, size_u, size_v, use_centripetal) # Compute knot vectors kv_u = compute_knot_vector(degree_u, size_u, uk) kv_v = compute_knot_vector(degree_v, size_v, vl) # Do global interpolation on the u-direction ctrlpts_r = [] for v in range(size_v): pts = [points[v + (size_v * u)] for u in range(size_u)] matrix_a = _build_coeff_matrix(degree_u, kv_u, uk, pts) ctrlpts_r += ginterp(matrix_a, pts) # Do global interpolation on the v-direction ctrlpts = [] for u in range(size_u): pts = [ctrlpts_r[u + (size_u * v)] for v in range(size_v)] matrix_a = _build_coeff_matrix(degree_v, kv_v, vl, pts) ctrlpts += ginterp(matrix_a, pts) # Generate B-spline surface surf = BSpline.Surface() surf.degree_u = degree_u surf.degree_v = degree_v surf.ctrlpts_size_u = size_u surf.ctrlpts_size_v = size_v surf.ctrlpts = ctrlpts surf.knotvector_u = kv_u surf.knotvector_v = kv_v return surf
[ "def", "interpolate_surface", "(", "points", ",", "size_u", ",", "size_v", ",", "degree_u", ",", "degree_v", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "use_centripetal", "=", "kwargs", ".", "get", "(", "'centripetal'", ",", "False", ")", "# G...
Surface interpolation through the data points. Please refer to the Algorithm A9.4 on The NURBS Book (2nd Edition), pp.380 for details. Keyword Arguments: * ``centripetal``: activates centripetal parametrization method. *Default: False* :param points: data points :type points: list, tuple :param size_u: number of data points on the u-direction :type size_u: int :param size_v: number of data points on the v-direction :type size_v: int :param degree_u: degree of the output surface for the u-direction :type degree_u: int :param degree_v: degree of the output surface for the v-direction :type degree_v: int :return: interpolated B-Spline surface :rtype: BSpline.Surface
[ "Surface", "interpolation", "through", "the", "data", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/fitting.py#L57-L112
244,107
orbingol/NURBS-Python
geomdl/fitting.py
compute_knot_vector
def compute_knot_vector(degree, num_points, params): """ Computes a knot vector from the parameter list using averaging method. Please refer to the Equation 9.8 on The NURBS Book (2nd Edition), pp.365 for details. :param degree: degree :type degree: int :param num_points: number of data points :type num_points: int :param params: list of parameters, :math:`\\overline{u}_{k}` :type params: list, tuple :return: knot vector :rtype: list """ # Start knot vector kv = [0.0 for _ in range(degree + 1)] # Use averaging method (Eqn 9.8) to compute internal knots in the knot vector for i in range(num_points - degree - 1): temp_kv = (1.0 / degree) * sum([params[j] for j in range(i + 1, i + degree + 1)]) kv.append(temp_kv) # End knot vector kv += [1.0 for _ in range(degree + 1)] return kv
python
def compute_knot_vector(degree, num_points, params): # Start knot vector kv = [0.0 for _ in range(degree + 1)] # Use averaging method (Eqn 9.8) to compute internal knots in the knot vector for i in range(num_points - degree - 1): temp_kv = (1.0 / degree) * sum([params[j] for j in range(i + 1, i + degree + 1)]) kv.append(temp_kv) # End knot vector kv += [1.0 for _ in range(degree + 1)] return kv
[ "def", "compute_knot_vector", "(", "degree", ",", "num_points", ",", "params", ")", ":", "# Start knot vector", "kv", "=", "[", "0.0", "for", "_", "in", "range", "(", "degree", "+", "1", ")", "]", "# Use averaging method (Eqn 9.8) to compute internal knots in the kn...
Computes a knot vector from the parameter list using averaging method. Please refer to the Equation 9.8 on The NURBS Book (2nd Edition), pp.365 for details. :param degree: degree :type degree: int :param num_points: number of data points :type num_points: int :param params: list of parameters, :math:`\\overline{u}_{k}` :type params: list, tuple :return: knot vector :rtype: list
[ "Computes", "a", "knot", "vector", "from", "the", "parameter", "list", "using", "averaging", "method", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/fitting.py#L358-L383
244,108
orbingol/NURBS-Python
geomdl/fitting.py
ginterp
def ginterp(coeff_matrix, points): """ Applies global interpolation to the set of data points to find control points. :param coeff_matrix: coefficient matrix :type coeff_matrix: list, tuple :param points: data points :type points: list, tuple :return: control points :rtype: list """ # Dimension dim = len(points[0]) # Number of data points num_points = len(points) # Solve system of linear equations matrix_l, matrix_u = linalg.lu_decomposition(coeff_matrix) ctrlpts = [[0.0 for _ in range(dim)] for _ in range(num_points)] for i in range(dim): b = [pt[i] for pt in points] y = linalg.forward_substitution(matrix_l, b) x = linalg.backward_substitution(matrix_u, y) for j in range(num_points): ctrlpts[j][i] = x[j] # Return control points return ctrlpts
python
def ginterp(coeff_matrix, points): # Dimension dim = len(points[0]) # Number of data points num_points = len(points) # Solve system of linear equations matrix_l, matrix_u = linalg.lu_decomposition(coeff_matrix) ctrlpts = [[0.0 for _ in range(dim)] for _ in range(num_points)] for i in range(dim): b = [pt[i] for pt in points] y = linalg.forward_substitution(matrix_l, b) x = linalg.backward_substitution(matrix_u, y) for j in range(num_points): ctrlpts[j][i] = x[j] # Return control points return ctrlpts
[ "def", "ginterp", "(", "coeff_matrix", ",", "points", ")", ":", "# Dimension", "dim", "=", "len", "(", "points", "[", "0", "]", ")", "# Number of data points", "num_points", "=", "len", "(", "points", ")", "# Solve system of linear equations", "matrix_l", ",", ...
Applies global interpolation to the set of data points to find control points. :param coeff_matrix: coefficient matrix :type coeff_matrix: list, tuple :param points: data points :type points: list, tuple :return: control points :rtype: list
[ "Applies", "global", "interpolation", "to", "the", "set", "of", "data", "points", "to", "find", "control", "points", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/fitting.py#L509-L536
244,109
orbingol/NURBS-Python
geomdl/fitting.py
_build_coeff_matrix
def _build_coeff_matrix(degree, knotvector, params, points): """ Builds the coefficient matrix for global interpolation. This function only uses data points to build the coefficient matrix. Please refer to The NURBS Book (2nd Edition), pp364-370 for details. :param degree: degree :type degree: int :param knotvector: knot vector :type knotvector: list, tuple :param params: list of parameters :type params: list, tuple :param points: data points :type points: list, tuple :return: coefficient matrix :rtype: list """ # Number of data points num_points = len(points) # Set up coefficient matrix matrix_a = [[0.0 for _ in range(num_points)] for _ in range(num_points)] for i in range(num_points): span = helpers.find_span_linear(degree, knotvector, num_points, params[i]) matrix_a[i][span-degree:span+1] = helpers.basis_function(degree, knotvector, span, params[i]) # Return coefficient matrix return matrix_a
python
def _build_coeff_matrix(degree, knotvector, params, points): # Number of data points num_points = len(points) # Set up coefficient matrix matrix_a = [[0.0 for _ in range(num_points)] for _ in range(num_points)] for i in range(num_points): span = helpers.find_span_linear(degree, knotvector, num_points, params[i]) matrix_a[i][span-degree:span+1] = helpers.basis_function(degree, knotvector, span, params[i]) # Return coefficient matrix return matrix_a
[ "def", "_build_coeff_matrix", "(", "degree", ",", "knotvector", ",", "params", ",", "points", ")", ":", "# Number of data points", "num_points", "=", "len", "(", "points", ")", "# Set up coefficient matrix", "matrix_a", "=", "[", "[", "0.0", "for", "_", "in", ...
Builds the coefficient matrix for global interpolation. This function only uses data points to build the coefficient matrix. Please refer to The NURBS Book (2nd Edition), pp364-370 for details. :param degree: degree :type degree: int :param knotvector: knot vector :type knotvector: list, tuple :param params: list of parameters :type params: list, tuple :param points: data points :type points: list, tuple :return: coefficient matrix :rtype: list
[ "Builds", "the", "coefficient", "matrix", "for", "global", "interpolation", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/fitting.py#L539-L566
244,110
orbingol/NURBS-Python
geomdl/visualization/vtk_helpers.py
create_render_window
def create_render_window(actors, callbacks, **kwargs): """ Creates VTK render window with an interactor. :param actors: list of VTK actors :type actors: list, tuple :param callbacks: callback functions for registering custom events :type callbacks: dict """ # Get keyword arguments figure_size = kwargs.get('figure_size', (800, 600)) camera_position = kwargs.get('camera_position', (0, 0, 100)) # Find camera focal point center_points = [] for actor in actors: center_points.append(actor.GetCenter()) camera_focal_point = linalg.vector_mean(*center_points) # Create camera camera = vtk.vtkCamera() camera.SetPosition(*camera_position) camera.SetFocalPoint(*camera_focal_point) # Create renderer renderer = vtk.vtkRenderer() renderer.SetActiveCamera(camera) renderer.SetBackground(1.0, 1.0, 1.0) # Add actors to the scene for actor in actors: renderer.AddActor(actor) # Render window render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window.SetSize(*figure_size) # Render window interactor window_interactor = vtk.vtkRenderWindowInteractor() window_interactor.SetRenderWindow(render_window) # Add event observers for cb in callbacks: window_interactor.AddObserver(cb, callbacks[cb][0], callbacks[cb][1]) # cb name, cb function ref, cb priority # Render actors render_window.Render() # Set window name after render() is called render_window.SetWindowName("geomdl") # Use trackball camera interactor_style = vtk.vtkInteractorStyleTrackballCamera() window_interactor.SetInteractorStyle(interactor_style) # Start interactor window_interactor.Start() # Return window interactor instance return window_interactor
python
def create_render_window(actors, callbacks, **kwargs): # Get keyword arguments figure_size = kwargs.get('figure_size', (800, 600)) camera_position = kwargs.get('camera_position', (0, 0, 100)) # Find camera focal point center_points = [] for actor in actors: center_points.append(actor.GetCenter()) camera_focal_point = linalg.vector_mean(*center_points) # Create camera camera = vtk.vtkCamera() camera.SetPosition(*camera_position) camera.SetFocalPoint(*camera_focal_point) # Create renderer renderer = vtk.vtkRenderer() renderer.SetActiveCamera(camera) renderer.SetBackground(1.0, 1.0, 1.0) # Add actors to the scene for actor in actors: renderer.AddActor(actor) # Render window render_window = vtk.vtkRenderWindow() render_window.AddRenderer(renderer) render_window.SetSize(*figure_size) # Render window interactor window_interactor = vtk.vtkRenderWindowInteractor() window_interactor.SetRenderWindow(render_window) # Add event observers for cb in callbacks: window_interactor.AddObserver(cb, callbacks[cb][0], callbacks[cb][1]) # cb name, cb function ref, cb priority # Render actors render_window.Render() # Set window name after render() is called render_window.SetWindowName("geomdl") # Use trackball camera interactor_style = vtk.vtkInteractorStyleTrackballCamera() window_interactor.SetInteractorStyle(interactor_style) # Start interactor window_interactor.Start() # Return window interactor instance return window_interactor
[ "def", "create_render_window", "(", "actors", ",", "callbacks", ",", "*", "*", "kwargs", ")", ":", "# Get keyword arguments", "figure_size", "=", "kwargs", ".", "get", "(", "'figure_size'", ",", "(", "800", ",", "600", ")", ")", "camera_position", "=", "kwar...
Creates VTK render window with an interactor. :param actors: list of VTK actors :type actors: list, tuple :param callbacks: callback functions for registering custom events :type callbacks: dict
[ "Creates", "VTK", "render", "window", "with", "an", "interactor", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/vtk_helpers.py#L14-L73
244,111
orbingol/NURBS-Python
geomdl/visualization/vtk_helpers.py
create_color
def create_color(color): """ Creates VTK-compatible RGB color from a color string. :param color: color :type color: str :return: RGB color values :rtype: list """ if color[0] == "#": # Convert hex string to RGB return [int(color[i:i + 2], 16) / 255 for i in range(1, 7, 2)] else: # Create a named colors instance nc = vtk.vtkNamedColors() return nc.GetColor3d(color)
python
def create_color(color): if color[0] == "#": # Convert hex string to RGB return [int(color[i:i + 2], 16) / 255 for i in range(1, 7, 2)] else: # Create a named colors instance nc = vtk.vtkNamedColors() return nc.GetColor3d(color)
[ "def", "create_color", "(", "color", ")", ":", "if", "color", "[", "0", "]", "==", "\"#\"", ":", "# Convert hex string to RGB", "return", "[", "int", "(", "color", "[", "i", ":", "i", "+", "2", "]", ",", "16", ")", "/", "255", "for", "i", "in", "...
Creates VTK-compatible RGB color from a color string. :param color: color :type color: str :return: RGB color values :rtype: list
[ "Creates", "VTK", "-", "compatible", "RGB", "color", "from", "a", "color", "string", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/vtk_helpers.py#L76-L90
244,112
orbingol/NURBS-Python
geomdl/visualization/vtk_helpers.py
create_actor_pts
def create_actor_pts(pts, color, **kwargs): """ Creates a VTK actor for rendering scatter plots. :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) point_size = kwargs.get('size', 5) point_sphere = kwargs.get('point_as_sphere', True) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create a PolyData object and add points polydata = vtk.vtkPolyData() polydata.SetPoints(points) # Run vertex glyph filter on the points array vertex_filter = vtk.vtkVertexGlyphFilter() vertex_filter.SetInputData(polydata) # Map ploy data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(vertex_filter.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) actor.GetProperty().SetPointSize(point_size) actor.GetProperty().SetRenderPointsAsSpheres(point_sphere) # Return the actor return actor
python
def create_actor_pts(pts, color, **kwargs): # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) point_size = kwargs.get('size', 5) point_sphere = kwargs.get('point_as_sphere', True) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create a PolyData object and add points polydata = vtk.vtkPolyData() polydata.SetPoints(points) # Run vertex glyph filter on the points array vertex_filter = vtk.vtkVertexGlyphFilter() vertex_filter.SetInputData(polydata) # Map ploy data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputConnection(vertex_filter.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) actor.GetProperty().SetPointSize(point_size) actor.GetProperty().SetRenderPointsAsSpheres(point_sphere) # Return the actor return actor
[ "def", "create_actor_pts", "(", "pts", ",", "color", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "array_name", "=", "kwargs", ".", "get", "(", "'name'", ",", "\"\"", ")", "array_index", "=", "kwargs", ".", "get", "(", "'index'", ",", "0", ...
Creates a VTK actor for rendering scatter plots. :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", "scatter", "plots", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/vtk_helpers.py#L93-L135
244,113
orbingol/NURBS-Python
geomdl/visualization/vtk_helpers.py
create_actor_polygon
def create_actor_polygon(pts, color, **kwargs): """ Creates a VTK actor for rendering polygons. :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) line_width = kwargs.get('size', 1.0) # Create points points = vtk.vtkPoints() points.SetData(pts) # Number of points num_points = points.GetNumberOfPoints() # Create lines cells = vtk.vtkCellArray() for i in range(num_points - 1): line = vtk.vtkLine() line.GetPointIds().SetId(0, i) line.GetPointIds().SetId(1, i + 1) cells.InsertNextCell(line) # Create a PolyData object and add points & lines polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetLines(cells) # Map poly data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputDataObject(polydata) 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) actor.GetProperty().SetLineWidth(line_width) # Return the actor return actor
python
def create_actor_polygon(pts, color, **kwargs): # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) line_width = kwargs.get('size', 1.0) # Create points points = vtk.vtkPoints() points.SetData(pts) # Number of points num_points = points.GetNumberOfPoints() # Create lines cells = vtk.vtkCellArray() for i in range(num_points - 1): line = vtk.vtkLine() line.GetPointIds().SetId(0, i) line.GetPointIds().SetId(1, i + 1) cells.InsertNextCell(line) # Create a PolyData object and add points & lines polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetLines(cells) # Map poly data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputDataObject(polydata) 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) actor.GetProperty().SetLineWidth(line_width) # Return the actor return actor
[ "def", "create_actor_polygon", "(", "pts", ",", "color", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "array_name", "=", "kwargs", ".", "get", "(", "'name'", ",", "\"\"", ")", "array_index", "=", "kwargs", ".", "get", "(", "'index'", ",", "0...
Creates a VTK actor for rendering polygons. :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", "polygons", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/vtk_helpers.py#L138-L186
244,114
orbingol/NURBS-Python
geomdl/visualization/vtk_helpers.py
create_actor_mesh
def create_actor_mesh(pts, lines, color, **kwargs): """ Creates a VTK actor for rendering quadrilateral plots. :param pts: points :type pts: vtkFloatArray :param lines: point connectivity information :type lines: vtkIntArray :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) line_width = kwargs.get('size', 0.5) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create lines cells = vtk.vtkCellArray() for line in lines: pline = vtk.vtkPolyLine() pline.GetPointIds().SetNumberOfIds(5) for i in range(len(line)): pline.GetPointIds().SetId(i, line[i]) pline.GetPointIds().SetId(4, line[0]) cells.InsertNextCell(pline) # Create a PolyData object and add points & lines polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetLines(cells) # Map poly data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputDataObject(polydata) 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) actor.GetProperty().SetLineWidth(line_width) # Return the actor return actor
python
def create_actor_mesh(pts, lines, color, **kwargs): # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) line_width = kwargs.get('size', 0.5) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create lines cells = vtk.vtkCellArray() for line in lines: pline = vtk.vtkPolyLine() pline.GetPointIds().SetNumberOfIds(5) for i in range(len(line)): pline.GetPointIds().SetId(i, line[i]) pline.GetPointIds().SetId(4, line[0]) cells.InsertNextCell(pline) # Create a PolyData object and add points & lines polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetLines(cells) # Map poly data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputDataObject(polydata) 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) actor.GetProperty().SetLineWidth(line_width) # Return the actor return actor
[ "def", "create_actor_mesh", "(", "pts", ",", "lines", ",", "color", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "array_name", "=", "kwargs", ".", "get", "(", "'name'", ",", "\"\"", ")", "array_index", "=", "kwargs", ".", "get", "(", "'index...
Creates a VTK actor for rendering quadrilateral plots. :param pts: points :type pts: vtkFloatArray :param lines: point connectivity information :type lines: vtkIntArray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor
[ "Creates", "a", "VTK", "actor", "for", "rendering", "quadrilateral", "plots", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/vtk_helpers.py#L189-L238
244,115
orbingol/NURBS-Python
geomdl/visualization/vtk_helpers.py
create_actor_tri
def create_actor_tri(pts, tris, color, **kwargs): """ Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: 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 points points = vtk.vtkPoints() points.SetData(pts) # Create triangles triangles = vtk.vtkCellArray() for tri in tris: tmp = vtk.vtkTriangle() for i, v in enumerate(tri): tmp.GetPointIds().SetId(i, v) triangles.InsertNextCell(tmp) # Create a PolyData object and add points & triangles polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(triangles) # Map poly data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputDataObject(polydata) 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_tri(pts, tris, color, **kwargs): # Keyword arguments array_name = kwargs.get('name', "") array_index = kwargs.get('index', 0) # Create points points = vtk.vtkPoints() points.SetData(pts) # Create triangles triangles = vtk.vtkCellArray() for tri in tris: tmp = vtk.vtkTriangle() for i, v in enumerate(tri): tmp.GetPointIds().SetId(i, v) triangles.InsertNextCell(tmp) # Create a PolyData object and add points & triangles polydata = vtk.vtkPolyData() polydata.SetPoints(points) polydata.SetPolys(triangles) # Map poly data to the graphics primitives mapper = vtk.vtkPolyDataMapper() mapper.SetInputDataObject(polydata) 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_tri", "(", "pts", ",", "tris", ",", "color", ",", "*", "*", "kwargs", ")", ":", "# Keyword arguments", "array_name", "=", "kwargs", ".", "get", "(", "'name'", ",", "\"\"", ")", "array_index", "=", "kwargs", ".", "get", "(", "'index'"...
Creates a VTK actor for rendering triangulated surface plots. :param pts: points :type pts: vtkFloatArray :param tris: list of triangle indices :type tris: ndarray :param color: actor color :type color: list :return: a VTK actor :rtype: vtkActor
[ "Creates", "a", "VTK", "actor", "for", "rendering", "triangulated", "surface", "plots", "." ]
b1c6a8b51cf143ff58761438e93ba6baef470627
https://github.com/orbingol/NURBS-Python/blob/b1c6a8b51cf143ff58761438e93ba6baef470627/geomdl/visualization/vtk_helpers.py#L241-L286
244,116
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): # 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'", ",", ...
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
244,117
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): # 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'", ",", "...
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
244,118
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): 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", "="...
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
244,119
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): # 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", ...
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
244,120
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): # 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", "i...
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
244,121
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): 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", "=", "[", "]", ...
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
244,122
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): 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", "...
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
244,123
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'): # 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_ctr...
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
244,124
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'): # 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", ...
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
244,125
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): 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_wind...
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
244,126
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): # 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", ":",...
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
244,127
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): 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", ...
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
244,128
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): 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", "=...
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
244,129
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): 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", "="...
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
244,130
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): # 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", ".", "...
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
244,131
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): # 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", ...
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
244,132
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): # 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...
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
244,133
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): 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 shoul...
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
244,134
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): 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",...
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
244,135
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): 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",...
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
244,136
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): 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", ...
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
244,137
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): 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"...
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
244,138
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): 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'", ",", "...
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
244,139
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): 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", "(",...
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
244,140
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): 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",...
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
244,141
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): # 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", ",", ...
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
244,142
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): 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", "(", "*", "*", ...
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
244,143
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): 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", "=", "cou...
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
244,144
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): # 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...
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
244,145
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): 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", "]...
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
244,146
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): 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", ","...
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
244,147
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): # 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...
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
244,148
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): 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", "(", "degr...
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
244,149
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): 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", "...
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
244,150
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): 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", ")",...
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
244,151
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): 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...
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
244,152
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): # 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", "(",...
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
244,153
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): 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", "]", "-...
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
244,154
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): # 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", "(", ...
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
244,155
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): 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_ve...
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
244,156
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): # 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", ...
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
244,157
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): 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_vect...
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
244,158
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): # 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_c...
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
244,159
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): 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_...
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
244,160
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): 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", ")", "re...
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
244,161
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): 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_...
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
244,162
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): # 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", ...
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
244,163
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): # 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", "sp...
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
244,164
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): # 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", ")", "# Val...
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
244,165
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): 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 argu...
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
244,166
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): # 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...
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
244,167
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): 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_cur...
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
244,168
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): 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", "=", ...
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
244,169
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): # 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 ab...
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
244,170
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): 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", "[", "...
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
244,171
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): 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",...
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
244,172
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): 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", ...
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
244,173
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): 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"...
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
244,174
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): # 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 ...
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
244,175
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): # 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 b...
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
244,176
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): # 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_c...
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
244,177
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): 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", "]", ...
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
244,178
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): 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", "(", "\...
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
244,179
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): 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", "Valu...
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
244,180
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): 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", "ValueE...
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
244,181
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): 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", ...
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
244,182
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): 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",...
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
244,183
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): 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", ")...
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
244,184
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): 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
244,185
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): 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_magnitu...
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
244,186
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): 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", "=...
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
244,187
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): 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", ":", "rai...
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
244,188
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): 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...
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
244,189
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): 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", ...
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
244,190
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): 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", "=", "[", "]", "fo...
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
244,191
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): 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...
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
244,192
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): # 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", ")", "...
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
244,193
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): 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", ...
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
244,194
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): 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", "(", ...
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
244,195
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): 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", ":", "...
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
244,196
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): 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", "<", ...
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
244,197
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): 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", "]", ")", ")", "-", "(", "(...
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
244,198
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): 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", ")", ":", "#...
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
244,199
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): # 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", "(",...
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