#
#
#

__author__ = "Magdalena A. Jonikas"
__version__ = "3.0"
__date__ = "04/08/09"
__doc__ = """Assemble pieces using a converted library of pieces"""

import sys, math, time, pickle, random, copy
import c2a

def updateLog(logFile, numSteps, count, accept):
    logFile.write('%i %i %i\n' % (numSteps, count, accept))
    logFile.flush()

def assemble(fragIn,
             coarseIn,
             centerAtoms,
             pieceLib,
             outName,
             n,
             cutoff):

# Set up some variables and read in data
    goal = 0 # Number of desired collision
    steps = 500 # Max number of steps to try to reach goal
    tries = 5 # Max number of attempts for each structure
    piecesDefFile = open(fragIn).readlines()
    coarseModelIN = open(coarseIn).readlines()
    logFile = open('%s_log.txt' % outName, 'w') # Set up log file
    p2f2r = pickle.load(pieceLib) # Load the matches
    print "Data is loaded"

# Continue running until goal is reached
    for i in range(n):
        print "Working on structure # %i" % i
        t=0
        while t<=tries: # keep looking for a solution
            print "try # %i" % t
        # First round
            s = c2a.CombinedStructure(piecesDefFile, p2f2r, coarseModelIN, cutoff, centerAtoms)
            s.centerAtoms = centerAtoms
            s.i = i
            s.outName = outName
            s.logFile = logFile
            s.OLDchoice = s.randomChoice()
            s.OLDlines = s.assemblePieces(s.OLDchoice)
            (s.OLDbadPieces, s.OLDbadCount) = s.checkCollisions(s.OLDlines, centerAtoms)
            updateLog(logFile, s.numSteps, s.OLDbadCount, 0)
            s.bestLines = s.OLDlines
            s.minBadCount = s.OLDbadCount
            while s.numSteps<s.steps: # keep looking for a solution
                stop = s.stepForward()
                if stop: break
                s.numSteps+=1
            if stop: break
            t+=1
            if t>tries:
                print "Could not find a solution in %i tries, writing best solution observed" % tries
                s.writeFile(s.bestLines)


def main():
    time0 = time.clock()

# INPUT
    assemble(fragIn = sys.argv[1], # fragment definition file
             coarseIn = sys.argv[2], # Coarse grain template e.g. 6TNA-C3.pdb
             centerAtoms = sys.argv[3],
             pieceLib = open(sys.argv[4], 'r'), # Library of matches
             outName = sys.argv[5], # Output name
             n = int(sys.argv[6]), # number of full atomic structures to build
             cutoff = float(sys.argv[7])) # Define a collision distance e.g. 1.5

    time1 = time.clock()

    return (time1-time0)


if __name__=='__main__':
    sys.stdout.write("Total Time: %.1f\n" % (main()))
