[AstroPy] Remove a model from a composite model in astropy.modeling

Erik Bray embray at stsci.edu
Fri Aug 21 10:48:31 EDT 2015

On 08/21/2015 06:32 AM, Eric Emsellem wrote:
> Hi
> I would like to know if something like this is possible with
> astropy.modeling:
> Let's imagine I have a composite model made of 3 models, e.g.,
>   > modelC = model1 + model2 + model3
> where each model1, model2, model3 is a custom model or one of the
> integrated ones in astropy.modeling.models.
> Can I do something which would be equivalent to:
>   > modelC.remove(model2)
> where now modelC would be  : model1 + model3
> ???
> Thanks for any tips on this one!

Hi Eric,

Glad to see you're trying out compound models.

right now the easiest way to do what you're asking would just be to take two 
slices that exclude model2 and combine them.  For example with:

 >>> modelC = model1 + model2 + model3

model2 has the index 1 (you can check this via the output of print(modelC)).

Then you can do:

 >>> modelC = modelC[:1] + modelC[2:]

This is even easier if you give names to the individual models so that you don't 
have to worry about their numeric index.  Although in this case it's a little 
awkward because when you use names in slices the end points are *inclusive* so 
you have to know which models come before and after 'B'

 >>> model = model1.rename('A') + model2.rename('B') + model3.rename('C')
 >>> model = model[:'A'] + model['C':]

I could see a case for a .remove() method, as well as .insert(), etc.  But it 
would have to take some care with how it handles the operators.  If you're just 
talking a linear sum it's straightforward enough.  But what if you have:

 >>> model = a + b * c

If you do model.remove('b') should it become  a + c or a * c?  I think in that 
case probably a + c makes sense due to the order of operations.  But what about

 >>> model = a + b ** c?

This is less likely to show up, but is possible.  Neither a + c or a ** c make 
much sense as a result.

So again I think this would be a good thing to have but there are subtleties 
that would have to be worked out.


More information about the AstroPy mailing list