Skip to content

Commit

Permalink
Merge remote-tracking branch 'origin/v0.43' into v4.1_Annika
Browse files Browse the repository at this point in the history
# Conflicts:
#	amworkflow/src/geometries/composite_geometry.py
  • Loading branch information
aradermacher committed Sep 12, 2023
2 parents bba6f4c + 4f4b017 commit ff21815
Show file tree
Hide file tree
Showing 26 changed files with 697 additions and 623 deletions.
8 changes: 4 additions & 4 deletions amworkflow/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -318,10 +318,10 @@ def create_sym_hexagon1_infill(total_len: float, total_wid:float, height:float,
# """
# return cg.create_wall_by_points(pts, th, isclose, height,debug, debug_type, output,interpolate, R)

@staticmethod
class CreateWallByPoints(cg.CreateWallByPoints):
def __init__(self, pts: list, th: float, height: float):
super().__init__(pts,th,height)
# @staticmethod
class CreateWallByPoints(cg.CreateWallByPointsUpdate):
def __init__(self, pts: list, th: float, height: float, is_close:bool = True):
super().__init__(pts,th,height,is_close)

@staticmethod
def get_face_center_of_mass(face: TopoDS_Face, gp_pnt: bool = False) -> tuple | gp_Pnt:
Expand Down
715 changes: 130 additions & 585 deletions amworkflow/src/geometries/composite_geometry.py

Large diffs are not rendered by default.

1 change: 0 additions & 1 deletion amworkflow/src/geometries/mesher.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,6 @@ def mesher(item: TopoDS_Shape,
model.add(model_name)
v = get_geom_pointer(model, geo)
model.occ.synchronize()
gmsh.fltk.run()
for layer in v:
model.add_physical_group(3,[layer[1]], name=f"layer{layer[1]}")
phy_gp = model.getPhysicalGroups()
Expand Down
2 changes: 1 addition & 1 deletion amworkflow/src/geometries/operator.py
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ def split(item: TopoDS_Shape,
plan_len = 1.2 * max(abs(xmin - xmax), abs(ymin - ymax))
z = zmax - zmin
if nz != None:
z_list = np.linspace(zmin, z, nz)
z_list = np.linspace(zmin, z, nz+1)
if layer_thickness != None:
z_list = np.arange(zmin, z, layer_thickness)
z_list = np.concatenate((z_list,np.array([z])))
Expand Down
28 changes: 27 additions & 1 deletion amworkflow/src/geometries/property.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ def shortest_distance_point_line(line, p):
pt1, pt2 = line
s = pt2 - pt1
lmbda = (p - pt1).dot(s) / s.dot(s)
pt_compute = pt1 + lmbda * s
if lmbda < 1 and lmbda > 0:
pt_compute = pt1 + lmbda * s
distance = np.linalg.norm(pt_compute - p)
return lmbda, distance
elif lmbda <= 0:
Expand All @@ -144,6 +144,20 @@ def shortest_distance_line_line(line1, line2):
s2 = pt22 - pt21
s1square = np.dot(s1, s1)
s2square = np.dot(s2, s2)
term1 = s1square * s2square - (np.dot(s1, s2)**2)
term2 = s1square * s2square - (np.dot(s1, s2)**2)
if np.isclose(term1,0) or np.isclose(term2, 0):
if np.isclose(s1[0],0):
s_p = np.array([-s1[1],s1[0],0])
else:
s_p = np.array([s1[1],-s1[0],0])
l1 = np.random.randint(1,4) * 0.1
l2 = np.random.randint(6,9) * 0.1
pt1i = s1 * l1 + pt11
pt2i = s2 * l2 + pt21
si = pt2i - pt1i
dist = np.linalg.norm(si * ( si * s_p) / (np.linalg.norm(si) * np.linalg.norm(s_p)))
return dist, np.array([pt1i,pt2i])
lmbda1 = (np.dot(s1,s2) * np.dot(pt11 - pt21,s2) - s2square * np.dot(pt11 - pt21, s1)) / (s1square * s2square - (np.dot(s1, s2)**2))
lmbda2 = -(np.dot(s1,s2) * np.dot(pt11 - pt21,s1) - s1square * np.dot(pt11 - pt21, s2)) / (s1square * s2square - (np.dot(s1, s2)**2))
condition1 = lmbda1 >= 1
Expand Down Expand Up @@ -234,3 +248,15 @@ def check_overlap(line1: np.ndarray, line2: np.ndarray) -> np.ndarray:
indicator[1] = 1
return np.where(indicator == 1)[0], np.unique(pnt_list[np.where(indicator == 1)[0]], axis=0)

def p_get_face_area(points: list):
pts = np.array(points).T
x = pts[0]
y = pts[1]
result = 0
for i in range(len(x)):
if i < len(x) - 1:
t = x[i]*y[i+1] - x[i+1]*y[i]
else:
t = x[i]*y[0] - x[0]*y[i]
result += t
return np.abs(result) * 0.5
81 changes: 75 additions & 6 deletions amworkflow/src/geometries/simple_geometry.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,15 @@
from OCCUtils.Construct import make_face
from amworkflow.src.geometries.builder import geometry_builder, sewer
from amworkflow.src.geometries.property import check_overlap, check_parallel_line_line, shortest_distance_line_line

from amworkflow.src.utils.system import threads_count
from OCC.Core.GC import GC_MakeArcOfCircle
import math as m
from OCC.Core.BRepOffsetAPI import BRepOffsetAPI_MakeOffsetShape
from OCCUtils.Topology import Topo
import numpy as np

import multiprocessing
from itertools import repeat
from amworkflow.src.utils.meter import timer

def create_box(length: float,
width: float,
Expand Down Expand Up @@ -373,6 +375,7 @@ def pnt(self, pt_coord) -> np.ndarray:

def new_pnt(self, pt_coords: list):
pt_coords = self.pnt(pt_coords)

for i, v in self.pts_index.items():
if self.pnt_overlap(v, pt_coords):
return False, i
Expand Down Expand Up @@ -423,12 +426,15 @@ def update_digraph(self, start_node: int, end_node: int, insert_node: int = None
self.pts_digraph.update({start_node: [end_node]})
else:
raise Exception("No edge found for insertion option.")



class Segments(Pnt):
def __init__(self, *coords: list):
super().__init__(*coords)
self.segments_index = {}
self.modify_edge_list = {}
self.virtual_vector = {}
self.virtual_pnt = {}
self.find_overlap_node_on_edge()
self.modify_edge()

Expand Down Expand Up @@ -467,13 +473,65 @@ def modify_edge(self):
if i == 0:
continue
self.update_digraph(pts_list[i-1],nd,build_new_edge=False)
if (i != 1) and (i != len(pts_list) - 1):
if (pts_list[i-1] in self.virtual_pnt) and nd in (self.virtual_pnt):
self.virtual_vector.update({(pts_list[i-1],nd): True})

def check_self_edge(self, line: np.ndarray) -> bool:
if self.pnt_overlap(line[0],line[1]):
return True
else:
return False


def overlap_node_on_edge_finder(self,i,j):
v = self.init_pts_sequence[i]
vv = self.init_pts_sequence[j]
print(i,j)
lin1 = self.get_segment(v[0], v[1])
lin2 = self.get_segment(vv[0], vv[1])
self_edge = (self.check_self_edge(lin1) or self.check_self_edge(lin2))
if not self_edge:
parallel, colinear = check_parallel_line_line(lin1, lin2)
# if v == [13,14]:
# print("line:",(v,vv), parallel, colinear)
if parallel:
if colinear:
index, coords = check_overlap(lin1, lin2)
if len(index) < 4:
for ind in index:
if ind in [0,1]:
self.add_pending_change(tuple(vv),v[ind])
else:
self.add_pending_change(tuple(v),vv[ind])
else:
distance = shortest_distance_line_line(lin1, lin2)
intersect = np.isclose(distance[0],0)
new,pt = self.new_pnt(distance[1][0])
if intersect and new:
pnt_id = self.register_pnt(distance[1][0])
self.add_pending_change(tuple(v),pnt_id)
self.add_pending_change(tuple(vv), pnt_id)


def arg_generator(self):
iter_range = range(len(self.init_pts_sequence))
visited = {}
for i in iter_range:
for j in iter_range:
if i == j:
continue
if i == j + 1:
continue
if j == i - 1:
continue
if (i,j) in visited or (j,i) in visited:
continue
args = (self,i,j)
print(args)
yield args
visited.update({(i,j): True, (j,i): True})


def find_overlap_node_on_edge(self):
visited = {}
for i,v in enumerate(self.init_pts_sequence):
Expand All @@ -482,7 +540,9 @@ def find_overlap_node_on_edge(self):
continue
if i == j + 1:
continue
if j == i - 1:
if j == i + 1:
continue
if i == len(self.init_pts_sequence) * 2 -1 - i:
continue
if (i,j) in visited or (j,i) in visited:
continue
Expand All @@ -502,13 +562,22 @@ def find_overlap_node_on_edge(self):
if ind in [0,1]:
self.add_pending_change(tuple(vv),v[ind])
else:
self.add_pending_change(tuple(v),vv[ind])
self.add_pending_change(tuple(v),vv[ind-2])
else:
distance = shortest_distance_line_line(lin1, lin2)
intersect = np.isclose(distance[0],0)
new,pt = self.new_pnt(distance[1][0])
if intersect and new:
pnt_id = self.register_pnt(distance[1][0])
self.virtual_pnt.update({pnt_id: True})
self.add_pending_change(tuple(v),pnt_id)
self.add_pending_change(tuple(vv), pnt_id)
visited.update({(i,j): True, (j,i): True})

# def find_overlap_node_on_edge(self):
# with multiprocessing.Pool(processes=threads_count) as pool:
# args = self.arg_generator()
# # b = zip(repeat(self),args)
# # print(tuple(b))
# # pool.map(Segments.overlap_node_on_edge_finder,zip(repeat(self),args))
# pool.map(Segments.overlap_node_on_edge_finder,args)
11 changes: 11 additions & 0 deletions amworkflow/src/utils/meter.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
import time

def timer(func):
def wrapper(*args, **kwargs):
start_time = time.time()
result = func(*args, **kwargs)
end_time = time.time()
elapsed_time = end_time - start_time
print(f"{func.__name__} took {elapsed_time:.6f} seconds to run")
return result
return wrapper
2 changes: 2 additions & 0 deletions amworkflow/src/utils/system.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
import psutil
threads_count = psutil.cpu_count()
61 changes: 61 additions & 0 deletions amworkflow/src/utils/visualizer.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
from amworkflow.src.constants.exceptions import GmshUseBeforeInitializedException
import networkx as nx
import matplotlib.pyplot as plt
from amworkflow.src.geometries.property import shortest_distance_line_line
import numpy as np

def mesh_visualizer():
try:
Expand All @@ -25,4 +27,63 @@ def plot_digraph(dataset: dict) -> None:
# Draw the nodes and edges
nx.draw(G, pos=layout, with_labels=True, node_color='skyblue', font_size=10, node_size=500)
plt.title("NetworkX Graph Visualization")
plt.show()

def plot_intersect(x11 = 0, x12 = 0, y11 = 0, y12 = 0, x21 = 0, x22 = 0, y21 = 0, y22 = 0,segment1 = None, segment2 = None):
if (segment1 is None) and (segment2 is None):
# Coordinates for the two segments
segment1_x = [x11, x12]
segment1_y = [y11, y12]

segment2_x = [x21, x22]
segment2_y = [y21, y22]
intersect = shortest_distance_line_line(np.array([[x11, y11,0], [x12, y12,0]]), np.array([[x21, y21,0], [x22, y22,0]]))[1]
print(shortest_distance_line_line(np.array([[x11, y11,0], [x12, y12,0]]), np.array([[x21, y21,0], [x22, y22,0]]))[0])
else:
segment1_x = segment1.T[0]
segment1_y = segment1.T[1]
segment2_x = segment2.T[0]
segment2_y = segment2.T[1]
intersect = shortest_distance_line_line(segment1, segment2)[1]



# Coordinates for the single point

point_x_1 = [intersect[0].T[0]]
point_y_1 = [intersect[0].T[1]]
point_x_2 = [intersect[1].T[0]]
point_y_2 = [intersect[1].T[1]]

# Create a figure and axis
fig, ax = plt.subplots()

# Plot the two segments
ax.plot(segment1_x, segment1_y, color='blue', linestyle='-', linewidth=2, label='Segment 1')
ax.plot(segment2_x, segment2_y, color='green', linestyle='-', linewidth=2, label='Segment 2')

# Plot the single point
ax.plot(point_x_1, point_y_1, marker='o', markersize=8, color='red', label='Point1')
ax.plot(point_x_2, point_y_2, marker='o', markersize=8, color='red', label='Point2')

# Add labels for the point and segments
ax.text(2, 3, f'Point ({intersect[0]}, {intersect[1]})', fontsize=12, ha='right')
ax.text(1, 2, 'Segment 1', fontsize=12, ha='right')
ax.text(6, 3, 'Segment 2', fontsize=12, ha='right')

# Add a legend
ax.legend()

# Set axis limits for better visualization
ax.set_xlim(0, 7)
ax.set_ylim(0, 6)

# Set axis labels
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')

# Set plot title
ax.set_title('Two Segments and One Point')
plt.tight_layout()
# Display the plot
plt.show()
1 change: 1 addition & 0 deletions environment.yml
Original file line number Diff line number Diff line change
Expand Up @@ -399,6 +399,7 @@ dependencies:
- mdit-py-plugins==0.4.0
- mistune==3.0.1
- nbclassic==1.0.0
- networkx
- nbclient==0.8.0
- nbconvert==7.6.0
- nbformat==5.9.0
Expand Down
22 changes: 22 additions & 0 deletions environment_clean.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
name: amworkflow_clean
channels:
- conda-forge
- defaults
dependencies:
- pythonocc-core=7.7.0
- python=3.10
- pandas
- sqlite
- numpy
- fenics-dolfinx
- mpich
- pyvista
- pip
- pip:
- gmsh==4.11.1
- networkx
- pyqt5
- sphinx
- sqlalchemy
- ruamel-yaml
- doit
Loading

0 comments on commit ff21815

Please sign in to comment.