multiscale / muscle3

The third major version of the MUltiScale Coupling Library and Environment
Apache License 2.0
25 stars 13 forks source link

Recursive dictionary on C++ and python/matlab #261

Closed rnouail closed 1 year ago

rnouail commented 1 year ago

Dear Developpers,

I would like to define a dictionary structure to share data between a c++ model and a matlab/python model. At the end, the structure will be relatively complex, but to start, let try with this example:

data toto one_float=8.3 a_second_float=3.4 a_vector=[1 2 3] a_sub_sub_struct a_int=3 a_float=2.0 tata a_float_for_tata=3

Is it possible to create this kind of structure with the dictionary object ? I found an example of dict object in the C++ API but no a structure like I would like to do and I don't find example of dictionary for python.

Could you help me ?

Thank you in advance

Regards

Rémy

maarten-ic commented 1 year ago

Hi Rémy,

In Python you can pass a regular dictionary as data in a message:

libmuscle.Message(timestamp, data={
    "toto": {
        "one_float": 8.3,
        "a_second_float": 3.4,
        "a_vector": numpy.array([1, 2, 3]),
        "a_sub_sub_struct": {
            "a_int": 3,
            "a_float": 2.0,
        },
    },
    "tata": {
        "a_float_for_tata": 3,
    }
})

Doing this in MATLAB complicates things a bit, because you need to explicitly create py.dict objects, a smaller example:

toto = py.dict()
toto{"one_float"} = 8.3
a_sub_sub_struct = py.dict()
a_sub_sub_struct{"a_int"} = 3
toto{"a_sub_sub_struct"} = a_sub_sub_struct
data{"toto"} = toto
% etc.

In C++ it should be possible roughly as follows (not tested though):

Data data = Data::dict(
    "toto", Data::dict(
        "one_float", 8.3,
        "a_sub_sub_struct", Data::dict("a_int", 3)
    )
);
maarten-ic commented 1 year ago

Update, see this help page for more ways of creating the python dictionaries from MATLAB: https://www.mathworks.com/help/matlab/matlab_external/python-dict-variables.html

rnouail commented 1 year ago

Thank a lot for the tips, it has been very helpful.