ToolOptimal.py 16 KB

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