
    DUfg[                    <   d Z ddlmZ ddlZddlZddlZddlmZ ddlZ	ddl
ZdgZ e	j        e	j                  j        Ze	j        e	j        e	j        eedZg dZdd	d	dd
dd	d	dd	dddZddddddddZi ZdJdZ ed          dKd            Z ed          	 dLdMd            Z ed          	 dLdMd            Z ed           dKd!            Z ed"          dKd#            Z ed$          dKd%            Z ed&          dKd'            Z  ed(          dKd)            Z! ed*          dKd+            Z" ed,          dKd-            Z# ed.          dKd/            Z$ ed0          dKd1            Z%	 	 dNdOd8Z&dKd9Z'dPd;Z(dQd=Z)	 dLd>d?d2dd2d?d@dAdRdIZ*dS )Sa  Validate a BED dataframe against the BED specification.

The BED specification is defined here: https://github.com/samtools/hts-specs/blob/master/BEDv1.pdf

Some facts
----------
* Intervals are 0-based, half-open
* Fields use 7-bit printable ASCII, including spaces but excluding tabs,
  newlines and other control characters
* Flavors: BED{3,4,5,6,7,8,9,12}+m: m corresponds to custom fields, you
  can also do BEDn+ for an unspecified number of custom fields
* First 3 fields are mandatory, last 9 are optional
* BED10 and BED11 are illegal
* Order is "binding": if an optional field is filled then all previous ones
  must also be filled
* Standard BED fields can never be empty - must use a special null or
  "uninformative" placeholder value
* Custom BED fields can be empty when a single tab is used as delimiter

Delimiters
----------
While the BED spec allows for the use of either spaces or tabs as delimiters,
even permitting a mixture in the same file, we do not validate any of the
whitespace constraints imposed on fields in the spec to deal with the
possibility of either space or mixed whitespace delimiters in the file. We
assume that the dataframe will be written using a single tab as the sole
delimiter, as recommended.

Information we are agnostic to:
- The delimiter used in the file before it was parsed: we work with files that
  have already been parsed into a dataframe.
- Comment lines and blank lines: we assume that the dataframe contains only
  data lines.
- Custom field names, dtypes, and values.

Information supplied out-of-band:
- Assembly/chromsizes: a dictionary or pandas Series mapping chromosome names
  to lengths [optional].
- Custom fields in positions 4-12: which of the first 4 to 12 fields are
  provided as standard BED fields and which are custom fields.

Note that the spec is overly strict. For example, many BED files in the wild
will use "." as the uninformative score value for all features, but the spec
requires that the score be an integer between 0-1000. We provide some lenience
by allowing floats as well, which many tools use in practice. The spec defines
the uninformative score value as 0.

We also don't enforce limiting name fields to 7-bit printable ascii.
    )annotationsN)Callableto_bed)IntegerUnsignedFloat	CharacterString)chromstartendnamescorestrand
thickStartthickEnditemRgb
blockCount
blockSizesblockStartsOUiuiufiOU_.0)r   r   r   r   r   r   r   colstrreturnr   c                     d fd}|S )Nfuncr   r    c                    | t           <   | S N)BED_FIELD_VALIDATORS)r"   r   s    L/var/www/html/software/conda/lib/python3.11/site-packages/bioframe/io/bed.py	decoratorzvalidator.<locals>.decoratorw   s    $(S!    )r"   r   r    r    )r   r'   s   ` r&   	validatorr*   v   s)          r(   r   dfpd.DataFrame
dict[bool]c                    | d         j                             d                                          }| d         j                                         }|dk    |dk    z                                  }||dS )z
    Validate the chromosome names of a BED dataframe.

    The chrom column is limited to non-whitespace word characters only
    (alphanumeric characters and underscores). Each name must be between 1 and
    255 characters in length, inclusive.
    r   z^[A-Za-z0-9_]+$      )zchrom.is_alnumzchrom.is_len_ok)r   matchalllen)r+   is_alnumlengths	is_len_oks       r&   check_chromr7   ~   sx     '{$$%788<<>>H ko!!##GQ,7c>27799I #$  r(   r   
chromsizesdict | pd.Series | Nonec                   | d         dk                                     }| d         t          k                                     }||d}|Ct          j        |          }| d         || d                  k                                      }||d<   |S )at  
    Validate the start coordinates of a BED dataframe.

    Start must be an integer greater than or equal to 0 and less than or equal
    to the total number of bases of the chromosome to which it belongs.

    If the size of the chromosome is unknown, then start must be less than or
    equal to 2**64 - 1, which is the maximum size of an unsigned 64-bit integer.
    r   r   )zstart.is_nonnegzstart.is_le_64Nr   r   zstart.is_lt_chromr2   
UINT64_MAXpdSeries)r+   r8   	is_nonnegis_le_64outis_lt_chroms         r&   check_startrC      s     G!&&((I 7z)..00H %" C Yz**
%y:bk#::??AA#. Jr(   r   c                f   | d         dk                                     }| d         t          k                                     }| d         | d         k                                     }|||d}|Ct          j        |          }| d         || d                  k                                     }||d<   |S )az  
    Validate the end coordinates of a BED dataframe.

    End must be an integer greater than or equal to the value of start and
    less than or equal to the total number of bases in the chromosome to
    which it belongs.

    If the size of the chromosome is unknown, then end must be less than or
    equal to 2**64 - 1, the maximum size of an unsigned 64-bit integer.
    r   r   r   )zend.is_nonnegzend.is_le_64zend.is_end_ge_startNr   zend.is_le_chromr;   )r+   r8   r?   r@   is_end_ge_startrA   is_le_chroms          r&   	check_endrG      s     Ea$$&&I 5	Z',,..H%yBwK/4466O # . C Yz**
%yJr'{$;;@@BB!,Jr(   r   c                    | d         j                                         }|dk    |dk    z                                  }d|iS )z
    Validate the name column of a BED dataframe.

    Name must be 1 to 255 non-tab characters. Multiple data lines may share
    the same name. If all features have uninformative names, dot (.) may be
    used as a name on every data line.
    r   r/   r0   zname.is_len_ok)r   r3   r2   )r+   r5   r6   s      r&   
check_namerI      sJ     jn  ""GQ,7c>27799I 	) r(   r   c                `    | d         dk    | d         dk    z                                   }d|iS )aC  
    Validate the score column of a BED dataframe.

    Integer between 0 and 1000, inclusive. When all features have uninformative
    scores, 0 should be used as the score on every data line.

    Note: Using "." is illegal in the spec, but is used in practice. 0 is the
    the uninformative score used in the spec.
    r   r   i  zscore.is_in_ranger2   )r+   is_in_ranges     r&   check_scorerM      s=     wK1$G)<=BBDDK 	[ r(   r   c                n    | d         j                             d                                          }d|iS )z
    Validate the strand column of a BED dataframe.

    Strand must be one of +, -, . (no strand), or ? (unknown strand).
    When parsing files that are not BED6+, strand should be treated as ".".
    r   z	^[+\-.?]$zstrand.is_pattern_ok)r   r1   r2   )r+   is_pattern_oks     r&   check_strandrP      s;     xL$**<88<<>>M 	 r(   r   c                    | d         | d         k                                     }| d         | d         k                                     }||dS )z
    Validate the thickStart column of a BED dataframe.

    Must be an integer between start and end, inclusive. When all features
    have uninformative thickStarts, the value of start should be used.
    r   r   r   )zthickStart.is_ge_startzthickStart.is_le_endrK   r+   is_ge_start	is_le_ends      r&   check_thickStartrU     sY     l#r'{27799KL!RY.3355I #. )  r(   r   c                    | d         | d         k                                     }| d         | d         k                                     }||dS )z
    Validate the thickEnd column of a BED dataframe.

    Must be an integer greater than or equal to start and less than or equal
    to end, inclusive. When all features have uninformative thickEnds, the
    value of end should be used.
    r   r   r   )zthickEnd.is_ge_startzthickEnd.is_le_endrK   rR   s      r&   check_thickEndrW   "  sW     j>R[05577KJ2e9,1133I !,'  r(   r   c                   | d                              t                    j                            d          | d                              t                    dk    z                                  }| d                              t                    j                            d                              d                                           }||dS )a9  
    Validate the itemRgb column of a BED dataframe.

    A triple of 3 integers separated by commas. Each integer is between 0 and
    255, inclusive. To make a feature black, itemRgb may be a single 0, as a
    shorthand for 0,0,0. When all features have uninformative itemRgb values,
    0 should be used.
    r   z^(\d{1,3},){2}\d{1,3}$r   ,c                4    t          d | D                       S )Nc                Z    g | ](}t          |          d k    ot          |          dk    )S )r   r0   int.0is     r&   
<listcomp>z3check_itemRgb.<locals>.<lambda>.<locals>.<listcomp>K  s1    GGGc!ffk;c!ffmGGGr(   rK   xs    r&   <lambda>zcheck_itemRgb.<locals>.<lambda>K  s    GGQGGGHH r(   )zitemRgb.is_pattern_okzitemRgb.is_in_range)astyper   r1   r2   splitapply)r+   rO   rL   s      r&   check_itemRgbrh   6  s     	9S!!%++,EFFi=$$+	-	cee  	9S!!	UU3ZZ	HH	I	I	cee	  "/*  r(   r   c                F    | d         dk                                     }d|iS )z
    Validate the blockCount column of a BED dataframe.

    Must be an integer greater than 0.

    Note: mandatory in BED12+ files.
    r   r   zblockCount.is_gt_0rK   )r+   is_gt_0s     r&   check_blockCountrk   T  s0     ,!#((**G 	g r(   r   c                "   | d         j                             d                                          }| d         j                             d          j                             d          dz   }|| d         k                                    }||dS )a/  
    Validate the blockSizes column of a BED dataframe.

    Comma-separated list of length blockCount containing the size of each
    block. There must be no spaces before or after commas.

    There may be a trailing comma after the last element of the list.

    Note: mandatory in BED12+ files.
    r   ^(\d+,)*\d+(,)?$rY   r/   r   )zblockSizes.is_pattern_okzblockSizes.is_n_blocks_ok)r   r1   r2   rstripcount)r+   rO   n_blocksis_n_blocks_oks       r&   check_blockSizesrr   e  s     |$(../BCCGGIIM ,#**3//399#>>BH"\"227799N %2%3  r(   r   c                z   | d         j                             d                                          }| d         j                             d          j                             d                              d           }| d         j                             d          j                             d                              d           }t          j        ||| d         | d         gd	
          }|                    t                    | d         k                                    }|                    d d	
                                          }|                    d d	
                                          }|                    d d	
                                          }|                    d                                           }	d}
t          |j
        |j
                  D ]I\  }}t          t          |          d	z
            D ]$}||         ||         z   ||d	z            k    rd}
 n%J||||||	|
dS )ap  
    Validate the blockStarts column of a BED dataframe.

    Comma-separated list of length blockCount containing each block's start
    position, relative to start. There must not be spaces before or after the
    commas. There may be a trailing comma after the last element of the list.
    Each element in blockStarts is paired with the corresponding element in
    blockSizes.

    Each blockStarts element must be an integer between 0 and end - start,
    inclusive.

    Each block must be contained within the feature. That means that for each
    couple i of (blockStart, blockSize), the quantity start +
    blockStart + blockSize must be less or equal to end.

    The first block must start at start and the last block must end at end.

    The blockStarts must be sorted in ascending order.

    The blocks must not overlap.

    Note: mandatory in BED12+ files.
    r   rm   rY   c                    d | D             S )Nc                ,    g | ]}t          |          S r)   r\   r^   s     r&   ra   z7check_blockStarts.<locals>.<lambda>.<locals>.<listcomp>      ,,,Q#a&&,,,r(   r)   rb   s    r&   rd   z#check_blockStarts.<locals>.<lambda>      ,,!,,, r(   r   c                    d | D             S )Nc                ,    g | ]}t          |          S r)   r\   r^   s     r&   ra   z7check_blockStarts.<locals>.<lambda>.<locals>.<listcomp>  rv   r(   r)   rb   s    r&   rd   z#check_blockStarts.<locals>.<lambda>  rw   r(   r   r   r/   )axisr   c           	     z     t           fdt          t           d                             D                       S )Nc                d    g | ],}d          |         dk    od          |         d         k    -S )r   r   r   r)   )r_   r`   rc   s     r&   ra   z7check_blockStarts.<locals>.<lambda>.<locals>.<listcomp>  sP        - #q(LQ}-=a-@AeH-L  r(   r   )r2   ranger3   rb   s   `r&   rd   z#check_blockStarts.<locals>.<lambda>  sL    #   s1]#34455  
 
 r(   c                &    | d         d         dk    S )Nr   r   r)   rb   s    r&   rd   z#check_blockStarts.<locals>.<lambda>  s    1]#A&!+ r(   c                b    | d         d         | d         d         z   | d         | d         z
  k    S )Nr   r   r   r   r)   rb   s    r&   rd   z#check_blockStarts.<locals>.<lambda>  s0    1]#B'!L/"*==5AgJAVV r(   c                (    | t          |           k    S r$   )sortedrb   s    r&   rd   z#check_blockStarts.<locals>.<lambda>  s    Q&))^ r(   TF)zblockStarts.is_pattern_okzblockStarts.is_n_blocks_okzblockStarts.is_in_rangez blockStarts.is_first_block_startzblockStarts.is_last_block_endzblockStarts.is_sortedzblockStarts.is_no_overlap)r   r1   r2   rn   rf   rg   r=   concatr3   zipvaluesr}   )r+   rO   block_startsblock_sizesbs_start_endrq   rL   is_first_block_startis_last_block_end	is_sortedis_no_overlaprow_block_startsrow_block_sizesr`   s                 r&   check_blockStartsr   ~  sm   6 }%)//0CDDHHJJM 	=	VVC[[	UU3ZZ	,,	-	-	  	<	VVC[[	UU3ZZ	,,	-	-	  9	{BwKE;!  L
 #((--L1AAFFHHN $$	
 	
  %   
cee  (--	+	+1 .  	cee 
 %**	V	V +   
cee  ""#;#;<<@@BBI M-0[/. .  )/ s+,,q011 	 	A"_Q%77:J1q5:QQQ % R
 &3&4#.,@):!*%2  r(   Ffields	list[str]strict_scorebool#tuple[set[str], set[str], set[str]]c                   t                      }|D ]E}| |         j        j        }|r	|dk    rd}nt          |         }||vr|                    |           Fi }|D ]>}||vr8|dk    r|s| |                                                                         ||<   ?t          j        |          }t          |j	        |          j
                  }	i }
|D ]e}||vr_|dk    r|s|dv r*|
                    t          |         | |                     =|
                    t          |         |                      ft          j        |
          }
t          |
j	        |
          j
                  }||	|fS )a  
    Validate the fields of a BED dataframe.

    Parameters
    ----------
    df : pd.DataFrame
        BED dataframe to validate.
    fields : list of str
        List of fields to validate.
    chromsizes : dict or Series, optional [default: None]
        Assembly/chromsizes to validate against.
    strict_score : bool, optional [default: False]
        Whether to strictly enforce the score field.

    Returns
    -------
    Sets containing: (1) names of fields having an invalid dtype, (2) names of
    fields containing at least one null value, (3) properties that failed
    validation.

    Notes
    -----
    The BED spec is overly strict. For example, many BED files in the wild will
    use "." as the uninformative score value for all features, but the spec
    requires that the score be an integer between 0-1000. We provide some
    lenience by allowing floats as well, which many tools use in practice. The
    spec defines the uninformative score value as 0.
    r   r   )r   r   )setdtypekindBED_FIELD_KINDSaddnotnullr2   r=   r>   locindexupdater%   )r+   r   r8   r   dtype_failedr   r   allowed_kindsr   notnull_failedpropsprop_faileds               r&   validate_bed_fieldsr     s   D 55L " "#w}! 	1C7NN MM+C0M}$$S!!!G 3 3l""g~~l~c7??,,0022GCLi  GgX.455NE < <l""g~~l~&&&1#6r:FFGGGG1#6r::;;;IeEei'-..K44r(   c                   t           j        dt          j        | d         j        dd         | d         j        dd         k              dz   f         }| d                                         |         }t          |          t          t          j        |                    k    }d}|                     dd          D ]\  }}|d	                                         }|d
                                         }t          j        ||f          }	t          j	        ||	         |          rt          j	        ||	         |          sd} n||dS )a  
    Validate that a BED dataframe is sorted.

    BED dataframes should be sorted by chrom, then by start, then by end.

    The scheme for sorting the chrom column doesn't matter. The only thing
    that matters is that all rows with the same chrom value occur consecutively.
    r   r   r/   Nr   TF)sortr   r   )zsorted.is_chrom_consecutivezsorted.is_sorted_start_end)
npr_flatnonzeror   to_numpyr3   uniquegroupbylexsortarray_equal)
r+   
run_starts
run_valuesis_chrom_consecutiveis_sorted_start_endr   groupstartsendsindicess
             r&   check_is_sortedr      sL    	2>"W+,QRR0BwK4Fss4KKLLqPPJ G%%''
3Jz??c")J2G2G.H.HH JJwUJ33 	 	5w((**U|$$&&*dF^,,N6'?F33	tG}d33	 #(E	 (<&9  r(   tuple[int, bool]c                    dD ]}t           |dz
           | j        v r|} nt          d          t          | j                  |k    }||fS )N)   	                     r/   zCould not infer a BED schema.)BED_FIELD_NAMEScolumns
ValueErrorr3   )r+   r`   nextendeds       r&   infer_bed_schemar   C  sc    & : :1q5!RZ//AE 0 89992:"Hh;r(   schemac                $   d}t          j        ||                                           }|st          d|            |                    d          r"t          |                    d                    nd}|                    d          d u}||fS )Nz#^bed(3|4|5|6|7|8|9|12)?(\+(\d+)?)?$zInvalid BED schema name: r/   r      )rer1   lowerr   r   r]   )r   patternr1   r   r   s        r&   parse_bed_schemar   N  s    4GHWfllnn--E ?=V==>>>${{1~~4EKKNN1A{{1~~T)Hh;r(   inferTnan)r   validate_fieldsrequire_sortedr8   r   
replace_nana_reppathstr | pathlib.Path | Noner   r   r   r   
str | Nonec                  |dk    rt          |           \  }	}
nt          |          \  }	}
d| j        vsd| j        vs	d| j        vrt          d          |	dk    r*d| j        vsd| j        vs	d	| j        vrt          d
          t          d|	         }t          t          |          t          | j                  z
            }t          t          |          t          |          z
            }|
r1t          t          | j                  t          |          z
            ng }t                      }|rXt          | |||          \  }}}|rt          d| d          |r|st          d| d          |rt          d| d          |rVt          j
        t          |                     }|j        |                                          }|rt          d| d          t          j        | j                  }|D ]}||v r5|dk    r| d         ||<   |dk    r| d         ||<   *t          |         ||<   ;||v rPt!          j        d| dt          |          d           | |                             t          |                   ||<   | |         ||<   | j        D ]}||v r| |         ||<   |                    |d|dd          S )a  Write a DataFrame to a BED file.

    Parameters
    ----------
    df : pd.DataFrame
        DataFrame to write.
    path : str or Path, optional
        Path to write the BED file to. If ``None``, the serialized BED file is
        returned as a string.
    schema : str, optional [default: "infer"]
        BED schema to use. If ``"infer"``, the schema is inferred from the
        DataFrame's columns.
    validate_fields : bool, optional [default: True]
        Whether to validate the fields of the BED file.
    require_sorted : bool, optional [default: False]
        Whether to require the BED file to be sorted.
    chromsizes : dict or pd.Series, optional
        Chromosome sizes to validate against.
    strict_score : bool, optional [default: False]
        Whether to strictly enforce validation of the score field (0-1000).
    replace_na : bool, optional [default: True]
        Whether to replace null values of standard BED fields with
        compliant uninformative values.
    na_rep : str, optional [default: "nan"]
        String representation of null values if written.

    Returns
    -------
    str or None:
        The serialized BED file as a string if ``path`` is ``None``, otherwise
        ``None``.
    r   r   r   r   z=BED dataframe must have at least 3 fields: chrom, start, end.r   r   r   r   zYInformative blockCount, blockSizes, and blockStarts fields are mandatory in BED12+ files.N)r8   r   zFields contain invalid dtypes: r   zFields contain null values: z#Properties that failed validation: z!DataFrame isn't properly sorted: )r   r   r   zStandard column zK contains null values. These will be replaced with the uninformative value 	F)sepr   r   header)r   r   r   r   r   listr   r   	TypeErrorr=   r>   r   r   tolist	DataFrameBED_FIELD_FILLVALUESwarningswarnfillnato_csv)r+   r   r   r   r   r8   r   r   r   r   r   standard_cols	fill_cols	data_colscustom_colsfields_with_nullsdtypes_failedprops_failedr   bedr   s                        r&   r   r   X  st   X &r**88&v..8 	rz!!"*$$
""K
 
 	
 	BwwBJ&&rz))
**)
 
 	

 $BQB'MS''#bj//9::IS''#i..899I@HP$s2:]););;<<<bK 	T9L	j|:
 :
 :
6(,  	PNmNNNOOO 	RZ 	RP<MPPPQQQ 	TR<RRRSSS R	/"--..{E6*1133 	RPPPPQQQ
,RX
&
&
&C  )l""g;C
""e9C/4C%%%M03 0 0',0 0 0  
 #w~~&:3&?@@CHH#wCHHz  +#wCH::dV5:OOOr(   )r   r   r    r   )r+   r,   r    r-   r$   )r+   r,   r8   r9   r    r-   )NF)
r+   r,   r   r   r8   r9   r   r   r    r   )r+   r,   r    r   )r   r   r    r   )r+   r,   r   r   r   r   r   r   r   r   r8   r9   r   r   r   r   r   r   r    r   )+__doc__
__future__r   pathlibr   r   typingr   numpyr   pandasr=   __all__iinfouint64maxr<   int64float64objectBED_DTYPE_MAPr   r   r   r%   r*   r7   rC   rG   rI   rM   rP   rU   rW   rh   rk   rr   r   r   r   r   r   r   r)   r(   r&   <module>r      s  0 0b # " " " " "  				               * RXbi  $

 x	Z                7   * 7<@    @ 5<@! ! ! ! !H 6   " 7   $ 8    <   $ :   & 9   : <     <   0 =Z Z Z Z@ +/	A5 A5 A5 A5 A5H       F       '+rP   *.rP rP rP rP rP rP rP rPr(   