Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[SofaPython3] Remove -at-best- the use of this infamous string conver… #45

Open
wants to merge 3 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 28 additions & 4 deletions Plugin/src/SofaPython3/DataHelper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -45,25 +45,48 @@ std::string toSofaParsableString(const py::handle& p)
if(py::isinstance<py::list>(p) || py::isinstance<py::tuple>(p))
{
std::stringstream tmp;
for(auto pa : p){
for(auto pa : p)
{
tmp << toSofaParsableString(pa) << " ";
}
return tmp.str();
}
//TODO(dmarchal) This conversion to string is so bad.
if(py::isinstance<py::str>(p))
{
return py::str(p);
}

return py::repr(p);
}

/// RVO optimized function. Don't care about copy on the return code.
void fillBaseObjectdescription(sofa::core::objectmodel::BaseObjectDescription& desc,
const py::dict& dict)
const py::dict& dict)
{
for(auto kv : dict)
{
desc.setAttribute(py::str(kv.first), toSofaParsableString(kv.second));
}

return;
}

void processKwargsForObjectCreation(const py::dict dict,
py::list& parametersToLink,
py::list& parametersToCopy,
sofa::core::objectmodel::BaseObjectDescription& parametersAsString)
{
auto t = py::detail::get_type_handle(typeid(BaseData), false);
for(auto kv : dict)
{
desc.setAttribute(py::str(kv.first), toSofaParsableString(kv.second));
if (py::isinstance(kv.second, t))
parametersToLink.append(kv.first);
else if (py::isinstance<py::str>(kv.second))
parametersAsString.setAttribute(py::str(kv.first), py::cast<std::string>(kv.second));
else
parametersToCopy.append(kv.first);
}
return;
}

PythonTrampoline::~PythonTrampoline(){}
Expand All @@ -76,6 +99,7 @@ void PythonTrampoline::setInstance(py::object s)

pyobject = std::shared_ptr<PyObject>( s.ptr(), [](PyObject* ob)
{
SOFA_UNUSED(ob);
// runSofa Sofa/tests/pyfiles/ScriptController.py => CRASH
// Py_DECREF(ob);
});
Expand Down
177 changes: 63 additions & 114 deletions Plugin/src/SofaPython3/DataHelper.h
Original file line number Diff line number Diff line change
Expand Up @@ -42,119 +42,63 @@ along with sofaqtquick. If not, see <http://www.gnu.org/licenses/>.

////////////////////////// FORWARD DECLARATION ///////////////////////////
namespace sofa {
namespace defaulttype {
class AbstractTypeInfo;
}
namespace core {
namespace objectmodel {
class BaseData;


class SOFAPYTHON3_API PrefabLink
{
public:
PrefabLink() {}
PrefabLink(const Base::SPtr& targetBase) { m_targetBase = targetBase; }
PrefabLink(BaseLink* targetLink) { m_targetBase = targetLink->getLinkedBase(); }
PrefabLink(const std::string& targetPath) { m_targetPath = targetPath; }

const Base::SPtr& getTargetBase() const { return m_targetBase; }
void setTargetBase(const Base::SPtr& targetBase) { m_targetBase = targetBase; }

const std::string& getTargetPath() const { return m_targetPath; }
void setTargetPath(const std::string& targetPath) { m_targetPath = targetPath; }

friend std::ostream& operator << ( std::ostream& out, const PrefabLink& l)
{
if (l.getTargetBase())
{
auto bn = l.getTargetBase()->toBaseNode();
auto bo = l.getTargetBase()->toBaseObject();
out << "@" + (bn ? bn->getPathName() : bo->getPathName());
}
out << l.getTargetPath();
return out;
}

friend std::istream& operator >> ( std::istream& in, PrefabLink& l)
{
std::string s;
in >> s;
l.setTargetPath(s);
return in;
}

private:
Base::SPtr m_targetBase { nullptr };
std::string m_targetPath {""};
};

class SOFAPYTHON3_API DataLink : public Data<PrefabLink>
{
typedef Data<PrefabLink> Inherit;

DataLink( const std::string& helpMsg="", bool isDisplayed=true, bool isReadOnly=false )
: Inherit(helpMsg, isDisplayed, isReadOnly)
{
}

DataLink( const std::string& value, const std::string& helpMsg="", bool isDisplayed=true, bool isReadOnly=false )
: Inherit(value, helpMsg, isDisplayed, isReadOnly)
{
}

explicit DataLink(const BaseData::BaseInitData& init)
: Inherit(init)
{
}

const PrefabLink& getValue() const
{
updateIfDirty();
if (m_value.getValue().getTargetBase()) return m_value.getValue();

auto self = const_cast<DataLink*>(this);

Base* dst = nullptr;
this->getOwner()->findLinkDest(dst, self->m_value.getValue().getTargetPath(), nullptr);
if (dst) {
auto edit = self->m_value.beginEdit();
edit->setTargetBase(dst);
edit->setTargetPath("");
self->m_value.endEdit();
}
return m_value.getValue();
}

std::string getValueString() const
{
const auto& ptr = getValue();
if (ptr.getTargetBase())
{
auto bn = ptr.getTargetBase()->toBaseNode();
auto bo = ptr.getTargetBase()->toBaseObject();
return "@" + (bn ? bn->getPathName() : bo->getPathName());
}
return ptr.getTargetPath();
}


bool read(const std::string& value)
{
Base* dst;
auto data = m_value.beginEdit();
if (this->getOwner()->findLinkDest(dst, value, nullptr) && dst != nullptr)
data->setTargetBase(dst);
else {
data->setTargetBase(nullptr);
data->setTargetPath(value);
}
return true;
}
};
namespace defaulttype {
class AbstractTypeInfo;
}
namespace core {
namespace objectmodel {
class BaseData;


class SOFAPYTHON3_API PrefabLink
{
public:
PrefabLink() {}
PrefabLink(const Base::SPtr& targetBase) { m_targetBase = targetBase; }
PrefabLink(BaseLink* targetLink) { m_targetBase = targetLink->getLinkedBase(); }
PrefabLink(const std::string& targetPath) { m_targetPath = targetPath; }

const Base::SPtr& getTargetBase() const { return m_targetBase; }
void setTargetBase(const Base::SPtr& targetBase) { m_targetBase = targetBase; }

const std::string& getTargetPath() const { return m_targetPath; }
void setTargetPath(const std::string& targetPath) { m_targetPath = targetPath; }

friend std::ostream& operator << ( std::ostream& out, const PrefabLink& l)
{
if (l.getTargetBase())
{
auto bn = l.getTargetBase()->toBaseNode();
auto bo = l.getTargetBase()->toBaseObject();
out << "@" + (bn ? bn->getPathName() : bo->getPathName());
}
out << l.getTargetPath();
return out;
}

friend std::istream& operator >> ( std::istream& in, PrefabLink& l)
{
std::string s;
in >> s;
l.setTargetPath(s);
return in;
}

private:
damienmarchal marked this conversation as resolved.
Show resolved Hide resolved
Base::SPtr m_targetBase { nullptr };
std::string m_targetPath {""};
};
}
}
namespace defaulttype
{
template <>
struct DataTypeName<core::objectmodel::PrefabLink>
{
static const char* name() { return "PrefabLink"; }
};

}
}

/////////////////////////////// DECLARATION //////////////////////////////
Expand Down Expand Up @@ -192,7 +136,7 @@ template <typename T> class py_shared_ptr : public sofa::core::sptr<T>

SOFAPYTHON3_API void setItem2D(py::array a, py::slice slice, py::object o);
SOFAPYTHON3_API void setItem2D(py::array a, const py::slice& slice,
const py::slice& slice1, py::object o);
const py::slice& slice1, py::object o);
SOFAPYTHON3_API void setItem1D(py::array a, py::slice slice, py::object o);
SOFAPYTHON3_API void setItem(py::array a, py::slice slice, py::object value);

Expand All @@ -216,11 +160,16 @@ void SOFAPYTHON3_API copyFromListScalar(BaseData& d, const AbstractTypeInfo& nfo

std::string SOFAPYTHON3_API toSofaParsableString(const py::handle& p);

//py::object SOFAPYTHON3_API dataToPython(BaseData* d);

/// RVO optimized function. Don't care about copy on the return code.
void SOFAPYTHON3_API fillBaseObjectdescription(sofa::core::objectmodel::BaseObjectDescription& desc,
const py::dict& dict);
const py::dict& dict);

/// Split the content of the dictionnary 'dict' in three set.
/// On containing the data to parent, one containing the data to copy and on containing the data to parse in the BaseObjectDescription
void SOFAPYTHON3_API processKwargsForObjectCreation(const py::dict dict,
py::list& parametersToLink,
py::list& parametersToCopy,
sofa::core::objectmodel::BaseObjectDescription& parametersAsString);

template<typename T>
void copyScalar(BaseData* a, const AbstractTypeInfo& nfo, py::array_t<T, py::array::c_style> src)
Expand Down
30 changes: 26 additions & 4 deletions bindings/Sofa/src/SofaPython3/Sofa/Core/Binding_Node.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -157,16 +157,21 @@ py::object addObject(Node& self, BaseObject* object)
/// Implement the addObject function.
py::object addObjectKwargs(Node* self, const std::string& type, const py::kwargs& kwargs)
{
/// Check that the name of the component is not one of the protected keywords (like: children, nodes,and others...)
if (kwargs.contains("name"))
{
std::string name = py::str(kwargs["name"]);
if (sofapython3::isProtectedKeyword(name))
throw py::value_error("addObject: Cannot call addObject with name " + name + ": Protected keyword");
}

/// Prepare the description to hold the different python attributes as data field's
/// arguments then create the object.
BaseObjectDescription desc {type.c_str(), type.c_str()};
fillBaseObjectdescription(desc, kwargs);
py::list parametersToCopy;
py::list parametersToLink;

processKwargsForObjectCreation(kwargs, parametersToLink, parametersToCopy, desc);
auto object = ObjectFactory::getInstance()->createObject(self, &desc);

/// After calling createObject the returned value can be either a nullptr
Expand Down Expand Up @@ -195,18 +200,26 @@ py::object addObjectKwargs(Node* self, const std::string& type, const py::kwargs
{
BaseData* d = object->findData(py::cast<std::string>(a.first));
if(d)
{
if (parametersToLink.contains(a.first))
d->setParent(a.second.cast<BaseData*>());
else if(parametersToCopy.contains(a.first))
PythonFactory::fromPython(d, py::cast<py::object>(a.second));
d->setPersistent(true);
}else
{
throw py::type_error("Unknown Attribute: '"+py::cast<std::string>(a.first)+"'");
}
}
return PythonFactory::toPython(object.get());
}

/// Implement the addObject function.
/// Implement the add(callable, xxx) function.
py::object addKwargs(Node* self, const py::object& callable, const py::kwargs& kwargs)
{
if(py::isinstance<BaseObject*>(callable))
{
BaseObject* obj = py::cast<BaseObject*>(callable);

self->addObject(obj);
return py::cast(obj);
}
Expand Down Expand Up @@ -258,15 +271,24 @@ py::object addChildKwargs(Node* self, const std::string& name, const py::kwargs&
if (sofapython3::isProtectedKeyword(name))
throw py::value_error("addChild: Cannot call addChild with name " + name + ": Protected keyword");
BaseObjectDescription desc (name.c_str());
fillBaseObjectdescription(desc,kwargs);
py::list parametersToCopy;
py::list parametersToLink;
processKwargsForObjectCreation(kwargs, parametersToLink, parametersToCopy, desc);

auto node=simpleapi::createChild(self, desc);
checkParamUsage(desc);

for(auto a : kwargs)
{
BaseData* d = node->findData(py::cast<std::string>(a.first));
if(d)
{
if (parametersToLink.contains(a.first))
d->setParent(a.second.cast<BaseData*>());
else if(parametersToCopy.contains(a.first))
PythonFactory::fromPython(d, py::cast<py::object>(a.second));
d->setPersistent(true);
}
}

return py::cast(node);
Expand Down
2 changes: 1 addition & 1 deletion bindings/Sofa/tests/Core/ForceField.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@ def createParticle(node, node_name, use_implicit_scheme, use_iterative_solver):
p = node.addChild(node_name)
createIntegrationScheme(p, use_implicit_scheme)
createSolver(p, use_iterative_solver)
dofs = p.addObject('MechanicalObject', name="MO", position=[0, 0, 0])
dofs = p.addObject('MechanicalObject', name="MO", position=[[0, 0, 0]])
p.addObject('UniformMass', totalMass=1.0)

print ("dofs.rest_position " + str(dofs.rest_position.value))
Expand Down
2 changes: 1 addition & 1 deletion bindings/Sofa/tests/Simulation/Node.py
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ def test_GetAttr(self):
def test_init(self):
root = Sofa.Core.Node("rootNode")
c = root.addChild("child1")
c = c.addObject("MechanicalObject", name="MO", position=[0.0,1.0,2.0]*100)
c = c.addObject("MechanicalObject", name="MO", position=[[0.0,1.0,2.0]]*100)
root.init()
print("TYPE: "+str(len(c.position.value)))
self.assertEqual(len(c.position.value), 100)
Expand Down