# $CVSHeader: pal8e/src/Hrmsd-top10.py,v 1.2 2005/02/15 01:10:26 indraneel Rel $

import os
from string import split
from Sigma import Sigma

HrmsdFile = '../dat/stat/Hrmsd'
Hrmsd_10File = '../dat/stat/Hrmsd-top10'
Hsigma_10File = '../dat/stat/Hsigma-top10'

## mean Hrmsd from fitting Hrmsd-top10
slope = 0.0089
intercept = 2.1997

def readfile(fname):
    fh = file(fname)
    lines = fh.readlines()
    fh.close()
    return lines

def removeTop10(lines):
    data = {}
    outdata = {}
    for line in lines:
        (Hlen, rmsd) = line.split()
        Hlen = int(Hlen)
        rmsd = float(rmsd)
        if not data.has_key(Hlen):
            data[Hlen] = []
        data[Hlen].append(rmsd)
    for Hlen in data.keys():
        data[Hlen].sort()
        length = len(data[Hlen])
        length90 = int((float(length)/10) * 9)
        #if ((len(data[Hlen])-1)>0):
        #    outdata[Hlen] = data[Hlen]
        if (len(data[Hlen][:length90])):
            outdata[Hlen] = data[Hlen][:length90]
    return outdata

def writeRMSD(fname, data):
    Hlens = data.keys()
    Hlens.sort()
    lines = []
    outdata = []
    for Hlen in Hlens:
        for rmsd in data[Hlen]:
            line = str(Hlen)+'\t'+str(rmsd)+'\n'
            lines.append(line)
            outd = [Hlen, rmsd]
            outdata.append(outd)
    fh = file(fname, 'w')
    fh.writelines(lines)
    fh.close()
    return outdata

def getSigma(data):
    sigmas = {}
    for Hlen in data.keys():
        sigma = Sigma(data[Hlen])
        mean = slope * Hlen + intercept
        s = sigma.sigma(mean)
        sigmas[Hlen] = s
    return sigmas

def writeSigma(fname, data):
    Hlens = data.keys()
    Hlens.sort()
    lines = []
    for Hlen in Hlens:
        line = str(Hlen)+'\t'+str(data[Hlen])+'\n'
        lines.append(line)
    fh = file(fname, "w")
    fh.writelines(lines)
    fh.close()

if __name__ == '__main__':
    lines = readfile(HrmsdFile)
    data = removeTop10(lines)
    writeRMSD(Hrmsd_10File, data)
    sigmaDict = getSigma(data)
    writeSigma(Hsigma_10File, sigmaDict)
    
