Esempio n. 1
0
    for nrg in delta_nrgs:
        free_nrg.accumulate(nrg.value())
    deltaG = free_nrg.average() * kcal_per_mol
    return deltaG


if __name__ == "__main__":

    try:
        host = os.environ['HOSTNAME']
    except KeyError:
        host = "unknown"
    print("### Running electrostatics correction calculation on %s ###" % host)
    if True: #verbose.val:
        print("###================= Simulation Parameters=====================###")
        Parameter.printAll()
        print ("###===========================================================###\n")
    print("lambda is %s" % lambda_val.val)

    if os.path.exists(s3file.val):
        (molecules, space) = Sire.Stream.load(s3file.val)
    else:
        amber = Amber()
        (molecules, space) = amber.readCrdTop(crdfile.val, topfile.val)
        Sire.Stream.save((molecules, space), s3file.val)

    # What to do with this...
    system = createSystemFreeEnergy(molecules)
    lam = Symbol("lambda")
    solutes = system[MGName("solutes")]
    solute_ref = system[MGName("solute_ref")]
Esempio n. 2
0
    deltaG = free_nrg.average() * kcal_per_mol
    return deltaG


if __name__ == "__main__":

    try:
        host = os.environ['HOSTNAME']
    except KeyError:
        host = "unknown"
    print("### Running electrostatics correction calculation on %s ###" % host)
    if True:  #verbose.val:
        print(
            "###================= Simulation Parameters=====================###"
        )
        Parameter.printAll()
        print(
            "###===========================================================###\n"
        )
    print("lambda is %s" % lambda_val.val)

    if os.path.exists(s3file.val):
        (molecules, space) = Sire.Stream.load(s3file.val)
    else:
        amber = Amber()
        (molecules, space) = amber.readCrdTop(crdfile.val, topfile.val)
        Sire.Stream.save((molecules, space), s3file.val)

    # What to do with this...
    system = createSystemFreeEnergy(molecules)
    lam = Symbol("lambda")
Esempio n. 3
0
def runLambda():
    try:
        host = os.environ['HOSTNAME']
    except KeyError:
        host = "unknown"
    print("### Running LJ tail correction calculation on %s ###" % host)
    if verbose.val:
        print(
            "###================= Simulation Parameters=====================###"
        )
        Parameter.printAll()
        print(
            "###===========================================================###\n"
        )
    print("lambda is %s" % lambda_val.val)

    if os.path.exists(s3file.val):
        (molecules, space) = Sire.Stream.load(s3file.val)
    else:
        amber = Amber()
        (molecules, space) = amber.readCrdTop(crdfile.val, topfile.val)
        Sire.Stream.save((molecules, space), s3file.val)

    system = createSystemFreeEnergy(molecules)

    # !!! NEED TO DISABLE CHANGE IN COULOMBIC CUTOFF !!
    #system = zeroCharges(system)

    #import pdb; pdb.set_trace()

    # THIS IS THE ONE WITH SHORT CUTOFF
    system_shortc = System()
    system_shortc.copy(system)
    #import pdb; pdb.set_trace()
    system_shortc = setupLJFF(system_shortc, space, \
                              cutoff=cutoff_dist.val)
    #import pdb; pdb.set_trace()

    # Determine longest cutoff that can be used. Take lowest space dimension,
    # and decrease by 5%
    dims = space.dimensions()
    mindim = dims.x()
    if mindim > dims.y():
        mindim = dims.y()
    if mindim > dims.z():
        mindim = dims.z()
    long_cutoff = (mindim / 2.0 * 0.95) * angstrom
    print(long_cutoff)
    system_longc = System()
    system_longc.copy(system)
    system_longc = setupLJFF(system_longc, space, \
                             cutoff=long_cutoff)
    # NOW ADD ANALYTICAL CORRECTION TERM TO longc
    E_lrc_full = addAnalyticalLRC(system_longc, long_cutoff, bulk_rho.val)
    #import pdb; pdb.set_trace()
    # Now loop over snapshots in dcd and accumulate energies
    start_frame = 1
    end_frame = 1000000000
    step_frame = stepframe.val

    #mdtraj_top = mdtraj.load_prmtop(topfile.val)
    mdtraj_trajfile = mdtraj.open(trajfile.val, 'r')
    nframes = len(mdtraj_trajfile)
    if end_frame > (nframes - 1):
        end_frame = nframes - 1
    mdtraj_trajfile.seek(start_frame)
    current_frame = start_frame

    delta_nrgs = []

    while (current_frame <= end_frame):
        print("Processing frame %s " % current_frame)
        print("CURRENT POSITION %s " % mdtraj_trajfile.tell())
        frames_xyz, cell_lengths, cell_angles = mdtraj_trajfile.read(
            n_frames=1)
        #print (system_shortc.energy())
        #print (system_longc.energy())
        system_shortc = updateSystemfromTraj(system_shortc, frames_xyz,
                                             cell_lengths, cell_angles)
        system_longcc = updateSystemfromTraj(system_longc, frames_xyz,
                                             cell_lengths, cell_angles)
        #print (system_shortc.energy())
        #print (system_longc.energy())
        delta_nrg = (system_longc.energy() + E_lrc_full -
                     system_shortc.energy())
        delta_nrgs.append(delta_nrg)
        current_frame += step_frame
        mdtraj_trajfile.seek(current_frame)
    #print (delta_nrgs)
    # Now compute free energy change
    deltaG = getFreeEnergy(delta_nrgs)
    #print (deltaG)
    nbootstrap = 100
    deltaG_bootstrap = np.zeros(nbootstrap)
    for x in range(0, nbootstrap):
        resampled_nrgs = resample(delta_nrgs)
        dG = getFreeEnergy(resampled_nrgs)
        deltaG_bootstrap[x] = dG.value()
    dev = deltaG_bootstrap.std()
    print("DG_LJ = %8.5f +/- %8.5f kcal/mol (1 sigma) " %
          (deltaG.value(), dev))
Esempio n. 4
0
def run():
    try:
        host = os.environ['HOSTNAME']
    except KeyError:
        host = "unknown"
    print("### Running Standard state correction calculation on %s ###" % host)

    if verbose.val:
        print("###================= Simulation Parameters=====================###")
        Parameter.printAll()
        print ("###===========================================================###\n")

    #Constants
    delta_over_two = delta_trans.val/2.0
    deltavol = delta_trans.val*delta_trans.val*delta_trans.val
    ROT = 8 * pi**2
    deltarot = ROT# To adjsut after number of orientations has been determined
    kb = Sire.Units.k_boltz
    T = temperature.val.value()
    kbT = kb*T
    beta = 1/kbT

    Ztot = 0.0
    Uavg = 0

    sim_dictionary = distance_restraints_dict.val
    if sim_dictionary == {}:
        print ("Error, no distance restraints dictionary was found in the supplied config file. Abort.")
        sys.exit(-1)
    #now create a dictionary in this way:
    #dict[pairs] = {[Req,D,K] [coords] [coords]...}
    restr_dict = {}
    #create a list of host/guest indexes to be used with mdtraj for alignment
    host_indices = []
    guest_indices = []
    for pairs in sim_dictionary:
        req = sim_dictionary[pairs][0]
        K   = sim_dictionary[pairs][1]
        D   = sim_dictionary[pairs][2]
        # First entry are parameters, second and third entries for coordinates of first and second atom
        restr_dict[pairs]=[[req,K,D],[],[]]
        if not pairs[1] in host_indices:
            host_indices.append(pairs[1])
        if not pairs[0] in guest_indices:
            guest_indices.append(pairs[0])
        #idx = max(pairs)
        #hosts.append(idx)
    #FIXME: code assumes guest atoms have lower indices than host atoms
    # a more reliable algorithm could work out whether the atoms belong
    # to a guest residue?

    # FIXME:
    # Support loading a crd file only to define restraint parameters

    #load the trajectory
    start_frame = 0
    end_frame = 1000000000
    step_frame = stepframe.val
    #Check the extension of the topology file
    if ".top" in topfile.val:
        shutil.copy(topfile.val,"SYSTEM.prmtop")
        #top doesn't work with mdtraj
        top_file = "SYSTEM.prmtop"
    else:
        top_file = topfile.val
    #Check the extension of the traj file
    if ".crd" in trajfile.val:
        shutil.copy(trajfile.val,"SYSTEM.rst7")
        #crd doesn't work with mdtraj
        traj_file = "SYSTEM.rst7"
    else:
        traj_file = trajfile.val


    print("Loading trajectory and topology files")
    #
    mdtraj_trajfile = mdtraj.load(traj_file,top=top_file)
    nframes = len(mdtraj_trajfile)
    if end_frame > (nframes - 1):
        end_frame = nframes - 1
    current_frame = start_frame

    #Aligning everything along the first frame
    # Either use restrained host atoms, or a default selection if less than 3 unique atoms
    selection_default = "not water and not resname 'Na+' and not resname 'Cl-' and mass > 1"
    if len(host_indices) >2:
        selection = "index %s " % host_indices[0]
        for idx in host_indices[1:]:
            selection += " or index %s" % idx
    else:
        selection = selection_default

    print (selection)
    align_indices = mdtraj_trajfile.topology.select(selection)
    #print (align_indices)

    # FIXME: check whether alignment tolerates PBC artefacts
    print("Host: Aligning frames along first frame of trajectory")
    aligned_traj = mdtraj_trajfile.superpose(mdtraj_trajfile,0, atom_indices=align_indices)

    # First pass, collect aligned host coordinates
    while (current_frame <= end_frame):
        for pairs in restr_dict:
            idx1 = pairs[0]
            idx2 = pairs[1]
            #coord1 = aligned_traj.xyz[current_frame,idx1,:].tolist()
            coord2 = aligned_traj.xyz[current_frame,idx2,:].tolist()
            #restr_dict[pairs][1].append(coord1)
            restr_dict[pairs][2].append(coord2)
        current_frame += step_frame

    # Second pass, align against guest coordinates
    # and collect aligned guest coordinates
    if len(guest_indices) >2:
        selection = "index %s" % (guest_indices[0])
        for idx in guest_indices[1:]:
            selection += " or index %s" % idx
    else:
        selection = selection_default

    print (selection)
    align_indices = mdtraj_trajfile.topology.select(selection)
    #print (align_indices)
    # FIXME: check whether alignment tolerates PBC artefacts
    print("Guest: Aligning frames along first frame of trajectory")
    aligned_traj = mdtraj_trajfile.superpose(mdtraj_trajfile,0, atom_indices=align_indices)

    current_frame = start_frame
    while (current_frame <= end_frame):
        for pairs in restr_dict:
            idx1 = pairs[0]
            idx2 = pairs[1]
            coord1 = aligned_traj.xyz[current_frame,idx1,:].tolist()
            restr_dict[pairs][1].append(coord1)
        current_frame += step_frame

    #now restr_dict has:
    #restr_dict[lig,host]=[ [req,K,D], [ [coords]...] ,[ [coords],...] ]
    print("Calculating average coordinates for restrained atoms")
    #import pdb; pdb.set_trace()
    restr_dict = averageCoordinates(restr_dict)
    print(restr_dict)
    #now the restr_dict is:
    #restr_dict[pairs]=[[req,K,D],[avgx,avgy,avgz]]

    # Create N orientations of restrained guest atoms by
    # rigib body rotations around COM
    guest_orientations = genOrientations(restr_dict, norientations=norient.val)
    deltarot /= len(guest_orientations)
    # FIXME: make sure space extends well into regions where restraint energy
    # is high
    space = defineIntegrationDomain(restr_dict)
    if verbose.val:
        print("Integration space")
        print(space)

    #Grid creation
    Nx = int ( round ( ( space[1][0] - space[0][0] ) / delta_trans.val ) )
    Ny = int ( round ( ( space[1][0] - space[0][0] ) / delta_trans.val ) )
    Nz = int ( round ( ( space[1][0] - space[0][0] ) / delta_trans.val ) )
    print("Number of grid points to be evaluated %d (%d orientations per point)" %(Nx*Ny*Nz,norient.val*(norient.val/2)*norient.val))
    print("Evaluation...")
    count = 0
    free = 0
    loweight = 0
    for i in range(0,Nx):
        # FIXME: OpenMP ?
        for j in range(0,Ny):
            for k in range(0,Nz):
                count += 1
                if ( (count % 100000) == 0):
                    print ("Done %s grid points..." % (count))
                xgrid = space[0][0] + delta_trans.val*i + delta_over_two
                ygrid = space[0][1] + delta_trans.val*j + delta_over_two
                zgrid = space[0][2] + delta_trans.val*k + delta_over_two
                for orientation in guest_orientations:
                    pos = 0
                    U = 0.0
                    for pairs in restr_dict:
                        req = restr_dict[pairs][0][0]
                        k = restr_dict[pairs][0][1]
                        dtol = restr_dict[pairs][0][2]
                        host_coord = restr_dict[pairs][2]
                        guest_coord = orientation[pos]
                        # Accumulate energy
                        d2 = ((guest_coord[0]+xgrid) - host_coord[0])**2+\
                             ((guest_coord[1]+ygrid) - host_coord[1])**2+\
                             ((guest_coord[2]+zgrid) - host_coord[2])**2
                        d = math.sqrt(d2)
                        if (d > (req+dtol)):
                            U += k*(d-req-dtol)**2
                        elif (d < (req-dtol)):
                            U += k*(d-req+dtol)**2
                        else:
                            U += 0.0
                        pos += 1
                        #print ("d %s U %s " % (d,U))
                    Boltz = math.exp(-beta*U)*deltavol*deltarot
                    Uavg += U*Boltz
                    Ztot += Boltz
                    if (U < 0.000001):
                        free += 1/(norient.val*(norient.val/2)*norient.val)
                    if ( U*beta < 10):
                        loweight += 1/(norient.val*(norient.val/2)*norient.val)
                #import pdb;pdb.set_trace()
    #Calculation of Ztot, Uavg, S, Frestraint:
    free_vol = free*deltavol
    loweight_frac = loweight/float(count)
    print ("Volume where restraint is null %8.2f Angstrom^3" % (free_vol))
    print ("Fraction of points considered were restraint is under 10kbT %8.2f" % loweight_frac)
    if (loweight_frac > 0.25):
        print ("WARNING !!! The integration domain does not contain a significant number of datapoints with high restraint energy. It is possible that the domain does not cover all low restraint energy regions. Please check and if necessary increase the buffer keyword.")
        #sys.exit(-1)

    Uavg /= (Ztot)

    Zideal = 1661.*ROT
    Delta_F = -kbT*math.log(Zideal/Ztot)
    minTDelta_S = -T*(kb*math.log(Zideal/Ztot)-Uavg/T)
    print ("Ztot  = %8.2f Angstrom^3" % Ztot)
    print ("WARNING !!! Have you checked that Ztot does not increase significantly when the value of the command line argument -b/--buffer size is increased?")
    print ("WARNING !!! This calculation was done with the argument -b %s Angstrom" % buffer.val)
    print ("Free energy change upon removing the restraint and applying standard state conditions = %8.2f kcal/mol" % Delta_F)

    #tidy up the folder by removing prmtop
    cmd = "rm -f SYSTEM.prmtop SYSTEM.rst7"
    os.system(cmd)
Esempio n. 5
0
def runLambda():
    try:
        host = os.environ['HOSTNAME']
    except KeyError:
        host = "unknown"
    print("### Running LJ tail correction calculation on %s ###" % host)
    if verbose.val:
        print("###================= Simulation Parameters=====================###")
        Parameter.printAll()
        print ("###===========================================================###\n")
    print("lambda is %s" % lambda_val.val)

    if os.path.exists(s3file.val):
        (molecules, space) = Sire.Stream.load(s3file.val)
    else:
        amber = Amber()
        (molecules, space) = amber.readCrdTop(crdfile.val, topfile.val)
        Sire.Stream.save((molecules, space), s3file.val)

    system = createSystemFreeEnergy(molecules)

    # !!! NEED TO DISABLE CHANGE IN COULOMBIC CUTOFF !!
    #system = zeroCharges(system)

    #import pdb; pdb.set_trace()

    # THIS IS THE ONE WITH SHORT CUTOFF
    system_shortc = System()
    system_shortc.copy(system)
    #import pdb; pdb.set_trace()
    system_shortc = setupLJFF(system_shortc, space, \
                              cutoff=cutoff_dist.val)
    #import pdb; pdb.set_trace()

    # Determine longest cutoff that can be used. Take lowest space dimension,
    # and decrease by 5%
    dims = space.dimensions()
    mindim = dims.x()
    if mindim > dims.y():
        mindim = dims.y()
    if mindim > dims.z():
        mindim = dims.z()
    long_cutoff = (mindim/2.0 * 0.95) * angstrom
    print (long_cutoff)
    system_longc = System()
    system_longc.copy(system)
    system_longc = setupLJFF(system_longc, space, \
                             cutoff=long_cutoff)
    # NOW ADD ANALYTICAL CORRECTION TERM TO longc
    E_lrc_full = addAnalyticalLRC(system_longc, long_cutoff, bulk_rho.val)
    #import pdb; pdb.set_trace()
    # Now loop over snapshots in dcd and accumulate energies
    start_frame = 1
    end_frame = 1000000000
    step_frame = stepframe.val

    #mdtraj_top = mdtraj.load_prmtop(topfile.val)
    mdtraj_trajfile = mdtraj.open(trajfile.val,'r')
    nframes = len(mdtraj_trajfile)
    if end_frame > (nframes - 1):
        end_frame = nframes - 1
    mdtraj_trajfile.seek(start_frame)
    current_frame = start_frame

    delta_nrgs = []

    while (current_frame <= end_frame):
        print ("Processing frame %s " % current_frame)
        print ("CURRENT POSITION %s " % mdtraj_trajfile.tell() )
        frames_xyz, cell_lengths, cell_angles = mdtraj_trajfile.read(n_frames=1)
        #print (system_shortc.energy())
        #print (system_longc.energy())
        system_shortc = updateSystemfromTraj(system_shortc, frames_xyz, cell_lengths, cell_angles)
        system_longcc = updateSystemfromTraj(system_longc, frames_xyz, cell_lengths, cell_angles)
        #print (system_shortc.energy())
        #print (system_longc.energy())
        delta_nrg = (system_longc.energy()+E_lrc_full - system_shortc.energy())
        delta_nrgs.append(delta_nrg)
        current_frame += step_frame
        mdtraj_trajfile.seek(current_frame)
    #print (delta_nrgs)
    # Now compute free energy change
    deltaG = getFreeEnergy(delta_nrgs)
    #print (deltaG)
    nbootstrap = 100
    deltaG_bootstrap = np.zeros(nbootstrap)
    for x in range(0,nbootstrap):
        resampled_nrgs = resample(delta_nrgs)
        dG = getFreeEnergy(resampled_nrgs)
        deltaG_bootstrap[x] = dG.value()
    dev = deltaG_bootstrap.std()
    print ("DG_LJ = %8.5f +/- %8.5f kcal/mol (1 sigma) " % (deltaG.value(), dev))
Esempio n. 6
0
def runFreeNrg():

    # if (save_coords.val):
    #    buffer_freq = 500
    # else:
    #    buffer_freq = 0

    try:
        host = os.environ["HOSTNAME"]
    except KeyError:
        host = "unknown"

    print(" ### Running Single Topology Molecular Dynamics Free Energy on %s ### " % host)
    print("### Simulation Parameters ### ")
    Parameter.printAll()
    print("### ###")

    timer = QTime()
    timer.start()

    # Setup the system from scratch if no restart file is available

    if not os.path.exists(restart_file.val):

        print("New run. Loading input and creating restart")

        print("lambda is %s" % lambda_val.val)

        amber = Amber()

        if os.path.exists(s3file.val):
            (molecules, space) = Sire.Stream.load(s3file.val)
        else:
            (molecules, space) = amber.readCrdTop(crdfile.val, topfile.val)
            Sire.Stream.save((molecules, space), s3file.val)

        system = createSystemFreeEnergy(molecules)

        if center_solute.val:
            system = centerSolute(system, space)

        if use_restraints.val:
            system = setupRestraints(system)

        if use_distance_restraints.val:
            system = setupDistanceRestraints(system)

        # Note that this just set the mass to zero which freezes residues in OpenMM but Sire doesn't known that
        if freeze_residues.val:
            system = freezeResidues(system)

        system = setupForcefieldsFreeEnergy(system, space)

        if random_seed.val:
            ranseed = random_seed.val
        else:
            ranseed = RanGenerator().randInt(100000, 1000000)

        print("Setting up the simulation with random seed %s" % ranseed)

        moves = setupMovesFreeEnergy(system, ranseed, gpu.val, lambda_val.val)

        print("Saving restart")
        Sire.Stream.save([system, moves], restart_file.val)
    else:
        system, moves = Sire.Stream.load(restart_file.val)
        move0 = moves.moves()[0]
        integrator = move0.integrator()
        integrator.setDeviceIndex(str(gpu.val))
        move0.setIntegrator(integrator)
        moves = WeightedMoves()
        moves.add(move0)
        print("Index GPU = %s " % moves.moves()[0].integrator().getDeviceIndex())
        print("Loaded a restart file on wich we have performed %d moves." % moves.nMoves())

    cycle_start = int(moves.nMoves() / nmoves.val) + 1
    cycle_end = cycle_start + ncycles.val

    lam_str = "%7.5f" % lambda_val.val
    outgradients = open("gradients.dat", "a", 1)
    outgradients.write("# lambba_val.val %s\n" % lam_str)

    if save_coords.val:
        trajectory = setupDCD(dcd_root.val, system)

    s1 = timer.elapsed() / 1000.0

    print("Running MD simulation ")

    grads = {}
    grads[lambda_val.val] = AverageAndStddev()
    for i in range(cycle_start, cycle_end):
        print("\nCycle = ", i, "\n")

        # print("Energy before = %s kJ mol-1" % (system.energy().to(kJ_per_mol)))
        # import ipdb; ipdb.set_trace()
        system = moves.move(system, nmoves.val, True)
        # print("Energy after = %s kJ mol-1" % (system.energy().to(kJ_per_mol)))

        if save_coords.val:
            writeSystemData(system, moves, trajectory, i)

        mdmoves = moves.moves()[0]
        integrator = mdmoves.integrator()
        gradients = integrator.getGradients()
        outgradients.write("%5d %20.10f\n" % (i, gradients[i - 1]))
        grads[lambda_val.val].accumulate(gradients[i - 1])

    s2 = timer.elapsed() / 1000.0
    print("Simulation took %d s " % (s2 - s1))

    if os.path.exists("gradients.s3"):
        siregrads = Sire.Stream.load("gradients.s3")
    else:
        siregrads = Gradients()
    siregrads = siregrads + Gradients(grads)

    Sire.Stream.save(siregrads, "gradients.s3")

    if buffered_coords_freq.val > 0:
        system = clearBuffers(system)
        # Necessary to write correct restart
        system.mustNowRecalculateFromScratch()

    print("Backing up previous restart")
    cmd = "cp %s %s.previous" % (restart_file.val, restart_file.val)
    os.system(cmd)
    print("Saving new restart")
    Sire.Stream.save([system, moves], restart_file.val)
Esempio n. 7
0
def run():
    try:
        host = os.environ['HOSTNAME']
    except KeyError:
        host = "unknown"
    print("### Running Standard state correction calculation on %s ###" % host)

    if verbose.val:
        print(
            "###================= Simulation Parameters=====================###"
        )
        Parameter.printAll()
        print(
            "###===========================================================###\n"
        )

    #Constants
    delta = 0.10
    delta_over_two = delta / 2.0
    deltavol = delta * delta * delta
    kb = 0.001987
    T = 298
    kbT = kb * T
    beta = 1 / kbT
    ROT = 8 * pi**2
    Ztrans = 0.0
    Uavg = 0
    #import pdb; pdb.set_trace()
    #open the simfile and extract the reestraint dictionary
    #sim = open(simfile.val,"r")
    #for line in sim.readlines():
    #    if "dictionary" in line:
    #        sim_dictionary = line
    #        print("Found restraint dictionary: %s" % sim_dictionary)
    #    else:
    #        continue
    #
    #Sanity Check
    #if the dictionary was not found in the simfile exit from the script
    #if line==None:
    #    print("Error! Impossible to find dictionary restraint in sim.cfg")
    #    sys.exit(-1)
    #ast automatically transform a string into a dictionary
    #sim_dictionary=ast.literal_eval(sim_dictionary.strip("distance restraint dictionary="))

    sim_dictionary = distance_restraints_dict.val
    if sim_dictionary == {}:
        print(
            "Error, no distance restraints dictionary was found in the supplied config file. Abort."
        )
        sys.exit(-1)
    #now create a dictionary in this way:
    #dict[pairs] = {[Req,D,K] [coords] [coords]...}
    restr_dict = {}
    #create a list of host indexes to be used with mdtraj for alignment
    hosts = []
    for pairs in sim_dictionary:
        req = sim_dictionary[pairs][0]
        K = sim_dictionary[pairs][1]
        D = sim_dictionary[pairs][2]
        restr_dict[pairs] = [[req, K, D]]
        idx = max(pairs)
        hosts.append(idx)

    #load the trajectory
    start_frame = 1
    end_frame = 1000000000
    step_frame = stepframe.val
    #Check the extension of the topology file
    if ".top" in topfile.val:
        shutil.copy(topfile.val, "SYSTEM.prmtop")
        #top doesn't work with mdtraj
        top_file = "SYSTEM.prmtop"
    else:
        top_file = topfile.val

    print("Loading trajectory and topology files")
    #
    mdtraj_trajfile = mdtraj.load(trajfile.val, top=top_file)
    nframes = len(mdtraj_trajfile)
    if end_frame > (nframes - 1):
        end_frame = nframes - 1
    current_frame = start_frame

    #Aligning everything along the first frame
    print("Aligning frames along first frame of trajectory")
    aligned_traj = mdtraj_trajfile.superpose(mdtraj_trajfile,
                                             0,
                                             atom_indices=hosts)

    print("Processing frames")
    while (current_frame <= end_frame):
        #now for each lig:host pairs append the host coordinates
        for pairs in restr_dict:
            host_idx = max(pairs)
            restr_dict[pairs].append(aligned_traj.xyz[current_frame,
                                                      host_idx, :].tolist())

        current_frame += step_frame

    #now restr_dict has:
    #restr_dict[lig,host]=[ [req,K,D], [coords],[coords],...]
    print("Calculating average coordinates for restrained atoms")
    restr_dict = averageCoordinates(restr_dict)
    #now the restr_dict is:
    #restr_dict[pairs]=[[req,K,D],[avgx,avgy,avgz]]
    space = defineIntegrationDomain(restr_dict)
    if verbose.val:
        print("Integration space")
        print(space)

    #Grid creation
    Nx = int(round((space[1][0] - space[0][0]) / delta))
    Ny = int(round((space[1][0] - space[0][0]) / delta))
    Nz = int(round((space[1][0] - space[0][0]) / delta))
    #Constants
    print("Number of elements to be evaluated %d" % (Nx * Ny * Nz))
    print("Evaluation...")
    for i in range(0, Nx):
        for j in range(0, Ny):
            for k in range(0, Nz):
                x = space[0][0] + delta * i + delta_over_two
                y = space[0][1] + delta * j + delta_over_two
                z = space[0][2] + delta * k + delta_over_two

                counter = 0
                for pairs in restr_dict:
                    #restr_dict[pairs]=[[req,K,D],[coords]]
                    x_dict = float(restr_dict[pairs][1][0])
                    y_dict = float(restr_dict[pairs][1][1])
                    z_dict = float(restr_dict[pairs][1][2])

                    distance = ((x - x_dict)**2 + (y - y_dict)**2 +
                                (z - z_dict)**2)

                    upper_bound = restr_dict[pairs][0][1] + restr_dict[pairs][
                        0][2]
                    intmd_bound = restr_dict[pairs][0][1]
                    lower_bound = restr_dict[pairs][0][1] - restr_dict[pairs][
                        0][2]

                    if distance < upper_bound and distance > intmd_bound:
                        if counter == len(restr_dict) - 1:
                            U = 0.0
                        else:
                            counter += 1

                    elif distance < intmd_bound and distance > lower_bound:
                        if counter == len(restr_dict) - 1:
                            U = 0.0
                        else:
                            counter += 1
                    else:

                        dist = (math.sqrt(distance))
                        K = (restr_dict[pairs][0][1])
                        D = (restr_dict[pairs][0][2])
                        U = (K * (dist - D)**2)

                        break

                Boltz = math.exp(-beta * U) * deltavol
                Ztrans += (Boltz)
                Uavg += U * Boltz * ROT
    #Calculation of Ztot, Uavg, S, Frestraint:
    Ztot = Ztrans * ROT
    Uavg /= (Ztot)

    Zideal = 1661. * ROT
    Delta_F = -kbT * math.log(Ztot / Zideal)
    minTDelta_S = -T * (kb * math.log(Ztot / Zideal) + Uavg / T)

    print("Ztrans  = %8.5f Angstrom^3" % Ztrans)
    print("Free energy Cost of removing the restraint = %8.5f kcal/mol" %
          -Delta_F)

    #tidy up the folder by removing prmtop
    cmd = "rm SYSTEM.prmtop"
    os.system(cmd)