a
    ߙfb                    @   s  d Z ddlZddlZddlZddlZddlZddlZddlZddlZddl	m
Z
mZ ddlmZ ddlmZ ddlZddlmZmZ ddlmZ ddlmZmZmZ dd	lmZ dd
lmZmZmZmZmZ ddl m!Z! ddl"m#Z#m$Z$ ddl%m&Z&m'Z'm(Z(m)Z)m*Z*m+Z+ ddl,m-Z-m.Z. ddl/m0Z0m1Z1m2Z2m3Z3 g dZ4dd Z5G dd de6Z7G dd dej8Z9G dd de9dZ:G dd de:Z;G dd de;Z<G dd  d e;Z=d!d" Z>d#d$ Z?d%d& Z@e>ejAe>ejBe>ejCe>ejDe>ejEe?e@d'ZFe+ ZGd(d) ZHG d*d+ d+e:ZId,d- ZJd.d/ ZKd0d1 ZLd2d3 ZMg d4ZNi ZOePeND ]\ZQZReRD ]ZSeQeOeS< qLq@[Q[S[RdGd5d6ZTdHd8d9ZUdId:d;ZVdd<d=d>ZWd?d@ ZXdJdAdBZYdKdCdDZZdEdF Z[dS )Lad  
This module defines base classes for all models.  The base class of all
models is `~astropy.modeling.Model`. `~astropy.modeling.FittableModel` is
the base class for all fittable models. Fittable models can be linear or
nonlinear in a regression analysis sense.

All models provide a `__call__` method which performs the transformation in
a purely mathematical way, i.e. the models are unitless.  Model instances can
represent either a single model, or a "model set" representing multiple copies
of the same type of model, but with potentially different values of the
parameters in each model making up the set.
    N)defaultdictdeque)	signature)chain)indentmetadata)Table)Quantity
UnitsErrordimensionless_unscaled)quantity_asanyarray)sharedmethodfind_current_modulecheck_broadcastIncompatibleShapeError
isiterable)make_function_with_signature)	add_arrayextract_array   )combine_labelsmake_binary_operator_evalget_inputs_and_params_combine_equivalency_dict_ConstraintsDict_SpecialOperatorsDict)ModelBoundingBoxCompoundBoundingBox)	ParameterInputParameterErrorparam_repr_oneline_tofloat)
ModelFittableModelFittable1DModelFittable2DModelCompoundModel
fix_inputscustom_modelModelDefinitionErrorbind_bounding_boxbind_compound_bounding_boxc                    s    fddS )z
    Returns a function that evaluates a given Python arithmetic operator
    between two models.  The operator should be given as a string, like ``'+'``
    or ``'**'``.
    c                    s   t | |fi  S N)r&   )leftrightkwargsoper 4lib/python3.9/site-packages/astropy/modeling/core.py<lambda>:       z_model_oper.<locals>.<lambda>r2   )r1   r0   r2   r/   r3   _model_oper4   s    r6   c                   @   s   e Zd ZdZdS )r)   z&Used for incorrect models definitions.N)__name__
__module____qualname____doc__r2   r2   r2   r3   r)   =   s   r)   c                       s   e Zd ZdZdZ fddZ fddZdd Zd	d
 Zdd Z	e
dd Ze
dd Zd&ddZdd Zdd Zdd Z fddZedZedZedZedZed Zed!Zed"Zed#Zg f fd$d%	Z  ZS )'
_ModelMetaz
    Metaclass for Model.

    Currently just handles auto-generating the param_names list based on
    Parameter descriptors declared at the class-level of Model subclasses.
    Fc              
      s  d|vr| j |d< dtdfdtdfdtdfdtd	fd
tdfdtdfdtdfdtdfg}dd | D |d< |D ]\}}|||< qt | |||}t|d }|D ](}	|	jD ]}
t|
trt|
j	| }qqtt
|}|j	rt|drt||_n
t||_|S )N_is_dynamic__add__+__sub__-__mul__*__truediv__/__pow__**__or__|__and__&_fix_inputsr'   c                 S   s    i | ]\}}t |tr||qS r2   )
isinstancer   .0kvr2   r2   r3   
<dictcomp>h   s   
z&_ModelMeta.__new__.<locals>.<dictcomp>_parameters__param_names)r<   r6   itemssuper__new__list__mro__
issubclassr"   rR   dictfromkeyshasattrtuplerS   param_names)mclsnamebasesmembersZopermethodsZ
opermethodZopercallclsr^   basetbase	__class__r2   r3   rV   Y   s4    












z_ModelMeta.__new__c           	         sx   t t| ||| | | | | i }|D ]6}|jD ]*}t|tr:| j	 D ]\}}|||< qRq:q0| 
|| d S r,   )rU   r;   __init___create_inverse_property_create_bounding_box_propertyrX   rY   r"   rR   rT   _handle_special_methods)	rc   r`   ra   rb   pdictrd   re   parnamevalrf   r2   r3   rh      s    



z_ModelMeta.__init__c                 C   s   |   S )z3
        Custom repr for Model subclasses.
        )_format_cls_reprrc   r2   r2   r3   __repr__   s    z_ModelMeta.__repr__c                 C   s   | t|  dS )z
        Repr for IPython's pretty printer.

        By default IPython "pretty prints" classes, so we need to implement
        this so that IPython displays the custom repr for Models.
        N)textrepr)rc   pcycler2   r2   r3   _repr_pretty_   s    z_ModelMeta._repr_pretty_c                 C   sb   | j s| jS t| j}t|D ]}|dr||= qdD ]}||v r8||= q8t| | j| j|ffS )N_abc_)rh   __call__)r<   r7   rZ   __dict__rW   
startswithtype	__bases__)rc   rb   keyr2   r2   r3   
__reduce__   s    

z_ModelMeta.__reduce__c                 C   s   | j S )z
        The name of this model class--equivalent to ``cls.__name__``.

        This attribute is provided for symmetry with the `Model.name` attribute
        of model instances.
        )r7   rp   r2   r2   r3   r`      s    	z_ModelMeta.namec                 C   s   | j dpt|  S )z
        A class-level property that determines whether the class is a concrete
        implementation of a Model--i.e. it is not some abstract base class or
        internal implementation detail (i.e. begins with '_').
        _)r7   rz   inspect
isabstractrp   r2   r2   r3   _is_concrete   s    z_ModelMeta._is_concreteNc                 C   s   t d}|r|j}nd}|du r&| j}|du r6| j}nBt|tsJtdn.t|t| jkrxt| j dt| j d|du r| j	}nBt|tstdn.t|t| j	krt| j dt| j	 dt
|| f||d	}||_||_|S )
a  
        Creates a copy of this model class with a new name, inputs or outputs.

        The new class is technically a subclass of the original class, so that
        instance and type checks will still work.  For example::

            >>> from astropy.modeling.models import Rotation2D
            >>> SkyRotation = Rotation2D.rename('SkyRotation')
            >>> SkyRotation
            <class 'astropy.modeling.core.SkyRotation'>
            Name: SkyRotation (Rotation2D)
            N_inputs: 2
            N_outputs: 2
            Fittable parameters: ('angle',)
            >>> issubclass(SkyRotation, Rotation2D)
            True
            >>> r = SkyRotation(90)
            >>> isinstance(r, Rotation2D)
            True
           __main__Nz+Expected 'inputs' to be a tuple of strings.z	 expects z inputsz,Expected 'outputs' to be a tuple of strings.z outputs)inputsoutputs)r   r7   r`   r   rL   r]   	TypeErrorlen
ValueErrorr   r{   r8   r9   )rc   r`   r   r   modmodnameZnew_clsr2   r2   r3   rename   s,    



z_ModelMeta.renamec                 C   sB   | d}|d u s | jd tu r$d S t|tr4|j}|| _| `d S )Ninverser   )getr|   objectrL   propertyfget_inverser   )rc   rb   r   r2   r2   r3   ri      s    

z#_ModelMeta._create_inverse_propertyc              
   C   s   | d}|du s | jd tu r$dS t|tr4|j}t|szt| |}W q t	y~ } zt
|jd W Y d}~qd}~0 0 n"t|}t|jdkr| ||}|| _| `dS )z
        Takes any bounding_box defined on a concrete Model subclass (either
        as a fixed tuple or a property or method) and wraps it in the generic
        getter/setter interface for the bounding_box attribute.
        bounding_boxNr   r   )r   r|   r   rL   r   r   callabler   validater   r)   argsr   r   
parameters_create_bounding_box_subclass_bounding_boxr   )rc   rb   r   excsigr2   r2   r3   rj     s     


&
z(_ModelMeta._create_bounding_box_propertyc                    s    fdd}g }t |j D ]@\}}|dkr0q|j|ju rLtd| j||j|jf q||_	t
| j dtfd|iS )a  
        For Models that take optional arguments for defining their bounding
        box, we create a subclass of ModelBoundingBox with a ``__call__`` method
        that supports those additional arguments.

        Takes the function's Signature as an argument since that is already
        computed in _create_bounding_box_property, so no need to duplicate that
        effort.
        c                    s    | j fi |S r,   )Z_model)selfr0   funcr2   r3   rx   L  s    z:_ModelMeta._create_bounding_box_subclass.<locals>.__call__r   zThe bounding_box method for {0} is not correctly defined: If defined as a method all arguments to that method (besides self) must be keyword arguments with default values that can be used to compute a default bounding box.r   rx   )	enumerater   valuesdefaultemptyr)   formatr`   appendZ__signature__r{   r   )rc   r   r   rx   r0   idxparamr2   r   r3   r   5  s     z(_ModelMeta._create_bounding_box_subclassc                    sD  dd }d|vr~d|v r~t |d tr~|d dkr~ fdd}d}td	d
dtjfddg}t|||ddd}||  | _d|vr@t s@ j	r@t
dd | D rd}g }| D ]8\}}	|	j}
|	j}|d urt|
|dd}
|||
f qndt|  }i } fdd}t|||dd}||  | _d S )Nc                 S   s:   |j | _ t|| jj| _t|dr6|j d| j | _d S )Nr9   .)r8   getattrr7   r:   r\   r9   )wrapperrc   r2   r2   r3   update_wrapperg  s    
z:_ModelMeta._handle_special_methods.<locals>.update_wrapperrx   n_inputsr   c                    s   t | j|i |S )z+Evaluate this model on the supplied inputs.)rU   rx   )r   r   r0   rg   rc   r2   r3   rx   x  s    z4_ModelMeta._handle_special_methods.<locals>.__call__r   )model_set_axisN)with_bounding_boxF
fill_value)equivalenciesN)
inputs_mapNr   
new_inputs)Zvarargs	varkwargsrh   c                 s   s   | ]}|j d uV  qd S r,   r   rN   rt   r2   r2   r3   	<genexpr>  r5   z5_ModelMeta._handle_special_methods.<locals>.<genexpr>Fcopyc                    s   t | j|i |S r,   )rU   rh   )r   paramsr0   r   r2   r3   rh     s    z4_ModelMeta._handle_special_methods.<locals>.__init__r0   )r   )rL   intrZ   npnanr   rx   r   r   rR   allr   rT   r   unitr	   r   r]   keysrh   )rc   rb   rl   r   rx   r   r0   Znew_call
param_nameZ	param_valr   r   rh   Znew_initrf   rp   r3   rk   d  sN    




z"_ModelMeta._handle_special_methodsr>   r@   rB   rD   rF   rH   rJ   r'   c                    s   t   g}| js|d S dd }znd|| fd| jfd| jfg}| jrX|d| jf || D ]$\}}|dur`|| d	|  q`d
|W S  ty   |d  Y S 0 dS )
        Internal implementation of ``__repr__``.

        This is separated out for ease of use by subclasses that wish to
        override the default ``__repr__`` while keeping the same basic
        formatting.
        r   c                 S   sp   g }|   dd  D ]8}t|ts&qnt|s<|jdr@ qN||j q|rj| j dd	| dS | jS )Nr   r   z (z -> ))
mrorY   r"   r   r   r7   rz   r   r`   join)rc   ra   rd   r2   r2   r3   format_inheritance  s    


z7_ModelMeta._format_cls_repr.<locals>.format_inheritanceNameZN_inputsZ	N_outputszFittable parametersN: 
)	rU   rq   r   r   	n_outputsr^   r   r   	Exception)rc   keywordspartsr   default_keywordskeywordvaluerf   r2   r3   ro     s&    
z_ModelMeta._format_cls_repr)NNN)r7   r8   r9   r:   r<   rV   rh   rq   rv   r~   r   r`   r   r   ri   rj   r   rk   r6   r=   r?   rA   rC   rE   rG   rI   rK   ro   __classcell__r2   r2   rf   r3   r;   A   s2   +




2(/Tr;   c                       sb  e Zd ZdZejZdZdZdZ	dZ
dZdZdZdZe ZdZdZdZdZdZdZdZdZdZdZdZddd	 fd
d
Zdd Zdd Ze dd Z!e!j"dd Z!e dd Z#e#j"dd Z#e dd Z	e dd Z
dd Z$dd Z%e dd Z&e d d! Z'e d"d# Z(d$d% Z)d&d' Z*d(d) Z+e,d*d+ Z- fd,d-Z.d.d/ Z/dd0d1Z0e d2d3 Z1d4d5 Z2d6d7 Z3d8d9 Z4d:d; Z5d<d= Z6e d>d? Z7d@dA Z8dBdC Z9e dDdE Z:e:j"dFdE Z:e dGdH Z;e dIdJ Z<e dKdL Z=e=j"dMdL Z=e dNdO Z>e>j"dPdO Z>e dQdR Z?e dSdT Z@e dUdV ZAe dWdX ZBe dYdZ ZCd[d\ ZDe d]d^ ZEeEj"d_d^ ZEeEjFd`d^ ZEe dadb ZGe dcdd ZHeHj"dedd ZHdfdg ZIeHjFdhdd ZHe didj ZJe dkdl ZKeKj"dmdl ZKe dndo ZLeLj"dpdo ZLe dqdr ZMdsdt ZNdudv ZOdwdx ZPdydz ZQe d{d| ZRe d}d~ ZSeTjUdd ZVdd ZWdddZXe dd ZYe dd ZZdd Z[e,dd Z\dd Z]dddddZ^dddZ_dd Z`e,dd Zadd Zbdd Zcdd Zddd Zedd Zfegdd ZhdddZie dd Zjdd Zkdd Zldd Zmdd Zndd Zodd Zpdd ZqdddZrg i i fddZsg i fddZt  ZuS )r"   ad  
    Base class for all models.

    This is an abstract class and should not be instantiated directly.

    The following initialization arguments apply to the majority of Model
    subclasses by default (exceptions include specialized utility models
    like `~astropy.modeling.mappings.Mapping`).  Parametric models take all
    their parameters as arguments, followed by any of the following optional
    keyword arguments:

    Parameters
    ----------
    name : str, optional
        A human-friendly name associated with this model instance
        (particularly useful for identifying the individual components of a
        compound model).

    meta : dict, optional
        An optional dict of user-defined metadata to attach to this model.
        How this is used and interpreted is up to the user or individual use
        case.

    n_models : int, optional
        If given an integer greater than 1, a *model set* is instantiated
        instead of a single model.  This affects how the parameter arguments
        are interpreted.  In this case each parameter must be given as a list
        or array--elements of this array are taken along the first axis (or
        ``model_set_axis`` if specified), such that the Nth element is the
        value of that parameter for the Nth model in the set.

        See the section on model sets in the documentation for more details.

    model_set_axis : int, optional
        This argument only applies when creating a model set (i.e. ``n_models >
        1``).  It changes how parameter values are interpreted.  Normally the
        first axis of each input parameter array (properly the 0th axis) is
        taken as the axis corresponding to the model sets.  However, any axis
        of an input array may be taken as this "model set axis".  This accepts
        negative integers as well--for example use ``model_set_axis=-1`` if the
        last (most rapidly changing) axis should be associated with the model
        sets. Also, ``model_set_axis=False`` can be used to tell that a given
        input should be used to evaluate all the models in the model set.

    fixed : dict, optional
        Dictionary ``{parameter_name: bool}`` setting the fixed constraint
        for one or more parameters.  `True` means the parameter is held fixed
        during fitting and is prevented from updates once an instance of the
        model has been created.

        Alternatively the `~astropy.modeling.Parameter.fixed` property of a
        parameter may be used to lock or unlock individual parameters.

    tied : dict, optional
        Dictionary ``{parameter_name: callable}`` of parameters which are
        linked to some other parameter. The dictionary values are callables
        providing the linking relationship.

        Alternatively the `~astropy.modeling.Parameter.tied` property of a
        parameter may be used to set the ``tied`` constraint on individual
        parameters.

    bounds : dict, optional
        A dictionary ``{parameter_name: value}`` of lower and upper bounds of
        parameters. Keys are parameter names. Values are a list or a tuple
        of length 2 giving the desired range for the parameter.

        Alternatively the `~astropy.modeling.Parameter.min` and
        `~astropy.modeling.Parameter.max` or
        ~astropy.modeling.Parameter.bounds` properties of a parameter may be
        used to set bounds on individual parameters.

    eqcons : list, optional
        List of functions of length n such that ``eqcons[j](x0, *args) == 0.0``
        in a successfully optimized problem.

    ineqcons : list, optional
        List of functions of length n such that ``ieqcons[j](x0, *args) >=
        0.0`` is a successfully optimized problem.

    Examples
    --------
    >>> from astropy.modeling import models
    >>> def tie_center(model):
    ...         mean = 50 * model.stddev
    ...         return mean
    >>> tied_parameters = {'mean': tie_center}

    Specify that ``'mean'`` is a tied parameter in one of two ways:

    >>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3,
    ...                        tied=tied_parameters)

    or

    >>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3)
    >>> g1.mean.tied
    False
    >>> g1.mean.tied = tie_center
    >>> g1.mean.tied
    <function tie_center at 0x...>

    Fixed parameters:

    >>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3,
    ...                        fixed={'stddev': True})
    >>> g1.stddev.fixed
    True

    or

    >>> g1 = models.Gaussian1D(amplitude=10, mean=5, stddev=.3)
    >>> g1.stddev.fixed
    False
    >>> g1.stddev.fixed = True
    >>> g1.stddev.fixed
    True
    )eqconsineqconsr2   r   TFNr   )metar`   c          
         s   t    |   |d ur || _|| _| jj}|D ]F}t|tr2|j	
 D ],\}}t|}	| |	_|| jvrJ|	| j|< qJq2| | | |}| || |   |   d S r,   )rU   rh   _default_inputs_outputsr   _namerg   rX   rY   r"   rR   rT   r   deepcopymodelry   _initialize_constraints_initialize_setters_initialize_parameters_initialize_slices_initialize_unit_support)
r   r   r`   r   r0   r   rc   rm   rn   Znewparrf   r2   r3   rh     s$    





zModel.__init__c                 C   s   | j dkr"| jdkr"d| _d| _nz| j dkrD| jdkrDd| _d| _nXz8tdd t| j D | _td	d t| jD | _W n ty   d
| _d
| _Y n0 d S )Nr   )x)yr   )r   r   )zc                 s   s   | ]}d t | V  qdS r   NstrrN   r   r2   r2   r3   r     r5   z0Model._default_inputs_outputs.<locals>.<genexpr>c                 s   s   | ]}d t | V  qdS r   r   r   r2   r2   r3   r     r5   r2   )r   r   _inputs_outputsr]   ranger   r   r2   r2   r3   r     s    zModel._default_inputs_outputsc                    sD   t | dr@ fdd| j D }| D ]\}}t| || q* S )z|
        This exists to inject defaults for settable properties for models
        originating from `custom_model`.
        _settable_propertiesc                    s   i | ]\}}|  ||qS r2   )pop)rN   r`   r   r0   r2   r3   rQ     s   z-Model._initialize_setters.<locals>.<dictcomp>)r\   r   rT   setattr)r   r0   Zsettersr`   r   r2   r   r3   r     s    

zModel._initialize_settersc                 C   s   | j S r,   r   r   r2   r2   r3   r     s    zModel.inputsc                 C   s<   t || jkr*td| j dt | d|| _|   d S )N	Expected z number of inputs, got r   )r   r   r   r   r   r   rn   r2   r2   r3   r     s    c                 C   s   | j S r,   )r   r   r2   r2   r3   r     s    zModel.outputsc                 C   s4   t || jkr*td| j dt | d|| _d S )Nr   z number of outputs, got r   )r   r   r   r   r   r2   r2   r3   r     s    c                 C   sl   t | jdrdt| jjtrdzt| jjW S  tyb   zt| jW  Y S  ty\   Y Y dS 0 Y n0 | jjS )Nr   r   )	r\   rg   rL   r   r   r   r   r   AttributeErrorr   r2   r2   r3   r     s    zModel.n_inputsc                 C   sl   t | jdrdt| jjtrdzt| jjW S  tyb   zt| jW  Y S  ty\   Y Y dS 0 Y n0 | jjS )Nr   r   )	r\   rg   rL   r   r   r   r   r   r   r   r2   r2   r3   r     s    zModel.n_outputsc                 C   s   t S )z
        This is a hook which customises the behavior of modeling.separable.

        This allows complex subclasses to customise the separability matrix.
        If it returns `NotImplemented` the default behavior is used.
        )NotImplementedr   r2   r2   r3   _calculate_separability_matrix&  s    z$Model._calculate_separability_matrixc                    sH   t  jtr" fdd jD  _t  jtrD fdd jD  _dS )z
        Convert self._input_units_strict and
        self.input_units_allow_dimensionless to dictionaries
        mapping input name to a boolean value.
        c                    s   i | ]}| j qS r2   )_input_units_strictrN   r}   r   r2   r3   rQ   6  s   z2Model._initialize_unit_support.<locals>.<dictcomp>c                    s   i | ]}| j qS r2   ) _input_units_allow_dimensionlessr   r   r2   r3   rQ   :  s   N)rL   r   boolr   r   r   r2   r   r3   r   /  s    

zModel._initialize_unit_supportc                    s8   | j  t tr$ fdd| jD S tt| j  S )a}  
        Enforce strict units on inputs to evaluate. If this is set to True,
        input values to evaluate will be in the exact units specified by
        input_units. If the input quantities are convertible to input_units,
        they are converted. If this is a dictionary then it should map input
        name to a bool to set strict input units for that parameter.
        c                    s   i | ]
}| qS r2   r2   r   rn   r2   r3   rQ   H  r5   z,Model.input_units_strict.<locals>.<dictcomp>)r   rL   r   r   rZ   zipr   r   r2   r   r3   input_units_strict=  s    	
zModel.input_units_strictc                    s8   | j  t tr$ fdd| jD S tt| j  S )a\  
        Allow dimensionless input (and corresponding output). If this is True,
        input values to evaluate will gain the units specified in input_units. If
        this is a dictionary then it should map input name to a bool to allow
        dimensionless numbers for that input.
        Only has an effect if input_units is defined.
        c                    s   i | ]
}| qS r2   r2   r   r   r2   r3   rQ   W  r5   z9Model.input_units_allow_dimensionless.<locals>.<dictcomp>)r   rL   r   r   rZ   r   r   r   r2   r   r3   input_units_allow_dimensionlessK  s    

z%Model.input_units_allow_dimensionlessc                 C   s*   dd | j ddD }t|dkp(t|S )a  
        True if this model has been created with `~astropy.units.Quantity`
        objects or if there are no parameters.

        This can be used to determine if this model should be evaluated with
        `~astropy.units.Quantity` or regular floats.
        c                 S   s   g | ]}t |tqS r2   rL   r	   r   r2   r2   r3   
<listcomp>c  r5   z'Model.uses_quantity.<locals>.<listcomp>T)unitsr   )_param_setsr   any)r   Zpisqr2   r2   r3   uses_quantityZ  s    	zModel.uses_quantityc                 C   s   |   S r,   )_format_reprr   r2   r2   r3   rq   f  s    zModel.__repr__c                 C   s   |   S r,   )_format_strr   r2   r2   r3   __str__i  s    zModel.__str__c                 C   s   | j S r,   )	_n_modelsr   r2   r2   r3   __len__l  s    zModel.__len__c                 C   s   t dd | D S )Nc                 s   s   | ]}|d kr|V  qdS )r   Nr2   rN   itemr2   r2   r3   r   q  r5   z$Model._strip_ones.<locals>.<genexpr>)r]   )Zintupr2   r2   r3   _strip_oneso  s    zModel._strip_onesc                    sZ  t | tr| j}| j}|d ur2|| jv r2| j| }t|}|jd urT|| | | j| d }|dkrnd}t	|j
}|dkrd}| j| d }t||ks| || |krtd||t||||jd u rt |tr|j|_|j|_n||_n.t |ts td|j d|j|_|j|_n$|dv rH|| j|< nt || d S )	Nshaper2   r   sizez_Value for parameter {0} does not match shape or size
expected by model ({1}, {2}) vs ({3}, {4})zThe 'z]' parameter should be given as a Quantity because it was originally initialized as a Quantity)fittablelinear)rL   r&   rS   r^   ry   r!   
_validator_param_metricsr   arrayr  r
  r  r   r   r   r	   _unitr   r
   r`   rU   __setattr__)r   attrr   r^   r   ZeshapeZvshapeZesizerf   r2   r3   r  s  sF    






zModel.__setattr__c                    s<   j |i |\}}jddd  fdd}||||fS )zZ
        Model specific input setup that needs to occur prior to model evaluation
        T)rawr   c                    s   j t|   S r,   )evaluater   r   r   r   r2   r3   r    s    z%Model._pre_evaluate.<locals>.evaluate)prepare_inputsr   )r   r   r0   r   broadcasted_shapesr  r2   r  r3   _pre_evaluate  s    zModel._pre_evaluatec                 C   sP   d}t |tr|rLz
| j}W n ty.   Y n0 t |trLt |tsL|| }|S )as  
        Return the ``bounding_box`` of a model if it exists or ``None``
        otherwise.

        Parameters
        ----------
        with_bbox :
            The value of the ``with_bounding_box`` keyword argument
            when calling the model. Default is `True` for usage when
            looking up the model's ``bounding_box`` without risk of error.
        N)rL   r   r   NotImplementedErrorr   )r   	with_bboxbboxr2   r2   r3   get_bounding_box  s    
zModel.get_bounding_boxc                 C   s   | j S )zDThe inputs used to determine input_shape for bounding_box evaluation)r   r   r2   r2   r3   	_argnames  s    zModel._argnamesc                 C   s   t |}|r|rt||d k r<td| d|d  d|| | jkrz|| }W n typ   t|}Y n0 td| d| d| j d|S )	z
        Perform basic validation of a single model input's shape
            -- it has the minimum dimensions for the given model_set_axis

        Returns the shape of the input if validation succeeds.
        r   zFor model_set_axis=z, all inputs must be at least z-dimensional.zInput argument 'z9' does not have the correct dimensions in model_set_axis=z for a model set with n_models=r   )r   r  r   r   r  
IndexErrorr   )r   _inputr   argnamesr   check_model_set_axisinput_shapeargnamer2   r2   r3   _validate_input_shape  s*    
zModel._validate_input_shapec           	   
   C   s\   | j dko|du}g }t|D ] \}}|| ||||| qt| }|du rXtd|S )aG  
        Perform basic validation of model inputs
            --that they are mutually broadcastable and that they have
            the minimum dimensions for the given model_set_axis.

        If validation succeeds, returns the total shape that will result from
        broadcasting the input arrays with each other.
        r   FNz9All inputs must have identical shapes or must be scalars.)r  r   r   r$  r   r   )	r   r   r   r   r!  
all_shapesr   r  r"  r2   r2   r3   _validate_input_shapes  s    
zModel._validate_input_shapesc                 C   s   |  || j| jS )z+Get input shape for bounding_box evaluation)r&  r  r   )r   r   r2   r2   r3   r"    s    zModel.input_shapec                 C   s<   |  |}t|tr|r0|dur0||||}n||}|S )z
        Generic model evaluation routine
            Selects and evaluates model with or without bounding_box enforcement
        N)r  rL   r   r  )r   r  r   r   r  r  r   r2   r2   r3   _generic_evaluate  s
    
zModel._generic_evaluatec                 K   sX   |  |du r| jdkr|f}| j|g|R i |}| ||}| jdkrT|d S |S )zF
        Model specific post evaluation processing of outputs
        Nr   r   )r  r   prepare_outputs_process_output_unitsr   r   r   r  r  r0   r2   r2   r3   _post_evaluate  s    
zModel._post_evaluatec                 C   s   t | t S r,   rL   r&   r   r2   r2   r3   bbox_with_units#  s    zModel.bbox_with_unitsc           	      O   sn   | j |i |\}}|dd}|dtj}| j|i |\}}}}| ||||}| j||||fi |S )z
        Evaluate this model using the given input(s) and the parameter values
        that were specified when the model was instantiated.
        r   Fr   )!_get_renamed_inputs_as_positionalr   r   r   r  r'  r+  )	r   r   r0   r  r   r  r   r  r   r2   r2   r3   rx   '  s    zModel.__call__c           	      O   s   dd }t |}||\}}|t | }|| jk rJtd| j d| n || jkrjtd| j d| |dkrg }| jD ]}|||  q|nT|| jkrt|}g }| jD ]0}||v r|||  q||d  |d= qn|}||fS )Nc                 S   sD   g d}i }t |  }|D ]}||vr| | ||< | |= q|| fS )N)r   r   r   r   r   )rW   r   )r0   r   r   Zallkeysr}   r2   r2   r3   _keyword2positional=  s    zDModel._get_renamed_inputs_as_positional.<locals>._keyword2positionalz#Missing input arguments - expected z, got z$Too many input arguments - expected r   )r   r   r   r   r   rW   )	r   r   r0   r/  Zn_argsr   Z
n_all_argsnew_argsrO   r2   r2   r3   r.  <  s,    





z'Model._get_renamed_inputs_as_positionalc                 C   s   | j S )z+User-provided name for this model instance.r   r   r2   r2   r3   r`   t  s    z
Model.namec                 C   s
   || _ dS )z"Assign a (new) name to this model.Nr1  r   r2   r2   r3   r`   z  s    c                 C   s   | j S )a0  
        The index of the model set axis--that is the axis of a parameter array
        that pertains to which model a parameter value pertains to--as
        specified when the model was initialized.

        See the documentation on :ref:`astropy:modeling-model-sets`
        for more details.
        )_model_set_axisr   r2   r2   r3   r     s    zModel.model_set_axisc                 C   s   |   S )z
        Return parameters as a pset.

        This is a list with one item per parameter set, which is an array of
        that parameter's values across all parameter sets, with the last axis
        associated with the parameter set.
        )r   r   r2   r2   r3   
param_sets  s    
zModel.param_setsc                 C   sN   | j s| jS |   | j| j d  d j}| j| j d  d j}| j|| S )z
        A flattened array of all parameter values in all parameter sets.

        Fittable parameters maintain this list and fitters modify it.
        r   slice)r^   _parameters_parameters_to_arrayr  startstop)r   r8  r9  r2   r2   r3   r     s    zModel.parametersc              
   C   s   | j s
dS | j| j d  d j}| j| j d  d j}z t| }|| j||< W n2 ty } zt	d
|W Y d}~n
d}~0 0 |   dS )zl
        Assigning to this attribute updates the parameters array rather than
        replacing it.
        Nr   r4  r5  zJInput parameter values not compatible with the model parameters array: {0})r^   r  r8  r9  r   r  Zflattenr6  r   r   r   _array_to_parameters)r   r   r8  r9  er2   r2   r3   r     s    c                 C   s   t | dsd| _| jS )a+  
        This is a boolean property that indicates whether or not accessing constraints
        automatically check the constituent models current values. It defaults to True
        on creation of a model, but for fitting purposes it should be set to False
        for performance reasons.
        _sync_constraintsT)r\   r<  r   r2   r2   r3   sync_constraints  s    
zModel.sync_constraintsc                 C   s   t |tstd|| _d S )Nz5sync_constraints only accepts True or False as values)rL   r   r   r<  r   r   r2   r2   r3   r=    s    
c                 C   s"   t | dr| jrt| d| _| jS )zO
        A ``dict`` mapping parameter names to their fixed constraint.
        _fixedfixed)r\   r=  r   r?  r   r2   r2   r3   r@    s    zModel.fixedc                 C   s"   t | dr| jrt| d| _| jS )z
        A ``dict`` mapping parameter names to their upper and lower bounds as
        ``(min, max)`` tuples or ``[min, max]`` lists.
        _boundsbounds)r\   r=  r   rA  r   r2   r2   r3   rB    s    zModel.boundsc                 C   s"   t | dr| jrt| d| _| jS )zN
        A ``dict`` mapping parameter names to their tied constraint.
        _tiedtied)r\   r=  r   rC  r   r2   r2   r3   rD    s    z
Model.tiedc                 C   s
   | j d S )z'List of parameter equality constraints.r   _mconstraintsr   r2   r2   r3   r     s    zModel.eqconsc                 C   s
   | j d S )z)List of parameter inequality constraints.r   rE  r   r2   r2   r3   r     s    zModel.ineqconsc                 C   s$   z
| j  W n ty   Y dS 0 dS )z\
        Returns True if the model has an analytic or user
        inverse defined.
        FT)r   r  r   r2   r2   r3   has_inverse  s
    
zModel.has_inversec                 C   sF   | j dur| j S | jdur:|  }|tur:| js6d|_|S tddS )a  
        Returns a new `~astropy.modeling.Model` instance which performs the
        inverse transform, if an analytic inverse is defined for this model.

        Even on models that don't have an inverse defined, this property can be
        set with a manually-defined inverse, such a pre-computed or
        experimentally determined inverse (often given as a
        `~astropy.modeling.polynomial.PolynomialModel`, but not by
        requirement).

        A custom inverse can be deleted with ``del model.inverse``.  In this
        case the model's inverse is reset to its default, if a default exists
        (otherwise the default is to raise `NotImplementedError`).

        Note to authors of `~astropy.modeling.Model` subclasses:  To define an
        inverse for a model simply override this property to return the
        appropriate model representing the inverse.  The machinery that will
        make the inverse manually-overridable is added automatically by the
        base class.
        NzUNo analytical or user-supplied inverse transform has been implemented for this model.)_user_inverser   r   _has_inverse_bounding_boxr   r  )r   resultr2   r2   r3   r     s    

zModel.inversec                 C   s$   t |ttd fstd|| _d S )NzThe ``inverse`` attribute may be assigned a `Model` instance or `None` (where `None` explicitly forces the model to have no inverse.)rL   r"   r{   r   rH  r>  r2   r2   r3   r   -  s
    c                 C   s    z| ` W n ty   Y n0 dS )z~
        Resets the model's inverse to its default (if one exists, otherwise
        the model will have no inverse).
        N)rH  r   r   r2   r2   r3   r   7  s    c                 C   s
   | j duS )z
        A flag indicating whether or not a custom inverse model has been
        assigned to this model by a user, via assignment to ``model.inverse``.
        N)rH  r   r2   r2   r3   has_user_inverseC  s    zModel.has_user_inversec                 C   s   | j dur"| j tu rtd| j S | jdu r6tdnNt| jtrH| jS t| jtjrft| |  S | jd| d }| j|| dS dS )a	  
        A `tuple` of length `n_inputs` defining the bounding box limits, or
        raise `NotImplementedError` for no bounding_box.

        The default limits are given by a ``bounding_box`` property or method
        defined in the class body of a specific model.  If not defined then
        this property just raises `NotImplementedError` by default (but may be
        assigned a custom value by a user).  ``bounding_box`` can be set
        manually to an array-like object of shape ``(model.n_inputs, 2)``. For
        further usage, see :ref:`astropy:bounding-boxes`

        The limits are ordered according to the `numpy` ``'C'`` indexing
        convention, and are the reverse of the model input order,
        e.g. for inputs ``('x', 'y', 'z')``, ``bounding_box`` is defined:

        * for 1D: ``(x_low, x_high)``
        * for 2D: ``((y_low, y_high), (x_low, x_high))``
        * for 3D: ``((z_low, z_high), (y_low, y_high), (x_low, x_high))``

        Examples
        --------

        Setting the ``bounding_box`` limits for a 1D and 2D model:

        >>> from astropy.modeling.models import Gaussian1D, Gaussian2D
        >>> model_1d = Gaussian1D()
        >>> model_2d = Gaussian2D(x_stddev=1, y_stddev=1)
        >>> model_1d.bounding_box = (-5, 5)
        >>> model_2d.bounding_box = ((-6, 6), (-5, 5))

        Setting the bounding_box limits for a user-defined 3D `custom_model`:

        >>> from astropy.modeling.models import custom_model
        >>> def const3d(x, y, z, amp=1):
        ...    return amp
        ...
        >>> Const3D = custom_model(const3d)
        >>> model_3d = Const3D()
        >>> model_3d.bounding_box = ((-6, 6), (-5, 5), (-4, 4))

        To reset ``bounding_box`` to its default limits just delete the
        user-defined value--this will reset it back to the default defined
        on the class:

        >>> del model_1d.bounding_box

        To disable the bounding box entirely (including the default),
        set ``bounding_box`` to `None`:

        >>> model_1d.bounding_box = None
        >>> model_1d.bounding_box  # doctest: +IGNORE_EXCEPTION_DETAIL
        Traceback (most recent call last):
        NotImplementedError: No bounding box is defined for this model
        (note: the bounding box was explicitly disabled for this model;
        use `del model.bounding_box` to restore the default bounding box,
        if one is defined for this model).
        NzNo bounding box is defined for this model (note: the bounding box was explicitly disabled for this model; use `del model.bounding_box` to restore the default bounding box, if one is defined for this model).z*No bounding box is defined for this model.r2   r   )	_user_bounding_boxr   r  r   rL   r   types
MethodTyper   )r   r   r2   r2   r3   r   K  s     <


zModel.bounding_boxc              
   C   s   |du rd}t }n>t|ts&t|tr,t}n$t| jtrLt| jtrL| j}nt}|durz|| |}W n2 t	y } zt	|j
d W Y d}~n
d}~0 0 || _dS )z2
        Assigns the bounding box limits.
        Nr   )r   rL   r   rZ   r   r{   rY   r   r   r   r   rM  )r   r   rc   r   r2   r2   r3   r     s$    

$c                 G   s"   t | jtr|| j_ntdd S )Nz/The bounding_box for this model is not compound)rL   rM  r   Z
slice_argsRuntimeErrorr   r   r2   r2   r3   set_slice_args  s    
zModel.set_slice_argsc                 C   s
   d | _ d S r,   rM  r   r2   r2   r3   r     s    c                 C   s
   | j duS z
        A flag indicating whether or not a custom bounding_box has been
        assigned to this model by a user, via assignment to
        ``model.bounding_box``.
        NrS  r   r2   r2   r3   has_user_bounding_box  s    zModel.has_user_bounding_boxc                 C   s   | j S )zD
        Fitter should set covariance matrix, if available.
        )_cov_matrixr   r2   r2   r3   
cov_matrix  s    zModel.cov_matrixc                    s   |_ fddjD }t|tkrg }|D ] }|dd t|jD  q.t|D ]2\ }t	|} fdd|D |_
t|| qXnBdd t|jD }|D ]&}t	|}|d|_
t|| qd S )Nc                    s,   g | ]$} j | d u r j| d u r|qS )F)r@  rD  r   r   r2   r3   r     s   z$Model.cov_matrix.<locals>.<listcomp>c                 S   s"   g | ]}|d krt |ndqS r   Nr   ZsqrtrN   r   r2   r2   r3   r     r5   c                    s   g | ]}|  qS r2   r2   r  )rt   r2   r3   r     r5   c                 S   s"   g | ]}|d krt |ndqS rX  rY  rZ  r2   r2   r3   r     r5   r   )rV  r^   r{   rW   r   r   ZdiagrW  r   r   Zstdr   r   )r   ZcovZunfix_untied_paramsZ
param_stdscr   parr2   )rt   r   r3   rW    s    

c                 C   s   | j S )zV
        Standard deviation of parameters, if covariance matrix is available.
        _stdsr   r2   r2   r3   stds  s    z
Model.stdsc                 C   s
   || _ d S r,   r]  )r   r_  r2   r2   r3   r_    s    c                 C   s&   | j dur| j S td| jjdS )z0 A flag indicating whether a model is separable.Nz4The "separable" property is not defined for model {})
_separabler  r   rg   r7   r   r2   r2   r3   	separable  s    
zModel.separablec           	         s   |   } fdd| jD } fdd| jD }| ||}| D ]:\}}t||}|jdurD|j|j	|_	|j
ddd qDt|tr|  |S )a  
        Return an instance of the model for which the parameter values have
        been converted to the right units for the data, then the units have
        been stripped away.

        The input and output Quantity objects should be given as keyword
        arguments.

        Notes
        -----

        This method is needed in order to be able to fit models with units in
        the parameters, since we need to temporarily strip away the units from
        the model during the fitting (which might be done by e.g. scipy
        functions).

        The units that the parameters should be converted to are not
        necessarily the units of the input data, but are derived from them.
        Model subclasses that want fitting to work in the presence of
        quantities need to define a ``_parameter_units_for_data_units`` method
        that takes the input and output units (as two dictionaries) and
        returns a dictionary giving the target units for each parameter.

        c                    s*   i | ]"} | d ur|t  | dtqS Nr   r   r   rN   inpr   r2   r3   rQ      s   z0Model.without_units_for_data.<locals>.<dictcomp>c                    s*   i | ]"} | d ur|t  | dtqS rb  rc  rN   outr   r2   r3   rQ   #  s   NTZforce)r   r   r   _parameter_units_for_data_unitsrT   r   r   Zquantitytor   	_set_unitrL   r&   strip_units_from_tree	r   r0   r   Zinputs_unitZoutputs_unitZparameter_unitsr`   r   	parameterr2   r   r3   without_units_for_data  s$    




zModel.without_units_for_datac                    sd   | j }|du s|i kr` fdd| jD }| f i || jdkrHffddt| jD }|S )a  
        Return a dictionary of output units for this model given a dictionary
        of fitting inputs and outputs

        The input and output Quantity objects should be given as keyword
        arguments.

        Notes
        -----

        This method is needed in order to be able to fit models with units in
        the parameters, since we need to temporarily strip away the units from
        the model during the fitting (which might be done by e.g. scipy
        functions).

        This method will force extra model evaluations, which maybe computationally
        expensive. To avoid this, one can add a return_units property to the model,
        see :ref:`astropy:models_return_units`.
        Nc                    s   i | ]}| | qS r2   r2   rd  r   r2   r3   rQ   I  r5   z&Model.output_units.<locals>.<dictcomp>r   c                    s"   i | ]\}}|t  | d tqS )r   rc  )rN   indexrg  )r   r2   r3   rQ   O  s   )return_unitsr   r   r   r   )r   r0   r   r   r2   )r0   r   r3   output_units2  s    

zModel.output_unitsc                 C   s4   | j D ](}|jD ]}t||}|jd dd qqd S )NTrh  )	_leaflistr^   r   rk  )r   r  rm   r\  r2   r2   r3   rl  T  s    


zModel.strip_units_from_treec           	         sj   |   } fdd| jD } fdd| jD }| ||}| D ] \}}t||}|j|dd qD|S )a  
        Return an instance of the model which has units for which the parameter
        values are compatible with the data units specified.

        The input and output Quantity objects should be given as keyword
        arguments.

        Notes
        -----

        This method is needed in order to be able to fit models with units in
        the parameters, since we need to temporarily strip away the units from
        the model during the fitting (which might be done by e.g. scipy
        functions).

        The units that the parameters will gain are not necessarily the units
        of the input data, but are derived from them. Model subclasses that
        want fitting to work in the presence of quantities need to define a
        ``_parameter_units_for_data_units`` method that takes the input and output
        units (as two dictionaries) and returns a dictionary giving the target
        units for each parameter.
        c                    s*   i | ]"} | d ur|t  | dtqS rb  rc  rd  r   r2   r3   rQ   r  s   z.Model.with_units_from_data.<locals>.<dictcomp>c                    s*   i | ]"} | d ur|t  | dtqS rb  rc  rf  r   r2   r3   rQ   u  s   Trh  )r   r   r   ri  rT   r   rk  rm  r2   r   r3   with_units_from_dataZ  s    


zModel.with_units_from_datac                 C   s&   | j D ]}t| |jd ur dS qdS )NTF)r^   r   r   )r   r   r2   r2   r3   
_has_units  s    
zModel._has_unitsc                 C   s
   t | dS )Nri  )r\   r   r2   r2   r3   _supports_unit_fitting  s    zModel._supports_unit_fittingc                 O   s   dS )z+Evaluate the model on some input variables.Nr2   r   r   r0   r2   r2   r3   r    s    zModel.evaluatec                 O   s   dS )a  
        Evaluate the sum of any implicit model terms on some input variables.
        This includes any fixed terms used in evaluating a linear model that
        do not have corresponding parameters exposed to the user. The
        prototypical case is `astropy.modeling.functional_models.Shift`, which
        corresponds to a function y = a + bx, where b=1 is intrinsically fixed
        by the type of model, such that sum_of_implicit_terms(x) == x. This
        method is needed by linear fitters to correct the dependent variable
        for the implicit term(s) when solving for the remaining terms
        (ie. a = y - bx).
        Nr2   rw  r2   r2   r3   sum_of_implicit_terms  s    zModel.sum_of_implicit_termsc           
         s  z
| j }W n ty    d}Y n0 t|tr4|  }| j}|du rZ|du rZ|du rZtd|dkr~|durp|g}|dur~|g}|durtj|td}t	||ksJ |dur|d j
|j
krtdnt|d j
}|durt|}|j|krtd|durtdd	 |D tj}|\ }|dur^t|d
 d t fdd	|D }ndd	 |jD }tj| }|ddd }|du r| | }n2zt|| |  }W n ty   tdY n0 nB|du r|j
}	dd	 |	D }tj| }|ddd }|| | 7 }|S )}  
        Evaluate a model at fixed positions, respecting the ``bounding_box``.

        The key difference relative to evaluating the model directly is that
        this method is limited to a bounding box if the `Model.bounding_box`
        attribute is set.

        Parameters
        ----------
        out : `numpy.ndarray`, optional
            An array that the evaluated model will be added to.  If this is not
            given (or given as ``None``), a new array will be created.
        coords : array-like, optional
            An array to be used to translate from the model's input coordinates
            to the ``out`` array. It should have the property that
            ``self(coords)`` yields the same shape as ``out``.  If ``out`` is
            not specified, ``coords`` will be used to determine the shape of
            the returned array. If this is not provided (or None), the model
            will be evaluated on a grid determined by `Model.bounding_box`.

        Returns
        -------
        out : `numpy.ndarray`
            The model added to ``out`` if  ``out`` is not ``None``, or else a
            new array from evaluating the model over ``coords``.
            If ``out`` and ``coords`` are both `None`, the returned array is
            limited to the `Model.bounding_box` limits. If
            `Model.bounding_box` is `None`, ``arr`` or ``coords`` must be
            passed.

        Raises
        ------
        ValueError
            If ``coords`` are not given and the the `Model.bounding_box` of
            this model is not set.

        Examples
        --------
        :ref:`astropy:bounding-boxes`
        N7If no bounding_box is set, coords or out must be input.r   Zdtyper   !inconsistent shape of the output.<the array and model must have the same number of dimensions.c                 S   s0   g | ](}t |t |d  |d  d fqS r   r   r   r   ZmeanZceilrN   Zbbr2   r2   r3   r     s   z Model.render.<locals>.<listcomp>r   c                    s   g | ]}t | qS r2   r   rN   r[  posZ	sub_shaper2   r3   r     s   c                 S   s(   g | ] \}}t || || d  d qS r	  r4  rN   rt   dr2   r2   r3   r      r5   r5  kThe `bounding_box` is larger than the input out in one or more dimensions. Set `model.bounding_box = None`.c                 S   s   g | ]}t |qS r2   r  rN   ir2   r2   r3   r     r5   )r   r  rL   r   r   r   r   
asanyarrayfloatr   r  zerosndimr  astyper   Tr]   mgridr   
r   rg  coordsr  r  pddelta
sub_coordslimitsim_shaper2   r  r3   render  sn    *














zModel.renderc                    sZ   t | dr| jS t | jdrR| jj   dd  rVt fdd| jD S ndS dS )a  
        This property is used to indicate what units or sets of units the
        evaluate method expects, and returns a dictionary mapping inputs to
        units (or `None` if any units are accepted).

        Model sub-classes can also use function annotations in evaluate to
        indicate valid input units, in which case this property should
        not be overridden since it will return the input units based on the
        annotations.
        _input_units__annotations__returnNc                 3   s   | ]}| | fV  qd S r,   r2   rN   r`   annotationsr2   r3   r   .  r5   z$Model.input_units.<locals>.<genexpr>)r\   r  r  r  r   r   rZ   r   r   r2   r  r3   input_units  s    
zModel.input_unitsc                 C   s4   t | dr| jS t | jdr,| jjddS dS dS )a  
        This property is used to indicate what units or sets of units the
        output of evaluate should be in, and returns a dictionary mapping
        outputs to units (or `None` if any units are accepted).

        Model sub-classes can also use function annotations in evaluate to
        indicate valid output units, in which case this property should not be
        overridden since it will return the return units based on the
        annotations.
        _return_unitsr  r  N)r\   r  r  r  r   r   r2   r2   r3   rq  3  s
    
zModel.return_unitsc                 K   s  g }t |D ]\}}|j}|s,|d||< |s6|}nd}|D ]}	z| jrXt||	j}
n|}
W n0 ty   td| j| ||	j	|	jY n0 t
|
t
|kr|
}q>t
|
t
|kr>t||
}q>|| q| j| jkr
| j| j }|s|d  ||d g|  ||ffS )Nr	  r2   zaself input argument {0!r} of shape {1!r} cannot be broadcast with parameter {2!r} of shape {3!r}.r   )r   r  reshapestandard_broadcastingr   r   r   r   r   r`   r   maxr   r   r   extend)r   r   r   r0   Z
broadcastsr   r  r"  Zmax_broadcastr   Z	broadcastZextra_outputsr2   r2   r3   _prepare_inputs_single_modelG  s>    


z"Model._prepare_inputs_single_modelc                 C   sl   t | dkr| S |dk r@t | | }| d| | |d d  S |t | krXt | d }| |d d } | S )z
        Given a shape tuple as the first input, construct a new one by  removing
        that particular axis from the shape and all preceeding axes. Negative axis
        numbers are permittted, where the axis is relative to the last axis.
        r   Nr   )r   )r  Zaxisr2   r2   r3   _remove_axes_from_shapev  s    zModel._remove_axes_from_shapec                 K   s$  g }g }| j }t|D ]\}}	d}
| jdkrX|durX|	jd | |	j|d d   }n|	j}|D ]z}zt|| |j| W n8 ty   td| j	| ||j
| |j|Y n0 t|jd t|
krb| |j|}
qbt|}|du r^t|
|kr&dt|
 | }d| }||	j }|}n,|t|
 }|	jd | d |	j|d   }|	|}nt|
|krt|
| }| j }d| }|	jd |d  | |	j|d d   }|	|}n$|	jt|
 d }t|	||d }|| || q| j| jk r||g| j| j   ||ffS )Nr2   r   FzbModel input argument {0!r} of shape {1!r} cannot be broadcast with parameter {2!r} of shape {3!r}.r	  )r   r   r  r  r   r  r   r   r   r   r`   r   r  r  r   rollaxisr   r   r   r  )r   r   r   Zmodel_set_axis_inputr0   ZreshapedpivotsZmodel_set_axis_paramr   r  Zmax_param_shaper"  r   Z
input_ndimZ
n_new_axesnew_axesZ	new_shapepivotZ	new_inputr2   r2   r3   _prepare_inputs_model_set  sx    




zModel._prepare_inputs_model_set)r   r   c                   s   |du r j } fdd jD }dd |D } | j| |dd} |||} jdkrx j||fi |S  j|||fi |S dS )a  
        This method is used in `~astropy.modeling.Model.__call__` to ensure
        that all the inputs to the model can be broadcast into compatible
        shapes (if one or both of them are input as arrays), particularly if
        there are more than one parameter sets. This also makes sure that (if
        applicable) the units of the input will be compatible with the evaluate
        method.
        Nc                    s   g | ]}t  |qS r2   r   r  r   r2   r3   r     r5   z(Model.prepare_inputs.<locals>.<listcomp>c                 S   s   g | ]}t j|td qS )r{  )r   r  r  )rN   r  r2   r2   r3   r     r5   r   r   )	r   r^   r&  r   r   _validate_input_unitsr  r  r  )r   r   r   r   r0   r   r   r2   r   r3   r    s    
zModel.prepare_inputsc              
   C   s  t |}| jp| jj}| jd ur|rVi }|D ]$\}}| |u r.||d  ||d < q.n|}t| j|| j}tt	|D ],}	| j|	 }
| j
|
d }|d u rqvt||	 tr\||	 jj|||
 drt	|dks| j|
 r||	 j|||
 d||	< nb|tu r,td|| j|	 ||	 j||	 jjn.td|| j|	 ||	 j||	 jj||jqv| j|
 sv|turv|d urvt||	 dkrvtd|| j|	 ||jqv|S )Nr   r   )r   z[{0}: Units of input '{1}', {2} ({3}),could not be converted to required dimensionless inputza{0}: Units of input '{1}', {2} ({3}), could not be converted to required input units of {4} ({5})zg{0}: Units of input '{1}', (dimensionless), could not be converted to required input units of {2} ({3}))rW   r`   rg   r7   r  r   r   input_units_equivalenciesr   r   r   rL   r	   r   Zis_equivalentr   rj  r   r
   r   Zphysical_typer   r   r   )r   r   r   r   r`   Zedictr   mappingr  r  Z
input_nameZ
input_unitr2   r2   r3   r    sj    







zModel._validate_input_unitsc                    sj   t dd |D }| jrf|rf| jdkrBt| jsB| jd | ji n| j t fddt|| jD }|S )Nc                 S   s   g | ]}t |tqS r2   r   r  r2   r2   r3   r   L  r5   z/Model._process_output_units.<locals>.<listcomp>r   r   c                    s&   g | ]\}}t | |d ddqS )NT)Zsubok)r	   r   )rN   rg  Zout_namerq  r2   r3   r   T  s   )r   rq  r   r   r   r]   r   )r   r   r   Zinputs_are_quantityr2   r  r3   r)  K  s    

zModel._process_output_unitsc                 C   sb   |d ur^|s|   S z| |W S  ty\   z|   W  Y S  tyV   |  Y  Y S 0 Y n0 | S r,   )r  r  r   )outputbroadcast_shaper2   r2   r3   _prepare_output_single_modelX  s    z"Model._prepare_output_single_modelc              
   C   sf   t |}t|D ]L\}}zt|d  }W n" ttfyJ   |d | }Y n0 | ||||< qt|S Nr   )rW   r   r   r  r   r  r]   )r   r   r  r   r  r  r2   r2   r3   _prepare_outputs_single_modelh  s    z#Model._prepare_outputs_single_modelc                 C   sl   |d }|d u s|du r| j }t|}t|D ]4\}}|| }||jk r.||kr.t|||||< q.t|S )Nr   F)r   rW   r   r  r   r  r]   )r   r   r  r   r  r   r  r  r2   r2   r3   _prepare_outputs_model_sett  s    
z Model._prepare_outputs_model_setc                 O   s6   | dd }t| dkr$| ||S | |||S d S )Nr   r   )r   r   r  r  )r   r  r   r0   r   r2   r2   r3   r(    s    zModel.prepare_outputsc                 C   s
   t | S )z
        Return a copy of this model.

        Uses a deep copy so that all model attributes, including parameter
        values, are copied as well.
        )r   r   r   r2   r2   r3   r     s    z
Model.copyc                 C   s   |   S )z4
        Return a deep copy of this model.

        r   r   r2   r2   r3   r     s    zModel.deepcopyc                 C   s   |   }||_|S )z>
        Return a copy of this model with a new name.
        )r   r   )r   r`   Z	new_modelr2   r2   r3   r     s    zModel.renamec                    sX  ddl m} | } dur.| jdur,| jni fdd| jD D ]}|durD|tkrDtdqDt tr  t	| jkrdd
   d	d
| j d
}t| fdd| jD  t | jkrd| j dt  }t|tfddt| j D }	||	||d}
| j|
_| j|
_|
|B }durT| jdurL| jni fdd| jD D ]"}|durd|tkrdtdqdttr t	| jkrdd
  dd
| j d
}t|fdd| jD t| jkrd| j dt }t|tfddt| jD }	||	}| j|_| j|_||B }|S )a
  
        Attach units to this (unitless) model.

        Parameters
        ----------
        input_units : dict or tuple, optional
            Input units to attach.  If dict, each key is the name of a model input,
            and the value is the unit to attach.  If tuple, the elements are units
            to attach in order corresponding to `Model.inputs`.
        return_units : dict or tuple, optional
            Output units to attach.  If dict, each key is the name of a model output,
            and the value is the unit to attach.  If tuple, the elements are units
            to attach in order corresponding to `Model.outputs`.
        input_units_equivalencies : dict, optional
            Default equivalencies to apply to input values.  If set, this should be a
            dictionary where each key is a string that corresponds to one of the
            model inputs.
        input_units_allow_dimensionless : bool or dict, optional
            Allow dimensionless input. If this is True, input values to evaluate will
            gain the units specified in input_units. If this is a dictionary then it
            should map input name to a bool to allow dimensionless numbers for that
            input.

        Returns
        -------
        `CompoundModel`
            A `CompoundModel` composed of the current model plus
            `~astropy.modeling.mappings.UnitsMapping` model(s) that attach the units.

        Raises
        ------
        ValueError
            If the current model already has units.

        Examples
        --------

        Wrapping a unitless model to require and convert units:

        >>> from astropy.modeling.models import Polynomial1D
        >>> from astropy import units as u
        >>> poly = Polynomial1D(1, c0=1, c1=2)
        >>> model = poly.coerce_units((u.m,), (u.s,))
        >>> model(u.Quantity(10, u.m))  # doctest: +FLOAT_CMP
        <Quantity 21. s>
        >>> model(u.Quantity(1000, u.cm))  # doctest: +FLOAT_CMP
        <Quantity 21. s>
        >>> model(u.Quantity(10, u.cm))  # doctest: +FLOAT_CMP
        <Quantity 1.2 s>

        Wrapping a unitless model but still permitting unitless input:

        >>> from astropy.modeling.models import Polynomial1D
        >>> from astropy import units as u
        >>> poly = Polynomial1D(1, c0=1, c1=2)
        >>> model = poly.coerce_units((u.m,), (u.s,), input_units_allow_dimensionless=True)
        >>> model(u.Quantity(10, u.m))  # doctest: +FLOAT_CMP
        <Quantity 21. s>
        >>> model(10)  # doctest: +FLOAT_CMP
        <Quantity 21. s>
        r   )UnitsMappingNc                    s   g | ]}  |qS r2   r   r  model_unitsr2   r3   r     r5   z&Model.coerce_units.<locals>.<listcomp>z>Cannot specify input_units for model with existing input unitszinput_units keys (, z) do not match model inputs (r   c                    s   g | ]} | qS r2   r2   r  r  r2   r3   r     r5   z5input_units length does not match n_inputs: expected z, received c                 3   s    | ]\}}|  |fV  qd S r,   r  rN   r  r   r  r2   r3   r   	  r5   z%Model.coerce_units.<locals>.<genexpr>)r  r   c                    s   g | ]}  |qS r2   r  r  r  r2   r3   r   	  r5   z@Cannot specify return_units for model with existing output unitszreturn_units keys (z) do not match model outputs (c                    s   g | ]} | qS r2   r2   r  r  r2   r3   r   "	  r5   z7return_units length does not match n_outputs: expected c                 3   s    | ]\}}  ||fV  qd S r,   r  r  r  r2   r3   r   +	  r5   )Zmappingsr  r  r   r   r   rL   rZ   r   setr   r   r   r]   r   r   rq  r   )r   r  rq  r  r   r  rJ  r   messager  Zinput_mappingZreturn_mappingr2   )r  r  rq  r3   coerce_units  s~    D






zModel.coerce_unitsc                 C   s   dS )zb
        Return the number of components in a single model, which is
        obviously 1.
        r   r2   r   r2   r2   r3   n_submodels3	  s    zModel.n_submodelsc                 C   sl   | j D ]8}||i }| D ]\}}t| |}t||| qqi | _| jD ]}||g }|| j|< qLdS )z
        Pop parameter constraint values off the keyword arguments passed to
        `Model.__init__` and store them in private instance attributes.
        N)parameter_constraintsr   rT   r   r   rF  model_constraints)r   r0   Z
constraintr   ZckeyZcvaluer   r2   r2   r3   r   ;	  s    


zModel._initialize_constraintsc                 C   s  | dd}|du s:t|ttjfr,|dks:td|| dd}|du rj|durd|dkrdd}qd}n(|du stt|tjstd|t	 }t
|t
| jkrtd	| jjt
| jt
||| _tt| _t|D ]P\}}|du rq| j| }|| t|ts"t|td
}	n|}	| ||	 q| jD ]h}||v r:||v rftd| jj|| |}	|	du r~q:t|	td
}	|| | ||	 q:| jD ]}||vr| |d q|r|D ]}
td| jj|
q|dur|dkr|rd}|dk r t|}n|d }| jD ]z}t| |}	t|	}||k rdtd||||t||}|du r|	j| }n"|	j| |kr.td|||q.| | n|du rd}| d || _ |D ]*}t| |}|j!dur|!| |j" qdS )a	  
        Initialize the _parameters array that stores raw parameter values for
        all parameter sets for use with vectorized fitting algorithms; on
        FittableModels the _param_name attributes actually just reference
        slices of this array.
        n_modelsNr   zn_models must be either None (in which case it is determined from the model_set_axis of the parameter initial values) or it must be a positive integer (got {0!r})r   r   Fzmodel_set_axis must be either False or an integer specifying the parameter array axis to map to each model in a set of models (got {0!r}).zA{0}.__init__() takes at most {1} positional arguments ({2} given)r{  z6{0}.__init__() got multiple values for parameter {1!r}z2{0}.__init__() got an unrecognized parameter {1!r}zAll parameter values must be arrays of dimension at least {0} for model_set_axis={1} (the value given for {2!r} is only {3}-dimensional)zInconsistent dimensions for parameter {0!r} for {1} model sets.  The length of axis {2} must be the same for all input parameter values)#r   rL   r   r   integerr   r   
issubdtyper{   r  r   r^   r   rg   r7   r2  r   rZ   r  r   addr   r   r  _initialize_parameter_valueabsr   r  r   r  r  _check_param_broadcastr  r  r   )r   r   r0   r  r   r   r   argr   r   kwargmax_ndimZmin_ndimr`   
param_ndimr   r2   r2   r3   r   L	  s    	










	










zModel._initialize_parametersc                 C   s  t |tr|| j|< dS t| |}|du rX|j}|du rLtd| jj||}|j	}nt |t
rp|j	}|j}nd}|du r|j	durtd| jj|||_d|_|jdur
|dur||| }n
||}t |t
r|j	|_t|j|_nd|_t||_nt||_dS )zAMostly deals with consistency checks and determining unit issues.Nz3{0}.__init__() requires a value for parameter {1!r}z6{0}.__init__() requires a Quantity for parameter {1!r})rL   r   ry   r   r   r   r   rg   r7   r   r	   r   r   r  internal_unit_setterr   r  _internal_valueZ_value)r   r   r   r   r   r   Z_valr2   r2   r3   r  	  sD    





z!Model._initialize_parameter_valuec           	      C   s   | j }d}| jD ]b}t| |}|j}t|}t|}t||| }||| d< ||| d< ||| d< ||7 }qtj|tj	d| _
d S Nr   r4  r  r
  r{  r  r^   r   r   r   r
  r  r4  r   Zfloat64r6  	r   param_metricsZ
total_sizer`   r   r   Z
param_sizeparam_shapeZparam_slicer2   r2   r3   r   
  s    




zModel._initialize_slicesc                 C   sT   | j }| jD ]B}t| |}|j}t|tjs8t|g}| | j	|| d < qd S )Nr4  )
r  r^   r   r   rL   r   Zndarrayr  Zravelr6  r   r  r`   r   r   r2   r2   r3   r7  
  s    

zModel._parameters_to_arrayc                 C   sF   | j }| jD ]4}t| |}| j|| d  }|| d |_||_qd S )Nr4  r  )r  r^   r   r6  r  r   r  r2   r2   r3   r:  &
  s    

zModel._array_to_parametersc              
   C   s  g }| j }| jD ]}t| |}|j}t|}t|}|dur||k rd||  }	|dk rd|	| }
n$|d|d  |	 ||d d  }
|
| j| d< ||
 q|| qzt	|  W n\ t
y } zB|j\}}}}| j| }| j| }td||||W Y d}~n
d}~0 0 dS )a{  
        This subroutine checks that all parameter arrays can be broadcast
        against each other, and determines the shapes parameters must have in
        order to broadcast correctly.

        If model_set_axis is None this merely checks that the parameters
        broadcast and returns an empty dict if so.  This mode is only used for
        single model sets.
        Nr	  r   r   r  zParameter {0!r} of shape {1!r} cannot be broadcast with parameter {2!r} of shape {3!r}.  All parameter arrays must have shapes that are mutually compatible according to the broadcasting rules.)r2  r^   r   r   r   r  r   r  r   r   r   r   r   r   )r   r  r%  r   r`   r   r   r  r  r  r  r   Zshape_aZshape_a_idxZshape_bZshape_b_idxZparam_aZparam_br2   r2   r3   r  .
  s>    






zModel._check_param_broadcastc                 C   s   g }g }| j D ]}t| |}|r.|jr.|j}n|j}| j| d}|durV||}|t	
| t| dkr~t	|g}|r|r|jdur|j}	n|j}	|	durt||	}|| qtt|dks|rt	jt|td}
||
dd< |
S t	|S )a  
        Implementation of the Model.param_sets property.

        This internal implementation has a ``raw`` argument which controls
        whether or not to return the raw parameter values (i.e. the values that
        are actually stored in the ._parameters array, as opposed to the values
        displayed to users.  In most cases these are one in the same but there
        are currently a few exceptions.

        Note: This is notably an overcomplicated device and may be removed
        entirely in the near future.
        r  Nr   r{  )r^   r   r  r  r   r  r   r  r   r   r  r   r  r  r   r	   r  r   r   )r   r  r   r   Zshapesr`   r   r   r  r   Zpsetsr2   r2   r3   r   e
  s2    




	zModel._param_setsc                    s   dd |D }|  fdd jD   jdurD|d j | D ]2\}}||v rj|| |krjqL|| d| qLt dkr|d	t   d
 jj dd| dS )r   c                 S   s   g | ]}t |qS r2   )rs   )rN   ar2   r2   r3   r   
  r5   z&Model._format_repr.<locals>.<listcomp>c                 3   s&   | ]}| d t t | V  qdS )=N)r    r   r  r   r2   r3   r   
  s   z%Model._format_repr.<locals>.<genexpr>Nzname=r  r   z	n_models=<(r  z)>)	r  r^   r`   r   rT   r   rg   r7   r   )r   r   r0   defaultsr   r  r   r2   r   r3   r   
  s    	
zModel._format_reprc           
         s  d j jfd jfd jfd jfdt fg}dd |D }|D ]:\}}| |v rh||  |krhqB|| d|  qB|d	 t d
kr fdd jD }n fdd jD }|rt	| jd} jD ]}	t
 |	j||	 _q|tt|dd d|S )z
        Internal implementation of ``__str__``.

        This is separated out for ease of use by subclasses that wish to
        override the default ``__str__`` while keeping the same basic
        formatting.
        r"   r   ZInputsZOutputszModel set sizec                 S   s&   g | ]\}}|d ur| d| qS )Nr   r2   )rN   r   r   r2   r2   r3   r   
  s   z%Model._format_str.<locals>.<listcomp>r   zParameters:r   c                    s   g | ]}t  |jgqS r2   r   r   r  r   r2   r3   r   
  s   c                    s   g | ]}t  |jqS r2   r  r  r   r2   r3   r   
  s   )names   )widthr   )rg   r7   r`   r   r   r   lowerr   r^   r   r   r   r   r   r   )
r   r   r  r   r   r   r   columnsZparam_tabler`   r2   r   r3   r  
  s6    






zModel._format_str)T)NN)NN)NNNF)FF)vr7   r8   r9   r:   r   constraintsr  r  r^   r   r   r  r  r  r`  r   ZMetaDatar   r   rH  r   rM  rI  r  r   r   r  rV  r^  rh   r   r   r   r   setterr   r   r   r   r   r   rq   r  r  staticmethodr  r  r  r  r  r$  r&  r"  r'  r+  r-  rx   r.  r`   r   r3  r   r=  r@  rB  rD  r   r   rG  r   deleterrK  r   rR  rU  rW  r_  ra  ro  rr  rl  rt  ru  rv  abcabstractmethodr  rx  r  r  rq  r  r  r  r  r  r)  r  r  r  r(  r   r   r   r   r  r  r   r   r  r   r7  r:  r  r   r   r  r   r2   r2   rf   r3   r"     sR  w





	



+


8









	



!
	


U


	




-"*



v

/
D%
[



    
 
 +7
=r"   )	metaclassc                   @   s    e Zd ZdZdZdZdZdZdS )r#   z]
    Base class for models that can be fitted using the built-in fitting
    algorithms.
    FNT)r7   r8   r9   r:   r  	fit_derivcol_fit_derivr  r2   r2   r2   r3   r#   
  s
   	r#   c                   @   s   e Zd ZdZdZdZdZdS )r$   z
    Base class for one-dimensional fittable models.

    This class provides an easier interface to defining new models.
    Examples can be found in `astropy.modeling.functional_models`.
    r   TN)r7   r8   r9   r:   r   r   r`  r2   r2   r2   r3   r$   
  s   r$   c                   @   s   e Zd ZdZdZdZdS )r%   z
    Base class for two-dimensional fittable models.

    This class provides an easier interface to defining new models.
    Examples can be found in `astropy.modeling.functional_models`.
    r   r   N)r7   r8   r9   r:   r   r   r2   r2   r2   r3   r%     s   r%   c                    s    fdd}|S )Nc                    s"   t  | d |d | d | d fS )Nr   r   r   )r   fgr1   r2   r3   op  s    z%_make_arithmetic_operator.<locals>.opr2   )r1   r  r2   r  r3   _make_arithmetic_operator  s    r  c                    s    fdd d d fS )Nc                    s   d  d | ||S r  r2   r   r   r  r2   r3   r4   +  r5   z'_composition_operator.<locals>.<lambda>r   r   r2   r  r2   r  r3   _composition_operator$  s    r  c                    s,    fdd d d   d d  fS )Nc                    s4    d | d  d  |d |  d d  | S )Nr   r   r2   r  r  r2   r3   r4   6  s   z _join_operator.<locals>.<lambda>r   r   r2   r  r2   r  r3   _join_operator/  s    r  )r>   r@   rB   rD   rF   rH   rJ   c                 C   s   t | |S r,   )SPECIAL_OPERATORSr  )Zsop_nameZsopr2   r2   r3   _add_special_operatorH  s    r  c                       sh  e Zd ZdZdqddZdd Zdd Zd	d
 Zdd Zdd Z	dd Z
dd Zedd Zedd Zdd Zdd Zedd Zdd Zdd  Zed!d" Zd#d$ Zd%d& Zd'd( Zd)d* Zed+d, Zejd-d, Zed.d/ Zejd0d/ Zed1d2 Zejd3d2 Zed4d5 Zejd6d5 Zdrd8d9Zdsd:d;Zd<d= Z  fd>d?Z!d@dA Z"edBdC Z#edDdE Z$edFdG Z%e&dHZ'e&dIZ(e&dJZ)e&dKZ*e&dLZ+e&dMZ,e&dNZ-dOdP Z.dQdR Z/e0dSdT Z1dUdV Z2dWdX Z3edYdZ Z4ed[d\ Z5ed]d^ Z6ed_d` Z7edadb Z8dcdd Z9ededf Z:dtdgdhZ;didj Z<dkdl Z= fdmdnZ> fdodpZ?  Z@S )ur&   z
    Base class for compound models.

    While it can be used directly, the recommended way
    to combine models is through the model operators.
    Nc           
   	   C   sp  d | j d< d | _|| _|| _|| _d | _d | _d | _d | _d | _	d | _
d | _|dkrlt|t|krltdt|| _|dkr|j|jks|jrtd|j| _|dv s|tv r|j|jks|j|jkrtd|j| _|j| _|j| _|j| _n|dkr>|j|j | _|j|j | _t|j|j| _t|j|j| _n|dkr|j|jkrztd	|j|j|j|j|j|j|j| _|j| _|j| _|j| _nr|dkrt|tstd
t|tstd|jt| | _|j| _|j| _t|j}| }g }|D ]}t !t"|t j#r^||jks8|dk r@td||v rRtd|$| nHt|t%r
||jvr~td|j&|}	|	|v rtd|$|	 q
|'  |(  |D ]}	||	= qt)|| _z| jj*+| || _*W n t,y    Y n0 ntd| j|| _d | _-d | _.d | _/|dv rD|j0o>|j0| _0nd| _0g | _1g | _2t| jj3| _4| 5  d S )NrS   r'   z1Both operands must have equal values for n_modelsz=model_set_axis must be False or 0 and consistent for operands)r>   r@   rB   rD   rF   z6Both operands must match numbers of inputs and outputsrJ   rH   zUnsupported operands for |: {0} (n_inputs={1}, n_outputs={2}) and {3} (n_inputs={4}, n_outputs={5}); n_outputs for the left-hand model must match n_inputs for the right-hand model.zGFirst argument to "fix_inputs" must be an instance of an astropy Model.z:Expected a dictionary for second argument of "fix_inputs".r   z@Substitution key integer value not among possible input choices.z3Duplicate specification of same input (index/name).z9Substitution key string not among possible input choices.zIllegal operator: )rH   r>   r@   F)6ry   Z_n_submodelsr  r-   r.   r   rM  rs  _tdictr6  rR   r  r   r   r  r   r2  r  r   r   r)   r   r   r   r   r`   rL   r"   rZ   r   rW   r   r   r  r{   r  r   r   rp  sortreverser]   r   r'   r  	_fittabler  r  r  r   r   r   n_left_params_map_parameters)
r   r  r-   r.   r`   Z	newinputsr   Z	input_indr}   indr2   r2   r3   rh   T  s    











zCompoundModel.__init__c                 C   s   |d | j j S r,   )r-   r   rQ  r2   r2   r3   _get_left_inputs_from_args  s    z(CompoundModel._get_left_inputs_from_argsc                 C   sR   | j }|dkr*|| jj| jj| jj  S |dks:|dkr>d S |d | jj S d S )NrJ   rH   r'   )r  r-   r   r.   r   r   r  r2   r2   r3   _get_right_inputs_from_args  s    z)CompoundModel._get_right_inputs_from_argsc                 C   sN   | j }|dkr0| jj| jj }|||| j  S || jj| jj| j  S d S )NrJ   r  r-   r   r.   r  )r   r   r  r   r2   r2   r3   _get_left_params_from_args  s
    z(CompoundModel._get_left_params_from_argsc                 C   sR   | j }|dkrd S |dkr8|| jj| jj | j d  S || jj| j d  S d S )Nr'   rJ   r  r   r2   r2   r3   _get_right_params_from_args  s    z)CompoundModel._get_right_params_from_argsc              	   C   s   | j dkr8t|d | jj| jj  }| jj| jj }nt|d | jj }| jj}| jD ]X}||d }|d urx|}n0z|| }W n ty   tdY n0 |d7 }|| qZ||fS )NrJ   zMissing parameter or inputr   )	r  rW   r-   r   r.   r^   r   r  r   )r   r   r0   r0  Zargs_posr   Zkw_valuer   r2   r2   r3   )_get_kwarg_model_parameters_as_positional  s     

z7CompoundModel._get_kwarg_model_parameters_as_positionalc                 K   s   | j }|dkrttj||S |dkr2ttj||S |dkrHttj||S |dkr^ttj||S |dkrtttj||S |dkrt|t	s|f}t|t	s|f}|| S |t
v rtt
| ||S tdd S )Nr>   r@   rB   rD   rF   rJ   zUnrecognized operator {op})r  binary_operationoperatorr  submultruedivpowrL   r]   r  r)   )r   leftvalrightvalkwr  r2   r2   r3   _apply_operators_to_value_lists  s(    

z-CompoundModel._apply_operators_to_value_listsc           
         s  | j }| ||\}}| |}| |}|dkrztt| jjt| jj	fdd| j
 D   fddt|D }| jjt|| }|dkr|S | |}| |}|dkrt|tr| j
jt|| S | j
j|g|R  S n| j
jt|| }	| j||	fi |S )Nr'   c                    s0   i | ](\}}t t|t jr"|n | |qS r2   )r   r  r{   r  rN   r}   r   )	pos_indexr2   r3   rQ   %  s   z*CompoundModel.evaluate.<locals>.<dictcomp>c                    s(   g | ] \}}|   v r  | n|qS r2   )r   )rN   r  re  )fixed_inputsr2   r3   r   )  s   z*CompoundModel.evaluate.<locals>.<listcomp>rH   )r  r  r  r  rZ   r   r-   r   r   r   r.   rT   r   r  	itertoolsr   r  r  rL   r]   r  )
r   r   r  r  Zleft_inputsZleft_paramsr  Zright_inputsZright_paramsr  r2   )r  r  r3   r    s.    






zCompoundModel.evaluatec                 C   s   | j d u r|   t| j S r,   )rs  _make_leaflistr   r   r2   r2   r3   r  @  s    
zCompoundModel.n_submodelsc                 C   sh   | j du r|   dd | j D }d}g }|D ]0}|du rT|d|  |d7 }q.|| q.t|S )z6 Return the names of submodels in a ``CompoundModel``.Nc                 S   s   g | ]
}|j qS r2   r`   r  r2   r2   r3   r   K  r5   z0CompoundModel.submodel_names.<locals>.<listcomp>r   ZNone_r   )rs  r  r   r]   )r   r  Z	nonecountZnewnamesr  r2   r2   r3   submodel_namesF  s    

zCompoundModel.submodel_namesc                 C   s:   t dt z| jj}| jj}W n ty4   Y dS 0 dS )zR
        if both members of this compound model have inverses return True
        zICompoundModel.both_inverses_exist is deprecated. Use has_inverse instead.FT)warningswarnZAstropyDeprecationWarningr-   r   r.   r  )r   ZlinvZrinvr2   r2   r3   both_inverses_existV  s    z!CompoundModel.both_inverses_existc                    s<   d v r"dd    D  d<  fdd}||d fS )a  
        CompoundModel specific input setup that needs to occur prior to
            model evaluation.

        Note
        ----
            All of the _pre_evaluate for each component model will be
            performed at the time that the individual model is evaluated.
        r   c                 S   s$   g | ]\}}|d  |d |ffqS r   r   r2   r  r2   r2   r3   r   y  s   z/CompoundModel._pre_evaluate.<locals>.<listcomp>r   c                    s   j | i  S r,   )	_evaluater   r0   r   r2   r3   r  }  s    z-CompoundModel._pre_evaluate.<locals>.evaluateNr   rT   )r   r   r0   r  r2   r  r3   r  h  s    

zCompoundModel._pre_evaluatec                 C   s   dS )zONo inputs should be used to determine input_shape when handling compound modelsr2   r2   r   r2   r2   r3   r    s    zCompoundModel._argnamesc                 K   s$   |  |dur | jdkr |d S |S )z
        CompoundModel specific post evaluation processing of outputs

        Note
        ----
            All of the _post_evaluate for each component model will be
            performed at the time that the individual model is evaluated.
        Nr   r   )r  r   r*  r2   r2   r3   r+    s    	zCompoundModel._post_evaluatec                 O   s4  | j }|dkr|dkrF| j|i |}|dkr@| j|i |}q~d }n8| j|d | jj i |}| j|| jjd  i |}|dkr| j||fi |S |dkrt|tr| j|i |S | j|fi |S n^| j}t|}g }g }	| D ]V}
t	
t|
t	jr||
 n$t|
tr8| jj|
}|| |	||
  qg }g }t| D ]R}|| jv r\| j|}|t|k rtd|| |||  ||= q\|rtt||}|  tt| \}}|t| }|r tt||	}|  |D ]\}}||| q| j|i |S d S )Nr'   rJ   rH   z6Keyword argument duplicates positional value supplied.)r  r-   r.   r   r  rL   r]   rW   r   r   r  r{   r  r   r   r   rp  r   r   r   r  insert)r   r   r  r  r  r  ZsubsZnewargsZsubindsZsubvalsr}   r  ZkwindZkwvalZkwkeyr0   ZkwindsortedZkwvalsortedsubargsrn   r2   r2   r3   r    s^    



zCompoundModel._evaluatec                 C   s   | j S )z$ An ordered list of parameter names.)rS   r   r2   r2   r3   r^     s    zCompoundModel.param_namesc                 C   s&   i }g }t | d|| || _|| _d S )N )make_subtree_dictrs  r  )r   tdictleaflistr2   r2   r3   r    s
    zCompoundModel._make_leaflistc                 C   s4   |dkrt || jv r | j| S t d| ddS )z
        If someone accesses an attribute not already defined, map the
        parameters, and then see if the requested attribute is one of
        the parameters
        __setstate__zAttribute "z" not foundN)r   rS   ry   r   r`   r2   r2   r3   __getattr__  s
    

zCompoundModel.__getattr__c           
      C   sf  | j d u r|   | j }| j}t|tr$|jr8td|jd urdt|jtr\| 	|j}qh|j}nd}|j
d urt|j
tr| 	|j
}q|j
d }nt|d }|j
dkrtd|dk rt|| }|dk rt|| }||kr|}n8|D ]*}|| \}}}	||kr|	|kr|  S qtdtt|tjr@|| S t|trZ|| 	| S tdd S )Nz1Steps in slices not supported for compound modelsr   r   zSlice endpoint cannot be 0z$No appropriate subtree matches slicez2index must be integer, slice, or model name string)rs  r  r  rL   r4  stepr   r8  r   _str_index_to_intr9  r   r  r   r  r{   r  r   )
r   rp  r#  r"  r8  r9  r}   nodeZleftindZrightindr2   r2   r3   __getitem__  sF    




zCompoundModel.__getitem__c                 C   sr   g }t | jD ]"\}}t|dd |kr|| qt|dkrNtd| dt|dkrjtd|||d S )Nr`   r   zNo component with name 'z' foundr   z:Multiple components found using '{}' as name
at indices {})r   rs  r   r   r   r  r   )r   Z	str_indexfoundZnleafleafr2   r2   r3   r(    s    zCompoundModel._str_index_to_intc                 C   s   | j S )z! The number of inputs of a model.Z	_n_inputsr   r2   r2   r3   r   )  s    zCompoundModel.n_inputsc                 C   s
   || _ d S r,   r-  r>  r2   r2   r3   r   .  s    c                 C   s   | j S )z" The number of outputs of a model.Z
_n_outputsr   r2   r2   r3   r   2  s    zCompoundModel.n_outputsc                 C   s
   || _ d S r,   r.  r>  r2   r2   r3   r   7  s    c                 C   s   | j S r,   Z_eqconsr   r2   r2   r3   r   ;  s    zCompoundModel.eqconsc                 C   s
   || _ d S r,   r/  r>  r2   r2   r3   r   ?  s    c                 C   s   | j S r,   r/  r   r2   r2   r3   r   C  s    zCompoundModel.ineqconsc                 C   s
   || _ d S r,   r/  r>  r2   r2   r3   r   G  s    Fc                 C   sx   g }t | jtr"|| j| }n|| jg }t | jtrL|| j| }n|| jg }|rj|| j n
||  |S )z/ Postorder traversal of the CompoundModel tree.)rL   r-   r&   traverse_postorderr.   r   r  )r   Zinclude_operatorresr2   r2   r3   r0  K  s    
z CompoundModel.traverse_postorderc                 C   s"  d}t  }|d u rdd }|  D ]}t|tsJ|||| |d7 }q"| }| }|jtv rt|j }t|trt|jtrt|jj |k rd| d}t|j	trt|j	j |k rd| d}|d
||j|f q"d| d	}d| d
}|d
|jd ||f q"d
|S )Nr   c                 S   s   d|  dS )N[]r2   )r  lr2   r2   r3   r4   a  r5   z2CompoundModel._format_expression.<locals>.<lambda>r   r  r    z((z),z))r   )r   r0  rL   r&   r   r   r  OPERATOR_PRECEDENCEr-   r.   r   )r   Zformat_leafZleaf_idxZoperandsr)  r.   r-   Z
oper_orderr2   r2   r3   _format_expression\  s6    



z CompoundModel._format_expressionc                 C   s,   | j d u r|   ddd t| jD S )Nz

c                 s   s   | ]\}}d  ||V  qdS )z[{0}]: {1!r}N)r   )rN   r   mr2   r2   r3   r     s   z3CompoundModel._format_components.<locals>.<genexpr>)rR   r  r   r   rs  r   r2   r2   r3   _format_components~  s
    

z CompoundModel._format_componentsc                    s6   |   }|  }d|fddt| fg}t j|dS )NZ
ExpressionZ
Componentsr   )r   )r7  r9  r   rU   r  )r   Z
expressionZ
componentsr   rf   r2   r3   r    s    zCompoundModel.__str__c                 C   s
   || _ | S r,   r  r%  r2   r2   r3   r     s    zCompoundModel.renamec                 C   s   dS )NFr2   r   r2   r2   r3   isleaf  s    zCompoundModel.isleafc                 C   s<   | j dkr| jj| jjB S | j dkr4| jj| jj@ S tS d S )NrH   rJ   )r  r.   r   r-   r   r   r2   r2   r3   r     s
    

zCompoundModel.inversec                 C   s8   | j du r2| jdu r|   tdd | jD | _ | j S )z0 Set the fittable attribute on a compound model.Nc                 s   s   | ]}|j V  qd S r,   )r  rN   r8  r2   r2   r3   r     r5   z)CompoundModel.fittable.<locals>.<genexpr>)r  rs  r  r   r   r2   r2   r3   r    s
    

zCompoundModel.fittabler>   r@   rB   rD   rF   rH   rJ   c                 C   s   | j durdS | jdu r |   i | _i }g | _t| jD ]b\}}t|ts:|jD ]H}t	||}| d| }|| j
|< || j|< | j| ||f||< qRq:i | _|| _tdd | D | _|   t| j| _dS )a2  
        Map all the constituent model parameters to the compound object,
        renaming as necessary by appending a suffix number.

        This can be an expensive operation, particularly for a complex
        expression tree.

        All the corresponding parameter attributes are created that one
        expects for the Model class.

        The parameter objects that the attributes point to are the same
        objects as in the constiutent models. Changes made to parameter
        values to either are seen by both.

        Prior to calling this, none of the associated attributes will
        exist. This method must be called to make the model usable by
        fitting engines.

        If oldnames=True, then parameters are named as in the original
        implementation of compound models.
        Nr   c                 s   s   | ]\}}||fV  qd S r,   r2   rM   r2   r2   r3   r     r5   z0CompoundModel._map_parameters.<locals>.<genexpr>)r6  rs  r  rR   rS   r   rL   rZ   r^   r   ry   r   r  Z
_param_maprT   _param_map_inverser   r]   )r   Z	param_mapZlindexr,  r   r   Znew_param_namer2   r2   r3   r    s*    






zCompoundModel._map_parametersc           	      C   s   | j }d}| jD ]j}t| |}|j}t|}t|}t||| }i ||< ||| d< ||| d< ||| d< ||7 }qtj|tj	d| _
d S r  r  r  r2   r2   r3   r     s    




z CompoundModel._initialize_slicesc                 C   s   t | tr|| S | |fS r,   r,  )branchZadictr}   r2   r2   r3   _recursive_lookup  s    
zCompoundModel._recursive_lookupc           	         s<  i }t  jts$ fdd jD S  jdkr|t  jtrD j } jD ],}t  jtrh|| ||< qJ j|f||< qJn jdkrht  jtr j }t  jtr j }t jD ]\}}|t	 jjk rt  jtr| jj|  ||< n j jj| f||< qt  jtrB| jj|t	 jj   ||< q j jj|t	 jj  f||< qnЈ jdkrt
 j } fdd|D }t
t jj}|D ]}|| q|D ]$} j jj| f| jj| < qnRt  jtr j } jjD ]0}t  jtr&|| ||< n j|f||< q|S )zf
        Map the names of the inputs to this ExpressionTree to the inputs to the leaf models.
        c                    s   i | ]}| |fqS r2   r2   rd  r   r2   r3   rQ     r5   z,CompoundModel.inputs_map.<locals>.<dictcomp>rH   rJ   r'   c                    s,   g | ]$}t |tr$t jj|n|qS r2   )rL   r   rW   r-   r   rp  r  r   r2   r3   r     r5   z,CompoundModel.inputs_map.<locals>.<listcomp>)rL   r  r   r   r-   r&   r   r.   r   r   rW   r   r   r   remove)	r   r   Zl_inputs_mapre  Zr_inputs_mapr  Z	fixed_indr  Zinp_indr2   r   r3   r     sL    




"&$
zCompoundModel.inputs_mapc           	      C   s^   | j d u r|   i }t| j D ]8\}}|||}|D ]}| j||f }|| ||< q8q |S r,   )rs  r  r   ri  r<  )	r   r  rr  Zunits_for_dataZimodelr   Zunits_for_data_leafZ
param_leafr   r2   r2   r3   ri  %  s    
z-CompoundModel._parameter_units_for_data_unitsc                    s*   |     fdd  D }|r&|S d S )Nc                    s:   i | ]2\}\}} | d  j dur| | d  j | qS rX  r  rN   r}   r   Zorig_keyr   r2   r3   rQ   3  s   
z-CompoundModel.input_units.<locals>.<dictcomp>r  )r   Zinput_units_dictr2   rA  r3   r  0  s    
zCompoundModel.input_unitsc                    s*   |     fdd  D }|s&d S |S )Nc                    s:   i | ]2\}\}} | d  j dur| | d  j | qS rX  )r  r@  rA  r2   r3   rQ   =  s   
z;CompoundModel.input_units_equivalencies.<locals>.<dictcomp>r  )r   Zinput_units_equivalencies_dictr2   rA  r3   r  :  s    
z'CompoundModel.input_units_equivalenciesc                    s   |     fdd  D S )Nc                    s(   i | ] \}\}}| | d  j | qS r   )r   r@  rA  r2   r3   rQ   J  s   
zACompoundModel.input_units_allow_dimensionless.<locals>.<dictcomp>r  r   r2   rA  r3   r   G  s    
z-CompoundModel.input_units_allow_dimensionlessc                    s   |     fdd  D S )Nc                    s(   i | ] \}\}}| | d  j | qS rB  )r   r@  rA  r2   r3   rQ   P  s   
z4CompoundModel.input_units_strict.<locals>.<dictcomp>r  r   r2   rA  r3   r   M  s    
z CompoundModel.input_units_strictc                    s   |     fdd  D S )Nc                    s:   i | ]2\}\}} | d  j dur| | d  j | qS rX  r  r@  outputs_mapr2   r3   rQ   V  s   
z.CompoundModel.return_units.<locals>.<dictcomp>)rD  rT   r   r2   rC  r3   rq  S  s    
zCompoundModel.return_unitsc                    s  i }t  jts$ fdd jD S  jdkr|t  jtrD j } jD ],}t  jtrh|| ||< qJ j|f||< qJnV jdkrht  jtr j }t  jtr j }t jD ]\}}|t	 jjk rt  jtr| jj|  ||< n j jj| f||< qt  jtrB| jj|t	 jj   ||< q j jj|t	 jj  f||< qnj jdkr~ j S t  jtr j } jjD ]2}t  jtr| | ||< n j|f||< q|S )zh
        Map the names of the outputs to this ExpressionTree to the outputs to the leaf models.
        c                    s   i | ]}| |fqS r2   r2   rf  r   r2   r3   rQ   `  r5   z-CompoundModel.outputs_map.<locals>.<dictcomp>rH   rJ   r'   )
rL   r  r   r   r.   r&   rD  r-   r   r   )r   rD  Zr_outputs_maprg  Zl_outputs_mapr  r2   r   r3   rD  Z  s@    




"&

zCompoundModel.outputs_mapc                 C   s
   | j duS rT  rS  r   r2   r2   r3   rU    s    z#CompoundModel.has_user_bounding_boxc           
         s  |   }| j}|du r.|du r.|du r.td|dkrR|durD|g}|durR|g}|durtj|td}t||ksxJ |dur|d j|jkrtdnt|d j}|durt|}|j	|krtd|durt
dd	 |D tj}|\ }|dur2t|d
 d t
 fdd	|D }ndd	 |jD }tj| }|ddd }|du rn| | }n2zt|| |  }W n ty   tdY n0 nB|du r|j}	dd	 |	D }tj| }|ddd }|| | 7 }|S )ry  Nrz  r   r{  r   r|  r}  c                 S   s0   g | ](}t |t |d  |d  d fqS r~  r  r  r2   r2   r3   r     s   z(CompoundModel.render.<locals>.<listcomp>r   c                    s   g | ]}t | qS r2   r  r  r  r2   r3   r     s   c                 S   s(   g | ] \}}t || || d  d qS r	  r  r  r2   r2   r3   r     r5   r5  r  c                 S   s   g | ]}t |qS r2   r  r  r2   r2   r3   r     r5   )r  r   r   r   r  r  r   r  r  r  r  r  r   r  r]   r  r   r  r2   r  r3   r    sd    *











zCompoundModel.renderc                    s    fdd|   D }|rt|dkr4td  | }t|t|krTtd|j|jksl|j|jkrttdt|  }|r|  }|dd D ]}t||}qt	||d | t
|j|j|j|jd	}|dd }q~|S td
  dS )a<  
        Construct a new `~astropy.modeling.CompoundModel` instance from an
        existing CompoundModel, replacing the named submodel with a new model.

        In order to ensure that inverses and names are kept/reconstructed, it's
        necessary to rebuild the CompoundModel from the replaced node all the
        way back to the base. The original CompoundModel is left untouched.

        Parameters
        ----------
        name : str
            name of submodel to be replaced
        model : `~astropy.modeling.Model`
            replacement model
        c                    s    g | ]}t |d d kr|qS )r`   Nr  r;  r  r2   r3   r     s   z2CompoundModel.replace_submodel.<locals>.<listcomp>r   zMore than one submodel named z6New and old models must have equal values for n_modelszDNew model must match numbers of inputs and outputs of existing modelNr5  r  zNo submodels found named )r0  r   r   r   r   r   _get_submodel_pathr   r   r   r&   r  r-   r.   r`   )r   r`   r   Z	submodelsZ	old_modeltreer=  r)  r2   r  r3   replace_submodel  s.    

zCompoundModel.replace_submodelc                 C   sV   t | j||}|| _|| _|jD ]0}t||}t| |}|j|_|j|jdd q dS )z
        Provides a work-around to properly set the sub models and respective
        parameters's units/values when using ``without_units_for_data``
        or ``without_units_for_data`` methods.
        Trh  N)	r&   r  r-   r.   r^   r   r   rk  r   )r   r-   r.   r   r`   Zmodel_parameterrn  r2   r2   r3   #_set_sub_models_and_parameter_units1  s    


z1CompoundModel._set_sub_models_and_parameter_unitsc                    s|  | j dv rf|  } fdd| jD }| jjf i  | jjf i  | j dkr fdd| jjD } fdd| jjD }n0 fdd| jjD } fdd| jjD }||  ||  | jjf i |}t	|t
r|d	 |d
< |d |d< |d }| jjf i |}t	|t
rP|d	 |d
< |d |d< |d }||| |||fS t jf i  S dS )a  
        See `~astropy.modeling.Model.without_units_for_data` for overview
        of this method.

        Notes
        -----
        This modifies the behavior of the base method to account for the
        case where the sub-models of a compound model have different output
        units. This is only valid for compound * and / compound models as
        in that case it is reasonable to mix the output units. It does this
        by modifying the output units of each sub model by using the output
        units of the other sub model so that we can apply the original function
        and get the desired result.

        Additional data has to be output in the mixed output unit case
        so that the units can be properly rebuilt by
        `~astropy.modeling.CompoundModel.with_units_from_data`.

        Outside the mixed output units, this method is identical to the
        base method.
        rB   rD   c                    s   i | ]}| | qS r2   r2   rd  r   r2   r3   rQ   [  r5   z8CompoundModel.without_units_for_data.<locals>.<dictcomp>rB   c                    s*   i | ]"} | d ur| | |  qS r,   r2   rf  r0   right_unitsr2   r3   rQ   a  s   c                    s*   i | ]"} | d ur| | |  qS r,   r2   rf  r0   
left_unitsr2   r3   rQ   c  s   c                    s*   i | ]"} | d ur| | |  qS r,   r2   rf  rJ  r2   r3   rQ   f  s   c                    s.   i | ]&} | d ur|d |  |  qS )Nr   r2   rf  rL  r2   r3   rQ   h  s   r   _left_kwargsr   _right_kwargsr   N)r  r   r   r-   rr  r.   r   updatero  rL   r]   rH  rU   )r   r0   r   r   left_kwargsright_kwargsr-   r.   rf   )r0   rM  rK  r3   ro  C  sB    

z$CompoundModel.without_units_for_datac                    sp   | j dv rZ|d}|d}| jjf i |}| jjf i |}|  }||| |S t jf i |S dS )a  
        See `~astropy.modeling.Model.with_units_from_data` for overview
        of this method.

        Notes
        -----
        This modifies the behavior of the base method to account for the
        case where the sub-models of a compound model have different output
        units. This is only valid for compound * and / compound models as
        in that case it is reasonable to mix the output units. In order to
        do this it requires some additional information output by
        `~astropy.modeling.CompoundModel.without_units_for_data` passed as
        keyword arguments under the keywords ``_left_kwargs`` and ``_right_kwargs``.

        Outside the mixed output units, this method is identical to the
        base method.
        rI  rN  rO  N)r  r   r-   rt  r.   r   rH  rU   )r   r0   rQ  rR  r-   r.   r   rf   r2   r3   rt    s    


z"CompoundModel.with_units_from_data)N)F)N)NN)Ar7   r8   r9   r:   rh   r  r  r  r  r  r  r  r   r  r  r  r  r  r+  r  r^   r  r&  r*  r(  r   r  r   r   r   r0  r7  r9  r  r   r:  r   r  r6   r=   r?   rA   rC   rE   rG   rI   r  r   r  r>  r   ri  r  r  r   r   rq  rD  rU  r  rG  rH  ro  rt  r   r2   r2   rf   r3   r&   L  s   
x
	
#


@
-









"	


-
2
	



-
	
p0=r&   c              	   C   sp   t | dd|krg S zdgt| j| W S  ttfy>   Y n0 zdgt| j| W S  ttfyj   Y n0 dS )zpFind the route down a CompoundModel's tree to the model with the
    specified name (whether it's a leaf or not)r`   Nr-   r.   )r   rE  r-   r   r   r.   )r   r`   r2   r2   r3   rE    s    rE  c                    s:   t |tr0t |tr0t fddt||D S  ||S )zP
    Perform binary operation. Operands may be matching tuples of operands.
    c                    s   g | ]} |d  |d qS r  r2   r  binoperatorr2   r3   r     s   z$binary_operation.<locals>.<listcomp>)rL   r]   r   )rT  r-   r.   r2   rS  r3   r    s
    r  c                 C   s8   t | tr0|| j t| j| t| j| ndS dS )z7
    Recursive function to collect operators used.
    N)rL   r&   r  r  get_opsr-   r.   )rF  Zopsetr2   r2   r3   rU    s
    
rU  c                 C   sd   t | ds||  nJt|}t| j|d || t| j|d || t|d }| ||f||< dS )a  
    Traverse a tree noting each node by a key that indicates all the
    left/right choices necessary to reach that node. Each key will
    reference a tuple that contains:

    - reference to the compound model for that node.
    - left most index contained within that subtree
       (relative to all indices for the whole tree)
    - right most index contained within that subtree
    r:  r4  rr   N)r\   r   r   r!  r-   r.   )rF  Znodepathr"  r#  ZleftmostindZrightmostindr2   r2   r3   r!    s    
r!  ))r'   )rH   )rJ   )r>   r@   rI  )rF   c                 C   s\   t d| |}|durX|du r2tdd | D }t| ||}|j| |}|| |_|S )a4  
    This function creates a compound model with one or more of the input
    values of the input model assigned fixed values (scalar or array).

    Parameters
    ----------
    modelinstance : `~astropy.modeling.Model` instance
        This is the model that one or more of the
        model input values will be fixed to some constant value.
    values : dict
        A dictionary where the key identifies which input to fix
        and its value is the value to fix it at. The key may either be the
        name of the input or a number reflecting its order in the inputs.

    Examples
    --------

    >>> from astropy.modeling.models import Gaussian2D
    >>> g = Gaussian2D(1, 2, 3, 4, 5)
    >>> gv = fix_inputs(g, {0: 2.5})

    Results in a 1D function equivalent to Gaussian2D(1, 2, 3, 4, 5)(x=2.5, y)
    r'   Nc                 S   s   g | ]}|d fqS )Tr2   r   r2   r2   r3   r      r5   zfix_inputs.<locals>.<listcomp>)r&   r]   r   r   r   selector_argsZget_fixed_valuesr   )modelinstancer   bounding_boxesrW  r   r  Z	_selectorr2   r2   r3   r'     s    
r'   Cc                 C   s   t j| ||d| _dS )a  
    Set a validated bounding box to a model instance.

    Parameters
    ----------
    modelinstance : `~astropy.modeling.Model` instance
        This is the model that the validated bounding box will be set on.
    bounding_box : tuple
        A bounding box tuple, see :ref:`astropy:bounding-boxes` for details
    order : str, optional
        The ordering of the bounding box tuple, can be either ``'C'`` or
        ``'F'``.
    orderN)r   r   r   )rX  r   r\  r2   r2   r3   r*     s    r*   c                 C   s   t j| ||||d| _dS )a  
    Add a validated compound bounding box to a model instance.

    Parameters
    ----------
    modelinstance : `~astropy.modeling.Model` instance
        This is the model that the validated compound bounding box will be set on.
    bounding_boxes : dict
        A dictionary of bounding box tuples, see :ref:`astropy:bounding-boxes`
        for details.
    selector_args : list
        List of selector argument tuples to define selection for compound
        bounding box, see :ref:`astropy:bounding-boxes` for details.
    create_selector : callable, optional
        An optional callable with interface (selector_value, model) which
        can generate a bounding box based on a selector value and model if
        there is no bounding box in the compound bounding box listed under
        that selector value. Default is ``None``, meaning new bounding
        box entries will not be automatically generated.
    order : str, optional
        The ordering of the bounding box tuple, can be either ``'C'`` or
        ``'F'``.
    r[  N)r   r   r   )rX  rY  rW  Zcreate_selectorr\  r2   r2   r3   r+     s    r+   r  c                 G   sL   t |dkr(t|d r(t|d | dS |s:tjt| dS tdtdS )aD  
    Create a model from a user defined function. The inputs and parameters of
    the model will be inferred from the arguments of the function.

    This can be used either as a function or as a decorator.  See below for
    examples of both usages.

    The model is separable only if there is a single input.

    .. note::

        All model parameters have to be defined as keyword arguments with
        default values in the model function.  Use `None` as a default argument
        value if you do not want to have a default value for that parameter.

        The standard settable model properties can be configured by default
        using keyword arguments matching the name of the property; however,
        these values are not set as model "parameters". Moreover, users
        cannot use keyword arguments matching non-settable model properties,
        with the exception of ``n_outputs`` which should be set to the number of
        outputs of your function.

    Parameters
    ----------
    func : function
        Function which defines the model.  It should take N positional
        arguments where ``N`` is dimensions of the model (the number of
        independent variable in the model), and any number of keyword arguments
        (the parameters).  It must return the value of the model (typically as
        an array, but can also be a scalar for scalar inputs).  This
        corresponds to the `~astropy.modeling.Model.evaluate` method.
    fit_deriv : function, optional
        Function which defines the Jacobian derivative of the model. I.e., the
        derivative with respect to the *parameters* of the model.  It should
        have the same argument signature as ``func``, but should return a
        sequence where each element of the sequence is the derivative
        with respect to the corresponding argument. This corresponds to the
        :meth:`~astropy.modeling.FittableModel.fit_deriv` method.

    Examples
    --------
    Define a sinusoidal model function as a custom 1D model::

        >>> from astropy.modeling.models import custom_model
        >>> import numpy as np
        >>> def sine_model(x, amplitude=1., frequency=1.):
        ...     return amplitude * np.sin(2 * np.pi * frequency * x)
        >>> def sine_deriv(x, amplitude=1., frequency=1.):
        ...     return 2 * np.pi * amplitude * np.cos(2 * np.pi * frequency * x)
        >>> SineModel = custom_model(sine_model, fit_deriv=sine_deriv)

    Create an instance of the custom model and evaluate it::

        >>> model = SineModel()
        >>> model(0.25)
        1.0

    This model instance can now be used like a usual astropy model.

    The next example demonstrates a 2D Moffat function model, and also
    demonstrates the support for docstrings (this example could also include
    a derivative, but it has been omitted for simplicity)::

        >>> @custom_model
        ... def Moffat2D(x, y, amplitude=1.0, x_0=0.0, y_0=0.0, gamma=1.0,
        ...            alpha=1.0):
        ...     """Two dimensional Moffat function."""
        ...     rr_gg = ((x - x_0) ** 2 + (y - y_0) ** 2) / gamma ** 2
        ...     return amplitude * (1 + rr_gg) ** (-alpha)
        ...
        >>> print(Moffat2D.__doc__)
        Two dimensional Moffat function.
        >>> model = Moffat2D()
        >>> model(1, 1)  # doctest: +FLOAT_CMP
        0.3333333333333333
    r   r   r]  z{0} takes at most one positional argument (the callable/function to be turned into a model.  When used as a decorator it should be passed keyword arguments only (if any).N)r   r   _custom_model_wrapper	functoolspartialr   r   r7   )r  r   r2   r2   r3   r(   ;  s    Nr(   c           	         s   t | \}}dg dd tt D } fddtt D }i }i }i }|D ]d}|j v rn|j||j< qR|j|v r|j||j< qR|j|v rtd|j d| dqR|j||j< qR||||fS )a  
    Processes the inputs to the `custom_model`'s function into the appropriate
    categories.

    Parameters
    ----------
    func : callable

    Returns
    -------
    inputs : list
        list of evaluation inputs
    special_params : dict
        dictionary of model properties which require special treatment
    settable_params : dict
        dictionary of defaults for settable model properties
    params : dict
        dictionary of model parameters set by `custom_model`'s function
    r   c                 S   s(   g | ] \}}t |tr|jd ur|qS r,   rL   r   fsetrN   r  r   r2   r2   r3   r     s   z(_custom_model_inputs.<locals>.<listcomp>c                    s0   g | ](\}}t |tr|jd u r| vr|qS r,   ra  rc  Zspecialr2   r3   r     s   zParameter 'z' cannot be a model property: r   )r   varsr"   rT   r`   r   r   )	r   r   r   ZsettableZ
propertiesspecial_paramssettable_paramsr   r   r2   rd  r3   _custom_model_inputs  s     


rh  c                 C   s   t | std|dur(t |s(td| j}t| \}}}}|dur`t|jt|kr`tddd | D }td}|r|j}nd}t|| j	t||
d	d
t| |d}	|durt||	d< |	| t|tf|	}
t|d
krdnd|
_|
S )a7  
    Internal implementation `custom_model`.

    When `custom_model` is called as a function its arguments are passed to
    this function, and the result of this function is returned.

    When `custom_model` is used as a decorator a partial evaluation of this
    function is returned by `custom_model`.
    zDfunc is not callable; it must be a function or other callable objectNzFfit_deriv not callable; it must be a function or other callable objectzDderivative function should accept same number of parameters as func.c                 S   s   i | ]\}}|t ||d qS )r   )r   )rN   r   r   r2   r2   r3   rQ     s   z)_custom_model_wrapper.<locals>.<dictcomp>r   r   r   r   )r8   r:   r   r   r  r   r  TF)r   r)   r7   rh  r   __defaults__rT   r   r   r:   r   r  rP  r{   r#   r`  )r   r  Z
model_namer   rf  rg  r   r   r   rb   rc   r2   r2   r3   r^    sD    
	
r^  c           	         s  | j }|du |du @ |du @ r&td| jdkrL|dur>|g}|durL|g}|durp| }|j| jkrptd|durt|}t|| jkrtd|dur|d j|jkrtdnt	|d j}|durtdd	 |D 
tj }\ }|dur.t|d
 d t fdd	|D }ndd	 |jD }tj| }|ddd }|du rj| | }n2zt|| |  }W n ty   tdY n0 n>|du r|j}dd	 |D }tj| }|| |ddd  7 }|S )a@  
    Evaluates a model on an input array. Evaluation is limited to
    a bounding box if the `Model.bounding_box` attribute is set.

    Parameters
    ----------
    model : `Model`
        Model to be evaluated.
    arr : `numpy.ndarray`, optional
        Array on which the model is evaluated.
    coords : array-like, optional
        Coordinate arrays mapping to ``arr``, such that
        ``arr[coords] == arr``.

    Returns
    -------
    array : `numpy.ndarray`
        The model evaluated on the input ``arr`` or a new array from
        ``coords``.
        If ``arr`` and ``coords`` are both `None`, the returned array is
        limited to the `Model.bounding_box` limits. If
        `Model.bounding_box` is `None`, ``arr`` or ``coords`` must be passed.

    Examples
    --------
    :ref:`astropy:bounding-boxes`
    Nz6If no bounding_box is set,coords or arr must be input.r   zDnumber of array dimensions inconsistent with number of model inputs.z?coordinate length inconsistent with the number of model inputs.r   z3coordinate shape inconsistent with the array shape.c                 S   s0   g | ](}t |t |d  |d  d fqS r~  r  r  r2   r2   r3   r   :  s   z render_model.<locals>.<listcomp>r   c                    s   g | ]}t | qS r2   r  r  r  r2   r3   r   ?  s   c                 S   s(   g | ] \}}t || || d  d qS r	  r  r  r2   r2   r3   r   B  r5   r5  zkThe `bounding_box` is larger than the input arr in one or more dimensions. Set `model.bounding_box = None`.c                 S   s   g | ]}t |qS r2   r  r  r2   r2   r3   r   T  r5   )r   r   r   r   r  r   r  r   r  r  r  r   r  r]   r  r   )	r   Zarrr  r  r  r  r  r  r  r2   r  r3   render_model  s\    











rj  c                 C   s   | ` | S )a  
    This is a convenience function intended to disable automatic generation
    of the inverse in compound models by disabling one of the constituent
    model's inverse. This is to handle cases where user provided inverse
    functions are not compatible within an expression.

    Example:
        compound_model.inverse = hide_inverse(m1) + m2 + m3

    This will insure that the defined inverse itself won't attempt to
    build its own inverse, which would otherwise fail in this example
    (e.g., m = m1 + m2 + m3 happens to raises an exception for this
    reason.)

    Note that this permanently disables it. To prevent that either copy
    the model or restore the inverse later.
    )r   rL  r2   r2   r3   hide_inverse\  s    rk  )NN)rZ  )NrZ  )N)NN)\r:   r  r   r   r  r_  Znumbersr  rN  collectionsr   r   r   r   Znumpyr   Zastropy.utilsr   r   Zastropy.tabler   Zastropy.unitsr	   r
   r   Zastropy.units.utilsr   r   r   r   r   r   Zastropy.utils.codegenr   Zastropy.nddata.utilsr   r   Zutilsr   r   r   r   r   r   r   r   r   r   r   r   r    r!   __all__r6   r   r)   ABCMetar;   r"   r#   r$   r%   r  r  r  r  r  r	  r
  r  ZBINARY_OPERATORSr  r  r&   rE  r  rU  r!  Z_ORDER_OF_OPERATORSr6  r   r   opsr  r'   r*   r+   r(   rh  r^  rj  rk  r2   r2   r2   r3   <module>   s    	   8                  
        ^

#
 
 Z,
:
a