Allow models to be merged into other models
Previously called "Allow merging models with the Python API in a similar way to how kat script allows it" but edited to be a general issue for submodel merging following discussions in !21 (merged).
The parser allows sub-models to be defined, with export
syntax defining which ports should map to the "outside". These are handled by the parser. It seems like this duplicates the functionality of Model.merge
though. Perhaps we should just have the parser build the sub-model as its own independent model (create a new parser instance to do it), then merge it into the main model using Model.merge
and the mapping defined by export
syntax.
It would be good if we could build models and merge them into other models, with some sort of user-defined mapping of ports. For instance, one might want to build a model that represents a thick mirror (two beam splitters and a space) called model_mirror
. Then you would want to use it in another model, model_ifo
, attaching model_mirror.AR.p1
to model_ifo.BS.p3
for example. I foresee a method of Model
called merge
(unfortunately there's already one there that does something different) that can be called like:
model_ifo.merge(model_mirror, prefix="ITM")
model_ifo.connect(model_ifo.BS.p3, model_ifo.ITM_AR.p1)
The merge
method would rename the component names of model_mirror
to add the specified prefix
, with checks for existing name clashes. We could maybe even make a lightweight ModelContainer
class, which would simply be a namespace for model_mirror
. Then the code could be this:
model_ifo.merge(model_mirror, name="ITM")
model_ifo.connect(model_ifo.BS.p3, model_ifo.ITM.AR.p1) # no longer ITM_AR, but ITM.AR
This would allow the source model's component names to be preserved, and potentially clash with those in the main model. I imagine this would be useful for when the same submodel is merged several times into a model with different names each time.
We should also think about what to do with the source model being merged. Should it be destroyed or invalidated somehow? Or deepcopied before being merged? The latter would allow a submodel to be merged multiple times with different names, such as merging a thick mirror model into an interferometer model to act as ITMs and ETMs.
We would also like kat script support, e.g. this way:
submodel my_cavity (
mirror m1 R=0.99 T=0.01
mirror m2 R=0.99 T=0.01
space m1.p2 m2.p1
export ITMR=&m1.R ETMR=&m2.R inport=m1.p1 outport=m2.p2
)
# or
import my_cavity "my_cavity.kat"
mirror m3
space my_cavity.outport m3.p1
The file importer would need to check for recursive loading etc...