o
    tf~h                     @  s  d dl mZ d dlZd dlmZ d dlmZmZmZm	Z	m
Z
mZmZmZ d dlZd dlmZ d dlmZ d dlmZ g dZerFd dlmZ G dd	 d	ZG d
d dZG dd dZG dd dejeeeZG dd dejeeeZG dd dej eeeZ G dd dej!eeeZ!G dd dej"eeeZ#eee ee!e#f Z$e
de$dZ%G dd dej&e% eee% Z&e
de&dZ'ded!d"Z(G d#d$ d$ej)e&e%  eee% Z)e
d%e$dZ*e
d&e$dZ+dfd.d/Z,e-e,d0Z.e-e,d1Z/G d2d3 d3eZ0edgdhd8d9Z1edgdid;d9Z1edgdjd=d9Z1	dgdkd@d9Z1d d dAdBddddCdldPdQZ2dgdmdTdUZ3e
dVeeef dZ4dndWdXZ5eddYdod[d\Z6eddd]dpdcd\Z6ddYdqddd\Z6dS )r    )annotationsN)defaultdict)TYPE_CHECKINGClassVarGenericLiteralTypeVarUnioncastoverload)	BaseModel)	EnumTrackHeatmapTrack"IndependentViewportProjectionTrackCombinedTrackPluginTrackTrackTViewViewTViewconfconcathconcatvconcattrackviewcombinedividelock)TilesetResourcec                   @     e Zd Z	d
dddZd	S )_PropertiesMixinFselfutils.ModelTinplaceboolreturnc                 K  s4   |r| nt | }| D ]
\}}t||| q|S )ac  Configures top-level properties.

        Updates top-level properties for a Track, View, or Viewconf. This
        is really a convenience to allow method chaining/derived objects
        to be created without multiple lines of mutating the classes. For
        example,

        >>> view = hg.view(hg.track("heatmap"))
        >>> updated_view = view.properties(zoomFixed=True)
        >>> assert view.uid != updated_view.uid
        >>> assert view.zoomFixed is None
        >>> assert updated_view.zoomFixed is True

        inplace : bool, optional
            Whether to modify the existing track in place or return
            a new track with the options applied (default: `False`).

        **fields : dict
            The updated properties for .

        Returns
        -------
        track : A track with the the newly specified track options.

        )utilscopy_uniqueitemssetattr)r!   r#   fieldsmodelkv r.   T/var/www/html/software/conda/envs/catlas/lib/python3.10/site-packages/higlass/api.py
properties6   s   z_PropertiesMixin.propertiesNF)r!   r"   r#   r$   r%   r"   )__name__
__module____qualname__r0   r.   r.   r.   r/   r    5       r    c                   @  r   )_OptionsMixinFr!   r   r#   r$   r%   c                 K  s2   |r| nt | }|jdu ri |_|j| |S )a   Configures options for a Track.

        A convenience method to update `track.options`.

        Parameters
        ----------
        inplace : bool, optional
            Whether to modify the existing track in place or return
            a new track with the options applied (default: `False`).

        **options : dict
            Options to pass down to the underlying track object.

        Returns
        -------
        track : A track with the the newly specified track options.

        Examples
        --------
        >>> track = hg.track("heatmap")
        >>> derived = track.opts(colorRange=["rgba(255,255,255,1)", "rgba(0,0,0,1)"])
        >>> assert track.options is None
        >>> assert isinstance(derived.options["colorRange"], list)

        N)r&   r'   optionsupdate)r!   r#   r7   r   r.   r.   r/   opts[   s
   
z_OptionsMixin.optsNr1   )r!   r   r#   r$   r%   r   )r2   r3   r4   r9   r.   r.   r.   r/   r6   Z   r5   r6   c                   @  s   e Zd Z	ddd	d
ZdS )_TilesetMixinFr!   r   tilesetr   r#   r$   r%   c                 C  s(   |r| nt | }|j|_|jj|_|S )a  Replace or add a tileset to a Track.

        A convenience method to update a track with a tileset.

        Parameters
        ----------
        tileset : TilesetResource
            A tileset resource returned from `hg.server`.

        inplace : bool, optional
            Whether to modify the existing track in place or return
            a new track (default: `False`)

        Returns
        -------
        track : A track with the bound tileset.

        )r&   r'   serverr;   uid
tilesetUid)r!   r;   r#   r   r.   r.   r/   r;      s   
z_TilesetMixin.tilesetNr1   )r!   r   r;   r   r#   r$   r%   r   )r2   r3   r4   r;   r.   r.   r.   r/   r:      s    r:   c                   @     e Zd ZdZdS )r   zRepresents a generic track.Nr2   r3   r4   __doc__r.   r.   r.   r/   r          r   c                   @  r?   )r   z&Represets a specialized heatmap track.Nr@   r.   r.   r.   r/   r      rB   r   c                   @  r?   )r   z8Represents a view-independent viewport projection track.Nr@   r.   r.   r.   r/   r      s    r   c                   @  r?   )r   z-Represents a track combining multiple tracks.Nr@   r.   r.   r.   r/   r      rB   r   c                   @     e Zd ZU dZded< dS )r   z#Represents an unknown plugin track.zClassVar[str]
plugin_urlNr2   r3   r4   rA   __annotations__r.   r.   r.   r/   r      s   
 r   r   )boundc                   @  sh   e Zd ZdZ			dd d	d
Zd!ddZd!ddZdd Zdd Zd"ddZ	dd Z
		d#d$ddZdS )%r   z?Represets a HiGlass View that is generic over the inner tracks.NFxhgs.Domain | Noneyr#   r$   c                 C  s2   |r| nt | }|dur||_|dur||_|S )aE  Configures the view x and/or y domain(s).

        Parameters
        ----------
        x : tuple[float, float], optional
            The x domain for the view (default: `None`)

        y : tuple[float, float], optional
            The y domain for the view (default: `None`)

        inplace : bool, optional
            Whether to modify this view inplace. If `False` (default),
            a new view is created and returned with the domains
            applied (default: `False`)

        Returns
        -------
        view : a View with the updated x & y domains

        N)r&   r'   ZinitialXDomainZinitialYDomain)r!   rH   rJ   r#   r   r.   r.   r/   domain   s   zView.domainotherView[TrackT] | Viewconf[TrackT]c                 C  
   t | |S a8  Horizontally concatenate with another view or viewconf.

        A convenience method for `hg.hconcat`.

        Parameters
        ----------
        other : View | Viewconf
            The other view or viewconf to combine with.

        Returns
        -------
        viewconf : A combined Viewconf

        r   r!   rL   r.   r.   r/   __or__      
zView.__or__c                 C  rN   )a"  Vertically concatenate two Views.

        A convenience method for `hg.vconcat`.

        Parameters
        ----------
        other : View | Viewconf
            The other view or viewconf to combine with.

        Returns
        -------
        viewconf : A combined Viewconf

        r   rQ   r.   r.   r/   __truediv__  rS   zView.__truediv__c                 C  s
   t | S )zClone the the View instance.

        Inserts a unique uuid so the view can be uniquely identified in the front end.

        Returns
        -------
        view : A copy of the original view with a new uuid

        )r&   r'   )r!   r.   r.   r/   clone  s   

z
View.clonec                 K  s   t t dd| gi|S )zConsumes the current View into a top-level view config.

        Returns
        -------
        viewconf : A top-level HiGlass Viewconf.

        viewsNr.   )r   r   r!   kwargsr.   r.   r/   viewconf!  s   zView.viewconfc                 C  s   |   ||S )z. "Displays the view in an IPython environment.)rZ   _repr_mimebundle_)r!   includeexcluder.   r.   r/   r[   +  s   zView._repr_mimebundle_c                 K  s   |   jdi |S )zCreate a Jupyter Widget display for this view.

        Casts the view into a top-level view config which can be displayed.

        Returns
        -------
        widget : A HiGlassWidget instance
        Nr.   )rZ   widgetrX   r.   r.   r/   r^   /  s   	zView.widgetcenterr   on3Literal['center', 'top', 'bottom', 'left', 'right']c                 K  s   |r| nt | }|dkrd}n|dks|dkrd}n|dks#|dkr&d}ntd	t|j|d
u r9t|j|g  td||jd|}t|j|| |S )a  Project a different viewport onto this view.

        Creates a viewport-projection track whos bounds are synchonrized
        with an existing, separate view.

        Parameters
        ----------
        view : View
            The view with the desired viewport to project.

        on : Literal["center", "top", "bottom", "left", "right"], optional
            Where to project the viewport on this view (default: "center").

        inplace : bool
            Whether to modify this view inplace, or alternatively return
            a new view (default: `False`).

        **kwargs : dict
            Additional parameters for the created viewport-projection track.

        Returns
        -------
        view : A view with a new viewport-projection track.
        r_   zviewport-projection-centertopbottomzviewport-projection-horizontalleftrightzviewport-projection-verticalzNot possibleN)type_ZfromViewUidr.   )	r&   r'   
ValueErrorgetattrtracksr)   r   r=   append)r!   r   r`   r#   rY   Znew_viewZ
track_typeZtrkr.   r.   r/   project:  s   zView.project)NNF)rH   rI   rJ   rI   r#   r$   )rL   rM   NN)r_   F)r   r   r`   ra   r#   r$   )r2   r3   r4   rA   rK   rR   rU   rV   rZ   r[   r^   rk   r.   r.   r.   r/   r      s    
!


r   r   rW   list[ViewT]r%   	list[str]c                 C  s@   i }| D ]}|j D ]\}}t|tr|j||j< q	qt| S )z;Inspect tracks and extract plugin urls to inject into HTML.)ri   
isinstancer   rD   typelistvalues)rW   plugin_urlsr   _r   r.   r.   r/   gather_plugin_urlsq  s   
ru   c                   @  sZ   e Zd ZdZd ddZdd Zed!d	d
Zdddddd"ddZd#ddZ	d#ddZ
dS )$r   zGRepresents a top-level viewconfig, or a complete HiGlass visualization.Nc                 C  s2   t j }| jdu rg nt| j}||  |dS )z5 "Displays the view config in an IPython environment.N)rs   )displayZ	renderersgetrW   ru   dict)r!   r\   r]   rendererrs   r.   r.   r/   r[   ~  s   
zViewconf._repr_mimebundle_c                 K  s    ddl m} ||  fi |S )z5Create a Jupyter Widget display for this view config.r   )HiGlassWidget)Zhiglass._widgetrz   rx   )r!   rY   rz   r.   r.   r/   r^     s   zViewconf.widgeturlstrc                 K  sZ   ddl m} |j|fi |}||}| }W d   n1 s#w   Y  | |S )ac  Load a viewconf via URL and construct a Viewconf.

        Makes an HTTP request.

        Parameters
        ----------
        url : str
            The URL for a JSON HiGlass view config.

        **kwargs : dict
            Options for the `urllib.Request` instance.

        Returns
        -------
        viewconf : The parsed view config

        r   N)urllib.requestrequestRequesturlopenreadZ	parse_raw)clsr{   rY   urllibr~   responserawr.   r.   r/   from_url  s   

zViewconf.from_urlF)zoomlocationvalue_scaler#   lockshgs.Lock | hgs.ValueScaleLockr    list[hgs.Lock] | hgs.Lock | Noner   r   4list[hgs.ValueScaleLock] | hgs.ValueScaleLock | Noner#   r$   c                G  s  |r| nt | }t |}t |}t |}g }|D ]}t|tjr*|| q|| q|| || |jdu rDt	 |_|D ]}t|j
tsPJ ||jj|j
< |D ]\}	}
|j
|jj|	< qYqF|jdu rpt |_|D ]}t|j
ts|J ||jj|j
< |D ]\}	}
|j
|jj|	< qqr|jdu rt |_|D ]}t|j
tsJ ||jj|j
< |D ]\}	}
|j
|jj|	< qq|S )a  Specify view locks.

        Parameters
        ----------

        *locks : hgs.Lock | hgs.ValueScaleLock, optional
            A set of either zoom/location or value scale locks to add. Instances
            of `hgs.Lock` will synchronize _both_ zoom and location for the views
            included in the lock. If you'd like to synchronize just zoom or location,
            use the explicit keyword arguments below.

        zoom : hgs.Lock | list[hgs.Lock], optional
            A lock or set of locks to synchronize only the zoom.

        location : hgs.Lock | list[hgs.Lock], optional
            A lock or set of locks to synchronize only the location.

        value_scale : hgs.ValueScaleLock | list[hgs.ValueScaleLock], optional
            A single or set of value-scale locks.

        inplace : bool, optional
            Whether to modify the viewconf in place or return a new viewconf
            with the locks applied (default: `False`)

        Returns
        -------

        viewconf : A Viewconf with the synchronized views.


        Examples
        --------

        >>> view1 = hg.view(hg.track("heatmap"))
        >>> view2 = hg.view(hg.track("heatmap"))
        >>> # create an abstract lock for two views
        >>> view_lock = hg.lock(view1, view2)
        >>> # lock location & zoom
        >>> (view1 | view2).lock(view_lock)
        >>> # lock only zoom
        >>> (view1 | view2).lock(zoom=view_lock)
        >>> # lock only location
        >>> (view1 | view2).lock(location=view_lock)

        N)r&   r'   Zensure_listro   hgsLockrj   extend	zoomLocksZ	ZoomLocksr=   r|   	locksDictlocksByViewUidlocationLocksZLocationLocksvalueScaleLocksZValueScaleLocks)r!   r   r   r   r#   r   confZshared_locksr   Zvuidrt   r.   r.   r/   r     sH   5










zViewconf.locksrL   rM   r%   Viewconf[TrackT]c                 C  rN   rO   rP   rQ   r.   r.   r/   rR     rS   zViewconf.__or__c                 C  rN   )a6  Vertically concatenate with another view or viewconf.

        A convenience method for `hg.hconcat`.

        Parameters
        ----------
        other : View | Viewconf
            The other view or viewconf to combine with.

        Returns
        -------
        viewconf : A combined Viewconf

        rT   rQ   r.   r.   r/   rU     rS   zViewconf.__truediv__rl   )r{   r|   )
r   r   r   r   r   r   r   r   r#   r$   )rL   rM   r%   r   )r2   r3   r4   rA   r[   r^   classmethodr   r   rR   rU   r.   r.   r.   r/   r   {  s    

br   TrackTATrackTBmethod!Literal['horizontal', 'vertical']a!View[TrackTA] | Viewconf[TrackTA]b!View[TrackTB] | Viewconf[TrackTB]Viewconf[TrackTA | TrackTB]c                 C  sX  t |tr	| n|}|jdusJ t |tr| n|}|jdus$J | dkr/dd }d}n| dkr:dd }d}ntd	d
d |jD }|jdu rMdntt||j}|D ]}t|j|}t	|j|||  qW|j
| dD ]/}	t||	}
|
rt||	du rt	||	|
jdd qqt||	j|
j t||	j|
j qqtttttf  |S )a  Concatenate two views or separate viewconfs together.

    Uses the layout of one view or the total bounds of all views in one
    viewconf to offset the other view/viewconf.

    Parameters
    ----------
    method : Literal["horizontal", "vertical"]
        How to concatenate views/viewconfs.

    a : View | Viewconf
        A view or viewconf to combine.

    b : View | Viewconf
        The other view or viewconf to combine.

    Returns
    -------
    viewconf : A combined viewconf containing multiple views.

    Nverticalc                 S     | j j| j j S N)layoutrJ   hr   r.   r.   r/   mapperP     zconcat.<locals>.mapperrJ   
horizontalc                 S  r   r   )r   rH   wr   r.   r.   r/   r   V  r   rH   z1concat method must be 'vertical' or 'horizontal'.c                 S  s   g | ]}|j d dqS )Tdeep)copy).0r-   r.   r.   r/   
<listcomp>^  s    zconcat.<locals>.<listcomp>r   )r   r   r   Tr   )ro   r   rZ   rW   rg   maxmaprh   r   r)   r   r   r   r8   r   r
   r   r	   r   r   )r   r   r   r   fieldrW   offsetr   currZlockattrr   r.   r.   r/   r   .  s4   
r   r   r   c                   @  rC   )_TrackCreatora  Create track instances from their track type.

    Used internally by `hg.track` to leverage pydantic's ability to get
    the appropriate base model by the track type.

    Example:
    -------
    >>> assert isinstance(_TrackCreator(type="heatmap").__root__, HeatmapTrack)
    Track__root__NrE   r.   r.   r.   r/   r   }  s   
 
r   rf   hgs.EnumTrackTyper=   
str | Nonec                 K     d S r   r.   rf   r=   rY   r.   r.   r/   r        r   Literal['heatmap']c                 K  r   r   r.   r   r.   r.   r/   r     r   r|   c                 K  r   r   r.   r   r.   r.   r/   r     r   ,hgs.EnumTrackType | Literal['heatmap'] | strr   c                 K  s0   |du rt  }td| |d|}t|jS )ai  Create a HiGlass track.

    Parameters
    ----------
    type_ : str
        The track type to create

    uid: str, optional
        A unique id for the track. If unspecified (default), a unique id is given
        internally.

    **kwargs: dict
        Other top-level track properties.

    Returns
    -------
    track :  An instance of an hg.Track
    N)rp   r=   r.   )r&   r=   rx   r   Z	parse_objr   )rf   r=   rY   datar.   r.   r/   r     s         )rH   rJ   widthheightri   r   r=   _tracks@TrackT | tuple[TrackT, utils.TrackPosition] | hgs.Tracks[TrackT]rH   intrJ   r   r   ri   hgs.Tracks[TrackT] | Noner   hgs.Layout | NoneView[TrackT]c                 O  s
  |du rt j| |||d}n
t jdi | }|du r!tt}	ntt| }	|D ]=}
t|
t jrG|
 }
|
 D ]\}}|	| | q:q*t|
t	rQ|
\}
}nt
j|
j}|du r`td|	| |
 q*|du rpt
 }tt d|t jt di |	|d|S )aH  Create a HiGlass view from multiple tracks.

    Parameters
    ----------
    *_tracks : Track | tuple[Track, str] | hgs.Tracks[Track]
        The tracks to include in the view. Can be 1) separate track objects
        (position inferred), 2) explicit (Track, position) tuples, or 3.) a
        `higlass_schema.Tracks` Object specifying all tracks and positions.

    x : int, optional
        The x position of the view in the HiGlass grid (default: 0). Used to
        created a Layout if none is provided.

    y : int, optional
        The y position of the view in the HiGlass grid (default: 0). Used to
        created a Layout if none is provided.

    width : int, optional
        The width of the view (default: 12). Used to created a Layout if none is
        provided.

    height : int, optional
        The height of the view (default: 6). Used to created a Layout if none is
        provided.

    layout : hgs.Layout, optional
        An explicit layout for the view (default: None). If provided the `x`, `y`,
        `width`, and `height` parameters are ignored.

    uid: str, optional
        A unique id for the view. If unspecified (default), a unique id is automatically
        generated internally.

    **kwargs: dict
        Other top-level view properties.

    Returns
    -------
    view :  An instance of an hg.View
    N)rH   rJ   r   r   zNo default track type)r   ri   r=   r.   )r   ZLayoutrx   r   rq   ro   ZTracksr(   r   tupler&   Ztrack_default_positionrw   rp   rg   rj   r=   r   r   )rH   rJ   r   r   ri   r   r=   r   rY   r   r   positionZ
track_listr.   r.   r/   r     s6   3


r   t1t2c                 K  s   |du rt  }t| tr5tdi |  }|j|jdi |  | D ]
\}}t	||| q(|S tdd|dd | |fD d|S )a  A utility to create a CombinedTrack from two other tracks.

    Parameters
    ----------

    t1 : hg.Track
        The first of two tracks to combine.

    t2 : hg.Track
        The second of two tracks to combine.

    uid : str, optional
        A unique id for the newly created CombinedTrack.

    **kwargs : dict
        Additional properties to pass to the CombinedTrack constructor.

    Returns
    -------

    combined_track : An CombinedTrack with two children tracks.

    Ncombinedc                 S  s    g | ]}|j d i | qS )r.   )	__class__rx   r   r   r.   r.   r/   r   3  s     zcombine.<locals>.<listcomp>)rp   r=   contentsr.   )
r&   r=   ro   r   rx   r   rj   r   r(   r)   )r   r   r=   rY   r   keyvalr.   r.   r/   r     s   
r   Tc                 K  s   | j |j ks
J dt| jtsJ t| jtsJ t|jts"J t|jts*J t| }d|_d|_tjddd | |fD d|_	|
 D ]
\}}t||| qH|S )a  A utility to create a divided track.

    Tracks must the the same type.

    Parameters
    ----------

    t1 : hg.EnumTrack | hg.HeatmapTrack
        The first track to divide by the other.

    t2 : hg.EnumTrack | hg.HeatmapTrack
        The other track.

    **kwargs : dict
        Additional properties to pass to the newly created track.

    Returns
    -------

    divided_track : An identical track with "divided" data sources.

    z divided tracks must be same typeNZdividedc                 S  s   g | ]	}|j |jd qS )r>   r<   r   r   r.   r.   r/   r   ^  s    zdivide.<locals>.<listcomp>)rp   children)rp   ro   r>   r|   r<   r&   r'   r   ZDatar   r(   r)   )r   r   rY   r   r   r   r.   r.   r/   r   ;  s"   
r   r=   hgs.Lockc                 G     dS )a<  Create an abstract lock linking two or more views.

    Parameters
    ----------

    *views : View
        Two or more views to synchronize with this lock.

    uid : str, optional
        An (optional) unique id for this lock.

    Returns
    -------

    lock : An abstract lock linking two or more views.

    Nr.   )r=   rW   r.   r.   r/   r   l  s   r   )r=   ignoreOffScreenValuespairstuple[View, Track]r   bool | Nonehgs.ValueScaleLockc                 G  r   )aY  Create an abstract value-scale lock linking one or more (View, Track) pairs.

    Parameters
    ----------

    *pairs : tuple[View, Track]
        One or more (View, Track) pairs specifying a Track whos values should
        be used to scale all tracks within the View.

    uid : str, optional
        An (optional) unique id for this lock.

    ignoreOffScreenValues : bool, optional
        Whether to ignore off screen values when scaling the view.

    Returns
    -------

    lock : A value-scale lock defining how the tracks in a View should be scaled by
        by a particular track.

    Nr.   )r=   r   r   r.   r.   r/   r     s   c                 O  s   t |dksJ | du rt } t|d tr3tj| d}|D ]}t|jts)J t||jd q|S tj	d	d| i|}|D ](\}}t|jtsKJ t|jtsSJ |j d|j }t|||j|jd q?|S )
a  Create an abstract lock or value-scale lock.

    Overloaded to either return a `hgs.Lock` or `hgs.ValueScaleLock` depending on
    the arguments. See `Viewconf.locks` for how to use the created locks in
    your top-level view config.

    Examples
    --------

    Create an abstract lock linking two or more separate views.

    >>> view1 = hg.view(hg.track("heatmap"))
    >>> view2 = hg.view(hg.track("heatmap"))
    >>> lock = hg.lock(view1, view2)

    Create a value-scale lock, scaling two views by the values of a particular track.

    >>> t1 = hg.track("heatmap")
    >>> t2 = hg.track("heatmap")
    >>> view1 = hg.view(t1, t2)
    >>> view2 = hg.view(t1, t2)
    >>> value_scale_lock = hg.lock((view1, t2), (view2, t2))

       Nr   r   )r   r   r   r=   .)r   r   r.   )
lenr&   r=   ro   r   r   r   r|   r)   ZValueScaleLock)r=   r   rY   Zlckr   r   Zvtuidr.   r.   r/   r     s    )rW   rm   r%   rn   )r   r   r   r   r   r   r%   r   r   )rf   r   r=   r   r%   r   )rf   r   r=   r   r%   r   )rf   r|   r=   r   r%   r   )rf   r   r=   r   r%   r   )r   r   rH   r   rJ   r   r   r   r   r   ri   r   r   r   r=   r   r%   r   )r   r   r   r   r=   r   r%   r   )r   r   r   r   r%   r   )rW   r   r=   r   r%   r   )r   r   r=   r   r   r   r%   r   )r=   r   )7
__future__r   	functoolscollectionsr   typingr   r   r   r   r   r	   r
   r   Zhiglass_schemar   Zpydanticr   Zhiglass._display_displayrv   Zhiglass._utils_utilsr&   __all__Zhiglass.serverr   r    r6   r:   r   r   r   r   Z	BaseTrackr   r   r   r   r   ru   r   r   r   r   partialr   r   r   r   r   r   r   r   r   r.   r.   r.   r/   <module>   s    (
%&!
  
"
 0
EW*
1