o
    Rŀg*{                     @   s0  d 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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dlmZ e ZG dd de	ZG dd deZG dd deZG dd deZd"ddZd"ddZG dd deZG dd deZG dd  d eZ d!S )#a  Draw representations of organism chromosomes with added information.

These classes are meant to model the drawing of pictures of chromosomes.
This can be useful for lots of things, including displaying markers on
a chromosome (ie. for genetic mapping) and showing syteny between two
chromosomes.

The structure of these classes is intended to be a Composite, so that
it will be easy to plug in and switch different parts without
breaking the general drawing capabilities of the system. The
relationship between classes is that everything derives from
_ChromosomeComponent, which specifies the overall interface. The parts
then are related so that an Organism contains Chromosomes, and these
Chromosomes contain ChromosomeSegments. This representation differs
from the canonical composite structure in that we don't really have
'leaf' nodes here -- all components can potentially hold sub-components.

Most of the time the ChromosomeSegment class is what you'll want to
customize for specific drawing tasks.

For providing drawing capabilities, these classes use reportlab:

http://www.reportlab.com

This provides nice output in PDF, SVG and postscript.  If you have
reportlab's renderPM module installed you can also use PNG etc.
    )ArcPath)Drawing)Line)Rect)String)Wedge)Widget)colors)letter)inch)stringWidth)_write)_Colorsc                   @   s0   e Zd ZdZdd Zdd Zdd Zdd	 Zd
S )_ChromosomeComponentzBase class specifying the interface for a component of the system.

    This class should not be instantiated directly, but should be used
    from derived classes.
    c                 C   s
   g | _ dS )zInitialize a chromosome component.

        Attributes:
        - _sub_components -- Any components which are contained under
        this parent component. This attribute should be accessed through
        the add() and remove() functions.

        N)_sub_componentsself r   P/var/www/html/myenv/lib/python3.10/site-packages/Bio/Graphics/BasicChromosome.py__init__=   s   
	z_ChromosomeComponent.__init__c                 C   s(   t |tstd| | j| dS )z>Add a sub_component to the list of components under this item.z,Expected a _ChromosomeComponent object, got N)
isinstancer   	TypeErrorr   appendr   	componentr   r   r   addH   s   
z_ChromosomeComponent.addc                 C   s4   z	| j | W dS  ty   td| ddw )zRemove the specified component from the subcomponents.

        Raises a ValueError if the component is not registered as a
        sub_component.
        z
Component z not found in sub_components.N)r   remove
ValueErrorr   r   r   r   r   O   s   
z_ChromosomeComponent.removec                 C   s   t d)zDraw the specified component.zSubclasses must implement.)AssertionErrorr   r   r   r   draw\   s   z_ChromosomeComponent.drawN)__name__
__module____qualname____doc__r   r   r   r   r   r   r   r   r   6   s    r   c                   @   s2   e Zd ZdZdddZdd Zdd Zd	d
 ZdS )OrganismaX  Top level class for drawing chromosomes.

    This class holds information about an organism and all of its
    chromosomes, and provides the top level object which could be used
    for drawing a chromosome representation of an organism.

    Chromosomes should be added and removed from the Organism via the
    add and remove functions.
    pdfc                 C   s&   t |  t| _d| _d| _|| _dS )zInitialize the class.   r   N)r   r   r
   	page_size
title_size_legend_heightoutput_format)r   r*   r   r   r   r   l   s
   

zOrganism.__init__c           	      C   s   | j \}}t||}| |||| td }t| jdkr'|t t| j }n	 | jD ](}|d|  |_|d|  |_|dt  |_| j	dt  |_
|| ||7 }q+| || j	dt  | |du rf|S t||| jS )a   Draw out the information for the Organism.

        Arguments:
         - output_file -- The name of a file specifying where the
           document should be saved, or a handle to be written to.
           The output format is set when creating the Organism object.
           Alternatively, output_file=None will return the drawing using
           the low-level ReportLab objects (for further processing, such
           as adding additional graphics, before writing).
         - title -- The output title of the produced document.

              ?r   皙?ffffff?g      ?   N)r'   r   _draw_titler   lenr   start_x_positionend_x_positionstart_y_positionr)   end_y_positionr   _draw_legendr   r*   )	r   output_filetitlewidthheightcur_drawing	cur_x_posx_pos_changesub_componentr   r   r   r   z   s$   




zOrganism.drawc                 C   s6   t |d |t |}d|_| j|_d|_|| dS )z5Write out the title of the organism figure (PRIVATE).   zHelvetica-BoldmiddleN)r   r   fontNamer(   fontSize
textAnchorr   )r   r:   r7   r8   r9   title_stringr   r   r   r/      s
   zOrganism._draw_titlec                 C      dS )zDraw a legend for the figure (PRIVATE).

        Subclasses should implement this (see also self._legend_height) to
        provide specialized legends.
        Nr   )r   r:   start_yr8   r   r   r   r5          zOrganism._draw_legendN)r%   )r    r!   r"   r#   r   r   r/   r5   r   r   r   r   r$   a   s    

.	r$   c                   @   s8   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d ZdS )
ChromosomezClass for drawing a chromosome of an organism.

    This organizes the drawing of a single organisms chromosome. This
    class can be instantiated directly, but the draw method makes the
    most sense to be called in the context of an organism.
    c                 C   sV   t |  || _d| _d| _d| _d| _d| _d| _d| _	d| _
| j
d | _d| _dS )a  Initialize a Chromosome for drawing.

        Arguments:
         - chromosome_name - The label for the chromosome.

        Attributes:
         - start_x_position, end_x_position - The x positions on the page
           where the chromosome should be drawn. This allows multiple
           chromosomes to be drawn on a single page.
         - start_y_position, end_y_position - The y positions on the page
           where the chromosome should be contained.

        Configuration Attributes:
         - title_size - The size of the chromosome title.
         - scale_num - A number of scale the drawing by. This is useful if
           you want to draw multiple chromosomes of different sizes at the
           same scale. If this is not set, then the chromosome drawing will
           be scaled by the number of segments in the chromosome (so each
           chromosome will be the exact same final size).

        r&   N         ?r+   F)r   r   _namer1   r2   r3   r4   r(   	scale_num
label_sizechr_percentlabel_sep_percent_color_labels)r   chromosome_namer   r   r   r      s   

zChromosome.__init__c                 C   s   d}| j D ]}||j7 }q|S )z>Return the scaled size of all subcomponents of this component.r   )r   scale)r   	total_subr=   r   r   r   subcomponent_size   s   
zChromosome.subcomponent_sizec           	      C   s  | j | j| j| jfD ]
}|dksJ dq
| j}| jr'| jd | j | j }nt| jdkr;| jd | j |   }n	 g }g }| jD ]0}|j| }| j |_ | j|_||_|| |_g |_	g |_
|| ||j	7 }||j
7 }||8 }qC| ||| | || j dS )zDraw a chromosome on the specified template.

        Ideally, the x_position and y_*_position attributes should be
        set prior to drawing -- otherwise we're going to have some problems.
        rH    Need to set drawing coordinates.r-   r   N)r1   r2   r3   r4   rL   r0   r   rT   rR   _left_labels_right_labelsr   _draw_labels_draw_labelrK   )	r   r:   position	cur_y_posy_pos_changeleft_labelsright_labelsr=   this_y_pos_changer   r   r   r      s@   






zChromosome.drawc                 C   sD   d| j | j  }| j}t|||}d|_| j|_d|_|| dS )z*Draw a label for the chromosome (PRIVATE).r+   zTimes-BoldItalicr?   N)	r1   r2   r4   r   r@   r(   rA   rB   r   )r   r:   
label_name
x_position
y_positionlabel_stringr   r   r   rY   %  s   zChromosome._draw_labelc                 C   sz  | j sdS | j}| j| j | j }| j| j | j }| jd| j| j |   }g }| j D ]}	||	j|	jf q,t	|}
t
|}~| j}||| t||
||df|| || | t||
||dffD ]X\}}}}|D ]O\}}}}}|t|||||dd t||||d}d|_||_|r||_|rt||j|j}||kr|d	 }|t||d
|  ||||d || qjqbdS )at  Layout and draw sub-feature labels for the chromosome (PRIVATE).

        Tries to place each label at the same vertical position as the
        feature it applies to, but will adjust the positions to avoid or
        at least reduce label overlap.

        Draws the label text and a coloured line linking it to the
        location (i.e. feature) it applies to.
        Nr+   endstartrJ   )strokeColorstrokeWidth)rB   	Helveticag      g?)rf   	fillColor)r   rP   r2   r1   rN   rO   extendr3   r4   minmaxrM   _place_labelsr   r   r   r@   rA   ri   r   r   )r   r:   r]   r^   color_labelsegment_width	label_sep	segment_xy_limitsr=   y_miny_maxhx1x2labelsanchory1y2color
back_colornamerc   wr   r   r   rX   1  sp   






zChromosome._draw_labelsN)	r    r!   r"   r#   r   rT   r   rY   rX   r   r   r   r   rG      s    '5rG   c                   @   s@   e Zd ZdZdd Zdd Zdd Zdd	 Zd
d Zdd Z	dS )ChromosomeSegmentaR  Draw a segment of a chromosome.

    This class provides the important configurable functionality of drawing
    a Chromosome. Each segment has some customization available here, or can
    be subclassed to define additional functionality. Most of the interesting
    drawing stuff is likely to happen at the ChromosomeSegment level.
    c                 C   sD   t |  d| _d| _d| _d| _d| _d| _d| _d| _	d| _
dS )a  Initialize a ChromosomeSegment.

        Attributes:
         - start_x_position, end_x_position - Defines the x range we have
           to draw things in.
         - start_y_position, end_y_position - Defines the y range we have
           to draw things in.

        Configuration Attributes:
         - scale - A scaling value for the component. By default this is
           set at 1 (ie -- has the same scale as everything else). Higher
           values give more size to the component, smaller values give less.
         - fill_color - A color to fill in the segment with. Colors are
           available in reportlab.lib.colors
         - label - A label to place on the chromosome segment. This should
           be a text string specifying what is to be included in the label.
         - label_size - The size of the label.
         - chr_percent - The percentage of area that the chromosome
           segment takes up.

        rH   r.   NrI   rJ   )r   r   r1   r2   r3   r4   rR   
fill_colorlabelrM   rN   r   r   r   r   r     s   

zChromosomeSegment.__init__c                 C   sV   | j | j| j| jfD ]
}|dksJ dq
| | | | | | | | dS )ziDraw a chromosome segment.

        Before drawing, the range we are drawing in needs to be set.
        rH   rU   N)r1   r2   r3   r4   _draw_subcomponents_draw_segment_overdraw_subcomponentsrY   )r   r:   rZ   r   r   r   r     s   


zChromosomeSegment.drawc                 C   rD   )zDraw any subcomponents of the chromosome segment (PRIVATE).

        This should be overridden in derived classes if there are
        subcomponents to be drawn.
        Nr   r   r:   r   r   r   r     rF   z%ChromosomeSegment._draw_subcomponentsc           	      C   s   | j }| j| j | j }| j| j  }| jd| j| j |   }t||||| }t|| ||| || }|| || | jdurYt||||}| j|_	d|_
|| dS dS )z.Draw the current chromosome segment (PRIVATE).r+   N)r4   r2   r1   rN   r3   r   r   r   r   ri   rf   )	r   r:   	segment_yro   segment_heightrq   
right_line	left_linefill_rectangler   r   r   r     s*   


zChromosomeSegment._draw_segmentc                 C   rD   )zDraw any subcomponents of the chromosome segment over the main part (PRIVATE).

        This should be overridden in derived classes if there are
        subcomponents to be drawn.
        Nr   r   r   r   r   r     rF   z)ChromosomeSegment._overdraw_subcomponentsc                 C   st   | j dur8d| j| j  | jd | j| j   }| j| j d | j }t||| j }d|_| j|_	|
| dS dS )zAdd a label to the chromosome segment (PRIVATE).

        The label will be applied to the right of the segment.

        This may be overlapped by any sub-feature labels on other segments!
        Nr+   r,   r>   rh   )r   r1   r2   rN   r3   r4   r   r@   rM   rA   r   )r   r:   label_xlabel_yrc   r   r   r   rY     s   


zChromosomeSegment._draw_labelN)
r    r!   r"   r#   r   r   r   r   r   rY   r   r   r   r   r   |  s    $r   c                    s  t | }|dkr
| S |krtddd|dt| k s&t| |kr4tdt| t| |f | |d    k r\ddl}ddlm} |d	|  fd
dt|D S d}rw| d }| dd D ]}	||	 k rvd} nqj|r{| S | }
d|
 |
d d|
 d d|
 d|
 fD ]}| fdd| D fdd| D }t t | |k rqst | |
| d  krt	|d  |  S |st  |d  krt	d    S t  |d  kr#t | |
| d  kr#t	d  t	|d  |   S qt| t| }| |d  krK| |d    fddt|D S dt|   dt| |  }| |d  krz| |d    fddt|D S  fddt|D S )a  Try to layout label coordinates or other floats (PRIVATE).

    Originally written for the y-axis vertical positioning of labels on a
    chromosome diagram (where the minimum gap between y-axis coordinates is
    the label height), it could also potentially be used for x-axis placement,
    or indeed radial placement for circular chromosomes within GenomeDiagram.

    In essence this is an optimisation problem, balancing the desire to have
    each label as close as possible to its data point, but also to spread out
    the labels to avoid overlaps. This could be described with a cost function
    (modelling the label distance from the desired placement, and the inter-
    label separations as springs) and solved as a multi-variable minimization
    problem - perhaps with NumPy or SciPy.

    For now however, the implementation is a somewhat crude ad hoc algorithm.

    NOTE - This expects the input data to have been sorted!
    r.   zBad min/max fz and z&Data %f to %f out of bounds (%f to %f)r   N)BiopythonWarningz Too many labels to avoid overlapc                       g | ]}|   qS r   r   .0i
equal_stepminimumr   r   
<listcomp>$      z"_spring_layout.<locals>.<listcomp>TFr+   g      @r>   rJ   g      ?c                    s    g | ]}|d    kr|qS r+   r   r   xgapmidpointr   r   r   3       c                    s    g | ]}|d    kr|qS r   r   r   r   r   r   r   4  r   c                    r   r   r   r   r   lowr   r   r   O  r   c                    r   r   r   r   r   r   r   r   V  r   c                    r   r   r   r   r   r   r   r   Y  r   )
r0   r   rk   rl   warningsBior   warnrange_spring_layout)desiredr   maximumr   countr   r   goodprevnextspansplithighr   )r   r   r   r   r   r   r     sr   * r   c                 c   sX    |    tdd | D |||}t| |D ]\}}|d |ft|dd   V  qd S )Nc                 S   s   g | ]}|d  qS r   r   )r   rowr   r   r   r   g  s    z!_place_labels.<locals>.<listcomp>r   r.   )sortr   ziptuple)desired_etcr   r   r   placedoldr{   r   r   r   rm   d  s    rm   c                   @   s(   e Zd ZdZejdfddZdd ZdS )AnnotatedChromosomeSegmentzkAnnotated chromosome segment.

    This is like the ChromosomeSegment, but accepts a list of features.
    )gener   r~   	locus_tagproductc                 C   s2   t |  || _|| _|| _|| _| jd | _dS )a  Initialize.

        The features can either be SeqFeature objects, or tuples of values:
        start (int), end (int), strand (+1, -1, O or None), label (string),
        ReportLab color (string or object), and optional ReportLab fill color.

        Note we require 0 <= start <= end <= bp_length, and within the vertical
        space allocated to this segment lines will be places according to the
        start/end coordinates (starting from the top).

        Positive stand features are drawn on the right, negative on the left,
        otherwise all the way across.

        We recommend using consistent units for all the segment's scale values
        (e.g. their length in base pairs).

        When providing features as SeqFeature objects, the default color
        is used, unless the feature's qualifiers include an Artemis colour
        string (functionality also in GenomeDiagram). The caption also follows
        the GenomeDiagram approach and takes the first qualifier from the list
        or tuple specified in name_qualifiers.

        Note additional attribute label_sep_percent controls the percentage of
        area that the chromosome segment takes up, by default half of the
        chr_percent attribute (half of 25%, thus 12.5%)

        r+   N)r   r   	bp_lengthfeaturesdefault_feature_colorname_qualifiersrN   rO   )r   r   r   r   r   r   r   r   r   s  s   
"z#AnnotatedChromosomeSegment.__init__c              	   C   s4  | j }| j| j | j }| j| j | j }| j| j  }| jd| j| j |   }g }g }| jD ]}	z?|	jj}
|	jj	}|	jj
}zt|	jd d }W n tyV   | j}Y nw |}d}| jD ]}||	jv rn|	j| d } nq^W n) ty   |	dd \}
}}}}t|}t|	dkrt|	d }n|}Y nw d|
  kr|  kr| jksJ  J |dkr||d  }|d	 }n|d
kr|}|d	 }n|}|}|| j }t||| ||
  |||
|  }||_||_|| |r||krd}n|}|| ||
  |||f}|d
kr| j| q/| j| q/dS )zDraw any annotated features on the chromosome segment (PRIVATE).

        Assumes _draw_segment already called to fill out the basic shape,
        and assmes that uses the same boundaries.
        r+   r|   r    N   r.   g333333?g?rH   )r4   r2   r1   rN   rO   r3   r   locationre   rd   strand_color_trans	translate
qualifiers	Exceptionr   r   AttributeErrorr0   r   r   ri   rf   r   rV   r   rW   )r   r:   r   ro   rp   r   rq   r]   r^   r   re   rd   r   r|   r   r~   	qualifierr   r   local_scaler   r}   valuer   r   r   r     s   





(





z2AnnotatedChromosomeSegment._overdraw_subcomponentsN)r    r!   r"   r#   r	   bluer   r   r   r   r   r   r   m  s    	
)r   c                   @   s"   e Zd ZdZdddZdd ZdS )	TelomereSegmenta)  A segment that is located at the end of a linear chromosome.

    This is just like a regular segment, but it draws the end of a chromosome
    which is represented by a half circle. This just overrides the
    _draw_segment class of ChromosomeSegment to provide that specialized
    drawing.
    r   c                 C   s   t |  || _dS )a8  Initialize a segment at the end of a chromosome.

        See ChromosomeSegment for all of the attributes that can be
        customized in a TelomereSegments.

        Arguments:
         - inverted -- Whether or not the telomere should be inverted
           (ie. drawn on the bottom of a chromosome)

        N)r   r   	_inverted)r   invertedr   r   r   r     s   

zTelomereSegment.__init__c                 C   s   | j | j | j }| j| j }d| j | j  }|d|  }| jr(| j}d}d}n| j}d}d}t|||d |||}	d|	_| j|	_	|
|	 t }
|
|||d ||| |
|
 dS )zIDraw a half circle representing the end of a linear chromosome (PRIVATE).r+      ih  r   r>   N)r2   r1   rN   r3   r4   r   r   rf   r   ri   r   r   addArc)r   r:   r8   r9   center_xstart_xcenter_ystart_angle	end_angle	cap_wedgecap_arcr   r   r   r   	  s$   
zTelomereSegment._draw_segmentNr   )r    r!   r"   r#   r   r   r   r   r   r   r     s    
r   c                   @   s   e Zd ZdZdd ZdS )SpacerSegmentzA segment that is located at the end of a linear chromosome.

    Doesn't draw anything, just empty space which can be helpful
    for layout purposes (e.g. making room for feature labels).
    c                 C   rD   )zDraw nothing to the current diagram (dummy method).

        The segment spacer has no actual image in the diagram,
        so this method therefore does nothing, but is defined
        to match the expected API of the other segment objects.
        Nr   )r   cur_diagramr   r   r   r   -  rF   zSpacerSegment.drawN)r    r!   r"   r#   r   r   r   r   r   r   &  s    r   Nr   )!r#   reportlab.graphics.shapesr   r   r   r   r   r   reportlab.graphics.widgetbaser   reportlab.libr	   reportlab.lib.pagesizesr
   reportlab.lib.unitsr   reportlab.pdfbase.pdfmetricsr   Bio.Graphicsr   Bio.Graphics.GenomeDiagramr   ColorTranslatorr   r   r$   rG   r   r   rm   r   r   r   r   r   r   r   <module>   s6   +X D 

f	 5