Example #1
0
 def test_try_parameters(self):
     ref_box=self.ref_proj.get_bounding_square(margin=30)
     ref_img, _=self.ref_proj.rasterize(70, bounding_square=ref_box, rotate=45)
     scale=ref_box[1]-ref_box[0]
     distance, img, params = fph.try_parameters(ref_img, scale, self.cg, rotations=[0, 30, 60, 90, 180, 270 ], proj_directions=[list(fph.to_polar([1,1.1,1.2]))[1:]])
     self.assertLessEqual(distance, 2)
     self.assertLessEqual(abs(params[1]-45), 5)
     nptest.assert_allclose(params[0], list(fph.to_polar([1,1.1,1.2]))[1:], atol=5)
Example #2
0
 def test_try_parameters(self):
     ref_box=self.ref_proj.get_bounding_square(margin=30)
     ref_img, _=self.ref_proj.rasterize(70, bounding_square=ref_box, rotate=45)
     scale=ref_box[1]-ref_box[0]
     distance, img, params = fph.try_parameters(ref_img, scale, self.cg, rotations=[0, 30, 60, 90, 180, 270 ], proj_directions=[list(fph.to_polar([1,1.1,1.2]))[1:]])
     self.assertLessEqual(distance, 2)
     self.assertLessEqual(abs(params[1]-45), 5)
     nptest.assert_allclose(params[0], list(fph.to_polar([1,1.1,1.2]))[1:], atol=5)
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()
Example #4
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()
Example #5
0
         else:
             ref_box=ref_proj.get_bounding_square(margin=50)
             args.scale=ref_box[1]-ref_box[0]
         if args.dpi:
             ref_img, _=ref_proj.rasterize(args.dpi, bounding_square=ref_box)    
         else:
             parser.error("If the reference is not a png image, --dpi is required")
     ref_img=(ref_img>np.zeros_like(ref_img)) #Make it a boolean array
     for f in args.files:
         cg=ftmc.CoarseGrainRNA(f)
         if args.global_search or cg.project_from is None:
             distance, img, params = fph.globally_minimal_distance(ref_img, args.scale, cg)
             fname = os.path.basename(f)
             print ("{}:\t{} distance (projected from {}, rotated by {}, offset {}. Globally optimized)".format(fname, distance, params[0], params[1], params[2] ))
         else:
             distance, img, params = fph.try_parameters(ref_img, args.scale, cg)
             fname = os.path.basename(f)
             print ("{}:\t{} distance (projected from {}, rotated by {}, offset {}. Locally optimized)".format(fname, distance, params[0], params[1], params[2]))
     if args.show:
         fig, ax=plt.subplots(2)
         ax[0].imshow(ref_img, interpolation="none", cmap='gray')
         try:
             ax[1].imshow(img, interpolation="none", cmap='gray')
         except TypeError: pass # img is probably None
         ax[0].set_title("Reference")
         ax[1].set_title("{}: {} distance".format(fname, distance))
         plt.show()
 else: #No reference given. Compare all pairs.
     if not args.dpi:
         parser.error("--dpi is required if no reference is given!")
     numFiles=len(args.files)
Example #6
0
         else:
             ref_box=ref_proj.get_bounding_square(margin=50)
             args.scale=ref_box[1]-ref_box[0]
         if args.dpi:
             ref_img, _=ref_proj.rasterize(args.dpi, bounding_square=ref_box)    
         else:
             parser.error("If the reference is not a png image, --dpi is required")
     ref_img=(ref_img>np.zeros_like(ref_img)) #Make it a boolean array
     for f in args.files:
         cg=ftmc.CoarseGrainRNA(f)
         if args.global_search or cg.project_from is None:
             distance, img, params = fph.globally_minimal_distance(ref_img, args.scale, cg)
             fname = os.path.basename(f)
             print ("{}:\t{} distance (projected from {}, rotated by {}, offset {}. Globally optimized)".format(fname, distance, params[0], params[1], params[2] ))
         else:
             distance, img, params = fph.try_parameters(ref_img, args.scale, cg)
             fname = os.path.basename(f)
             print ("{}:\t{} distance (projected from {}, rotated by {}, offset {}. Locally optimized)".format(fname, distance, params[0], params[1], params[2]))
     if args.show:
         fig, ax=plt.subplots(2)
         ax[0].imshow(ref_img, interpolation="none", cmap='gray')
         try:
             ax[1].imshow(img, interpolation="none", cmap='gray')
         except TypeError: pass # img is probably None
         ax[0].set_title("Reference")
         ax[1].set_title("{}: {} distance".format(fname, distance))
         plt.show()
 else: #No reference given. Compare all pairs.
     if not args.dpi:
         parser.error("--dpi is required if no reference is given!")
     numFiles=len(args.files)