def vertical_from_q_rhino(form, *args, **kwargs): import compas_rhino def callback(line, args): print(line) compas_rhino.wait() f = XFunc('compas_tna.equilibrium.vertical_from_q_xfunc') f.tmpdir = compas_tna.TEMP f.callback = callback formdata = f(form.to_data(), *args, **kwargs) form.data = formdata
def delaunay(vertices, src='compas', cls=None): """Group the Delaunay functions from compas, numpy. Parameters ---------- vertices : list List of vertex coordinates. src : string Specify Delaunay algorithm to use: compas or numpy. cls Mesh class. Returns ------- cls The Delaunay mesh. """ if cls is None: cls = Mesh if src == 'compas': faces = delaunay_from_points(vertices) elif src == 'numpy_rpc': faces = delaunay_numpy_rpc(vertices) elif src == 'numpy_xfunc': faces = XFunc( 'compas_pattern.algorithms.decomposition.triangulation.delaunay_numpy_xfunc' )(vertices) else: return None return cls.from_vertices_and_faces(vertices, faces)
def horizontal_nodal_rhino(form, force, *args, **kwargs): import compas_rhino def callback(line, args): print(line) compas_rhino.wait() f = XFunc('compas_tna.equilibrium.horizontal_nodal_xfunc', tmpdir=compas_tna.TEMP, callback=callback) formdata, forcedata = f(form.to_data(), force.to_data(), *args, **kwargs) form.data = formdata force.data = forcedata
import compas import compas_rhino from compas.datastructures import Mesh from compas.utilities import XFunc # make the function available as a wrapped function with the same call signature and return value as the original. fd_numpy = XFunc('compas.numerical.fd_numpy') mesh = Mesh.from_obj(compas.get('faces.obj')) mesh.update_default_vertex_attributes({ 'is_fixed': False, 'px': 0.0, 'py': 0.0, 'pz': 0.0 }) mesh.update_default_edge_attributes({'q': 1.0}) for key, attr in mesh.vertices(True): attr['is_fixed'] = mesh.vertex_degree(key) == 2 key_index = mesh.key_index() vertices = mesh.get_vertices_attributes('xyz') edges = [(key_index[u], key_index[v]) for u, v in mesh.edges()] fixed = [key_index[key] for key in mesh.vertices_where({'is_fixed': True})] q = mesh.get_edges_attribute('q', 1.0) loads = mesh.get_vertices_attributes(('px', 'py', 'pz'), (0.0, 0.0, 0.0)) xyz, q, f, l, r = fd_numpy(vertices, edges, fixed, q, loads)
__copyright__ = 'Copyright 2017, BLOCK Research Group - ETH Zurich' __license__ = 'MIT License' __email__ = '*****@*****.**' # Input guid = rs.ObjectsByLayer('Plane')[0] rhinomesh = RhinoMesh(guid) vertices, faces = rhinomesh.get_vertices_and_faces() points = [[x, y, sin(x) * cos(y)] for x, y, z in vertices] # Set-up XFunc basedir = 'D:/compas-dev/examples/' tmpdir = 'C:/Temp/' xfunc = XFunc(basedir=basedir, tmpdir=tmpdir) # Python xfunc.funcname = 'hpc_normals_func.python_normals' normals, toc1 = xfunc(points, offset=0.5)['data'] print('Python : {0:.6f} ms'.format(toc1 * 1000)) # Numba xfunc.funcname = 'hpc_normals_func.numba_normals' normals, toc2 = xfunc(points, offset=0.5)['data'] print('Numba : {0:.6f} ms'.format((toc2 * 1000))) # Numpy
import compas import compas_rhino from compas.datastructures import Mesh from compas.utilities import XFunc from compas_rhino.helpers import MeshArtist mesh = Mesh.from_obj(compas.get('faces.obj')) vertices = mesh.get_vertices_attributes('xyz') edges = list(mesh.edges()) fixed = list([key for key in mesh.vertices() if mesh.vertex_degree(key) == 2]) q = mesh.get_edges_attribute('q', 1.0) loads = mesh.get_vertices_attributes(('px', 'py', 'pz'), (0.0, 0.0, 0.0)) xyz, q, f, l, r = XFunc('compas.numerical.fd_numpy')(vertices, edges, fixed, q, loads) for key, attr in mesh.vertices(True): attr['x'] = xyz[key][0] attr['y'] = xyz[key][1] attr['z'] = xyz[key][2] artist = MeshArtist(mesh) artist.clear() artist.draw_vertices() artist.draw_edges() artist.redraw()
vertices = network.get_vertices_attributes('xyz') edges = list(network.edges()) fixed = list(network.vertices_where({'is_fixed': True})) # q_bnd=18.25 , q_valley=16.25 , q_ridge=13.75 , q_rest=1.0 q = network.get_edges_attribute('q') # edges to assign length constraint (bnd, ridge and valley) lengths = network.edges_where({'l': True}) # edges to assign force constraint (rest) forces = network.edges_where({'f': True}) # FDM with iterative computation of q # LU decomposition for solving lin. system # procedure ends by reaching the num. of steps # lengths from the first iteration step nc0, f0, q0 = XFunc('iter.multistepFDM')(vertices, edges, fixed, q, steps=1) ll0 = XFunc('iter.list_of_element_lengths')(edges, nc0) # assignment of constraints # length constraints as lengths from the first iteration step for bnd, ridge and valley cables indexl = get_index(edges, lengths) edgvl = get_values(indexl, ll0) length_constraints = edge_constraints(indexl, edgvl) # force constraints as S=1.0 for the rest of the bars indexf = get_index(edges, forces) fs = map_value_to_all_edges(forces, 1.0) force_constraints = edge_constraints(indexf, fs) ##FDM with iterative computation of q - tolerances added for the termination of the outer loop ##LU decomposition for solving lin. system
def plot_principal_stresses(structure, step, ptype, scale, rotate=0, layer=None): """ Plots the principal stresses of the elements. Parameters ---------- structure : obj Structure object. step : str Name of the Step. ptype : str 'max' 'min' for maximum or minimum principal stresses. scale : float Scale on the length of the line markers. rotate : int Rotate lines by 90 deg, 0 or 1. layer : str Layer name for plotting. Returns ------- None Notes ----- - Currently an alpha script and only for triangular shell elements in Abaqus. - Centroids are taken on the undeformed geometry. """ data = structure.results[step]['element'] basedir = utilities.__file__.split('__init__.py')[0] xfunc = XFunc('principal_stresses', basedir=basedir, tmpdir=structure.path) xfunc.funcname = 'functions.principal_stresses' result = xfunc(data, ptype, scale, rotate) try: vec1, vec5, pr1, pr5 = result if not layer: layer = '{0}_principal_{1}'.format(step, ptype) rs.CurrentLayer(rs.AddLayer(layer)) rs.DeleteObjects(rs.ObjectsByLayer(layer)) centroids = [ structure.element_centroid(i) for i in sorted(structure.elements, key=int) ] rs.EnableRedraw(False) for c, centroid in enumerate(centroids): v1 = vec1[c] v5 = vec5[c] id1 = rs.AddLine(add_vectors(centroid, scale_vector(v1, -1)), add_vectors(centroid, v1)) id5 = rs.AddLine(add_vectors(centroid, scale_vector(v5, -1)), add_vectors(centroid, v5)) col1 = [255, 0, 0] if pr1[c] > 0 else [0, 0, 255] col5 = [255, 0, 0] if pr5[c] > 0 else [0, 0, 255] rs.ObjectColor(id1, col1) rs.ObjectColor(id5, col5) rs.EnableRedraw(True) except: print('\n***** Error calculating/plotting principal stresses *****')
import os import compas import compas_rhino import compas_rbe from compas.utilities import XFunc HERE = os.path.abspath(os.path.dirname(__file__)) try: import rhinoscriptsyntax as rs except ImportError: pass assembly_interfaces = XFunc('compas_rbe.interfaces.assembly_interfaces_xfunc', tmpdir=compas_rbe.TEMP) __all__ = ['InterfaceActions'] class InterfaceActions(object): def assembly_interfaces(self): assembly = self.assembly data = { 'assembly': assembly.to_data(), 'blocks': { str(key): assembly.blocks[key].to_data() for key in assembly.blocks }, }
import rhinoscriptsyntax as rs from compas.utilities import XFunc points = rs.GetObjects('pts', filter=1) points = [rs.PointCoordinates(pt) for pt in points] points = [[xyz[0], xyz[1], xyz[2]] for xyz in points] #from compas_pattern.algorithms.spatial_skeletonisation import spatial_skeleton_xfunc simplices, neighbors = XFunc( 'compas_pattern.algorithms.spatial_skeletonisation.spatial_skeleton_xfunc' )(points) #rs.EnableRedraw(False) #for a, b, c, d in simplices: # a, b, c, d = points[a], points[b], points[c], points[d] # group = rs.AddGroup() # lines = [rs.AddLine(a, b), rs.AddLine(a, c), rs.AddLine(a, d), rs.AddLine(b, c), rs.AddLine(b, d), rs.AddLine(c, d)] # rs.AddObjectsToGroup(lines, group) # from compas.geometry import centroid_points # rs.AddPoint(centroid_points([a, b, c, d])) # # sphere centre #rs.EnableRedraw(True) cells = [] for a, b, c, d in simplices: #print a, b, c, d halffaces = [[a, b, c], [a, b, d], [a, c, d], [b, c, d]] cells.append(halffaces) #halffaces.append([a, b, c]) #halffaces.append([c, b, a]) #halffaces.append([a, b, d])
def add_tets_from_mesh(structure, name, mesh, draw_tets=False, volume=None, layer='Default', acoustic=False, thermal=False): """ Adds tetrahedron elements from a Rhino mesh to the Structure object. Parameters ---------- structure : obj Structure object to update. name : str Name for the element set of tetrahedrons. mesh : obj The Rhino mesh representing the outer surface. draw_tets : bool Draw the generated tetrahedrons. volume : float Maximum volume for each tet. layer : str Layer to draw tetrahedrons if draw_tets=True. acoustic : bool Acoustic properties on or off. thermal : bool Thermal properties on or off. Returns ------- None Nodes and elements are updated in the Structure object. """ rhinomesh = RhinoMesh(mesh) vertices = rhinomesh.get_vertex_coordinates() faces = [face[:3] for face in rhinomesh.get_face_vertices()] basedir = utilities.__file__.split('__init__.py')[0] xfunc = XFunc('tets', basedir=basedir, tmpdir=structure.path) xfunc.funcname = 'functions.tets_from_vertices_faces' try: tets_points, tets_elements = xfunc(vertices=vertices, faces=faces, volume=volume) for point in tets_points: structure.add_node(point) ekeys = [] for element in tets_elements: nodes = [ structure.check_node_exists(tets_points[i]) for i in element ] ekey = structure.add_element(nodes=nodes, type='TetrahedronElement', acoustic=acoustic, thermal=thermal) ekeys.append(ekey) structure.add_set(name=name, type='element', selection=ekeys) if draw_tets: rs.EnableRedraw(False) rs.DeleteObjects(rs.ObjectsByLayer(layer)) rs.CurrentLayer(layer) tet_faces = [[0, 2, 1, 1], [1, 2, 3, 3], [1, 3, 0, 0], [0, 3, 2, 2]] for i, points in enumerate(tets_elements): xyz = [tets_points[j] for j in points] rs.AddMesh(vertices=xyz, face_vertices=tet_faces) rs.EnableRedraw(True) except: print('***** Error using MeshPy or drawing Tets *****')
from __future__ import print_function from __future__ import absolute_import from __future__ import division import compas import compas_rbe from compas.utilities import XFunc from compas_rbe.datastructures import Assembly from compas_rbe.rhino import AssemblyArtist from compas_rbe.rhino import AssemblyHelper assembly_interfaces = XFunc('compas_rbe.interfaces.assembly_interfaces_xfunc', tmpdir=compas_rbe.TEMP) compute_interface_forces = XFunc('compas_rbe.equilibrium.compute_interface_forces_xfunc', tmpdir=compas_rbe.TEMP) # initialize assembly and blocks from json file assembly = Assembly.from_json(compas_rbe.get('simple_stack_4.json')) # identify block interfaces and update block_model data = { 'assembly': assembly.to_data(), 'blocks' : {str(key): assembly.blocks[key].to_data() for key in assembly.blocks}, } result = assembly_interfaces(data, nmax=10, tmax=0.05, amin=0.01, lmin=0.01)
from compas_tna.equilibrium import vertical_from_qind_rhino as vertical_from_qind from compas_tna.rhino import FormArtist __author__ = ['Tom Van Mele', ] __copyright__ = 'Copyright 2016 - Block Research Group, ETH Zurich' __license__ = 'MIT License' __email__ = '*****@*****.**' __all__ = [] f = XFunc('compas_ags.ags.graphstatics.identify_dof_xfunc') def identify_dof(form): return f(form.to_data()) form = FormDiagram.from_obj(compas.get('lines.obj')) form.set_vertices_attributes(('is_fixed', 'is_anchor'), (True, True), keys=form.vertices_on_boundary()) form.set_edges_attribute('is_edge', False, keys=form.edges_on_boundary()) k, m, ind = identify_dof(form)
return self.data # ============================================================================== # Main # ============================================================================== if __name__ == '__main__': import compas from compas.datastructures import Mesh # from compas.plotters import MeshPlotter from compas.utilities import XFunc fd_numpy = XFunc('compas.numerical.fd.fd_numpy.fd_numpy', delete_files=True, serializer='json') mesh = Mesh.from_obj(compas.get('faces.obj')) vertices = mesh.get_vertices_attributes('xyz') edges = list(mesh.edges()) fixed = list([key for key in mesh.vertices() if mesh.vertex_degree(key) == 2]) q = mesh.get_edges_attribute('q', 1.0) loads = mesh.get_vertices_attributes(('px', 'py', 'pz'), (0.0, 0.0, 0.0)) xyz, q, f, l, r = fd_numpy(vertices, edges, fixed, q, loads) print(type(xyz)) for key, attr in mesh.vertices(True): attr['x'] = xyz[key][0]
# ============================================================================== # Main # ============================================================================== if __name__ == '__main__': import random import compas from compas.datastructures import Mesh from compas.utilities import XFunc from compas_rhino.artists import MeshArtist dr = XFunc('compas.numerical.dr_numpy') dva = { 'is_fixed': False, 'x': 0.0, 'y': 0.0, 'z': 0.0, 'px': 0.0, 'py': 0.0, 'pz': 0.0, 'rx': 0.0, 'ry': 0.0, 'rz': 0.0, } dea = {
# Attributes network.update_default_edge_attributes({'E': E, 'A': A, 's0': s0}) # Pins gkey_key = network.gkey_key() pins = [] for i in rs.ObjectsByLayer('Pins'): gkey = geometric_key(rs.PointCoordinates(i)) key = gkey_key[gkey] network.set_vertex_attributes(key, 'B', [[0, 0, 0]]) pins.append(key) # Run XFunc X, f, l, network = XFunc('compas.numerical.drx.drx_numpy.drx_numpy')( structure=network, factor=factor, tol=tol, steps=steps, refresh=10, update=True) # Draw Network artist = NetworkArtist(network=network, layer='Plot') artist.clear_layer() artist.draw_edges()
def plot_data(structure, step, field='um', layer=None, scale=1.0, radius=0.05, cbar=[None, None], iptype='mean', nodal='mean', mode='', colorbar_size=1): """ Plots analysis results on the deformed shape of the Structure. Parameters ---------- structure : obj Structure object. step : str Name of the Step. field : str Field to plot, e.g. 'um', 'sxx', 'sm1'. layer : str Layer name for plotting. scale : float Scale on displacements for the deformed plot. radius : float Radius of the pipe visualisation meshes. cbar : list Minimum and maximum limits on the colorbar. iptype : str 'mean', 'max' or 'min' of an element's integration point data. nodal : str 'mean', 'max' or 'min' for nodal values. mode : int Mode or frequency number to plot, for modal, harmonic or buckling analysis. colorbar_size : float Scale on the size of the colorbar. Returns ------- None Notes ----- - Pipe visualisation of line elements is not based on the element section. """ # Create and clear Rhino layer if not layer: layer = '{0}-{1}'.format(step, field) rs.CurrentLayer(rs.AddLayer(layer)) rs.DeleteObjects(rs.ObjectsByLayer(layer)) rs.EnableRedraw(False) # Node and element data nodes = structure.nodes_xyz() elements = [ structure.elements[i].nodes for i in sorted(structure.elements, key=int) ] nodal_data = structure.results[step]['nodal'] nkeys = sorted(structure.nodes, key=int) ux = [nodal_data['ux{0}'.format(mode)][i] for i in nkeys] uy = [nodal_data['uy{0}'.format(mode)][i] for i in nkeys] uz = [nodal_data['uz{0}'.format(mode)][i] for i in nkeys] try: data = [nodal_data['{0}{1}'.format(field, mode)][i] for i in nkeys] dtype = 'nodal' except (Exception): data = structure.results[step]['element'][field] dtype = 'element' # Postprocess basedir = utilities.__file__.split('__init__.py')[0] xfunc = XFunc('postprocess', basedir=basedir, tmpdir=structure.path) xfunc.funcname = 'functions.postprocess' result = xfunc(nodes, elements, ux, uy, uz, data, dtype, scale, cbar, 255, iptype, nodal) try: toc, U, cnodes, fabs, fscaled, celements, eabs = result print('\n***** Data processed : {0} s *****'.format(toc)) # Plot meshes mesh_faces = [] line_faces = [[0, 4, 5, 1], [1, 5, 6, 2], [2, 6, 7, 3], [3, 7, 4, 0]] block_faces = [[0, 1, 2, 3], [4, 5, 6, 7], [0, 1, 5, 4], [1, 2, 6, 5], [2, 3, 7, 6], [3, 0, 4, 7]] tet_faces = [[0, 2, 1, 1], [1, 2, 3, 3], [1, 3, 0, 0], [0, 3, 2, 2]] for element, nodes in enumerate(elements): n = len(nodes) if n == 2: u, v = nodes sp, ep = U[u], U[v] plane = rs.PlaneFromNormal(sp, subtract_vectors(ep, sp)) xa = plane.XAxis ya = plane.YAxis r = radius xa_pr = scale_vector(xa, +r) xa_mr = scale_vector(xa, -r) ya_pr = scale_vector(ya, +r) ya_mr = scale_vector(ya, -r) pts = [ add_vectors(sp, xa_pr), add_vectors(sp, ya_pr), add_vectors(sp, xa_mr), add_vectors(sp, ya_mr), add_vectors(ep, xa_pr), add_vectors(ep, ya_pr), add_vectors(ep, xa_mr), add_vectors(ep, ya_mr) ] guid = rs.AddMesh(pts, line_faces) if dtype == 'element': col1 = col2 = celements[element] elif dtype == 'nodal': col1 = cnodes[u] col2 = cnodes[v] rs.MeshVertexColors(guid, [col1] * 4 + [col2] * 4) elif n == 3: mesh_faces.append(nodes + [nodes[-1]]) elif n == 4: if structure.elements[element].__name__ in [ 'ShellElement', 'MembraneElement' ]: mesh_faces.append(nodes) else: for face in tet_faces: mesh_faces.append([nodes[i] for i in face]) elif n == 8: for block in block_faces: mesh_faces.append([nodes[i] for i in block]) if mesh_faces: guid = rs.AddMesh(U, mesh_faces) rs.MeshVertexColors(guid, cnodes) # Plot colorbar xr, yr, _ = structure.node_bounds() yran = yr[1] - yr[0] if yr[1] - yr[0] else 1 s = yran * 0.1 * colorbar_size xmin = xr[1] + 3 * s ymin = yr[0] xl = [xmin, xmin + s] yl = [ymin + i * s for i in range(11)] verts = [[xi, yi, 0] for xi in xl for yi in yl] faces = [[i, i + 1, i + 12, i + 11] for i in range(10)] id = rs.AddMesh(verts, faces) y = [i[1] for i in verts] yn = yran * colorbar_size colors = [ colorbar(2 * (yi - ymin - 0.5 * yn) / yn, input='float', type=255) for yi in y ] rs.MeshVertexColors(id, colors) h = 0.6 * s for i in range(5): x0 = xmin + 1.2 * s yu = ymin + (5.8 + i) * s yl = ymin + (3.8 - i) * s vu = float(+max(eabs, fabs) * (i + 1) / 5.) vl = float(-max(eabs, fabs) * (i + 1) / 5.) rs.AddText('{0:.5g}'.format(vu), [x0, yu, 0], height=h) rs.AddText('{0:.5g}'.format(vl), [x0, yl, 0], height=h) rs.AddText('0', [x0, ymin + 4.8 * s, 0], height=h) rs.AddText('Step:{0} Field:{1}'.format(step, field), [xmin, ymin + 12 * s, 0], height=h) if mode != '': freq = str(round(structure.results[step]['frequencies'][mode], 3)) rs.AddText('Mode:{0} Freq:{1}Hz'.format(mode, freq), [xmin, ymin - 1.5 * s, 0], height=h) # Return to Default layer rs.CurrentLayer(rs.AddLayer('Default')) rs.LayerVisible(layer, False) rs.EnableRedraw(True) except: print( '\n***** Error encountered during data processing or plotting *****' )
def plot_voxels(structure, step, field='smises', cbar=[None, None], iptype='mean', nodal='mean', vdx=None, mode='', plot='vtk'): """ Voxel 4D visualisation. Parameters ---------- structure : obj Structure object. step : str Name of the Step. field : str Field to plot, e.g. 'smises'. cbar : list Minimum and maximum limits on the colorbar. iptype : str 'mean', 'max' or 'min' of an element's integration point data. nodal : str 'mean', 'max' or 'min' for nodal values. vdx : float Voxel spacing. mode : int mode or frequency number to plot, in case of modal, harmonic or buckling analysis. plot : str Plot voxels with 'vtk'. Returns ------- None """ # Node and element data nodes = structure.nodes_xyz() elements = [ structure.elements[i].nodes for i in sorted(structure.elements, key=int) ] nodal_data = structure.results[step]['nodal'] nkeys = sorted(structure.nodes, key=int) ux = [nodal_data['ux{0}'.format(mode)][i] for i in nkeys] uy = [nodal_data['uy{0}'.format(mode)][i] for i in nkeys] uz = [nodal_data['uz{0}'.format(mode)][i] for i in nkeys] try: data = [nodal_data[field + str(mode)][key] for key in nkeys] dtype = 'nodal' except (Exception): data = structure.results[step]['element'][field] dtype = 'element' # Postprocess basedir = utilities.__file__.split('__init__.py')[0] xfunc = XFunc('postprocess', basedir=basedir, tmpdir=structure.path) xfunc.funcname = 'functions.postprocess' result = xfunc(nodes, elements, ux, uy, uz, data, dtype, 1, cbar, 255, iptype, nodal) try: toc, U, cnodes, fabs, fscaled, celements, eabs = result print('\n***** Data processed : {0} s *****'.format(toc)) except: print('\n***** Error post-processing *****') try: xfunc = XFunc('voxels', basedir=basedir, tmpdir=structure.path) xfunc.funcname = 'functions.plotvoxels' xfunc(values=fscaled, U=U, vdx=vdx, plot=plot) print('\n***** Voxels finished *****') except: print('\n***** Error plotting voxels *****')
from compas.datastructures import Network from compas.utilities import geometric_key from compas.utilities import XFunc from compas_rhino.artists import NetworkArtist import rhinoscriptsyntax as rs drx_numpy = XFunc('compas.numerical.drx_numpy') # Input s0 = 10**6 E = 10**6 A = 0.005**2 factor = 5.0 tol = 0.1 steps = 10000 # Network guids = rs.ObjectsByLayer('Lines') lines = [[rs.CurveStartPoint(i), rs.CurveEndPoint(i)] for i in guids if rs.IsCurve(i)] network = Network.from_lines(lines) # Attributes network.update_default_edge_attributes({'E': E, 'A': A, 's0': s0}) # Pins