Подключен генератор PDDL-доменов и функция экспорта

This commit is contained in:
Mark Voltov 2023-07-04 21:30:42 +03:00
parent 8971bb13df
commit 46758e4b62
10 changed files with 9 additions and 587 deletions

View file

@ -1,286 +0,0 @@
"
#Создаем объект, к которому привязываем вспомогательную информацию:
1. Выбираем элемент в модели:
1.1. Поверхность - можем создать призматический объект. Соответствует точке захвата, рабочей зоне, опорной поверхности, поверхности базирования
1.1.1 Выбираем тип объкта, который нам нужно построить.
1.1.2 В зависимости от выбора, предлагается указать объект для ориентации осей.
1.1.3 Указать размеры зоны построения. Для захвата соответствует габаритам пальца, для рабочей зоны - координатам. Полуавтоматическое (ручное???) создание эскиза?
1.1.4 Для захвата выбираем вытягивание объекта на нужную длину до параллельной поверхности
1.1.5 - Результат - построенный параллелограмм с размерами и привязкой к моделям. Его мы экспортируем в json через существующий функционал
1.2. Цилиндрическая поверхность - осесимметричный объект. Захват двухпальцевый, трехпальцевый, четырехпальцевый, цилиндрическая зона установки, отверстия сопряжения
1.2.1 Выбираем тип объекта
1.2.2. Выбираем ориентацию главной оси. //Потенциально, мы можем захватить цилиндрический объект в любой ориентации, нужно ли добавлять конкретное указание?
видимо, только если геометрия обязывает нас придерживаться ее (напр. не дает поставить 4 палец)
указание требуется, если есть фиксаторы, опорные площадки или что-то иное, что приводит к однозначному позиционированию
1.2.3. Вытягиваем зону до привязки. Пальцы ставим как цилиндрический массив( нужно ли??)
1.2.4 Результат - цилиндрическая зона с радиусом, ориентациями осей.
2. К размеченным объектам необходимо привязать метаданные, содержащие связи с конкретными моделями. STEP-файл захвата, step-файл входной детали и/или выходной.
2.1 Нужно ли привязывать захват? Да, но в некоем обобщенном виде. Позиция захвата - характеристика способа воздействия, а не объекта.
2.2 Для станков входы и выходы необходимы.
2.3
"
#!/usr/bin/env python3
# coding: utf-8
#
# LGPL
# Copyright HUBERT Zoltán
#
# newDatumCmd.py
import os
from PySide import QtGui, QtCore
import FreeCADGui as Gui
import FreeCAD as App
from FreeCAD import Console as FCC
import Asm4_libs as Asm4
"""
+-----------------------------------------------+
| a class to create all Datum objects |
+-----------------------------------------------+
"""
class newDatum:
"My tool object"
def __init__(self, datumName):
self.datumName = datumName
# recognised containers (not the same as Asm4.containerTypes !)
self.containers = [ 'App::Part', 'PartDesign::Body', 'App::DocumentObjectGroup']
if self.datumName == 'Point':
self.datumType = 'PartDesign::Point'
self.menutext = "New Point"
self.tooltip = "Create a new Datum Point in a Part"
self.icon = os.path.join( Asm4.iconPath , 'Asm4_Point.svg')
self.datumColor = (0.00,0.00,0.00)
self.datumAlpha = []
elif self.datumName == 'Axis':
self.datumType = 'PartDesign::Line'
self.menutext = "New Axis"
self.tooltip = "Create a new Datum Axis in a Part"
self.icon = os.path.join( Asm4.iconPath , 'Asm4_Axis.svg')
self.datumColor = (0.00,0.00,0.50)
self.datumAlpha = []
elif self.datumName == 'Plane':
self.datumType = 'PartDesign::Plane'
self.menutext = "New Plane"
self.tooltip = "Create a new Datum Plane in a Part"
self.icon = os.path.join( Asm4.iconPath , 'Asm4_Plane.svg')
self.datumColor = (0.50,0.50,0.50)
self.datumAlpha = 80
elif self.datumName == 'LCS':
self.datumType = 'PartDesign::CoordinateSystem'
self.menutext = "New Coordinate System"
self.tooltip = "Create a new Coordinate System in a Part"
self.icon = os.path.join( Asm4.iconPath , 'Asm4_CoordinateSystem.svg')
self.datumColor = []
self.datumAlpha = []
elif self.datumName == 'Sketch':
self.datumType = 'Sketcher::SketchObject'
self.menutext = "New Sketch"
self.tooltip = "Create a new Sketch in a Part"
self.icon = os.path.join( Asm4.iconPath , 'Asm4_Sketch.svg')
self.datumColor = []
self.datumAlpha = []
def GetResources(self):
return {"MenuText": self.menutext,
"ToolTip": self.tooltip,
"Pixmap" : self.icon }
def IsActive(self):
if App.ActiveDocument:
# is something correct selected ?
if self.checkSelection():
return(True)
return(False)
def checkSelection(self):
# if something is selected ...
if Gui.Selection.getSelection():
selectedObj = Gui.Selection.getSelection()[0]
# ... and it's an App::Part or an datum object
selType = selectedObj.TypeId
if selType in self.containers or selType in Asm4.datumTypes or selType=='Sketcher::SketchObject':
return(selectedObj)
# or of nothing is selected ...
elif Asm4.getAssembly():
# ... but there is as assembly:
return Asm4.getAssembly()
# if we're here it's because we didn't find a good reason to not be here
return None
"""
+-----------------------------------------------+
| the real stuff |
+-----------------------------------------------+
"""
def Activated(self):
# check that we have somewhere to put our stuff
selectedObj = self.checkSelection()
# default name increments the datum type's end numeral
proposedName = Asm4.nextInstance( self.datumName, startAtOne=True )
parentContainer = None
# check whether we have selected a container
if selectedObj.TypeId in self.containers:
parentContainer = selectedObj
# if a datum object is selected
elif selectedObj.TypeId in Asm4.datumTypes or selectedObj.TypeId=='Sketcher::SketchObject':
# see whether it's in a container
parent = selectedObj.getParentGeoFeatureGroup()
if parent.TypeId in self.containers:
parentContainer = parent
# if there is an assembly
elif Asm4.getAssembly():
parentContainer = Asm4.getAssembly()
# something went wrong
else:
Asm4.warningBox("I can't create a "+self.datumType+" with the current selections")
# check whether there is already a similar datum, and increment the instance number
# instanceNum = 1
#while App.ActiveDocument.getObject( self.datumName+'_'+str(instanceNum) ):
# instanceNum += 1
#datumName = self.datumName+'_'+str(instanceNum)
if parentContainer:
# input dialog to ask the user the name of the Sketch:
#proposedName = Asm4.nextInstance( self.datumName + '_' + selectedObj.Label, startAtOne=True )
text,ok = QtGui.QInputDialog.getText(None,'Create new '+self.datumName,
'Enter '+self.datumName+' name :'+' '*40, text = proposedName)
if ok and text:
# App.activeDocument().getObject('Model').newObject( 'Sketcher::SketchObject', text )
createdDatum = App.ActiveDocument.addObject( self.datumType, text )
parentContainer.addObject( createdDatum )
createdDatum.Label = text
# automatic resizing of datum Plane sucks, so we set it to manual
if self.datumType=='PartDesign::Plane':
createdDatum.ResizeMode = 'Manual'
createdDatum.Length = 100
createdDatum.Width = 100
elif self.datumType=='PartDesign::Line':
createdDatum.ResizeMode = 'Manual'
createdDatum.Length = 200
# if color or transparency is specified for this datum type
if self.datumColor:
Gui.ActiveDocument.getObject(createdDatum.Name).ShapeColor = self.datumColor
if self.datumAlpha:
Gui.ActiveDocument.getObject(createdDatum.Name).Transparency = self.datumAlpha
# highlight the created datum object
Gui.Selection.clearSelection()
Gui.Selection.addSelection( App.ActiveDocument.Name, parentContainer.Name, createdDatum.Name+'.' )
Gui.runCommand('Part_EditAttachment')
"""
+-----------------------------------------------+
| a class to create an LCS on a hole |
+-----------------------------------------------+
"""
class newHole:
def GetResources(self):
return {"MenuText": "New Hole Axis",
"ToolTip": "Create a Datum Axis attached to a hole",
"Pixmap" : os.path.join( Asm4.iconPath , 'Asm4_Hole.svg')
}
def IsActive(self):
selection = self.getSelectedEdges()
if selection is None:
return False
else:
return True
"""
+-----------------------------------------------+
| the real stuff |
+-----------------------------------------------+
"""
def getSelectedEdges(self):
# check that we have selected only circular edges
selection = None
parent = None
edges = []
# 1 selection means a single parent
if App.ActiveDocument and len(Gui.Selection.getSelection()) == 1:
parent = Gui.Selection.getSelection()[0]
# parse all sub-elemets of the selection
for i in range(len(Gui.Selection.getSelectionEx()[0].SubObjects)):
edgeObj = Gui.Selection.getSelectionEx()[0].SubObjects[i]
edgeName = Gui.Selection.getSelectionEx()[0].SubElementNames[i]
# if the edge is circular
if Asm4.isCircle(edgeObj):
edges.append( [edgeObj,edgeName] )
# if we found circular edges
if len(edges) > 0:
selection = ( parent, edges )
return selection
def Activated(self):
( selectedObj, edges ) = self.getSelectedEdges()
for i in range(len(edges)):
edgeObj = edges[i][0]
edgeName = edges[i][1]
parentPart = selectedObj.getParentGeoFeatureGroup()
# we can create a datum only in a container
if parentPart:
parentDoc = parentPart.Document
# if the solid having the edge is indeed in an App::Part
if parentPart and (parentPart.TypeId=='App::Part' or parentPart.TypeId=='PartDesign::Body'):
# check whether there is already a similar datum, and increment the instance number
instanceNum = 1
while parentDoc.getObject( 'HoleAxis_'+str(instanceNum) ):
instanceNum += 1
axis = parentPart.newObject('PartDesign::Line','HoleAxis_'+str(instanceNum))
axis.Support = [( selectedObj, (edgeName,) )]
axis.MapMode = 'AxisOfCurvature'
axis.MapReversed = False
axis.ResizeMode = 'Manual'
axis.Length = edgeObj.BoundBox.DiagonalLength
axis.ViewObject.ShapeColor = (0.0,0.0,1.0)
axis.ViewObject.Transparency = 50
axis.recompute()
parentPart.recompute()
#
else:
FCC.PrintMessage('Datum objects can only be created inside Part or Body containers')
"""
+-----------------------------------------------+
| add the commands to the workbench |
+-----------------------------------------------+
"""
Gui.addCommand( 'Asm4_newPoint', newDatum('Point') )
Gui.addCommand( 'Asm4_newAxis', newDatum('Axis') )
Gui.addCommand( 'Asm4_newPlane', newDatum('Plane') )
Gui.addCommand( 'Asm4_newLCS', newDatum('LCS') )
Gui.addCommand( 'Asm4_newSketch',newDatum('Sketch'))
Gui.addCommand( 'Asm4_newHole', newHole() )
# defines the drop-down button for Datum objects
createDatumList = [ 'Asm4_newLCS',
'Asm4_newPlane',
'Asm4_newAxis',
'Asm4_newPoint',
'Asm4_newHole' ]
Gui.addCommand( 'Asm4_createDatum', Asm4.dropDownCmd( createDatumList, 'Create Datum Object'))

View file

@ -13,6 +13,7 @@
# License along with this library. If not, see <http://www.gnu.org/licenses/>.
from BoMList import run_BoM_list
import pddl.freecad2pddl as freecad2pddl
from ImportExportEntities import export_coordinate_systems
import FreeCAD
import Tools
from usecases.asm4parser_usecase import Asm4StructureParseUseCase
@ -301,12 +302,6 @@ def spawnFeatureFrameCreator():
ffpanel = FeatureFramePanel()
FreeCADGui.Control.showDialog(ffpanel)
def BoMGeneration(part):
obj = FreeCAD.ActiveDocument.addObject("App::FeaturePython",
"FeatureFrame")
print(obj)
###################################################################
@ -378,6 +373,13 @@ Tools.spawnClassCommand("PDDL_ExportPDDL",
"MenuText": "ExportDomain",
"ToolTip": "Create and Export Domain.pddl to File"})
Tools.spawnClassCommand("Export_Entities",
export_coordinate_systems,
{"Pixmap": str(os.path.join(icondir, "BoMList.svg")),
"MenuText": "ExportLCS",
"ToolTip": "Export all the markups"})
###################################################################
# GUI buttons

View file

@ -46,6 +46,7 @@ class Frames(Workbench):
]
self.toolcommands = [
"ExportPlacementAndPropertiesCommand",
"Export_Entities",
"ExportGazeboModels",
"InsertGraspPose",
"ASM4StructureParsing",

View file

@ -1,31 +0,0 @@
import os
import subprocess
import time
import subprocess
# import FreeCAD
# import Mesh
import gcoder
# gcode_path = '/home/mark-voltov/Winder/axis.gcode'
# gcode.main(gcode)
file_path = '/home/mark-voltov/Winder/axis.gcode'
gcoder_path = '/home/mark-voltov/GitProjects/framework/cg/freecad/Frames/gcoder.py'
with open(file_path, 'r') as file:
gcode = file.readlines()
# print(gcode)
(gcoder.LightGCode(gcode))
cmd = [file_path gcoder_path]
subprocess.run(cmd)
# subprocess.run( '/home/mark-voltov/Winder/axis.gcode', '/home/mark-voltov/GitProjects/framework/cg/freecad/Frames/gcoder.py')

Binary file not shown.

View file

@ -1,96 +0,0 @@
(define (domain roboarm)
(:requirements :strips :typing)
(:types
zone
part
assembly
roboarm
printer
)
(:predicates
(arm_available ?a - roboarm)
(printer_available ?p - printer)
;касты на сборку
(assembly_at ?a - assembly ?z - zone)
(part_of ?part - part ?whole - assembly)
(assembled ?whole - assembly)
(assembly_order ?prev ?next - assembly)
(part_at ?part - part ?z - zone)
)
(:durative-action assemble
:parameters (?part - part ?prev ?next - assembly ?z - zone ?a - arm)
:duration ( = ?duration 5)
:condition (and
(at start (arm_available ?a))
(at start (assembly_order ?prev ?next))
(at start (part_of ?part ?next))
(at start (assembly_at ?prev ?z))
(at start (assembled ?prev))
)
:effect (and
(at start (not (arm_available ?a)))
(at end (assembly_at ?next ?z))
(at end (assembled ?next))
(at end (arm_available ?a))
)
)
(:durative-action print
:parameters (?part - part ?p - printer ?z - zone )
:duration ( = ?duration 10)
:condition (and
(at start (printer_available ?p))
(at_start (not (part_at ?part ?z)))
)
:effect (and
(at start (not (printer_available ?p)))
(at end (part_at ?part ?z))
(at end (printer_available ?a))
)
)
; (:action take
; :parameters (?r - roboarm ?w - workspace )
; :condition (and
; (roboarm_free ?r)
; (roboarm_available ?r)
; )
; :effect (and
; (not (roboarm_free ?r))
; (not (roboarm_available ?r))
; )
; )
; (:action assemble
; :parameters (?r - roboarm ?w - workspace ?a - assembly )
; :duration (= ?duration 5 )
; :condition (and
; (not(roboarm_free ?r))
; (not(roboarm_available ?r))
; )
; :effect (and
; (roboarm_free ?r)
; (roboarm_available ?r)
; (assembled ?a)
; )
; )
; (:goal (and
; (roboarm_free ?r)
; (assembled ?a)
; )
; ))
;

View file

@ -1,124 +0,0 @@
;; Modified domain taken from
;; "Knowledge transfer in robot manipulation tasks" by Jacob O. Huckaby 2014
(define (domain robossembler)
(:requirements :strips :typing :adl :fluents :durative-actions )
(:types
printer workspace - zone
part
arm
assembly
human
filament
)
(:predicates
(arm_available ?a - arm)
(part_at ?p - part ?z - zone)
(printer_ready ?p - printer)
(printer_checked ?p - printer)
(printer_at_work ?p - printer )
(part_of ?part - part ?whole - assembly)
(assembly_order ?prev ?next - assembly)
(assembled ?whole - assembly ?z - zone)
(observer_free ?h - human)
(filament_at ?f - filament ?z - zone)
)
(:functions)
(:durative-action print
:parameters (?p - part ?pr - printer)
:duration ( = ?duration 20)
:condition (and
(at start(printer_ready ?pr))
)
:effect (and
(at start (not (printer_ready ?pr)))
; (at start (printer_at_work ?pr ))
(at end(part_at ?p ?pr))
; (at end (not (printer_at_work ?pr )))
)
)
(:durative-action remove
:parameters (?p - part ?pr - printer ?z - zone ?a - arm)
:duration (= ?duration 1)
:condition (and
(at start (part_at ?p ?pr))
(at start (arm_available ?a))
)
:effect (and
(at start (not (arm_available ?a)))
(at end (part_at ?p ?z))
(at end (arm_available ?a))
(at end (printer_ready ?pr))
)
)
(:durative-action assemble
:parameters (?p - part ?prev ?next - assembly ?w - workspace ?arm - arm)
:duration (= ?duration 5)
:condition (and
(at start (assembled ?prev ?w))
(at start (part_at ?p ?w))
(at start (part_of ?p ?next))
(at start (arm_available ?arm))
(at start (assembly_order ?prev ?next))
)
:effect (and
(at start (not (arm_available ?arm)))
(at end (not (part_at ?p ?w)))
(at end (arm_available ?arm))
(at end (assembled ?next ?w))
)
)
(:durative-action printer_check ; здесь мы подготавливаем сам механизм 3д-принтера
:parameters (?p - printer ?h - human)
:duration (= ?duration 1)
:condition (and
(at start ( observer_free ?h ))
)
:effect (and
(at start (not (observer_free ?h)))
(at end (observer_free ?h))
(at end (printer_checked ?p))
)
)
(:durative-action printer_filament_load ; а здесь - заправляем пластик, чтобы он был готов к печати
:parameters (?p - printer ?h - human ?f - filament ?w - workspace)
:duration (= ?duration 5)
:condition (and
(at start (printer_checked ?p))
(at start (observer_free ?h))
(at start (filament_at ?f ?w)) ; филамент в зоне
; (at start (not(printer_ready ?p)))
)
:effect (and
(at start (not(observer_free ?h)))
(at end (observer_free ?h))
(at end (printer_ready ?p))
(at end (not (filament_at ?f ?w)))
)
)
)
;; end Domain ;;;;;;;;;;;;;;;;;;;;;;;;

View file

@ -1,44 +0,0 @@
(define (problem p1)
(:domain robossembler)
(:objects
;; information from Scene
rasmt - arm
printer1 printer2 printer3 - printer
workspace1 - workspace
worker - human
filament1 filament2 filament3 - filament
;; information from CAD
part1 part2 part3 part4 - part
subasm0 subasm1 subasm2 subasm3 subasm4 - assembly
)
(:init
;; information from Scene
(observer_free worker)
; (not(printer_ready printer1))
; (printer_ready printer2)
; (printer_ready printer3)
(filament_at filament1 workspace1)
(filament_at filament2 workspace1)
(filament_at filament3 workspace1)
(arm_available rasmt)
;; information from CAD
(assembled subasm0 workspace1)
(part_of part1 subasm1)
(part_of part2 subasm2)
(part_of part3 subasm3)
(part_of part4 subasm4)
(assembly_order subasm0 subasm1)
(assembly_order subasm1 subasm2)
(assembly_order subasm2 subasm3)
(assembly_order subasm3 subasm4)
)
(:goal (and
;; information from CAD
(assembled subasm4 workspace1)
)
)
)