示例#1
0
def get_main_output(traj_file, out_filename, first_bp = 0, last_bp = -1):
	'''
	Take the trajectory file_name and the first and last base-pair to consider, then compute writhe and twist.
	'''
	# process input and do a basic sanity check
	l = readers.LorenzoReader(traj_file, 'prova.top')
	s = l.get_system()
	while s:
		base_pairs_pos = get_bp_pos(s, first_bp, last_bp)
		tangents = get_tangent_vectors_from_bp_pos(base_pairs_pos, s._box, True)
		#writhe = get_writhe_from_system(t_array)
		#twist = get_twist_from_system(t_array)
		circular = s._strands[0]._circular or s._strands[1]._circular
		pos, tan, vec = get_bp_pos_tan_vec_from_system(s, first_bp, last_bp)
		for b,p,t,tt in zip(base_pairs_pos[:-1], pos,tangents[:-1],tan):
			if np.linalg.norm(b-p) > 1e-3:
				print 'errorbp:',b,p
				sys.exit()
			if np.linalg.norm(t-tt) > 1e-3:
				print 'errorttt:',t,tt
				sys.exit()
		# compute twist and writhe
		tw, wr = get_twist_writhe_from_pos_tan_vec(pos,tan,vec,circular)
		print '%e\t%.4lf\t\t%.4lf\t\t%.4lf\t\t%.4lf'%(s._time, tw, wr, tw + wr, get_linking_number_from_system(s))
		s = l.get_system()
示例#2
0
def buildHisto(inputfile, conffile, topologyfile, ops, skip=1):
    import random
    output_bonds_exe = PROCESSPROGRAM
    # check for presence of files
    if not os.path.isfile(output_bonds_exe):
        raise IOError("Cannot find output_bonds program")
    for myfile in [inputfile, conffile, topologyfile]:
        if not os.path.isfile(myfile):
            raise ValueError('Histo.build(): could not open ' + myfile)
    if not isinstance(ops, OrderParameters):
        raise TypeError(
            'Histo.buidl(): last argument must be OrderParameters instance')
    if not isinstance(skip, int):
        raise TypeError(
            'Histo.buidl(): skip optional argument must be integer >= 1')
    if not skip >= 1:
        raise ValueError(
            'Histo.buidl(): skip optional argument must be integer >=1')
    # we scan through the trajectory, rebuild each configuration,
    # feed it to load_system and than process it with order_parameters
    rstr = ''.join(random.choice("abcdefg") for x in range(10))
    tmpcnf = '__' + rstr + '__.cnf'
    tmptop = '__' + rstr + '__.top'
    while os.path.isfile(tmpcnf) or os.path.isfile(tmptop):
        rstr = ''.join(random.choice("abcdefg") for x in range(10))
        tmpcnf = '__' + rstr + '__.cnf'
        tmptop = '__' + rstr + '__.top'

    ret = Histo()
    l = readers.LorenzoReader(conffile, topologyfile)
    s = l.get_system()
    nconf = 1
    while s:
        if nconf % skip == 0:
            s.print_lorenzo_output(tmpcnf, tmptop)
            s.map_nucleotides_to_strands()
            launchargs = [output_bonds_exe, inputfile, tmpcnf]
            myinput = subprocess.Popen(launchargs,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            if myinput.wait() != 0:
                raise IOError('Critical Error')
            s.read_all_interactions(myinput.stdout.readlines())

            state = ops.get_all_states(s)
            ret.update(state, 1.)

            #print >> sys.stderr, '#', nconf, 'done'

        nconf += 1
        # get next system
        s = l.get_system()
    os.remove(tmpcnf)
    os.remove(tmptop)
    return ret
    def run_simulation(self, inputfile, last_conf, dbg=0):
        self.success = -1
        while self.success == -1:
            #benchmark = time.time()
            #os.system(self.launchcommand + ' ' + inputfile + ' 2>/dev/null')
            launchargs = [self.launchcommand, inputfile]
            myinput = subprocess.Popen(launchargs,
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
            myinput.wait()
            self.runningtime += self.timeunit
            #benchmark = time.time() - benchmark
            #print ' Running program took ', benchmark
            #benchmark = time.time()
            reader = readers.LorenzoReader(last_conf, self.topologyfile)
            system = reader.get_system()

            system.map_nucleotides_to_strands()
            myinput = os.popen(PROCESSDIR + 'output_bonds ' + str(inputfile) +
                               " " + last_conf + ' 2>/dev/null')
            #print myinput.readlines()
            system.read_H_bonds(myinput.readlines())
            myinput.close()

            #self.order_pars.set_system(system)

            #self.order_pars.calculate_order_parameters()

            if (dbg != 0):
                print('State ', dbg, ' is ',
                      self.order_pars.get_state(dbg, system))
            #print self.stop, ' is ', self.order_pars.get_order_parameter(self.stop)
            #print self.Astate, ' is' , self.order_pars.get_order_parameter(self.Astate)
            #print self.init, ' is ', self.order_pars.get_order_parameter(self.init)

            #if(self.order_pars.get_order_parameter('MINDIST_0_3') > 10.0):
            #	print "These are the following parameters: "
            #	g = self.order_pars.get_all_parameters()
            #	print g
            #print self.stop, ' is ', self.order_pars.get_order_parameter(self.stop)

            if (
                    self.order_pars.get_state(self.Astate, system)
            ):  #This means the system fell down to Astate before reaching stop order parameter
                self.success = 0

            if (self.order_pars.get_state(self.stop,
                                          system)):  #This means success
                self.success = 1
            #print 'Success is ', self.success
            #benchmark = time.time() - benchmark
            #print 'Evalloop took ',benchmark
        return self.success
def check_domain_status(conffile, topologyfile, a1, b1, a2, b2):
    r = readers.LorenzoReader(conffile, topologyfile)
    mysystem = r.get_system()
    mysystem.map_nucleotides_to_strands()
    print PROCESSDIR + 'output_bonds.py'
    launchargs = [PROCESSDIR + 'output_bonds.py', inputfile, conffile]
    myinput = subprocess.Popen(launchargs,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    mysystem.read_H_bonds(myinput.stdout.readlines())
    #a1 paried with b1, a2 with b2
    print 'Launched my inpit and got', inputfile, conffile
    bindex = b1
    totbonds = 0
    for i in range(a1, a2 + 1):
        if bindex in mysystem._nucleotides[i].interactions:
            totbonds += 1
        bindex -= 1
    return totbonds, a2 - a1 + 1
示例#5
0
    def __import_trajectory(self):
        """
        Import system trajectory into Runner object
            self.run_trajectory --- List of systems.
        """
        conffile = self.run_input_options['trajectory_file']
        topologyfile = self.run_input_options['topology']
        try:
            myreader = readers.LorenzoReader(conffile, topologyfile)
            mysystem = myreader.get_system()
        except (NameError):
            logger.error("Trajectory cannot be read (%s)", self.input_filepath)
            return False

        self.trajectory = []
        while mysystem != False:
            self.run_trajectory.append(mysystem)
            mysystem = myreader.get_system()
        return True
def gen_force_file(conffile, topology, bond_pairs, no_of_w, out_file_name):
    r = readers.LorenzoReader(conffile, topology)
    s = r.get_system()
    counter = 0
    outfile = open(out_file_name, 'w')
    for pair in bond_pairs:
        a = pair[0]
        b = pair[1]
        if (s._nucleotides[a]._btype + s._nucleotides[b]._btype != 3):
            print 'Error, bases ', a, b, ' are not complementary'
        ous = '{ \ntype = mutual_trap\nparticle = %d\nstiff = 0.9\nr0 = 1.2\nref_particle = %d\nPBC=1\n}\n' % (
            a, b)
        ous += '{ \ntype = mutual_trap\nparticle = %d\nstiff = 0.9\nr0 = 1.2\nref_particle = %d\nPBC=1\n}\n' % (
            b, a)
        outfile.write(ous)
        counter = counter + 1
        print 'Using mutual trap ', a, b
        if (counter > no_of_w):
            outfile.close()
            return
    outfile.close()
示例#7
0
def load_system(inputfile, conffile, topologyfile):
    reader = readers.LorenzoReader(conffile, topologyfile)
    system = reader.get_system()
    if system == False:
        raise IOError('Crashed when trying to read configuration file ' +
                      str(conffile) + ' and topology file ' +
                      str(topologyfile))
    system.map_nucleotides_to_strands()
    #print 'LAUNCHING',PROCESSDIR + "output_bonds.py"
    #os.system(PROCESSDIR + "output_bonds.py")
    if not os.path.isfile(PROCESSPROGRAM):
        raise IOError("Cannot execute output_bonds program " + PROCESSPROGRAM)
    launchargs = [PROCESSPROGRAM, inputfile, conffile]
    myinput = subprocess.Popen(launchargs,
                               stdout=subprocess.PIPE,
                               stderr=subprocess.PIPE)
    if myinput.wait() != 0:
        for line in myinput.stderr.readlines():
            print(line, )
        raise IOError('Critical Error')
    system.read_all_interactions(myinput.stdout.readlines())
    return system
    base.Logger.log("Usage is %s configuration topology [howmany] [box_side]" % sys.argv[0], base.Logger.CRITICAL)
    sys.exit()

conf = sys.argv[1]
top = sys.argv[2]
howmany = 2
box_side = 100.
if len (sys.argv) > 3:
    howmany = int(sys.argv[3])
if len (sys.argv) > 4:
    box_side = float(sys.argv[4])

systems = []
for i in range(0, howmany):
    base.Logger.log ("# Reading system %i" % i)
    l1 = readers.LorenzoReader(conf, top)
    systems.append (l1.get_system())

base.Logger.log ("# Bringing nucleotides in box")
# bring the nucleotides back in the box
for S in systems:

    myr = S._strands[0].cm_pos
    for s in S._strands:
        s.translate (-myr)

    base.Logger.log ("   # Bringing nucleotides in box or another system...")
    for s in S._strands:
        diff = np.rint(s.cm_pos / S._box ) * S._box
        s.translate (-diff)
示例#9
0
    line = line.lstrip()
    if not line.startswith('#'):
        if "topology" in line:
            topologyfile = line.split('=')[1].replace(' ',
                                                      '').replace('\n', '')

#strand ids
sid1 = int(sys.argv[3])
sid2 = int(sys.argv[4])

if (sid1 > sid2):
    pom = sid2
    sid2 = sid1
    sid1 = pom

myreader = readers.LorenzoReader(conffile, topologyfile)
mysystem = myreader.get_system()

if not os.path.isfile(PROCESSPROGRAM):
    print "Cannot execute output_bonds program. Please make sure to compile DNAnalysis in ../bin/ directory"
    sys.exit(1)

counter = 0

tempfile_obj = tempfile.NamedTemporaryFile()
launchcommand = inputfile + ' trajectory_file=' + tempfile_obj.name + ' ' + command_for_data

launchargs = [
    PROCESSPROGRAM, inputfile, 'trajectory_file=' + tempfile_obj.name,
    command_for_data
]
示例#10
0
    print "USAGE:"
    print "\t%s trajectory topology skip" % sys.argv[0]
    sys.exit(1)


try:
    traj = sys.argv[1]
    print traj
    topo = sys.argv[2]
    print topo
    skip = int(sys.argv[3])
    print skip
except:
    print_usage()

l = readers.LorenzoReader(traj, topo)
s = l.get_system(N_skip=skip)

base.Logger.log('Writing to decimated.dat')
base.Logger.log('skipping %d confs' % (skip))
out = open('decimated.dat', 'w')
niter = 1
while s:
    base.Logger.log("Working on conf %i..." % niter, base.Logger.INFO)
    s = l.get_system(N_skip=skip)
    if s:
        s.print_lorenzo_output('tmpdec.dat', 'tmpdec.top')
        inp = open('tmpdec.dat', 'r')
        for line in inp.readlines():
            out.write(line)
        inp.close()
示例#11
0
import origami_utils as oru
import numpy as np
import sys, readers, base

# usage: python *.py conf top virt2nuc conf top
l = readers.LorenzoReader(sys.argv[1], sys.argv[2])
s = l.get_system()
o = oru.Origami(system=s, cad2cuda_file=sys.argv[3])
n = s._N
l2 = readers.LorenzoReader(sys.argv[4], sys.argv[5])
s2 = l2.get_system()
n2 = s2._N
assert n2 % n == 0
n_monomer = n2 / n
forcefile = open('pull.force', 'w')
eqforcefile = open('eq.force', 'w')
inputfile = open('data_input', 'w')
inputfile.write(
    'data_output_1 = {\n\tprint_every = 1e4\n\tname = pull.dist\n\tcol_1 = {\n\t\ttype = step\n\t}\n'
)

pairs = [[vh1, vb1, vh2, vb2, k, k + 1]
         for (vh1, vh2) in zip(range(28, 18, -1), range(30, 40))
         for (vb1, vb2) in ([127, 128], [170, 169])
         for k in range(n_monomer - 1)]

for idx, item in enumerate(pairs):
    #print item[0], item[1], o.get_nucleotides(item[0],item[1],type = 'stap')
    #print item[2], item[3], o.get_nucleotides(item[2],item[3],type = 'stap')
    nuc1idx = o.get_nucleotides(item[0], item[1], type='scaf')[0] + n * item[4]
    nuc2idx = o.get_nucleotides(item[2], item[3], type='scaf')[0] + n * item[5]
def main():
    if len(sys.argv) < 3:
        base.Logger.log(
            "Usage is %s configuration topology [N_skip]" % sys.argv[0],
            base.Logger.CRITICAL)
        exit()

    if len(sys.argv) > 3:
        N_skip = int(sys.argv[3])
    else:
        N_skip = 0

    output = sys.argv[1] + ".vbond"

    np.random.seed(39823)

    l = readers.LorenzoReader(sys.argv[1], sys.argv[2])
    s = l.get_system(N_skip=N_skip)
    box = s._box

    # we keep fixed strand 0 and 1 and we insert randomly strands 2 and 3 while
    # keeping their internal degrees of freedom fixed
    diff = s._strands[1].cm_pos - s._strands[0].cm_pos
    diff = box * np.rint(diff / box)
    s._strands[1].cm_pos = s._strands[1].cm_pos - diff
    initial = (s._strands[0]._nucleotides[0].cm_pos +
               s._strands[1]._nucleotides[-1].cm_pos) / 2.
    radius = s._strands[0]._nucleotides[0].cm_pos - s._strands[1]._nucleotides[
        -1].cm_pos
    radius = base.CXST_RCHIGH + 0.5 * np.sqrt(np.dot(radius, radius))

    f = open(output, "w")
    V4pi = 4 * np.pi * (4 * np.pi * radius**3 / 3.)
    f.write("%e\n" % V4pi)
    f.close()

    diff = s._strands[3].cm_pos - s._strands[2].cm_pos
    diff = box * np.rint(diff / box)
    s._strands[3].cm_pos = s._strands[3].cm_pos - diff
    found = counter = 0

    while found < MAX_FOUND:
        bring_in_dstrand(s._strands[2], s._strands[3], initial, radius)

        E = strand_dstrand_energy(s._strands[2], s._strands[0], s._strands[1],
                                  box)
        if E < 2.:
            E += strand_dstrand_energy(s._strands[3], s._strands[0],
                                       s._strands[1], box)

        if E < 0.:
            print(E)
            f = open(output, "a")
            f.write("%d %e\n" % (counter, E))
            f.close()
            found += 1

        counter += 1

    s.print_crepy_output("prova2.mgl", same_colors=True)

    # cycle over the trajectory
    '''
    counter = 0
    while s:
    base.Logger.log("Analyzed configuration", base.Logger.INFO)
    s = l.get_system(N_skip=N_skip)
    counter += 1
    '''

    base.Logger.log("Output printed on '%s'" % output, base.Logger.INFO)
示例#13
0
try:
	confs = sys.argv[1::2]
	tops = sys.argv[2::2]
except:
	base.Logger.log("Usage is %s configuration1 topology1 configuration2 topology2 [configuration3 topology3] ... " % sys.argv[0], base.Logger.CRITICAL)
	sys.exit(-1)

if len(tops) != len(confs):
	base.Logger.log ("There must be the same numbers of configurations and topologies", base.Logger.CRITICAL)
	sys.exit(-1)

systems = []
for i, conf in enumerate(confs):
	top = tops[i]
	base.Logger.log ("Working on %s %s" % (conf, top))
	systems.append (readers.LorenzoReader (conf, top).get_system())

assert (len(systems) == len(confs))

base.Logger.log ("# Bringing nucleotides in box")
# bring the nucleotides back in the box
for S in systems:
    base.Logger.log ("   # Bringing nucleotides in box or another system...")
    for s in S._strands:
        diff = np.rint(s.cm_pos / S._box ) * S._box
        s.translate (-diff)

# the biggest box has to be the first system, so we reshuffle them
has_max_box = 0
for S in systems[1:]:
    for k in [0, 1, 2]:
示例#14
0
plect_file = open("miekbin/plectoneme624.dat", "r").readlines()
"""
circles
"""
#top = "miekbin/circle_400-Lk2.top"
#conf = "miekbin/last_conf_TD.dat"
##conf = "miekbin/circle_400-Lk2.dat"

#traj_file = "miekbin/trajectory_300-Lk7.dat"
##init_conf = "miekbin/last_conf.dat"
#init_conf = "miekbin/circle_300-Lk7.dat"
#top = "miekbin/circle_300-Lk7.top"

num_lines = sum(1 for line in plect_file)

l = readers.LorenzoReader(init_conf, top)
s = l.get_system()
strand1 = s._strands[0]
strand2 = s._strands[1]
bp = len(strand1._nucleotides)
steps = 251000000  #number of simulation steps
printed_steps = num_lines  #results printed every steps
lines_per_print = int(
    steps / printed_steps)  #number of steps wanted for this calculation
print(printed_steps)
calc_steps = 10
npoints = 1000
'''
Converts a trajectory file into mutiple configuration files so that they can 
be passed through various routines
'''
示例#15
0
import os
import base
import readers
import numpy as np


l = readers.LorenzoReader("prova.conf", "prova.top")
s = l.get_system()
s.map_nucleotides_to_strands()
system = base.System(s._box, s._time)
init = []

break_index = 0

for strand in s._strands:
    break_index = 0
    for i in range(len(strand._nucleotides)-1):
        dr = strand._nucleotides[i].distance(strand._nucleotides[i+1],box=system._box)
        d = np.sqrt(np.dot(dr,dr))
        if d > 0.7525+0.25:
            init.append([strand._nucleotides[i].index,strand._nucleotides[i+1].index,d])
            #if strand.get_slice(break_index, i).N != 0:
            system.add_strand(strand.get_slice(break_index, i+1), check_overlap=False)
            break_index = i+1
        #if strand.get_slice(break_index, strand._last-strand._first).N != 0:
    system.add_strand(strand.get_slice(break_index, strand._last-strand._first+1),check_overlap=False)
    if break_index == 0 and strand._circular==True:
        system._strands[-1]._circular = True

r = 0
while True:
示例#16
0
    sys.exit(-2)

if len(files) < 2:
    base.Logger.log(
        "Usage is %s [-s] [-c domain_file] configuration topology [output]" %
        sys.argv[0] +
        "\n-s colours bases by their type\n-c allows colouring of backbones by domain\ndomain_file should assign domains to all bases, in the format:\n#a,#b,#c,#d,\n#e,#f,#g,#h,\netc\nwhere strand #a, bases #b->#c have a domain value of #d;\nstrand #e, bases #f->#g have a domain value of #h etc.\nAll bases of a certain domain will be the same colour, more than\none region of DNA can be tagged as a certain domain (eg., #d=#h is allowed).\nTo label two domains #d and #h as complementary, set #h=-#d.\nSimilar colours will be used for two complementary domains.\nThe system can handle 8 distinctly coloured domains and 8 complementary domains,\nusing any more will lead to repeated colours.\nAny base not assigned to a domain will be coloured sandy brown.",
        base.Logger.CRITICAL)
    sys.exit()

if len(files) > 2:
    output = files[2]
else:
    output = files[0] + ".pdb"

l = readers.LorenzoReader(files[0], files[1])
s = l.get_system()
cdm20 = True
append = False
domain = []
domains = False
domain_file = ''
colour_by_seq = False
for opt, arg in args:
    if opt in ('-c', 'colour_by_domain'):
        domains = True
        domain_file = arg
    elif opt in ('-s', 'seq_base_colour'):
        colour_by_seq = True
    else:
        base.Logger.log("Option '%s' not recognised" % opt, base.Logger.INFO)
示例#17
0
# NB the current procedure is to make a reference file with every possible correctly bonded pair (i.e. the duplication of staple strands is accounted for with this file). The file is generated using extract_ref.py 29/10/12

import readers
import base
import numpy as np
import sys

region_width = 16 # number of base pairs in a region
hb_threshold = 8 # this number of hbonds or more between a staple region and a scaffold region to count as attached

if len(sys.argv) < 5:
    base.Logger.log("Usage is %s configuration topology reference_h_bonds_file h_bonds_file [duplicates]" % sys.argv[0], base.Logger.CRITICAL)
    sys.exit()

base.Logger.log("Using region width %d, hydrogen bond count threshold %d" %(region_width, hb_threshold))
r = readers.LorenzoReader(sys.argv[1], sys.argv[2])
ss = r.get_system()
rawref = sys.argv[3]
rawdat = sys.argv[4]

check_duplicates = False
if len(sys.argv) > 5:
    if sys.argv[5] == "duplicates":
        base.Logger.log("checking for duplicates", base.Logger.INFO)
        check_duplicates = True

outfile = "assembly_op.dat"

lens = []
for strand in ss._strands:
    lens.append(strand.get_length())
示例#18
0
import sys
import subprocess

PROCESSDIR = os.path.join(os.path.dirname(__file__), "process_data/")

if len(sys.argv) < 4:
    base.Logger.log("Usage is %s input configuration topology [output]" % sys.argv[0], base.Logger.CRITICAL)
    sys.exit()

inputfile = sys.argv[1]

if len(sys.argv) > 4:
    output = sys.argv[4]
else: output = sys.argv[2] + ".dbk"
    
l = readers.LorenzoReader(sys.argv[2], sys.argv[3])
s = l.get_system()
s.map_nucleotides_to_strands()
launchargs = [PROCESSDIR + 'output_bonds', inputfile, sys.argv[2], "0"]
myinput = subprocess.Popen(launchargs,stdout=subprocess.PIPE, stderr=subprocess.PIPE) 
s.read_H_bonds(myinput.stdout.readlines())

for line in myinput.stderr.readlines():
      if "CRITICAL" in line:
        base.Logger.log("Error running output_bonds'", base.Logger.INFO)

s.print_dot_bracket_output(output)

base.Logger.log("Output printed on '%s'" % output, base.Logger.INFO)