a
    L9f>9                     @   s   d dl Zd dlZd dlmZ d dlmZ d dlm	Z
 d dlZd dlZd dlmZ d dlmZ d dlmZ d dlmZ d dlmZ d dlmZ de
jd	< d
e
jd< de
jd< dejj_djejj_ e!d dd Z"G dd dZ#dS )    N)deepcopy)HandlerPatch)log)frames)get_horizons_coord)	body_dictg      ?zaxes.linewidth   z	font.sizei N  zagg.path.chunksizez{:.1f}WARNINGc                  C   s2   t jjtdg ddddgd } d| j_| S )z
    prints a selection of body keys and the corresponding body names which may be provided to the
    HeliosphericConstellation class
    index)IDZBodyColor)orientcolumnsr   r   r   Key)pd	DataFrame	from_dictr   dropdrop_duplicatesr
   name)data r   O/Users/putuwistika/Documents/TRILAK/hydralit-example/apps/extras/backmapping.pyprint_body_list   s    
r   c                   @   s<   e Zd ZdZg ddfddZdddZdddZdd ZdS )HeliosphericConstellationan  
    Class which handles the selected bodies
    Parameters
    ----------
    date: str
    body_list: list
            list of body keys to be used. Keys can be string of int.
    vsw_list: list, optional
            list of solar wind speeds at the position of the different bodies. Must have the same length as body_list.
            Default is an epmty list leading to vsw=400km/s used for every body.
    reference_long: float, optional
                Carrington longitute of reference position at the Sun
    reference_lat: float, optional
                Heliographic latitude of referene position at the Sun
    Nc                     s  t t|}tt || _|| _|| _td| jd}|	t
jdd| _t|dkrhtt|d }g d}g }g }	g }
g }g }g }g }g }g }g }t| D ]J\}}| v r܈ | d } | d } | d	 }n.|}t|}|| } t|g|||g zt||d}|	t
jdd} | |  | ||  |jj| jjj }|d
krp|d }|jj| jjj }||jj |	|jj |
|jj || || |||  | j||||| d\}} | | |jj| }|dkr|d }|| | jd url | | |jj| j }|d
krX|d }|| || | jd ur|jj| j }|| W q ty   td tdt| d | j  tdt| d | j  || Y q0 q fdd|D }|| _t|
| _ t!"t | j# ||	|
||||d| _$| jd ur^|| j$d< || j$d< | jd urt|| j$d< | j$j%j&f i ddi d S )Ni  idSun)observerr     )forestgreen
mediumbluemsaddlebrowntomatoolive	steelbluedarkmagentacdarkslategrayyellowdarkolivegreen              v@)vswh   z!!! No ephemeris for target "z" for date zNo ephemeris for target "c                    s   i | ]}| | qS r   r   ).0Zsel_keybodiesr   r   
<dictcomp>       z6HeliosphericConstellation.__init__.<locals>.<dictcomp>)zSpacecraft/Bodyu   Carrington Longitude (°)u   Latitude (°)zHeliocentric Distance (AU)z,Longitudinal separation to Earth's longitudez*Latitudinal separation to Earth's latitudeVswz)Magnetic footpoint longitude (Carrington)z7Longitudinal separation between body and reference_longzLLongitudinal separation between body's mangetic footpoint and reference_longz5Latitudinal separation between body and reference_latz
text-alignleft)'listdictfromkeysr   r   datereference_longreference_latr   transform_tor   HeliographicCarringtonpos_Elennpzeros	enumeratecopystrupdateappendlonvaluelatradiusbackmapping
ValueErrorprintstwarningremovemaxmax_distr   r   keyscoord_tablestyleZset_properties) selfr<   	body_listvsw_listr=   r>   rA   random_colsZbody_lon_listZbody_lat_listZbody_dist_listZlongsep_E_listZlatsep_E_listZbody_vsw_listZfootp_long_listZlongsep_listZlatsep_listZfootp_longsep_listibodybody_idbody_lab
body_colorposZ	longsep_EZlatsep_EsepalphaZbody_footp_longZlong_sepZlat_sepZbody_dict_shortr   r3   r   __init__<   s    









z"HeliosphericConstellation.__init__r   c                 C   s   t jd }|}|jj}|jj}td}	|| | }
t|	|
 }|dur||| | }|dkrf|d }|dk rdt| }nt	j
}||fS )a;  
        Determine the longitudinal separation angle of a given spacecraft and a given reference longitude
        Parameters
        ----------
        body_pos : astropy.coordinates.sky_coordinate.SkyCoord
               coordinate of the body in Carrington coordinates
        date: str
              e.g., '2020-03-22 12:30'
        reference_long: float
                        Carrington longitude of reference point at Sun to which we determine the longitudinal separation
        vsw: float
             solar wind speed (km/s) used to determine the position of the magnetic footpoint of the body. Default is 400.
        out:
            sep: float
                longitudinal separation of body magnetic footpoint and reference longitude in degrees
            alpha: float
                backmapping angle
          M?j%?Ng     f@r0   g     f)constaurJ   rK   rM   mathradiansdegreesabsrC   nan)rY   body_posr<   r=   r/   AUrb   rJ   distomegattrd   rc   r   r   r   rN      s    

z%HeliosphericConstellation.backmappingTFr1   c           '      C   s$  ddl }tjd }tjtdddd\}	}
|
| _td| j	d	 d
}t
d}t| jD ]\}}| j| d }| j| d }| j| d }| j| d }|}|jj}|jj}| jjj}| jjj}|
jt||d||d |r|
jt|t|gd|gd|d |rX|| | }t|| }t||||  ||   }|
j|||d qX| jdur| j}|dk rx|d }t||||  || |   |||  ||   }t| j	d dg}tj|d dd|dddddddd}|r|
j||dd | d!d" |
jd#d$d%}| jdurTd&d' } |
j|gd(gd)tjt| d*id$d+}!|
| |
|d,  |
td-|  |
| j	d	  |
d |
j ! j"j#dd. tj$d/| j	d0 |
j%j&d1dd2dd3}"|
'|" | j	dk r|
j(td| j	d0 d4dd d5d6 n2| j	d7k r6|
j(td| j	d0 d8dd d5d6 |
j)| j*d9 d:d; t+  tj,d<d= |r|
- }#d>}$|#j.|$d  |#j/|$d  |#j0|$ |#j1|$ g}%| 2|
||%}&|
j3d?d7d@ |
j4dAdBdCdDdEdFdG|	j5dH |
j4dAd>dIdJdKdFdG|	j5dH |r|	j67d |dLkrt8| t9:|	 dS )Ma  
        Make a polar plot showing the Sun in the center (view from North) and the positions of the selected bodies
        Parameters
        ----------
        plot_spirals: bool
                    if True, the magnetic field lines connecting the bodies with the Sun are plotted
        plot_sun_body_line: bool
                    if True, straight lines connecting the bodies with the Sun are plotted
        show_earth_centered_coord: bool
                    if True, additional longitudinal tickmarks are shown with Earth at longitude 0
        reference_vsw: int
                    if defined, defines solar wind speed for reference. if not defined, 400 km/s is used
        outfile: string
                if provided, the plot is saved with outfile as filename
        r   Nrf   polar)
projection)      )
subplot_kwfigsizegy&1|?333333?gMbP?rg   r+   r,         s)colorlabelg{Gz?:)r~           r.   g	@g       @g?gQ?blackg?   )
head_widthhead_length	edgecolor	facecolorlwzorderoverhangz--kz)field line connecting to
ref. long. (vsw=z km/s))r   )333333?gffffff?   )locfontsizec                 [   s   t jdd| | ddd| dS )Nr         ?Tg      ?)length_includes_headr   )mpatches
FancyArrow)widthheight_r   r   r   legend_arrow  s    z4HeliosphericConstellation.plot.<locals>.legend_arrowzreference long.)r   g333333?)
patch_func)r   handler_mapr   x   i  )nbins)r   r   g(\?kF)	transformr   r   fillr   r   g     6@)angle
   g      ?
<   )padg333333?)bottomgQ?x)axisr   gGz?g{Gz?z
Solar-MACHzDejaVu Serif   rightr   )
fontfamilyr   havar   zhttps://solar-mach.github.iozDejaVu Sans   r1   );pylabrh   ri   pltsubplotsr:   axrC   arangerU   rk   rE   r   rM   rK   rJ   rA   plotdeg2radrl   r=   minarrowlegendr   r   r   
add_artistset_rlabel_positionset_theta_offsetset_rmaxset_rminyaxisget_major_locatorbase
set_paramsCircle	transData_b	add_patch
set_rgrids	set_titler<   tight_layoutsubplots_adjustget_positionx0y0r   r   _polar_twintick_paramstexttransFigurepatch	set_alphasavefigrQ   pyplot)'rY   plot_spiralsplot_sun_body_lineshow_earth_centered_coordreference_vswtransparentoutfileplrp   figr   rrr   r]   r_   r`   ra   Zbody_vswro   rb   Z	dist_bodyZ	body_longE_longZdist_ers   rd   Z
alpha_bodyZ	delta_refZ	alpha_refZ
arrow_distZref_arrZleg1r   Zleg2circlepos1offsetpos2ax2r   r   r   r      s    



&
 


(&,



zHeliosphericConstellation.plotc                 C   st   |j j|ddd| |d}|| jd  |jd |d |jddd	d
 |j	
 }|D ]}|d q`|S )z|
        add an additional axes which is needed to plot additional longitudinal tickmarks with Earth at longitude 0
        rt   twinF)ru   r   frameontheta_directiontheta_offsetrz   Sr   	darkgreenr   )r   colorsr   )figureadd_axesget_theta_directionr   rU   r   set_visibleset_theta_zero_locationr   xaxisget_gridlines	set_color)rY   r   r   positionr   	gridlinesZxaxr   r   r   r   J  s    


z%HeliosphericConstellation._polar_twin)r   )TFTr   Fr1   )__name__
__module____qualname____doc__re   rN   r   r   r   r   r   r   r   +   s
   h
*
|r   )$	streamlitrQ   rj   rF   r   matplotlib.patchespatchesr   matplotlib.pyplotr   r   numpyrC   pandasr   scipy.constants	constantsrh   Zmatplotlib.legend_handlerr   sunpyr   sunpy.coordinatesr   r   Zapps.extras.selected_bodiesr   rcParamsoptionsdisplaymax_rowsformatfloat_formatsetLevelr   r   r   r   r   r   <module>   s(   




