src.acoustools.Mesh.Features

  1from acoustools.Utilities import device, DTYPE
  2import acoustools.Constants as Constants
  3
  4import torch
  5import matplotlib.pyplot as plt
  6import numpy as np
  7
  8from torch import Tensor
  9from vedo import Mesh
 10
 11
 12def get_plane(scatterer: Mesh, origin:tuple[int]=(0,0,0), normal:tuple[int]=(1,0,0)) -> Mesh:
 13    '''
 14    Get intersection of a scatterer and a plane\n
 15    :param scatterer: The scatterer to intersect
 16    :param origin: A point on the plane as a tuple `(x,y,z)`. Default `(0,0,0)`
 17    :param normal: The normal to the plane at `point` as a tuple (x,y,z). Default `(1,0,0)`
 18    :return: new `Mesh` Containing the intersection of the plane and the scatterer
 19    '''
 20    intersection = scatterer.clone().intersect_with_plane(origin,normal)
 21    intersection.filename = scatterer.filename + "plane" + str(origin)+str(normal)
 22    return intersection
 23
 24def get_lines_from_plane(scatterer:Mesh, origin:tuple[int]=(0,0,0), normal:tuple[int]=(1,0,0)) -> list[int]:
 25    '''
 26    Gets the edges on a plane from the intersection between a scatterer and the plane\n
 27    :param scatterer: The scatterer to intersect
 28    :param origin: A point on the plane as a tuple `(x,y,z)`. Default `(0,0,0)`
 29    :param normal: The normal to the plane at `point` as a tuple (x,y,z). Default `(1,0,0)`
 30    :return: a list of edges in the plane 
 31    '''
 32
 33    mask = [0,0,0]
 34    for i in range(3):
 35        mask[i] =not normal[i]
 36    mask = np.array(mask)
 37
 38    intersection = get_plane(scatterer, origin, normal)
 39    verticies = intersection.vertices
 40    lines = intersection.lines
 41
 42    connections = []
 43
 44    for i in range(len(lines)):
 45        connections.append([verticies[lines[i][0]][mask],verticies[lines[i][1]][mask]])
 46
 47    return connections
 48
 49def plot_plane(connections:list[int]) -> None:
 50    '''
 51    Plot a set of edges assuming they are co-planar\n
 52    :param connections: list of connections to plot
 53    '''
 54    
 55    for con in connections:
 56        xs = [con[0][0], con[1][0]]
 57        ys = [con[0][1], con[1][1]]
 58        plt.plot(xs,ys,color = "blue")
 59
 60    plt.xlim((-0.06,0.06))
 61    plt.ylim((-0.06,0.06))
 62    plt.show()
 63
 64def get_normals_as_points(*scatterers:Mesh, permute_to_points:bool=True) -> Tensor:
 65    '''
 66    Returns the normal vectors to the surface of a scatterer as a `torch` `Tensor` as acoustools points\n
 67    :param scatterers: The scatterer to use
 68    :param permute_to_points: If true will permute the order of coordinates to agree with what acoustools expects.
 69    :return: normals
 70    '''
 71    norm_list = []
 72    for scatterer in scatterers:
 73        scatterer.compute_normals()
 74        norm =  torch.tensor(scatterer.cell_normals).to(device)
 75
 76        if permute_to_points:
 77            norm = torch.permute(norm,(1,0))
 78        
 79        norm_list.append(norm.to(DTYPE))
 80    
 81    return torch.stack(norm_list)
 82
 83def get_centre_of_mass_as_points(*scatterers:Mesh, permute_to_points:bool=True) ->Tensor:
 84    '''
 85    Returns the centre of mass(es) of a scatterer(s) as a `torch` `Tensor` as acoustools points\n
 86    :param scatterers: The scatterer(s) to use
 87    :param permute_to_points: If true will permute the order of coordinates to agree with what acoustools expects.
 88    :return: centre of mass(es)
 89    '''
 90    centres_list = []
 91    for scatterer in scatterers:
 92        centre_of_mass =  torch.tensor(scatterer.center_of_mass()).to(DTYPE).to(device)
 93
 94        if permute_to_points:
 95            centre_of_mass = torch.unsqueeze(centre_of_mass,1)
 96        
 97        centres_list.append(centre_of_mass.to(DTYPE))
 98    
 99    return torch.real(torch.stack(centres_list))
100
101
102def get_centres_as_points(*scatterers:Mesh, permute_to_points:bool=True, add_normals:bool=False, normal_scale:float=0.001) ->Tensor:
103    '''
104    Returns the centre of scatterer faces as a `torch` `Tensor` as acoustools points\n
105    :param scatterers: The scatterer to use
106    :param permute_to_points: If `True` will permute the order of coordinates to agree with what acoustools expects.
107    :return: centres
108    '''
109    centre_list = []
110    for scatterer in scatterers:
111        centres =  torch.tensor(scatterer.cell_centers().points).to(DTYPE).to(device)
112
113        if permute_to_points:
114            centres = torch.permute(centres,(1,0)).unsqueeze_(0)
115        
116        if add_normals:
117            norms= get_normals_as_points(scatterer)
118            centres += norms.real * normal_scale
119        
120        centre_list.append(centres)
121    centres = torch.cat(centre_list,dim=0)
122    return centres
123
124def get_verticies_as_points(*scatterers:Mesh):
125    '''
126    Gets the verticies of a mesh as a Tensor of AcousTools (B,3,N) points \n
127    :param Mesh: Mesh to use
128    :returns verticies: verticies as points
129    '''
130   
131    vert_list = []
132    for scatterer in scatterers:
133        vert =  torch.tensor(scatterer.vertices).to(DTYPE).to(device)
134        vert_list.append(vert)
135
136    verts = torch.cat(vert_list,dim=0).unsqueeze(0).permute(0,2,1)
137    return verts
138
139def get_cell_verticies(*scatterers:Mesh):
140    '''
141    Gets a tensor of (B,3,M,3) - batch x (xyz) x Faces x (vertex) \n
142    :param Mesh: Mesh to use
143    :returns verticies: verticies
144    '''
145    verts = get_verticies_as_points(*scatterers)
146    vert_list = []
147    for scatterer in scatterers:
148        cells = torch.tensor(scatterer.cells)
149        N = cells.shape[0]
150        cell_indexes = cells.flatten()
151        cell_verts = torch.index_select(verts, 2, cell_indexes)
152        cell_verts=cell_verts.reshape(1,3,N,3)
153
154
155        vert_list.append(cell_verts)
156    verts = torch.cat(vert_list,dim=0)
157    return verts
158
159
160
161def get_barycentric_points(*scatterers:Mesh, N=7, sum=True):
162    '''
163    @private
164    '''
165    
166
167    if N != 7: raise ValueError("Only N=7 is supported") #Allow for N as a parameter incase it it implemented in future
168
169    cell_verts = get_cell_verticies(*scatterers)
170
171    DUNAVANT_7 = torch.tensor([
172    [1/3, 1/3, 1/3, 0.225],
173    [0.0597158717, 0.4701420641, 0.4701420641, 0.1323941527],
174    [0.4701420641, 0.0597158717, 0.4701420641, 0.1323941527],
175    [0.4701420641, 0.4701420641, 0.0597158717, 0.1323941527],
176    [0.7974269853, 0.1012865073, 0.1012865073, 0.1259391805],
177    [0.1012865073, 0.7974269853, 0.1012865073, 0.1259391805],
178    [0.1012865073, 0.1012865073, 0.7974269853, 0.1259391805],
179    ])
180    DUNAVANT_7_abg = DUNAVANT_7[:,:3].permute(1,0).unsqueeze(0).unsqueeze(0).unsqueeze(0)
181
182
183    DUNAVANT_7_W = DUNAVANT_7[:,3]
184
185    cell_verts = cell_verts.unsqueeze(-1)
186    barycentric_verts = cell_verts * DUNAVANT_7_abg
187    if sum: barycentric_verts = barycentric_verts.sum(dim=3)
188
189    return barycentric_verts, DUNAVANT_7_W
190
191    
192
193def get_areas(*scatterers: Mesh) -> Tensor:
194    '''
195    Returns the areas of faces of any number of scatterers\n
196    :param scatterers: The scatterers to use.
197    :return: areas
198    '''
199    area_list = []
200    for scatterer in scatterers:
201        scatterer.compute_cell_size()
202        area_list.append(torch.Tensor(scatterer.celldata["Area"]).to(device))
203    
204    return torch.stack(area_list)
205
206def get_weight(scatterer:Mesh, density:float=Constants.p_p, g:float=9.81) -> float:
207    '''
208    Get the weight of a scatterer\\
209    :param scatterer: The scatterer to use\\
210    :param density: The density to use. Default density for EPS\\
211    :param g: value for g to use. Default 9.81\\
212    :return: weight
213    '''
214    mass = scatterer.volume() * density
215    return g * mass
216
217
218
219
220
221
222def get_edge_data(scatterer:Mesh, wavelength:float=Constants.wavelength, print_output:bool=True, break_down_average:bool=False) -> None|tuple[float]:
223    '''
224    Get the maximum, minimum and average size of edges in a mesh. Optionally prints or returns the result.\n
225    :param scatterer: Mesh of interest
226    :param wavelength: Wavenelgth size for printing results as multiple of some wavelength
227    :param print_output: If True, prints results else returns values
228    :break_down_average: If True will also return (distance_sum, N)
229    :return: None if `print_outputs` is `True` else returns `(max_distance, min_distance, average_distance)` and optionally  (distance_sum, N)
230
231    '''
232    points = scatterer.vertices
233
234    distance_sum = 0
235    N = 0
236
237    max_distance = 0
238    min_distance = 100000000
239
240
241    for (start,end) in scatterer.edges:
242        start_point = points[start]
243        end_point = points[end]
244        sqvec = torch.Tensor((start_point-end_point)**2)
245        # print(sqvec, torch.sum(sqvec)**0.5)
246        distance = torch.sum(sqvec)**0.5
247        distance_sum += distance
248        N += 1
249        if distance < min_distance:
250            min_distance = distance
251        if distance > max_distance:
252            max_distance = distance
253
254    average_distance = distance_sum/N
255
256    if print_output:
257        print('Max Distance', max_distance.item(),'=' ,max_distance.item()/wavelength, 'lambda')
258        print('Min Distance', min_distance.item(),'=', min_distance.item()/wavelength, 'lambda')
259        print('Ave Distance', average_distance.item(),'=', average_distance.item()/wavelength, 'lambda')
260    else:
261        if break_down_average:
262            return (max_distance, min_distance, average_distance), (distance_sum, N)
263        else:
264            return (max_distance, min_distance, average_distance)
265
266
267def get_volume(scatterer:Mesh):
268    '''
269    Returns the volume of a mesh
270    '''
271    return scatterer.volume()
272
273def get_diameter(scatterer:Mesh):
274    x1,x2,y1,y2,z1,z2 = scatterer.bounds()
275    diameter_sphere = torch.norm(torch.Tensor([x2,]) - torch.Tensor([x1,]), p=2)
276    return diameter_sphere
def get_plane( scatterer: vedo.mesh.core.Mesh, origin: tuple[int] = (0, 0, 0), normal: tuple[int] = (1, 0, 0)) -> vedo.mesh.core.Mesh:
13def get_plane(scatterer: Mesh, origin:tuple[int]=(0,0,0), normal:tuple[int]=(1,0,0)) -> Mesh:
14    '''
15    Get intersection of a scatterer and a plane\n
16    :param scatterer: The scatterer to intersect
17    :param origin: A point on the plane as a tuple `(x,y,z)`. Default `(0,0,0)`
18    :param normal: The normal to the plane at `point` as a tuple (x,y,z). Default `(1,0,0)`
19    :return: new `Mesh` Containing the intersection of the plane and the scatterer
20    '''
21    intersection = scatterer.clone().intersect_with_plane(origin,normal)
22    intersection.filename = scatterer.filename + "plane" + str(origin)+str(normal)
23    return intersection

Get intersection of a scatterer and a plane

Parameters
  • scatterer: The scatterer to intersect
  • origin: A point on the plane as a tuple (x,y,z). Default (0,0,0)
  • normal: The normal to the plane at point as a tuple (x,y,z). Default (1,0,0)
Returns

new Mesh Containing the intersection of the plane and the scatterer

def get_lines_from_plane( scatterer: vedo.mesh.core.Mesh, origin: tuple[int] = (0, 0, 0), normal: tuple[int] = (1, 0, 0)) -> list[int]:
25def get_lines_from_plane(scatterer:Mesh, origin:tuple[int]=(0,0,0), normal:tuple[int]=(1,0,0)) -> list[int]:
26    '''
27    Gets the edges on a plane from the intersection between a scatterer and the plane\n
28    :param scatterer: The scatterer to intersect
29    :param origin: A point on the plane as a tuple `(x,y,z)`. Default `(0,0,0)`
30    :param normal: The normal to the plane at `point` as a tuple (x,y,z). Default `(1,0,0)`
31    :return: a list of edges in the plane 
32    '''
33
34    mask = [0,0,0]
35    for i in range(3):
36        mask[i] =not normal[i]
37    mask = np.array(mask)
38
39    intersection = get_plane(scatterer, origin, normal)
40    verticies = intersection.vertices
41    lines = intersection.lines
42
43    connections = []
44
45    for i in range(len(lines)):
46        connections.append([verticies[lines[i][0]][mask],verticies[lines[i][1]][mask]])
47
48    return connections

Gets the edges on a plane from the intersection between a scatterer and the plane

Parameters
  • scatterer: The scatterer to intersect
  • origin: A point on the plane as a tuple (x,y,z). Default (0,0,0)
  • normal: The normal to the plane at point as a tuple (x,y,z). Default (1,0,0)
Returns

a list of edges in the plane

def plot_plane(connections: list[int]) -> None:
50def plot_plane(connections:list[int]) -> None:
51    '''
52    Plot a set of edges assuming they are co-planar\n
53    :param connections: list of connections to plot
54    '''
55    
56    for con in connections:
57        xs = [con[0][0], con[1][0]]
58        ys = [con[0][1], con[1][1]]
59        plt.plot(xs,ys,color = "blue")
60
61    plt.xlim((-0.06,0.06))
62    plt.ylim((-0.06,0.06))
63    plt.show()

Plot a set of edges assuming they are co-planar

Parameters
  • connections: list of connections to plot
def get_normals_as_points( *scatterers: vedo.mesh.core.Mesh, permute_to_points: bool = True) -> torch.Tensor:
65def get_normals_as_points(*scatterers:Mesh, permute_to_points:bool=True) -> Tensor:
66    '''
67    Returns the normal vectors to the surface of a scatterer as a `torch` `Tensor` as acoustools points\n
68    :param scatterers: The scatterer to use
69    :param permute_to_points: If true will permute the order of coordinates to agree with what acoustools expects.
70    :return: normals
71    '''
72    norm_list = []
73    for scatterer in scatterers:
74        scatterer.compute_normals()
75        norm =  torch.tensor(scatterer.cell_normals).to(device)
76
77        if permute_to_points:
78            norm = torch.permute(norm,(1,0))
79        
80        norm_list.append(norm.to(DTYPE))
81    
82    return torch.stack(norm_list)

Returns the normal vectors to the surface of a scatterer as a torch Tensor as acoustools points

Parameters
  • scatterers: The scatterer to use
  • permute_to_points: If true will permute the order of coordinates to agree with what acoustools expects.
Returns

normals

def get_centre_of_mass_as_points( *scatterers: vedo.mesh.core.Mesh, permute_to_points: bool = True) -> torch.Tensor:
 84def get_centre_of_mass_as_points(*scatterers:Mesh, permute_to_points:bool=True) ->Tensor:
 85    '''
 86    Returns the centre of mass(es) of a scatterer(s) as a `torch` `Tensor` as acoustools points\n
 87    :param scatterers: The scatterer(s) to use
 88    :param permute_to_points: If true will permute the order of coordinates to agree with what acoustools expects.
 89    :return: centre of mass(es)
 90    '''
 91    centres_list = []
 92    for scatterer in scatterers:
 93        centre_of_mass =  torch.tensor(scatterer.center_of_mass()).to(DTYPE).to(device)
 94
 95        if permute_to_points:
 96            centre_of_mass = torch.unsqueeze(centre_of_mass,1)
 97        
 98        centres_list.append(centre_of_mass.to(DTYPE))
 99    
100    return torch.real(torch.stack(centres_list))

Returns the centre of mass(es) of a scatterer(s) as a torch Tensor as acoustools points

Parameters
  • scatterers: The scatterer(s) to use
  • permute_to_points: If true will permute the order of coordinates to agree with what acoustools expects.
Returns

centre of mass(es)

def get_centres_as_points( *scatterers: vedo.mesh.core.Mesh, permute_to_points: bool = True, add_normals: bool = False, normal_scale: float = 0.001) -> torch.Tensor:
103def get_centres_as_points(*scatterers:Mesh, permute_to_points:bool=True, add_normals:bool=False, normal_scale:float=0.001) ->Tensor:
104    '''
105    Returns the centre of scatterer faces as a `torch` `Tensor` as acoustools points\n
106    :param scatterers: The scatterer to use
107    :param permute_to_points: If `True` will permute the order of coordinates to agree with what acoustools expects.
108    :return: centres
109    '''
110    centre_list = []
111    for scatterer in scatterers:
112        centres =  torch.tensor(scatterer.cell_centers().points).to(DTYPE).to(device)
113
114        if permute_to_points:
115            centres = torch.permute(centres,(1,0)).unsqueeze_(0)
116        
117        if add_normals:
118            norms= get_normals_as_points(scatterer)
119            centres += norms.real * normal_scale
120        
121        centre_list.append(centres)
122    centres = torch.cat(centre_list,dim=0)
123    return centres

Returns the centre of scatterer faces as a torch Tensor as acoustools points

Parameters
  • scatterers: The scatterer to use
  • permute_to_points: If True will permute the order of coordinates to agree with what acoustools expects.
Returns

centres

def get_verticies_as_points(*scatterers: vedo.mesh.core.Mesh):
125def get_verticies_as_points(*scatterers:Mesh):
126    '''
127    Gets the verticies of a mesh as a Tensor of AcousTools (B,3,N) points \n
128    :param Mesh: Mesh to use
129    :returns verticies: verticies as points
130    '''
131   
132    vert_list = []
133    for scatterer in scatterers:
134        vert =  torch.tensor(scatterer.vertices).to(DTYPE).to(device)
135        vert_list.append(vert)
136
137    verts = torch.cat(vert_list,dim=0).unsqueeze(0).permute(0,2,1)
138    return verts

Gets the verticies of a mesh as a Tensor of AcousTools (B,3,N) points

Parameters
  • Mesh: Mesh to use :returns verticies: verticies as points
def get_cell_verticies(*scatterers: vedo.mesh.core.Mesh):
140def get_cell_verticies(*scatterers:Mesh):
141    '''
142    Gets a tensor of (B,3,M,3) - batch x (xyz) x Faces x (vertex) \n
143    :param Mesh: Mesh to use
144    :returns verticies: verticies
145    '''
146    verts = get_verticies_as_points(*scatterers)
147    vert_list = []
148    for scatterer in scatterers:
149        cells = torch.tensor(scatterer.cells)
150        N = cells.shape[0]
151        cell_indexes = cells.flatten()
152        cell_verts = torch.index_select(verts, 2, cell_indexes)
153        cell_verts=cell_verts.reshape(1,3,N,3)
154
155
156        vert_list.append(cell_verts)
157    verts = torch.cat(vert_list,dim=0)
158    return verts

Gets a tensor of (B,3,M,3) - batch x (xyz) x Faces x (vertex)

Parameters
  • Mesh: Mesh to use :returns verticies: verticies
def get_areas(*scatterers: vedo.mesh.core.Mesh) -> torch.Tensor:
194def get_areas(*scatterers: Mesh) -> Tensor:
195    '''
196    Returns the areas of faces of any number of scatterers\n
197    :param scatterers: The scatterers to use.
198    :return: areas
199    '''
200    area_list = []
201    for scatterer in scatterers:
202        scatterer.compute_cell_size()
203        area_list.append(torch.Tensor(scatterer.celldata["Area"]).to(device))
204    
205    return torch.stack(area_list)

Returns the areas of faces of any number of scatterers

Parameters
  • scatterers: The scatterers to use.
Returns

areas

def get_weight( scatterer: vedo.mesh.core.Mesh, density: float = 29.36, g: float = 9.81) -> float:
207def get_weight(scatterer:Mesh, density:float=Constants.p_p, g:float=9.81) -> float:
208    '''
209    Get the weight of a scatterer\\
210    :param scatterer: The scatterer to use\\
211    :param density: The density to use. Default density for EPS\\
212    :param g: value for g to use. Default 9.81\\
213    :return: weight
214    '''
215    mass = scatterer.volume() * density
216    return g * mass

Get the weight of a scatterer\

Parameters
  • scatterer: The scatterer to use\
  • density: The density to use. Default density for EPS\
  • g: value for g to use. Default 9.81\
Returns

weight

def get_edge_data( scatterer: vedo.mesh.core.Mesh, wavelength: float = 0.008575, print_output: bool = True, break_down_average: bool = False) -> None | tuple[float]:
223def get_edge_data(scatterer:Mesh, wavelength:float=Constants.wavelength, print_output:bool=True, break_down_average:bool=False) -> None|tuple[float]:
224    '''
225    Get the maximum, minimum and average size of edges in a mesh. Optionally prints or returns the result.\n
226    :param scatterer: Mesh of interest
227    :param wavelength: Wavenelgth size for printing results as multiple of some wavelength
228    :param print_output: If True, prints results else returns values
229    :break_down_average: If True will also return (distance_sum, N)
230    :return: None if `print_outputs` is `True` else returns `(max_distance, min_distance, average_distance)` and optionally  (distance_sum, N)
231
232    '''
233    points = scatterer.vertices
234
235    distance_sum = 0
236    N = 0
237
238    max_distance = 0
239    min_distance = 100000000
240
241
242    for (start,end) in scatterer.edges:
243        start_point = points[start]
244        end_point = points[end]
245        sqvec = torch.Tensor((start_point-end_point)**2)
246        # print(sqvec, torch.sum(sqvec)**0.5)
247        distance = torch.sum(sqvec)**0.5
248        distance_sum += distance
249        N += 1
250        if distance < min_distance:
251            min_distance = distance
252        if distance > max_distance:
253            max_distance = distance
254
255    average_distance = distance_sum/N
256
257    if print_output:
258        print('Max Distance', max_distance.item(),'=' ,max_distance.item()/wavelength, 'lambda')
259        print('Min Distance', min_distance.item(),'=', min_distance.item()/wavelength, 'lambda')
260        print('Ave Distance', average_distance.item(),'=', average_distance.item()/wavelength, 'lambda')
261    else:
262        if break_down_average:
263            return (max_distance, min_distance, average_distance), (distance_sum, N)
264        else:
265            return (max_distance, min_distance, average_distance)

Get the maximum, minimum and average size of edges in a mesh. Optionally prints or returns the result.

Parameters
  • scatterer: Mesh of interest
  • wavelength: Wavenelgth size for printing results as multiple of some wavelength
  • print_output: If True, prints results else returns values :break_down_average: If True will also return (distance_sum, N)
Returns

None if print_outputs is True else returns (max_distance, min_distance, average_distance) and optionally (distance_sum, N)

def get_volume(scatterer: vedo.mesh.core.Mesh):
268def get_volume(scatterer:Mesh):
269    '''
270    Returns the volume of a mesh
271    '''
272    return scatterer.volume()

Returns the volume of a mesh

def get_diameter(scatterer: vedo.mesh.core.Mesh):
274def get_diameter(scatterer:Mesh):
275    x1,x2,y1,y2,z1,z2 = scatterer.bounds()
276    diameter_sphere = torch.norm(torch.Tensor([x2,]) - torch.Tensor([x1,]), p=2)
277    return diameter_sphere