main.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715
  1. import os
  2. import sys
  3. import comtypes.client
  4. import pandas as pd
  5. from shapely import points
  6. pd.set_option('future.no_silent_downcasting', True)
  7. import itertools
  8. import tkinter as tk
  9. from tkinter import *
  10. from tkinter import ttk, messagebox, scrolledtext
  11. from tkinter.filedialog import askopenfilename
  12. import math
  13. import numpy as np
  14. import warnings
  15. warnings.filterwarnings('ignore', category=UserWarning, module='openpyxl')
  16. import threading
  17. import time
  18. nombre_archivo = "resultados1.txt"
  19. f = open(nombre_archivo, "w")
  20. f.write("H\tb\ttf\ttw\tFrecuencia\tCoef_Impacto\tFlecha_38D\tFlecha_86E\tFlecha_Media\tArea\tIxg\tIyg\tImax\tImin\tPeso\n")
  21. f.close() # Limpiar el archivo al inicio
  22. class TimeoutException(Exception):
  23. pass
  24. def raise_timeout():
  25. raise TimeoutException()
  26. timer = threading.Timer(20.0, raise_timeout) #se crea un timer de 20 segundos
  27. timer.start()
  28. try:
  29. #Conexion con SAP2000
  30. helper = comtypes.client.CreateObject('SAP2000v1.Helper')
  31. helper = helper.QueryInterface(comtypes.gen.SAP2000v1.cHelper)
  32. mySapObject = helper.GetObject("CSI.SAP2000.API.SapObject")
  33. SapModel = mySapObject.SapModel
  34. if SapModel.GetModelisLocked(): SapModel.SetModelisLocked(False)
  35. except TimeoutException as exc:
  36. messagebox.showerror(
  37. "Error",
  38. "No se encuentra una instancia de SAP2000 abierta. Por favor, abra SAP2000 e intente de nuevo."
  39. )
  40. sys.exit(1)
  41. finally:
  42. timer.cancel()
  43. class SAPSectionDesignerGUI:
  44. def __init__(self):
  45. self.root = tk.Tk()
  46. self.root.title("Diseñador de Secciones SAP2000 - Python API")
  47. self.root.geometry("600x800")
  48. self.SapModel = None
  49. self.crear_interfaz()
  50. def crear_interfaz(self):
  51. # === Datos de la sección ===
  52. tk.Label(self.root, text="Datos de la Sección", font=("Arial", 12, "bold")).pack(pady=(20,5))
  53. frame_datos = tk.Frame(self.root)
  54. frame_datos.pack(pady=5, padx=20, fill="x")
  55. # Frame para parámetros fijos
  56. frame_fixed = ttk.LabelFrame(self.root, text="Parámetros Fijos", padding=5)
  57. frame_fixed.pack(fill=tk.X, pady=(0, 10))
  58. # Variables para toggle fijo/barrido
  59. self.sweep_toggle_vars = {}
  60. self.sweep_fixed_entries = {}
  61. self.sweep_range_entries = {}
  62. params_ipe = ['H', 'b', 'tf', 'tw']
  63. for param in params_ipe:
  64. container = ttk.Frame(frame_fixed)
  65. container.pack(pady=2)
  66. var = tk.BooleanVar(value=True)
  67. self.sweep_toggle_vars[param] = var
  68. chk = ttk.Checkbutton(container, text=f"Fijo: {param}", variable=var,
  69. command=lambda p=param: self.on_sweep_toggle(p))
  70. chk.pack(side=tk.LEFT, fill=tk.X, expand=True)
  71. entry = ttk.Spinbox(container, from_=0.0, to=1000.0, increment=0.001, width=10)
  72. entry.pack(side=tk.LEFT, padx=5)
  73. self.sweep_fixed_entries[param] = entry
  74. # Cargar valores actuales
  75. self.sweep_fixed_entries['H'].set("1.0")
  76. self.sweep_fixed_entries['b'].set("0.45")
  77. self.sweep_fixed_entries['tf'].set("0.01")
  78. self.sweep_fixed_entries['tw'].set("0.01")
  79. # Frame para parámetros a barrer
  80. frame_sweep = ttk.LabelFrame(self.root, text="Parámetros a Barrer", padding=5)
  81. frame_sweep.pack(fill=tk.X, pady=(0, 10))
  82. self.sweep_range_labels = {}
  83. self.sweep_range_entries = {}
  84. for param in params_ipe:
  85. container = ttk.Frame(frame_sweep)
  86. container.pack(fill=tk.X, pady=2)
  87. lbl = ttk.Label(container, text=f"{param}:", width=5)
  88. lbl.pack(side=tk.LEFT)
  89. self.sweep_range_labels[param] = lbl
  90. ttk.Label(container, text="min:").pack(side=tk.LEFT, padx=(10, 2))
  91. min_entry = ttk.Spinbox(container, from_=0.0, to=1000.0, increment=0.001, width=8)
  92. min_entry.pack(side=tk.LEFT, padx=2)
  93. ttk.Label(container, text="max:").pack(side=tk.LEFT, padx=(10, 2))
  94. max_entry = ttk.Spinbox(container, from_=0.0, to=1000.0, increment=0.001, width=8)
  95. max_entry.pack(side=tk.LEFT, padx=2)
  96. ttk.Label(container, text="pasos:").pack(side=tk.LEFT, padx=(10, 2))
  97. steps_entry = ttk.Spinbox(container, from_=2, to=20, increment=1, width=8)
  98. steps_entry.pack(side=tk.LEFT, padx=2)
  99. steps_entry.set(5)
  100. self.sweep_range_entries[param] = {
  101. 'min': min_entry,
  102. 'max': max_entry,
  103. 'steps': steps_entry
  104. }
  105. # Botones de control
  106. button_frame = ttk.Frame(self.root)
  107. button_frame.pack(fill=tk.X, pady=(10, 0))
  108. # === Botón Crear ===
  109. btn_crear = tk.Button(self.root, text="🚀 Crear Sección en Section Designer",
  110. command=self.execute_parametric_sweep, width=40, height=2,
  111. bg="#2196F3", fg="white", font=("Arial", 10, "bold"))
  112. btn_crear.pack(pady=20)
  113. tk.Label(self.root, text="Nota: Todas las unidades estan en [m].",
  114. fg="gray").pack()
  115. def on_sweep_toggle(self, param):
  116. """Alterna parámetro entre fijo y barrido"""
  117. is_fixed = self.sweep_toggle_vars[param].get()
  118. # Los rangos se mostrarán solo si no está fijo
  119. # Esta lógica se puede mejorar si es necesario
  120. def execute_parametric_sweep(self):
  121. """Ejecuta el barrido paramétrico"""
  122. if SapModel.GetModelisLocked(): SapModel.SetModelisLocked(False)
  123. try:
  124. # Recopilar configuración
  125. fixed_params = {}
  126. sweep_configs = {}
  127. for param in ['H', 'b', 'tf', 'tw']:
  128. is_fixed = self.sweep_toggle_vars[param].get()
  129. if is_fixed:
  130. value = float(self.sweep_fixed_entries[param].get())
  131. fixed_params[param] = value
  132. else:
  133. min_val = float(self.sweep_range_entries[param]['min'].get())
  134. max_val = float(self.sweep_range_entries[param]['max'].get())
  135. steps = int(self.sweep_range_entries[param]['steps'].get())
  136. if steps < 1:
  137. messagebox.showerror("Error", f"El número de pasos para {param} debe ser al menos 1")
  138. return
  139. if min_val <= 0:
  140. messagebox.showerror("Error", f"Valores de {param} deben ser positivos")
  141. return
  142. if min_val >= max_val:
  143. messagebox.showerror("Error", f"Rango inválido para {param}: min >= max")
  144. return
  145. sweep_configs[param] = {
  146. 'min': min_val,
  147. 'max': max_val,
  148. 'steps': steps
  149. }
  150. if not sweep_configs:
  151. messagebox.showerror("Error", "Debe barrer al menos un parámetro")
  152. return
  153. if not fixed_params:
  154. messagebox.showwarning("Advertencia", "No hay parámetros fijos")
  155. combinations = self.generar_matriz_sweep(sweep_configs, fixed_params)
  156. if not combinations:
  157. messagebox.showerror("Error", "No se generaron combinaciones para el barrido")
  158. return
  159. results = []
  160. for params in combinations:
  161. SapModel.SetModelisLocked(False)
  162. SapModel.SetPresentUnits(10) #unidades en niutons metros
  163. points_ipe = self.generate_ipe_points(params['H'], params['b'], params['tf'], params['tw'])
  164. properties_ipe = self.calculate_section_properties(points_ipe)
  165. points_hueco_inf = self.generate_hueco_inf_points(params['H'], params['b'], params['tf'], params['tw'])
  166. points_hueco_sup = self.generate_hueco_sup_points(params['H'], params['b'], params['tf'], params['tw'])
  167. points_completo = self.generate_completo_points(params['H'], params['b'], params['tf'], params['tw'])
  168. self.crear_seccion(points_ipe, tipo="ipe", nombre_poligono = "Polygon1")
  169. self.crear_seccion(points_hueco_inf, tipo="hueco", nombre_poligono = "Polygon1")
  170. self.crear_seccion(points_hueco_sup, tipo="hueco", nombre_poligono = "Polygon2")
  171. self.crear_seccion(points_completo, tipo="completo", nombre_poligono = "Polygon1")
  172. ret = SapModel.Analyze.RunAnalysis()
  173. frequency = self.obtain_frequency()
  174. coef_impacto = self.calc_coef_impacto(frequency)
  175. ret = SapModel.SetModelisLocked(False)
  176. ret = SapModel.LoadCases.StaticLinear.SetLoads("H3. Sobrecarga UIC 71", 1, ["Load"],
  177. ["H3. Sobrecarga UIC"], [coef_impacto])
  178. if ret[3] != 0:
  179. messagebox.showerror("Error de carga", f"Error al aplicar cargas para la combinación: {params}\nCódigo de error: {ret}")
  180. return
  181. ret = SapModel.Analyze.RunAnalysis()
  182. SapModel.SetPresentUnits(9) # Unidades niutons milimetos
  183. ret = SapModel.Results.Setup.DeselectAllCasesAndCombosForOutput()
  184. ret = SapModel.Results.Setup.SetComboSelectedForOutput("1. ENV ELS FREQ")
  185. FieldKeyList = []
  186. GroupName = 'All'
  187. TableVersion = 1
  188. FieldsKeysIncluded = []
  189. NumberRecords = 1
  190. TableData = []
  191. ret = SapModel.DatabaseTables.GetTableforDisplayArray("Joint Displacements", FieldKeyList, GroupName,
  192. TableVersion, FieldsKeysIncluded, NumberRecords, TableData)
  193. if ret[-1] != 0:
  194. messagebox.showerror("Error de resultados", f"Error al obtener resultados para la combinación: {params}\nCódigo de error: {ret}")
  195. return
  196. big_tuple = ret[4]
  197. items = list(big_tuple)
  198. filas = []
  199. j = 0
  200. while j < len(items):
  201. if j + 10 <= len(items):
  202. fila = items[j:j+10]
  203. filas.append(fila)
  204. j += 10
  205. else:
  206. break
  207. flecha1 = self.filtrar_por_joint(filas, "38D")
  208. flecha2 = self.filtrar_por_joint(filas, "86E")
  209. flecha_media = (flecha1 + flecha2) / 2
  210. f = open(nombre_archivo, "a")
  211. string = (f"{params['H'].item() if isinstance(params['H'], np.ndarray) else params['H']}\
  212. {params['b'].item() if isinstance(params['b'], np.ndarray) else params['b']}\
  213. {params['tf'].item() if isinstance(params['tf'], np.ndarray) else params['tf']}\
  214. {params['tw'].item() if isinstance(params['tw'], np.ndarray) else params['tw']}\
  215. {frequency}\
  216. {coef_impacto}\
  217. {flecha1}\
  218. {flecha2}\
  219. {flecha_media}\
  220. {properties_ipe['area'].item()}\
  221. {properties_ipe['ixg'].item()}\
  222. {properties_ipe['iyg'].item()}\
  223. {properties_ipe['imax'].item()}\
  224. {properties_ipe['imin'].item()}\
  225. {properties_ipe['peso'].item()}\n").replace(".", ",")
  226. f.write(string)
  227. f.close()
  228. return
  229. except Exception as e:
  230. messagebox.showerror("Error en configuración", f"Revisa los valores ingresados:\n{e}")
  231. return
  232. def filtrar_por_joint(self, filas, joint_id):
  233. for fila in filas:
  234. if fila[0] == joint_id and fila[3] == "Min":
  235. return float(fila[6].replace(",", "."))
  236. return None
  237. def calc_coef_impacto(self, frecuencia):
  238. #calculo segun EC1.2 trenes reales
  239. L_phi = 15 # m
  240. v = 80 # km/h
  241. r = 0.5 # calidad de mantenimiento de la vía
  242. alpha = 1 if v/3.6 > 22 else v/(3.6*22)
  243. K = v/(3.6*L_phi*frecuencia)
  244. phi1 = 1.325 if K >= 0.76 else K/(1-K+K**4)
  245. phi2 = alpha*(56*math.exp(-((L_phi/10)**2))+50*(L_phi*frecuencia/80-1)*math.exp(-((L_phi/20)**2)))/100
  246. return 1.21 * (1 + phi1 + r * phi2) #aplicado el factor alpha
  247. def obtain_frequency(self):
  248. Num_results = 0
  249. LoadCase = ""
  250. Steptype = []
  251. Stepnum = []
  252. Period = []
  253. Ux = []
  254. Uy = []
  255. Uz = []
  256. SumUx = []
  257. SumUy = []
  258. SumUz = []
  259. Rx = []
  260. Ry = []
  261. Rz = []
  262. SumRx = []
  263. SumRy = []
  264. SumRz = []
  265. ret = SapModel.Results.ModalParticipatingMassRatios(Num_results, LoadCase, Steptype, Stepnum, Period,
  266. Ux, Uy, Uz, SumUx, SumUy, SumUz,
  267. Rx, Ry, Rz, SumRx, SumRy, SumRz)
  268. if ret[17] != 0:
  269. messagebox.showerror("Error al obtener frecuencias", f"Código de error: {ret}")
  270. return None
  271. return 1/ret[4][min(ret[7].index(max(ret[7])), ret[12].index(max(ret[12])))]
  272. def calculate_section_properties(self, points):
  273. """Calcula propiedades de la sección a partir de puntos"""
  274. # Constantes de material
  275. DENS = 7850 # kg/m3
  276. FY = 355 # MPa
  277. GAMMAS = 1.05
  278. EYOUNG = 210000 # MPa
  279. NU = 0.3
  280. FYD = FY * 10**6 / GAMMAS
  281. npuntos = len(points)
  282. px = points[:, 0]
  283. py = points[:, 1]
  284. bmax = np.amax(px) - np.amin(px)
  285. hmax = np.amax(py) - np.amin(py)
  286. # Perímetro
  287. long_i = np.zeros(npuntos - 1)
  288. for i in range(npuntos - 1):
  289. long_i[i] = ((points[i+1, 0] - points[i, 0])**2 + (points[i+1, 1] - points[i, 1])**2)**(1/2)
  290. perimetro = abs(sum(long_i))
  291. # Área
  292. area_i = np.zeros(npuntos - 1)
  293. for i in range(npuntos - 1):
  294. area_i[i] = (points[i+1, 0] - points[i, 0]) * (points[i+1, 1] + points[i, 1]) / 2
  295. area = abs(sum(area_i))
  296. # Peso
  297. peso = area * DENS
  298. # Centro de gravedad
  299. cdg_i = np.zeros([npuntos, 2])
  300. for i in range(npuntos - 1):
  301. h1 = points[i, 1]
  302. h2 = points[i+1, 1]
  303. b = points[i+1, 0] - points[i, 0]
  304. d = points[i, 0]
  305. if h1 + h2 == 0:
  306. cdg_i[i, 1] = 0
  307. else:
  308. cdg_i[i, 1] = 1/3 * (h1*h1 + h1*h2 + h2*h2) / (h1 + h2)
  309. if h1 + h2 == 0:
  310. cdg_i[i, 0] = d + b/2
  311. else:
  312. cdg_i[i, 0] = d + b/3 * (h1 + 2*h2) / (h1 + h2)
  313. statico_i = np.zeros([npuntos, 2])
  314. for i in range(npuntos - 1):
  315. statico_i[i, 1] = area_i[i] * cdg_i[i, 1]
  316. statico_i[i, 0] = area_i[i] * cdg_i[i, 0]
  317. cdg = sum(statico_i) / sum(area_i)
  318. xg = cdg[0]
  319. yg = cdg[1]
  320. # Fibras más alejadas
  321. v1y = np.amax(py) - yg
  322. v2y = np.amin(py) - yg
  323. v1x = np.amax(px) - xg
  324. v2x = np.amin(px) - xg
  325. # Momentos de inercia
  326. inercia_i = np.zeros([npuntos, 3])
  327. for i in range(npuntos - 1):
  328. h1 = points[i, 1]
  329. h2 = points[i+1, 1]
  330. b = points[i+1, 0] - points[i, 0]
  331. d = points[i, 0]
  332. xgi = cdg_i[i, 0]
  333. ygi = cdg_i[i, 1]
  334. ai = area_i[i]
  335. if h2 >= h1:
  336. ixcuad_G_local = 1/12 * b * (h1**3) + b * h1 * (h1/2 - ygi)**2
  337. ixtriang_G_loc = 1/36 * b * (h2-h1)**3 + 1/2 * b * (h2-h1) * ((2*h1+h2)/3 - ygi)**2
  338. else:
  339. ixcuad_G_local = 1/12 * b * (h2**3) + b * h2 * (h2/2 - ygi)**2
  340. ixtriang_G_loc = 1/36 * b * (h1-h2)**3 + 1/2 * b * (h1-h2) * ((2*h2+h1)/3 - ygi)**2
  341. inercia_i[i, 0] = ixcuad_G_local + ixtriang_G_loc + ai * (yg - ygi)**2
  342. if h2 >= h1:
  343. iycuad = 1/12 * h1 * b**3 + h1 * b * (b/2 + d - xgi)**2
  344. iytrian = 1/36 * (h2-h1) * b**3 + 1/2 * b * (h2-h1) * (2/3*b + d - xgi)**2
  345. else:
  346. iycuad = 1/12 * h2 * b**3 + h2 * b * (b/2 + d - xgi)**2
  347. iytrian = 1/36 * (h1-h2) * b**3 + 1/2 * b * (h1-h2) * (1/3*b + d - xgi)**2
  348. inercia_i[i, 1] = iycuad + iytrian + ai * (xg - xgi)**2
  349. if h2 >= h1:
  350. pxygcuadrado = b * h1 * (-h1/2 + ygi) * (-d - b/2 + xgi)
  351. pxytriangulo = b*b * (h2-h1)**2 / 72 + b * (h2-h1) / 2 * (-(h2-h1)/3 - h1 + ygi) * (-d - 2/3*b + xgi)
  352. else:
  353. pxygcuadrado = b * h2 * (-h2/2 + ygi) * (-d - b/2 + xgi)
  354. pxytriangulo = -b*b * (h1-h2)**2 / 72 + b * (h1-h2) / 2 * (-(h1-h2)/3 - h2 + ygi) * (-d - 1/3*b + xgi)
  355. inercia_i[i, 2] = pxygcuadrado + pxytriangulo + ai * (-xg + xgi) * (-yg + ygi)
  356. ig = sum(inercia_i)
  357. ixg = abs(ig[0])
  358. iyg = abs(ig[1])
  359. pxyg = ig[2]
  360. if sum(area_i) >= 0:
  361. pxyg = pxyg
  362. else:
  363. pxyg = -pxyg
  364. # Radios de giro
  365. rx = (ixg / area)**0.5
  366. ry = (iyg / area)**0.5
  367. # Ejes principales
  368. ic = (ixg + iyg) / 2
  369. ir = (((ixg - iyg)/2)**2 + pxyg**2)**0.5
  370. imax = ic + ir
  371. imin = ic - ir
  372. rmax = (imax / area)**0.5
  373. rmin = (imin / area)**0.5
  374. # Conversión a unidades prácticas (cm, cm2, cm3, cm4, kN)
  375. pot = 2
  376. area_cm2 = area * 10**(pot*2)
  377. ixg_cm4 = ixg * 10**(pot*4)
  378. iyg_cm4 = iyg * 10**(pot*4)
  379. imax_cm4 = imax * 10**(pot*4)
  380. imin_cm4 = imin * 10**(pot*4)
  381. return {
  382. 'area': area_cm2,
  383. 'ixg': ixg_cm4,
  384. 'iyg': iyg_cm4,
  385. 'imax': imax_cm4,
  386. 'imin': imin_cm4,
  387. 'peso': peso,
  388. }
  389. def generate_completo_points(self, H, b, tf, tw):
  390. """Genera los puntos de una sección IPE a partir de parámetros normalizados"""
  391. h_alma = H - 2*tf
  392. x_alma_ini = (b - .3) / 2
  393. x_alma_fin = (b + .3) / 2
  394. points = np.array([
  395. [0, 0],
  396. [b, 0],
  397. [b, tf],
  398. [x_alma_fin, 0.169],
  399. [x_alma_fin, H - .169],
  400. [b, H - tf],
  401. [b, H],
  402. [0, H],
  403. [0, H - tf],
  404. [x_alma_ini, H - .169],
  405. [x_alma_ini, 0.169],
  406. [0, tf],
  407. ])
  408. return points
  409. def generate_hueco_inf_points(self, H, b, tf, tw):
  410. """Genera los puntos de una sección IPE a partir de parámetros normalizados"""
  411. h_alma = H - 2*tf
  412. x_alma_ini = (b - tw) / 2
  413. x_alma_fin = (b + tw) / 2
  414. points = np.array([
  415. [0, 0],
  416. [b, 0],
  417. [b, tf],
  418. [x_alma_fin, tf],
  419. [x_alma_fin, H - tf -.36 - .169],
  420. [x_alma_ini, H - tf - .36 - .169],
  421. [x_alma_ini, tf],
  422. [0, tf],
  423. ])
  424. return points
  425. def generate_hueco_sup_points(self, H, b, tf, tw):
  426. """Genera los puntos de una sección IPE a partir de parámetros normalizados"""
  427. h_alma = H - 2*tf
  428. x_alma_ini = (b - tw) / 2
  429. x_alma_fin = (b + tw) / 2
  430. points = np.array([
  431. [x_alma_fin, H - tf - .169],
  432. [x_alma_fin, H - tf],
  433. [b, H - tf],
  434. [b, H],
  435. [0, H],
  436. [0, H - tf],
  437. [x_alma_ini, H - tf],
  438. [x_alma_ini, H - tf - .169],
  439. ])
  440. return points
  441. def generate_ipe_points(self, H, b, tf, tw):
  442. """Genera los puntos de una sección IPE a partir de parámetros normalizados"""
  443. h_alma = H - 2*tf
  444. x_alma_ini = (b - tw) / 2
  445. x_alma_fin = (b + tw) / 2
  446. points = np.array([
  447. [0, 0],
  448. [b, 0],
  449. [b, tf],
  450. [x_alma_fin, tf],
  451. [x_alma_fin, H - tf],
  452. [b, H - tf],
  453. [b, H],
  454. [0, H],
  455. [0, H - tf],
  456. [x_alma_ini, H - tf],
  457. [x_alma_ini, tf],
  458. [0, tf],
  459. ])
  460. return points
  461. def _valid_geometry(self, params):
  462. """Valida que la combinación de parámetros genere una geometría válida"""
  463. H = params.get('H', 0)
  464. b = params.get('b', 0)
  465. tf = params.get('tf', 0)
  466. tw = params.get('tw', 0)
  467. if H <= 0 or b <= 0 or tf <= 0 or tw <= 0:
  468. return False
  469. if H < 0.360 + 0.169 + tf:
  470. return False
  471. if b < 0.3:
  472. return False
  473. if tf > H/2 or tf > 0.169:
  474. return False
  475. if tw > b:
  476. return False
  477. return True
  478. def generar_matriz_sweep(self, sweep_configs, fixed_params):
  479. sweep_params = list(sweep_configs.keys())
  480. param_values = {}
  481. for param in sweep_params:
  482. config = sweep_configs[param]
  483. values = np.linspace(config['min'], config['max'], config['steps'])
  484. param_values[param] = values
  485. combinations = []
  486. for combo in itertools.product(*param_values.values()):
  487. params = fixed_params.copy()
  488. for i, param in enumerate(sweep_params):
  489. params[param] = combo[i]
  490. if self._valid_geometry(params):
  491. combinations.append(params)
  492. return combinations
  493. def crear_seccion(self, puntos = [], tipo="ipe", nombre_poligono="Nueva sección"):
  494. material = "S355"
  495. if not len(puntos) or not tipo:
  496. messagebox.showerror("Error", "Faltan puntos o tipos de sección")
  497. return
  498. # Leer coordenadas
  499. try:
  500. X = [float(p[0]) for p in puntos]
  501. Y = [float(p[1]) for p in puntos]
  502. num_points = len(X)
  503. Radius = [0.0] * num_points
  504. if num_points < 3:
  505. raise ValueError("Se necesitan al menos 3 puntos")
  506. except Exception as e:
  507. messagebox.showerror("Error en coordenadas", str(e))
  508. return
  509. if tipo == "hueco":
  510. nombre = "hueca"
  511. elif tipo == "completo":
  512. nombre = "rigida"
  513. elif tipo == "ipe":
  514. nombre = "entera"
  515. else:
  516. messagebox.showerror("Error", f"Tipo de sección desconocido: {tipo}")
  517. return
  518. try:
  519. ret = SapModel.PropFrame.SetSDSection(
  520. nombre, material, 1, -1, "", "Default"
  521. )
  522. if not (ret == 0 or ret == 1): # 1 = sección ya existe, lo cual está bien
  523. messagebox.showerror("Error SetSDSection", f"Código: {ret}")
  524. return
  525. if not (nombre == "hueca" and nombre_poligono == "Polygon2"): #si es la sección hueca, el polígono 2 es el hueco, no se borra
  526. ret = SapModel.PropFrame.SDShape.Delete(
  527. nombre,
  528. "",
  529. True
  530. )
  531. if ret != 0 :
  532. messagebox.showerror("Error Delete", f"Código: {ret}")
  533. return
  534. ret = SapModel.PropFrame.SDShape.SetPolygon(
  535. nombre, # Nombre de la sección SD
  536. nombre_poligono, # Nombre del shape
  537. material, # Material
  538. "Default",
  539. num_points, # Número de puntos
  540. X, # Lista normal de Python (X)
  541. Y, # Lista normal (Y)
  542. Radius, # Lista normal (Radius)
  543. -1, # Color
  544. False,
  545. ""
  546. )
  547. if ret[4] != 0:
  548. messagebox.showerror("Error SAP",
  549. f"SetPolygon devolvió código de error: {ret}\n\nRevisa que el material exista y las coordenadas sean correctas.")
  550. except Exception as e:
  551. messagebox.showerror("Error SAP", str(e))
  552. def run(self):
  553. self.root.mainloop()
  554. if __name__ == "__main__":
  555. app = SAPSectionDesignerGUI()
  556. app.run()