示例#1
0
	def __init__(self, screen2D=[256, 256], primitives=[] , lights=[] , camerapos=Vector(0, 0, 0), O=Vector(0, 0, 0), U=Vector(0, 0, 0), V=Vector(0, 0, 0)):
		self.lights = lights
		self.camerapos = camerapos
		self.viewportpos = Viewport(O=O, U=U, V=V)
		self.list_of_primitives = []
		self.primitives = primitives 
		self.screen2D = Screen2D(screen2D[0], screen2D[1])
		self.size = self.screen2D.image.size

		
		# cornell box components
		triangle_back_1 = Triangle(a= Vector(0, 0, 10), b= Vector(20, 0, 10), c= Vector(0, 20, 10), color= Vector(247, 195, 49))
		triangle_right_1 = Triangle(a= Vector(10, 20, 0), b= Vector(10, 0, 20), c= Vector(10, 0, 0), color= Vector(70, 130, 180))
		triangle_top_1 = Triangle(a= Vector(0, 10, 0), b= Vector(20, 10, 0), c= Vector(0, 10, 20), color= Vector(176, 224, 230))
		triangle_left_1 = Triangle(a= Vector(0, 0, 0), b= Vector(0, 0, 20), c= Vector(0, 20, 0), color= Vector(215, 57, 37))
		triangle_bottom_1 = Triangle(a= Vector(0, 0, 0), b= Vector(20, 0, 0), c= Vector(0, 0, 20), color= Vector(205, 205, 201))
		


		for prim in self.primitives:
			print "prim", prim
			self.list_of_primitives.append(prim)


		# appending cornell box componenet to the list_of_primitives  
		self.list_of_primitives.append(triangle_back_1)
		self.list_of_primitives.append(triangle_right_1)
		self.list_of_primitives.append(triangle_top_1)
		self.list_of_primitives.append(triangle_left_1)
		self.list_of_primitives.append(triangle_bottom_1)
	
		#calculate ambient illumination for the point_light
		self.ambient = self.lights[0].ambient_illumination()
def get_rand_area(c):
    p1 = c.random_point_on_circumference()
    p2 = c.random_point_inside()
    p3 = c.random_point_inside()
    t = Triangle(p1, p2, p3)
    print('{0} with area {1:.2f}'.format(t, t.area()))
    return t.area()
	def add_edges(self, triangle, point):
		def index_of_other_triangle_in_its_side_edges(line, triangle):
			if line.triangle1 == triangle : return 1
			return 2
		l1, l2, l3 = triangle.sort_lines()

		line1 = Line(l1.point1, point)
		line2 = Line(l2.point1, point)
		line3 = Line(l3.point1, point)

		tri1 = Triangle(triangle.line1, line1, line2)
		tri2 = Triangle(triangle.line2, line3, line2)
		tri3 = Triangle(triangle.line3, line1, line3)

		line1.set_triangles(tri1, 1)
		line1.set_triangles(tri3, 2)

		line2.set_triangles(tri1, 1)
		line2.set_triangles(tri2, 2)

		line3.set_triangles(tri3, 1)
		line3.set_triangles(tri2, 2)

		triangle.line1.set_triangles(tri1, index_of_other_triangle_in_its_side_edges(triangle.line1, triangle))
		triangle.line2.set_triangles(tri2, index_of_other_triangle_in_its_side_edges(triangle.line2, triangle))
		triangle.line3.set_triangles(tri3, index_of_other_triangle_in_its_side_edges(triangle.line3, triangle))

		triangle.triangles += [tri1, tri2, tri3]

		point.neighbours += [l1.point1, l2.point1, l3.point1]
		l1.point1.neighbours.append(point)
		l2.point1.neighbours.append(point)
		l3.point1.neighbours.append(point)
示例#4
0
文件: VillaEmo.py 项目: romatre/ggpl
 def __init__(self):
     self.planimetry = Factory.create_planimetry()
     self.column = Factory.create_column()
     self.gorgeous_column = GorgeousColumn(5, 18)
     self.top_triangle = Triangle(42, 10)
     self.lateral_roof = Triangle(52, 201)
     self.main_roof = Roof(72, 65.16, 16)
     self.arch = Arch(4, 15, 1.5)
示例#5
0
def triangle():
	if request.method == "GET":
		return jsonify({"area":"undefined"})
	elif request.method == "POST":
		amazing = request.json["amazing"]
		height = request.json["height"]
		this_triangle = Triangle(amazing, height)
		area = this_triangle.area()
		return jsonify({"triangle_area":area})
示例#6
0
	def effect(self):
		linewidth=int(self.options.linewidth)
		# メインのルート要素であるSVGを取得
		svg = self.document.getroot()
		pathlist=svg.findall(ALL+"{"+inkex.NSS['svg']+"}path")

		for path in pathlist:
			if path == None:
				inkex.errormsg(u"パスを書いてください!!")
			#パスの頂点座標を取得
			vals=simplepath.parsePath(path.get('d'))
			bone=[]
			for cmd,vert in vals:
				#たまに空のが入ってるため、それ対策
				if len(vert) != 0:
					bone.append(Vertex(vert[0],vert[1]))
			outVertexArray=stripline(bone,linewidth,self.options.logfilename)

			pointer=0
			for t in range(len(outVertexArray)-2):
				tri=Triangle(outVertexArray[pointer][0],outVertexArray[pointer+1][0],outVertexArray[pointer+2][0])

				stripstr=tri.toSVG()
				color2="blue"
				if outVertexArray[pointer][1]:
					color="blue"
				else:
					color="red"
				pointer+=1
				attributes={"points":stripstr,
				"style":"fill:"+color2+";stroke:"+color2+";stroke-width:"+str(linewidth/3),"fill-opacity":"0.5"}
				pth =inkex.etree.Element("polygon",attributes)
				svg.append(pth)
			pointer=0
			#+−を示す点を描く
			for t in range(len(outVertexArray)):

				if outVertexArray[pointer][1]:
					point=Plus(outVertexArray[pointer][0].x,outVertexArray[pointer][0].y,linewidth/3)
					color="blue"
				else:
					point=Minus(outVertexArray[pointer][0].x,outVertexArray[pointer][0].y,linewidth/3)
					color="red"
				if pointer==0:
					color="#6f0018"#暗い赤
				point.appendToSVG(color,svg)
				#svg.append(Circle.toSVG(outVertexArray[pointer][0].x,outVertexArray[pointer][0].y,linewidth/3,color,0))
				pointer+=1
			pointer=0
			pathstr="M "
			for t in range(len(outVertexArray)):
				pathstr+=str(outVertexArray[pointer][0].x)+" "+str(outVertexArray[pointer][0].y)+" "
				pointer+=1

			att3={"d":pathstr,"r":"1","fill":"none","stroke-width":"1","stroke":"white"}
			pt=inkex.etree.Element("path",att3)
示例#7
0
    def createObjects(self):
        #self.objects = importObjects("objects.txt")

        v = Vector3(-100,0,0)
        self.objects =[
            Triangle(Vector3(0,0,0)+v, Vector3(40,0,0)+v, Vector3(20,140,-10)+v, ['red']),
            Triangle(Vector3(-40,20,-10)+v, Vector3(100,0,0)+v, Vector3(100,40,0)+v, ['green']),
            Triangle(Vector3(60,100,0)+v, Vector3(80,-40,-10)+v, Vector3(100,100,0)+v, ['blue']),
            Triangle(Vector3(0,100,0)+v, Vector3(0,60,0)+v, Vector3(140,80,-10)+v, ['orange']),
        ]
示例#8
0
    def test_triangle_negative_area_negative_mantissa(self):
        """Negative test of Triangle.area method. Give -1 as mantissa value."""
        t = Triangle(Point(0, 3.1415), Point(2.7, 3), Point(3**0.5, 6.023))

        with self.assertRaises(ValueError) as err:
            t.area(-1)
            self.assertEqual(
                err.args[0], "Negative number for mantissa is not allowed.",
                "Triangle(Point(0, 3.1415), Point(2.7, 3), Point(3 ** 0.5, 6.023)).area(-1) failed,\
                              no ValueError was raised.")
示例#9
0
文件: VillaEmo.py 项目: romatre/ggpl
 def get_top_triangle(self):
     height_base = 9
     return T([1, 2, 3])([230, 108, 41])((STRUCT([
         T(2)(-26)(self.texture("intonaco.jpg", 5,
                                5)(CUBOID([42, 5, height_base]))),
         self.texture("tegole.jpg", 1,
                      2)(T(3)(height_base)(Triangle(42, 27).render())),
         T([2, 3])([-26.5,
                    height_base])(self.texture("fronte.jpg", 35.,
                                               31.)(Triangle(42,
                                                             1).render())),
     ])))
示例#10
0
def intersection():
    """
    fonction de test d'intersection sur un tetraedre simple
    """
    #pylint: disable=C0103
    t1 = Triangle((0, 0, 0), (1, 0, 0), (0, 0, 1))
    t2 = Triangle((0, 0, 0), (0, 1, 0), (0, 0, 1))
    t3 = Triangle((1, 0, 0), (0, 0, 1), (0, 1, 0))
    tranche = Tranche(0.5)
    tranche.intersection_tranche([t1, t2, t3])
    print(tranche.segments)
    tranche.dessine_svg("tetraedre.svg", 1000, 1000)
示例#11
0
def test_fonction_intersection_plan():
    """
    test la fonction, sachant que tri1 et tri2 sont en intersections, mais pas tri3.
    Le test doit renvoyer True True False
    """
    tri1 = Triangle((1, 2, 3), (4, 5, 6), (4, 5, 2))
    tri2 = Triangle((5, 2, 3), (4, 8, 6), (2, 5, 2))
    tri3 = Triangle((5, 2, 5), (4, 8, 6), (2, 5, 5))
    tri4 = Triangle((5, 2, 3), (4, 8, 3), (2, 5, 3))
    tranche = Tranche(4)
    print(tranche.intersecte_avec(tri1))
    print(tranche.intersecte_avec(tri2))
    print(tranche.intersecte_avec(tri3))
    print(tranche.intersecte_avec(tri4))
示例#12
0
 def test_triangle_positive_area(self):
     """Positive test of Triangle.area method."""
     t = Triangle(Point(0, 3.1415), Point(2.7, 3), Point(3**0.5, 6.023))
     self.assertEqual(
         t.area(1), 4.0,
         "Test of Triangle(Point(0, 3.1415), Point(2.7, 3), Point(3 ** 0.5, 6.023)).area(1),\
                       returned value != 4.0.")
     self.assertEqual(
         t.area(), 4.013,
         "Test of Triangle(Point(0, 3.1415), Point(2.7, 3), Point(3 ** 0.5, 6.023)).area(1) failed,\
                       returned value != 4.013.")
     self.assertEqual(
         t.area(6), 4.012568,
         "Test of Triangle(Point(0, 3.1415), Point(2.7, 3), Point(3 ** 0.5, 6.023)).area(6) failed,\
                       returned value != 4.012568.")
示例#13
0
def main():
    rect = Rectangle()
    sq = square(6)
    tri = Triangle()
    rect.breadth = 5
    rect.length = 30

    sq.length = 6
    tri = Triangle()
    result1 = rect.area()
    result2 = tri.area()
    result3 = sq.area()
    #always observe the object used
    final = result3 + result2 + result1
    print("behold... the reuslt", final)
示例#14
0
 def loadModel(self, path, mtl):
     """
     Loads a model from a obj and mtl file.
     Parmeters:
         path: String. The path to the obj file
         mtl: String. The path to the mtl file
     """
     mat = None
     if mtl is not None:
         for line in open(mtl):
             if "newmtl" in line:
                 # update current material
                 mat = line[7:].strip()
             elif line[0:2] == "Kd":
                 # add material colour
                 self.materials[mat] = (
                     Vec3(*(map(float, line[3:].strip().split()))))
     verts = []
     for line in open(path):
         # If line is a vertex
         if line[0] == "v":
             # Add vertex
             verts.append(
                 Vec3(*(map(float, line[1:].strip().split(" ")))))
         # If line is a face
         if line[0] == "f":
             # add face
             a = line[1:].strip().split(" ")
             self.addPrimitive(
                 Triangle(*[Copy(verts[int(i) - 1]) for i in a], mat))
         # if line is a material declaration
         if "usemtl" in line:
             mat = line[7:].strip()  # Update material
def initializeT(points):
    # Create array of points T
    t = []
    d = {}

    # Find the extreme coordinates in points
    extremes = getExtremes(points)
    minx = extremes[0]
    maxx = extremes[1]
    miny = extremes[2]
    maxy = extremes[3]

    # Add three points for the bounding triangle
    midx = (minx + maxx) / 2
    midy = (miny + maxy) / 2
    dx = maxx - minx
    dy = maxy - miny
    p0 = Point(-100000, -100000, -1)
    p1 = Point(100000, -100000, -1)
    p2 = Point(0, 100000, -1)
    tr = Triangle(p0, p1, p2)
    t.append(tr)

    # Update the dictionary
    d[(p0, p1)] = [tr]
    d[(p1, p2)] = [tr]
    d[(p2, p0)] = [tr]

    # Return T
    return t, d
示例#16
0
def objRead(fn):

    vertices = []
    indices = []
    with open(fn, "r") as f:
        for line in f:
            if line[0] == "#":
                continue
            if line[-1] == "\n" or line[-1] == "\r":
                line = line[:-1]
            temp = line.split(" ")
            if temp[0] == "v":
                vertices.append(
                    np.array([
                        float(temp[1]) * 30 + 8.0,
                        float(temp[2]) * 30,
                        float(temp[3]) * 30 - 30
                    ]))
            elif temp[0] == "f":
                indices.append((int(temp[1]), int(temp[2]), int(temp[3])))
    iteml = []

    print len(vertices)
    print len(indices)
    for item in indices:
        p1 = vertices[item[0] - 1]
        p2 = vertices[item[1] - 1]
        p3 = vertices[item[2] - 1]
        tri = Triangle(p1, p2, p3, np.array([0.5, 1.0, 0.8]), 0.02, 0.75, 1,
                       30, 0.0)
        iteml.append(tri)

    return iteml
示例#17
0
    def create_triangle_objects(self):
        """
        Yielded to save memory instead of adding each obj to memory(in a list)
        Create some checks on the file while looping through it
        Let user know
        :return:
        """
        with open(self._file, "r") as csv_file:
            csv_reader = csv.reader(csv_file)

            # Skip Headers
            next(csv_reader)
            c = 0
            for data in csv_reader:
                c += 1
                try:
                    if len(data) != 4:
                        print("Your file contains an error on line - ", c + 1,
                              " - ", data)
                        print("Only the first four indexes will be used.")
                        print("\n")
                    # product, origin_year, development_year, incremental_value
                    yield Triangle(data[0], data[1], data[2], data[3])
                except Exception as e:
                    print(e)
示例#18
0
def main():
    """Start of program for shapes and inheritance"""

    print("\nShapes and inheritance practice in Python (v3.3.5)")

    circ = Circle(3)
    tri = Triangle(4, 5, 7, 5.7)
    sq = Square(11)

    #To print out pydocs: print(help(circ))
    print("Circle area: " + str(circ.area()))
    print("Square area: " + str(sq.area()))
    print("Triangle area: " + str(tri.area()))
    print("Circle perimeter: " + str(circ.perimeter()))
    print("Square perimeter: " + str(sq.perimeter()))
    print("Triangle perimeter: " + str(tri.perimeter()))
示例#19
0
class Playground():
    Circle=Circle(6)
    Polygon=Polygon(3)
    Square=Square(5,2)
    Triangle=Triangle(1,4,2)
    Shape=Shape()
    
    # Implement __init__() for this class

    def __init__(self):
        print("The instances you created")

    # Call Method find_area of each class 

    print(f"{Circle} and area = {Circle.find_area()}")
    print(f"{Square} and area = {Square.find_area()}")
    print(f"{Triangle} and area = {Triangle.find_area()}")

    #find_circumference
    #find_perimeter
    # Call Methods find_circumference and find_perimeter of each class
    print(f"{Circle} and circumference = {Circle.find_circumference()}")
    print(f"{Square} and perimeter = {Square.find_perimeter()}")
    print(f"{Triangle} and perimeter = {Triangle.find_perimeter()}")

    def __str__(self):
        print("Playground...Shapes")
示例#20
0
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self.set_minimum_size(400, 300)
        glClearColor(0.2, 0.3, 0.2, 1.0)

        # Create object
        self.triangle = Triangle()
示例#21
0
    def __init__(self, triangles):
        triLst = []
        self.adjLst = [] # triangles
        if isinstance(triangles, Triangulator):
            # get the full list of triangles because we can't search a partial list
            for i in range(0, triangles.getNumTriangles()):
                v0 = triangles.getVertex(triangles.getTriangleV0(i))
                v1 = triangles.getVertex(triangles.getTriangleV1(i))
                v2 = triangles.getVertex(triangles.getTriangleV2(i))
                self.adjLst.append(AdjLstElement(Triangle(Point3(v0.x, v0.y, 0),
                                                      Point3(v1.x, v1.y, 0),
                                                      Point3(v2.x, v2.y, 0)), i))
        elif isinstance(triangles, AdjacencyList):
            for i in range(0, len(triangles.adjLst)):
                self.adjLst.append(AdjLstElement(triangles.adjLst[i].tri, i))
        else:  # should be a list or a Triangulator
            for i in range(0, len(triangles)):
                self.adjLst.append(AdjLstElement(triangles[i].tri, i))

        # adjLst in the form [(triangle, n12, n23, n13)] i.e. n12 is the triInd across verts 1 & 2
        # find the neighbours
        for j in range(0, len(self.adjLst)):
            for k in range(0, len(self.adjLst)):
                if j != k:
                    nayb = getSharedEdgeStr(self.adjLst[j], self.adjLst[k])
                    if nayb == '12':
                        self.adjLst[j].n12 = k
                    if nayb == '23':
                        self.adjLst[j].n23 = k
                    if nayb == '13':
                        self.adjLst[j].n13 = k
示例#22
0
def read_msh_file(name, **kwargs):
    print 'Reading MSH file'
    d = {}
    lmsh = open(name + '.msh', 'r').readlines()
    d['faces'] = {}
    physical_correspondance = {}
    for i, l in enumerate(lmsh):
        if '$PhysicalNames' in l:
            N = int(lmsh[i + 1])
            for j in range(N):
                il = i + j + 2
                lpn = lmsh[il].split()
                number = int(lpn[1])
                name = str(lpn[2].replace('\"', ''))
                d['faces'][name] = []
                physical_correspondance[name] = number
            i = i + N + 2
            break
    i0 = i
    print physical_correspondance
    for i, l in enumerate(lmsh):
        if '$Nodes' in l:
            d['vertices'] = []
            N = int(lmsh[i + 1])
            for j in range(N):
                il = i + j + 2
                lpn = lmsh[il].split()
                pt = Point([float(lpn[1]), float(lpn[2]), float(lpn[3])])
                d['vertices'].append(pt)
            i = i + N + 2
            break
    i0 = i
    flog = open('logFMS', 'w')
    for i, l in enumerate(lmsh):
        if '$Elements' in l:
            N = int(lmsh[i + 1])
            for j in range(N):
                il = i + j + 2
                lpn = lmsh[il].split()
                if int(lpn[1]) == 2:
                    print lpn
                    flog.write('triangle :' + str(int(lpn[0])) + '\n')
                    tags = int(lpn[2])
                    phys = int(lpn[1 + tags])
                    flog.write('physical :' + str(phys) + '\n')
                    p0 = int(lpn[2 + tags + 1]) + 1
                    p1 = int(lpn[2 + tags + 2]) + 1
                    p2 = int(lpn[2 + tags + 3]) + 1
                    for group in d['faces']:
                        if phys == physical_correspondance[group]:
                            flog.write('triangle belongs to ' + group + '\n')
                            # why is this triangle written reversed ?
                            tri = (p2 - 1, p1 - 1, p0 - 1)
                            #pt = ((p2-1,p1-1,p0-1),k[0]-1)
                            d['faces'][group].append(Triangle(tri))
                            break
            i = i + N + 2
            break
    i0 = i
    return Triangulation(**d)
示例#23
0
    def __init__(self, triOrPts, slfInd, n12Ind=None, n23Ind=None, n13Ind=None):
        """If points are past they must be in a tuple-like object"""
        if isinstance(triOrPts, Triangle):
            Triangle.__init__(self, triOrPts.pt1, triOrPts.pt2, triOrPts.pt3)
        else:
            Triangle.__init__(self, triOrPts[0], triOrPts[1], triOrPts[2])

        self.selfInd = slfInd
        self.n12 = n12Ind  # neighbour on 12's edge
        self.w2313 = -1  # width when crossing edges 23 & 13
        self.n23 = n23Ind
        self.w1213 = -1
        self.n13 = n13Ind
        self.w1223 = -1
        self.par = None
        self.g = 100000
        self.f = 100000
示例#24
0
def test_calcul_intersection():
    """
    Fonction de test sur la formule du caclul d'intersection
    """
    tranche = Tranche(2)
    segment = tranche.calcul_intersection(
        Triangle((2, 0, 0), (4, 0, 0), (2, 0, 3)))
    print(segment)
示例#25
0
    def __init__(self, triOrPts, slfInd, n12Ind=None, n23Ind=None, n13Ind=None):
        """If points are past they must be in a tuple-like object"""
        if isinstance(triOrPts, Triangle):
            Triangle.__init__(self, triOrPts.pt1, triOrPts.pt2, triOrPts.pt3)
        else:
            Triangle.__init__(self, triOrPts[0], triOrPts[1], triOrPts[2])

        self.selfInd = slfInd
        self.n12 = n12Ind  # neighbour on 12's edge
        self.w2313 = -1  # width when crossing edges 23 & 13
        self.n23 = n23Ind
        self.w1213 = -1
        self.n13 = n13Ind
        self.w1223 = -1
        self.par = None
        self.g = 100000
        self.f = 100000
示例#26
0
 def test_triangle_positive_init(self):
     """Positive test of Triangle.__init__ method."""
     t = Triangle(Point(1, 1), Point(2, 3), Point(4, 5))
     self.assertEqual(
         str(t), '((1.0, 1.0), (2.0, 3.0), (4.0, 5.0))',
         "Test of Triangle(Point(0, 0), Point(8, 0), Point(4, 5)) failed,\
                       returned value != ((1.0, 1.0), (2.0, 3.0), (4.0, 5.0))."
     )
示例#27
0
    def test_triangle_negative_init_wrong_argument_type(self):
        """Negative test of Triangle.__init__ method. Wrong type of arguments."""
        with self.assertRaises(ValueError) as err:
            Triangle('foo', Point(1, 3), 'bar')
            self.assertEqual(
                err.args[0],
                "Given points belong to one line and can not define triangle.",
                "Triangle('foo', Point(1, 3), 'bar') failed, no ValueError was raised."
            )

        with self.assertRaises(ValueError) as err:
            Triangle(42, Point(1, 3), 21)
            self.assertEqual(
                err.args[0],
                "Given points belong to one line and can not define triangle.",
                "Triangle(42, Point(1, 3), 21) failed, no ValueError was raised."
            )
示例#28
0
 def test_triangle_positive_is_isosceles_property(self):
     """Positive test of Triangle.is_isosceles property."""
     a = Point(-2, 0)
     b = Point(2, 0)
     c = Point(0, 4)
     t = Triangle(a, b, c)
     self.assertTrue(
         t.is_isosceles,
         "Test of Triangle(Point(-2, 0), Point(2, 0), Point(0, 4)) failed, returned value != True."
     )
     d = Point(-2, 45)
     e = Point(2, 0)
     f = Point(0, 4)
     g = Triangle(d, e, f)
     self.assertFalse(
         g.is_isosceles,
         "Test of Triangle(Point(-2, 45), Point(2, 0), Point(0, 4)) failed, returned value != False."
     )
示例#29
0
 def test_triangle_negative_init_points_on_line(self):
     """Negative test of Triangle.__init__ method. Points belong to one line."""
     with self.assertRaises(ValueError) as err:
         Triangle(Point(1, 1), Point(1, 3), Point(1, 5))
         self.assertEqual(
             err.args[0],
             "Given points belong to one line and can not define triangle.",
             "Triangle(Point(1, 1), Point(1, 3), Point(1, 5)) failed, no ValueError was raised."
         )
示例#30
0
 def test_triangle_positive_is_equilateral_property(self):
     """Positive test of Triangle.is_equilateral property."""
     a = Point(-9, 10)
     b = Point(-1, 4)
     c = Point(3 * 3**0.5 - 5, 4 * 3**0.5 + 7)
     t = Triangle(a, b, c)
     self.assertTrue(
         t.is_equilateral,
         "Test of Triangle(Point(-9, 10), Point(-1, 4), Point(3 * 3 ** 0.5 - 5, 4 * 3 ** 0.5 + 7))\
                       failed, returned value != True.")
     a = Point(-9, 21)
     b = Point(-1, 4)
     c = Point(3 * 3**0.5 - 5, 4 * 3**0.5 + 7)
     t = Triangle(a, b, c)
     self.assertFalse(
         t.is_equilateral,
         "Test of Triangle(Point(-9, 21), Point(-1, 4), Point(3 * 3 ** 0.5 - 5, 4 * 3 ** 0.5 + 7))\
                       failed, returned value != False.")
示例#31
0
 def triangle_list(self):
     _triangles = []
     for f in self['faces']:
         p0 = Point(self['vertices'][f[0] - 1])
         p1 = Point(self['vertices'][f[1] - 1])
         p2 = Point(self['vertices'][f[2] - 1])
         tr = Triangle((p0, p1, p2))
         _triangles.append(tr)
     return _triangles
def main():

	#square and triangle objects
	S1 = Square(2)
	T1 = Triangle(3)

	#Pint objects T1 and S1
	print("Square with side length of 2\n",S1)
	print()
	print("Triangle with side length of 3\n", T1)
示例#33
0
 def get_triangles(self):
     _triangles = []
     for group in self['faces']:
         for f in self['faces'][group]:
             p = []
             p.append(self['vertices'][f[0] - 1])
             p.append(self['vertices'][f[1] - 1])
             p.append(self['vertices'][f[2] - 1])
             _triangles.append(Triangle(p))
     return _triangles
示例#34
0
class TestTriangle(unittest.TestCase):

    def setUp(self):
        self.triangle0 = Triangle(1, 2, 3, 20, 30)
        print("In TestTriangle.setUp():" + self.triangle0.to_string())
        self.triangle1 = Triangle(1, 2, 77, 20, 230)
        print("In TestTriangle.setUp():" + self.triangle1.to_string())

    def test_get_third_angle(self):
        self.assertEqual(130, self.triangle0.get_third_angle())
        self.assertEqual(60, self.triangle1.get_third_angle())

    def test_has_point(self):
        self.assertTrue(self.triangle0.has_point(1))
        self.assertTrue(self.triangle0.has_point(3))
        self.assertFalse(self.triangle0.has_point(4))
        self.assertTrue(self.triangle1.has_point(77))
示例#35
0
def triangulate(a, perim):
    """
    Recursively tries every triangulation in search a feasible one
        Each layer
            makes a Triangle out of three perimeter portals
            for every feasible way of max-fielding that Triangle
                try triangulating the two perimeter-polygons to the sides of the Triangle

    Returns True if a feasible triangulation has been made in graph a
    """
    pn = len(perim)
    if pn < 3:
        # Base of recursion
        return True

    try:
        startStackLen = len(a.edgeStack)
    except AttributeError:
        startStackLen = 0
        a.edgeStack = []
    try:
        startTriLen = len(a.triangulation)
    except AttributeError:
        startTriLen = 0
        a.triangulation = []

    #    odegrees = [a.out_degree(p) for p in perim
    #    order = np.argsort(odegrees)

    # Try all possible first generation triangles with two edges on boundary that both use node i (using i as final vertex will cause no 2 first generation triangles to have same final vertex)
    for i in np.random.permutation(range(0, pn)):
        #        print perim
        #        print 'using %s as final'%perim[i]
        for j in xrange(TRIES_PER_TRI):
            t0 = Triangle(perim[[i, i - 1, (i + 1) % pn]], a, True)
            t0.findContents()
            #            t0.randSplit() # Split triangle on a random portal
            t0.nearSplit()  # Split triangle on the nearest portal
            try:
                #                print 'trying to build'
                t0.buildGraph()
            except Deadend as d:
                # TODO when allowing suboptimal plans, this block would be unnecessary if first generation triangles were made in the right order: see Triangle.buildGraph
                # remove the links formed since beginning of loop
                removeSince(a, startStackLen, startTriLen)
            #                print 'small fail'
            else:
                # This build was successful. Break from the loop
                #                print 'build succeeded'
                break
        else:
            # The loop ended "normally" so this triangle failed
            #            print 'big fail'
            continue

        #        print 'continuing with',perim[range(i+1-pn,i)]
        if not triangulate(a, perim[range(i + 1 - pn, i)]):  # i+1 through i-1
            # remove the links formed since beginning of loop
            removeSince(a, startStackLen, startTriLen)
            continue

        # This will be a list of the first generation triangles
        a.triangulation.append(t0)

        # This triangle and the ones to its sides succeeded
        return True

    # Could not find a solution
    return False
示例#36
0
 def test_triangle_isosceles1(self):
     parametro = [3, 2, 2]
     trian = Triangle(parametro)
     self.assertEqual('Isosceles', trian.istriangle())
示例#37
0
 def test_triangle_isosceles3(self):
     parametro = [5, 5, 8]
     trian = Triangle(parametro)
     self.assertEqual('Isosceles', trian.istriangle())
示例#38
0
 def test_triangle_scalene(self):
     parametro = [7, 3, 4]
     trian = Triangle(parametro)
     self.assertEqual('Scalene', trian.istriangle())
示例#39
0
 def test_no_es_triangulo2(self):
     param = [8, 1, 3]
     trian = Triangle(param)
     self.assertEqual('NotATriangle', trian.istriangle())
示例#40
0
 def setUp(self):
     self.triangle0 = Triangle(1, 2, 3, 20, 30)
     print("In TestTriangle.setUp():" + self.triangle0.to_string())
     self.triangle1 = Triangle(1, 2, 77, 20, 230)
     print("In TestTriangle.setUp():" + self.triangle1.to_string())
示例#41
0
class Test_Triangle(unittest.TestCase):

    def setUp(self):
        self.triangle = Triangle()

    def test_Triangle_Scalene(self):
        self.assertEqual("Scalene", self.triangle.setSides(6, 9, 5))

    def test_Triangle_Isosceles(self):
        self.assertEqual("Isosceles", self.triangle.setSides(6, 3, 6))

    def test_Triangle_Isosceles2(self):
        self.assertEqual("Isosceles", self.triangle.setSides(5, 5, 12))

    def test_Triangle_Isosceles3(self):
        self.assertEqual("Isosceles", self.triangle.setSides(4, 6, 6))

    def test_Triangle_Equilateral(self):
        self.assertEqual("Equilateral", self.triangle.setSides(3, 3, 3))

    def test_Triangle_NotATriangule(self):
        self.assertEqual("NotATriangle", self.triangle.setSides(6, 3, 9))

    def test_Triangle_NotATriangule1(self):
        self.assertEqual("NotATriangle", self.triangle.setSides(12, 7, 5))

    def test_Triangle_NotATriangule2(self):
        self.assertEqual("NotATriangle", self.triangle.setSides(3, 7, 4))

    def test_Triangle_NotATriangule3(self):
        self.assertEqual("NotATriangle", self.triangle.setSides(3, 6, 9))

    def test_Triangle_NotATriangule4(self):
        self.assertEqual("NotATriangle", self.triangle.setSides(6, 12, 6))

    def test_Triangle_NotATriangule5(self):
        self.assertEqual("NotATriangle", self.triangle.setSides(10, 4, 4))
示例#42
0
 def setUp(self):
     self.triangle = Triangle()
示例#43
0
文件: demo.py 项目: darkn3rd/oop-tut
#!/usr/bin/env python
from Shape import Shape         # include Shape.py
from Triangle import Triangle   # include Triangle.py
from Rectangle import Rectangle # include Rectangle.py

# create new objects and initialize data
shapeObject     = Shape()
triangleObject  = Triangle(4, 5)
rectangleObject = Rectangle(4, 5)

print('Shapeless area is: %24.1f' % (shapeObject.get_area()))
print('Triangle (base=%d, height=%d) area is: %6.1f' % (4, 5, triangleObject.get_area()))
print('Rectangle (width=%d, height=%d) area is: %4.1f' % (4, 5, rectangleObject.get_area()))
示例#44
0
def when_i_determine_triangle_type(step):
	triangle = Triangle()
	world.type = triangle.setSides(world.number[0],world.number[1],world.number[2])
示例#45
0
def triangulate(a,perim):
    '''
    Recursively tries every triangulation in search a feasible one
        Each layer
            makes a Triangle out of three perimeter portals
            for every feasible way of max-fielding that Triangle
                try triangulating the two perimeter-polygons to the sides of the Triangle

    Returns True if a feasible triangulation has been made in graph a
    '''
    pn = len(perim)
    if pn < 3:
        return True

    try:
        startStackLen = len(a.edgeStack)
    except AttributeError:
        startStackLen = 0
        a.edgeStack = []
    try:
        startTriLen = len(a.triangulation)
    except AttributeError:
        startTriLen = 0
        a.triangulation = []

    # Try all triangles using perim[0:2] and another perim node
    for i in np.random.permutation(range(2,pn)):

        for j in xrange(TRIES_PER_TRI):
            t0 = Triangle(perim[[0,1,i]],a,True)
            t0.findContents()
            t0.randSplit()
            try:
                t0.buildGraph()
            except Deadend as d:
                # remove the links formed since beginning of loop
                removeSince(a,startStackLen,startTriLen)
            else:
                # This build was successful. Break from the loop
                break
        else:
            # The loop ended "normally" so this triangle failed
            continue

        if not triangulate(a,perim[range(1,i   +1   )]): # 1 through i
            # remove the links formed since beginning of loop
            removeSince(a,startStackLen,startTriLen)
            continue

        if not triangulate(a,perim[range(0,i-pn-1,-1)]): # i through 0
           # remove the links formed since beginning of loop
           removeSince(a,startStackLen,startTriLen)
           continue

        # This will be a list of the first generation triangles
        a.triangulation.append(t0)

        # This triangle and the ones to its sides succeeded
        return True

    # Could not find a solution
    return False
示例#46
0
def when_realizo_el_calculo(step):
    trian = Triangle(world.parametros)
    world.tipo = trian.istriangle()
示例#47
0
 def test_triangle_equilateral(self):
     parametro = [4, 4, 4]
     trian = Triangle(parametro)
     self.assertEqual('Equilateral', trian.istriangle())
示例#48
0
 def test_no_es_triangulo(self):
     param = [201, 0, 201]
     trian = Triangle(param)
     self.assertEqual('NotATriangle', trian.istriangle())
示例#49
0
 def _init_triangles(self):
     self._triangles = []
     for i in xrange(self.nsimplex):
         t = Triangle(self.points[self.vertices[i]])
         t.set_transform(self.transform[i])
         self._triangles.append(t)
示例#50
0
 def test_triangle_area(self):
     triangle = Triangle('scalene',[40,32,98], 3, 8)
     self.assertEqual(triangle.get_area(), 12)