ribolands/syswraps.py
def sys_barriers_180(basename, sofile,
                     barriers = 'barriers',
                     minh = 0.001,
                     maxn = 50,
                     temp = 37.0,
                     noLP = False,
                     moves = 'single-base-pair',
                     zipped = True,
                     rates = True,
                     k0 = 1.,
                     paths = None,
                     bsize = False,
                     ssize = False,
                     circ = False,
                     saddle = False,
                     bmfile = None,
                     plot = False,
                     connected = False,
                     force = False):
    """Perform a system-call of the program ``barriers``.

    The print the results into a file and return the respective filename. This
    wrapper will return the output files, including ``STDIN`` and ``STDERR``.

    Args:
      name (str): Name of the sequence used to name the output file.
      sofile (str): Input filename for ``barriers`` as produced by ``RNAsubopt``.
      temp (float, optional): Specify temperature in Celsius.
      force (bool, optional): Overwrite existing files with the same name.

    Raises:
      ExecError: Program does not exist.
      SuboprocessError: Program terminated with exit code: ...

    Returns:
      [bofile, befile, brfile, bbfile, bpfile, bmfile]: 
        A list of produced files containing ``barriers`` results.
    """

    if zipped and which('zcat') is None:
        rlog.error('Using gzipped subopt files requires the commandline tool zcat.')
        raise ExecError('zcat', "zcat")

    if which(barriers) is None:
        raise ExecError(barriers, "barriers",
                        'http://www.tbi.univie.ac.at/RNA/Barriers')

    if not sofile or not os.path.exists(sofile):
        raise Exception('Cannot find input file:', sofile)

    bofile = basename + '_barriers.bar'
    befile = basename + '_barriers.err'
    brfile = basename + '_barriers_rates.txt'
    bbfile = basename + '_barriers_rates.bin'
    bpfile = basename + '_barriers_tree.ps' if plot else None
    bmfile = basename + '_barriers.ms' if bmfile else None

    if not force and os.path.exists(bofile) and os.path.exists(brfile) and os.path.exists(bbfile) and \
      (not paths or all(map(os.path.exists, ['{:s}_path.{:03d}.{:03d}.txt'.format(basename, int(x), int(y)) for x, y in map(lambda x: x.split('='), paths)]))) and \
      (not plot or os.path.exists(bpfile)) and \
      (not bmfile or os.path.exists(bmfile)):
        rlog.info(f"# files exist: {bofile}, {brfile}")
        return [bofile, befile, brfile, bbfile, bpfile, bmfile]

    barcall = [barriers]

    if not plot:
        barcall.extend(['-q'])

    if connected:
        barcall.extend(['-c'])

    if paths:
        for p in paths:
            barcall.extend(['--path', p])

    if noLP:
        barcall.extend(['-G', 'RNA-noLP'])
    else:
        barcall.extend(['-G', 'RNA'])

    if moves == 'single-base-pair':
        pass
    elif moves == 'shift':
        barcall.extend(['--moves=Shift'])
    else:
        raise ValueError(f"Invalid move-set for barriers: {moves}")

    # buggy barriers
    if subopt_reaches_minh(sofile, minh, zipped):
        barcall.extend(["--minh", str(minh)])
        barcall.extend(["--max", str(int(maxn))])
    barcall.extend(["-T", str(temp)])

    if rates:
        barcall.extend(['--rates'])
        barcall.extend(['--rates-text-file', brfile])
        barcall.extend(['--rates-binary-file', bbfile])
    if bsize:
        barcall.extend(['--bsize'])
    if ssize:
        barcall.extend(['--ssize'])
    if saddle:
        barcall.extend(['--saddle'])

    if bmfile:
        barcall.extend(["--mapstruc", bmfile])
        barcall.extend(["--mapstruc-output", bmfile])

    call = "{} 2> {} > {}".format(' '.join(barcall), befile, bofile)
    rlog.info(f'# {call}')
    # TODO: This version is prettier than the old one, but it might be slower
    # than just writing the string and "shell = True".
    if zipped:
        inp = sub.Popen(["zcat", sofile], stdout = sub.PIPE)
        with open(bofile, 'w') as bh, open(befile, 'w') as eh:
            proc = sub.Popen(barcall, stdin = sub.PIPE, stdout = bh, stderr = eh)
            proc.communicate(inp.communicate()[0])
            if proc.returncode:
                raise SubprocessError(proc.returncode, call)
    else:
        with open(sofile, 'r') as sh, open(bofile, 'w') as bh, open(befile, 'w') as eh:
            proc = sub.Popen(barcall, stdin = sh, stdout = bh, stderr = eh)
            proc.communicate()
            if proc.returncode:
                raise SubprocessError(proc.returncode, call)

    if rates and k0 != 1.: # So this should actually be supported by barriers, but it's not.
        with open(bbfile, 'rb') as rf, \
                open(brfile + '.tmp', 'w') as nr, \
                open(bbfile + '.tmp', 'wb') as nb:
            dim, = unpack('i', rf.read(calcsize('i')))
            nb.write(pack("i", dim))

            rm = []
            for e in range(dim):
                col = []
                for e in range(dim):
                    r, = unpack('d', rf.read(8))
                    rate = r * k0
                    nb.write(pack("d", rate))
                    col.append(rate)
                rm.append(col)

            for line in zip(*rm):
                newline = "".join(map("{:10.4g}".format, line))
                nr.write(newline + "\n")
 
        os.rename(brfile + '.tmp', brfile)
        os.rename(bbfile + '.tmp', bbfile)

    if plot:
        os.rename('tree.ps', bpfile)

    if paths:
        for p in paths:
            x, y = p.split('=')
            pfname = 'path.{:03d}.{:03d}.txt'.format(int(x), int(y))
            os.rename(pfname, basename + '_' + pfname)

    return [bofile, befile, brfile, bbfile, bpfile, bmfile]
Perform a system-call of the program ``barriers``.

    The print the results into a file and return the respective filename. This
    wrapper will return the output files, including ``STDIN`` and ``STDERR``.

    Args:
      name (str): Name of the sequence used to name the output file.
      sofile (str): Input filename for ``barriers`` as produced by ``RNAsubopt``.
      temp (float, optional): Specify temperature in Celsius.
      force (bool, optional): Overwrite existing files with the same name.

    Raises:
      ExecError: Program does not exist.
      SuboprocessError: Program terminated with exit code: ...

    Returns:
      [bofile, befile, brfile, bbfile, bpfile, bmfile]: 
        A list of produced files containing ``barriers`` results.
    
Perform a system-call of the program ``barriers``.
The print the results into a file and return the respective filename.
Perform a system - call of the program ` ` barriers ` ` . The print the results into a file and return the respective filename .
def sys_barriers_180(basename, sofile,
                     barriers = 'barriers',
                     minh = 0.001,
                     maxn = 50,
                     temp = 37.0,
                     noLP = False,
                     moves = 'single-base-pair',
                     zipped = True,
                     rates = True,
                     k0 = 1.,
                     paths = None,
                     bsize = False,
                     ssize = False,
                     circ = False,
                     saddle = False,
                     bmfile = None,
                     plot = False,
                     connected = False,
                     force = False):
    if zipped and which('zcat') is None:
        rlog.error('Using gzipped subopt files requires the commandline tool zcat.')
        raise ExecError('zcat', "zcat")
    if which(barriers) is None:
        raise ExecError(barriers, "barriers",
                        'http://www.tbi.univie.ac.at/RNA/Barriers')
    if not sofile or not os.path.exists(sofile):
        raise Exception('Cannot find input file:', sofile)
    bofile = basename + '_barriers.bar'
    befile = basename + '_barriers.err'
    brfile = basename + '_barriers_rates.txt'
    bbfile = basename + '_barriers_rates.bin'
    bpfile = basename + '_barriers_tree.ps' if plot else None
    bmfile = basename + '_barriers.ms' if bmfile else None
    if not force and os.path.exists(bofile) and os.path.exists(brfile) and os.path.exists(bbfile) and \
      (not paths or all(map(os.path.exists, ['{:s}_path.{:03d}.{:03d}.txt'.format(basename, int(x), int(y)) for x, y in map(lambda x: x.split('='), paths)]))) and \
      (not plot or os.path.exists(bpfile)) and \
      (not bmfile or os.path.exists(bmfile)):
        rlog.info(f"# files exist: {bofile}, {brfile}")
        return [bofile, befile, brfile, bbfile, bpfile, bmfile]
    barcall = [barriers]
    if not plot:
        barcall.extend(['-q'])
    if connected:
        barcall.extend(['-c'])
    if paths:
        for p in paths:
            barcall.extend(['--path', p])
    if noLP:
        barcall.extend(['-G', 'RNA-noLP'])
    else:
        barcall.extend(['-G', 'RNA'])
    if moves == 'single-base-pair':
        pass
    elif moves == 'shift':
        barcall.extend(['--moves=Shift'])
    else:
        raise ValueError(f"Invalid move-set for barriers: {moves}")
    if subopt_reaches_minh(sofile, minh, zipped):
        barcall.extend(["--minh", str(minh)])
        barcall.extend(["--max", str(int(maxn))])
    barcall.extend(["-T", str(temp)])
    if rates:
        barcall.extend(['--rates'])
        barcall.extend(['--rates-text-file', brfile])
        barcall.extend(['--rates-binary-file', bbfile])
    if bsize:
        barcall.extend(['--bsize'])
    if ssize:
        barcall.extend(['--ssize'])
    if saddle:
        barcall.extend(['--saddle'])
    if bmfile:
        barcall.extend(["--mapstruc", bmfile])
        barcall.extend(["--mapstruc-output", bmfile])
    call = "{} 2> {} > {}".format(' '.join(barcall), befile, bofile)
    rlog.info(f'# {call}')
    if zipped:
        inp = sub.Popen(["zcat", sofile], stdout = sub.PIPE)
        with open(bofile, 'w') as bh, open(befile, 'w') as eh:
            proc = sub.Popen(barcall, stdin = sub.PIPE, stdout = bh, stderr = eh)
            proc.communicate(inp.communicate()[0])
            if proc.returncode:
                raise SubprocessError(proc.returncode, call)
    else:
        with open(sofile, 'r') as sh, open(bofile, 'w') as bh, open(befile, 'w') as eh:
            proc = sub.Popen(barcall, stdin = sh, stdout = bh, stderr = eh)
            proc.communicate()
            if proc.returncode:
                raise SubprocessError(proc.returncode, call)
    if rates and k0 != 1.: 
        with open(bbfile, 'rb') as rf, \
                open(brfile + '.tmp', 'w') as nr, \
                open(bbfile + '.tmp', 'wb') as nb:
            dim, = unpack('i', rf.read(calcsize('i')))
            nb.write(pack("i", dim))
            rm = []
            for e in range(dim):
                col = []
                for e in range(dim):
                    r, = unpack('d', rf.read(8))
                    rate = r * k0
                    nb.write(pack("d", rate))
                    col.append(rate)
                rm.append(col)
            for line in zip(*rm):
                newline = "".join(map("{:10.4g}".format, line))
                nr.write(newline + "\n")
        os.rename(brfile + '.tmp', brfile)
        os.rename(bbfile + '.tmp', bbfile)
    if plot:
        os.rename('tree.ps', bpfile)
    if paths:
        for p in paths:
            x, y = p.split('=')
            pfname = 'path.{:03d}.{:03d}.txt'.format(int(x), int(y))
            os.rename(pfname, basename + '_' + pfname)
    return [bofile, befile, brfile, bbfile, bpfile, bmfile]
def sys_barriers_180 ( basename , sofile , barriers = 'barriers' , minh = 0.001 , maxn = 50 , temp = 37.0 , noLP = False , moves = 'single-base-pair' , zipped = True , rates = True , k0 = 1. , paths = None , bsize = False , ssize = False , circ = False , saddle = False , bmfile = None , plot = False , connected = False , force = False ) : if zipped and which ( 'zcat' ) is None : rlog . error ( 'Using gzipped subopt files requires the commandline tool zcat.' ) raise ExecError ( 'zcat' , "zcat" ) if which ( barriers ) is None : raise ExecError ( barriers , "barriers" , 'http://www.tbi.univie.ac.at/RNA/Barriers' ) if not sofile or not os . path . exists ( sofile ) : raise Exception ( 'Cannot find input file:' , sofile ) bofile = basename + '_barriers.bar' befile = basename + '_barriers.err' brfile = basename + '_barriers_rates.txt' bbfile = basename + '_barriers_rates.bin' bpfile = basename + '_barriers_tree.ps' if plot else None bmfile = basename + '_barriers.ms' if bmfile else None if not force and os . path . exists ( bofile ) and os . path . exists ( brfile ) and os . path . exists ( bbfile ) and ( not paths or all ( map ( os . path . exists , [ '{:s}_path.{:03d}.{:03d}.txt' . format ( basename , int ( x ) , int ( y ) ) for x , y in map ( lambda x : x . split ( '=' ) , paths ) ] ) ) ) and ( not plot or os . path . exists ( bpfile ) ) and ( not bmfile or os . path . exists ( bmfile ) ) : rlog . info ( f"# files exist: {bofile}, {brfile}" ) return [ bofile , befile , brfile , bbfile , bpfile , bmfile ] barcall = [ barriers ] if not plot : barcall . extend ( [ '-q' ] ) if connected : barcall . extend ( [ '-c' ] ) if paths : for p in paths : barcall . extend ( [ '--path' , p ] ) if noLP : barcall . extend ( [ '-G' , 'RNA-noLP' ] ) else : barcall . extend ( [ '-G' , 'RNA' ] ) if moves == 'single-base-pair' : pass elif moves == 'shift' : barcall . extend ( [ '--moves=Shift' ] ) else : raise ValueError ( f"Invalid move-set for barriers: {moves}" ) if subopt_reaches_minh ( sofile , minh , zipped ) : barcall . extend ( [ "--minh" , str ( minh ) ] ) barcall . extend ( [ "--max" , str ( int ( maxn ) ) ] ) barcall . extend ( [ "-T" , str ( temp ) ] ) if rates : barcall . extend ( [ '--rates' ] ) barcall . extend ( [ '--rates-text-file' , brfile ] ) barcall . extend ( [ '--rates-binary-file' , bbfile ] ) if bsize : barcall . extend ( [ '--bsize' ] ) if ssize : barcall . extend ( [ '--ssize' ] ) if saddle : barcall . extend ( [ '--saddle' ] ) if bmfile : barcall . extend ( [ "--mapstruc" , bmfile ] ) barcall . extend ( [ "--mapstruc-output" , bmfile ] ) call = "{} 2> {} > {}" . format ( ' ' . join ( barcall ) , befile , bofile ) rlog . info ( f'# {call}' ) if zipped : inp = sub . Popen ( [ "zcat" , sofile ] , stdout = sub . PIPE ) with open ( bofile , 'w' ) as bh , open ( befile , 'w' ) as eh : proc = sub . Popen ( barcall , stdin = sub . PIPE , stdout = bh , stderr = eh ) proc . communicate ( inp . communicate ( ) [ 0 ] ) if proc . returncode : raise SubprocessError ( proc . returncode , call ) else : with open ( sofile , 'r' ) as sh , open ( bofile , 'w' ) as bh , open ( befile , 'w' ) as eh : proc = sub . Popen ( barcall , stdin = sh , stdout = bh , stderr = eh ) proc . communicate ( ) if proc . returncode : raise SubprocessError ( proc . returncode , call ) if rates and k0 != 1. : with open ( bbfile , 'rb' ) as rf , open ( brfile + '.tmp' , 'w' ) as nr , open ( bbfile + '.tmp' , 'wb' ) as nb : dim , = unpack ( 'i' , rf . read ( calcsize ( 'i' ) ) ) nb . write ( pack ( "i" , dim ) ) rm = [ ] for e in range ( dim ) : col = [ ] for e in range ( dim ) : r , = unpack ( 'd' , rf . read ( 8 ) ) rate = r * k0 nb . write ( pack ( "d" , rate ) ) col . append ( rate ) rm . append ( col ) for line in zip ( * rm ) : newline = "" . join ( map ( "{:10.4g}" . format , line ) ) nr . write ( newline + "\n" ) os . rename ( brfile + '.tmp' , brfile ) os . rename ( bbfile + '.tmp' , bbfile ) if plot : os . rename ( 'tree.ps' , bpfile ) if paths : for p in paths : x , y = p . split ( '=' ) pfname = 'path.{:03d}.{:03d}.txt' . format ( int ( x ) , int ( y ) ) os . rename ( pfname , basename + '_' + pfname ) return [ bofile , befile , brfile , bbfile , bpfile , bmfile ]
Perform a system-call of the program ``barriers``.
Perform a system - call of the program ` ` barriers ` ` .
"""Perform a system-call of the program ``barriers``.

    The print the results into a file and return the respective filename. This
    wrapper will return the output files, including ``STDIN`` and ``STDERR``.

    Args:
      name (str): Name of the sequence used to name the output file.
      sofile (str): Input filename for ``barriers`` as produced by ``RNAsubopt``.
      temp (float, optional): Specify temperature in Celsius.
      force (bool, optional): Overwrite existing files with the same name.

    Raises:
      ExecError: Program does not exist.
      SuboprocessError: Program terminated with exit code: ...

    Returns:
      [bofile, befile, brfile, bbfile, bpfile, bmfile]: 
        A list of produced files containing ``barriers`` results.
    """ # buggy barriers # TODO: This version is prettier than the old one, but it might be slower # than just writing the string and "shell = True". # So this should actually be supported by barriers, but it's not.
A list of produced files containing ``barriers`` results.
A list of produced files containing ` ` barriers ` ` results .
[bofile, befile, brfile, bbfile, bpfile, bmfile]
Program does not exist.
Program does not exist .
ExecError
Program terminated with exit code.
Program terminated with exit code .
SuboprocessError
basename
sofile
Input filename for ``barriers`` as produced by ``RNAsubopt``.
Input filename for ` ` barriers ` ` as produced by ` ` RNAsubopt ` ` .
barriers
minh
maxn
temp
Specify temperature in Celsius.
Specify temperature in Celsius .
noLP
moves
zipped
rates
k0
paths
bsize
ssize
circ
saddle
bmfile
plot
connected
force
Overwrite existing files with the same name.
Overwrite existing files with the same name .
name
Name of the sequence used to name the output file.
Name of the sequence used to name the output file .