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()
def createTraitListingsHTML(traitListDir):
    
    traitSet = set(gwasDB.__studyByTrait.keys())
    
    for trait in traitSet:
        if trait not in __traitMetaAnalysis:
            continue
        
        traitMetadata = __traitMetaAnalysis[trait]
        RE_proteins = traitMetadata['RE']
        drug_proteins = traitMetadata['drugbank']
        other_proteins = traitMetadata['other']
        
        chi_RE = traitMetadata['RE_chi']
        chi_Drugbank = traitMetadata['drugbank_chi']
        
        traitListFilename = os.sep.join([traitListDir, trait.replace(" ","_").replace("/", " or ").replace("\\", " or ") + ".html"])
        
        traitpage = htmltools.createPage("Trait Summary: " + trait, css_file='../genereport.css')
        
        htmltools.pageDescription(traitpage, "Gene list overlap summary for trait: %s" % (trait))
        
        # two of these
        
        htmltools.createContingencyTable(traitpage, "Overlap with rapidly evolving genes:", "RE", "trait", chi_RE[0], chi_RE[1], chi_RE[2],
                chi_RE[3], chi_RE[4], chi_RE[5], chi_RE[6], chi_RE[7] )
        
        htmltools.createContingencyTable(traitpage, "Overlap with drugbank genes:",
                "Drugbank", "trait", chi_Drugbank[0], chi_Drugbank[1],
                chi_Drugbank[2], chi_Drugbank[3], chi_Drugbank[4],
                chi_Drugbank[5], chi_Drugbank[6], chi_Drugbank[7])
        
        chi_drugs = traitMetadata['drugchi']
        htmltools.createContingencyTable(traitpage, "Drug contingency for targeting disease vs targeting rapidly evolving proteins:",
                "Targets Disease Genes", "Targets RE Genes", chi_drugs[0], chi_drugs[1],
                chi_drugs[2], chi_drugs[3], chi_drugs[4],
                chi_drugs[5], chi_drugs[6], chi_drugs[7])


        traitpage.table.open(class_="invisible")
        traitpage.tr.open()

        traitpage.td.open()
        traitpage.div("Gene Lists:", class_="header")
        
        traitpage.div("Trait genes indicated as rapidly evolving: ", class_="description")
        createGeneListTable(traitpage, RE_proteins)
        
        traitpage.div("Trait genes associated with Drugbank targets: ", class_="description")
        createGeneListTable(traitpage, drug_proteins)
        
        traitpage.div("Other trait genes: ", class_="description")
        createGeneListTable(traitpage, other_proteins)
        
        traitpage.td.close()
        traitpage.td.open()

        traitpage.div("Drug Lists:", class_="header")
        
        druglistlen = len(__traitMetaAnalysis[trait]['RE_drugs'])
        traitpage.div("%d drugs targeting associated rapidly evolving proteins" % (druglistlen), class_="description")
        
        traitpage.div.open(class_="druglist")
        traitpage.ul.open()
        for drug in __traitMetaAnalysis[trait]['RE_drugs']:
            link = "http://www.drugbank.ca/drugs/%s" % (drug)
            if drug not in drugDB.__drugs:
                traitpage.li(oneliner.a(drug, href=link))
            else:
                traitpage.li(oneliner.a(drugDB.__drugs[drug]['name'], href=link))
        traitpage.ul.close()
        traitpage.div.close()
        
        druglistlen = len(__traitMetaAnalysis[trait]['other_drugs'])
        traitpage.div("%d Drugs targeting other proteins" % (druglistlen), class_="description")
        
        
        traitpage.div.open(class_="druglist")
        traitpage.ul.open()
        for drug in __traitMetaAnalysis[trait]['other_drugs']:
            link = "http://www.drugbank.ca/drugs/%s" % (drug)
            if drug not in drugDB.__drugs:
                traitpage.li(oneliner.a(drug, href=link))
            else:
                traitpage.li(oneliner.a(drugDB.__drugs[drug]['name'], href=link))
        traitpage.ul.close()
        traitpage.div.close()


        traitpage.td.close()
        traitpage.tr.close()
        traitpage.table.close()
        
        htmltools.savePage(traitpage, traitListFilename)
     os.mkdir(os.sep.join([output_dir, "traitlists"]))
     os.mkdir(os.sep.join([output_dir, "DAVID"]))
     
 print "\nCopying support files..."
     
 os.system("copy %s %s" % (os.sep.join(["html", "genereport.css"]), output_dir ))
 os.system("copy %s %s" % (os.sep.join(["html", "sorttable.js"]), output_dir ))
 os.system("copy %s %s" % (os.sep.join(["html", "DAVID", str(gene_frequency_filter), "*"]), os.sep.join([output_dir, "DAVID", ""])))
 
 # make index.html
 
 print "Making index.html..."
 
 # Report data set properties
 
 indexpage = htmltools.createPage("Rapidly Evolving Gene Meta-Analysis Report")
 
 indexpage.div("Summary of loaded information:", class_="header")
 
 indexpage.div("Rapidly Evolving genes loaded:                  %d".replace(" ", "&nbsp;") % (len(studyGenes)),class_="console")
 indexpage.div("Drugbank drug target proteins loaded:           %d".replace(" ", "&nbsp;") % (len(drugDB.__geneSet)),class_="console")
 indexpage.div("GWAS Genes indicated in disease studies:        %d".replace(" ", "&nbsp;") % (len(gwasDB.__geneSet)),class_="console")
 
 
 # report gwas, RE overlap chi matrix
 
 htmltools.createContingencyTable(indexpage, "GWAS Overlap with Rapidly Evolving Geneset:", "GWAS", "RE", a1, b1, c1, d1,
         oddsratio1, kappa1, fisher_exact1, fisherp1)
 
 indexpage.div.open(class_="links")
 indexpage.a("Trait Report", href="gwas_traits.html")