U
    md2                     @   s  d dl mZmZmZmZmZ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mZmZmZ dd	lmZ dd
lmZ ddlmZ eeeeeedeee df dddZeeeeeedeeee df dddZ eeeeeedddde!e!eeee df dddZ"d-eee#ej$f eee#ej$f  e#e%e#ee e!e%eeddd Z&eed!d.eee# e'e'e%e!eee%e%f  e!e!eee#e!f  ee d$d%d&Z(d/e#e#eee%e%f  e!e!eee#e!f  d*d+d,Z)dS )0    )UnionListOptionalAnyTuple
CollectionN)AnnData)Axes   )_doc_params	embedding)doc_adata_color_etcdoc_edges_arrowsdoc_scatter_embeddingdoc_show_save_ax)_wraps_plot_scatter)_utils   )_anndata_to_wishbone)Zadata_color_etcZedges_arrowsZscatter_bulkshow_save_ax)returnc                 K   s   t | df|S )a      Scatter plot in PHATE basis.

    Parameters
    ----------
    {adata_color_etc}
    {edges_arrows}
    {scatter_bulk}
    {show_save_ax}

    Returns
    -------
    If `show==False`, a list of :class:`~matplotlib.axes.Axes` objects.
    Every second element corresponds to the 'right margin'
    drawing area for color bars and legends.

    Examples
    --------
    >>> from anndata import AnnData
    >>> import scanpy.external as sce
    >>> import phate
    >>> data, branches = phate.tree.gen_dla(
    ...     n_dim=100,
    ...     n_branch=20,
    ...     branch_length=100,
    ... )
    >>> data.shape
    (2000, 100)
    >>> adata = AnnData(data)
    >>> adata.obs['branches'] = branches
    >>> sce.tl.phate(adata, k=5, a=20, t=150)
    >>> adata.obsm['X_phate'].shape
    (2000, 2)
    >>> sce.pl.phate(
    ...     adata,
    ...     color='branches',
    ...     color_map='tab20',
    ... )
    phater   adatakwargs r   K/home/sam/Atlas/atlas_env/lib/python3.8/site-packages/scanpy/external/pl.pyr      s    /r   c                 K   s   t | df|S )z    Scatter plot in TriMap basis.

    Parameters
    ----------
    {adata_color_etc}
    {edges_arrows}
    {scatter_bulk}
    {show_save_ax}

    Returns
    -------
    If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
    trimapr   r   r   r   r   r   H   s    r   TF)show
return_fig)r   r    r   c                K   sv   | j d }| j|  }tdt|\}}t|D ],\}}	t| d||	|	d|| dd}
|
  q4|rj|S |sr|S dS )aN      Scatter plot in Harmony force-directed layout basis.

    Parameters
    ----------
    {adata_color_etc}
    {edges_arrows}
    {scatter_bulk}
    {show_save_ax}

    Returns
    -------
    If `return_fig` is True, a :class:`~matplotlib.figure.Figure`.
    If `show==False` a :class:`~matplotlib.axes.Axes` or a list of it.
    Zharmony_timepoint_varr   ZharmonyFnone)colorgroupstitler   axZ
legend_locN)	unsobsuniquepltsubplotslen	enumerater   Zset_axis_off)r   r   r    r   Ztp_nameZtpsfigaxesitppr   r   r   harmony_timeseriesa   s&    


r2   X_umap
Spectral_r        k      $@)r   
projectionccmap	linewidth	edgecolorr.   colorbarsr   r   c	                 K   s  t |tr8z| j| }
W q< tk
r4   tdY q<X n|}
|dkrTt  t }|dkr|j|
dddf |
dddf f|||d|	 |S t |trzt	
t| j| }W n tk
r   Y nX t |d tt	jfr|t |t	jtfr|ddlm} ||}t	j|dd\}}|j|
dddf |
dddf f|||||d|	}|rtj|||d	}|j||  nft |t	jtfsd
}|}|j|
dddf |
dddf f|||||d|	}|rtj||d |S )a      Scatter plot using the SAM projection or another input projection.

    Parameters
    ----------
    projection
        A case-sensitive string indicating the projection to display (a key
        in adata.obsm) or a 2D numpy array with cell coordinates. If None,
        projection defaults to UMAP.
    c
        Cell color values overlaid on the projection. Can be a string from adata.obs
        to overlay cluster assignments / annotations or a 1D numpy array.
    axes
        Plot output to the specified, existing axes. If None, create new
        figure window.
    kwargs
        all keyword arguments in matplotlib.pyplot.scatter are eligible.
    z;Please create a projection first using run_umap or run_tsneNr   r   )r>   r;   r<   T)Zreturn_index)r9   r:   r>   r;   r<   )r%   ZticksF)r%   )
isinstancestrZobsmKeyError
ValueErrorr)   figuregcaZscatternparraylistr'   Zstr_ndarrayZsamalg.utilitiesZ	utilitiesZconvert_annotationsr(   r=   r%   Zset_yticklabels)r   r8   r9   r:   r;   r<   r.   r=   r>   r   dtutr/   ZuiZaiZcaxZcbarr   r   r   sam   s    
   
(
rK   )r      皙?)r   markersno_binssmoothing_factor	min_deltashow_variancefigsizer    r   saver%   c              	   C   s   t | }|dkr*dt| }dt| }n|\}}|
r>|
j}ntj||fd}t }
|j|||||||
d\}}}
|d | jd< |d | jd	< |d
 | jd< tjd||	d |r|S |s|
S dS )a}      Plot marker trends along trajectory, and return trajectory branches for further
    analysis and visualization (heatmap, etc..)

    Parameters
    ----------
    adata
        Annotated data matrix.
    markers
        Iterable of markers/genes to be plotted.
    show_variance
        Logical indicating if the trends should be accompanied with variance.
    no_bins
        Number of bins for calculating marker density.
    smoothing_factor
        Parameter controlling the degree of smoothing.
    min_delta
        Minimum difference in marker expression after normalization to show
        separate trends for the two branches.
    figsize
        width, height
    return_fig
        Return the matplotlib figure.
    {show_save_ax}

    Returns
    -------
    Updates `adata` with the following fields:

    `trunk_wishbone` : :class:`pandas.DataFrame` (`adata.uns`)
        Computed values before branching
    `branch1_wishbone` : :class:`pandas.DataFrame` (`adata.uns`)
        Computed values for the first branch
    `branch2_wishbone` : :class:`pandas.DataFrame` (`adata.uns`)
        Computed values for the second branch.
    Nr
   g      ?rS   )rN   rR   rO   rP   rQ   r-   r%   ZTrunkZtrunk_wishboneZBranch1Zbranch1_wishboneZBranch2Zbranch2_wishboneZwishbone_trajectoryr   rT   )	r   r+   rC   r)   rD   Zplot_marker_trajectoryr&   r   savefig_or_show)r   rN   rO   rP   rQ   rR   rS   r    r   rT   r%   wbwidthheightr-   Z
ret_valuesr   r   r   wishbone_marker_trajectory   s4    3
r[   loglinear      )scale_hist_obsscale_hist_simrS   r    r   rT   c                 C   s  dt jtjttddd}d| jkr,tdd| jd kr~| jd d }| j| jdd	d
}	t	|	j
j}
|d |d |
 f}n tjtd| jd| jd}	d}
t j|
d|d\}}t| j|	D ]\}\}}d| jd kr0| jd d | dd}| jd d | d }d| }|| d }|| d }n4| jd dd}| jd d }d}|d }|d }|||d |d| |d ||||d| |d q|  tjd||d |r|S |s|S dS )a      Plot histogram of doublet scores for observed transcriptomes and simulated doublets.

    The histogram for simulated doublets is useful for determining the correct doublet
    score threshold.

    Scrublet must have been run previously with the input object.

    Parameters
    ----------
    adata
        An annData object resulting from func:`~scanpy.external.scrublet`.
    scale_hist_obs
        Set y axis scale transformation in matplotlib for the plot of observed
        transcriptomes (e.g. "linear", "log", "symlog", "logit")
    scale_hist_sim
        Set y axis scale transformation in matplotlib for the plot of simulated
        doublets (e.g. "linear", "log", "symlog", "logit")
    figsize
        width, height
    show
         Show the plot, do not return axis.
    save
        If `True` or a `str`, save the figure.
        A string is appended to the default filename.
        Infer the filetype if ending on {`'.pdf'`, `'.png'`, `'.svg'`}.

    Returns
    -------
    If `return_fig` is True, a :class:`~matplotlib.figure.Figure`.
    If `show==False` a list of :class:`~matplotlib.axes.Axes`.

    See also
    --------
    :func:`~scanpy.external.pp.scrublet`: Main way of running Scrublet, runs
        preprocessing, doublet simulation and calling.
    :func:`~scanpy.external.pp.scrublet_simulate_doublets`: Run Scrublet's doublet
        simulation separately for advanced usage.
    N)r%   scoresscaler$   c                 S   s   | j |tddddddd | | |  }| | |d k	r^| j|td |ddd	 | | | 	d
 | 
d d S )Nr   r   2   grayT)r"   r;   Zdensityr
   black)r9   r;   zDoublet scorezProb. density)histrE   ZlinspaceZ
set_yscaleZget_ylimZset_ylimZplotZones	set_titleZ
set_xlabelZ
set_ylabel)r%   rc   rd   r$   	thresholdZylr   r   r   _plot_scoresz  s    



z1scrublet_score_distribution.<locals>._plot_scoresZscrubletz@Please run scrublet before trying to generate the scrublet plot.
batched_bycategoryF)copyr   r   )Zdtypeindexr
   rU   batchesrj   doublet_scores_simz (%s) Zdoublet_scorezObserved transcriptomes )rd   r$   rj   zSimulated doublets scrublet_score_distributionrV   )N)r)   r	   rE   rH   r@   r&   rB   r'   Zastyper+   cat
categoriespdZSeriesZbroadcast_toZn_obsZ	obs_namesr*   r,   groupbygetZtight_layoutr   rW   )r   ra   rb   rS   r    r   rT   rk   rl   rp   Z	n_batchesr-   ZaxsidxZ	batch_keyZsub_obsrj   rq   Zaxis_lab_suffixZobs_axZsim_axr   r   r   rs   I  sx    2    
   rs   )r3   Nr4   r5   r6   NTr7   )	rL   r   rM   FNFTNN)r\   r]   r^   FTN)*typingr   r   r   r   r   r   numpyrE   Zpandasrv   Zmatplotlib.pyplotZpyplotr)   Zanndatar   Zmatplotlib.axesr	   r   r   Zplottingr   Zplotting._docsr   r   r   r   Zplotting._tools.scatterplotsr   Ztl._wishboner   r   r   boolr2   r@   rH   floatrK   intr[   rs   r   r   r   r   <module>   s    +   +        a         X      