Beispiel #1
0
def withPbc(testfile="supper.pdb", args=''):
    a = Pdb(testfile)
    b = a.parser()
    b.assignAtomTypes()
    b.assignEleTypes()
    b.assignIdNumbers()
    b.toFrac()
    #b.translate(12.0, "z")
    toXyz(b, "out.xyz")
    toMusic(b, "out.music")
    if len(b.pbc) == 0:
        b.geotag = "BIOGRF 200"
    else:
        b.geotag = "XTLGRF 200"
    toReaxLammps(b, "lammps.data")
    toGeo(b, "sim.geo")
    toMsd(b, "sim.msd")
    toPoscar(b, )
    toCfg(b, )
    toJdft(b, )
    toTowheecoords(b)
    if args:
        if args.element:
            toPdb(b, "out.pdb", 1)
    else:
        toPdb(b, "out.pdb")
Beispiel #2
0
def monte_carlo():
    """ a python shell for Monte Carlo reaxFF simulation'
    """
    welcome()
    mc = MC()
    # read the pdb file
    print("Reading input pdbfile")
    pdbfile = "model.pdb"
    a = Pdb(pdbfile)
    sim = a.parser()
    sim.assignEleTypes()
    sim.assignAtomTypes()
    # read the control file
    read_control(mc)
    # read index file
    indexfile = "index.ndx"
    grp = Group(indexfile)

    # system init
    log = open(mc.log, "w")

    if mc.swap_flag == 1:
        assign_swap_grps(mc, sim, grp)

    print "Starting simulation:"
    for i in range(mc.nsteps):
        print("Running step %d" % i)
        log.write("step %-6d" % i)
        mc_moves(mc, sim, grp, log)
        shutil.copy("out.data", "out.data.%06d" % i)
        shutil.copy("dump.lmp", "dump.lmp.%06d" % i)

    toReaxLammps(sim, "lammps.data.final")
    log.close()
Beispiel #3
0
def test():
    testfile = "e_2_pdb.pdb"
    a = Pdb(testfile)
    b = a.parser()
    b.assignAtomTypes()
    b.pbc = [20.80, 20.80, 20.80, 90.0, 90.0, 90.0]
    toReaxLammps(b)
Beispiel #4
0
def pdbIntoRunningThread(tid):
    from pdb import Pdb
    #from IPython.Debugger import Pdb

    pdb = Pdb()
    pdb.reset()

    import threading
    injectEvent = threading.Event()

    def inject_tracefunc(frame, ev, arg):
        injectEvent.set()
        pdb.interaction(frame, None)
        return pdb.trace_dispatch

    sys.settrace(dummytracer)  # set some dummy. required by setTraceOfThread

    # go into loop. in some cases, it doesn't seem to work for some reason...
    while not injectEvent.isSet():
        setTraceOfThread(tid, inject_tracefunc)

        # Wait until we got into the inject_tracefunc.
        # This may be important as there is a chance that some of these
        # objects will get freed before they are used. (Which is probably
        # some other refcounting bug somewhere.)
        injectEvent.wait(1)
Beispiel #5
0
 def to_pdb(self, atomfilter=lambda atom: True):
     "Returns a Pdb object containing the Atom objects within this ResidueList"
     p = Pdb(self.code, [])
     for res in self:
         for atm in res:
             if atomfilter(atm):
                 p.data.append(atm)
     return p
Beispiel #6
0
 def _recursive(self, g, l):
     """Inspect wdb with pdb"""
     # Inspect curent debugger vars through pdb
     sys.settrace(None)
     from pdb import Pdb
     p = Pdb()
     sys.call_tracing(p.run, ('1/0', g, l))
     sys.settrace(self.trace_dispatch)
     self.lastcmd = p.lastcmd
Beispiel #7
0
def main():
    port_var = 'MYSTIKOS_PDB_PORT'

    port = os.environ.get(port_var)
    if not port:
        print(
            'MYSTIKOS_PDB_PORT environment variable not set. Defaulting to port 5678'
        )
        port = 5678
    else:
        port = int(port)

    print('Mystikos pdb waiting for connections at port %d' % port)
    sys.stdout.flush()

    host = '127.0.0.1'
    client_socket = socket.create_server((host, port),
                                         family=socket.AF_INET,
                                         reuse_port=False)

    client_socket.listen(1)
    connection, address = client_socket.accept()
    fd = connection.makefile('rw')

    args = sys.argv[1:]
    mainpyfile = args[0]
    run_as_module = False

    if args[0] == '-m':
        run_as_module = True
        mainpyfile = args[1]
        args = args[1:]

    # Update args
    sys.argv[:] = args

    if not run_as_module:
        mainpyfile = os.path.realpath(mainpyfile)
        # Replace pdb's dir with script's dir in front of module search path.
        sys.path[0] = os.path.dirname(mainpyfile)
    else:
        runpy._get_module_details(mainpyfile)

    pdb = Pdb(completekey='tab', stdin=fd, stdout=fd)
    # Alias n, c, s commands to show source listing.
    pdb.rcLines.extend(
        ['alias n n;; l .', 'alias c c;; l .', 'alias s s;; l .'])
    try:
        if run_as_module:
            pdb._runmodule(mainpyfile)
        else:
            pdb._runscript(mainpyfile)
    except:
        pass

    connection.close()
    client_socket.close()
Beispiel #8
0
def read_pdb(pdbfile):
    """read pdb file
    """

    a = Pdb(pdbfile)
    b = a.parser()
    b.assignAtomTypes()
    b.assignEleTypes()
    return b
Beispiel #9
0
def start_x(a, b):
    from pdb import Pdb
    import os
    from pty import openpty

    (master, slave) = openpty()
    cmd = "rxvt -pty-fd {} &".format(master)
    os.system(cmd)
    io = os.fdopen(slave, "r+b")
    Pdb(stdin=io, stdout=io).set_trace()
Beispiel #10
0
def read_pdb(control):
    print "    Reading pdb file ..."
    a = Pdb(control.pdbfile)
    b = a.parser()
    b.assignAtomTypes2()
    print "        cell parameters:"
    print "            a = %8.3f: "%b.pbc[0]
    print "            a = %8.3f: "%b.pbc[1]
    print "            a = %8.3f: "%b.pbc[2]
    return b
Beispiel #11
0
def ddb(rank=0):
    """
    Distributed Debugger that will insert a py debugger on rank `rank` and
    pause all other distributed processes until debugging is complete.
    :param rank:
    """
    if torch.distributed.get_rank() == rank:
        from pdb import Pdb
        pdb = Pdb(skip=["torch.distributed.*"])
        pdb.set_trace(sys._getframe().f_back)
    torch.distributed.barrier()
Beispiel #12
0
 def debug_func(self, *args, **kwargs):
     if not self.on_error:
         return runcall(self.func, *args, **kwargs)
     try:
         if has_ipdb:
             with launch_ipdb_on_exception():
                 return self.func(*args, **kwargs)
         else:
             return self.func(*args, **kwargs)
     except Exception as e:
         traceback.print_exc(file=sys.stderr)
         Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__).set_trace()
Beispiel #13
0
 def __init__(self, fn):
     ''' generate a CallTree with the given function '''
     assert callable(
         fn), 'CallTree needs a function as its argument, not {}'.format(fn)
     sio = StringIO()
     p = Pdb(stdout=sio)
     for i in range(512):
         p.cmdqueue.append('s')
     p.cmdqueue.append('q')
     p.runcall(fn)
     sio.seek(0)
     self.target_fn = fn
     self.pdb_text = sio.read()
Beispiel #14
0
def set_trace(**kwargs):
    """Debugger hook that works inside worker processes.

    Set PYTHONBREAKPOINT=edb.common.debug.set_trace, and this will be triggered
    by `breakpoint()`.

    Unfortunately readline doesn't work when not using stdin itself,
    so try running the server wrapped with `rlwrap.`
    """
    from pdb import Pdb
    new_stdin = open("/dev/tty", "r")
    Pdb(stdin=new_stdin, stdout=sys.stdout).set_trace(sys._getframe().f_back,
                                                      **kwargs)
Beispiel #15
0
def pdb_wrapper(this_frame):
    DEBUG_INTERNAL = EnvConfig().get('DEBUG_INTERNAL')
    _pdb = Pdb() if DEBUG_INTERNAL else _Pdb()

    def wrapper():
        if DEBUG_INTERNAL:
            _pdb.set_trace(sys._getframe(3))
        else:
            # Frame to be stepped in is not retrieved by `sys._getframe()`,
            # so that we don't need to pass its `f_back` into `set_trace()`
            _pdb.set_trace(this_frame)

    return wrapper
Beispiel #16
0
def test_ensure_file_can_write_unicode():
    import io
    from pdb import DefaultConfig, Pdb

    out = io.BytesIO(b"")
    stdout = io.TextIOWrapper(out, encoding="latin1")

    p = Pdb(Config=DefaultConfig, stdout=stdout)

    assert p.stdout.stream is out

    p.stdout.write(u"test äöüß")
    out.seek(0)
    assert out.read().decode("utf-8") == u"test äöüß"
Beispiel #17
0
def test_config_terminalformatter(monkeypatch):
    from pdb import DefaultConfig, Pdb
    import pygments.formatters

    assert DefaultConfig.use_terminal256formatter is None

    monkeypatch.setenv("TERM", "")

    p = Pdb(Config=DefaultConfig)
    assert p._init_pygments() is True
    assert isinstance(p._fmt, pygments.formatters.TerminalFormatter)

    p = Pdb(Config=DefaultConfig)
    monkeypatch.setenv("TERM", "xterm-256color")
    assert p._init_pygments() is True
    assert isinstance(p._fmt, pygments.formatters.Terminal256Formatter)

    class Config(DefaultConfig):
        use_terminal256formatter = False

    p = Pdb(Config=Config)
    assert p._init_pygments() is True
    assert isinstance(p._fmt, pygments.formatters.TerminalFormatter)
Beispiel #18
0
def getBoxl(pdbfile, n, density):

    density = density * 1000
    a = Pdb(pdbfile)
    b = a.parser()
    b.getMass()
    mass = b.mass
    print "Molecule mass: ", mass
    total = mass * n
    vol = total * amc / density * 1e30  # here length is in A
    print "Volume: ", vol
    l = math.pow(vol, 1 / 3.0)
    print "box a, b, c =", l

    return l
Beispiel #19
0
def fortranOut(testfile="output.pdb", args=''):
    a = Pdb(testfile)
    b = a.parser()
    b.assignAtomTypes()
    b.assignEleTypes()
    b.pbc = [50.00, 50.00, 50.00, 90.0, 90.0, 90.0]
    b.geotag = "XTLGRF 200"
    toReaxLammps(b, "lammps.data")
    if args:
        if args.element:
            toPdb(b, "out.pdb", 1)
    else:
        toPdb(b, "out.pdb")
    toMsd(b, "sim.msd")
    toGeo(b, "sim.geo")
Beispiel #20
0
 def __init__(self, pdb, code=None):
     "Takes a list or tuple or Pdb object as argument. Otherwise passes the argument to Pdb() first."
     if not pdb:
         pass
     elif isinstance(pdb, list) or isinstance(pdb, tuple):
         for r in pdb:
             self.append(r)
     else:
         if not isinstance(pdb, Pdb):
             pdb = Pdb(pdb)
         for r in pdb.xresidues():
             self.append(Residue(r))
         if pdb.code:
             self.code = pdb.code
     if code is not None:
         self.code = code
Beispiel #21
0
def main():
    if len(sys.argv) < 4:
        usage()
    else:
        pdbfile = sys.argv[1]
        n = int(sys.argv[2])
        density = float(sys.argv[3])
        l = getBoxl(pdbfile, n, density)
        writeInp(pdbfile, n, l)
        os.system("packmol < inp")
        if os.path.exists("sim.pdb"):
            os.system("editconf -f sim.pdb -o sim.pdb -box %.4f" % (l / 10))
            a = Pdb("sim.pdb")
            b = a.parser()
            b.assignAtomTypes()
            toReaxLammps(b)
Beispiel #22
0
class BreakpointSection(object):
    classProvides(ISectionBlueprint)
    implements(ISection)

    pdb = Pdb()

    def __init__(self, transmogrifier, name, options, previous):
        condition = options['condition']
        self.condition = Condition(condition, transmogrifier, name, options)
        self.previous = previous

    def __iter__(self):
        for item in self.previous:
            if self.condition(item):
                self.pdb.set_trace(sys._getframe().f_back)  # Break!
            yield item
Beispiel #23
0
def eval_and_count_steps(str, local_vars):
    # This function works by hijacking the python debugger, pdb.
    stepcount = [0]

    class consolemock:
        def readline(self):
            stepcount[0] += 1
            return "s"  # "take 1 Step"
        def write(self, *args):
            return
        def flush(self):
            return

    runner = Pdb(stdin=consolemock(), stdout=consolemock())
    result = runner.runeval(str, locals = local_vars)

    return result, stepcount[0]
Beispiel #24
0
    def GetSequenceFromPdb(self, tmpPath='.', localPdb='', verbose=False):

        for i, prot in self.analogs.iterrows():

            pdb2name = prot['pdb']
            myChain = prot['chain']

            if verbose:
                print(" reading file " + tmpPath + '/' + pdb2name + '.pdb')

            pdb = Pdb()
            if not path.isfile(tmpPath + '/' + pdb2name + '.pdb'):
                if localPdb == '':
                    if verbose: print(" downloading file")
                    pdb.Download(pdbCode=pdb2name, verbose=True, path=tmpPath)
                    pdb.ReadFile(tmpPath + '/' + pdb2name + '.pdb',
                                 skipNonAminoacid=True)
                else:
                    if verbose:
                        print(" copying file from local directory " + localPdb)
                    pdb.TakeLocalFiles(pdbCode=pdb2name,
                                       sourceDir=localPdb,
                                       targetDir=tmpPath)
                    pdb.ReadFile(tmpPath + '/' + pdb2name + '.pdb',
                                 skipNonAminoacid=True)
            else:
                pdb.ReadFile(tmpPath + '/' + pdb2name + '.pdb',
                             skipNonAminoacid=True)

            seq = pdb.GetSequence(chain=myChain)

            self.analogs.at[i, 'sequence'] = seq

            self.analogs.at[i, 'organism_id'] = pdb.GetKey('ORGANISM_TAXID')
            self.analogs.at[i, 'organism_scientific'] = pdb.GetKey(
                'ORGANISM_SCIENTIFIC')

            if len(seq) == 0:
                sys.exit("ERROR: Empty sequence for pdb " + pdb2name + myChain)

            if verbose:
                print(' has read pdb ' + pdb2name + myChain + ' (length=' +
                      str(len(seq)) + ')')
                print(seq)

            del pdb
Beispiel #25
0
def make_ndx(atp, lo, hi):
    assert lo < hi
    a = Pdb("model.pdb")
    b = a.parser()
    b.assignEleTypes()
    b.assignAtomTypes()
    n = 0
    counter = 0
    for i in b.atoms:
        if i.element == atp:
            z = i.x[2]
            if z > lo and z <= hi:
                print "%5d" % (n + 1),
                if (counter + 1) % 15 == 0:
                    print ''
                counter += 1
        n += 1
    print ''
Beispiel #26
0
    def __init__(self,
                 refPdb,
                 refChain,
                 tmpPath='.',
                 localPdb='',
                 verbose=False):

        self.analogs = pd.DataFrame(columns=[
            'pdb', 'chain', 'z', 'rmsd', 'lali', 'nres', 'id', 'title',
            'sequence', 'aligned', 'organism_id', 'organism_scientific'
        ])
        self.equivalences = pd.DataFrame(
            columns=['pdb2', 'chain2', 'from1', 'to1', 'from2', 'to2'])
        self.refPdb = refPdb
        self.refChain = refChain
        self.refSequence = ''
        self.refLength = 0
        self.analogs['organism_id'] = ''

        if verbose: print('Creating Dali object for pdb ' + refPdb + refChain)

        pdb = Pdb()

        if not path.isdir(tmpPath):
            try:
                mkdir(tmpPath)
            except:
                sys.exit('Cannot make dir ' + tmpPath)

        if not path.isfile(tmpPath + '/' + refPdb + '.pdb'):
            if localPdb == '':
                pdb.Download(pdbCode=refPdb, verbose=verbose, path=tmpPath)
            else:
                pdb.TakeLocalFiles(pdbCode=refPdb,
                                   sourceDir=localPdb,
                                   targetDir=tmpPath)

        pdb.ReadFile(tmpPath + '/' + refPdb + '.pdb', skipNonAminoacid=True)
        self.refSequence = pdb.GetSequence(chain=refChain)
        del pdb
        self.refLength = len(self.refSequence)

        if verbose:
            print('Length of reference sequence is ' + str(self.refLength))
Beispiel #27
0
 def __init__(self, config, num):
     self.name, self.conformation, self.location = config['ligand'][num]
     self.selection = 'name CA and not HETERO'
     try:
         pdb = Pdb(self.name, selection=self.selection)
         atoms = pdb.atoms.models()[0]
         atoms.update_sec(pdb.dssp())
     except InvalidPdbCode:
         seq = self.name.split(':')[0]
         check_peptide_sequence(seq)
         atoms = Atoms(self.name)
     atoms.set_bfac(0.0)
     Atoms.__init__(self, atoms)
     # checks the input peptide sequence for non-standard amino acids.
     rev_dct = dict(map(reversed, AA_NAMES.items()))
     [
         check_peptide_sequence(rev_dct[peptide.resname])
         for peptide in atoms.atoms
     ]
Beispiel #28
0
    def __init__(self, config):
        name = config['receptor']
        selection = 'name CA and not HETERO'
        pdb = Pdb(name, selection=selection)
        atoms = pdb.atoms.models()[0]

        token = config.get('receptor_flexibility')
        if token:
            try:
                bfac = float(token)
                atoms.set_bfac(bfac)
            except ValueError:
                if token.lower() == 'bf':
                    pass
                elif token.lower() == 'bfi':
                    for a in atoms:
                        if a.bfac > 1.:
                            a.bfac = 0.
                        else:
                            a.bfac = 1. - a.bfac
                elif exists(token):
                    d, de = self.read_flexibility(token)
                    atoms.update_bfac(d, de)
                elif exists(join(config['work_dir'], token)):
                    d, de = self.read_flexibility(
                        join(config['work_dir'], token))
                    atoms.update_bfac(d, de)
                else:
                    raise Exception(
                        'Invalid receptor_flexibility setting in \'%s\'!!!' %
                        token)
        else:
            atoms.set_bfac(1.0)

        self.old_ids = atoms.update_sec(
            pdb.dssp(dssp_command=config['dssp_command'])).fix_broken_chains()
        self.new_ids = {v: k for k, v in self.old_ids.items()}
        Atoms.__init__(self, atoms)
        self.center = self.cent_of_mass()
        self.dimension = self.max_dimension()
        self.patches = {}
        self.check_residue_modifications()
 def bp(msg='', hide=False):
     # Only execute the breakpoints when the right set of user defined conditions have been met
     if (pxdebug.debug_enabled == True) and (pxdebug.breakpoints_enabled
                                             == True):
         if (pxdebug.hidden_breakpoints_enabled == True) or (hide == False):
             frame = sys._getframe().f_back
             (filename, line_number, function_name, lines,
              index) = inspect.getframeinfo(frame)
             old_stdout = sys.stdout
             sys.stdout = sys.__stdout__
             if msg is not '':
                 pxdebug.basic(msg)
             pxdebug.basic(
                 '---BREAK----> ' + filename + ' | func=' +
                 function_name)  #+'|line'+str(line_number) + ' <-------')
             try:
                 Pdb().set_trace(frame)
             except e as Exception:
                 print("pxdebug ERROR SETTING TRACE")
                 raise e
             sys.stdout = old_stdout
def pdb_main():
    """This pdb_main is modified from pdb.main().
    """
    from pdb import Pdb, Restart, traceback
    
    mainpyfile =  sys.argv[0]     # Get script filename
    if not os.path.exists(mainpyfile):
        print 'Error:', mainpyfile, 'does not exist'
        sys.exit(1)

    # Replace pdb's dir with script's dir in front of module search path.
    sys.path[0] = os.path.dirname(mainpyfile)

    # Note on saving/restoring sys.argv: it's a good idea when sys.argv was
    # modified by the script being debugged. It's a bad idea when it was
    # changed by the user from the command line. There is a "restart" command
    # which allows explicit specification of command line arguments.
    pdb = Pdb(stdin=sys.__stdin__, stdout=sys.__stdout__)
    while True:
        try:
            pdb._runscript(mainpyfile)
            if pdb._user_requested_quit:
                break
            print "The program finished and will be restarted"
        except Restart:
            print "Restarting", mainpyfile, "with arguments:"
            print "\t" + " ".join(sys.argv[1:])
        except SystemExit:
            # In most cases SystemExit does not warrant a post-mortem session.
            print "The program exited via sys.exit(). Exit status: ",
            print sys.exc_info()[1]
        except:
            traceback.print_exc()
            print "Uncaught exception. Entering post mortem debugging"
            print "Running 'cont' or 'step' will restart the program"
            t = sys.exc_info()[2]
            pdb.interaction(None, t)
            print "Post mortem debugger finished. The " + mainpyfile + \
                  " will be restarted"