Пример #1
0
def convex_hull(a, b):
    fa = [1.0-ind for ind in a]
    fb = [1.0 - ind for ind in b]
    fc = [max(ind, jnd) for ind, jnd in zip(fa, fb)]
    points = [(ind, jnd) for ind, jnd in zip(fa, fc)]
    ch = convexHull(points)
    return [it[0] for it in ch], [it[1] for it in ch]
Пример #2
0
def convex_hull(a, b):
    fa = [1.0 - ind for ind in a]
    fb = [1.0 - ind for ind in b]
    fc = [max(ind, jnd) for ind, jnd in zip(fa, fb)]
    points = [(ind, jnd) for ind, jnd in zip(fa, fc)]
    ch = convexHull(points)
    return [it[0] for it in ch], [it[1] for it in ch]
Пример #3
0
    def set_state(self, state):
        assert self.config is not None
        self.state = state

        stance_points = []

        self.body.setPos(*self._project(_legtool.Point3D(), state.body_frame))
        self.cog.setPos(*self._project(_legtool.Point3D(), state.cog_frame))

        for leg_num, shoulder in self.shoulders.iteritems():
            if leg_num >= len(state.legs):
                continue
            shoulder_frame = _legtool.Frame()
            self.state.make_shoulder(self.config.mechanical.leg_config[leg_num],
                                     shoulder_frame)
            shoulder.setPos(*self._project(_legtool.Point3D(), shoulder_frame))

        for leg_num, leg_item in self.legs.iteritems():
            if leg_num >= len(state.legs):
                continue
            leg = state.legs[leg_num]

            point = self._project(leg.point, leg.frame)
            leg_item.setPos(*point)

            shoulder_frame = _legtool.Frame()
            self.state.make_shoulder(self.config.mechanical.leg_config[leg_num],
                                     shoulder_frame)
            shoulder_point = shoulder_frame.map_from_frame(
                leg.frame, leg.point)

            ik_result = leg.leg_ik.do_ik(_legtool.Point3D(shoulder_point.x,
                                                          shoulder_point.y,
                                                          shoulder_point.z))

            if not ik_result.valid():
                color = QtCore.Qt.red
            elif leg.mode == _legtool.LegMode.kStance:
                color = QtCore.Qt.green
                stance_points.append(point)
            elif leg.mode == _legtool.LegMode.kSwing:
                color = QtCore.Qt.yellow
            else:
                assert False, 'unknown leg mode %d' % leg.mode

            leg_item.setBrush(QtGui.QBrush(color))

        if len(stance_points) >= 3:
            self.support_poly.setVisible(True)
            hull = convexhull.convexHull(stance_points)

            poly = QtGui.QPolygonF([QtCore.QPointF(x, y) for x, y in hull])
            self.support_poly.setPolygon(poly)
        else:
            self.support_poly.setVisible(False)

        self.resize()
Пример #4
0
    def set_state(self, state):
        assert self.config is not None
        self.state = state

        stance_points = []

        self.body.setPos(*self._project(_legtool.Point3D(), state.body_frame))
        self.cog.setPos(*self._project(_legtool.Point3D(), state.cog_frame))

        for leg_num, shoulder in self.shoulders.iteritems():
            if leg_num >= len(state.legs):
                continue
            shoulder_frame = _legtool.Frame()
            self.state.make_shoulder(
                self.config.mechanical.leg_config[leg_num], shoulder_frame)
            shoulder.setPos(*self._project(_legtool.Point3D(), shoulder_frame))

        for leg_num, leg_item in self.legs.iteritems():
            if leg_num >= len(state.legs):
                continue
            leg = state.legs[leg_num]

            point = self._project(leg.point, leg.frame)
            leg_item.setPos(*point)

            shoulder_frame = _legtool.Frame()
            self.state.make_shoulder(
                self.config.mechanical.leg_config[leg_num], shoulder_frame)
            shoulder_point = shoulder_frame.map_from_frame(
                leg.frame, leg.point)

            ik_result = leg.leg_ik.do_ik(
                _legtool.Point3D(shoulder_point.x, shoulder_point.y,
                                 shoulder_point.z))

            if not ik_result.valid():
                color = QtCore.Qt.red
            elif leg.mode == _legtool.LegMode.kStance:
                color = QtCore.Qt.green
                stance_points.append(point)
            elif leg.mode == _legtool.LegMode.kSwing:
                color = QtCore.Qt.yellow
            else:
                assert False, 'unknown leg mode %d' % leg.mode

            leg_item.setBrush(QtGui.QBrush(color))

        if len(stance_points) >= 3:
            self.support_poly.setVisible(True)
            hull = convexhull.convexHull(stance_points)

            poly = QtGui.QPolygonF([QtCore.QPointF(x, y) for x, y in hull])
            self.support_poly.setPolygon(poly)
        else:
            self.support_poly.setVisible(False)

        self.resize()
Пример #5
0
def min_sigma_to_cover(points_, gmm):
    
    points = convexHull(points_)

    min_sigma = 0.0
    if len(gmm.means_) > 1:
        raise Exception('muliple component gmm not supported')

    for point in points:
        sigma = bisection(point_included, point=point, mean_=gmm.means_[0], 
                          cov_=gmm.covars_[0])

        min_sigma = max(sigma, min_sigma)
        #print '%s,%s' % point 

    for point in points:
        assert bisection(point_included, point=point, mean_=gmm.means_[0], 
                          cov_=gmm.covars_[0]) <= min_sigma + 1e-5

    return min_sigma
Пример #6
0
    def makeCSObstacleFromCircle(self, realObstacle, robotRadius):

        csoPoints = [];
        roVertices = realObstacle.getLocationList();

        for roVertex in  roVertices:

            csoPoints.append((roVertex.getX() + robotRadius, roVertex.getY() + robotRadius));
            csoPoints.append((roVertex.getX() - robotRadius, roVertex.getY() + robotRadius));
            csoPoints.append((roVertex.getX() - robotRadius, roVertex.getY() - robotRadius));
            csoPoints.append((roVertex.getX() + robotRadius, roVertex.getY() - robotRadius));
        

        hullPoints = convexhull.convexHull(csoPoints);
        
        # forming points into an obstacle
        convexObstacle = obstacle.Obstacle([]);
        for (x,y) in hullPoints:
            convexObstacle.addXY(x,y);

        return convexObstacle
Пример #7
0
    def draw_convex_hulls(self, img):

        dr = ImageDraw.Draw(img)

        for type in self.ctx['hulls']:

            points = []

            # sigh...
            key = "%ss" % type

            for coord in self.ctx[key]:
                pt = self.latlon_to_point(coord['latitude'],
                                          coord['longitude'])
                points.append((pt.x, pt.y))

            hull = convexhull.convexHull(points)

            #
            # no way to assign width to polygon outlines in PIL...
            #

            pink = (255, 0, 132)
            cnt = len(hull)
            i = 0

            while i < cnt:
                (x1, y1) = hull[i]

                j = i + 1

                if j == cnt:
                    (x2, y2) = hull[0]
                else:
                    (x2, y2) = hull[j]

                dr.line((x1, y1, x2, y2), fill=pink, width=6)
                i += 1

        return img
Пример #8
0
    def draw_convex_hulls(self, img) :

        dr = ImageDraw.Draw(img)

        for type in self.ctx['hulls'] :

            points = []

            # sigh...
            key = "%ss" % type
            
            for coord in self.ctx[key] : 
                pt = self.latlon_to_point(coord['latitude'], coord['longitude'])    
                points.append((pt.x, pt.y))

            hull = convexhull.convexHull(points)
            
            #
            # no way to assign width to polygon outlines in PIL...
            #
            
            pink = (255, 0, 132)
            cnt = len(hull)
            i = 0

            while i < cnt : 
                (x1, y1) = hull[i]
                
                j = i + 1

                if j == cnt :
                    (x2, y2) = hull[0]
                else :
                    (x2, y2) = hull[j]

                dr.line((x1, y1, x2, y2), fill=pink, width=6)
                i += 1

        return img
def init_system(mesh,nextDensity,particles_point,length_scale):
	print "Creating system"
	dim = mesh.geometry().dim()
	system = System()

	#this will need to be fixed.
	ntypepy = materials.Silicon()
	ptypepy = materials.Silicon()

	#create materials
	system.n_dist = ntypepy.random_momentum("ntype")
	system.p_dist = ptypepy.random_momentum("ptype")
	print system.n_dist,len(system.n_dist),system.n_dist[0]
	print "Creating ntype"
	ntype = lib.new_material(ctypes.c_double(ntypepy.electron_mass),
				  ctypes.c_double(ntypepy.free_dist),
				  system.n_dist.ctypes.data,
				  len(system.n_dist),dim)
	print "Creating ptype"
	ptype = lib.new_material(ctypes.c_double(ptypepy.hole_mass),
				ctypes.c_double(ptypepy.free_dist),
				system.p_dist.ctypes.data,
				len(system.p_dist),dim)
	system.materials=lib.material_pair(ptype,ntype)

	#create mesh
	#create materials **
	index = it.count()
	boundary_ids = []
	ntype_ids = []
	ptype_ids = []
	
	mesh_coord = mesh.coordinates()
	for x in mesh_coord:
		i = index.next()
		if tuple(x) in mesh.p_region:
			ptype_ids.append(i)
		if tuple(x) in mesh.n_region:
			ntype_ids.append(i)
		if i in mesh.ibd:
			boundary_ids.append(i)
	ptype_ids = np.array(ptype_ids)
	ntype_ids = np.array(ntype_ids)
	boundary_ids = np.array(boundary_ids)

	#make the arrays persistent
	system.ntype_ids = ntype_ids
	system.ptype_ids = ptype_ids
	system.boundary_ids = boundary_ids
	#Construct polytope from points
	if dim==2:
		#get inner and outer bounding arrays
		#at the moment, boundaries must be convex.
		bm = dolfin.BoundaryMesh(mesh);
		bmc = bm.coordinates().copy()
		inner,outer = 	map(np.array,
				 qhull.inner_outer(bmc))
		print "inner",inner
		print "outer",outer
		inner_p = lib.create_polytope2(inner.ctypes.data,len(inner))
		outer_p = lib.create_polytope2(outer.ctypes.data,len(outer))
	elif dim==3:
		qfaces = qhull.qhull_faces(mesh.coordinates())
		faces = []
		for face in qfaces:
			face = np.array(face)
			print face
			faces.append(lib.create_face(face.ctypes.data,
							len(face),3))
		faces_p = (ctypes.void_p*len(faces))(*faces)
		inner_p = 0 #should be NULL
		outer_p = lib.create_polytope3(faces_p,len(faces))
		system.faces_p = faces_p
		system.inner_p = inner_p
		system.outer_p = outer_p
	else:
		raise("Invalid dimension.")
	print "Polytopes",inner_p,outer_p
		
	print boundary_ids,len(boundary_ids)
	system.c_mesh = lib.create_mesh(mesh_coord.ctypes.data,
			    len(mesh_coord),
			    dim,
			    system.materials,
			    boundary_ids.ctypes.data,
			    len(boundary_ids),
			    ptype_ids.ctypes.data,
			    len(ptype_ids),
			    ntype_ids.ctypes.data,
			    len(ntype_ids),
			    mesh.kdt,
			    mesh.gen_num,
			    ctypes.c_double(mesh.super_particles_count),
			    outer_p,inner_p)
	mesh.c_mesh = system.c_mesh
	#create bounding polygon
	print "Creating Bounding polygon"
	print list(mesh.bd)
	convexpoints_list = map(tuple,list(mesh.bd))
	print convexpoints_list
	raw_hull= convexhull.convexHull(map(tuple,list(mesh.bd)))
	convex_hull = list(raw_hull)
	convex_hull.reverse() 
	convex_hull = np.array(convex_hull)
	polygon = lib.new_polygon(convex_hull.ctypes.data,
					ctypes.c_int(len(convex_hull)))
	print "..done"
	#system.bounding_polygon = polygon
	print "Creating a ton of particles..."
	#create particles
	system.particles = CParticles(5*10**6,system.c_mesh,dim)
	#initialize particles
	for i in xrange(len(mesh_coord)):
		if tuple(mesh_coord[i]) in mesh.p_region:
			sign = 1
			mass = ptypepy.hole_mass
		if tuple(mesh_coord[i]) in mesh.n_region:
			sign = -1
			mass = ntypepy.electron_mass
		for delta in range(particles_point):
			index = lib.create_particleC(ctypes.c_int(i),
					system.particles.ptr,
					nextDensity.ctypes.data,
					ctypes.c_int(sign),
					ctypes.c_double(mass),
					system.c_mesh)
			#print hex(system.particles.pos.ctypes.data)
			#print system.particles.pos[index]
			#raw_input()
	for i in xrange(len(nextDensity)):
		nextDensity[i] = 0
	print "Created system"
	return system
Пример #10
0
"""

import sys, convexhull, re, string

# need to get a set of points
if __name__ == '__main__':
    try:
        data = sys.argv[1]
    except IndexError:
        data = "sample.eps"  #die?

    # read the file
    f = open(data, 'r')

    P = []
    l = f.readline()
    while l != "":
        #print l
        s = re.split('\s+', l, 2)
        if s[0] != "#" and s[1] != "":
            P.append((string.atof(s[0]), string.atof(s[1])))
        l = f.readline()

    f.close()

    H = convexhull.convexHull(P)

    for p in H:
        #	print '%f,%f' % (p[0],p[1])
        print p[0], p[1]
Пример #11
0
def simplex(fin='../data/words/ingredients-basic.tsv',
            out='../data/simplex/20110920/',
            figname='some',
            ellipses=False,
            contours=False,
            conv_hull=True,
            conv_thresh=[0.2],
            xnum=10,
            ynum=10,
            norm=True,
            linewidth=0.2,
            text=True,
            mew=1.5,
            special=None):

    utils.safe_mkdir(out)
    z = tb.tabarray(SVfile=fin)

    names = [
        n for n in z.dtype.names
        if n not in ['type', 'names', 'name', 'ingredients']
    ]

    n = len(names)

    array = utils.normalize(z[names].extract())
    data = tb.tabarray(array=array, names=names)

    if figname.startswith('some'):
        typevec = [
            'chocolate-cakes', 'angel-food-cakes', 'brownies', 'sugar-cookies',
            'scones', 'loaves', 'pancakes', 'crepes'
        ]
        colorvec = ['brown', 'g', 'm', 'b', 'k', 'r', 'y', 'c']
    elif figname.startswith('all'):
        typevec = ['']
        z['type'] = ''
        colorvec = ['g']

    for j1 in range(n):
        i1 = names[j1]
        for j2 in range(n):
            i2 = names[j2]
            for j3 in range(n):
                i3 = names[j3]
                k = 0
                pylab.clf()
                for kind in typevec:
                    color = colorvec[k]

                    p = data[z['type'] == kind][i1] - data[z['type'] ==
                                                           kind][i2]
                    q = np.sqrt(3) * data[z['type'] == kind][i3]

                    pylab.plot(p, q, '+', color=color, markeredgewidth=mew)

                    if conv_hull:

                        for ct in conv_thresh:

                            x = p.mean()
                            y = q.mean()
                            d = np.sqrt((x - p)**2 + (y - q)**2)
                            ind = d.argsort()[:-int(len(p) * ct)]
                            pts = [(p[j], q[j]) for j in ind]
                            if pts:
                                hull = np.array(convexHull(pts))
                                pylab.fill(hull[:, 0],
                                           hull[:, 1],
                                           color=color,
                                           alpha=0.2)

                    k += 1

                if special is not None:
                    p = data[z['name'] == special][i1] - data[z['name'] ==
                                                              special][i2]
                    q = np.sqrt(3) * data[z['name'] == special][i3]
                    pylab.plot(p, q, '*', color='y', markersize=20, mew=2)

                pylab.plot([-1, 1], [0, 0], 'k-.', linewidth=linewidth)
                pylab.plot([-1, 0], [0, np.sqrt(3)],
                           'k-.',
                           linewidth=linewidth)
                pylab.plot([0, 1], [np.sqrt(3), 0], 'k-.', linewidth=linewidth)

                if text:
                    pylab.text(1.1, -0.1, i1, fontsize=16)
                    pylab.text(-1.1, -0.1, i2, fontsize=16)
                    pylab.text(-0.05, 1.8, i3, fontsize=16)

                pylab.axis('equal')
                pylab.axis('off')

                pylab.savefig(out + figname + '_' + '_'.join([i1, i2, i3]) +
                              '.pdf',
                              transparent=True)

    if special is not None:
        pylab.legend(typevec + [special])
    else:
        pylab.legend(typevec)
    pylab.savefig(out + figname + '_legend.pdf', transparent=True)

    return (z, data)
Пример #12
0
def scatter(fin='../data/original.tsv',
            out='../data/scatter/20110902/',
            figname='some',
            ellipses=False,
            contours=False,
            conv_hull=True,
            conv_thresh=[0.2],
            xnum=10,
            ynum=10,
            norm=None,
            mew=1,
            legend=False,
            special=None,
            simple=True,
            typevec=None,
            colorvec=None):

    print figname

    utils.safe_mkdir(out)
    z = files.filter_hack(tb.tabarray(SVfile=fin))

    names = np.array([
        n for n in z.dtype.names
        if n not in ['type', 'names', 'name', 'ingredients']
    ])

    a = z[names].extract()

    if norm == None:
        a = utils.normalize(a)  # normalize data

    if figname.startswith('some'):
        typevec = [
            'chocolate-cakes', 'angel-food-cakes', 'brownies', 'sugar-cookies',
            'scones', 'loaves', 'pancakes', 'crepes'
        ]
        colorvec = ['brown', 'g', 'm', 'b', 'k', 'r', 'y', 'c']
    elif figname.startswith('all'):
        typevec = ['']
        z['type'] = ''
        colorvec = ['g']

    ingredientvec = ['white sugar', 'all-purpose flour']
    name_dict = dict(zip(names, range(len(names))))

    idict = {}
    for i in ['egg', 'flour', 'sugar', 'oil']:
        idict[i] = [n for n in z.dtype.names if i in n]

    idict['liquid'] = ['water']
    idict['liquid'] += [
        n for n in z.dtype.names
        if ('milk' in n) and ('powder' not in n) and ('chip' not in n)
    ]
    idict['liquid'] += [
        n for n in z.dtype.names if ('juice' in n) and ('with' not in n)
    ]

    idict['sugar'] += ['corn syrup', 'light corn syrup']

    idict['butter'] = [
        'butter', 'margarine', 'butter or margarine',
        'butter or stick margarine'
    ]
    idict['oil'] += [n for n in z.dtype.names if 'shortening' in n]
    idict['fat'] = idict['butter'] + idict['oil']
    idict.pop('butter')
    idict.pop('oil')

    print idict

    columns = []
    ingredientvec = idict.keys()
    for i in ingredientvec:
        name_list = np.array([name_dict[j] for j in idict[i]])
        columns += [a[:, name_list].sum(axis=1)]
    data = tb.tabarray(columns=columns, names=ingredientvec)
    print data
    n = len(ingredientvec)

    if norm is not None:
        d = data.extract()
        i = list(data.dtype.names).index(norm)
        array = d / np.repeat(d[:, i], d.shape[1]).reshape(
            d.shape[0], d.shape[1])
        data = tb.tabarray(array=array, names=data.dtype.names)

    for j1 in range(n - 1):
        i1 = ingredientvec[j1]
        for j2 in range(j1 + 1, n):
            i2 = ingredientvec[j2]
            k = 0
            pylab.clf()
            for kind in typevec:
                color = colorvec[k]

                #p = a[z['type']==kind][:,name_dict[i1]]
                #q = a[z['type']==kind][:,name_dict[i2]]
                p = data[z['type'] == kind][i1]
                q = data[z['type'] == kind][i2]

                if simple:
                    pylab.plot(p, q, '+', color=color, markeredgewidth=mew)

                if conv_hull:

                    for ct in conv_thresh:

                        x = p.mean()
                        y = q.mean()
                        d = np.sqrt((x - p)**2 + (y - q)**2)
                        ind = d.argsort()[:-int(len(p) * ct)]
                        pts = [(p[j], q[j]) for j in ind]
                        if pts:
                            hull = np.array(convexHull(pts))
                            pylab.fill(hull[:, 0],
                                       hull[:, 1],
                                       color=color,
                                       alpha=0.2)
                        #else:
                        #	print t

                k += 1

            pylab.xlabel(i1)
            pylab.ylabel(i2)

            if special is not None:
                p = data[z['name'] == special][i1]
                q = data[z['name'] == special][i2]
                pylab.plot(p, q, '*', color='y', markersize=20, mew=2)

            if legend:
                if special is not None:
                    pylab.legend(typevec + [special])
                else:
                    pylab.legend(typevec)

            if norm is None:
                pylab.axis([0, 1, 0, 1])

            pylab.savefig(out + figname + '_' + i1 + '_' + i2 + '.pdf')

    if special is not None:
        pylab.legend(typevec + [special])
    else:
        pylab.legend(typevec)
    pylab.savefig(out + figname + '_legend.pdf')

    data = z[['type', 'name']].colstack(data)

    if figname.startswith('some'):
        data.saveSV('../data/words/ingredients-basic.tsv')

    return (z, data)
Пример #13
0
def scatter(fin='../data/original.tsv', out='../data/scatter/20110902/', figname='some', ellipses=False, contours=False, conv_hull=True, conv_thresh=[0.2], xnum=10, ynum=10, norm=None, mew=1, legend=False, special=None, simple=True, typevec=None, colorvec=None):

	print figname

	utils.safe_mkdir(out)
	z = files.filter_hack(tb.tabarray(SVfile=fin))
	
	names = np.array([n for n in z.dtype.names if n not in ['type', 'names', 'name', 'ingredients']])
	
	a = z[names].extract()
	
	if norm == None:
		a = utils.normalize(a)	# normalize data 

	if figname.startswith('some'):
		typevec = ['chocolate-cakes', 'angel-food-cakes', 'brownies', 'sugar-cookies', 'scones', 'loaves', 'pancakes', 'crepes']
		colorvec = ['brown', 'g', 'm', 'b', 'k', 'r', 'y', 'c']
	elif figname.startswith('all'):
		typevec = ['']
		z['type'] = ''
		colorvec = ['g']
	
	ingredientvec = ['white sugar', 'all-purpose flour']
	name_dict = dict(zip(names, range(len(names))))	
	
	idict = {}	
	for i in ['egg', 'flour', 'sugar', 'oil']:
		idict[i] = [n for n in z.dtype.names if i in n]

	idict['liquid'] = ['water']
	idict['liquid'] += [n for n in z.dtype.names if ('milk' in n) and ('powder' not in n) and ('chip' not in n)]
	idict['liquid'] += [n for n in z.dtype.names if ('juice' in n) and ('with' not in n)]
	
	idict['sugar'] += ['corn syrup', 'light corn syrup']

	idict['butter'] = ['butter', 'margarine', 'butter or margarine', 'butter or stick margarine']
	idict['oil'] += [n for n in z.dtype.names if 'shortening' in n]	
	idict['fat'] = idict['butter'] + idict['oil']
	idict.pop('butter')
	idict.pop('oil')
	
	print idict
	
	columns = []
	ingredientvec = idict.keys()
	for i in ingredientvec:
		name_list = np.array([name_dict[j] for j in idict[i]])
		columns += [a[:, name_list].sum(axis=1)]
	data = tb.tabarray(columns=columns, names=ingredientvec)
	print data
	n = len(ingredientvec)
	
	if norm is not None:
		d = data.extract()
		i = list(data.dtype.names).index(norm)
		array = d / np.repeat(d[:,i], d.shape[1]).reshape(d.shape[0], d.shape[1])
		data = tb.tabarray(array=array, names=data.dtype.names)
	
	for j1 in range(n-1):
		i1 = ingredientvec[j1]
		for j2 in range(j1+1, n):
			i2 = ingredientvec[j2]
			k = 0
			pylab.clf()
			for kind in typevec:		
				color = colorvec[k]
		
		
				#p = a[z['type']==kind][:,name_dict[i1]]
				#q = a[z['type']==kind][:,name_dict[i2]]
				p = data[z['type']==kind][i1]
				q = data[z['type']==kind][i2]
				
				if simple:
					pylab.plot(p, q, '+', color=color, markeredgewidth=mew)
					
				if conv_hull:
					
					for ct in conv_thresh:
				
						x = p.mean()
						y = q.mean()
						d = np.sqrt((x - p)**2 + (y - q)**2)
						ind = d.argsort()[:-int(len(p) * ct)]							
						pts = [(p[j], q[j]) for j in ind]
						if pts:
							hull = np.array(convexHull(pts))
							pylab.fill(hull[:,0], hull[:,1], color=color, alpha=0.2)
						#else:
						#	print t		
					
				k += 1

			pylab.xlabel(i1)
			pylab.ylabel(i2)

			if special is not None:
				p = data[z['name']==special][i1]
				q = data[z['name']==special][i2]
				pylab.plot(p, q, '*', color='y', markersize=20, mew=2)
			
			if legend:
				if special is not None:
					pylab.legend(typevec + [special])	
				else:
					pylab.legend(typevec)	
				
			if norm is None:
				pylab.axis([0, 1, 0, 1])
			
			pylab.savefig(out + figname + '_' + i1 + '_' + i2 +'.pdf')

	if special is not None:
		pylab.legend(typevec + [special])	
	else:
		pylab.legend(typevec)	
	pylab.savefig(out + figname + '_legend.pdf')

	data = z[['type', 'name']].colstack(data)
	
	if figname.startswith('some'):
		data.saveSV('../data/words/ingredients-basic.tsv')
		
	return (z, data)
Пример #14
0
def simplex(fin='../data/words/ingredients-basic.tsv', out='../data/simplex/20110920/', figname='some', ellipses=False, contours=False, conv_hull=True, conv_thresh=[0.2], xnum=10, ynum=10, norm=True, linewidth=0.2, text=True, mew=1.5, special=None):

	utils.safe_mkdir(out)
	z = tb.tabarray(SVfile=fin)
	
	names = [n for n in z.dtype.names if n not in ['type', 'names', 'name', 'ingredients']]
	
	n = len(names)

	array = utils.normalize(z[names].extract())
	data = tb.tabarray(array=array, names=names)	

	if figname.startswith('some'):
		typevec = ['chocolate-cakes', 'angel-food-cakes', 'brownies', 'sugar-cookies', 'scones', 'loaves', 'pancakes', 'crepes']
		colorvec = ['brown', 'g', 'm', 'b', 'k', 'r', 'y', 'c']
	elif figname.startswith('all'):
		typevec = ['']
		z['type'] = ''
		colorvec = ['g']
	
	for j1 in range(n):
		i1 = names[j1]
		for j2 in range(n):
			i2 = names[j2]
			for j3 in range(n):
				i3 = names[j3]
				k = 0
				pylab.clf()
				for kind in typevec:		
					color = colorvec[k]
			
					p = data[z['type']==kind][i1] - data[z['type']==kind][i2]
					q = np.sqrt(3) * data[z['type']==kind][i3]

					pylab.plot(p, q, '+', color=color, markeredgewidth=mew)
					
					if conv_hull:
						
						for ct in conv_thresh:
					
							x = p.mean()
							y = q.mean()
							d = np.sqrt((x - p)**2 + (y - q)**2)
							ind = d.argsort()[:-int(len(p) * ct)]							
							pts = [(p[j], q[j]) for j in ind]
							if pts:
								hull = np.array(convexHull(pts))
								pylab.fill(hull[:,0], hull[:,1], color=color, alpha=0.2)
						
					k += 1

				if special is not None:
					p = data[z['name']==special][i1] - data[z['name']==special][i2]
					q = np.sqrt(3) * data[z['name']==special][i3]				
					pylab.plot(p, q, '*', color='y', markersize=20, mew=2)

				pylab.plot([-1, 1], [0, 0], 'k-.', linewidth=linewidth)
				pylab.plot([-1, 0], [0, np.sqrt(3)], 'k-.', linewidth=linewidth)
				pylab.plot([0, 1], [np.sqrt(3), 0], 'k-.', linewidth=linewidth)				
	
				if text:
					pylab.text(1.1, -0.1, i1, fontsize=16)
					pylab.text(-1.1, -0.1, i2, fontsize=16)
					pylab.text(-0.05, 1.8, i3, fontsize=16)
				
				pylab.axis('equal')
				pylab.axis('off')
				
				pylab.savefig(out + figname + '_' + '_'.join([i1, i2, i3]) +'.pdf', transparent=True)

	if special is not None:
		pylab.legend(typevec + [special])	
	else:
		pylab.legend(typevec)		
	pylab.savefig(out + figname + '_legend.pdf', transparent=True)
		
	return (z, data)
Пример #15
0
def convexHull(points):
    return list(convexhull.convexHull(points))
Пример #16
0
def get_voronoi_and_salience(poff_filename):
    points = poff_reader(poff_filename)

    # Convex hull
    convex_hull = convexHull(points)
    convex_hull_idx = map(lambda p: points.index(p), convex_hull)
    convex_hull_edges = get_edges(convex_hull_idx)

    # Get boundaries edges
    points_idx = range(0, len(points))
    boundary_edges = get_edges(points_idx)

    # Add one dimension
    o_points = map(lambda x: x + (0,), points)

    # Add a virtual infinite vertex
    #inf_vertex = (0, 0, float('inf'))
    inf_vertex = (0, 0, 9999999)
    points = o_points + [inf_vertex]
    inf_idx = points.index(inf_vertex)

    # Get triangles (in 3D)
    t_obj = Triangulation(points)
    tetraherons = t_obj.get_elements_indices()

    triangles = filter(lambda x: inf_idx not in x,
                       set([tuple(sorted(i)) for t in tetraherons
                            for i in xuniqueCombinations(t, 3)]))

    # Calculate neighbours table
    neighbours = get_neighbours(triangles)

    # Classify all infinite Delaunay faces as EXTERIOR and push them
    # to a queue
    side_table = {}
    q = Queue.Queue()
    for face in triangles:
        edges = set([tuple(sorted(e)) for e in xuniqueCombinations(face, 2)])
        if edges & (convex_hull_edges - boundary_edges):
            side_table[face] = EXTERIOR
            q.put(face)
            continue
        if edges & (boundary_edges & convex_hull_edges):
            side_table[face] = INTERIOR
            q.put(face)
            continue
    # Collect all EXTERIOR triangles
    o_triangles_idx = filter(lambda x: side_table[x] is EXTERIOR, side_table.keys())
    o_triangles = idx_to_real(o_triangles_idx, o_points)

    # Mark every triangle as EXTERIOR or INTERIOR
    while not q.empty():
        face = q.get()
        for nface in neighbours[face]:
            if nface not in side_table:
                nedge = tuple(sorted(list(set(nface) & set(face))))
                assert len(nedge) == 2
                if nedge in boundary_edges:
                    side_table[nface] = not side_table[face]
                else:
                    side_table[nface] = side_table[face]
                q.put(nface)

    # Collect all INTERIOR triangles
    i_triangles_idx = filter(lambda x: side_table[x] is INTERIOR, triangles)
    i_triangles = idx_to_real(i_triangles_idx, o_points)

    # Filter neighbours dictionary to only INTERIOR triangles
    i_neighbours = {}
    for k, d in neighbours.items():
        if side_table[k] is INTERIOR:
            i_neighbours[k] = filter(lambda x: side_table[x] is INTERIOR, d)

    # Calculate areas and circumenteres of triangles
    areas = {}
    circumcenters = {}
    for t_idx, t in zip(i_triangles_idx, i_triangles):
        areas[t_idx] = abs((t[2][0] - t[0][0]) * (t[1][1] - t[0][1]) - \
                           (t[1][0] - t[0][0]) * (t[2][1] - t[0][1])) / 2
        circumcenters[t_idx] = get_circumcenter(t)

    # find triangles that have two edge on the boundary
    boundary_triangles_idx = set([])
    for t in i_triangles_idx:
        edges = set([tuple(sorted(e)) for e in xuniqueCombinations(t, 2)])
        if len(edges & boundary_edges) == 2:
            boundary_triangles_idx.add(t)

    # traverse all triangles, and calculate the salience value
    voronoi_edges = []
    r = {}
    k = {}
    sum_area = sum(areas.values())
    visited_t = set([])
    for start_t in boundary_triangles_idx:
        q = Queue.Queue()
        q.put(start_t)
        while not q.empty():
            t = q.get()
            visited_t.add(t)
            for new_t in i_neighbours[t]:
                if new_t in visited_t:
                    continue
                nedge = tuple(sorted(list(set(new_t) & set(t))))
                assert len(nedge) == 2
                area_1 = get_any_part_area(nedge, i_neighbours, areas)
                area_2 = sum_area - area_1
                v_edge = tuple(sorted([circumcenters[t], circumcenters[new_t]]))
                if v_edge[0] == v_edge[1]:
                    q.put(new_t)
                    continue
                if v_edge not in voronoi_edges:
                    voronoi_edges.append(v_edge)
                r[v_edge] = min(area_1, area_2) / max(area_1, area_2)
                k[v_edge] = min(area_1, area_2) / length(v_edge)
                q.put(new_t)
        break

    # Do something with r, k and voronoi_edges
    return o_points, voronoi_edges, r, k, i_triangles