Add model splice context manager
Just documenting an idea. In Pykat for getting an interferometer model to its operating point we often deepcopy the model over and over again to temporarily add or remove components and detectors. This works, but deepcopying is an expensive operation and a little bit dangerous e.g. if objects from one model get mixed with objects from another. Another approach could be to implement a context manager like this in
@contextmanager def spliced(self, from_node, to_node=None, via=None): """Splices out any components and spaces between `from_node` and `to_node` and connects directly.""" # Actually remove elements between the nodes... subnetwork = self._get_subnetwork_between(from_node, to_node) # Doesn't exist yet. for element in subnetwork: self.remove(element) # Also want to remove spaces etc.? # Run the user's context. yield # Restore the spliced elements. for element in subnetwork: self.add(element)
This would be used like this:
model = ... with model.spiced(omc.p2.o): # Removes everything connected to omc.p2.o # Do stuff, e.g. model.run() # omc.p2.o components are back again.