Exemple #1
0
    def segmentation(self):

        import segment_dialog as sd
        s = sd.current_segmentation()
        if s is None and sd.segmentation_map():
            d = sd.volume_segmentation_dialog()
            s = d.Segment(group=False)
            for r in s.regions:
                r.set_color(self.ungrouped_color)
            v = s.volume_data()
            if v:
                v.display = False
        if s is None:
            print 'mouse down: no current segmentation'
            return None
        return s
Exemple #2
0
    def Icos2Map0(self):

        dmap = segmentation_map()
        if dmap == None:
            self.umsg("Select a map in Segment Map dialog")
            return

        mm = dmap.full_matrix()
        #m1 = numpy.zeros_like ( mm )

        # transform to index reference frame of ref_map
        f1 = dmap.data.ijk_to_xyz_transform

        nm = numpy.zeros_like(mm)

        minr, maxr = 300, 400
        pt = numpy.array([[0, 0, 0]], numpy.float32)
        p = pt[0]

        im, jm, km = dmap.data.size[0] / 2, dmap.data.size[
            1] / 2, dmap.data.size[2] / 2

        for i in range(dmap.data.size[0]):
            self.status("Masking %s %.1f->%.1f, %d/%d" %
                        (dmap.name, minr, maxr, i + 1, dmap.data.size[0]))
            di = abs(i - im) * dmap.data.step[0]

            for j in range(dmap.data.size[1]):
                dj = abs(j - jm) * dmap.data.step[1]

                for k in range(dmap.data.size[2]):
                    dk = abs(k - km) * dmap.data.step[2]
                    r = numpy.sqrt(di * di + dj * dj + dk * dk)
                    if dk >= minr and dk < maxr:
                        nm[k, j, i] = mm[k, j, i]

        ndata = VolumeData.Array_Grid_Data(nm, dmap.data.origin,
                                           dmap.data.step,
                                           dmap.data.cell_angles)
        try:
            nvg = VolumeViewer.volume.add_data_set(ndata, None)
        except:
            nvg = VolumeViewer.volume.volume_from_grid_data(ndata)
        nvg.name = dmap.name + "__%.0f--to--%.0f" % (minr, maxr)
Exemple #3
0
    def Icos2Map0(self):

        smod = self.GetMod("Icosahedron Faces")
        if smod == None:
            self.umsg("No Icosahedron2 model found")
            return

        dmap = segmentation_map()
        if dmap == None:
            self.umsg("Select a map in Segment Map dialog")
            return

        sepRs = self.segRads.get().split(",")
        print "Sep rads:", sepRs

        if len(sepRs) != 2:
            self.umsg("Enter two radii separated by a comma")
            return

        try:
            start_rad = int(sepRs[0])
        except:
            self.umsg("Invalid start radius: " + sepRs[0])
            return

        try:
            end_rad = int(sepRs[1])
        except:
            self.umsg("Invalid end radius: " + sepRs[1])
            return

        if end_rad <= start_rad:
            self.umsg("End rad should be larger than start rad :) ")
            return

        self.umsg("Mask %s, %d -> %d" % (dmap.name, start_rad, end_rad))

        self.MakeTNorms(smod)

        import time
        start = time.time()

        mm = dmap.full_matrix()
        #m1 = numpy.zeros_like ( mm )

        # transform to index reference frame of ref_map
        f1 = dmap.data.ijk_to_xyz_transform

        from _contour import affine_transform_vertices as transform_vertices
        #f2 = xform_matrix ( mask_map.openState.xform )
        #f3 = xform_matrix ( ref_map.openState.xform.inverse() )
        #f4 = ref_map.data.xyz_to_ijk_transform
        #tf = multiply_matrices( f2, f1 )
        #tf = multiply_matrices( f3, tf )
        #tf = multiply_matrices( f4, tf )

        nm = numpy.zeros_like(mm)

        self.updateIcos2(start_rad)
        minr, maxr = self.MinRad2(smod), self.MaxRad2(smod)
        print " - start rad %d -- min rad %.1f, max rad %.1f" % (
            start_rad, numpy.sqrt(minr), numpy.sqrt(maxr))

        done = time.time()
        elapsed = done - start
        print "Took: ", elapsed

        pt = numpy.array([[0, 0, 0]], numpy.float32)
        p = pt[0]

        for i in range(dmap.data.size[0]):
            self.status("Masking %s, outside radius %d, %d/%d" %
                        (dmap.name, start_rad, i + 1, dmap.data.size[0]))
            p[0] = i * f1[0][0] + f1[0][3]
            for j in range(dmap.data.size[1]):
                p[1] = j * f1[1][1] + f1[1][3]
                for k in range(dmap.data.size[2]):
                    #p[2] = k * f1[2][2] + f1[2][3]
                    #pt = numpy.array ( [[i,j,k]], numpy.float32 )
                    #p[0],p[1],p[2] = ti,tj,tk
                    #transform_vertices ( pt, f1 )
                    p[2] = k * f1[2][2] + f1[2][3]
                    ptr = numpy.sum(p * p)
                    if ptr < minr:
                        pass
                    elif ptr > maxr:
                        nm[k, j, i] = mm[k, j, i]
                    elif self.PIsOutside(pt[0], smod):
                        nm[k, j, i] = mm[k, j, i]

        self.updateIcos2(end_rad)
        minr, maxr = self.MinRad2(smod), self.MaxRad2(smod)
        print " - end rad %d -- min rad %.1f, max rad %.1f" % (
            start_rad, numpy.sqrt(minr), numpy.sqrt(maxr))

        for i in range(dmap.data.size[0]):
            self.status("Masking %s, inside radius %d, %d/%d" %
                        (dmap.name, end_rad, i + 1, dmap.data.size[0]))
            p[0] = i * f1[0][0] + f1[0][3]
            for j in range(dmap.data.size[1]):
                p[1] = j * f1[1][1] + f1[1][3]
                for k in range(dmap.data.size[2]):
                    #pt = numpy.array ( [[i,j,k]], numpy.float32 )
                    #p[0],p[1],p[2] = ti,tj,tk
                    #transform_vertices ( pt, f1 )
                    p[2] = k * f1[2][2] + f1[2][3]
                    ptr = numpy.sum(p * p)
                    if ptr < minr:
                        continue
                    elif ptr > maxr:
                        nm[k, j, i] = 0.0
                    elif self.PIsOutside(p, smod):
                        nm[k, j, i] = 0.0

        ndata = VolumeData.Array_Grid_Data(nm, dmap.data.origin,
                                           dmap.data.step,
                                           dmap.data.cell_angles)
        try:
            nvg = VolumeViewer.volume.add_data_set(ndata, None)
        except:
            nvg = VolumeViewer.volume.volume_from_grid_data(ndata)
        nvg.name = dmap.name + "__%d--to--%d_fast" % (start_rad, end_rad)

        done = time.time()
        elapsed = done - start
        print "Took: ", elapsed
Exemple #4
0
    def Icos2CC(self):

        smod = self.GetMod("Icosahedron Faces")

        if smod == None:
            self.umsg("No Icos2 found")
            return

        dmap = segmentation_map()
        if dmap == None:
            self.umsg("No map selected")
            return

        start_rad, end_rad = 0, 0
        try:
            start_rad = int(self.startRad.get())
        except:
            self.umsg("Invalid start radius: " + self.startRad.get())
            return

        try:
            end_rad = int(self.endRad.get())
        except:
            self.umsg("Invalid end radius: " + self.endRad.get())
            return

        if end_rad <= start_rad:
            self.umsg("End rad should be larger than start rad :) ")
            return

        self.umsg("CC in %s" % dmap.name)

        fname = "IcosCC.txt"
        if hasattr(self, 'fi'):
            fname = "IcosCC_%d.txt" % self.fi

        p1 = smod.icosVerts[smod.icosTris[0][0]]
        rS = numpy.sqrt(numpy.sum(p1 * p1))
        print " - rad before: ", rS

        ccs = []
        #fp = open ( fname, "w" )
        for rad in range(start_rad, end_rad + 1):
            self.updateIcos2(rad)
            cc = self.IcosCC(smod, dmap)
            self.status("Rad: %d, CC: %.4f" % (rad, cc))
            #fp.write ( "%d\t%f\n" % (rad, cc) )
            ccs.append([rad, cc])

        #fp.close ()

        self.updateIcos2(rS)

        def save(okay, dialog):
            if okay:
                paths = dialog.getPaths()
                if paths:
                    path = paths[0]
                    self.umsg("Saved CCs to: " + path)
                    f = open(path, "w")
                    for rad, cc in ccs:
                        f.write("%d\t%f\n" % (rad, cc))
                    f.close()

        from OpenSave import SaveModeless
        SaveModeless(title='Save Cross Correlations',
                     filters=[('TXT', '*.txt', '.txt')],
                     initialfile="rad_cc.txt",
                     command=save)
Exemple #5
0
    def LineCC(self):

        dmap = segmentation_map()
        if dmap == None:
            umsg("No map selected")
            return

        from chimera import Molecule
        mlist = OML(modelTypes=[Molecule])
        if len(mlist) == 0:
            umsg("No molecule found")
            return

        mol = mlist[0]

        print "Doing line CC in " + dmap.name + " using mol " + mol.name

        print dmap.openState.xform
        print mol.openState.xform

        rccs = []
        rmap = None
        rmap_pos = None
        rpoints, rpoint_weights = None, None
        xf = None

        resolution = 10.0

        for ri, res in enumerate(mol.residues):
            try:
                cat = res.atomsMap["CA"][0]
            except:
                continue

            if rmap == None:
                rmap = makeMap("#%d:%d@CA" % (mol.id, res.id.position),
                               resolution, 1, (.5, .5, .5, 1.0), "resmap")
                rmap_pos = cat.coord().toVector()
                print " - sphere map pos ", rmap_pos
                #rpoints, rpoint_weights = fit_points (rmap)
                rpoints, rpoint_weights = fit_points_old(rmap)
                xf = rmap.openState.xform

                break

        for radi in range(0, 1300, 1):

            #d = cat.coord() - rmap_pos
            d = chimera.Vector(0, 0, radi) - rmap_pos
            #print chimera.Vector(0,0,radi)
            trx = chimera.Xform.translation(d)
            #xf = dmap.openState.xform.inverse
            xf2 = xf.__copy__()
            xf2.multiply(trx)

            rmap.openState.xform = xf2
            break

            if 1:
                rmap_values = dmap.interpolated_values(rpoints, xf2)
                olap, corr = overlap_and_correlation(rpoint_weights,
                                                     rmap_values)

                if radi % 100 == 0:
                    print " %d - overlap: %f, cross-correlation: %f" % (
                        radi, olap, corr)

                rccs.append([radi, corr])
            #print corr,

        #chimera.openModels.close ( rmap )

        fp = open("lineCC.txt", "w")
        for rad, cc in rccs:
            fp.write("%d\t%f\n" % (rad, cc))

        fp.close()
Exemple #6
0
    def Segment2(self):

        dmap = segmentation_map()
        if dmap == None:
            self.umsg("Please select a map in the Segment Map Dialog")
            return

        smod = current_segmentation()
        if smod == None:
            self.umsg(
                "Please select a Current Segmentation in the Segment Map dialog"
            )
            return

        print "Seg has %d regions" % (len(smod.regions))

        imod2 = self.GetMod("Icosahedron Faces")
        if imod2 == None:
            self.umsg("No Icosahedron2 model found")
            return

        sepRs = []
        for rstr in self.segRads.get().split(","):
            try:
                radv = float(rstr)
            except:
                self.umsg(
                    "Error parsing distances; enter only numbers and commas")
                return

            sepRs.append(radv)

        print "Sep rads:", sepRs
        regs = list(smod.regions)
        sregs = []

        f1 = dmap.data.ijk_to_xyz_transform
        from _contour import affine_transform_vertices as transform_vertices

        self.MakeTNorms(imod2)

        for i, srad in enumerate(sepRs):

            self.umsg("Segmenting using %s - rad %.1f - %d regs" %
                      (imod2.name, srad, len(regs)))
            self.updateIcos2(srad)

            gregs, left_regs = [], []

            for ri, r in enumerate(regs):

                p = r.max_point
                #pt = numpy.array ( [ [ p[2],p[1],p[0] ] ], numpy.float32 )
                pt = numpy.array([[p[2], p[1], p[0]]], numpy.float32)
                transform_vertices(pt, f1)

                c = r.center_of_points()
                ptc = numpy.array([c], numpy.float32)

                #print ri, p, c, pt[0]
                #return

                if self.PIsOutside(ptc[0], imod2):
                    #print " - outside"
                    left_regs.append(r)
                else:
                    #print " - inside"
                    gregs.append(r)

                if ri % 1000 == 0:
                    self.status("Segmenting using %s - rad %.1f - %s/%s regs" %
                                (imod2.name, srad, "{:,}".format(ri),
                                 "{:,}".format(len(regs))))

            sregs.append(gregs)
            regs = left_regs
            print " - rad %.1f - %d regions inside" % (srad, len(gregs))

        print " - remaining %d regions" % (len(regs))
        sregs.append(regs)

        for i, regs in enumerate(sregs):
            self.status("Segmenting, layer %d - %d regs" % (i, len(regs)))
            if len(regs) > 1:
                try:
                    smod.join_regions(regs)
                except:
                    self.umsg(
                        "An error occurred - regions may have changed - please start again."
                    )
                    smod.display_regions()
                    return

        smod.display_regions()

        self.umsg("Done, created %d groups based on radial distances" %
                  len(sregs))

        from segment_dialog import volume_segmentation_dialog
        volume_segmentation_dialog().ReportRegionCount(smod)
Exemple #7
0
    def Segment(self):

        segMap = segmentation_map()
        if segMap == None:
            self.umsg("Please select a map in the Segment Map Dialog")
            return

        smod = current_segmentation()
        if smod == None:
            self.umsg(
                "Please select a Current Segmentation in the Segment Map dialog"
            )
            return

        print "Seg has %d regions" % (len(smod.regions))

        print "Seg rads:", self.segRads.get()

        if hasattr(self, 'distByReg'):
            print "Found distByReg"
        else:
            self.umsg("Make Histogram first.")
            return

        sepRs = []
        for rstr in self.segRads.get().split(","):
            try:
                radv = float(rstr)
            except:
                self.umsg(
                    "Error parsing distances; enter only numbers and commas")
                return

            sepRs.append(radv)
        sepRs.append(1e99)

        self.umsg("Segmenting...")

        print "Sep rads:", sepRs
        sregs = []
        for r in sepRs:
            sregs.append([])

        for reg, rad in self.distByReg.iteritems():
            #if reg.surface_piece != None :
            #    if reg.surface_piece.display == False :
            #        continue

            minRad = 0.0
            for i, maxRad in enumerate(sepRs):
                if rad > minRad and rad <= maxRad:
                    sregs[i].append(reg)
                    break

        for i, regs in enumerate(sregs):
            print "%d - %d regs" % (i, len(regs))
            if len(regs) > 1:
                try:
                    smod.join_regions(regs)
                except:
                    self.umsg(
                        "An error occurred - regions may have changed - please start again."
                    )
                    smod.display_regions()
                    return

        smod.display_regions()

        self.umsg("Done, created %d groups based on radial distances" %
                  len(sregs))

        from segment_dialog import volume_segmentation_dialog
        volume_segmentation_dialog().ReportRegionCount(smod)
Exemple #8
0
    def MakeHist(self):

        segMap = segmentation_map()
        if segMap == None:
            self.umsg("Please select a map in the Segment Map Dialog")
            return

        import axes
        reload(axes)
        pts, weights = axes.map_points(segMap)
        print len(pts)

        COM, U, S, V = prAxes(pts)

        print " - COM : ", COM

        smod = current_segmentation()
        if smod == None:
            self.umsg(
                "Please select a Current Segmentation in the Segment Map dialog"
            )
            return

        print "Seg has %d regions" % (len(smod.regions))

        if hasattr(self, 'icos_vecs'):
            self.umsg("Making (icosahedrally corrected) histogram...")
        else:
            self.umsg("Making histogram...")

        nregs, last = len(smod.regions), 0
        regs = list(smod.regions)
        distByReg = {}
        for ri, r in enumerate(regs):

            if 0 and r.surface_piece != None:
                if r.surface_piece.display == False:
                    print "i" + ri,
                    continue
            try:
                p = r.center_of_points()
            except:
                print "+"
                continue

            rvec = chimera.Vector(p[0], p[1], p[2]) - chimera.Vector(
                COM[0], COM[1], COM[2])
            rad = 0.0

            if hasattr(self, 'icos_vecs'):
                for ivec in self.icos_vecs:
                    irad = ivec * rvec
                    if irad > rad:
                        rad = irad
            else:
                rad = rvec.length

            distByReg[r] = rad
            at = int(numpy.floor(10.0 * (ri + 1) / nregs))
            if at > last:
                #print at,
                if hasattr(self, 'icos_vecs'):
                    self.status(
                        "Making (icosahedrally corrected) histogram %d regions, at %d"
                        % (len(regs), ri + 1))
                else:
                    self.status("Making histogram %d regions, at %d" %
                                (len(regs), ri + 1))
                last = at
                at += 1

        print ""

        dists = distByReg.values()
        maxDist = max(dists) + 0.01
        minDist = min(dists)
        nbins = int(self.numBins.get())
        dr = (maxDist - minDist) / float(nbins)
        print "%d dists - max %.2f, min %.2f, nb %d, dr %.2f" % (
            len(dists), maxDist, minDist, nbins, dr)

        bins = []
        for i in range(nbins):
            bins.append([])

        print "bad bins: ",
        for regm, rad in distByReg.iteritems():
            bini = int(numpy.floor((rad - minDist) / dr))
            if bini >= len(bins):
                print bini,
                bini = len(bins) - 1
            bins[bini].append(regm)

        print ""

        if 0:
            f = open("rads.txt", "w")
            for k, regs in enumerate(bins):
                v = len(regs)
                vmin = minDist + k * dr
                vmax = minDist + (k + 1) * dr
                rm = .5 * (vmin + vmax)
                vn = v / (4 * 3.14 * rm * rm)
                f.write("%d\t%.2f\t%.2f\t%d\t%f\n" % (k, vmin, vmax, v, vn))
            f.close()

        self.distByReg = distByReg

        #print self.distByReg

        def save(okay, dialog):
            if okay:
                paths = dialog.getPaths()
                if paths:
                    path = paths[0]
                    self.umsg("Saved plot to: " + path)
                    f = open(path, "w")
                    for k, regs in enumerate(bins):
                        v = len(regs)
                        vmin = minDist + k * dr
                        vmax = minDist + (k + 1) * dr
                        rm = .5 * (vmin + vmax)
                        vn = v / (4 * 3.14 * rm * rm)
                        f.write("%.2f,%d\n" % (vmin, v))
                    f.close()

        from OpenSave import SaveModeless
        SaveModeless(title='Save Histogram',
                     filters=[('TXT', '*.txt', '.txt')],
                     initialfile="dist_hist.txt",
                     command=save)