B
    z‹d&w  ã            3   @   sê   d dgZ ddlZddlmZmZmZmZ ddlm	Z	m
Z
 ddlmZ ddlmZ ddlmZ dd	lmZ ddlZG d
d„ dejƒZG dd„ dejƒZG dd„ dejƒZG dd„ dejƒZdd„ Zdd„ Zd(d$d „Zd)d%d„Zd*d&d'„ZdS )+ÚprojviewÚnewprojploté    Né   )Úang2pixÚ
npix2nsideÚremove_dipoleÚremove_monopole)ÚRotatorÚcoordsys2euler_zyz)Úget_color_table)ÚGeoAxes)ÚMultipleLocatorc                   s"   e Zd ZdZd‡ fdd„	Z‡  ZS )Ú!ThetaFormatterCounterclockwisePhiz~Convert tick labels from rads to degs and shifts labelling from -180|-90|0|90|180 to conterclockwise periodic 180|90|0|270|180Nc                s8   |dkr|d9 }|dk r&|dt j 7 }tt| ƒ ||¡S )Nr   éÿÿÿÿé   )ÚnpÚpiÚsuperr   Ú__call__)ÚselfÚxÚpos)Ú	__class__© ú_/work/yifan.wang/ringdown/master-ringdown-env/lib/python3.7/site-packages/healpy/newvisufunc.pyr      s
    z*ThetaFormatterCounterclockwisePhi.__call__)N)Ú__name__Ú
__module__Ú__qualname__Ú__doc__r   Ú__classcell__r   r   )r   r   r      s   r   c                   s"   e Zd ZdZd‡ fdd„	Z‡  ZS )ÚThetaFormatterClockwisePhizxConvert tick labels from rads to degs and shifts labelling from -180|-90|0|90|180 to clockwise periodic 180|270|0|90|180Nc                s(   |dk r|dt j 7 }tt| ƒ ||¡S )Nr   r   )r   r   r   r    r   )r   r   r   )r   r   r   r      s    z#ThetaFormatterClockwisePhi.__call__)N)r   r   r   r   r   r   r   r   )r   r   r       s   r    c                   s"   e Zd ZdZd‡ fdd„	Z‡  ZS )ÚThetaFormatterSymmetricPhizKJust convert phi ticks from rad to degs and keep the true -180|-90|0|90|180Nc                s   t t| ƒ ||¡S )N)r   r!   r   )r   r   r   )r   r   r   r   &   s    z#ThetaFormatterSymmetricPhi.__call__)N)r   r   r   r   r   r   r   r   )r   r   r!   #   s   r!   c                   s"   e Zd ZdZd‡ fdd„	Z‡  ZS )ÚThetaFormatterThetaz%Convert theta ticks from rads to degsNc                s   t t| ƒ ||¡S )N)r   r"   r   )r   r   r   )r   r   r   r   -   s    zThetaFormatterTheta.__call__)N)r   r   r   r   r   r   r   r   )r   r   r"   *   s   r"   c             C   s&   t  |¡}t jd t  | ¡ }||fS )z0Converts theta and phi to longitude and latituder   )r   Zasarrayr   )ÚthetaÚphiÚ	longitudeÚlatituder   r   r   Úlonlat1   s    
r'   c             C   s.   x(|   ¡ D ]\}}||kr
|| | |< q
W | S )N)Úitems)Z	main_dictZupdate_dictÚkeyZkey_valr   r   r   Úupdate_dictionary9   s    r*   Ú éè  FÚastroú%gTÚviridisÚ	mollweideÚ
horizontalé<   é   ÚblackÚcounterclockwiseéo   c3       d   
      s²  ddddg}4|dkr&ˆ dk	r&t  ˆ ¡}|	dkr@ˆ dk	r@t  ˆ ¡}	dddd	œ}5|dk	r^t|5|ƒ}5|0rtt| |2|d
d} n|1rˆt| |2|d
d} dd„ }6ddddddddœ}7|$dk	r¶t|7|$ƒ}7t  |6|ƒ|6|	ƒg¡}8|8dkrÚd}9nd|8 }9d}:|};|dkr$|dkr
d}<d}=d}|dkr$d}<d}=d}9d}||4krn|dkrDd}<d}=d}|dkrnd}<d }=ˆ dk	rfd}9nd!}9d"}|d#kr¾|dkr’d}<d}=d$}d%}:|dkr¾d&}<d}=d'}9d(}|dkr¾d}=d}:|d)krø|dkrÞd}<d}=d}|dkrød&}<d}=d}9d}|;dk	r|;}|dkrL|dk	r:d*|kr:|d* d+kr6d,n|9}9|dk	rL|9d-7 }9|<|=|9d.d+||:d/œ}>|dk	r t d0t|>ƒ d1 ¡ t|>|ƒ}>t d2t|>ƒ d1 ¡ |"dkr®d3n|"}?d4|?d5d5||d6œ}@|dk	rt d7t|@ƒ d1 ¡ t|@|ƒ}@t d8t|@ƒ d1 ¡ |spt	|,d9ƒr"|,\}A}B}Cn |,d: |,d: d |,d   }A}B}C|Cdk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d` |Ij6da|7db |!d` |d#kr²|I 8d¡ |
r˜ˆ dkrÊ||	g‰ |*dk	r$dc}*|t  | ¡krìdd}*|	t  | ¡k 	r de}*|t  | ¡k	r$|	t  | ¡k 	r$dZ}*|)	r.dnˆ }\|j9|X||>df |>dg |\|*dh}]|)	r¼t:t;|] <¡ ƒt;ˆ ƒB ƒ}\t  =|\¡}\|\|\|k }\|\|\|	k }\‡ ‡fdidj„|\D ƒ}^|] >|\|^¡ |] 4|^¡ n‡fdkdj„ˆ D ƒ}^|dk
r(|]j?j@|^|#dV |]j?j*jA||7dl |#d] |]j?j6d^|7dm |>dn do |>dp |]j?j*_B|dk
rŒ|]j?jC|^|>d* dq|#dr |]j?j.jA||7dl d+|#ds |]j?j6da|7dm |>dn do |>dp |]j?j._B|]jD Edt¡ |IjF||7du |#d] |IjG||7dv |#d] |
sÐ|dk	rR|dk
rÞdw}tH||@dx |@dy dz\}_}`xXtI|_ƒD ]L\}a}b|a|`kr"|@d{ d| }cn|@d{ }ctjJ|b|c|@d} |@d~ |@d d€œŽ qW |dk	r|tjKdd‚|dƒdq|7dl |#|IjLd„ |dk	r¦tjKd…d‚|d†dq|7dl |#|IjLd„ t M¡  |XS )‡a‚  Plot a healpix map (given as an array) in the chosen projection.

    See examples of using this function in the documentation under "Other
    tutorials". Overplot points or lines using :func:`newprojplot`.

    .. warning::
        this function is work in progress, the aim is to reimplement the healpy
        plot functions using the new features of matplotlib and remove most
        of the custom projection code.
        Please report bugs or submit feature requests via Github.
        The interface will change in future releases.

    Parameters
    ----------
    m : float, array-like or None
      An array containing the map, supports masked maps, see the `ma` function.
      If None, will display a blank map, useful for overplotting.
    fig : int or None, optional
      The figure number to use. Default: create a new figure
    rot : scalar or sequence, optional
      Describe the rotation to apply. In the form (lon, lat, psi) (unit:
      degrees) : the point at longitude *lon* and latitude *lat* will be at the
      center. An additional rotation of angle *psi* around this direction is
      applied.
    coord : sequence of character, optional
      Either one of 'G', 'E' or 'C' to describe the coordinate system of the
      map, or a sequence of 2 of these to rotate the map from the first to the
      second coordinate system. default: 'G'
    unit : str, optional
      A text describing the unit of the data. Default: ''
    xsize : int, optional
      The size of the image. Default: 800
    width : float, optional
        Sets the width of the figure. Use override_plot_properties for more.
        Overrides the default width of the figure
    nest : bool, optional
      If True, ordering scheme is NESTED. Default: False (RING)
    min : float, optional
      The minimum range value
    max : float, optional
      The maximum range value
    flip : {'astro', 'geo'}, optional
      Defines the convention of projection : 'astro' (default, east towards
      left, west towards right) or 'geo' (east towards roght, west towards left)
      It creates the `healpy_flip` attribute on the Axes to save the convention
      in the figure.
    format : str, optional
      The format of the scale label. Default: '%g'
    cbar : bool, optional
      Display the colorbar. Default: True
    cmap : str, optional
        Specify the colormap. default: Viridis
    norm : {'hist', 'log', 'symlog', 'symlog2', None}
      Color normalization:
      hist = histogram equalized color mapping.
      log = logarithmic color mapping.
      symlog = symmetric logarithmic, linear between -linthresh and linthresh.
      symlog2 = similar to symlog, used for plack log colormap.
      default: None (linear color mapping)
    norm_dict : dict, optional
        Parameters for normalization:
        default is set to {"linthresh": 1, "base": 10, "linscale": 0.1}
        where linthresh determines the linear regime of symlog norm,
        and linscale sets the size of the linear regime on the cbar.
        default: None
    graticule : bool
      add graticule
    graticule_labels : bool
      longitude and latitude labels
    rot_graticule : bool
      rotate also the graticule when rotating the map
    graticule_coord : str
      Either one of 'G', 'E' or 'C' to describe the coordinate system of the
      graticule
    override_rot_graticule_properties : dict
      Override the following rotated graticule properties: "g_linestyle",
      "g_linewidth", "g_color", "g_alpha", "t_step", "p_step".
    return_only_data : bool, optional
        Return array of data
    projection_type :  {'aitoff', 'hammer', 'lambert', 'mollweide', 'cart',
    '3d', 'polar'}
      type of the plot
    cb_orientation : {'horizontal', 'vertical'}
      color bar orientation
    xlabel : str
      set x axis label
    ylabel : str
      set y axis label
    longitude_grid_spacing : float
      set x axis grid spacing
    latitude_grid_spacing : float
      set y axis grid spacing
    override_plot_properties : dict
      Override the following plot properties: "cbar_shrink", "cbar_pad",
      "cbar_label_pad", "cbar_tick_direction", "vertical_tick_rotation"
      "figure_width": width, "figure_size_ratio": ratio.
    title : str
      set title of the plot
    rlabel : str
      set label at top right corner of axis
    llabel : str
      set label at top left corner of axis
    xtick_label_color : str
        Change the color of the graticule xticks
    ytick_label_color : str
        Change the color of the graticule yticks
    graticule_color : str
        Change the color of the graticule
    fontname : str
        Change the fontname of the text
    fontsize:  dict
      Override fontsize of labels: "xlabel", "ylabel", "title", "xtick_label",
      "ytick_label", "cbar_label", "cbar_tick_label".
    phi_convention : string
      convention on x-axis (phi), 'counterclockwise' (default), 'clockwise',
      'symmetrical' (phi as it is truly given) if `flip` is "geo",
      `phi_convention` should be set to 'clockwise'.
    custom_xtick_labels : list
      override x-axis tick labels
    custom_ytick_labels : list
      override y-axis tick labels
    cbar_ticks : list
      custom ticks on the colorbar
    show_tickmarkers : bool, optional
      Preserve tickmarkers for the full bar with labels specified by ticks
      default: None
    extend : str, optional
      Whether to extend the colorbar to mark where min or max tick is less than
      the min or max of the data. Options are "min", "max", "neither", or "both"
    invRot : bool
      invert rotation
    sub : int, scalar or sequence, optional
      Use only a zone of the current figure (same syntax as subplot). Default:
      111
    reuse_axes : bool, optional
      If True, reuse the current Axes (should be a MollweideAxes). This is
      useful if you want to overplot with a partially transparent colormap, such
      as for plotting a line integral convolution. Default: False
    margins : None or sequence, optional
      Either None, or a sequence (left,bottom,right,top) giving the margins on
      left,bottom,right and top of the axes. Values are relative to figure
      (0-1). Default: None
    hold : bool, optional
      If True, replace the current Axes by new axis. use this if you want to
      have multiple maps on the same figure. Default: False
    remove_dip : bool, optional
      If :const:`True`, remove the dipole+monopole
    remove_mono : bool, optional
      If :const:`True`, remove the monopole
    gal_cut : float, scalar, optional
      Symmetric galactic cut for the dipole/monopole fit. Removes points in
      latitude range [-gal_cut, +gal_cut]
    kwargs : dict
        any leftover arguments will be passed to pcolormesh
    ZaitoffÚhammerZlambertr0   Nr   é
   gš™™™™™¹?)Z	linthreshÚbaseZlinscaleT)Úgal_cutÚnestÚcopyc             S   s&   yt t| ƒ d¡d ƒS    dS d S )NÚ.r   r   )ÚlenÚstrÚsplit)Únumberr   r   r   Úfind_number_of_decimals%  s    z)projview.<locals>.find_number_of_decimalsé   é   )ÚxlabelÚylabelÚtitleÚxtick_labelÚytick_labelÚ
cbar_labelÚcbar_tick_labelé   iåÿÿÿi÷ÿÿÿg)\Âõ(ä?Z3dÚverticalgš™™™™™á?g{®Gáz”?g      '@r1   gš™™™™™É?r   iöÿÿÿg333333ã?g{®Gáz„?gš™™™™™©?iøÿÿÿg      !@Zcartg333333#@gáz®GáÚ?gš™™™™™Ù?iôÿÿÿgš™™™™™!@ZpolarÚvertical_tick_rotationéZ   é   é   Úout)Úcbar_shrinkÚcbar_padÚcbar_label_padÚcbar_tick_directionrN   Úfigure_widthÚfigure_size_ratioz)
 *** Overriding default plot properies: z ***z
 *** New plot properies: Zgreyú-g      è?)Úg_linestyleÚg_colorÚg_alphaÚg_linewidthÚt_stepÚp_stepz.
 *** Overriding rotated graticule properies: z'
 *** New rotated graticule properies: Ú__len__éd   z Wrong values for sub: %d, %d, %dr6   rW   rX   )Zfigsize)g{®Gáz”?gš™™™™™©?g¸…ëQ¸î?gÍÌÌÌÌÌì?)Z
projectiong\Âõ(\ï?gffffffî?r   iLÿÿÿé´   r-   r   )ÚleftÚrightÚtopÚbottomi¦ÿÿÿ)ÚcoordÚrotÚinv)ÚcmapÚnorm)r;   Úauto)rk   Ú
rasterizedrj   Zshading)rj   rk   rm   F)Úcolorr5   Z	clockwiseZsymmetrical)ÚfontnamezPut names for all z& x-tick labels!. No re-labelling done.z& y-tick labels!. No re-labelling done.Zboth)ÚaxisÚwhichÚlengthrG   )Úfontsizero   r   rH   )rp   Ú	labelsizeÚcolorsÚyrI   ZneitherÚminÚmaxrS   rT   )ZorientationÚshrinkÚpadÚticksÚextendc                s    g | ]}|ˆ krˆ| nd ‘qS )r+   r   )Ú.0Útick)Ú
cbar_ticksÚformatr   r   ú
<listcomp>§  s    zprojview.<locals>.<listcomp>c                s   g | ]}ˆ | ‘qS r   r   )r}   r~   )r€   r   r   r   ¬  s    rJ   rK   rV   )rp   rt   Ú	directionrU   Úcenter)ÚrotationÚvaro   )rs   r„   ro   ZfacerE   rF   ÚGr^   r_   )r^   r_   r]   g      @rZ   r[   r\   )Ú	linewidthZ	linestylern   Úalphag333333ï?gš™™™™™í?rd   )Zhar…   rs   ro   Z	transformgš™™™™™™?rc   )Nr   rw   rx   r*   r   r   ÚwarningsÚwarnr?   ÚhasattrÚ
ValueErrorÚpltZfigureZgcfÚarrayÚgcaZget_positionZravelZdelaxesZget_fignumsZadd_subplotÚlinspacer   ÚradiansZsubplots_adjustÚhealpy_flipZmeshgridr	   ÚflattenZreshaper   r>   ÚisnanÚisinfr   r   Z
pcolormeshZplot_surfaceÚgridZset_longitude_gridZset_latitude_gridZset_longitude_grid_endsZxaxisZset_major_locatorr   Údeg2radZyaxisr   r    r!   Zset_major_formatterr"   Zset_ticklabelsZget_ticklabelsZtick_paramsÚ	set_titleZ
set_aspectZcolorbarÚlistÚsetZ	get_ticksÚsortZ	set_ticksÚaxZset_xticklabelsZset_label_textZlabelpadZset_yticklabelsZsolidsZset_edgecolorZ
set_xlabelZ
set_ylabelÚCreateRotatedGraticuleÚ	enumerateÚplotÚtextZ	transAxesZdraw)dÚmZfigrh   rg   ÚunitZxsizeÚwidthr;   rw   rx   Úflipr€   Zcbarrj   rk   Z	norm_dictZ	graticuleZgraticule_labelsZrot_graticuleZgraticule_coordZ!override_rot_graticule_propertiesZreturn_only_dataZprojection_typeZcb_orientationrE   rF   Zlongitude_grid_spacingZlatitude_grid_spacingZoverride_plot_propertiesrG   ZrlabelZllabelZxtick_label_colorZytick_label_colorZgraticule_colorro   rs   Zphi_conventionZcustom_xtick_labelsZcustom_ytick_labelsr   Zshow_tickmarkersr|   ZinvRotÚsubZ
reuse_axesZmarginsZholdZ
remove_dipZremove_monor:   ÚkwargsZgeographic_projectionsZnorm_dict_defaultsrB   Zfontsize_defaultsZdecsZlpadÚratioZcustom_widthry   rz   Zplot_propertiesZg_colZrot_graticule_propertiesZnrowsZncolsÚidxZextentrc   rf   rd   re   rœ   Zysizer#   r$   r%   r&   ZPHIZTHETAÚrZnsideÚwÚcmÚnnZgrid_pixZgrid_mapÚretZ	LONGITUDEZLATITUDEZxtick_formatterr{   ÚcbÚlabelsÚrotated_grid_linesÚ
where_zeroÚiZg_liner‡   r   )r   r€   r   r   @   s¦    R

























 







 














"
"



 








c       
      K   sn   ddl m} | ¡ }t|ddƒ}t| |ƒ\}}|dkr>|d }|dkrX|j||f|Ž}	n|j|||f|Ž}	|	S )a¿  newprojplot is a wrapper around :func:`matplotlib.Axes.plot` to support
    colatitude theta and longitude phi and take into account the longitude convention
    (see the `flip` keyword of :func:`projview`)

    You can call this function as::

       newprojplot(theta, phi)        # plot a line going through points at coord (theta, phi)
       newprojplot(theta, phi, 'bo')  # plot 'o' in blue at coord (theta, phi)

    Parameters
    ----------
    theta, phi : float, array-like
      Coordinates of point to plot in radians.
    fmt : str
      A format string (see :func:`matplotlib.Axes.plot` for details)

    Notes
    -----
    Other keywords are passed to :func:`matplotlib.Axes.plot`.
    r   Nr’   r-   r   )Úmatplotlib.pyplotÚpyplotr   Úgetattrr'   rŸ   )
r#   r$   Úfmtr¦   r   rœ   r¤   r%   r&   r­   r   r   r   r     s    c          	   C   sð  | d }y| d }W n   d}Y nX d}t jd }t  dd| |¡}t  dd| |¡}t  t  |dk¡d |jt  |dk¡d  f¡}	t  t  dd|¡¡}
t  t  dd|¡¡| }g }x`|D ]X}t  t  |¡| ¡| }t	d|fd	d
}|||
ƒ\}}|| }|| }| 
||g¡ q¾W xt|D ]l}t  t  |¡| ¡}t	|dfd	d
}|||ƒ\}}t	d|fd	d
}|||ƒ\}}|| }| 
||g¡ q W xV|D ]N}t  t  t  |d ¡¡t  d¡k¡}t j |d ¡|d< t jj|d |< q–W ||	fS )Nr   r   ra   r   i¦ÿÿÿrO   iLÿÿÿrb   T)rh   ri   é-   )r   r   ZarangeZhstackÚwhereÚsizer—   r   Zzerosr	   ÚappendÚabsÚdiffÚmarŽ   Zmasked)rh   r^   r_   r$   r#   ZpointDensityZconventionThetaOffsetZthetaSpacingZ
phiSpacingr±   Zgline_phi_fixedZgline_theta_fixedr°   Z
thetaSpaceZgline_thetar©   Zgline_theta_rotZgline_phi_fixed_rotZphiSpaceZ	gline_phiZgline_theta_fixed_rotZgline_phi_rotZg_linesÚmaskr   r   r   r   /  sF    




$r   )3NNNNr+   r,   NFNNr-   r.   Tr/   NNFFFNNFr0   r1   NNr2   r3   NNNNr4   r4   NNNr5   NNNFNTr6   FNFFFr   )N)r3   r3   )Ú__all__Únumpyr   Z	pixelfuncr   r   r   r   Úrotatorr	   r
   Zprojaxesr   r³   r´   r   Zmatplotlib.projections.geor   Zmatplotlib.tickerr   r‰   ZThetaFormatterr   r    r!   r"   r'   r*   r   r   r   r   r   r   r   Ú<module>   s                                                     
     
$