Beispiel #1
0
def async_calculation(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.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 
Beispiel #2
0
 def test_global_search_with_rotation(self):
     ref_box=self.ref_proj_na.get_bounding_square(margin=30)
     ref_img, _=self.ref_proj_na.rasterize(70, bounding_square=ref_box, rotate=45)
     scale=ref_box[1]-ref_box[0]
     distance, img, params = fph.globally_minimal_distance(ref_img, scale, self.cg, virtual_atoms=False, verbose = True)
     #fig, ax=plt.subplots(2)
     #ax[0].imshow(ref_img, interpolation="none", cmap='gray')
     #ax[1].imshow(img, interpolation="none", cmap='gray')
     #ax[1].set_title("{} distance".format(distance))
     #plt.show()
     self.assertLessEqual(distance, 3)
     #self.assertLessEqual(abs(params[1]-45), 5)
     nptest.assert_allclose(params[0], fph.to_polar([2,0,-1.2])[1:], atol=5)
Beispiel #3
0
 def test_global_search(self):
     ref_box=self.ref_proj_na.get_bounding_square(margin=30)
     ref_img, _=self.ref_proj_na.rasterize(70, bounding_square=ref_box, rotate=45)
     scale=ref_box[1]-ref_box[0]
     distance, img, params = fph.globally_minimal_distance(ref_img, scale, self.cg, virtual_atoms=False)
     #fig, ax=plt.subplots(2)
     #ax[0].imshow(ref_img, interpolation="none", cmap='gray')
     #ax[1].imshow(img, interpolation="none", cmap='gray')
     #ax[1].set_title("{} distance".format(distance))
     #plt.show()
     self.assertLessEqual(distance, 3)
     #self.assertLessEqual(abs(params[1]-45), 5)
     nptest.assert_allclose(params[0], fph.to_polar([2,0,-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()
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
     except ValueError:
           parser.error('The reference *.cg file needs a "project" line.')
     if args.scale:            
         ref_box=fph.get_box(ref_proj, args.scale)
     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()
Beispiel #7
0
import matplotlib.pyplot as plt
import scipy.signal
import scipy.ndimage
import scipy.misc

import multiprocessing
from functools import partial

WIDTH=500

def async_calculation((ref_img, ref_box), numFiles, filenames):
    try:
        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: