text: #!/usr/bin/env python3
  # -*- coding: utf-8 -*-
  '''
  Author       : windz
  Date         : 2020-06-04 11:53:34
  LastEditTime : 2021-10-12 14:38:52
  Description  : rename FLAIR isoforms that match isoforms in existing annotation according to the gene_id
  '''
  
  
  from collections import defaultdict, Counter
  import pickle
  import numpy as np
  import pandas as pd
  import click
  from tqdm import tqdm
  
  
  
  NAMES=[
      'Chromosome', 'Start', 'End', 'Name', 'Score', 'Strand', 
      'ThickStart', 'ThickEnd', 'ItemRGB', 'BlockCount', 'BlockSizes', 'BlockStarts', 
      'geneChromosome', 'geneStart', 'geneEnd', 'geneName', 'geneScore', 'geneStrand', 
      'geneThickStart', 'geneThickEnd', 'geneItemRGB', 'geneBlockCount', 'geneBlockSizes',   'geneBlockStarts', 'cov'
      ]
  
  
  @click.command()
  @click.option('--in_intersect', required=True)
  @click.option('--in_isoform', required=True)
  @click.option('-o', '--outfile', required=True)
  def main(in_intersect, in_isoform,  outfile):
      df = pd.read_csv(
          in_intersect, 
          sep='\t', 
          names=NAMES,
          header=None
          )
  
  
      results = defaultdict(
          lambda : {
              'cov': 0, 
              'is_splicing_intermediates': False, 
              'gene_len': 0,
              'gene_id': None
              }
      )
  
      # Step1
      for item in tqdm(df.itertuples(), desc="Step 1/2: iter bed intersect",):
          if results[item.Name]['cov'] < item.cov:
              results[item.Name]['cov'] = item.cov
              results[item.Name]['gene_id'] = item.geneName.split('.')[0]
  
      # Setp2
      df = pd.read_csv(in_isoform, sep='\t', header=None)
      gene_counter = Counter()
      with open(outfile, 'w') as o:
          for item in tqdm(df.values, desc="Step 2/2: output reannotate isoform"):
              isoform_id = item[3]
              if isoform_id in results:
                  gene_id = results[isoform_id]['gene_id']
                  gene_counter[gene_id] += 1
                  reannotate_isoform_id = gene_id+'_'+str(gene_counter[gene_id])
                  item[3] = reannotate_isoform_id
              
              print('\t'.join(map(str, item)), file=o)
  
      
  
  if __name__ == "__main__":
      main()