diff --git a/README.md b/README.md index cdacc7ae..595ac3ba 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,7 @@ [![CI testing](https://github.com/GEOUNED-org/GEOUNED/actions/workflows/ci.yml/badge.svg?branch=main)](https://github.com/GEOUNED-org/GEOUNED/actions/workflows/ci.yml) +[![Upload Python Package](https://github.com/GEOUNED-org/GEOUNED/actions/workflows/python-publish.yml/badge.svg)](https://github.com/GEOUNED-org/GEOUNED/actions/workflows/python-publish.yml) + # GEOUNED A tool to convert from CAD to CSG & CSG to CAD for Monte Carlo transport codes (MCNP & OpenMC). This repository contains the implementation of the algorithm presented in the paper [GEOUNED: A new conversion tool from CAD to Monte Carlo geometry](https://doi.org/10.1016/j.net.2024.01.052). diff --git a/src/geouned/GEOUNED/Conversion/CellDefinition.py b/src/geouned/GEOUNED/Conversion/CellDefinition.py index 6a866896..70a22887 100644 --- a/src/geouned/GEOUNED/Conversion/CellDefinition.py +++ b/src/geouned/GEOUNED/Conversion/CellDefinition.py @@ -23,20 +23,20 @@ from ..Utils.Options.Classes import Tolerances as tol -def getId(facein, Surfaces): +def getId(facein, surfaces): surfin = str(facein) if surfin == "": if isParallel(facein.Axis, FreeCAD.Vector(1, 0, 0), tol.pln_angle): - P = "PX" + p = "PX" elif isParallel(facein.Axis, FreeCAD.Vector(0, 1, 0), tol.pln_angle): - P = "PY" + p = "PY" elif isParallel(facein.Axis, FreeCAD.Vector(0, 0, 1), tol.pln_angle): - P = "PZ" + p = "PZ" else: - P = "P" + p = "P" - for s in Surfaces[P]: + for s in surfaces[p]: if BF.isSamePlane( facein, s.Surf, @@ -47,7 +47,7 @@ def getId(facein, Surfaces): return s.Index elif surfin == "": - for s in Surfaces["Cyl"]: + for s in surfaces["Cyl"]: if BF.isSameCylinder( facein, s.Surf, @@ -58,7 +58,7 @@ def getId(facein, Surfaces): return s.Index elif surfin == "": - for s in Surfaces["Cone"]: + for s in surfaces["Cone"]: if BF.isSameCone( facein, s.Surf, @@ -69,14 +69,14 @@ def getId(facein, Surfaces): return s.Index elif surfin[0:6] == "Sphere": - for s in Surfaces["Sph"]: + for s in surfaces["Sph"]: if BF.isSameSphere( facein, s.Surf, tol.sph_distance, relTol=tol.relativeTol ): return s.Index elif surfin == "": - for s in Surfaces["Tor"]: + for s in surfaces["Tor"]: if BF.isSameTorus( facein, s.Surf, @@ -95,9 +95,9 @@ def isInverted(solid): # u=(face.Surface.bounds()[0]+face.Surface.bounds()[1])/2.0 # entre 0 y 2pi si es completo # v=face.Surface.bounds()[0]+(face.Surface.bounds()[3]-face.Surface.bounds()[2])/3.0 # a lo largo del eje - Range = face.ParameterRange - u = (Range[1] + Range[0]) / 2.0 - v = (Range[3] + Range[2]) / 2.0 + parameter_range = face.ParameterRange + u = (parameter_range[1] + parameter_range[0]) / 2.0 + v = (parameter_range[3] + parameter_range[2]) / 2.0 if str(face.Surface) == "": dist1 = face.Surface.value(u, v).distanceToLine( @@ -127,13 +127,13 @@ def isInverted(solid): elif str(face.Surface)[0:6] == "Sphere": # radii = point - center radii = face.Surface.value(u, v).add(face.Surface.Center.multiply(-1)) - radiiB = ( + radii_b = ( face.Surface.value(u, v) .add(face.Surface.normal(u, v).multiply(1.0e-6)) .add(face.Surface.Center.multiply(-1)) ) - # radiiB = radii.add( face.Surface.normal(u,v).multiply(1.0e-6) ) - if (radiiB.Length - radii.Length) < 0.0: + # radii_b = radii.add( face.Surface.normal(u,v).multiply(1.0e-6) ) + if (radii_b.Length - radii.Length) < 0.0: # An increasing of the radii vector in the normal direction decreases the radii: oposite normal direction return True @@ -163,105 +163,105 @@ def GenPlane(face, solid): def getClosedRanges(solid, face_index): - UNodes = [] + u_nodes = [] for index in face_index: URange = solid.Faces[index].ParameterRange - UNodes.append((URange[0], index)) - UNodes.append((URange[1], index)) - UNodes.sort() + u_nodes.append((URange[0], index)) + u_nodes.append((URange[1], index)) + u_nodes.sort() - closedRange = getIntervals(UNodes) + closed_range = getIntervals(u_nodes) - aMin = closedRange[0][0][0] - aMax = closedRange[-1][1][0] + a_min = closed_range[0][0][0] + a_max = closed_range[-1][1][0] - if abs(aMax - aMin - 2.0 * math.pi) < 1e-2: - if len(closedRange) == 1: - closedFace = True + if abs(a_max - a_min - 2.0 * math.pi) < 1e-2: + if len(closed_range) == 1: + closed_face = True else: - endPoint = (closedRange[-1][0][0] - 2 * math.pi, closedRange[-1][0][1]) - closedRange[0][0] = endPoint - closedRange[0][2].update(closedRange[-1][2]) - del closedRange[-1] + endPoint = (closed_range[-1][0][0] - 2 * math.pi, closed_range[-1][0][1]) + closed_range[0][0] = endPoint + closed_range[0][2].update(closed_range[-1][2]) + del closed_range[-1] - if len(closedRange) == 1: + if len(closed_range) == 1: if ( - abs(closedRange[0][1][0] - closedRange[0][0][0] - 2.0 * math.pi) + abs(closed_range[0][1][0] - closed_range[0][0][0] - 2.0 * math.pi) < 1e-2 ): - closedFace = True + closed_face = True else: - closedFace = False + closed_face = False else: - closedFace = False + closed_face = False else: - closedFace = False - return closedRange, closedFace + closed_face = False + return closed_range, closed_face -def getIntervals(UNodes): - closedRange = [] - posMin = dict() - posMax = dict() - for i, node in enumerate(UNodes): - if node[1] not in posMin.keys(): - posMin[node[1]] = i +def getIntervals(u_nodes): + closed_ranges = [] + pos_min = dict() + pos_max = dict() + for i, node in enumerate(u_nodes): + if node[1] not in pos_min.keys(): + pos_min[node[1]] = i else: - posMax[node[1]] = i + pos_max[node[1]] = i - UMin = UNodes[0] - iPos = posMax[UMin[1]] + u_min = u_nodes[0] + i_pos = pos_max[u_min[1]] while True: - x = UNodes[iPos] + x = u_nodes[i_pos] end = True - for i in range(iPos + 1, len(UNodes)): - nxtInt = UNodes[i][1] + for i in range(i_pos + 1, len(u_nodes)): + mxt_int = u_nodes[i][1] if ( - UNodes[posMin[nxtInt]][0] - x[0] + u_nodes[pos_min[mxt_int]][0] - x[0] ) < 1e-5: # x pos is > min boundary of the next inteval inside precision 1e-5 - iPos = posMax[nxtInt] + i_pos = pos_max[mxt_int] end = False break if end: - UMax = x - closedRange.append([UMin, UMax]) - iPos += 1 - if iPos < len(UNodes): - UMin = UNodes[iPos] - iPos = posMax[UMin[1]] + u_max = x + closed_ranges.append([u_min, u_max]) + i_pos += 1 + if i_pos < len(u_nodes): + u_min = u_nodes[i_pos] + i_pos = pos_max[u_min[1]] else: break - for rnge in closedRange: + for closed_range in closed_ranges: index = set() - xmin = rnge[0][0] - xmax = rnge[1][0] - for interval in UNodes: + xmin = closed_range[0][0] + xmax = closed_range[1][0] + for interval in u_nodes: x = interval[0] if (xmin - x) < 1.0e-5 and (x - xmax) < 1.0e-5: index.add(interval[1]) - rnge.append(index) + closed_range.append(index) - return closedRange + return closed_ranges -def getUValueBoundary(solid, face_index, myIndex): +def getUValueBoundary(solid, face_index, my_index): - faceURange, closedFace = getClosedRanges(solid, face_index) - if closedFace: + face_u_ranges, closed_face = getClosedRanges(solid, face_index) + if closed_face: return None, None - for rnge in faceURange: - if myIndex in rnge[2]: - UMin, UMax = rnge[0:2] - return UMin, UMax + for face_u_range in face_u_ranges: + if my_index in face_u_range[2]: + u_min, u_max = face_u_range[0:2] + return u_min, u_max def GenPlaneSphere(face, solid): - Same_Faces = [] - Same_Faces.append(face) + same_faces = [] + same_faces.append(face) for f in solid.Faces: if f.isEqual(face) or str(f.Surface) != "Sphere": @@ -271,14 +271,14 @@ def GenPlaneSphere(face, solid): and f.Surface.Radius == face.Surface.Radius ): # print 'Warning: coincident sphere faces are the same' - for f2 in Same_Faces: + for f2 in same_faces: if f.distToShape(f2)[0] < 1e-6: - Same_Faces.append(f) + same_faces.append(f) break - # print Same_Faces + # print same_faces normal = FreeCAD.Vector(0, 0, 0) - for f in Same_Faces: + for f in same_faces: normal += f.Area * (f.CenterOfMass - face.Surface.Center) return Part.Plane(face.Surface.Center, normal).toShape() @@ -286,20 +286,20 @@ def GenPlaneSphere(face, solid): def GenPlaneCylinder(face, solid): - Surf = face.Surface - rad = Surf.Radius + surf = face.Surface + rad = surf.Radius - if str(Surf) != "": + if str(surf) != "": return None - myIndex = solid.Faces.index(face) - face_index = [myIndex] + my_index = solid.Faces.index(face) + face_index = [my_index] for i, face2 in enumerate(solid.Faces): if face2.Area < tol.min_area: if opt.verbose: print( - f"Warning: {str(Surf)} surface removed from cell definition. Face area < Min area ({face2.Area} < {tol.min_area}) " + f"Warning: {str(surf)} surface removed from cell definition. Face area < Min area ({face2.Area} < {tol.min_area}) " ) continue if str(face2.Surface) == "" and not (face2.isEqual(face)): @@ -313,36 +313,36 @@ def GenPlaneCylinder(face, solid): # print 'Warning: coincident cylinder faces are the same' face_index.append(i) - UMin, UMax = getUValueBoundary(solid, face_index, myIndex) - if UMin is None: + u_min, u_max = getUValueBoundary(solid, face_index, my_index) + if u_min is None: return None - U1, i1 = UMin - U2, i2 = UMax + u_1, i1 = u_min + u_2, i2 = u_max - V1 = solid.Faces[i1].ParameterRange[2] - V2 = solid.Faces[i2].ParameterRange[2] + v_1 = solid.Faces[i1].ParameterRange[2] + v_2 = solid.Faces[i2].ParameterRange[2] - P1 = solid.Faces[i1].valueAt(U1, V1) - P2 = solid.Faces[i2].valueAt(U2, V2) + p1 = solid.Faces[i1].valueAt(u_1, v_1) + p2 = solid.Faces[i2].valueAt(u_2, v_2) - if P1.isEqual(P2, 1e-5): + if p1.isEqual(p2, 1e-5): if opt.verbose: print("Error in the additional place definition") return None - normal = P2.sub(P1).cross(face.Surface.Axis) - plane = Part.Plane(P1, normal).toShape() + normal = p2.sub(p1).cross(face.Surface.Axis) + plane = Part.Plane(p1, normal).toShape() return plane def GenPlaneCylinder_old(face, solid): - Surf = face.Surface - rad = Surf.Radius + surf = face.Surface + rad = surf.Radius - if str(Surf) != "": + if str(surf) != "": return None face_index = [solid.Faces.index(face)] @@ -351,7 +351,7 @@ def GenPlaneCylinder_old(face, solid): if face2.Area < tol.min_area: if opt.verbose: print( - f"Warning: {str(Surf)} surface removed from cell definition. Face area < Min area ({face2.Area} < {tol.min_area}) " + f"Warning: {str(surf)} surface removed from cell definition. Face area < Min area ({face2.Area} < {tol.min_area}) " ) continue if str(face2.Surface) == "" and not (face2.isEqual(face)): @@ -365,15 +365,15 @@ def GenPlaneCylinder_old(face, solid): # print 'Warning: coincident cylinder faces are the same' face_index.append(i) - AngleRange = 0.0 - Uval = [] + angle_range = 0.0 + U_val = [] for index in face_index: Range = solid.Faces[index].ParameterRange - AngleRange = AngleRange + abs(Range[1] - Range[0]) - if not (Range[0] in Uval) and not (Range[1] in Uval): - Uval.append(Range[0]) - Uval.append(Range[1]) - if 2.0 * math.pi - AngleRange < 1e-2: + angle_range = angle_range + abs(Range[1] - Range[0]) + if not (Range[0] in U_val) and not (Range[1] in U_val): + U_val.append(Range[0]) + U_val.append(Range[1]) + if 2.0 * math.pi - angle_range < 1e-2: return None UVNodes = [] @@ -384,47 +384,47 @@ def GenPlaneCylinder_old(face, solid): except RuntimeError: UVNodes.append(face2.getUVNodes()) - Uval_str_cl = [] - for i, elem1 in enumerate(Uval): + U_val_str_cl = [] + for i, elem1 in enumerate(U_val): num_str1 = "%11.4E" % elem1 if abs(elem1) < 1.0e-5: num_str1 = "%11.4E" % 0.0 - if not (BF.isDuplicateInList(num_str1, i, Uval)): - Uval_str_cl.append(num_str1) + if not (BF.isDuplicateInList(num_str1, i, U_val)): + U_val_str_cl.append(num_str1) face_index_2 = [face_index[0], face_index[0]] - Node_min = UVNodes[0][0] - Node_max = UVNodes[0][1] + node_min = UVNodes[0][0] + node_max = UVNodes[0][1] - dif1_0 = abs(float(Uval_str_cl[0]) - Node_min[0]) - dif2_0 = abs(float(Uval_str_cl[1]) - Node_max[0]) + dif1_0 = abs(float(U_val_str_cl[0]) - node_min[0]) + dif2_0 = abs(float(U_val_str_cl[1]) - node_max[0]) # searching for minimum and maximum angle points for j, Nodes in enumerate(UVNodes): for elem in Nodes: - dif1 = abs(float(Uval_str_cl[0]) - elem[0]) - dif2 = abs(float(Uval_str_cl[1]) - elem[0]) + dif1 = abs(float(U_val_str_cl[0]) - elem[0]) + dif2 = abs(float(U_val_str_cl[1]) - elem[0]) if dif1 < dif1_0: - Node_min = elem + node_min = elem face_index_2[0] = face_index[j] dif1_0 = dif1 if dif2 < dif2_0: - Node_max = elem + node_max = elem face_index_2[1] = face_index[j] dif2_0 = dif2 - V1 = solid.Faces[face_index_2[0]].valueAt(Node_min[0], Node_min[1]) - V2 = solid.Faces[face_index_2[1]].valueAt(Node_max[0], Node_max[1]) + v_1 = solid.Faces[face_index_2[0]].valueAt(node_min[0], node_min[1]) + v_2 = solid.Faces[face_index_2[1]].valueAt(node_max[0], node_max[1]) - if V1.isEqual(V2, 1e-5): + if v_1.isEqual(v_2, 1e-5): if opt.verbose: print("Error in the additional place definition") return None - normal = V2.sub(V1).cross(face.Surface.Axis) - plane = Part.Plane(V1, normal).toShape() + normal = v_2.sub(v_1).cross(face.Surface.Axis) + plane = Part.Plane(v_1, normal).toShape() return plane @@ -453,33 +453,33 @@ def GenPlaneCone(face, solid): ): face_index.append(i) - UMin, UMax = getUValueBoundary(solid, face_index, myIndex) - if UMin is None: + u_min, u_max = getUValueBoundary(solid, face_index, myIndex) + if u_min is None: return None - U1, i1 = UMin - U2, i2 = UMax + u_1, i1 = u_min + u_2, i2 = u_max - V1 = solid.Faces[i1].ParameterRange[2] - V2 = solid.Faces[i2].ParameterRange[2] + v_1 = solid.Faces[i1].ParameterRange[2] + v_2 = solid.Faces[i2].ParameterRange[2] - P1 = solid.Faces[i1].valueAt(U1, V1) - P2 = solid.Faces[i2].valueAt(U2, V2) + p1 = solid.Faces[i1].valueAt(u_1, v_1) + p2 = solid.Faces[i2].valueAt(u_2, v_2) - if P1.isEqual(P2, 1e-5): + if p1.isEqual(p2, 1e-5): if opt.verbose: print("Error in the additional place definition") return None - plane = Part.Plane(P1, P2, face.Surface.Apex).toShape() + plane = Part.Plane(p1, p2, face.Surface.Apex).toShape() return plane def GenPlaneCone_old(face, solid): - Surf = face.Surface - if str(Surf) != "": + surf = face.Surface + if str(surf) != "": return None face_index = [solid.Faces.index(face)] @@ -488,7 +488,7 @@ def GenPlaneCone_old(face, solid): if face2.Area < tol.min_area: if opt.verbose: print( - f"Warning: {str(Surf)} surface removed from cell definition. Face area < Min area ({face2.Area} < {tol.min_area}) " + f"Warning: {str(surf)} surface removed from cell definition. Face area < Min area ({face2.Area} < {tol.min_area}) " ) continue if str(face2.Surface) == "" and not (face2.isEqual(face)): @@ -499,70 +499,70 @@ def GenPlaneCone_old(face, solid): ): face_index.append(i) - AngleRange = 0.0 - Uval = [] + angle_range = 0.0 + u_val = [] for index in face_index: - Range = solid.Faces[index].ParameterRange - AngleRange = AngleRange + abs(Range[1] - Range[0]) - Uval.append(Range[0]) - Uval.append(Range[1]) + parameter_range = solid.Faces[index].ParameterRange + angle_range = angle_range + abs(parameter_range[1] - parameter_range[0]) + u_val.append(parameter_range[0]) + u_val.append(parameter_range[1]) - if 2.0 * math.pi - AngleRange < 1e-2: + if 2.0 * math.pi - angle_range < 1e-2: return None - UVNodes = [] + uv_nodes = [] for index in face_index: face2 = solid.Faces[index] try: - UVNodes.append(face2.getUVNodes()) + uv_nodes.append(face2.getUVNodes()) except RuntimeError: face.tessellate(1.0, True) - UVNodes.append(face2.getUVNodes()) + uv_nodes.append(face2.getUVNodes()) - Uval_str_cl = [] + u_val_str_cl = [] - for i, elem1 in enumerate(Uval): + for i, elem1 in enumerate(u_val): num_str1 = "%11.4E" % elem1 if abs(elem1) < 1.0e-5: num_str1 = "%11.4E" % 0.0 - if not (BF.isDuplicateInList(num_str1, i, Uval)): - Uval_str_cl.append(num_str1) + if not (BF.isDuplicateInList(num_str1, i, u_val)): + u_val_str_cl.append(num_str1) face_index_2 = [face_index[0], face_index[0]] - Node_min = UVNodes[0][0] - Node_max = UVNodes[0][1] - dif1_0 = abs(float(Uval_str_cl[0]) - Node_min[0]) - dif2_0 = abs(float(Uval_str_cl[1]) - Node_max[0]) + node_min = uv_nodes[0][0] + node_max = uv_nodes[0][1] + dif1_0 = abs(float(u_val_str_cl[0]) - node_min[0]) + dif2_0 = abs(float(u_val_str_cl[1]) - node_max[0]) # searching for minimum and maximum angle points - for j, Nodes in enumerate(UVNodes): + for j, Nodes in enumerate(uv_nodes): for elem in Nodes: - dif1 = abs(float(Uval_str_cl[0]) - elem[0]) - dif2 = abs(float(Uval_str_cl[1]) - elem[0]) + dif1 = abs(float(u_val_str_cl[0]) - elem[0]) + dif2 = abs(float(u_val_str_cl[1]) - elem[0]) if dif1 < dif1_0: - Node_min = elem + node_min = elem face_index_2[0] = face_index[j] dif1_0 = dif1 if dif2 < dif2_0: - Node_max = elem + node_max = elem face_index_2[1] = face_index[j] dif2_0 = dif2 - V1 = solid.Faces[face_index_2[0]].valueAt(Node_min[0], Node_min[1]) - V2 = solid.Faces[face_index_2[1]].valueAt(Node_max[0], Node_max[1]) + v_1 = solid.Faces[face_index_2[0]].valueAt(node_min[0], node_min[1]) + v_2 = solid.Faces[face_index_2[1]].valueAt(node_max[0], node_max[1]) - if V1.isEqual(V2, 1e-5): + if v_1.isEqual(v_2, 1e-5): if opt.verbose: print("Error in the additional place definition") return None - plane = Part.Plane(V1, V2, face.Surface.Apex).toShape() + plane = Part.Plane(v_1, v_2, face.Surface.Apex).toShape() return plane -def GenTorusAnnexUPlanes(face, Uparams): +def GenTorusAnnexUPlanes(face, u_params): if isParallel(face.Surface.Axis, FreeCAD.Vector(1, 0, 0), tol.tor_angle): axis = FreeCAD.Vector(1, 0, 0) @@ -572,11 +572,11 @@ def GenTorusAnnexUPlanes(face, Uparams): axis = FreeCAD.Vector(0, 0, 1) center = face.Surface.Center - p1 = face.valueAt(Uparams[0], 0.0) - p2 = face.valueAt(Uparams[1], 0.0) - pmid = face.valueAt(0.5 * (Uparams[0] + Uparams[1]), 0.0) + p1 = face.valueAt(u_params[0], 0.0) + p2 = face.valueAt(u_params[1], 0.0) + pmid = face.valueAt(0.5 * (u_params[0] + u_params[1]), 0.0) - if isSameValue(abs(Uparams[1] - Uparams[0]), math.pi, tol.value): + if isSameValue(abs(u_params[1] - u_params[0]), math.pi, tol.value): d = axis.cross(p2 - p1) d.normalize() if d.dot(pmid - center) < 0: @@ -586,7 +586,7 @@ def GenTorusAnnexUPlanes(face, Uparams): None, ), False - elif Uparams[1] - Uparams[0] < math.pi: + elif u_params[1] - u_params[0] < math.pi: d = axis.cross(p2 - p1) d.normalize() if d.dot(pmid - center) < 0: @@ -613,7 +613,7 @@ def GenTorusAnnexUPlanes(face, Uparams): ), True # (d1 : d2) -def GenTorusAnnexUPlanes_org(face, Uparams): +def GenTorusAnnexUPlanes_org(face, u_params): if isParallel(face.Surface.Axis, FreeCAD.Vector(1, 0, 0), tol.tor_angle): axis = FreeCAD.Vector(1, 0, 0) @@ -623,11 +623,11 @@ def GenTorusAnnexUPlanes_org(face, Uparams): axis = FreeCAD.Vector(0, 0, 1) center = face.Surface.Center - p1 = face.valueAt(Uparams[0], 0.0) - p2 = face.valueAt(Uparams[1], 0.0) - pmid = face.valueAt(0.5 * (Uparams[0] + Uparams[1]), 0.0) + p1 = face.valueAt(u_params[0], 0.0) + p2 = face.valueAt(u_params[1], 0.0) + pmid = face.valueAt(0.5 * (u_params[0] + u_params[1]), 0.0) - if isSameValue(abs(Uparams[1] - Uparams[0]), math.pi, tol.value): + if isSameValue(abs(u_params[1] - u_params[0]), math.pi, tol.value): d = axis.cross(p2 - p1) d.normalize() if pmid.dot(d) < 0: @@ -645,7 +645,7 @@ def GenTorusAnnexUPlanes_org(face, Uparams): if pmid.dot(d2) < 0: d2 = -d2 - if Uparams[1] - Uparams[0] < math.pi: + if u_params[1] - u_params[0] < math.pi: return ( (center, d1, face.Surface.MajorRadius, face.Surface.MajorRadius), (center, d2, face.Surface.MajorRadius, face.Surface.MajorRadius), @@ -657,7 +657,7 @@ def GenTorusAnnexUPlanes_org(face, Uparams): ), True # (d1 : d2) -def GenTorusAnnexVSurface(face, Vparams, forceCylinder=False): +def GenTorusAnnexVSurface(face, v_params, force_cylinder=False): if isParallel(face.Surface.Axis, FreeCAD.Vector(1, 0, 0), tol.tor_angle): axis = FreeCAD.Vector(1, 0, 0) elif isParallel(face.Surface.Axis, FreeCAD.Vector(0, 1, 0), tol.tor_angle): @@ -665,100 +665,104 @@ def GenTorusAnnexVSurface(face, Vparams, forceCylinder=False): elif isParallel(face.Surface.Axis, FreeCAD.Vector(0, 0, 1), tol.tor_angle): axis = FreeCAD.Vector(0, 0, 1) - p1 = face.valueAt(0.0, Vparams[0]) - face.Surface.Center + p1 = face.valueAt(0.0, v_params[0]) - face.Surface.Center z1 = p1.dot(axis) d1 = p1.cross(axis).Length - p2 = face.valueAt(0.0, Vparams[1]) - face.Surface.Center + p2 = face.valueAt(0.0, v_params[1]) - face.Surface.Center z2 = p2.dot(axis) d2 = p2.cross(axis).Length if isSameValue(z1, z2, tol.distance): - surfType = "Plane" + surf_type = "Plane" center = face.Surface.Center + z1 * axis - Vmid = (Vparams[0] + Vparams[1]) * 0.5 - pMid = face.valueAt(0, Vmid) - face.Surface.Center - if pMid.dot(axis) < z1: - inSurf = True + v_mid = (v_params[0] + v_params[1]) * 0.5 + p_mid = face.valueAt(0, v_mid) - face.Surface.Center + if p_mid.dot(axis) < z1: + in_surf = True else: - inSurf = False + in_surf = False return ( (center, axis, face.Surface.MajorRadius, face.Surface.MajorRadius), - surfType, - inSurf, + surf_type, + in_surf, ) - elif isSameValue(d1, d2, tol.distance) or forceCylinder: - surfType = "Cylinder" + elif isSameValue(d1, d2, tol.distance) or force_cylinder: + surf_type = "Cylinder" radius = min(d1, d2) center = face.Surface.Center if isSameValue(d1, face.Surface.MajorRadius, tol.distance): - Vmid = (Vparams[0] + Vparams[1]) * 0.5 - pMid = face.valueAt(0, Vmid) - center - if pMid.cross(axis).Length < face.Surface.MajorRadius: - inSurf = True - radius = max(d1,d2) + v_mid = (v_params[0] + v_params[1]) * 0.5 + p_mid = face.valueAt(0, v_mid) - center + if p_mid.cross(axis).Length < face.Surface.MajorRadius: + in_surf = True + v_mid = (v_params[0] + v_params[1]) * 0.5 + p_mid = face.valueAt(0, v_mid) - center + if p_mid.cross(axis).Length < face.Surface.MajorRadius: + in_surf = True + radius = max(d1, d2) else: - inSurf = False + in_surf = False else: if d1 < face.Surface.MajorRadius: - inSurf = True - radius = max(d1,d2) + in_surf = True + radius = max(d1, d2) else: - inSurf = False - return (center, axis, radius, face.Surface.MinorRadius), surfType, inSurf + in_surf = False + return (center, axis, radius, face.Surface.MinorRadius), surf_type, in_surf else: - surfType = "Cone" + surf_type = "Cone" za = (z2 * d1 - z1 * d2) / (d1 - d2) - Apex = face.Surface.Center + za * axis - semiAngle = abs(math.atan(d1 / (z1 - za))) + apex = face.Surface.Center + za * axis + semi_angle = abs(math.atan(d1 / (z1 - za))) - ConeAxis = axis if (z1 - za) > 0.0 else -axis + cone_axis = axis if (z1 - za) > 0.0 else -axis - Vmid = (Vparams[0] + Vparams[1]) * 0.5 - pMid = face.valueAt(0, Vmid) - face.Surface.Center - zMid = pMid.dot(axis) - dMid = pMid.cross(axis).Length + v_mid = (v_params[0] + v_params[1]) * 0.5 + p_mid = face.valueAt(0, v_mid) - face.Surface.Center + z_mid = p_mid.dot(axis) + d_mid = p_mid.cross(axis).Length - dCone = d1 * (zMid - za) / (z1 - za) - inSurf = True if dMid < dCone else False + d_cone = d1 * (z_mid - za) / (z1 - za) + in_surf = True if d_mid < d_cone else False return ( ( - Apex, - ConeAxis, - semiAngle, + apex, + cone_axis, + semi_angle, face.Surface.MinorRadius, face.Surface.MajorRadius, ), - surfType, - inSurf, + surf_type, + in_surf, ) -def cellDef(metaObj, Surfaces, UniverseBox): +def cellDef(meta_obj, surfaces, universe_box): - solids = metaObj.Solids - delList = [] + solids = meta_obj.Solids + del_list = [] - PieceDef = BoolSequence(operator="OR") - PieceObj = [] + piece_def = BoolSequence(operator="OR") + iece_obj = [] cones = set() for isol, solid in enumerate(solids): - SurfPiece = [] - SurfObj = [] - extraPlaneReverse = dict() + surf_piece = [] + surf_obj = [] + extra_plane_reverse = dict() flag_inv = isInverted(solid) - solid_GU = GU.SolidGu(solid) - lastTorus = -1 - for iface, face in enumerate(solid_GU.Faces): - surfaceType = str(face.Surface) + solid_gu = GU.SolidGu(solid) + last_torus = -1 + for iface, face in enumerate(solid_gu.Faces): + surface_type = str(face.Surface) if abs(face.Area) < tol.min_area: if opt.verbose: print( - f"Warning: {surfaceType} surface removed from cell definition. Face area < Min area ({face.Area} < {tol.min_area}) " + f"Warning: {surface_type} surface removed from cell definition. Face area < Min area ({face.Area} < {tol.min_area}) " ) continue if face.Area < 0: @@ -775,24 +779,24 @@ def cellDef(metaObj, Surfaces, UniverseBox): else: orient = face.Orientation - if "Sphere" in surfaceType: - surfaceType = "Sphere" + if "Sphere" in surface_type: + surface_type = "Sphere" # cone additional plane is added afterward if ( - surfaceType in ("", "", "Sphere") + surface_type in ("", "", "Sphere") and orient == "Reversed" ): # cone additional plane is added afterward - idFace = getId(face.Surface, Surfaces) - if surfaceType == "": - cones.add(idFace) - if str(idFace) not in SurfPiece: - SurfPiece.append(str(idFace)) - SurfObj.append(face) + id_face = getId(face.Surface, surfaces) + if surface_type == "": + cones.add(id_face) + if str(id_face) not in surf_piece: + surf_piece.append(str(id_face)) + surf_obj.append(face) try: - plane = GenPlane(face, solid_GU) + plane = GenPlane(face, solid_gu) if plane is not None: plane = GU.PlaneGu(plane) except: @@ -803,27 +807,27 @@ def cellDef(metaObj, Surfaces, UniverseBox): if plane is not None: p = GeounedSurface( ("Plane", (plane.Position, plane.Axis, plane.dim1, plane.dim2)), - UniverseBox, + universe_box, Face="Build", ) - id, exist = Surfaces.addPlane(p) + id, exist = surfaces.addPlane(p) sign = signPlane(face.CenterOfMass, p) if exist: - pp = Surfaces.getSurface(id) + pp = surfaces.getSurface(id) if isOposite(p.Surf.Axis, pp.Surf.Axis, tol.angle): id = -id id *= sign - if idFace not in extraPlaneReverse.keys(): - extraPlaneReverse[idFace] = [str(id)] - SurfObj.append(p.shape) + if id_face not in extra_plane_reverse.keys(): + extra_plane_reverse[id_face] = [str(id)] + surf_obj.append(p.shape) else: - if str(id) not in extraPlaneReverse[idFace]: - extraPlaneReverse[idFace].append(str(id)) - SurfObj.append(p.shape) + if str(id) not in extra_plane_reverse[id_face]: + extra_plane_reverse[id_face].append(str(id)) + surf_obj.append(p.shape) - elif surfaceType == "": + elif surface_type == "": if ( isParallel(face.Surface.Axis, FreeCAD.Vector(1, 0, 0), tol.angle) @@ -831,111 +835,110 @@ def cellDef(metaObj, Surfaces, UniverseBox): or isParallel(face.Surface.Axis, FreeCAD.Vector(0, 0, 1), tol.angle) ): - idT = getId(face.Surface, Surfaces) + idT = getId(face.Surface, surfaces) - index, Uparams = solid_GU.TorusUParams[iface] - if index == lastTorus: + index, u_params = solid_gu.TorusUParams[iface] + if index == last_torus: continue - lastTorus = index + last_torus = index # add if necesary additional planes following U variable - UClosed, UminMax = Uparams - # UClosed = True - if not UClosed: - planes, ORop = GenTorusAnnexUPlanes(face, UminMax) + u_closed, u_minMax = u_params + # u_closed = True + if not u_closed: + planes, ORop = GenTorusAnnexUPlanes(face, u_minMax) plane1, plane2 = planes - plane = GeounedSurface( - ("Plane", plane1), UniverseBox, Face="Build" + ("Plane", plane1), universe_box, Face="Build" ) - id1, exist = Surfaces.addPlane(plane) + id1, exist = surfaces.addPlane(plane) if exist: - p = Surfaces.getSurface(id1) + p = surfaces.getSurface(id1) if isOposite(plane.Surf.Axis, p.Surf.Axis, tol.pln_angle): id1 = -id1 if plane2 is None: - UVar = "%i" % id1 + u_var = "%i" % id1 else: plane = GeounedSurface( - ("Plane", plane2), UniverseBox, Face="Build" + ("Plane", plane2), universe_box, Face="Build" ) - id2, exist = Surfaces.addPlane(plane) + id2, exist = surfaces.addPlane(plane) if exist: - p = Surfaces.getSurface(id2) + p = surfaces.getSurface(id2) if isOposite( plane.Surf.Axis, p.Surf.Axis, tol.pln_angle ): id2 = -id2 - UVar = ( + u_var = ( "(%i : %i)" % (id1, id2) if ORop else "%i %i" % (id1, id2) ) else: - UVar = "" + u_var = "" # add if necesary additional surface following V variable if orient == "Forward": - VVar = "-%i" % idT + v_var = "-%i" % idT else: - index, Vparams = solid_GU.TorusVParams[iface] + index, Vparams = solid_gu.TorusVParams[iface] VClosed, VminMax = Vparams if VClosed: - VVar = "%i" % idT + v_var = "%i" % idT else: - surfParams, surfType, inSurf = GenTorusAnnexVSurface( + surf_params, surf_type, in_surf = GenTorusAnnexVSurface( face, VminMax, opt.forceCylinder ) - if surfType == "Cone": + if surf_type == "Cone": cone = GeounedSurface( - ("Cone", surfParams), UniverseBox, Face="Build" + ("Cone", surf_params), universe_box, Face="Build" ) - id2, exist = Surfaces.addCone(cone) + id2, exist = surfaces.addCone(cone) - elif surfType == "Cylinder": + elif surf_type == "Cylinder": cyl = GeounedSurface( - ("Cylinder", surfParams), UniverseBox, Face="Build" + ("Cylinder", surf_params), universe_box, Face="Build" ) - id2, exist = Surfaces.addCylinder(cyl) + id2, exist = surfaces.addCylinder(cyl) - elif surfType == "Plane": + elif surf_type == "Plane": plane = GeounedSurface( - ("Plane", surfParams), UniverseBox, Face="Build" + ("Plane", surf_params), universe_box, Face="Build" ) - id2, exist = Surfaces.addPlane(plane) + id2, exist = surfaces.addPlane(plane) if exist: - p = Surfaces.getSurface(id2) + p = surfaces.getSurface(id2) if isOposite( plane.Surf.Axis, p.Surf.Axis, tol.pln_angle ): id2 = -id2 - VVar = "%i %i" % (idT, -id2 if inSurf else id2) + v_var = "%i %i" % (idT, -id2 if in_surf else id2) - var = VVar if UClosed else " ".join((VVar, UVar)) - if var not in SurfPiece: - SurfPiece.append(var) - SurfObj.append(face) + var = v_var if u_closed else " ".join((v_var, u_var)) + if var not in surf_piece: + surf_piece.append(var) + surf_obj.append(face) else: if opt.verbose: print( "Only Torus with axis along X, Y , Z axis can be reproduced" ) else: - id = getId(face.Surface, Surfaces) - if surfaceType == "": + id = getId(face.Surface, surfaces) + if surface_type == "": cones.add(-id) surf = face if id == 0: if opt.verbose: - print("Warning: ", surfaceType, " not found in surface list") - if surfaceType == "": + print("Warning: ", surface_type, " not found in surface list") + if surface_type == "": dim1 = face.ParameterRange[1] - face.ParameterRange[0] dim2 = face.ParameterRange[3] - face.ParameterRange[2] plane = GeounedSurface( @@ -943,13 +946,13 @@ def cellDef(metaObj, Surfaces, UniverseBox): "Plane", (face.Surface.Position, face.Surface.Axis, dim1, dim2), ), - UniverseBox, + universe_box, Face="Build", ) - id, exist = Surfaces.addPlane(plane) + id, exist = surfaces.addPlane(plane) surf = plane.shape - elif surfaceType == "": - dimL = face.ParameterRange[3] - face.ParameterRange[2] + elif surface_type == "": + dim_l = face.ParameterRange[3] - face.ParameterRange[2] cylinder = GeounedSurface( ( "Cylinder", @@ -957,13 +960,13 @@ def cellDef(metaObj, Surfaces, UniverseBox): face.Surface.Center, face.Surface.Axis, face.Surface.Radius, - dimL, + dim_l, ), ), - UniverseBox, + universe_box, Face="Build", ) - id, exist = Surfaces.addCylinder(cylinder) + id, exist = surfaces.addCylinder(cylinder) surf = cylinder.shape if orient == "Reversed": @@ -971,29 +974,29 @@ def cellDef(metaObj, Surfaces, UniverseBox): elif orient == "Forward": var = -id - if surfaceType == "": - s = Surfaces.getSurface(id) + if surface_type == "": + s = surfaces.getSurface(id) if isOposite(face.Surface.Axis, s.Surf.Axis, tol.pln_angle): var = -var - if str(var) in SurfPiece: + if str(var) in surf_piece: continue - SurfPiece.append(str(var)) - SurfObj.append(surf) + surf_piece.append(str(var)) + surf_obj.append(surf) - if extraPlaneReverse: - for extra in extraPlaneReverse.values(): + if extra_plane_reverse: + for extra in extra_plane_reverse.values(): if len(extra) == 1: - if extra[0] not in SurfPiece: - SurfPiece.append(extra[0]) + if extra[0] not in surf_piece: + surf_piece.append(extra[0]) else: - SurfPiece.append("({})".format(":".join(extra))) + surf_piece.append("({})".format(":".join(extra))) - SurfPieceBool = BoolSequence(" ".join(SurfPiece)) + surf_piece_bool = BoolSequence(" ".join(surf_piece)) # possible expresion for e # i1 - # i1 i2SurfPiece + # i1 i2surf_piece # i1 i2 i3 # (i1:i2) # i1 (i2:i3) @@ -1003,35 +1006,35 @@ def cellDef(metaObj, Surfaces, UniverseBox): # print (e) # if semi != -1 : # orTerm = expOR(int(e[1:semi]),int(e[semi+1:-1])) - # SurfPieceBool.add(orTerm) + # surf_piece_bool.add(orTerm) # elif blk != -1 : - # SurfPieceBool.add(int(e[1:blk]),int(e[blk+1:-1])) + # surf_piece_bool.add(int(e[1:blk]),int(e[blk+1:-1])) # else : - # SurfPieceBool.add(int(e)) + # surf_piece_bool.add(int(e)) - if SurfPieceBool.elements: - PieceDef.append(SurfPieceBool) - PieceObj.append(SurfObj) + if surf_piece_bool.elements: + piece_def.append(surf_piece_bool) + iece_obj.append(surf_obj) else: - delList.append(isol) + del_list.append(isol) - for isol in reversed(delList): - del metaObj.Solids[isol] - metaObj.setDefinition(PieceDef) - metaObj.setFaces(PieceObj) + for isol in reversed(del_list): + del meta_obj.Solids[isol] + meta_obj.setDefinition(piece_def) + meta_obj.setFaces(iece_obj) return tuple(cones) -def getSurfValue(Definition, reverse=False): +def getSurfValue(definition, reverse=False): - if Definition.level == 0: + if definition.level == 0: if reverse: - surf = {-i for i in Definition.elements} + surf = {-i for i in definition.elements} else: - surf = set(Definition.elements) + surf = set(definition.elements) else: surf = set() - for e in Definition.elements: + for e in definition.elements: if e.operator == "AND": if reverse: surf = {-i for i in e.elements} @@ -1041,58 +1044,58 @@ def getSurfValue(Definition, reverse=False): return surf -def appendComp(newCell, cellDef, cellCAD, metaComplementary): +def appendComp(new_cell, cell_def, cell_cad, meta_complementary): - surfCell = getSurfValue(cellDef, True) - if metaComplementary.Definition.operator == "AND": - if not cellCAD.BoundBox.intersect(metaComplementary.CADSolid.BoundBox): + surf_cell = getSurfValue(cell_def, True) + if meta_complementary.Definition.operator == "AND": + if not cell_cad.BoundBox.intersect(meta_complementary.CADSolid.BoundBox): return False - Seq = metaComplementary.Definition + Seq = meta_complementary.Definition surfComp = getSurfValue(Seq, False) - if len(surfComp & surfCell) > 0: + if len(surfComp & surf_cell) > 0: return False - newCell.append(Seq.getComplementary()) + new_cell.append(Seq.getComplementary()) return True else: append = False - for i, compPart in enumerate(metaComplementary.Solids): - if not cellCAD.BoundBox.intersect(compPart.BoundBox): + for i, compPart in enumerate(meta_complementary.Solids): + if not cell_cad.BoundBox.intersect(compPart.BoundBox): continue - Seq = metaComplementary.Definition.elements[i] + Seq = meta_complementary.Definition.elements[i] surfComp = getSurfValue(Seq, False) - if len(surfComp & surfCell) > 0: + if len(surfComp & surf_cell) > 0: continue append = True - newCell.append(Seq.getComplementary()) + new_cell.append(Seq.getComplementary()) return append -def noOverlappingCell(metaList, Surfaces): +def noOverlappingCell(metaList, surfaces): Surfs = {} - for lst in Surfaces.values(): + for lst in surfaces.values(): for s in lst: Surfs[s.Index] = s - newDefinitionList = [] + new_definition_list = [] metaList[0].setCADSolid() for i, m in enumerate(metaList[1:]): m.setCADSolid() if m.Definition.operator == "AND": - newDef = BoolSequence(operator="AND") - newDef.append(m.Definition.copy()) + new_def = BoolSequence(operator="AND") + new_def.append(m.Definition.copy()) simplify = False for mm in metaList[: i + 1]: - simp = appendComp(newDef, m.Definition, m.CADSolid, mm) + simp = appendComp(new_def, m.Definition, m.CADSolid, mm) if simp: simplify = True simpTerm = [simplify] else: - newDef = BoolSequence(operator="OR") + new_def = BoolSequence(operator="OR") simpTerm = [] for j, partSolid in enumerate(m.Solids): subDef = BoolSequence(operator="AND") @@ -1103,47 +1106,47 @@ def noOverlappingCell(metaList, Surfaces): if simp: simplify = True simpTerm.append(simplify) - newDef.append(subDef) - newDefinitionList.append((newDef, simpTerm)) + new_def.append(subDef) + new_definition_list.append((new_def, simpTerm)) - for m, tDef in zip(metaList[1:], newDefinitionList): - Def, simplify = tDef + for m, t_def_and_simplify in zip(metaList[1:], new_definition_list): + t_def, simplify = t_def_and_simplify if True in simplify: print(f"reduce cell {m.__id__}") - Box = UF.getBox(m) + box = UF.getBox(m) # evaluate only diagonal elements of the Constraint Table (fastest) and remove surface not # crossing in the solid boundBox CT = buildCTableFromSolids( - Box, (tuple(Def.getSurfacesNumbers()), Surfs), option="diag" + box, (tuple(t_def.getSurfacesNumbers()), Surfs), option="diag" ) - newDef = removeExtraSurfaces(Def, CT) + new_def = removeExtraSurfaces(t_def, CT) # evaluate full constraint Table with less surfaces involved CT = buildCTableFromSolids( - Box, (tuple(newDef.getSurfacesNumbers()), Surfs), option="full" + box, (tuple(new_def.getSurfacesNumbers()), Surfs), option="full" ) - if newDef.operator == "AND": - newDef.simplify(CT) - newDef.clean() + if new_def.operator == "AND": + new_def.simplify(CT) + new_def.clean() else: for i, s in enumerate(simplify): if not s: continue - comp = newDef.elements[i] + comp = new_def.elements[i] comp.simplify(CT) comp.clean() - m.setDefinition(newDef) + m.setDefinition(new_def) m.Definition.joinOperators() m.Definition.levelUpdate() -def ExtraPlaneCylFace(face, Box, Surfaces): +def ExtraPlaneCylFace(face, box, surfaces): wire = face.OuterWire - planesId = [] + planes_id = [] for e in wire.OrderedEdges: curve = str(e.Curve) if curve[0:6] == "Circle" or curve == "": @@ -1156,24 +1159,24 @@ def ExtraPlaneCylFace(face, Box, Surfaces): dim1 = e.Curve.Radius dim2 = e.Curve.Radius plane = GeounedSurface( - ("Plane", (center, dir, dim1, dim2)), Box, Face="Build" + ("Plane", (center, dir, dim1, dim2)), box, Face="Build" ) - id, exist = Surfaces.addPlane(plane) + id, exist = surfaces.addPlane(plane) if exist: - pp = Surfaces.getSurface(id) + pp = surfaces.getSurface(id) if isOposite(plane.Surf.Axis, pp.Surf.Axis, tol.pln_angle): id = -id - planesId.append(id) - return planesId + planes_id.append(id) + return planes_id -def addConePlane(Definition, conesList, Surfaces, UniverseBox): +def addConePlane(definition, cones_list, surfaces, universe_box): x_axis = FreeCAD.Vector(1, 0, 0) y_axis = FreeCAD.Vector(0, 1, 0) z_axis = FreeCAD.Vector(0, 0, 1) - for cid in conesList: - cone = Surfaces.getSurface(abs(cid)) + for cid in cones_list: + cone = surfaces.getSurface(abs(cid)) if ( isParallel(cone.Surf.Axis, x_axis, tol.angle) or isParallel(cone.Surf.Axis, y_axis, tol.angle) @@ -1182,16 +1185,16 @@ def addConePlane(Definition, conesList, Surfaces, UniverseBox): continue plane = GeounedSurface( - ("Plane", (cone.Surf.Apex, cone.Surf.Axis, 1, 1)), UniverseBox, Face="Build" + ("Plane", (cone.Surf.Apex, cone.Surf.Axis, 1, 1)), universe_box, Face="Build" ) - pid, exist = Surfaces.addPlane(plane) + pid, exist = surfaces.addPlane(plane) if exist: - p = Surfaces.getSurface(pid) + p = surfaces.getSurface(pid) if isOposite(plane.Surf.Axis, p.Surf.Axis, tol.pln_angle): pid = -pid if cid > 0: - insertInSequence(Definition, cid, -pid, "OR") + insertInSequence(definition, cid, -pid, "OR") else: - insertInSequence(Definition, cid, pid, "AND") + insertInSequence(definition, cid, pid, "AND") diff --git a/src/geouned/GEOUNED/Cuboid/translate.py b/src/geouned/GEOUNED/Cuboid/translate.py index 6cebfd35..72679024 100644 --- a/src/geouned/GEOUNED/Cuboid/translate.py +++ b/src/geouned/GEOUNED/Cuboid/translate.py @@ -21,16 +21,16 @@ def commonEdge(face1, face2): def isConvex(face1, face2, edge): de = 0.1 tol = 1.0e-5 - e = edge.Vertexes[1].Point - edge.Vertexes[0].Point - e.normalize() - V = e.cross(face2.Surface.Axis) + delta_point = edge.Vertexes[1].Point - edge.Vertexes[0].Point + delta_point.normalize() + axis = delta_point.cross(face2.Surface.Axis) - P = edge.CenterOfMass + de * V - if not face2.__face__.isInside(P, tol, True): - V = -V + point = edge.CenterOfMass + de * axis + if not face2.__face__.isInside(point, tol, True): + axis = -axis convex = False - if face1.Surface.Axis.dot(V) < 0: + if face1.Surface.Axis.dot(axis) < 0: if face1.Orientation == "Forward": convex = True else: @@ -48,9 +48,9 @@ def removeElement(Faces, idf): def isInverted(solid): face = solid.Faces[0] - Range = face.ParameterRange - u = (Range[1] + Range[0]) / 2.0 - v = (Range[3] + Range[2]) / 2.0 + parameter_range = face.ParameterRange + u = (parameter_range[1] + parameter_range[0]) / 2.0 + v = (parameter_range[3] + parameter_range[2]) / 2.0 point2 = face.CenterOfMass.add(face.normalAt(u, v).multiply(1.0e-6)) @@ -60,20 +60,20 @@ def isInverted(solid): return False -def getId(facein, Surfaces): +def getId(face_in, Surfaces): - if isParallel(facein.Axis, FreeCAD.Vector(1, 0, 0), tol.pln_angle): - P = "PX" - elif isParallel(facein.Axis, FreeCAD.Vector(0, 1, 0), tol.pln_angle): - P = "PY" - elif isParallel(facein.Axis, FreeCAD.Vector(0, 0, 1), tol.pln_angle): - P = "PZ" + if isParallel(face_in.Axis, FreeCAD.Vector(1, 0, 0), tol.pln_angle): + plane = "PX" + elif isParallel(face_in.Axis, FreeCAD.Vector(0, 1, 0), tol.pln_angle): + plane = "PY" + elif isParallel(face_in.Axis, FreeCAD.Vector(0, 0, 1), tol.pln_angle): + plane = "PZ" else: - P = "P" + plane = "P" - for s in Surfaces[P]: + for s in Surfaces[plane]: if BF.isSamePlane( - facein, + face_in, s.Surf, dtol=tol.pln_distance, atol=tol.pln_angle, @@ -84,12 +84,12 @@ def getId(facein, Surfaces): return 0 -def translate(MetaList, Surfaces, UniverseBox, setting): - totsolid = len(MetaList) - for i, m in enumerate(MetaList): +def translate(meta_list, surfaces, universe_box, setting): + tot_solid = len(meta_list) + for i, m in enumerate(meta_list): if m.IsEnclosure: continue - print("Decomposing solid: {}/{} ".format(i, totsolid)) + print("Decomposing solid: {}/{} ".format(i, tot_solid)) if setting["debug"]: print(m.Comments) if m.IsEnclosure: @@ -97,25 +97,25 @@ def translate(MetaList, Surfaces, UniverseBox, setting): else: m.Solids[0].exportStep("origSolid_{}.stp".format(i)) - Surfaces.extend( + surfaces.extend( Decom.ExtractSurfaces( - Part.makeCompound(m.Solids), "Plane3Pts", UniverseBox, MakeObj=False + Part.makeCompound(m.Solids), "Plane3Pts", universe_box, MakeObj=False ) ) - setDefinition(m, Surfaces) + setDefinition(m, surfaces) -def setDefinition(metaObj, Surfaces): - solids = metaObj.Solids - sDef = BoolSequence(operator="OR") +def setDefinition(meta_obj, surfaces): + solids = meta_obj.Solids + s_def = BoolSequence(operator="OR") for sol in solids: subSol = BoolSequence(operator="AND") flag_inv = isInverted(sol) - solid_GU = GU.SolidGu(sol, plane3Pts=True) + solid_gu = GU.SolidGu(sol, plane3Pts=True) - Faces = [] - for face in solid_GU.Faces: + faces = [] + for face in solid_gu.Faces: if abs(face.Area) < 1e-2: continue if face.Area < 0: @@ -127,37 +127,37 @@ def setDefinition(metaObj, Surfaces): if face.Orientation not in ("Forward", "Reversed"): continue - id = getId(face.Surface, Surfaces) - s = Surfaces.getSurface(id) + id = getId(face.Surface, surfaces) + s = surfaces.getSurface(id) if isOposite(face.Surface.Axis, s.Surf.Axis, tol.pln_angle): id = -id if face.Orientation == "Forward": id = -id if flag_inv: id = -id - Faces.append((id, face)) + faces.append((id, face)) - while len(Faces) > 0: - id1, face1 = Faces[0] - noConvex = [] - for id2, face2 in Faces[1:]: + while len(faces) > 0: + id1, face1 = faces[0] + no_convex = [] + for id2, face2 in faces[1:]: edge = commonEdge(face1, face2) if edge is None: continue if not isConvex(face1, face2, edge): - noConvex.append(id2) + no_convex.append(id2) - if noConvex != []: - noConvex.insert(0, id1) - for i in noConvex: - removeElement(Faces, i) + if no_convex != []: + no_convex.insert(0, id1) + for i in no_convex: + removeElement(faces, i) orPlanes = BoolSequence(operator="OR") - orPlanes.append(*noConvex) + orPlanes.append(*no_convex) subSol.append(orPlanes) else: - removeElement(Faces, id1) + removeElement(faces, id1) subSol.append(id1) - sDef.append(subSol) + s_def.append(subSol) - metaObj.setDefinition(sDef) + meta_obj.setDefinition(s_def) diff --git a/src/geouned/GEOUNED/Decompose/Decom_one.py b/src/geouned/GEOUNED/Decompose/Decom_one.py index 6a7f85de..50b39a8c 100644 --- a/src/geouned/GEOUNED/Decompose/Decom_one.py +++ b/src/geouned/GEOUNED/Decompose/Decom_one.py @@ -21,30 +21,30 @@ def splitFullCylinder(solid): explode = [] - Bases = [solid] + bases = [solid] while True: - newBases = [] - for base in Bases: - cutSolids = cutFullCylinder(base) - if len(cutSolids) == 1: - explode.extend(cutSolids) + new_bases = [] + for base in bases: + cut_solids = cutFullCylinder(base) + if len(cut_solids) == 1: + explode.extend(cut_solids) else: - newBases.extend(cutSolids) - if len(newBases) == 0: + new_bases.extend(cut_solids) + if len(new_bases) == 0: break else: - Bases = newBases + bases = new_bases return Part.makeCompound(explode) def cutFullCylinder(solid): - solid_GU = GU.SolidGu(solid) - Surfaces = UF.SurfacesDict() - flag_inv = CD.isInverted(solid_GU.solid) - UniverseBox = solid.BoundBox + solid_gu = GU.SolidGu(solid) + surfaces = UF.SurfacesDict() + flag_inv = CD.isInverted(solid_gu.solid) + universe_box = solid.BoundBox - for face in solid_GU.Faces: + for face in solid_gu.Faces: surf = str(face.Surface) if surf == "": if flag_inv: @@ -60,31 +60,31 @@ def cutFullCylinder(solid): dir = face.Surface.Axis orig = face.Surface.Center rad = face.Surface.Radius - dimL = face.ParameterRange[3] - face.ParameterRange[2] + dim_l = face.ParameterRange[3] - face.ParameterRange[2] cylinder = UF.GeounedSurface( - ("Cylinder", (orig, dir, rad, dimL)), UniverseBox + ("Cylinder", (orig, dir, rad, dim_l)), universe_box ) cylinder.buildSurface() - Surfaces.addCylinder(cylinder, False) + surfaces.addCylinder(cylinder, False) # add planes if cylinder axis is cut by a plane (plane quasi perpedicular to axis) - for p in CylBoundPlanes(face, UniverseBox): + for p in CylBoundPlanes(face, universe_box): p.buildSurface() - Surfaces.addPlane(p, False) + surfaces.addPlane(p, False) break - Planes = [] + planes = [] for P in ("PX", "PY", "PZ", "P"): - Planes.extend(Surfaces[P]) - Planes = sortPlanes(Planes, True) + planes.extend(surfaces[P]) + planes = sortPlanes(planes, True) - if len(Planes) == 0: + if len(planes) == 0: return [solid] - if len(Planes[-1]) < opt.nPlaneReverse: - Planes.reverse() + if len(planes[-1]) < opt.nPlaneReverse: + planes.reverse() cut = False - for pp in Planes: + for pp in planes: # cut with more external parallel planes pp[0].buildSurface() if len(pp) != 1: @@ -98,25 +98,25 @@ def cutFullCylinder(solid): except: comsolid = solid if len(comsolid.Solids) > 1: - outSolid = comsolid.Solids + out_solid = comsolid.Solids cut = True break if cut: - return outSolid + return out_solid - tool = (Surfaces["Cyl"][0].shape,) + tool = (surfaces["Cyl"][0].shape,) try: comsolid = UF.splitBOP(solid, tool, opt.splitTolerance) except: comsolid = solid if len(comsolid.Solids) > 1: - outSolid = comsolid.Solids + out_solid = comsolid.Solids else: - outSolid = [solid] + out_solid = [solid] - return outSolid + return out_solid def GenPlane(pos, normal, diag): @@ -201,37 +201,37 @@ def PlaneSplineCurve(edge): normal = edge.derivative1At(0).cross(edge.derivative1At(0.5)) normal.normalize() - curve2D = True + curve_2d = True for p in (0.25, 0.75, 1): # check if derivative orthogonal to curve normal vector if abs(normal.dot(edge.derivative1At(p))) > tol.value: - curve2D = False + curve_2d = False break r = edge.valueAt(0.25) - edge.valueAt(0.75) - if curve2D: + if curve_2d: return (edge.valueAt(0), normal, r.Length, r.Length) else: return None -def ExtractSurfaces(solid, kind, UniverseBox, MakeObj=False): +def ExtractSurfaces(solid, kind, universe_box, MakeObj=False): if kind == "All": fuzzy = True - solidParts = [] + solid_parts = [] for s in solid.Solids: - solidParts.append(GU.SolidGu(s)) + solid_parts.append(GU.SolidGu(s)) else: fuzzy = False if kind == "Plane3Pts": P3P = True else: P3P = False - solidParts = [GU.SolidGu(solid, P3P)] + solid_parts = [GU.SolidGu(solid, P3P)] - Surfaces = UF.SurfacesDict() + surfaces = UF.SurfacesDict() - for solid_GU in solidParts: + for solid_GU in solid_parts: # Get the parameter of all faces of the solid # Add auxillary planes for Cylinders and Cones @@ -243,65 +243,65 @@ def ExtractSurfaces(solid, kind, UniverseBox, MakeObj=False): dim1 = face.ParameterRange[1] - face.ParameterRange[0] dim2 = face.ParameterRange[3] - face.ParameterRange[2] plane = UF.GeounedSurface( - ("Plane", (pos, normal, dim1, dim2)), UniverseBox + ("Plane", (pos, normal, dim1, dim2)), universe_box ) if MakeObj: plane.buildSurface() - Surfaces.addPlane(plane, fuzzy) + surfaces.addPlane(plane, fuzzy) elif surf == "": dir = face.Surface.Axis orig = face.Surface.Center rad = face.Surface.Radius - dimL = face.ParameterRange[3] - face.ParameterRange[2] + dim_l = face.ParameterRange[3] - face.ParameterRange[2] if kind in ["Cyl", "All"]: cylinder = UF.GeounedSurface( - ("Cylinder", (orig, dir, rad, dimL)), UniverseBox + ("Cylinder", (orig, dir, rad, dim_l)), universe_box ) if MakeObj: cylinder.buildSurface() - Surfaces.addCylinder(cylinder, fuzzy) + surfaces.addCylinder(cylinder, fuzzy) if kind in ["Planes", "All"]: # add planes if cylinder axis is cut by a plane (plane quasi perpedicular to axis) - for p in CylBoundPlanes(face, UniverseBox): + for p in CylBoundPlanes(face, universe_box): if MakeObj: p.buildSurface() - Surfaces.addPlane(p) + surfaces.addPlane(p) elif surf == "": dir = face.Surface.Axis apex = face.Surface.Apex - halfAngle = face.Surface.SemiAngle - dimL = face.ParameterRange[3] - face.ParameterRange[2] + half_angle = face.Surface.SemiAngle + dim_l = face.ParameterRange[3] - face.ParameterRange[2] dimR = face.Surface.Radius if kind in ["Cone", "All"]: cone = UF.GeounedSurface( - ("Cone", (apex, dir, halfAngle, dimL, dimR)), UniverseBox + ("Cone", (apex, dir, half_angle, dim_l, dimR)), universe_box ) if MakeObj: cone.buildSurface() - Surfaces.addCone(cone) + surfaces.addCone(cone) if kind in ["Planes", "All"]: - for p in CylBoundPlanes(face, UniverseBox): + for p in CylBoundPlanes(face, universe_box): if MakeObj: p.buildSurface() - Surfaces.addPlane(p) + surfaces.addPlane(p) elif surf[0:6] == "Sphere" and kind in ["Sph", "All"]: rad = face.Surface.Radius pnt = face.Surface.Center - sphere = UF.GeounedSurface(("Sphere", (pnt, rad)), UniverseBox) + sphere = UF.GeounedSurface(("Sphere", (pnt, rad)), universe_box) if MakeObj: sphere.buildSurface() - Surfaces.addSphere(sphere) + surfaces.addSphere(sphere) if kind in ["Planes", "All"]: - for p in CylBoundPlanes(face, UniverseBox): + for p in CylBoundPlanes(face, universe_box): if MakeObj: p.buildSurface() - Surfaces.addPlane(p) + surfaces.addPlane(p) elif surf == "": if kind in ["Tor", "All"]: @@ -310,17 +310,17 @@ def ExtractSurfaces(solid, kind, UniverseBox, MakeObj=False): center = face.Surface.Center dir = face.Surface.Axis torus = UF.GeounedSurface( - ("Torus", (center, dir, radMaj, radMin)), UniverseBox + ("Torus", (center, dir, radMaj, radMin)), universe_box ) if MakeObj: torus.buildSurface() - Surfaces.addTorus(torus) + surfaces.addTorus(torus) if kind in ["Planes", "All"]: - for p in TorusBoundPlanes(face, UniverseBox): + for p in TorusBoundPlanes(face, universe_box): if MakeObj: p.buildSurface() - Surfaces.addPlane(p) + surfaces.addPlane(p) elif surf == "" and kind == "Plane3Pts": pos = face.CenterOfMass @@ -330,13 +330,13 @@ def ExtractSurfaces(solid, kind, UniverseBox, MakeObj=False): points = tuple(v.Point for v in face.Vertexes) plane = UF.GeounedSurface( - ("Plane3Pts", (pos, normal, dim1, dim2, points)), UniverseBox + ("Plane3Pts", (pos, normal, dim1, dim2, points)), universe_box ) if MakeObj: plane.buildSurface() - Surfaces.addPlane(plane, fuzzy) + surfaces.addPlane(plane, fuzzy) - return Surfaces + return surfaces def isAlreadyInPlanes(plane, Array): @@ -692,14 +692,14 @@ def Plane2ndOrder(solid_GU, face, flag_inv, convex=True): return planes -def SplitPlanes(Solids, UniverseBox, newVersion=True): +def SplitPlanes(Solids, universe_box, newVersion=True): if newVersion: - return SplitPlanes_new(Solids, UniverseBox) + return SplitPlanes_new(Solids, universe_box) else: - return SplitPlanes_org(Solids, UniverseBox) + return SplitPlanes_org(Solids, universe_box) -def SplitPlanes_new(Solids, UniverseBox): +def SplitPlanes_new(Solids, universe_box): Bases = Solids[:] simpleSolid = [] @@ -707,11 +707,11 @@ def SplitPlanes_new(Solids, UniverseBox): while True: newBases = [] for base in Bases: - cutSolids = splitPPlanes_new(base, UniverseBox) - if len(cutSolids) == 1: - simpleSolid.extend(cutSolids) + cut_solids = splitPPlanes_new(base, universe_box) + if len(cut_solids) == 1: + simpleSolid.extend(cut_solids) else: - newBases.extend(cutSolids) + newBases.extend(cut_solids) if len(newBases) == 0: break else: @@ -720,7 +720,7 @@ def SplitPlanes_new(Solids, UniverseBox): return simpleSolid, 0 -def SplitPlanes_org(Solids, UniverseBox): +def SplitPlanes_org(Solids, universe_box): Bases = [] err = 0 for sol in Solids: @@ -737,7 +737,7 @@ def SplitPlanes_org(Solids, UniverseBox): base = item[0] index = item[1] - SPlanes = ExtractSurfaces(base, "Planes", UniverseBox, MakeObj=True) + SPlanes = ExtractSurfaces(base, "Planes", universe_box, MakeObj=True) Planes = [SPlanes["PX"], SPlanes["PY"], SPlanes["PZ"]] for i in index: del Planes[i] @@ -798,11 +798,11 @@ def SplitPlanes_org(Solids, UniverseBox): while True: newBases = [] for base in Bases: - cutSolids = splitPPlanes_org(base, UniverseBox) - if len(cutSolids) == 1: - simpleSolid.extend(cutSolids) + cut_solids = splitPPlanes_org(base, universe_box) + if len(cut_solids) == 1: + simpleSolid.extend(cut_solids) else: - newBases.extend(cutSolids) + newBases.extend(cut_solids) if len(newBases) == 0: break else: @@ -864,8 +864,8 @@ def sortPlanes(PlaneList, sortElements=False): return sortedPlanes -def splitPPlanes_new(solid, UniverseBox): - SPlanes = ExtractSurfaces(solid, "Planes", UniverseBox) +def splitPPlanes_new(solid, universe_box): + SPlanes = ExtractSurfaces(solid, "Planes", universe_box) Planes = [] for P in ("PX", "PY", "PZ", "P"): @@ -877,7 +877,7 @@ def splitPPlanes_new(solid, UniverseBox): return [solid] if len(Planes[-1]) < opt.nPlaneReverse: Planes.reverse() - outSolid = [solid] + out_solid = [solid] for pp in Planes: for p in pp: p.buildSurface() @@ -885,27 +885,27 @@ def splitPPlanes_new(solid, UniverseBox): comsolid = UF.splitBOP(solid, tools, opt.splitTolerance) if len(comsolid.Solids) > 1: - outSolid = comsolid.Solids + out_solid = comsolid.Solids break - return outSolid + return out_solid -def splitPPlanes_org(solid, UniverseBox): - SPlanes = ExtractSurfaces(solid, "Planes", UniverseBox) +def splitPPlanes_org(solid, universe_box): + SPlanes = ExtractSurfaces(solid, "Planes", universe_box) if len(SPlanes["P"]) == 0: return [solid] - outSolid = [solid] + out_solid = [solid] for p in SPlanes["P"]: p.buildSurface() comsolid = UF.splitBOP(solid, [p.shape], opt.splitTolerance) if len(comsolid.Solids) > 1: - outSolid = comsolid.Solids + out_solid = comsolid.Solids break - return outSolid + return out_solid -def Split2ndOrder(Solids, UniverseBox): +def Split2ndOrder(Solids, universe_box): err = 0 Base = Solids for kind in ["Cyl", "Cone", "Sph", "Tor"]: @@ -913,7 +913,7 @@ def Split2ndOrder(Solids, UniverseBox): while True: cutBase = [] for solid in Base: - Surfaces = ExtractSurfaces(solid, kind, UniverseBox) + Surfaces = ExtractSurfaces(solid, kind, universe_box) if len(Surfaces[kind]) == 0: kindBase.append(solid) else: @@ -959,11 +959,11 @@ def Split2ndOrderPlanes(Solids): while True: newBases = [] for base in Bases: - cutSolids, err = split2ndOPlane(base) - if len(cutSolids) == 1: - simpleSolid.extend(cutSolids) + cut_solids, err = split2ndOPlane(base) + if len(cut_solids) == 1: + simpleSolid.extend(cut_solids) else: - newBases.extend(cutSolids) + newBases.extend(cut_solids) if len(newBases) == 0: break else: @@ -1013,7 +1013,7 @@ def removeSolids(Solids): return Solids_Clean, err -def splitComponent(solidShape, UniverseBox): +def splitComponent(solidShape, universe_box): err = 0 err2 = 0 @@ -1021,10 +1021,10 @@ def splitComponent(solidShape, UniverseBox): Solids = solidShape.Solids # Split with explicit planes bounding the solid and # implicit planes interface of two 2nd order surfaces - split0, err = SplitPlanes(Solids, UniverseBox, opt.newSplitPlane) + split0, err = SplitPlanes(Solids, universe_box, opt.newSplitPlane) # Split with explicit 2nd order surfaces bounding the solid - split1, err1 = Split2ndOrder(split0, UniverseBox) + split1, err1 = Split2ndOrder(split0, universe_box) err += err1 split, err2 = Split2ndOrderPlanes(split1) @@ -1054,14 +1054,14 @@ def splitComponent(solidShape, UniverseBox): return comsolid, err -def SplitSolid(solidShape, UniverseBox): +def SplitSolid(solidShape, universe_box): - solidParts = [] + solid_parts = [] for solid in solidShape.Solids: explode = splitFullCylinder(solid) - piece, err = splitComponent(explode, UniverseBox) - solidParts.append(piece) + piece, err = splitComponent(explode, universe_box) + solid_parts.append(piece) - return Part.makeCompound(solidParts), err + return Part.makeCompound(solid_parts), err diff --git a/src/geouned/GEOUNED/LoadFile/LoadFunctions.py b/src/geouned/GEOUNED/LoadFile/LoadFunctions.py index 56066a62..eb733eca 100644 --- a/src/geouned/GEOUNED/LoadFile/LoadFunctions.py +++ b/src/geouned/GEOUNED/LoadFile/LoadFunctions.py @@ -20,62 +20,62 @@ def GetLabel(label): def getCommentTree(obj): - recursiveList = [] - cObj = obj - while cObj.InList: - label = GetLabel(cObj.InList[0].Label) - recursiveList.append(label) - cObj = cObj.InList[0] + recursive_list = [] + c_obj = obj + while c_obj.InList: + label = GetLabel(c_obj.InList[0].Label) + recursive_list.append(label) + c_obj = c_obj.InList[0] comment = "" - for label in reversed(recursiveList): + for label in reversed(recursive_list): comment += "/" + label return comment -def joinEnvelopes(MetaList): - joinList = [] - oldID = -1 - newlist = [] - for i, m in enumerate(MetaList): +def joinEnvelopes(meta_list): + join_list = [] + old_id = -1 + new_list = [] + for i, m in enumerate(meta_list): if m.CellType != "envelope": continue - if m.EnclosureID != oldID: - joinList.append(newlist) - newlist = [i] - oldID = m.EnclosureID + if m.EnclosureID != old_id: + join_list.append(new_list) + new_list = [i] + old_id = m.EnclosureID else: - newlist.append(i) + new_list.append(i) - joinList.append(newlist) - del joinList[0] + join_list.append(new_list) + del join_list[0] - for IDlist in joinList: - fuseMetaObj(MetaList, IDlist[0], IDlist[-1] + 1) + for id_list in join_list: + fuseMetaObj(meta_list, id_list[0], id_list[-1] + 1) -def fuseMetaObj(MetaList, init, end): +def fuseMetaObj(meta_list, init, end): if end - init == 1: - MetaList[init].__id__ = init + 1 + meta_list[init].__id__ = init + 1 return solids = [] - for m in MetaList[init:end]: + for m in meta_list[init:end]: solids.extend(m.Solids) - newMeta = GeounedSolid(init + 1, solids) - newMeta.EnclosureID = MetaList[init].EnclosureID - newMeta.ParentEnclosureID = MetaList[init].ParentEnclosureID - newMeta.IsEnclosure = MetaList[init].IsEnclosure - newMeta.CellType = MetaList[init].CellType + new_meta = GeounedSolid(init + 1, solids) + new_meta.EnclosureID = meta_list[init].EnclosureID + new_meta.ParentEnclosureID = meta_list[init].ParentEnclosureID + new_meta.IsEnclosure = meta_list[init].IsEnclosure + new_meta.CellType = meta_list[init].CellType - del MetaList[init:end] - MetaList.insert(init, newMeta) + del meta_list[init:end] + meta_list.insert(init, new_meta) # Paco mod -def checkCADFileMaterial(Material, mdict): +def checkCADFileMaterial(material, mdict): """Function to check that if a component in the CAD file has a material, it exist in the material file""" - templist = [elem for elem in set(Material) if elem not in mdict] + templist = [elem for elem in set(material) if elem not in mdict] if templist: raise ValueError( "At least one material in the CAD model is not present in the material file\n" @@ -86,52 +86,52 @@ def checkCADFileMaterial(Material, mdict): # Paco mod -def setEnclosureSolidList(MetaList): +def setEnclosureSolidList(meta_list): """Function to define DataList list.""" - return [elem for elem in MetaList if elem.IsEnclosure] + return [elem for elem in meta_list if elem.IsEnclosure] -def RemoveEnclosure(MetaList): - """This function removes Enclosure solid and actualises __id__ attributes to take into account the removal from MetaList list of nested enclosures originally loaded from CAD model.""" +def RemoveEnclosure(meta_list): + """This function removes Enclosure solid and actualises __id__ attributes to take into account the removal from meta_list list of nested enclosures originally loaded from CAD model.""" # update id of solids - lenMetaList = len(MetaList) - icount = 0 - for i, m in enumerate(MetaList): + len_meta_list = len(meta_list) + i_count = 0 + for i, m in enumerate(meta_list): if m.IsEnclosure: - icount += 1 + i_count += 1 else: - MetaList[i].__id__ -= icount + meta_list[i].__id__ -= i_count # remove Enclosure solids from metaList - for i in range(lenMetaList - 1, -1, -1): - if MetaList[i].IsEnclosure: - MetaList.pop(i) + for i in range(len_meta_list - 1, -1, -1): + if meta_list[i].IsEnclosure: + meta_list.pop(i) -def setEnclosureLevels(EnclosureList): - nestedList = [[0], []] - nestedEnclosure = [[]] - parentLevel = 0 - tempList = EnclosureList[:] +def setEnclosureLevels(enclosure_list): + nested_list = [[0], []] + nested_enclosure = [[]] + parent_level = 0 + temp_list = enclosure_list[:] - while len(tempList) > 0: + while len(temp_list) > 0: remove = [] - for i, encl in enumerate(tempList): - if encl.ParentEnclosureID in nestedList[parentLevel]: - nestedList[parentLevel + 1].append(encl.EnclosureID) - nestedEnclosure[parentLevel].append(encl) + for i, encl in enumerate(temp_list): + if encl.ParentEnclosureID in nested_list[parent_level]: + nested_list[parent_level + 1].append(encl.EnclosureID) + nested_enclosure[parent_level].append(encl) remove.append(i) - nestedList.append([]) - nestedEnclosure.append([]) - parentLevel += 1 + nested_list.append([]) + nested_enclosure.append([]) + parent_level += 1 remove.reverse() for i in remove: - del tempList[i] + del temp_list[i] - nestedEnclosureList = [] - for Level in nestedEnclosure: + nested_enclosure_list = [] + for Level in nested_enclosure: temp = [] for i, encl in enumerate(Level): temp.append((encl.ParentEnclosureID, i)) @@ -140,25 +140,25 @@ def setEnclosureLevels(EnclosureList): grouped = [] for t in temp: grouped.append(Level[t[1]]) - nestedEnclosureList.append(grouped) + nested_enclosure_list.append(grouped) - for i, Level in enumerate(nestedEnclosureList[0:-1]): + for i, Level in enumerate(nested_enclosure_list[0:-1]): for encl in Level: - childList = [] - for child in nestedEnclosureList[i + 1]: + child_list = [] + for child in nested_enclosure_list[i + 1]: if child.ParentEnclosureID == encl.EnclosureID: - childList.append(child) - encl.SonEnclosures = childList[:] + child_list.append(child) + encl.SonEnclosures = child_list[:] - return nestedEnclosureList + return nested_enclosure_list -def checkEnclosure(FreeCAD_doc, EnclosureList): +def checkEnclosure(freecad_doc, enclosure_list): stop = False # check all enclosure labels have an associated solid - TempList = [] - for elem in FreeCAD_doc.Objects: + temp_list = [] + for elem in freecad_doc.Objects: if elem.TypeId == "Part::Feature": if elem.Shape.Solids: if elem.InList: @@ -171,16 +171,16 @@ def checkEnclosure(FreeCAD_doc, EnclosureList): elem.TypeId == "Part::Feature" and len(elem.Shape.Solids) == 0 ): - TempList.append(elem) + temp_list.append(elem) - if TempList: + if temp_list: stop = True print( "One or more nested enclosure labels in CAD solid tree view/structure tree do not have any CAD solid.\n", "Each nested enclosure must have only one solid.\nCode STOPS.", "\nList of problematic nested enclosure labels:", ) - for elem in TempList: + for elem in temp_list: print(elem.EnclosureID) # check enclosure Labels don't make loops @@ -189,27 +189,27 @@ def checkEnclosure(FreeCAD_doc, EnclosureList): # 2) check 0 is not in child enclosure label # 3) check child enclosure label is not repeated - SIDList = [] - PIDSet = set() - repeatedID = set() + sid_list = [] + pid_set = set() + repeated_id = set() - for encl in EnclosureList: - PIDSet.add(encl.ParentEnclosureID) - if encl.EnclosureID in SIDList: - repeatedID.add(encl.EnclosureID) + for encl in enclosure_list: + pid_set.add(encl.ParentEnclosureID) + if encl.EnclosureID in sid_list: + repeated_id.add(encl.EnclosureID) else: - SIDList.append(encl.EnclosureID) + sid_list.append(encl.EnclosureID) - if 0 in SIDList: + if 0 in sid_list: stop = True print('"0" cannot be label on child Enclosure') - if 0 not in PIDSet: + if 0 not in pid_set: stop = True print(' "0" should parent label of most external enclosure(s)') - if repeatedID: + if repeated_id: stop = True print("Child label cannot be repeated.\nRepeated labels :") - for lab in repeatedID: + for lab in repeated_id: print(lab) # this stop should not be move to the end of routine @@ -218,60 +218,60 @@ def checkEnclosure(FreeCAD_doc, EnclosureList): raise ValueError("Exiting to avoid infinite loop") # 4) look for explicit loops - enclDict = dict() - for encl in EnclosureList: - if encl.ParentEnclosureID in enclDict.keys(): - enclDict[encl.ParentEnclosureID].append(encl.EnclosureID) + encl_dict = dict() + for encl in enclosure_list: + if encl.ParentEnclosureID in encl_dict.keys(): + encl_dict[encl.ParentEnclosureID].append(encl.EnclosureID) else: - enclDict[encl.ParentEnclosureID] = [encl.EnclosureID] + encl_dict[encl.ParentEnclosureID] = [encl.EnclosureID] parent = [0] cont = True while cont: cont = False - nextParent = [] + next_parent = [] for p in parent: - if p in enclDict.keys(): + if p in encl_dict.keys(): cont = True - nextParent.extend(enclDict[p]) - del enclDict[p] - parent = nextParent + next_parent.extend(encl_dict[p]) + del encl_dict[p] + parent = next_parent - if enclDict.keys(): + if encl_dict.keys(): print("Following enclosure produce loop") - for p in enclDict.keys(): - for s in enclDict[p]: + for p in encl_dict.keys(): + for s in encl_dict[p]: print("{}_{}".format(s, p)) raise ValueError("GEOUNED.LoadFunctions.checkEnclosure failed") # check enclosures solids are correctly nested and don't overlap each other - nestedLevels = setEnclosureLevels(EnclosureList) + nested_levels = setEnclosureLevels(enclosure_list) overlap = [] - enclTree = [[0]] - for level in nestedLevels: - enclTree = updateTree(enclTree, level) + encl_tree = [[0]] + for level in nested_levels: + encl_tree = updateTree(encl_tree, level) for encl in level: - sameParent = dict() - if encl.ParentEnclosureID in sameParent.keys(): - sameParent[encl.ParentEnclosureID].append(encl.EnclosureID) + same_parent = dict() + if encl.ParentEnclosureID in same_parent.keys(): + same_parent[encl.ParentEnclosureID].append(encl.EnclosureID) else: - sameParent[encl.ParentEnclosureID] = [encl.EnclosureID] - for encl in sameParent.values(): + same_parent[encl.ParentEnclosureID] = [encl.EnclosureID] + for encl in same_parent.values(): overlap.extend(checkOverlap(encl)) - notEmbedded = [] - for chain in enclTree: + not_embedded = [] + for chain in encl_tree: up = chain[0] for low in chain[1:]: inter = up.checkIntersection(low.CADSolid) if inter != -2: - notEmbedded.append((low.EnclosureID, up.EnclosureID)) + not_embedded.append((low.EnclosureID, up.EnclosureID)) - if notEmbedded: + if not_embedded: stop = True print(" Following enclosures are not fully embedded in Parent enclosure") - for elemt in notEmbedded: + for elemt in not_embedded: print("{}_{}").format(elemt[0], elemt[1]) if overlap: @@ -295,13 +295,13 @@ def checkOverlap(enclosures): def updateTree(Tree, level): - newTree = [] + new_tree = [] for encl in level: for lst in Tree: if lst[-1] == encl.ParentEnclosureID: - newTree.append(lst + [encl.EnclosureID]) + new_tree.append(lst + [encl.EnclosureID]) continue - return newTree + return new_tree def set_docOptions(): diff --git a/src/geouned/GEOUNED/LoadFile/LoadSTEP.py b/src/geouned/GEOUNED/LoadFile/LoadSTEP.py index 03e4732f..221925ef 100644 --- a/src/geouned/GEOUNED/LoadFile/LoadSTEP.py +++ b/src/geouned/GEOUNED/LoadFile/LoadSTEP.py @@ -14,51 +14,51 @@ # Paco mod def extractMaterials(filename): - rhoreal = [] - mdict = {} # _ Material dictionary + rho_real = [] + m_dict = {} # _ Material dictionary with open(filename, "rt") as file: for line in file: vals = line.split() if vals[0].startswith("#"): continue - matlabel = int(vals[0]) - rhoreal = -float(vals[1]) + mat_label = int(vals[0]) + rho_real = -float(vals[1]) matname = " ".join(vals[2:]) - mdict[matlabel] = (rhoreal, matname) - return mdict + m_dict[mat_label] = (rho_real, matname) + return m_dict -def LoadCAD(filename, matfilename, defaultMat=[], compSolids=True): +def LoadCAD(filename, mat_filename, default_mat=[], comp_solids=True): # Set document solid tree options when opening CAD differing from version 0.18 if int(FreeCAD.Version()[1]) > 18: LF.set_docOptions() - CAD_simplificado_doc = FreeCAD.newDocument("CAD_simplificado") + cad_simplificado_doc = FreeCAD.newDocument("CAD_simplificado") Import.insert(filename, "CAD_simplificado") - if matfilename != "": - if os.path.exists(matfilename): - mdict = extractMaterials(matfilename) + if mat_filename != "": + if os.path.exists(mat_filename): + m_dict = extractMaterials(mat_filename) else: - print("Material definition file {} does not exist.".format(matfilename)) - mdict = {} + print("Material definition file {} does not exist.".format(mat_filename)) + m_dict = {} else: - mdict = {} + m_dict = {} s = Part.Shape() s.read(filename) Solids = s.Solids - MetaList = [] + meta_list = [] for i, s in enumerate(Solids): - MetaList.append(UF.GeounedSolid(i + 1, s)) + meta_list.append(UF.GeounedSolid(i + 1, s)) - isolid = 0 - missingMat = set() + i_solid = 0 + missing_mat = set() - docObjects = CAD_simplificado_doc.Objects + doc_objects = cad_simplificado_doc.Objects - for elem in docObjects: + for elem in doc_objects: if elem.TypeId == "Part::Feature": comment = LF.getCommentTree(elem) if not elem.Shape.Solids: @@ -69,126 +69,126 @@ def LoadCAD(filename, matfilename, defaultMat=[], compSolids=True): ) continue else: - tempremat = None - tempredil = None + tempre_mat = None + tempre_dil = None # MIO: lightly modification of label if required label = LF.GetLabel(elem.Label) comment = comment + "/" + label if elem.InList: # MIO: lightly modification of label if required - label_inList = LF.GetLabel(elem.InList[0].Label) - enclLabel = re.search( - "enclosure(?P[0-9]+)_(?P[0-9]+)_", label_inList + label_in_list = LF.GetLabel(elem.InList[0].Label) + encl_label = re.search( + "enclosure(?P[0-9]+)_(?P[0-9]+)_", label_in_list ) - if not enclLabel: - enclLabel = re.search( + if not encl_label: + encl_label = re.search( "enclosure(?P[0-9]+)_(?P[0-9]+)_", label ) - envelLabel = re.search( - "envelope(?P[0-9]+)_(?P[0-9]+)_", label_inList + envel_label = re.search( + "envelope(?P[0-9]+)_(?P[0-9]+)_", label_in_list ) - if not envelLabel: - envelLabel = re.search( + if not envel_label: + envel_label = re.search( "envelope(?P[0-9]+)_(?P[0-9]+)_", label ) - # tempremat = re.search("(m(?P\d+)_)",elem.Label) - # if not tempremat : - # tempremat = re.search("(m(?P\d+)_)",elem.InList[0].Label) + # tempre_mat = re.search("(m(?P\d+)_)",elem.Label) + # if not tempre_mat : + # tempre_mat = re.search("(m(?P\d+)_)",elem.InList[0].Label) - # tempredil = re.search("(_d(?P\d*\.\d*)_)",elem.Label) - # if not tempredil : - # tempredil = re.search("(_d(?P\d*\.\d*)_)",elem.InList[0].Label) + # tempre_dil = re.search("(_d(?P\d*\.\d*)_)",elem.Label) + # if not tempre_dil : + # tempre_dil = re.search("(_d(?P\d*\.\d*)_)",elem.InList[0].Label) # Paco modifications # Search for material definition in tree xelem = [elem] - while xelem and not tempremat: + while xelem and not tempre_mat: # MIO: Modification of label if required temp_label = LF.GetLabel(xelem[0].Label) - tempremat = re.search("_m(?P\d+)_", "_" + temp_label) + tempre_mat = re.search("_m(?P\d+)_", "_" + temp_label) xelem = xelem[0].InList # Search for dilution definition in tree xelem = [elem] - while xelem and not tempredil: + while xelem and not tempre_dil: # MIO: Modification of label if required temp_label = LF.GetLabel(xelem[0].Label) - tempredil = re.search("_d(?P\d*\.\d*)_", temp_label) + tempre_dil = re.search("_d(?P\d*\.\d*)_", temp_label) xelem = xelem[0].InList # Paco end else: - enclLabel = None - envelLabel = None + encl_label = None + envel_label = None # compSolid Diferent solid of the same cell are stored in the same metaObject (compSolid) # enclosures and envelopes are always stored as compound - if compSolids or enclLabel or envelLabel: + if comp_solids or encl_label or envel_label: - init = isolid - end = isolid + len(elem.Shape.Solids) - LF.fuseMetaObj(MetaList, init, end) - nsolids = 1 + init = i_solid + end = i_solid + len(elem.Shape.Solids) + LF.fuseMetaObj(meta_list, init, end) + n_solids = 1 else: - nsolids = len(elem.Shape.Solids) + n_solids = len(elem.Shape.Solids) - for i in range(nsolids): - MetaList[isolid].setComments("{}{}".format(comment, (i + 1))) - MetaList[isolid].setCADSolid() + for i in range(n_solids): + meta_list[i_solid].setComments("{}{}".format(comment, (i + 1))) + meta_list[i_solid].setCADSolid() - if tempremat: - matlabel = int(tempremat.group("mat")) - if matlabel in mdict.keys(): - MetaList[isolid].setMaterial( - matlabel, mdict[matlabel][0], mdict[matlabel][1] + if tempre_mat: + mat_label = int(tempre_mat.group("mat")) + if mat_label in m_dict.keys(): + meta_list[i_solid].setMaterial( + mat_label, m_dict[mat_label][0], m_dict[mat_label][1] ) else: - if matlabel == 0: - MetaList[isolid].setMaterial(matlabel, 0, 0) + if mat_label == 0: + meta_list[i_solid].setMaterial(mat_label, 0, 0) else: - MetaList[isolid].setMaterial( - matlabel, + meta_list[i_solid].setMaterial( + mat_label, -100, "Missing material density information", ) - missingMat.add(matlabel) + missing_mat.add(mat_label) else: # print('Warning : No material label associated to solid {}.\nDefault material used instead.'.format(comment)) - if defaultMat: - MetaList[isolid].setMaterial(*defaultMat) - if tempredil: - MetaList[isolid].setDilution(float(tempredil.group("dil"))) - - if enclLabel is not None: - MetaList[isolid].EnclosureID = int(enclLabel.group("encl")) - MetaList[isolid].ParentEnclosureID = int( - enclLabel.group("parent") + if default_mat: + meta_list[i_solid].setMaterial(*default_mat) + if tempre_dil: + meta_list[i_solid].setDilution(float(tempre_dil.group("dil"))) + + if encl_label is not None: + meta_list[i_solid].EnclosureID = int(encl_label.group("encl")) + meta_list[i_solid].ParentEnclosureID = int( + encl_label.group("parent") ) - MetaList[isolid].IsEnclosure = True - MetaList[isolid].CellType = "void" + meta_list[i_solid].IsEnclosure = True + meta_list[i_solid].CellType = "void" - if envelLabel is not None: - MetaList[isolid].EnclosureID = int(envelLabel.group("env")) - MetaList[isolid].ParentEnclosureID = int( - envelLabel.group("parent") + if envel_label is not None: + meta_list[i_solid].EnclosureID = int(envel_label.group("env")) + meta_list[i_solid].ParentEnclosureID = int( + envel_label.group("parent") ) - MetaList[isolid].IsEnclosure = True - MetaList[isolid].CellType = "envelope" - isolid += 1 + meta_list[i_solid].IsEnclosure = True + meta_list[i_solid].CellType = "envelope" + i_solid += 1 - LF.joinEnvelopes(MetaList) - if missingMat: + LF.joinEnvelopes(meta_list) + if missing_mat: print( "Warning!! At least one material in the CAD model is not present in the material file" ) - print("List of not present materials:", missingMat) + print("List of not present materials:", missing_mat) - EnclosureList = LF.setEnclosureSolidList(MetaList) - if EnclosureList: - LF.checkEnclosure(CAD_simplificado_doc, EnclosureList) - # LF.RemoveEnclosure(MetaList) - return MetaList, EnclosureList + enclosure_list = LF.setEnclosureSolidList(meta_list) + if enclosure_list: + LF.checkEnclosure(cad_simplificado_doc, enclosure_list) + # LF.RemoveEnclosure(meta_list) + return meta_list, enclosure_list else: - return MetaList, [] + return meta_list, []