I am trying to conduct volume driven parametric optimization using FreeCAD and Python. I am experiencing some problems, could you help me ?
Let's say we have a cube of side length = L , initially equal to 1. How could I create a python code that would :
1) Analyze the volume of the cube
2) Modify the driving parameter "L"
3) Stop when the goal volume is reached
I tried two things without getting the result I wanted :
1) Externally, with the following piece of code :
Code: Select all
import sys
FREECADPATH = r'PATH\TO\FREECAD'
sys.path.append(FREECADPATH)
import FreeCAD, FreeCADGui as Gui, Part, PartDesign
FreeCAD.openDocument(r'PATH\TO\DOCUMENT',True)
goal = FreeCAD.ActiveDocument.getObjectsByLabel("Body")[0]
vol = goal.Shape.Volume
obj = 100 #Goal volume
print(vol)
print(obj)
a = 1
if vol < obj :
while vol - obj < 5:
doc.getObject('Sketch').setDatum(9,App.Units.Quantity(a))
a = a+1
print(vol)
else:
while vol - obj > 5:
doc.getObject('Sketch').setDatum(9,App.Units.Quantity(a))
a = a-1
print(vol)
( I am quite new to FreeCAD, and I am unsure about wheter or not this is correct way (setDatum) to do what I want)
2) Inside the python console :
Code: Select all
body=FreeCAD.ActiveDocument.getObjectsByLabel("Body")[0]
>>> vol = body.Shape.Volume
>>> vol
0.9999999999999998
>>> # Gui.Selection.addSelection('learning','Body','Pad.Sketch.')
>>> # Gui.Selection.clearSelection()
>>> vol
0.9999999999999998
>>> body.recompute
<built-in method recompute of PartDesign.Body object at 0x00000265CF6F3C18>
>>> vol
0.9999999999999998
Code: Select all
OS: Windows 10 Version 2009
Word size of FreeCAD: 64-bit
Version: 0.20.2.29177 +426 (Git)
Build type: Release
Branch: (HEAD detached from 0.20.2)
Hash: 930dd9a76203a3260b1e6256c70c1c3cad8c5cb8
Python 3.8.10, Qt 5.15.2, Coin 4.0.1, Vtk 8.2.0, OCC 7.6.3
Locale: French/France (fr_FR)