def createGeneListTable(page, genes, verify=None):
    output_list = []
    
    total = 0
    for pair in genes:
        geneSym, l = pair
        total += l
        if geneSym in drugDB.__drugDict:
            drugs = len(drugDB.__drugDict[geneSym])
        else:
            drugs = 0
        if verify==None or geneSym in verify:
            output_list.append(["<a href=\"../genelists/%s.html\" > %s </a>" % (geneSym, geneDB.__original_names[geneSym]), l, drugs])
        else:
            output_list.append([geneDB.__original_names[geneSym], l, drugs])
        
    output_list = sorted(output_list, key=lambda item: -item[1])
    htmltools.createTable(page, output_list, ["Gene", "#Associated Traits", "#Targeted Drugs"], "genelisthead", None, ["genecol","traitcol", "drugcol"],"genetable",None)
def writeTraitPage(filename, title, desc, commonGenes, pfilter_cutoff):
    traitpage = htmltools.createPage(title, scripts={'sorttable.js':'javascript'})
    htmltools.pageDescription(traitpage, desc)
    
    traitChi = computeTraitStatistics(commonGenes, pfilter_cutoff)
    
    significance_pairs = [ (i, trait, traitChi[trait][5]) for i, trait in enumerate(traitChi.keys()) ]
    significance_levels = [ pval for (i, trait, pval) in significance_pairs ]

    FDR = computePermutationTest(traitChi, commonGenes, significance_levels, __ITERATIONS)
    FDR_map = dict( [ ( trait, FDR[i] ) for (i, trait, pval) in significance_pairs ] )
    
    traitTable = []
    for trait in traitChi:
        (cnt, oddsratio, kappa, numgenes, fisher_exact, fisher_p, genes) = traitChi[trait]
        fdr_value = FDR_map[trait]

        translate = trait.replace(" ","_").replace("/", " or ").replace("\\", " or ")

        if len(trait) > 38:
            trait = trait[:35] + "..."
        alink = "<a href=\"traitlists/%s.html\">%s</a>" % (translate, trait)

        entry = [alink, cnt, numgenes, "%.7f" % (fisher_exact), "%.7f" %
                (fisher_p), "%.1f" % (oddsratio), "%.4f" % (kappa), fdr_value]
        traitTable.append(entry)

    traitTable = sorted(traitTable, key=lambda item: -item[1])

    htmltools.createTable(
              traitpage,
              traitTable,
            ["Disease/Trait", "# RE Genes", "# Trait Genes",
                "fisher exact", "p-value", "odds ratio", "kappa",
                "FDR"],
             "traitlisthead",
              None,
            ["traitcol", "recol", "genecol", "fishercol","pcol",
                "oddscol", "kappacol","bencol"],
             "sortable", None)
    htmltools.endPage(traitpage)
    htmltools.savePage(traitpage, filename)
def writeGenePage(output_dir, filename, title, desc, total, geneTable):
    genepage = htmltools.createPage(title)

    htmltools.pageDescription(genepage, desc)
    
    newTable=[]
    for row in geneTable:
        drugcount = 0
        if row[0] in drugDB.__drugDict:
            drugcount = len(drugDB.__drugDict[row[0]])

        if os.path.exists(os.sep.join([output_dir,"genelists",row[0]+".html"])):
            newTable.append(["<a href=\"genelists/%s.html\">%s</a>" % (row[0], geneDB.__original_names[row[0]]), row[1], drugcount])
        else:
            newTable.append([geneDB.__original_names[row[0]], row[1], drugcount])
    
    htmltools.createTable(genepage, newTable, ["Gene","#Associated Traits", "#Targeted Drugs"], "genelisthead", None, ["genecol","traitcol", "drugcol"],"genetable",None)
    
    htmltools.endPage(genepage)
    htmltools.savePage(genepage, filename)
def createGeneListingsHTML(geneListDir):

    pbar = ProgressBar()
    pbar.setMaximum(len(gwasDB.__geneSet))
    pbar.updateProgress(0)

    i=0
    for gene in gwasDB.__geneSet:
        if i % 10 == 0:
            pbar.updateProgress(i)
        i+=1
        genePage = htmltools.createPage("Gene Summary: " +
                geneDB.__original_names[gene], css_file='../genereport.css',
                scripts = {'../sorttable.js':'javascript'})
        
        
        # Create the disease trait tables
        traits = []
        for trait in gwasDB.__traitDict[gene]:
            traits.append(trait)
            
        traits = sorted(traits, key=lambda trait: -__traitMetaAnalysis[trait]['RE_chi'][0])
        
        traitTable = []
        for trait in traits:
            cnt       = len(__traitMetaAnalysis[trait]['RE'])
            oddsratio = __traitMetaAnalysis[trait]['RE_chi'][4]
            kappa     = __traitMetaAnalysis[trait]['RE_chi'][5]
            fisher_exact = __traitMetaAnalysis[trait]['RE_chi'][6]
            fisherp    = __traitMetaAnalysis[trait]['RE_chi'][7]
            numgenes  = __traitMetaAnalysis[trait]['geneset_size']
            translate = trait.replace(" ","_").replace("/", " or ").replace("\\", " or ")
            
            if len(trait) > 38:
                trait = trait[:35] + "..."
            traitTable.append(["<a href=\"../traitlists/%s.html\">%s</a>" %
                (translate,trait), cnt, numgenes, "%.7f" % (fisher_exact),
                "%.7f" % (fisherp), "%.1f" % (oddsratio), "%.4f" % (kappa), ])
            
        genePage.div("Gene %s, total traits: %d" % (geneDB.__original_names[gene],len(traitTable)), class_="header")
        
        htmltools.createTable(genePage, traitTable, ["Disease/Trait", "#RE Genes", 
            "#Trait Genes", "fisher exact", "P-value",
            "oddsratio", "kappa"], "traitlisthead", None,
            ["traitcol","recol",
                "genecol","fishercol","pcol",
                "oddscol","kappacol"], "sortable", None)
        
        # Create drug bank links
        
        
        if gene not in drugDB.__drugDict:
            genePage.div("No drugs target gene %s" % (geneDB.__original_names[gene]), class_="header")
        else:
            drugbank_size = len(drugDB.__drugDict[gene])
            
            genePage.div("%d drugs targeting gene %s" % (drugbank_size, geneDB.__original_names[gene]), class_="header")
            
            genePage.div.open(class_="druglist")
            genePage.ul.open()
            for drug in drugDB.__drugDict[gene]:
                link = "http://www.drugbank.ca/drugs/%s" % (drug)
                if drug not in drugDB.__drugs:
                    genePage.li(oneliner.a(drug, href=link))
                else:
                    genePage.li(oneliner.a(drugDB.__drugs[drug]['name'], href=link))
            genePage.ul.close()
            genePage.div.close()
            
        
        htmltools.savePage(genePage, os.sep.join([geneListDir, gene + ".html"]))
    pbar.finalize()