ModelingToolkit @mtkmodel and loop on equations

Greetings Julia community,

I’m currently exploring the possibility of transitioning from a Modelica/Python workflow to a fully Julia-based workflow for my projects. As I’m relatively new to Julia, I’ve encountered an issue while working with @mtkmodel.

The following code snippet demonstrates the problem:

@mtkmodel Circuit1 begin

    @components begin
        pipe = [Pipe() for i in 1:8]
    end
    
    @equations begin
        for i in 1:7
            connect(pipe[i].c_out, pipe[i+1].c_in)
        end
    end
    
end

@mtkbuild circuit_model = Circuit1()

While the above code throws an error: MethodError: Cannot convert an object of type Nothing to an object of type Equation

The following code, which manually lists each connection, works as expected:

@mtkmodel Circuit2 begin

    @components begin
        pipe = [Pipe() for i in 1:8]
    end
    
    @equations begin
        connect(pipe[1].c_out, pipe[2].c_in)
        connect(pipe[2].c_out, pipe[3].c_in)
        connect(pipe[3].c_out, pipe[4].c_in)
        connect(pipe[4].c_out, pipe[5].c_in)
        connect(pipe[5].c_out, pipe[6].c_in)
        connect(pipe[6].c_out, pipe[7].c_in)
        connect(pipe[7].c_out, pipe[8].c_in)
    end
    
end

@mtkbuild circuit_model = Circuit2()

I’d greatly appreciate any insights or suggestions on how to properly loop over the connections within @equations using @mtkmodel.

Thank you in advance for your help!

1 Like

If you want to loop over constructions then you likely want to direct build the ODESystem.

Hi @ChrisRackauckas , can you give an example? The example above is a typical way of how to create discretized volumes like pipes in Modelica. I wonder what the best way to do this with MTK would look like.

@mtkmodel Circuit1 begin

    @components begin
        pipe = [Pipe() for i in 1:8]
    end
    
    @equations begin
        [connect(pipe[i].c_out, pipe[i+1].c_in) for i in 1:7]...
    end
    
end

@mtkbuild circuit_model = Circuit1()

This works.

The for...end syntax returns nothing resulting the above error; maybe we should add a parser for that as well. For now, please use [<> for <>]... syntax.