ToolOptimal.py 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344
  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"))
  49. self.title_res_label.setToolTip(_("Display minimum distance between copper features."))
  50. self.result_label = QtWidgets.QLabel('%s:' % _("Determined"))
  51. self.result_entry = FCEntry()
  52. self.result_entry.setReadOnly(True)
  53. self.units_lbl = QtWidgets.QLabel(self.units.lower())
  54. self.units_lbl.setDisabled(True)
  55. self.freq_label = QtWidgets.QLabel('%s:' % _("Occurring"))
  56. self.freq_label.setToolTip(_("How many times this minimum is found."))
  57. self.freq_entry = FCEntry()
  58. self.freq_entry.setReadOnly(True)
  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. self.locations_cb = FCCheckBox(_("Minimum points coordinates"))
  65. self.locations_cb.setToolTip(_("Coordinates for points where minimum distance was found."))
  66. self.locations_textb = FCTextArea(parent=self)
  67. self.locations_textb.setReadOnly(True)
  68. self.locations_textb.setToolTip(_("Coordinates for points where minimum distance was found."))
  69. stylesheet = """
  70. QTextEdit { selection-background-color:yellow;
  71. selection-color:black;
  72. }
  73. """
  74. self.locations_textb.setStyleSheet(stylesheet)
  75. self.locate_button = QtWidgets.QPushButton(_("Jump to selected position"))
  76. self.locate_button.setToolTip(
  77. _("Select a position in the Locations text box and then\n"
  78. "click this button.")
  79. )
  80. self.locate_button.setMinimumWidth(60)
  81. self.locate_button.setDisabled(True)
  82. hlay = QtWidgets.QHBoxLayout()
  83. hlay.addWidget(self.result_entry)
  84. # hlay.addStretch()
  85. hlay.addWidget(self.units_lbl)
  86. form_lay.addRow(QtWidgets.QLabel(""))
  87. form_lay.addRow(self.gerber_object_label, self.gerber_object_combo)
  88. form_lay.addRow(self.precision_label, self.precision_spinner)
  89. form_lay.addRow(QtWidgets.QLabel(""))
  90. form_lay.addRow(self.title_res_label)
  91. form_lay.addRow(self.result_label, hlay)
  92. form_lay.addRow(self.freq_label, self.freq_entry)
  93. form_lay.addRow(self.locations_cb)
  94. form_lay.addRow(self.locations_textb)
  95. form_lay.addRow(self.locate_button)
  96. self.loc_ois = OptionalHideInputSection(self.locations_cb, [self.locations_textb, self.locate_button])
  97. self.calculate_button = QtWidgets.QPushButton(_("Find Minimum"))
  98. self.calculate_button.setToolTip(
  99. _("Calculate the minimum distance between copper features,\n"
  100. "this will allow the determination of the right tool to\n"
  101. "use for isolation or copper clearing.")
  102. )
  103. self.calculate_button.setMinimumWidth(60)
  104. self.layout.addWidget(self.calculate_button)
  105. self.decimals = 4
  106. self.selected_text = ''
  107. # ## Signals
  108. self.calculate_button.clicked.connect(self.find_minimum_distance)
  109. self.locate_button.clicked.connect(self.on_locate_position)
  110. self.update_text.connect(self.on_update_text)
  111. self.locations_textb.cursorPositionChanged.connect(self.on_textbox_clicked)
  112. self.layout.addStretch()
  113. def install(self, icon=None, separator=None, **kwargs):
  114. FlatCAMTool.install(self, icon, separator, shortcut='ALT+O', **kwargs)
  115. def run(self, toggle=True):
  116. self.app.report_usage("ToolOptimal()")
  117. self.result_entry.set_value(0.0)
  118. self.freq_entry.set_value('0')
  119. if toggle:
  120. # if the splitter is hidden, display it, else hide it but only if the current widget is the same
  121. if self.app.ui.splitter.sizes()[0] == 0:
  122. self.app.ui.splitter.setSizes([1, 1])
  123. else:
  124. try:
  125. if self.app.ui.tool_scroll_area.widget().objectName() == self.toolName:
  126. # if tab is populated with the tool but it does not have the focus, focus on it
  127. if not self.app.ui.notebook.currentWidget() is self.app.ui.tool_tab:
  128. # focus on Tool Tab
  129. self.app.ui.notebook.setCurrentWidget(self.app.ui.tool_tab)
  130. else:
  131. self.app.ui.splitter.setSizes([0, 1])
  132. except AttributeError:
  133. pass
  134. else:
  135. if self.app.ui.splitter.sizes()[0] == 0:
  136. self.app.ui.splitter.setSizes([1, 1])
  137. FlatCAMTool.run(self)
  138. self.set_tool_ui()
  139. self.app.ui.notebook.setTabText(2, _("Optimal Tool"))
  140. def set_tool_ui(self):
  141. self.precision_spinner.set_value(int(self.decimals))
  142. self.locations_textb.clear()
  143. # new cursor - select all document
  144. cursor = self.locations_textb.textCursor()
  145. cursor.select(QtGui.QTextCursor.Document)
  146. # clear previous selection highlight
  147. tmp = cursor.blockFormat()
  148. tmp.clearBackground()
  149. cursor.setBlockFormat(tmp)
  150. self.locations_textb.setVisible(False)
  151. self.locate_button.setVisible(False)
  152. self.result_entry.set_value(0.0)
  153. self.freq_entry.set_value('0')
  154. self.reset_fields()
  155. def find_minimum_distance(self):
  156. self.units = self.app.ui.general_defaults_form.general_app_group.units_radio.get_value().upper()
  157. self.decimals = int(self.precision_spinner.get_value())
  158. selection_index = self.gerber_object_combo.currentIndex()
  159. model_index = self.app.collection.index(selection_index, 0, self.gerber_object_combo.rootModelIndex())
  160. try:
  161. fcobj = model_index.internalPointer().obj
  162. except Exception as e:
  163. log.debug("ToolOptimal.find_minimum_distance() --> %s" % str(e))
  164. self.app.inform.emit('[WARNING_NOTCL] %s' % _("There is no Gerber object loaded ..."))
  165. return
  166. if not isinstance(fcobj, FlatCAMGerber):
  167. self.app.inform.emit('[ERROR_NOTCL] %s' % _("Only Gerber objects can be evaluated."))
  168. return
  169. proc = self.app.proc_container.new(_("Working..."))
  170. def job_thread(app_obj):
  171. app_obj.inform.emit(_("Optimal Tool. Started to search for the minimum distance between copper features."))
  172. try:
  173. old_disp_number = 0
  174. pol_nr = 0
  175. app_obj.proc_container.update_view_text(' %d%%' % 0)
  176. total_geo = list()
  177. for ap in list(fcobj.apertures.keys()):
  178. if 'geometry' in fcobj.apertures[ap]:
  179. app_obj.inform.emit(
  180. '%s: %s' % (_("Optimal Tool. Parsing geometry for aperture"), str(ap)))
  181. for geo_el in fcobj.apertures[ap]['geometry']:
  182. if self.app.abort_flag:
  183. # graceful abort requested by the user
  184. raise FlatCAMApp.GracefulException
  185. if 'solid' in geo_el and geo_el['solid'] is not None and geo_el['solid'].is_valid:
  186. total_geo.append(geo_el['solid'])
  187. app_obj.inform.emit(
  188. _("Optimal Tool. Creating a buffer for the object geometry."))
  189. total_geo = MultiPolygon(total_geo)
  190. total_geo = total_geo.buffer(0)
  191. geo_len = len(total_geo)
  192. geo_len = (geo_len * (geo_len - 1)) / 2
  193. app_obj.inform.emit(
  194. '%s: %s' % (_("Optimal Tool. Finding the distances between each two elements. Iterations"),
  195. str(geo_len)))
  196. min_dict = dict()
  197. idx = 1
  198. for geo in total_geo:
  199. for s_geo in total_geo[idx:]:
  200. if self.app.abort_flag:
  201. # graceful abort requested by the user
  202. raise FlatCAMApp.GracefulException
  203. # minimize the number of distances by not taking into considerations those that are too small
  204. dist = geo.distance(s_geo)
  205. dist = float('%.*f' % (self.decimals, dist))
  206. loc_1, loc_2 = nearest_points(geo, s_geo)
  207. dx = loc_1.x - loc_2.x
  208. dy = loc_1.y - loc_2.y
  209. loc = (float('%.*f' % (self.decimals, (min(loc_1.x, loc_2.x) + (abs(dx) / 2)))),
  210. float('%.*f' % (self.decimals, (min(loc_1.y, loc_2.y) + (abs(dy) / 2)))))
  211. if dist in min_dict:
  212. min_dict[dist].append(loc)
  213. else:
  214. min_dict[dist] = [loc]
  215. pol_nr += 1
  216. disp_number = int(np.interp(pol_nr, [0, geo_len], [0, 100]))
  217. if old_disp_number < disp_number <= 100:
  218. app_obj.proc_container.update_view_text(' %d%%' % disp_number)
  219. old_disp_number = disp_number
  220. idx += 1
  221. app_obj.inform.emit(
  222. _("Optimal Tool. Finding the minimum distance."))
  223. min_list = list(min_dict.keys())
  224. min_dist = min(min_list)
  225. min_dist_string = '%.*f' % (self.decimals, float(min_dist))
  226. self.result_entry.set_Value(min_dist_string)
  227. freq = len(min_dict[min_dist])
  228. freq = '%d' % int(freq)
  229. self.freq_entry.set_value(freq)
  230. self.update_text.emit(min_dict[min_dist])
  231. app_obj.inform.emit('[success] %s' % _("Optimal Tool. Finished successfully."))
  232. except Exception as ee:
  233. proc.done()
  234. log.debug(str(ee))
  235. return
  236. proc.done()
  237. self.app.worker_task.emit({'fcn': job_thread, 'params': [self.app]})
  238. def on_locate_position(self):
  239. # cursor = self.locations_textb.textCursor()
  240. # self.selected_text = cursor.selectedText()
  241. try:
  242. loc = eval(self.selected_text)
  243. self.app.on_jump_to(custom_location=loc)
  244. except Exception as e:
  245. self.app.inform.emit("[ERROR_NOTCL] The selected text is no valid location in the format (x, y).")
  246. def on_update_text(self, data):
  247. txt = ''
  248. for loc in data:
  249. txt += '%s\n' % str(loc)
  250. self.locations_textb.setPlainText(txt)
  251. self.locate_button.setDisabled(False)
  252. def on_textbox_clicked(self):
  253. # new cursor - select all document
  254. cursor = self.locations_textb.textCursor()
  255. cursor.select(QtGui.QTextCursor.Document)
  256. # clear previous selection highlight
  257. tmp = cursor.blockFormat()
  258. tmp.clearBackground()
  259. cursor.setBlockFormat(tmp)
  260. # new cursor - select the current line
  261. cursor = self.locations_textb.textCursor()
  262. cursor.select(QtGui.QTextCursor.LineUnderCursor)
  263. # highlight the current selected line
  264. tmp = cursor.blockFormat()
  265. tmp.setBackground(QtGui.QBrush(QtCore.Qt.yellow))
  266. cursor.setBlockFormat(tmp)
  267. self.selected_text = cursor.selectedText()
  268. def reset_fields(self):
  269. self.gerber_object_combo.setRootModelIndex(self.app.collection.index(0, 0, QtCore.QModelIndex()))
  270. self.gerber_object_combo.setCurrentIndex(0)