def parse_logic(restraints_fn, verbose):
    """Parse logic of restraints.

    Args:
       restraints_nf(string): path to a file with restraints in the rigth format (see below)
       verbose (bool)       : be verbose?

    Format::

        # ignore comments
        (d:A1-A2 <  10.0  1)|(d:A2-A1 <= 10 1)

    Returns:
       list: parse restraints into a list of lists, e.g. [('A9', 'A41', '10.0', '1'), ('A10', 'A16', '10', '1')]

    """

    txt = ''
    with open(restraints_fn) as f:
        for l in f:
            if not l.startswith('#'):
                txt += l.strip()
    if verbose:
        logger.info(txt)
    restraints = re.findall(
        '\(d:(?P<start>.+?)-(?P<end>.+?)\s*(?P<operator>\>\=|\=|\<|\<\=)\s*(?P<distance>[\d\.]+)\s+(?P<weight>.+?)\)',
        txt)
    return restraints
def get_residues(pdb_fn, restraints, verbose):
    residues = set()
    for h in restraints:
        a = h[0]
        b = h[1]
        a = a[0] + ':' + a[1:]
        residues.add(a)  # A19
        b = b[0] + ':' + b[1:]
        residues.add(b)
    # set(['A:41', 'A:9', 'A:10', 'A:16'])

    selection = ','.join(residues)
    selection_parsed = select_pdb_fragment(selection,
                                           separator=",",
                                           splitting="[,:;]")

    residues = parse_pdb(pdb_fn, selection_parsed)

    # get mb
    for r in residues:
        if 'N9' in residues[r]:  # A,G
            residues[r]['mb'] = residues[r]['N9'] - (
                (residues[r]['N9'] - residues[r]['C6']) / 2)
        else:  # A,G
            residues[r]['mb'] = residues[r]['N1'] - (
                (residues[r]['N1'] - residues[r]['C4']) / 2)
    for r in residues:
        if verbose:
            logger.info(' '.join(['mb for ', str(r), str(residues[r]['mb'])]))
    return residues
def __filter_simrna_trajectory():
    f = (line for line in open(args.trajectory))
    c = 0
    while 1:
        try:
            header = f.next().strip()
        except StopIteration:  # not nice
            break
        c += 1
        coords = f.next().strip()
        traj = SimRNATrajectory()
        traj.load_from_string(c, header + '\n' + coords)
        frame = traj.frames[0]
        print(c)
        for h in restraints:
            a = int(h[0].replace('A',
                                 '')) - 1  # A1 -> 0 (indexing Python-like)
            b = int(h[1].replace('A', '')) - 1
            a_mb = frame.residues[a].get_center()
            b_mb = frame.residues[b].get_center()
            # print '  mb for A' + str(a+1), a_mb
            # print '  mb for A' + str(b+1), b_mb
            dist = get_distance(a_mb, b_mb)
            logger.info(' '.join('  d:A' + str(a + 1) + "-A" + str(b + 1),
                                 dist))
def parse_logic_newlines(restraints_fn, offset=0, verbose=False):
    """Parse logic of restraints.

    Args:
       restraints_nf(string): path to a file with restraints in the rigth format (see below)
       verbose (bool)       : be verbose?

    Format::

        # ignore comments
        d:Y23-Y69 < 25.0
        d:Y22-Y69 < 25.0
        # d:<chain><resi_A>-<resi_B> <operator> <distance> <weight>; each restraints in a new line

    Raises:
       __main__.RNAFilterErrorInRestraints: Please check the format of your restraints!

    Returns:
       list: parse restraints into a list of lists, e.g. [('A9', 'A41', '10.0', '1'), ('A10', 'A16', '10', '1')]

    """
    restraints = []
    with open(restraints_fn) as f:
        for l in f:
            if l.strip():
                if not l.startswith('#'):
                    if verbose:
                        logger.info(l)
                    restraint = re.findall(
                        'd:(?P<start>.+?)-(?P<end>.+?)\s*(?P<operator>\>\=|\=|\<|\<\=)\s*(?P<distance>[\d\.]+)\s+(?P<weight>.+?)',
                        l)
                    if restraint:
                        # without [0] it is restraints [[('Y23', 'Y69', '<', '25.0', '1')], [('Y22', 'Y69', '<', '25.0', '1')]]
                        # why? to convert 'Y23', 'Y69', '<', '25.0', '1' -> 'Y23', 'Y69', '<', 25.0, 1
                        start = restraint[0][0][0] + str(
                            int(restraint[0][0][1:]) + offset)
                        end = restraint[0][1][0] + str(
                            int(restraint[0][1][1:]) + offset)
                        restraints.append([
                            start, end, restraint[0][1], restraint[0][2],
                            float(restraint[0][3]),
                            float(restraint[0][4])
                        ])

    if len(restraints) == 0:
        raise RNAFilterErrorInRestraints(
            'Please check the format of your restraints!')
    return restraints  # [('A9', 'A41', '10.0', '1'), ('A10', 'A16', '10', '1')]
            a = int(h[0].replace('A',
                                 '')) - 1  # A1 -> 0 (indexing Python-like)
            b = int(h[1].replace('A', '')) - 1
            a_mb = frame.residues[a].get_center()
            b_mb = frame.residues[b].get_center()
            # print '  mb for A' + str(a+1), a_mb
            # print '  mb for A' + str(b+1), b_mb
            dist = get_distance(a_mb, b_mb)
            logger.info(' '.join('  d:A' + str(a + 1) + "-A" + str(b + 1),
                                 dist))


# main
if __name__ == '__main__':
    parser = get_parser()
    args = parser.parse_args()

    # score = 1
    # print ((True|True)|(False|False)), score

    restraints = parse_logic_newlines(args.restraints_fn, args.offset,
                                      args.verbose)
    if args.verbose:
        logger.info('restraints' + str(restraints))

    if args.structures:
        calc_scores_for_pdbs(args.structures, restraints, args.verbose)

    # if args.trajectory:
    # __filter_simrna_trajectory()