ToolOptimal.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  1. # ##########################################################
  2. # FlatCAM: 2D Post-processing for Manufacturing #
  3. # http://flatcam.org #
  4. # File Author: Marius Adrian Stanciu (c) #
  5. # Date: 09/27/2019 #
  6. # MIT Licence #
  7. # ##########################################################
  8. from FlatCAMTool import FlatCAMTool
  9. from FlatCAMObj import *
  10. from shapely.geometry import Point
  11. from shapely import affinity
  12. from shapely.ops import nearest_points
  13. from PyQt5 import QtCore
  14. import gettext
  15. import FlatCAMTranslation as fcTranslate
  16. import builtins
  17. fcTranslate.apply_language('strings')
  18. if '_' not in builtins.__dict__:
  19. _ = gettext.gettext
  20. class ToolOptimal(FlatCAMTool):
  21. toolName = _("Optimal Tool")
  22. update_text = pyqtSignal(list)
  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. # ## Title
  27. title_label = QtWidgets.QLabel("%s" % self.toolName)
  28. title_label.setStyleSheet("""
  29. QLabel
  30. {
  31. font-size: 16px;
  32. font-weight: bold;
  33. }
  34. """)
  35. self.layout.addWidget(title_label)
  36. # ## Form Layout
  37. form_lay = QtWidgets.QFormLayout()
  38. self.layout.addLayout(form_lay)
  39. # ## Gerber Object to mirror
  40. self.gerber_object_combo = QtWidgets.QComboBox()
  41. self.gerber_object_combo.setModel(self.app.collection)
  42. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  43. self.gerber_object_combo.setCurrentIndex(1)
  44. self.gerber_object_label = QtWidgets.QLabel("<b>%s:</b>" % _("GERBER"))
  45. self.gerber_object_label.setToolTip(
  46. "Gerber object for which to find the minimum distance between copper features."
  47. )
  48. self.title_res_label = QtWidgets.QLabel('<b>%s</b>' % _("Minimum distance between copper features"))
  49. self.result_label = QtWidgets.QLabel('%s:' % _("Determined"))
  50. self.show_res = QtWidgets.QLabel('%s' % '')
  51. self.units_lbl = QtWidgets.QLabel(self.units)
  52. self.freq_label = QtWidgets.QLabel('%s:' % _("Occurring"))
  53. self.freq_label.setToolTip(_("How many times this minimum is found."))
  54. self.freq_res = QtWidgets.QLabel('%s' % '')
  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. self.locations_cb = FCCheckBox(_("Locations"))
  61. self.locations_cb.setToolTip(_("Locations where minimum distance was found."))
  62. self.locations_textb = FCTextArea(parent=self)
  63. self.locations_textb.setReadOnly(True)
  64. self.locations_textb.setToolTip(_("Locations where minimum distance was found."))
  65. stylesheet = """
  66. QTextEdit { selection-background-color:yellow;
  67. selection-color:black;
  68. }
  69. """
  70. self.locations_textb.setStyleSheet(stylesheet)
  71. hlay = QtWidgets.QHBoxLayout()
  72. hlay.addWidget(self.show_res)
  73. hlay.addStretch()
  74. hlay.addWidget(self.units_lbl)
  75. form_lay.addRow(QtWidgets.QLabel(""))
  76. form_lay.addRow(self.gerber_object_label, self.gerber_object_combo)
  77. form_lay.addRow(self.precision_label, self.precision_spinner)
  78. form_lay.addRow(QtWidgets.QLabel(""))
  79. form_lay.addRow(self.title_res_label)
  80. form_lay.addRow(self.result_label, hlay)
  81. form_lay.addRow(self.freq_label, self.freq_res)
  82. form_lay.addRow(self.locations_cb)
  83. form_lay.addRow(self.locations_textb)
  84. self.calculate_button = QtWidgets.QPushButton(_("Find Distance"))
  85. self.calculate_button.setToolTip(
  86. _("Calculate the minimum distance between copper features,\n"
  87. "this will allow the determination of the right tool to\n"
  88. "use for isolation or copper clearing.")
  89. )
  90. self.calculate_button.setMinimumWidth(60)
  91. self.layout.addWidget(self.calculate_button)
  92. self.locate_button = QtWidgets.QPushButton(_("Locate position"))
  93. self.locate_button.setToolTip(
  94. _("Select a position in the Locations text box and then\n"
  95. "click this button.")
  96. )
  97. self.locate_button.setMinimumWidth(60)
  98. self.layout.addWidget(self.locate_button)
  99. self.locate_button.setDisabled(True)
  100. self.decimals = 4
  101. self.selected_text = ''
  102. # self.dt_label = QtWidgets.QLabel("<b>%s:</b>" % _('Alignment Drill Diameter'))
  103. # self.dt_label.setToolTip(
  104. # _("Diameter of the drill for the "
  105. # "alignment holes.")
  106. # )
  107. # self.layout.addWidget(self.dt_label)
  108. #
  109. # hlay = QtWidgets.QHBoxLayout()
  110. # self.layout.addLayout(hlay)
  111. #
  112. # self.drill_dia = FCEntry()
  113. # self.dd_label = QtWidgets.QLabel('%s:' % _("Drill dia"))
  114. # self.dd_label.setToolTip(
  115. # _("Diameter of the drill for the "
  116. # "alignment holes.")
  117. # )
  118. # hlay.addWidget(self.dd_label)
  119. # hlay.addWidget(self.drill_dia)
  120. self.calculate_button.clicked.connect(self.find_minimum_distance)
  121. self.locate_button.clicked.connect(self.on_locate_position)
  122. self.update_text.connect(self.on_update_text)
  123. self.locations_textb.cursorPositionChanged.connect(self.on_textbox_clicked)
  124. self.locations_cb.stateChanged.connect(self.on_location_cb)
  125. self.layout.addStretch()
  126. # ## Signals
  127. def install(self, icon=None, separator=None, **kwargs):
  128. FlatCAMTool.install(self, icon, separator, shortcut='ALT+O', **kwargs)
  129. def run(self, toggle=True):
  130. self.app.report_usage("ToolOptimal()")
  131. self.show_res.setText('')
  132. if toggle:
  133. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  134. if self.app.ui.splitter.sizes()[0] == 0:
  135. self.app.ui.splitter.setSizes([1, 1])
  136. else:
  137. try:
  138. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  139. # if tab is populated with the tool but it does not have the focus, focus on it
  140. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  141. # focus on Tool Tab
  142. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  143. else:
  144. self.app.ui.splitter.setSizes([0, 1])
  145. except AttributeError:
  146. pass
  147. else:
  148. if self.app.ui.splitter.sizes()[0] == 0:
  149. self.app.ui.splitter.setSizes([1, 1])
  150. FlatCAMTool.run(self)
  151. self.set_tool_ui()
  152. self.app.ui.notebook.setTabText(2, _("Optimal Tool"))
  153. def set_tool_ui(self):
  154. self.precision_spinner.set_value(int(self.decimals))
  155. self.locations_textb.clear()
  156. # new cursor - select all document
  157. cursor = self.locations_textb.textCursor()
  158. cursor.select(QtGui.QTextCursor.Document)
  159. # clear previous selection highlight
  160. tmp = cursor.blockFormat()
  161. tmp.clearBackground()
  162. cursor.setBlockFormat(tmp)
  163. self.locations_textb.setVisible(False)
  164. self.locate_button.setVisible(False)
  165. self.show_res.setText('')
  166. self.freq_res.setText('')
  167. self.reset_fields()
  168. def find_minimum_distance(self):
  169. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  170. self.decimals = int(self.precision_spinner.get_value())
  171. selection_index = self.gerber_object_combo.currentIndex()
  172. model_index = self.app.collection.index(selection_index, 0, self.gerber_object_combo.rootModelIndex())
  173. try:
  174. fcobj = model_index.internalPointer().obj
  175. except Exception as e:
  176. log.debug("ToolOptimal.find_minimum_distance() --> %s" % str(e))
  177. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  178. return
  179. if not isinstance(fcobj, FlatCAMGerber):
  180. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Only Gerber objects can be evaluated."))
  181. return
  182. proc = self.app.proc_container.new(_("Working..."))
  183. def job_thread(app_obj):
  184. app_obj.inform.emit(_("Optimal Tool. Started to search for the minimum distance between copper features."))
  185. try:
  186. old_disp_number = 0
  187. pol_nr = 0
  188. app_obj.proc_container.update_view_text(' %d%%' % 0)
  189. total_geo = list()
  190. for ap in list(fcobj.apertures.keys()):
  191. if 'geometry' in fcobj.apertures[ap]:
  192. app_obj.inform.emit(
  193. '%s: %s' % (_("Optimal Tool. Parsing geometry for aperture"), str(ap)))
  194. for geo_el in fcobj.apertures[ap]['geometry']:
  195. if self.app.abort_flag:
  196. # graceful abort requested by the user
  197. raise FlatCAMApp.GracefulException
  198. if 'solid' in geo_el and geo_el['solid'] is not None and geo_el['solid'].is_valid:
  199. total_geo.append(geo_el['solid'])
  200. app_obj.inform.emit(
  201. _("Optimal Tool. Creating a buffer for the object geometry."))
  202. total_geo = MultiPolygon(total_geo)
  203. total_geo = total_geo.buffer(0)
  204. geo_len = len(total_geo)
  205. geo_len = (geo_len * (geo_len - 1)) / 2
  206. app_obj.inform.emit(
  207. '%s: %s' % (_("Optimal Tool. Finding the distances between each two elements. Iterations"),
  208. str(geo_len)))
  209. min_dict = dict()
  210. idx = 1
  211. for geo in total_geo:
  212. for s_geo in total_geo[idx:]:
  213. if self.app.abort_flag:
  214. # graceful abort requested by the user
  215. raise FlatCAMApp.GracefulException
  216. # minimize the number of distances by not taking into considerations those that are too small
  217. dist = geo.distance(s_geo)
  218. dist = float('%.*f' % (self.decimals, dist))
  219. loc_1, loc_2 = nearest_points(geo, s_geo)
  220. dx = loc_1.x - loc_2.x
  221. dy = loc_1.y - loc_2.y
  222. loc = (float('%.*f' % (self.decimals, (min(loc_1.x, loc_2.x) + (abs(dx) / 2)))),
  223. float('%.*f' % (self.decimals, (min(loc_1.y, loc_2.y) + (abs(dy) / 2)))))
  224. if dist in min_dict:
  225. min_dict[dist].append(loc)
  226. else:
  227. min_dict[dist] = [loc]
  228. pol_nr += 1
  229. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  230. if old_disp_number < disp_number <= 100:
  231. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  232. old_disp_number = disp_number
  233. idx += 1
  234. app_obj.inform.emit(
  235. _("Optimal Tool. Finding the minimum distance."))
  236. min_list = list(min_dict.keys())
  237. min_dist = min(min_list)
  238. min_dist_string = '%.*f' % (self.decimals, float(min_dist))
  239. self.show_res.setText(min_dist_string)
  240. freq = len(min_dict[min_dist])
  241. freq = '%d' % int(freq)
  242. self.freq_res.setText(freq)
  243. self.update_text.emit(min_dict[min_dist])
  244. app_obj.inform.emit('[success] %s' % _("Optimal Tool. Finished successfully."))
  245. except Exception as ee:
  246. proc.done()
  247. log.debug(str(ee))
  248. return
  249. proc.done()
  250. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  251. def on_locate_position(self):
  252. # cursor = self.locations_textb.textCursor()
  253. # self.selected_text = cursor.selectedText()
  254. try:
  255. loc = eval(self.selected_text)
  256. self.app.on_jump_to(custom_location=loc)
  257. except Exception as e:
  258. self.app.inform.emit("[ERROR_NOTCL] The selected text is no valid location in the format (x, y).")
  259. def on_update_text(self, data):
  260. txt = ''
  261. for loc in data:
  262. txt += '%s\n' % str(loc)
  263. self.locations_textb.setPlainText(txt)
  264. self.locate_button.setDisabled(False)
  265. def on_textbox_clicked(self):
  266. # new cursor - select all document
  267. cursor = self.locations_textb.textCursor()
  268. cursor.select(QtGui.QTextCursor.Document)
  269. # clear previous selection highlight
  270. tmp = cursor.blockFormat()
  271. tmp.clearBackground()
  272. cursor.setBlockFormat(tmp)
  273. # new cursor - select the current line
  274. cursor = self.locations_textb.textCursor()
  275. cursor.select(QtGui.QTextCursor.LineUnderCursor)
  276. # highlight the current selected line
  277. tmp = cursor.blockFormat()
  278. tmp.setBackground(QtGui.QBrush(QtCore.Qt.yellow))
  279. cursor.setBlockFormat(tmp)
  280. self.selected_text = cursor.selectedText()
  281. def on_location_cb(self, state):
  282. if state:
  283. self.locations_textb.setVisible(True)
  284. self.locate_button.setVisible(True)
  285. else:
  286. self.locations_textb.setVisible(False)
  287. self.locate_button.setVisible(False)
  288. def reset_fields(self):
  289. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  290. self.gerber_object_combo.setCurrentIndex(0)