Example #1
0
def main():
    logger = init_logger('Qpyl')

    parser = argparse.ArgumentParser(description="""
    Fits EVB parameters Hij and alpha to reproduce
    reference activation and reaction free energies.

    By default, all subdirectories in current dir will be used
    for mapping, or current dir if no subdirs are found.
    This can be changed with --dirs.

    Initial guess values for Hij and alpha should be relatively close to
    their correct values (+-50) otherwise qfep crashes. If it doesn't converge,
    change the step size (--step), number of iterations (--iter) or the threshold
    (--threshold).
    """,
                                     add_help=False)
    reqarg = parser.add_argument_group("Required")
    reqarg.add_argument("ref_dga",
                        type=float,
                        help="Reference activation free energy.")

    reqarg.add_argument("ref_dg0",
                        type=float,
                        help="Reference reaction free energy.")

    reqarg.add_argument("init_hij",
                        type=float,
                        help="Initial guess for Hij (offdiagonal)")

    reqarg.add_argument("init_alpha",
                        type=float,
                        help="Initial guess for alpha (state 2 shift)")

    optarg = parser.add_argument_group("Optional")
    optarg.add_argument("--nt",
                        dest='nthreads',
                        type=int,
                        default=QScfg.get("mapping", "nthreads"),
                        help="Number of threads (default = {})"
                        "".format(QScfg.get("mapping", "nthreads")))

    optarg.add_argument("--bins",
                        dest="gap_bins",
                        type=int,
                        default=QScfg.get("mapping", "gap_bins"),
                        help="Number of gap-bins (default={})."
                        "".format(QScfg.get("mapping", "gap_bins")))

    optarg.add_argument("--skip",
                        dest="points_skip",
                        type=int,
                        default=QScfg.get("mapping", "points_skip"),
                        help="Number of points to skip in each frame "
                        "(default={})."
                        "".format(QScfg.get("mapping", "points_skip")))

    optarg.add_argument("--min",
                        dest="minpts_bin",
                        type=int,
                        default=QScfg.get("mapping", "minpts_bin"),
                        help="Minimum points for gap-bin (default={})."
                        "".format(QScfg.get("mapping", "minpts_bin")))

    optarg.add_argument("--temp",
                        dest="temperature",
                        type=float,
                        default=QScfg.get("mapping", "temperature"),
                        help="Temperature (default={})."
                        "".format(QScfg.get("mapping", "temperature")))

    optarg.add_argument("--dirs",
                        nargs="+",
                        dest="mapdirs",
                        default=[],
                        help="Directories to map (default=all subdirs "
                        "in cwd that contain the energy-files list {})."
                        "".format(QScfg.get("files", "en_list_fn")))

    optarg.add_argument("--out",
                        dest="outfile",
                        default=QScfg.get("files", "automapper_log"),
                        help="Logfile name (default={})."
                        "".format(QScfg.get("files", "automapper_log")))

    _args, _, _, _defaults = inspect.getargspec(QMapper.fit_to_reference)
    defs = dict(zip(_args[-len(_defaults):], _defaults))

    optarg.add_argument("--step",
                        dest="step_size",
                        type=float,
                        help="Step size (default={})."
                        "".format(defs["step_size"]),
                        default=defs["step_size"])

    optarg.add_argument("--threshold",
                        dest="threshold",
                        type=float,
                        help="Convergence threshold for dG# and dG0 "
                        "(default={}).".format(defs["threshold"]),
                        default=defs["threshold"])

    optarg.add_argument("--iter",
                        dest="max_iterations",
                        type=int,
                        help="Max number of iterations (default={})."
                        "".format(defs["max_iterations"]),
                        default=defs["max_iterations"])

    optarg.add_argument("--nosingle",
                        dest="nosingle",
                        action="store_true",
                        help="Do not run the first iteration on only 1 dir.")

    optarg.add_argument("--qfep_exec",
                        dest="qfep_exec",
                        default=QScfg.get("qexec", "qfep"),
                        help="qfep executable path (default={})."
                        "".format(QScfg.get("qexec", "qfep")))
    optarg.add_argument("-v",
                        "--version",
                        action="version",
                        version=get_version_full())
    optarg.add_argument("-h",
                        "--help",
                        action="help",
                        help="show this help "
                        "  message and exit")

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args()

    print """\
Attempting to fit to dG# = {} and dG0 = {}
(stepsize = {}, threshold = {}, max iterations = {})
""".format(args.ref_dga, args.ref_dg0, args.step_size, args.threshold,
           args.max_iterations)

    mapdirs = args.mapdirs

    # if mapping directories were not passed in as an argument,
    # store all directories in the current folder
    if not mapdirs:
        lsdir = os.listdir(os.getcwd())
        mapdirs = [md for md in lsdir if os.path.isdir(md)]

    mapdirs.sort()

    # if there are no folders in the current working directory,
    # map just the current one
    if not mapdirs:
        mapdirs = [
            os.getcwd(),
        ]
        print "No subdirectories. Mapping files in current directory only."
    else:
        print "Will use these directories for mapping (use --dirs to "\
              "change this): {}".format(", ".join(mapdirs))

    qmapper_parms = {
        "hij": args.init_hij,
        "alpha": args.init_alpha,
        "nthreads": args.nthreads,
        "temperature": args.temperature,
        "points_skip": args.points_skip,
        "minpts_bin": args.minpts_bin,
        "gap_bins": args.gap_bins,
        "qfep_exec": args.qfep_exec,
        "en_list_fn": QScfg.get("files", "en_list_fn"),
        "gas_const": QScfg.get("mapping", "gas_const")
    }

    # automap with only the first replica (when we have 3 or more)
    # to get a better init guess quickly
    if not args.nosingle and len(mapdirs) > 2:
        print "\nInitial fit, using only the first folder (disable this "\
                "with --nosingle)."
        # create QMapper instance with all arguments
        qmapper_parms["mapdirs"] = mapdirs[:1]
        qmapper_single = QMapper(**qmapper_parms)
        try:
            qmapper_single.fit_to_reference(args.ref_dga,
                                            args.ref_dg0,
                                            step_size=args.step_size,
                                            threshold=args.threshold,
                                            max_iterations=1)

        except QMapperError:
            print "...failed, will try with all dirs anyhow..."
        except KeyboardInterrupt:
            qmapper_single.kill_event.set()
            raise
        else:
            qmapper_parms.update({
                "hij": qmapper_single.parms["hij"],
                "alpha": qmapper_single.parms["alpha"]
            })

        print "\nSwitching to all directories..."

    qmapper_parms["mapdirs"] = mapdirs
    qmapper = QMapper(**qmapper_parms)

    try:
        rcode = qmapper.fit_to_reference(args.ref_dga,
                                         args.ref_dg0,
                                         step_size=args.step_size,
                                         threshold=args.threshold,
                                         max_iterations=args.max_iterations)
    except QMapperError as error_msg:
        print "\nMassive fail:\n{}\n".format(error_msg)
        sys.exit(1)
    except KeyboardInterrupt:
        qmapper.kill_event.set()
        raise

    if not rcode:
        print "Did not converge. Try changing the step (--step), increasing "\
              "number of iterations (--iter) or raising the threshold "\
              "(--threshold)\n"

    else:
        print """

Well done! Use this on your non-reference simulations:
{}

""".format(qmapper.input_parms_str)

        # write out the inputs and outputs from the last step
        qfep_inp_fn = QScfg.get("files", "qfep_inp")
        qfep_out_fn = QScfg.get("files", "qfep_out")
        for mapdir, (qfep_inp_str, qfep_out_str) in qmapper.mapped.iteritems():
            qfep_inp = os.path.join(mapdir, qfep_inp_fn)
            qfep_out = os.path.join(mapdir, qfep_out_fn)
            open(qfep_inp, "w").write(qfep_inp_str)
            open(qfep_out, "w").write(qfep_out_str)

        # analyse the outputs
        output_files = [os.path.join(md, qfep_out_fn) for md in qmapper.mapped]
        qafs = QAnalyseFeps(output_files)
        fails = "\n".join([
            "{}: {}".format(qfo, err) for qfo, err in qafs.failed.iteritems()
        ])

        outstr = """
{mapper_details}
Analysis Stats:
{analysis_stats}
Analysis Fails:
{analysis_fails}
""".format(mapper_details=qmapper.details,
           analysis_stats=qafs.stats_str,
           analysis_fails=fails or "None")

        if fails or qmapper.failed:
            print """
WARNING! Some dirs failed to map/analyse! Look at the log!

"""

        print "Writting out the logfile..."
        backup = backup_file(args.outfile)
        if backup:
            print "# Backed up '{}' to '{}'".format(args.outfile, backup)
        open(args.outfile, "w").write(outstr)
        print "Wrote '{}'...".format(args.outfile)
Example #2
0
Bond energy: total {t[bonds]:.2f}, max {m[bonds]:.2f}
Angle energy: total {t[angles]:.2f}, max {m[angles]:.2f}
Torsion energy: total {t[torsions]:.2f}, max {m[torsions]:.2f}
Improper energy: total {t[impropers]:.2f}, max {m[impropers]:.2f}

""".format(n=nprm, t=total_e, m=max_e)

#
# write the files
#
libfn = args.output_basename + ".lib"
prmfn = args.output_basename + ".prm"
prmchkfn = args.output_basename + ".prm.chk"

print "Writing the library file: {}".format(libfn)
backup = backup_file(libfn)
if backup:
    print "# Backed up '{}' to '{}'".format(libfn, backup)
outstring = """# Generated with {}, version {}
# Date: {}
#
{}
""".format(os.path.basename(__file__), __version__,
           time.ctime(), qlib.get_string())
open(libfn, "w").write(outstring)

print "Writing the parameter file: {}".format(prmfn)
backup = backup_file(prmfn)
if backup:
    print "# Backed up '{}' to '{}'".format(prmfn, backup)
outstring = """# Generated with {}, version {}
Example #3
0
    e_dc = qads.get_energies(k, percent_skip=args.skip, stride=args.stride)
    e_cs, e_cts = e_dc.get_columns(), e_dc.get_column_titles()
    if e_cs:
        for i, e_ct in enumerate(e_cts[1:]):
            plots[key].add_subplot(e_ct, e_cs[0], e_cs[i + 1])  # 0==Time

for k in qads.qen_section_keys:
    for evb_state in range(1, qads.n_evb_states + 1):
        key = "EQ{}_{}".format(evb_state, k)
        plots[key] = plotdata.PlotData("Q Energy: {} (state {})"
                                       "".format(k, evb_state),
                                       xlabel=time_label,
                                       ylabel="Energy [kcal/mol]")
        qe_dc = qads.get_q_energies(k,
                                    evb_state,
                                    percent_skip=args.skip,
                                    stride=args.stride)
        qe_cs, qe_cts = qe_dc.get_columns(), qe_dc.get_column_titles()
        if qe_cs:
            for i, qe_ct in enumerate(qe_cts[1:]):
                plots[key].add_subplot(qe_ct, qe_cs[0],
                                       qe_cs[i + 1])  # 0==Time

jsonenc = plotdata.PlotDataJSONEncoder(indent=2)
backup = backup_file(args.plots_out)
if backup:
    print "Backed up '{}' to '{}'".format(args.plots_out, backup)
open(args.plots_out, 'w').write(jsonenc.encode(plots))
print "\nWrote '{}'. Use q_plot.py to visualize the plots.".format(
    args.plots_out)
Example #4
0
                    "--help",
                    action="help",
                    help="show this "
                    "help message and exit")

if len(sys.argv) == 1:
    parser.print_help()
    sys.exit(1)

args = parser.parse_args()

for k, v in six.iteritems(vars(args)):
    if k in ["inp", "pdb"] and not os.path.lexists(v):
        print("FATAL! File '{}' doesn't exist.".format(v))
        sys.exit(1)

inpstr = open(args.inp, "r").read()

try:
    qstruct = QStruct(args.pdb, "pdb", ignore_errors=args.ignore_errors)
    outstring = qstruct.convert_placeholders(inpstr)
except QStructError as e:
    print("FATAL! Exception raised: {}".format(str(e)))
    sys.exit(1)

backup = backup_file(args.out)
if backup:
    print("Backed up '{}' to '{}'".format(args.out, backup))
open(args.out, "w").write(outstring)
print("Created file '{}'...".format(args.out))
Example #5
0
    com = "    #  %-40s" % ("-".join([a.pdb_id for a in impr.atoms]))
    for imprt in impr.improper_types:
        if imprt:
            i = imprt.index
            c = "-".join(imprt.atom_types)
        else:
            i = 0
            c = "None"
        s = s + "%5d" % i
        com = com + " %-35s" % c
    fepstring += s + com + "\n"

fepstring += "\n\n\n#\n# Created with 'q_makefep.py' version '%s'\n# Date: %s\n#" % (
    __version__, time.ctime())

backup = backup_file(OUT_FN)
if backup:
    print "Backed up '%s' to '%s'" % (OUT_FN, backup)

open(OUT_FN, 'w').write(fepstring)
print "\nWrote fep file:  %s\n" % (OUT_FN)
print "Please inspect it for probable errors and add the soft pair and Morse parameters..."

# Debug - print out non-changing parameters
#
#for a in fep_changes["atoms"]:
#    print a, a.connections
#
#for k,v in fep_changes.iteritems():
#    try:
#        print k
Example #6
0
def gc(args):

    if not os.path.lexists(args.pdb):
        print "This file went missing: {}".format(args.pdb)
        sys.exit(1)

    if args.qmaskfile:
        try:
            qmask = open(args.qmaskfile, "r").read().split()
            if not qmask:
                raise IOError
        except IOError:
            print "Can't read '{}' or file empty".format(args.qmaskfile)
            sys.exit(1)
    else:
        qmask = None

    lambdas = []
    for lamb in args.lra_l:
        try:
            lamb = float(lamb)
            if lamb < 0 or lamb > 1:
                raise ValueError
        except ValueError:
            print "FATAL! Lambda values make no sense. 0 <= lambda <= 1 please."
            sys.exit(1)
        lambdas.append((lamb, 1 - lamb))

    calcdirs = args.dirs
    if not calcdirs:
        lsdir = os.listdir(os.getcwd())
        calcdirs = [f for f in lsdir if os.path.isdir(f)]
    if not calcdirs:
        calcdirs = [
            os.getcwd(),
        ]
        print "No subdirectories. Calculating in current directory only.\n"
    else:
        print "Will use these directories for calculating GCs (use --dirs to "\
              "change this): {}\n".format(", ".join(calcdirs))

    qgc = QGroupContrib(args.qcalc_exec, calcdirs, args.pdb,
                        QScfg.get("files", "en_list_fn"), lambdas[0],
                        lambdas[1], args.resid_first, args.resid_last,
                        args.scale_ionized, args.nthreads, qmask)

    try:
        qgc.calcall()
    except QGroupContribError as error_msg:
        print "\nMassive fail:\n{}\n".format(error_msg)
        sys.exit(1)
    except KeyboardInterrupt:
        qgc.kill_event.set()
        raise

    # writeout QCalc inputs and outputs
    if args.writeout:
        for calcdir, (qcinps, qcouts) in qgc._qcalc_io.iteritems():
            for i, qci in enumerate(qcinps):
                fn = os.path.join(calcdir, "q_calc.gc.{}.inp".format(i + 1))
                try:
                    open(fn, 'w').write(qci)
                except OSError as err:
                    print "Error when writing to {}: {}".format(fn, err)
                else:
                    print "Wrote {}".format(fn)
            for i, qco in enumerate(qcouts):
                fn = os.path.join(calcdir, "q_calc.gc.{}.out".format(i + 1))
                try:
                    open(fn, 'w').write(qco)
                except OSError as err:
                    print "Error when writing to {}: {}".format(fn, err)
                else:
                    print "Wrote {}".format(fn)

    # write out details and top 10 GCs to stdout and outfile
    if not qgc.gcs:
        top_gcs = "None, all directories failed..."
        top_gcs_reorg = "None, all directories failed..."
    else:
        top_rows = sorted(qgc.gcs_stats.get_rows(),
                          key=lambda x: -abs(x[13]))[:10]

        out_l = ["{:<10} {:>10} {:>10}".format("# Residue", "Mean", "Stdev")]

        for row in top_rows:
            rid, rn, el, elstd = row[0], row[1], row[13], row[14]

            tmp = "{}_{}".format(rn.capitalize(), rid)
            tmp2 = "{:<10} {:10.2f} {:10.2f}".format(tmp, el, elstd)
            out_l.append(tmp2)

        top_gcs = "\n".join(out_l)

        top_rows = sorted(qgc.gcs_stats.get_rows(),
                          key=lambda x: -abs(x[17]))[:10]

        out_l = ["{:<10} {:>10} {:>10}".format("# Residue", "Mean", "Stdev")]

        for row in top_rows:
            rid, rn, el, elstd = row[0], row[1], row[17], row[18]

            tmp = "{}_{}".format(rn.capitalize(), rid)
            tmp2 = "{:<10} {:10.2f} {:10.2f}".format(tmp, el, elstd)
            out_l.append(tmp2)

        top_gcs_reorg = "\n".join(out_l)

    outstr = """
{gc_details}
Top LRA (el) contributions:
{top_gcs}

Top REORG (el) contributions:
{top_gcs_reorg}
""".format(gc_details=qgc.details,
           top_gcs=top_gcs,
           top_gcs_reorg=top_gcs_reorg)

    print outstr
    fn_out = args.output_fn
    backup = backup_file(fn_out)
    if backup:
        print "# Backed up '{}' to '{}'".format(fn_out, backup)
    open(fn_out, "w").write(outstr)
    print "Wrote '{}'...".format(fn_out)

    # convert plots to json and write them out
    fn_out = args.plots_out
    plots = qgc.plotdata
    jsonenc = plotdata.PlotDataJSONEncoder(indent=2)
    backup = backup_file(fn_out)
    if backup:
        print "# Backed up '{}' to '{}'".format(fn_out, backup)
    open(fn_out, 'w').write(jsonenc.encode(plots))
    print "Wrote '{}'... (q_plot.py is your "\
          "friend)".format(fn_out)

    # writeout the pdbgc if requested
    if args.pdbgc_out:
        backup = backup_file(args.pdbgc_out)
        if backup:
            print "# Backed up '{}' to '{}'".format(args.pdbgc_out, backup)
        open(args.pdbgc_out, 'w').write(qgc.get_pdbgc())
        print "Wrote '{}'... (use Pymol/Chimera/VMD and color by occupancy "\
              "(LRA) or B-factor (reorg))".format(args.pdbgc_out)
Example #7
0
    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args()

    for k, v in six.iteritems(vars(args)):
        if k in ["pdb", "parms", "libs", "qmap"]:
            for fn in v:
                if not os.path.lexists(fn):
                    print("File '{}' doesn't exist.".format(fn))
                    sys.exit(1)

    try:
        fepstr = make_fep(args.qmap[0],
                          args.pdb[0],
                          args.forcefield,
                          args.prms,
                          args.libs,
                          ignore_errors=args.ignore_errors)
    except QMakeFepError as err:
        print("\nFATAL!\n{}\n".format(err))
        sys.exit(1)

    output_file = args.outfile[0]
    backup = backup_file(output_file)
    if backup:
        print("\n# Backed up '{}' to '{}'".format(output_file, backup))
    open(output_file, 'w').write(fepstr)
    print("Wrote '{}'... ".format(output_file))
Example #8
0
def main():
    logger = init_logger('Qpyl')

    parser = argparse.ArgumentParser(description="""
    Command-line interface for mapping EVB (or just plain old FEP) simulations
    with QFep. At the moment, supports only single Hij (constant) and alpha.
    For FEP, use Hij=alpha=0.

    By default, all subdirectories in current dir will be used
    for mapping, or current dir if no subdirs are found.
    This can be changed with --dirs.
    """,
                                     add_help=False)

    reqarg = parser.add_argument_group("Required")
    reqarg.add_argument("hij", type=float, help="Hij coupling constant")

    reqarg.add_argument("alpha", type=float, help="state 2 shift (alpha)")

    optarg = parser.add_argument_group("Optional")
    optarg.add_argument("--nt",
                        dest='nthreads',
                        type=int,
                        default=QScfg.get("mapping", "nthreads"),
                        help="Number of threads (default = {})"
                        "".format(QScfg.get("mapping", "nthreads")))

    optarg.add_argument("--bins",
                        dest="gap_bins",
                        type=int,
                        default=QScfg.get("mapping", "gap_bins"),
                        help="Number of gap-bins (default={})."
                        "".format(QScfg.get("mapping", "gap_bins")))

    optarg.add_argument("--skip",
                        dest="points_skip",
                        type=int,
                        default=QScfg.get("mapping", "points_skip"),
                        help="Number of points to skip in each frame "
                        "(default={})."
                        "".format(QScfg.get("mapping", "points_skip")))

    optarg.add_argument("--min",
                        dest="minpts_bin",
                        type=int,
                        default=QScfg.get("mapping", "minpts_bin"),
                        help="Minimum points for gap-bin (default={})."
                        "".format(QScfg.get("mapping", "minpts_bin")))

    optarg.add_argument("--temp",
                        dest="temperature",
                        type=float,
                        default=QScfg.get("mapping", "temperature"),
                        help="Temperature (default={})."
                        "".format(QScfg.get("mapping", "temperature")))

    optarg.add_argument("--dirs",
                        nargs="+",
                        dest="mapdirs",
                        default=[],
                        help="Directories to map (default=all subdirs "
                        "in cwd or current dir)")

    optarg.add_argument("--out",
                        dest="outfile",
                        default=QScfg.get("files", "mapper_log"),
                        help="Logfile name (default={})."
                        "".format(QScfg.get("files", "mapper_log")))

    optarg.add_argument("--qfep_exec",
                        dest="qfep_exec",
                        default=QScfg.get("qexec", "qfep"),
                        help="qfep executable path (default={})."
                        "".format(QScfg.get("qexec", "qfep")))

    optarg.add_argument("-v",
                        "--version",
                        action="version",
                        version=get_version_full())
    optarg.add_argument("-h",
                        "--help",
                        action="help",
                        help="show this "
                        "help message and exit")

    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args()

    mapdirs = args.mapdirs

    # if mapping directories were not passed in as an argument,
    # store all directories in the current folder
    if not mapdirs:
        lsdir = os.listdir(os.getcwd())
        mapdirs = [md for md in lsdir if os.path.isdir(md)]

    mapdirs.sort()

    # if there are no folders in the current working directory,
    # map just the current one
    if not mapdirs:
        mapdirs = [
            os.getcwd(),
        ]
        print "No subdirectories. Mapping files in current directory only."
    else:
        print "Will use these directories for mapping (use --dirs to "\
              "change this): {}".format(", ".join(mapdirs))

    qmapper_parms = {
        "mapdirs": mapdirs,
        "hij": args.hij,
        "alpha": args.alpha,
        "nthreads": args.nthreads,
        "temperature": args.temperature,
        "points_skip": args.points_skip,
        "minpts_bin": args.minpts_bin,
        "gap_bins": args.gap_bins,
        "qfep_exec": args.qfep_exec,
        "en_list_fn": QScfg.get("files", "en_list_fn"),
        "gas_const": QScfg.get("mapping", "gas_const")
    }

    qmapper = QMapper(**qmapper_parms)
    try:
        qmapper.mapall()
    except KeyboardInterrupt:
        qmapper.kill_event.set()
        raise

    qfep_inp_fn = QScfg.get("files", "qfep_inp")
    qfep_out_fn = QScfg.get("files", "qfep_out")

    # write out the inputs and outputs
    for mapdir, (qfep_inp_str, qfep_out_str) in qmapper.mapped.iteritems():
        qfep_inp = os.path.join(mapdir, qfep_inp_fn)
        qfep_out = os.path.join(mapdir, qfep_out_fn)
        open(qfep_inp, "w").write(qfep_inp_str)
        open(qfep_out, "w").write(qfep_out_str)

    # analyse the outputs
    output_files = [os.path.join(md, qfep_out_fn) for md in qmapper.mapped]
    qafs = QAnalyseFeps(output_files)

    outstr = """
{mapper_details}
Analysis Stats:
{analysis_stats}
Analysis Fails:
FEP: {fails}, EVB: {fails_dg}

Run q_analysefeps.py for more info...
""".format(mapper_details=qmapper.details,
           analysis_stats=qafs.stats_str,
           fails=len(qafs.failed) or "None",
           fails_dg=len(qafs.failed_dg) or "None")

    print outstr
    backup = backup_file(args.outfile)
    if backup:
        print "# Backed up '{}' to '{}'".format(args.outfile, backup)
    open(args.outfile, "w").write(outstr)
    print "Wrote '{}'...".format(args.outfile)
Example #9
0
def main():
    logger = init_logger('Qpyl')

    parser = argparse.ArgumentParser(description="""
Tool for analysing QFep outputs - extracting FEP results, activation and reaction free
energies, calculating LRA contributions, calculating statistics over all
outputs, and exporting all the data into JSON format. Should be used after
every mapping.
    """, add_help=False)
    reqarg = parser.add_argument_group("Required")
    reqarg.add_argument("fepdirs", nargs="+",
                        help="Directories to scan for qfep output.")

    optarg = parser.add_argument_group("Optional")
    def_lra_l = QScfg.get("analysis", "lambdas_state1").split(",")

    optarg.add_argument("--lra_l", dest="lra_l", nargs=2,
                        metavar=("l1", "l2"),
                        default=def_lra_l,
                        help="Specify lambdas (state 1) at which LRA and "
                             "REORG are calculated. Default is '{}'."
                             "".format(str(def_lra_l)))


    optarg.add_argument("--qfep_out", dest="qfep_out",
                        help="Qfep output filename (default='{}')"
                             "".format(QScfg.get("files", "qfep_out")),
                        default=QScfg.get("files", "qfep_out"))

    optarg.add_argument("--out", dest="output_fn",
                        help="Output filename (default='{}')"
                             "".format(QScfg.get("files", "analysefeps_log")),
                        default=QScfg.get("files", "analysefeps_log"))

    optarg.add_argument("--plots_out", dest="plots_out",
                        help="Output filename for plot data (default='{}')"
                             "".format(QScfg.get("files", "analysefeps_plots")),
                        default=QScfg.get("files", "analysefeps_plots"))

    optarg.add_argument("--subcalcs", dest="subcalcs", default=False,
                        help="Write out plot data for sub-calculations "
                             "(QCP, QCP_mass, Exclusions). By default "
                             "this data is not written out.",
                        action="store_true")

    optarg.add_argument("--subcalc_dir", dest="subcalc_dir",
                        help="Output directory for sub-calculation plot data "
                             "Default={}".format(QScfg.get("files", \
                                                 "analysefeps_subcalc_dir")),
                        default=QScfg.get("files", "analysefeps_subcalc_dir"))
    optarg.add_argument("-v", "--version", action="version",
                        version=get_version_full())
    optarg.add_argument("-h", "--help", action="help", help="show this help "
                        "  message and exit")


    if len(sys.argv) == 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args()

    lra_l = []
    for lamb in args.lra_l:
        try:
            lamb = float(lamb)
            if lamb < 0 or lamb > 1:
                raise ValueError
        except ValueError:
            print("FATAL! LRA lambdas make no sense. 0<lambda<1 please.")
            sys.exit(1)
        lra_l.append(lamb)

    if args.subcalcs and os.path.lexists(args.subcalc_dir):
        print("Directory '{}' exists. Please (re)move it or "\
              "use --subcalc_dir.".format(args.subcalc_dir))
        sys.exit(1)

    # analyse the outputs
    qos = [os.path.join(md, args.qfep_out) for md in sorted(args.fepdirs)]
    qaf = QAnalyseFeps(qos, lra_lambdas=lra_l)

    stats, fails = [], []

    # get the statistics
    stats.append(qaf.stats_str)
    for sub_calc_key, sub_calc in sorted(six.iteritems(qaf.sub_calcs)):
        stats.append(sub_calc.stats_str)

    # get those that completely failed
    if qaf.failed:
        fails.append("Failed to parse:")
    for failed_path, failed_msg in sorted(six.iteritems(qaf.failed)):
        relp = os.path.relpath(failed_path)
        fails.append("-> {}: {}".format(relp, failed_msg))

    # get those that didn't produce dG*/dG0
    if qaf.failed_dg:
        fails.append("Failed to produce dGa/dG0:")
    for failed_path, failed_msg in sorted(six.iteritems(qaf.failed_dg)):
        relp = os.path.relpath(failed_path)
        fails.append("-> {}: {}".format(relp, failed_msg))

    stats = "\n".join(stats)
    fails = "\n".join(fails) or None

    summary = """
----------------------------------- SUMMARY -----------------------------------
# Analysed with: QTools/q_analysefeps.py ({version})
# Work dir: {cwd}
# Date: {date}
# CMDline: {cmdline}


----- Statistics -----

{stats}

------- Fails --------

{fails}
-------------------------------------------------------------------------------
""".format(version=__version__, date=time.ctime(), cwd=os.getcwd(),
           stats=stats, fails=fails, cmdline=" ".join(sys.argv))

    print(summary)

    if not qaf.qfos:
        print("\nFATAL! None of the outputs could be parsed!")
        print("Are you running an ancient Q version? Then don't...")
        print("If not, report a bug.")
        sys.exit(1)


    # save some useful data
    output_string = """
------------------------------- Free energies ---------------------------------
{}
{}
""".format(qaf.dg_all, summary)

    fn_out = args.output_fn
    backup = backup_file(fn_out)
    open(fn_out, "w").write(output_string)

    if backup:
        print("Wrote '{}'...    # Backed up to '{}'".format(fn_out, backup))
    else:
        print("Wrote '{}'...".format(fn_out))

    # convert plots to json and write them out
    fn_out = args.plots_out
    plots = qaf.plotdata
    jsonenc = plotdata.PlotDataJSONEncoder(indent=2, separators=(",", ": "))
    backup = backup_file(fn_out)
    open(fn_out, 'w').write(jsonenc.encode(plots))
    if backup:
        print("Wrote '{}'... (q_plot.py is your friend)   "\
              "# Backed up to '{}'".format(fn_out, backup))
    else:
        print("Wrote '{}'... (q_plot.py is your friend)".format(fn_out))

    # if there are sub-calculations in the outputs
    if qaf.sub_calcs:
        if not args.subcalcs:
            print("\nNote: These sub-calculations were found: {}. "\
                  "Use --subcalcs to write out the plot data."\
                  "".format(", ".join(qaf.sub_calcs)))
            sys.exit(1)
        else:
            os.mkdir(args.subcalc_dir)
            for subcalc_key, subcalc in six.iteritems(qaf.sub_calcs):
                fn_out = os.path.join(args.subcalc_dir,
                                      "qaf.{}.json".format(subcalc_key))

                open(fn_out, 'w').write(jsonenc.encode(subcalc.plotdata))
                print("Wrote '{}'... (q_plot.py is your "\
                      "friend)".format(fn_out))
Example #10
0
def test_backupfile(tmpdir):
    shutil.copy("data/qdyn.inp.1", tmpdir.dirname)
    fn = backup_file(os.path.join(tmpdir.dirname, "qdyn.inp.1"))
    inpstr = open("data/qdyn.inp.1").read()
    inpstr2 = open(os.path.join(tmpdir.dirname, fn)).read()
    assert inpstr == inpstr2
Example #11
0
    ch_groups = residue_lib.charge_groups

# iterate over the charge groups and rescale the charges
for ch_group in ch_groups:
    try:
        residue_lib.rescale(ch_group, args.threshold)
    except QLibError as e:
        print "Library error: {}".format(str(e))
        sys.exit(1)

print "Checking the library..."
try:
    qlib.check_valid()
except QLibError as e:
    print "Library error: {}".format(str(e))
    sys.exit(1)
print "Done"
print

backup = backup_file(args.lib_file)
if backup:
    print "Backed up '{}' to '{}'".format(args.lib_file, backup)
outstring = """# Generated with {}, version {}
# Date: {}
#
{}
""".format(os.path.basename(__file__), __version__, time.ctime(),
           qlib.get_string())
open(args.lib_file, 'w').write(outstring)
print "Successfully modified the library."