ToolOptimal.py 23 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # File Author: Marius Adrian Stanciu (c) #
  4. # Date: 09/27/2019 #
  5. # MIT Licence #
  6. # ##########################################################
  7. from PyQt5 import QtWidgets, QtCore, QtGui
  8. from FlatCAMTool import FlatCAMTool
  9. from flatcamGUI.GUIElements import OptionalHideInputSection, FCTextArea, FCEntry, FCSpinner, FCCheckBox
  10. from FlatCAMObj import FlatCAMGerber
  11. import FlatCAMApp
  12. from shapely.geometry import MultiPolygon
  13. from shapely.ops import nearest_points
  14. import numpy as np
  15. import logging
  16. import gettext
  17. import FlatCAMTranslation as fcTranslate
  18. import builtins
  19. fcTranslate.apply_language('strings')
  20. if '_' not in builtins.__dict__:
  21. _ = gettext.gettext
  22. log = logging.getLogger('base')
  23. class ToolOptimal(FlatCAMTool):
  24. toolName = _("Optimal Tool")
  25. update_text = QtCore.pyqtSignal(list)
  26. update_sec_distances = QtCore.pyqtSignal(dict)
  27. def __init__(self, app):
  28. FlatCAMTool.__init__(self, app)
  29. self.units = self.app.defaults['units'].upper()
  30. self.decimals = 4
  31. # ############################################################################
  32. # ############################ GUI creation ##################################
  33. # ## Title
  34. title_label = QtWidgets.QLabel("%s" % self.toolName)
  35. title_label.setStyleSheet(
  36. """
  37. QLabel
  38. {
  39. font-size: 16px;
  40. font-weight: bold;
  41. }
  42. """)
  43. self.layout.addWidget(title_label)
  44. # ## Form Layout
  45. form_lay = QtWidgets.QFormLayout()
  46. self.layout.addLayout(form_lay)
  47. form_lay.addRow(QtWidgets.QLabel(""))
  48. # ## Gerber Object to mirror
  49. self.gerber_object_combo = QtWidgets.QComboBox()
  50. self.gerber_object_combo.setModel(self.app.collection)
  51. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  52. self.gerber_object_combo.setCurrentIndex(1)
  53. self.gerber_object_label = QtWidgets.QLabel("<b>%s:</b>" % _("GERBER"))
  54. self.gerber_object_label.setToolTip(
  55. "Gerber object for which to find the minimum distance between copper features."
  56. )
  57. form_lay.addRow(self.gerber_object_label, self.gerber_object_combo)
  58. # Precision = nr of decimals
  59. self.precision_label = QtWidgets.QLabel('%s:' % _("Precision"))
  60. self.precision_label.setToolTip(_("Number of decimals kept for found distances."))
  61. self.precision_spinner = FCSpinner()
  62. self.precision_spinner.set_range(2, 10)
  63. self.precision_spinner.setWrapping(True)
  64. form_lay.addRow(self.precision_label, self.precision_spinner)
  65. # Results Title
  66. self.title_res_label = QtWidgets.QLabel('<b>%s:</b>' % _("Minimum distance"))
  67. self.title_res_label.setToolTip(_("Display minimum distance between copper features."))
  68. form_lay.addRow(self.title_res_label)
  69. # Result value
  70. self.result_label = QtWidgets.QLabel('%s:' % _("Determined"))
  71. self.result_entry = FCEntry()
  72. self.result_entry.setReadOnly(True)
  73. self.units_lbl = QtWidgets.QLabel(self.units.lower())
  74. self.units_lbl.setDisabled(True)
  75. hlay = QtWidgets.QHBoxLayout()
  76. hlay.addWidget(self.result_entry)
  77. hlay.addWidget(self.units_lbl)
  78. form_lay.addRow(self.result_label, hlay)
  79. # Frequency of minimum encounter
  80. self.freq_label = QtWidgets.QLabel('%s:' % _("Occurring"))
  81. self.freq_label.setToolTip(_("How many times this minimum is found."))
  82. self.freq_entry = FCEntry()
  83. self.freq_entry.setReadOnly(True)
  84. form_lay.addRow(self.freq_label, self.freq_entry)
  85. # Control if to display the locations of where the minimum was found
  86. self.locations_cb = FCCheckBox(_("Minimum points coordinates"))
  87. self.locations_cb.setToolTip(_("Coordinates for points where minimum distance was found."))
  88. form_lay.addRow(self.locations_cb)
  89. # Locations where minimum was found
  90. self.locations_textb = FCTextArea(parent=self)
  91. self.locations_textb.setPlaceholderText(
  92. _("Coordinates for points where minimum distance was found.")
  93. )
  94. self.locations_textb.setReadOnly(True)
  95. stylesheet = """
  96. QTextEdit { selection-background-color:blue;
  97. selection-color:white;
  98. }
  99. """
  100. self.locations_textb.setStyleSheet(stylesheet)
  101. form_lay.addRow(self.locations_textb)
  102. # Jump button
  103. self.locate_button = QtWidgets.QPushButton(_("Jump to selected position"))
  104. self.locate_button.setToolTip(
  105. _("Select a position in the Locations text box and then\n"
  106. "click this button.")
  107. )
  108. self.locate_button.setMinimumWidth(60)
  109. self.locate_button.setDisabled(True)
  110. form_lay.addRow(self.locate_button)
  111. # Other distances in Gerber
  112. self.title_second_res_label = QtWidgets.QLabel('<b>%s:</b>' % _("Other distances"))
  113. self.title_second_res_label.setToolTip(_("Will display other distances in the Gerber file ordered from\n"
  114. "the minimum to the maximum, not including the absolute minimum."))
  115. form_lay.addRow(self.title_second_res_label)
  116. # Control if to display the locations of where the minimum was found
  117. self.sec_locations_cb = FCCheckBox(_("Other distances points coordinates"))
  118. self.sec_locations_cb.setToolTip(_("Other distances and the coordinates for points\n"
  119. "where the distance was found."))
  120. form_lay.addRow(self.sec_locations_cb)
  121. # this way I can hide/show the frame
  122. self.sec_locations_frame = QtWidgets.QFrame()
  123. self.sec_locations_frame.setContentsMargins(0, 0, 0, 0)
  124. self.layout.addWidget(self.sec_locations_frame)
  125. self.distances_box = QtWidgets.QVBoxLayout()
  126. self.distances_box.setContentsMargins(0, 0, 0, 0)
  127. self.sec_locations_frame.setLayout(self.distances_box)
  128. # Other Distances label
  129. self.distances_label = QtWidgets.QLabel('%s' % _("Gerber distances"))
  130. self.distances_label.setToolTip(_("Other distances and the coordinates for points\n"
  131. "where the distance was found."))
  132. self.distances_box.addWidget(self.distances_label)
  133. # Other distances
  134. self.distances_textb = FCTextArea(parent=self)
  135. self.distances_textb.setPlaceholderText(
  136. _("Other distances and the coordinates for points\n"
  137. "where the distance was found.")
  138. )
  139. self.distances_textb.setReadOnly(True)
  140. stylesheet = """
  141. QTextEdit { selection-background-color:blue;
  142. selection-color:white;
  143. }
  144. """
  145. self.distances_textb.setStyleSheet(stylesheet)
  146. self.distances_box.addWidget(self.distances_textb)
  147. self.distances_box.addWidget(QtWidgets.QLabel(''))
  148. # Other Locations label
  149. self.locations_label = QtWidgets.QLabel('%s' % _("Points coordinates"))
  150. self.locations_label.setToolTip(_("Other distances and the coordinates for points\n"
  151. "where the distance was found."))
  152. self.distances_box.addWidget(self.locations_label)
  153. # Locations where minimum was found
  154. self.locations_sec_textb = FCTextArea(parent=self)
  155. self.locations_sec_textb.setPlaceholderText(
  156. _("Other distances and the coordinates for points\n"
  157. "where the distance was found.")
  158. )
  159. self.locations_sec_textb.setReadOnly(True)
  160. stylesheet = """
  161. QTextEdit { selection-background-color:blue;
  162. selection-color:white;
  163. }
  164. """
  165. self.locations_sec_textb.setStyleSheet(stylesheet)
  166. self.distances_box.addWidget(self.locations_sec_textb)
  167. # Jump button
  168. self.locate_sec_button = QtWidgets.QPushButton(_("Jump to selected position"))
  169. self.locate_sec_button.setToolTip(
  170. _("Select a position in the Locations text box and then\n"
  171. "click this button.")
  172. )
  173. self.locate_sec_button.setMinimumWidth(60)
  174. self.locate_sec_button.setDisabled(True)
  175. self.distances_box.addWidget(self.locate_sec_button)
  176. # GO button
  177. self.calculate_button = QtWidgets.QPushButton(_("Find Minimum"))
  178. self.calculate_button.setToolTip(
  179. _("Calculate the minimum distance between copper features,\n"
  180. "this will allow the determination of the right tool to\n"
  181. "use for isolation or copper clearing.")
  182. )
  183. self.calculate_button.setMinimumWidth(60)
  184. self.layout.addWidget(self.calculate_button)
  185. self.loc_ois = OptionalHideInputSection(self.locations_cb, [self.locations_textb, self.locate_button])
  186. self.sec_loc_ois = OptionalHideInputSection(self.sec_locations_cb, [self.sec_locations_frame])
  187. # ################## Finished GUI creation ###################################
  188. # ############################################################################
  189. # this is the line selected in the textbox with the locations of the minimum
  190. self.selected_text = ''
  191. # this is the line selected in the textbox with the locations of the other distances found in the Gerber object
  192. self.selected_locations_text = ''
  193. # dict to hold the distances between every two elements in Gerber as keys and the actual locations where that
  194. # distances happen as values
  195. self.min_dict = dict()
  196. # ############################################################################
  197. # ############################ Signals #######################################
  198. # ############################################################################
  199. self.calculate_button.clicked.connect(self.find_minimum_distance)
  200. self.locate_button.clicked.connect(self.on_locate_position)
  201. self.update_text.connect(self.on_update_text)
  202. self.locations_textb.cursorPositionChanged.connect(self.on_textbox_clicked)
  203. self.locate_sec_button.clicked.connect(self.on_locate_sec_position)
  204. self.update_sec_distances.connect(self.on_update_sec_distances_txt)
  205. self.distances_textb.cursorPositionChanged.connect(self.on_distances_textb_clicked)
  206. self.locations_sec_textb.cursorPositionChanged.connect(self.on_locations_sec_clicked)
  207. self.layout.addStretch()
  208. def install(self, icon=None, separator=None, **kwargs):
  209. FlatCAMTool.install(self, icon, separator, shortcut='ALT+O', **kwargs)
  210. def run(self, toggle=True):
  211. self.app.report_usage("ToolOptimal()")
  212. self.result_entry.set_value(0.0)
  213. self.freq_entry.set_value('0')
  214. if toggle:
  215. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  216. if self.app.ui.splitter.sizes()[0] == 0:
  217. self.app.ui.splitter.setSizes([1, 1])
  218. else:
  219. try:
  220. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  221. # if tab is populated with the tool but it does not have the focus, focus on it
  222. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  223. # focus on Tool Tab
  224. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  225. else:
  226. self.app.ui.splitter.setSizes([0, 1])
  227. except AttributeError:
  228. pass
  229. else:
  230. if self.app.ui.splitter.sizes()[0] == 0:
  231. self.app.ui.splitter.setSizes([1, 1])
  232. FlatCAMTool.run(self)
  233. self.set_tool_ui()
  234. self.app.ui.notebook.setTabText(2, _("Optimal Tool"))
  235. def set_tool_ui(self):
  236. self.precision_spinner.set_value(int(self.app.defaults["tools_opt_precision"]))
  237. self.locations_textb.clear()
  238. # new cursor - select all document
  239. cursor = self.locations_textb.textCursor()
  240. cursor.select(QtGui.QTextCursor.Document)
  241. # clear previous selection highlight
  242. tmp = cursor.blockFormat()
  243. tmp.clearBackground()
  244. cursor.setBlockFormat(tmp)
  245. self.locations_textb.setVisible(False)
  246. self.locate_button.setVisible(False)
  247. self.result_entry.set_value(0.0)
  248. self.freq_entry.set_value('0')
  249. self.reset_fields()
  250. def find_minimum_distance(self):
  251. self.units = self.app.defaults['units'].upper()
  252. self.decimals = int(self.precision_spinner.get_value())
  253. selection_index = self.gerber_object_combo.currentIndex()
  254. model_index = self.app.collection.index(selection_index, 0, self.gerber_object_combo.rootModelIndex())
  255. try:
  256. fcobj = model_index.internalPointer().obj
  257. except Exception as e:
  258. log.debug("ToolOptimal.find_minimum_distance() --> %s" % str(e))
  259. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  260. return
  261. if not isinstance(fcobj, FlatCAMGerber):
  262. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Only Gerber objects can be evaluated."))
  263. return
  264. proc = self.app.proc_container.new(_("Working..."))
  265. def job_thread(app_obj):
  266. app_obj.inform.emit(_("Optimal Tool. Started to search for the minimum distance between copper features."))
  267. try:
  268. old_disp_number = 0
  269. pol_nr = 0
  270. app_obj.proc_container.update_view_text(' %d%%' % 0)
  271. total_geo = list()
  272. for ap in list(fcobj.apertures.keys()):
  273. if 'geometry' in fcobj.apertures[ap]:
  274. app_obj.inform.emit(
  275. '%s: %s' % (_("Optimal Tool. Parsing geometry for aperture"), str(ap)))
  276. for geo_el in fcobj.apertures[ap]['geometry']:
  277. if self.app.abort_flag:
  278. # graceful abort requested by the user
  279. raise FlatCAMApp.GracefulException
  280. if 'solid' in geo_el and geo_el['solid'] is not None and geo_el['solid'].is_valid:
  281. total_geo.append(geo_el['solid'])
  282. app_obj.inform.emit(
  283. _("Optimal Tool. Creating a buffer for the object geometry."))
  284. total_geo = MultiPolygon(total_geo)
  285. total_geo = total_geo.buffer(0)
  286. try:
  287. __ = iter(total_geo)
  288. geo_len = len(total_geo)
  289. geo_len = (geo_len * (geo_len - 1)) / 2
  290. except TypeError:
  291. app_obj.inform.emit('[ERROR_NOTCL] %s' %
  292. _("The Gerber object has one Polygon as geometry.\n"
  293. "There are no distances between geometry elements to be found."))
  294. return 'fail'
  295. app_obj.inform.emit(
  296. '%s: %s' % (_("Optimal Tool. Finding the distances between each two elements. Iterations"),
  297. str(geo_len)))
  298. self.min_dict = dict()
  299. idx = 1
  300. for geo in total_geo:
  301. for s_geo in total_geo[idx:]:
  302. if self.app.abort_flag:
  303. # graceful abort requested by the user
  304. raise FlatCAMApp.GracefulException
  305. # minimize the number of distances by not taking into considerations those that are too small
  306. dist = geo.distance(s_geo)
  307. dist = float('%.*f' % (self.decimals, dist))
  308. loc_1, loc_2 = nearest_points(geo, s_geo)
  309. proc_loc = (
  310. (float('%.*f' % (self.decimals, loc_1.x)), float('%.*f' % (self.decimals, loc_1.y))),
  311. (float('%.*f' % (self.decimals, loc_2.x)), float('%.*f' % (self.decimals, loc_2.y)))
  312. )
  313. if dist in self.min_dict:
  314. self.min_dict[dist].append(proc_loc)
  315. else:
  316. self.min_dict[dist] = [proc_loc]
  317. pol_nr += 1
  318. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  319. if old_disp_number < disp_number <= 100:
  320. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  321. old_disp_number = disp_number
  322. idx += 1
  323. app_obj.inform.emit(
  324. _("Optimal Tool. Finding the minimum distance."))
  325. min_list = list(self.min_dict.keys())
  326. min_dist = min(min_list)
  327. min_dist_string = '%.*f' % (self.decimals, float(min_dist))
  328. self.result_entry.set_value(min_dist_string)
  329. freq = len(self.min_dict[min_dist])
  330. freq = '%d' % int(freq)
  331. self.freq_entry.set_value(freq)
  332. min_locations = self.min_dict.pop(min_dist)
  333. self.update_text.emit(min_locations)
  334. self.update_sec_distances.emit(self.min_dict)
  335. app_obj.inform.emit('[success] %s' % _("Optimal Tool. Finished successfully."))
  336. except Exception as ee:
  337. proc.done()
  338. log.debug(str(ee))
  339. return
  340. proc.done()
  341. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  342. def on_locate_position(self):
  343. # cursor = self.locations_textb.textCursor()
  344. # self.selected_text = cursor.selectedText()
  345. try:
  346. if self.selected_text != '':
  347. loc = eval(self.selected_text)
  348. else:
  349. return 'fail'
  350. except Exception as e:
  351. log.debug("ToolOptimal.on_locate_position() --> first try %s" % str(e))
  352. self.app.inform.emit("[ERROR_NOTCL] The selected text is no valid location in the format "
  353. "((x0, y0), (x1, y1)).")
  354. return 'fail'
  355. try:
  356. loc_1 = loc[0]
  357. loc_2 = loc[1]
  358. dx = loc_1[0] - loc_2[0]
  359. dy = loc_1[1] - loc_2[1]
  360. loc = (float('%.*f' % (self.decimals, (min(loc_1[0], loc_2[0]) + (abs(dx) / 2)))),
  361. float('%.*f' % (self.decimals, (min(loc_1[1], loc_2[1]) + (abs(dy) / 2)))))
  362. self.app.on_jump_to(custom_location=loc)
  363. except Exception as e:
  364. log.debug("ToolOptimal.on_locate_position() --> sec try %s" % str(e))
  365. return 'fail'
  366. def on_update_text(self, data):
  367. txt = ''
  368. for loc in data:
  369. if loc:
  370. txt += '%s, %s\n' % (str(loc[0]), str(loc[1]))
  371. self.locations_textb.setPlainText(txt)
  372. self.locate_button.setDisabled(False)
  373. def on_textbox_clicked(self):
  374. # new cursor - select all document
  375. cursor = self.locations_textb.textCursor()
  376. cursor.select(QtGui.QTextCursor.Document)
  377. # clear previous selection highlight
  378. tmp = cursor.blockFormat()
  379. tmp.clearBackground()
  380. cursor.setBlockFormat(tmp)
  381. # new cursor - select the current line
  382. cursor = self.locations_textb.textCursor()
  383. cursor.select(QtGui.QTextCursor.LineUnderCursor)
  384. # highlight the current selected line
  385. tmp = cursor.blockFormat()
  386. tmp.setBackground(QtGui.QBrush(QtCore.Qt.yellow))
  387. cursor.setBlockFormat(tmp)
  388. self.selected_text = cursor.selectedText()
  389. def on_update_sec_distances_txt(self, data):
  390. distance_list = sorted(list(data.keys()))
  391. txt = ''
  392. for loc in distance_list:
  393. txt += '%s\n' % str(loc)
  394. self.distances_textb.setPlainText(txt)
  395. self.locate_sec_button.setDisabled(False)
  396. def on_distances_textb_clicked(self):
  397. # new cursor - select all document
  398. cursor = self.distances_textb.textCursor()
  399. cursor.select(QtGui.QTextCursor.Document)
  400. # clear previous selection highlight
  401. tmp = cursor.blockFormat()
  402. tmp.clearBackground()
  403. cursor.setBlockFormat(tmp)
  404. # new cursor - select the current line
  405. cursor = self.distances_textb.textCursor()
  406. cursor.select(QtGui.QTextCursor.LineUnderCursor)
  407. # highlight the current selected line
  408. tmp = cursor.blockFormat()
  409. tmp.setBackground(QtGui.QBrush(QtCore.Qt.yellow))
  410. cursor.setBlockFormat(tmp)
  411. distance_text = cursor.selectedText()
  412. key_in_min_dict = eval(distance_text)
  413. self.on_update_locations_text(dist=key_in_min_dict)
  414. def on_update_locations_text(self, dist):
  415. distance_list = self.min_dict[dist]
  416. txt = ''
  417. for loc in distance_list:
  418. if loc:
  419. txt += '%s, %s\n' % (str(loc[0]), str(loc[1]))
  420. self.locations_sec_textb.setPlainText(txt)
  421. def on_locations_sec_clicked(self):
  422. # new cursor - select all document
  423. cursor = self.locations_sec_textb.textCursor()
  424. cursor.select(QtGui.QTextCursor.Document)
  425. # clear previous selection highlight
  426. tmp = cursor.blockFormat()
  427. tmp.clearBackground()
  428. cursor.setBlockFormat(tmp)
  429. # new cursor - select the current line
  430. cursor = self.locations_sec_textb.textCursor()
  431. cursor.select(QtGui.QTextCursor.LineUnderCursor)
  432. # highlight the current selected line
  433. tmp = cursor.blockFormat()
  434. tmp.setBackground(QtGui.QBrush(QtCore.Qt.yellow))
  435. cursor.setBlockFormat(tmp)
  436. self.selected_locations_text = cursor.selectedText()
  437. def on_locate_sec_position(self):
  438. try:
  439. if self.selected_locations_text != '':
  440. loc = eval(self.selected_locations_text)
  441. else:
  442. return 'fail'
  443. except Exception as e:
  444. log.debug("ToolOptimal.on_locate_sec_position() --> first try %s" % str(e))
  445. self.app.inform.emit("[ERROR_NOTCL] The selected text is no valid location in the format "
  446. "((x0, y0), (x1, y1)).")
  447. return 'fail'
  448. try:
  449. loc_1 = loc[0]
  450. loc_2 = loc[1]
  451. dx = loc_1[0] - loc_2[0]
  452. dy = loc_1[1] - loc_2[1]
  453. loc = (float('%.*f' % (self.decimals, (min(loc_1[0], loc_2[0]) + (abs(dx) / 2)))),
  454. float('%.*f' % (self.decimals, (min(loc_1[1], loc_2[1]) + (abs(dy) / 2)))))
  455. self.app.on_jump_to(custom_location=loc)
  456. except Exception as e:
  457. log.debug("ToolOptimal.on_locate_sec_position() --> sec try %s" % str(e))
  458. return 'fail'
  459. def reset_fields(self):
  460. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  461. self.gerber_object_combo.setCurrentIndex(0)