ToolOptimal.py 23 KB

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