Beispiel #1
0
 def test_local_search(self):
     ref_box=self.ref_proj.get_bounding_square(margin=30)
     ref_img, _=self.ref_proj.rasterize(70, bounding_square=ref_box, rotate=0)
     scale=ref_box[1]-ref_box[0]
     distance, img, params = fph.locally_minimal_distance(ref_img, scale, self.cg, proj_dir=list(fph.to_polar([1,1.1,1.2]))[1:])
     self.assertLessEqual(distance, 2)
     self.assertLessEqual(abs(params[1]%360), 5)
     nptest.assert_allclose(params[0], list(fph.to_polar([1,1.1,1.2]))[1:], atol=5)
Beispiel #2
0
 def test_local_search(self):
     ref_box=self.ref_proj.get_bounding_square(margin=30)
     ref_img, _=self.ref_proj.rasterize(70, bounding_square=ref_box, rotate=0)
     scale=ref_box[1]-ref_box[0]
     distance, img, params = fph.locally_minimal_distance(ref_img, scale, self.cg, proj_dir=list(fph.to_polar([1,1.1,1.2]))[1:])
     self.assertLessEqual(distance, 2)
     self.assertLessEqual(abs(params[1]%360), 5)
     nptest.assert_allclose(params[0], list(fph.to_polar([1,1.1,1.2]))[1:], atol=5)
Beispiel #3
0
def parallel_localOpt(im_and_box, numFiles, filenames):
    (ref_img, ref_box) = im_and_box
    try:
        distances=[]
        for j in range(numFiles):
            cg=ftmc.CoarseGrainRNA(filenames[j])
            distance, img, _ = fph.locally_minimal_distance(ref_img, ref_box[1]-ref_box[0], cg)
            distances.append(distance)
        return distances
    except KeyboardInterrupt:
        print("In worker {}: Keyboard Interrupt".format(id(ref_img)))
        return
def main(args):

    cgs = []
    projs = []
    for file_ in args.files:
        cgs.append(ftmc.CoarseGrainRNA(file_))
        try:
            projs.append(ftmp.Projection2D(cgs[-1]))
        except ValueError:
            projs.append(None)

    p_rmsds = OrderedDict()
    cg_rmsds = OrderedDict()
    p_rmsds[0] = 0.0
    cg_rmsds[0] = 0.0

    if "," in args.max_diff:
        diffs = map(int, args.max_diff.split(","))
    else:
        diffs = range(1, int(args.max_diff) + 1)
    for diff in diffs:
        print ("diff {}".format(diff))
        prmsd = 0
        cgrmsd = 0
        count = 0
        pcount = 0
        for i in range(0, len(cgs) - diff):
            count += 1
            try:
                vrs1 = np.array([x for p in sorted(projs[i]._coords.keys()) for x in projs[i]._coords[p]])
                vrs2 = np.array([x for p in sorted(projs[i + diff]._coords.keys()) for x in projs[i + diff]._coords[p]])
                prmsd += ftms.rmsd(vrs1, vrs2)
                pcount += 1
            except:
                pass
            cgrmsd += ftms.cg_rmsd(cgs[i], cgs[i + diff])
        if count:
            cg_rmsds[diff] = cgrmsd / count
        if pcount:
            p_rmsds[diff] = prmsd / pcount
    print "projection RMSDs:", p_rmsds
    print "3D-RMSDs:", cg_rmsds
    import matplotlib.pyplot as plt

    if args.target_structure and args.hausdorff_reference:
        fig, (ax, axT, axH) = plt.subplots(3)
    elif args.target_structure:
        fig, (ax, axT) = plt.subplots(2)
    elif args.hausdorff_reference:
        fig, (ax, axH) = plt.subplots(2)
    else:
        fig, ax = plt.subplots()

    if args.target_structure:
        target = ftmc.CoarseGrainRNA(args.target_structure)
        target_rmsds = []
        target_proj_rmsds = []
        try:
            target_proj = ftmp.Projection2D(target)
        except ValueError:
            pass
        else:
            target_vrs = np.array([x for p in sorted(target_proj._coords.keys()) for x in target_proj._coords[p]])
            for proj in projs:
                try:
                    vrs1 = np.array([x for p in sorted(proj._coords.keys()) for x in proj._coords[p]])
                    prmsd = ftms.rmsd(vrs1, target_vrs)
                    target_proj_rmsds.append(prmsd)
                except:
                    target_proj_rmsds.append(float("nan"))
        target_vrs = ftug.bg_virtual_residues(target)
        for cg in cgs:
            vrs1 = ftug.bg_virtual_residues(cg)
            cgrmsd = ftms.rmsd(vrs1, target_vrs)
            target_rmsds.append(cgrmsd)
        xval = np.arange(len(cgs)) * args.step_size
        if target_proj_rmsds:
            axT.plot(xval, target_proj_rmsds, label="Projection", color="green")
        axT.plot(xval, target_rmsds, label="3D", color="blue")
        axT.set_title("RMSD to target structure")
        axT.set_xlabel("step")
        axT.set_ylabel("RMSD")
        leg = axT.legend(framealpha=0.8, fancybox=True)
        leg.get_frame().set_linewidth(0.0)
        plt.subplots_adjust(hspace=0.4)
    if args.hausdorff_reference:
        ref_img = scipy.ndimage.imread(args.hausdorff_reference)
        ref_quarter = scipy.ndimage.zoom(ref_img, 0.3) > 150
        degrees = get_refimg_longest_axis(ref_img)
        global_optima = []
        local_optima = []
        for cg in cgs:
            score, img, params = fph.try_parameters(ref_img, args.hausdorff_scale, cg, degrees)
            local_optima.append(score)
            s, i, params = fph.globally_minimal_distance(
                ref_quarter, args.hausdorff_scale, cg, start_points=40, starting_rotations=degrees, virtual_atoms=False
            )
            score, img, params = fph.locally_minimal_distance(
                ref_img, args.hausdorff_scale, cg, params[1], params[2], params[0], maxiter=200
            )
            global_optima.append(score)

        axH.plot(xval, global_optima, label="Global Minimization", color="red")
        axH.plot(xval, local_optima, label="Local Minimization", color="lavender")
        axH.set_title("Hausdorff Distance to reference image")
        axH.set_xlabel("step")
        axH.set_ylabel("Hausdorff Distance")
        leg = axH.legend(framealpha=0.8, fancybox=True)
        leg.get_frame().set_linewidth(0.0)
        plt.subplots_adjust(hspace=0.4)

    p_rmsds = np.array(p_rmsds.items())
    cg_rmsds = np.array(cg_rmsds.items())
    ax.plot(p_rmsds[:, 0] * args.step_size, p_rmsds[:, 1], label="Projection", color="green", marker="o")
    ax.plot(cg_rmsds[:, 0] * args.step_size, cg_rmsds[:, 1], label="3D", color="blue", marker="o")
    ax.set_title("Average RMSD between structures X steps apart.")
    ax.set_xlabel("steps apart")
    ax.set_ylabel("RMSD")
    leg = ax.legend(framealpha=0.8, fancybox=True)
    leg.get_frame().set_linewidth(0.0)
    fig.patch.set_facecolor("white")
    if args.save_fig:
        with open(args.save_fig, "w") as f:
            pickle.dump(fig, f)
    plt.show()
Beispiel #5
0
def main(args):

    cgs = []
    projs = []
    for file_ in args.files:
        cgs.append(ftmc.CoarseGrainRNA(file_))
        try:
            projs.append(ftmp.Projection2D(cgs[-1]))
        except ValueError:
            projs.append(None)

    p_rmsds = OrderedDict()
    cg_rmsds = OrderedDict()
    p_rmsds[0] = 0.
    cg_rmsds[0] = 0.

    if "," in args.max_diff:
        diffs = map(int, args.max_diff.split(","))
    else:
        diffs = range(1, int(args.max_diff) + 1)
    for diff in diffs:
        print("diff {}".format(diff))
        prmsd = 0
        cgrmsd = 0
        count = 0
        pcount = 0
        for i in range(0, len(cgs) - diff):
            count += 1
            try:
                vrs1 = np.array([
                    x for p in sorted(projs[i]._coords.keys())
                    for x in projs[i]._coords[p]
                ])
                vrs2 = np.array([
                    x for p in sorted(projs[i + diff]._coords.keys())
                    for x in projs[i + diff]._coords[p]
                ])
                prmsd += ftms.rmsd(vrs1, vrs2)
                pcount += 1
            except:
                pass
            cgrmsd += ftms.cg_rmsd(cgs[i], cgs[i + diff])
        if count:
            cg_rmsds[diff] = cgrmsd / count
        if pcount:
            p_rmsds[diff] = prmsd / pcount
    print("projection RMSDs:", p_rmsds)
    print("3D-RMSDs:", cg_rmsds)
    import matplotlib.pyplot as plt
    if args.target_structure and args.hausdorff_reference:
        fig, (ax, axT, axH) = plt.subplots(3)
    elif args.target_structure:
        fig, (ax, axT) = plt.subplots(2)
    elif args.hausdorff_reference:
        fig, (ax, axH) = plt.subplots(2)
    else:
        fig, ax = plt.subplots()

    if args.target_structure:
        target = ftmc.CoarseGrainRNA(args.target_structure)
        target_rmsds = []
        target_proj_rmsds = []
        try:
            target_proj = ftmp.Projection2D(target)
        except ValueError:
            pass
        else:
            target_vrs = np.array([
                x for p in sorted(target_proj._coords.keys())
                for x in target_proj._coords[p]
            ])
            for proj in projs:
                try:
                    vrs1 = np.array([
                        x for p in sorted(proj._coords.keys())
                        for x in proj._coords[p]
                    ])
                    prmsd = ftms.rmsd(vrs1, target_vrs)
                    target_proj_rmsds.append(prmsd)
                except:
                    target_proj_rmsds.append(float("nan"))
        target_vrs = target.get_ordered_virtual_residue_poss()
        for cg in cgs:
            vrs1 = cg.get_ordered_virtual_residue_poss()
            cgrmsd = ftms.rmsd(vrs1, target_vrs)
            target_rmsds.append(cgrmsd)
        xval = np.arange(len(cgs)) * args.step_size
        if target_proj_rmsds:
            axT.plot(xval,
                     target_proj_rmsds,
                     label="Projection",
                     color="green")
        axT.plot(xval, target_rmsds, label="3D", color="blue")
        axT.set_title("RMSD to target structure")
        axT.set_xlabel("step")
        axT.set_ylabel("RMSD")
        leg = axT.legend(framealpha=0.8, fancybox=True)
        leg.get_frame().set_linewidth(0.0)
        plt.subplots_adjust(hspace=0.4)
    if args.hausdorff_reference:
        ref_img = scipy.ndimage.imread(args.hausdorff_reference)
        ref_quarter = (scipy.ndimage.zoom(ref_img, 0.3) > 150)
        degrees = get_refimg_longest_axis(ref_img)
        global_optima = []
        local_optima = []
        for cg in cgs:
            score, img, params = fph.try_parameters(ref_img,
                                                    args.hausdorff_scale, cg,
                                                    degrees)
            local_optima.append(score)
            s, i, params = fph.globally_minimal_distance(
                ref_quarter,
                args.hausdorff_scale,
                cg,
                start_points=40,
                starting_rotations=degrees,
                virtual_atoms=False)
            score, img, params = fph.locally_minimal_distance(
                ref_img,
                args.hausdorff_scale,
                cg,
                params[1],
                params[2],
                params[0],
                maxiter=200)
            global_optima.append(score)

        axH.plot(xval, global_optima, label="Global Minimization", color="red")
        axH.plot(xval,
                 local_optima,
                 label="Local Minimization",
                 color="lavender")
        axH.set_title("Hausdorff Distance to reference image")
        axH.set_xlabel("step")
        axH.set_ylabel("Hausdorff Distance")
        leg = axH.legend(framealpha=0.8, fancybox=True)
        leg.get_frame().set_linewidth(0.0)
        plt.subplots_adjust(hspace=0.4)

    p_rmsds = np.array(list(p_rmsds.items()))
    cg_rmsds = np.array(list(cg_rmsds.items()))
    ax.plot(p_rmsds[:, 0] * args.step_size,
            p_rmsds[:, 1],
            label="Projection",
            color="green",
            marker="o")
    ax.plot(cg_rmsds[:, 0] * args.step_size,
            cg_rmsds[:, 1],
            label="3D",
            color="blue",
            marker="o")
    ax.set_title("Average RMSD between structures X steps apart.")
    ax.set_xlabel("steps apart")
    ax.set_ylabel("RMSD")
    leg = ax.legend(framealpha=0.8, fancybox=True)
    leg.get_frame().set_linewidth(0.0)
    fig.patch.set_facecolor('white')
    if args.save_fig:
        with open(args.save_fig, "w") as f:
            pickle.dump(fig, f)
    plt.show()
Beispiel #6
0
        distances=[]
        for j in range(numFiles):
            cg=ftmc.CoarseGrainRNA(filenames[j])
            distance, img, _ = fph.globally_minimal_distance(ref_img, ref_box[1]-ref_box[0], cg)
            distances.append(distance)
        return distances
    except KeyboardInterrupt:
        print("In worker {}: Keyboard Interrupt".format(id(ref_img)))
        return 

def parallel_localOpt((ref_img, ref_box), numFiles, filenames):
    try:
        distances=[]
        for j in range(numFiles):
            cg=ftmc.CoarseGrainRNA(filenames[j])
            distance, img, _ = fph.locally_minimal_distance(ref_img, ref_box[1]-ref_box[0], cg)
            distances.append(distance)
        return distances
    except KeyboardInterrupt:
        print("In worker {}: Keyboard Interrupt".format(id(ref_img)))
        return

def get_parser():
    """
    Here all commandline & help-messages arguments are defined.

    :returns: an instance of argparse.ArgumentParser
    """
    parser = argparse.ArgumentParser()
    #Argument(s)
    parser.add_argument('files', nargs="+", help='One or more "*.cg"/"*.coord" files.')