def test_add(self): c = Calc() x = 100 y = 200 result = 0 result = c.add(x,y) print '{0} + {1} = {2}'.format(x, y, result) self.assertEqual(x + y, result)
def test_add_notint_x(self): c = Calc() x = "aaa" y = "bbb" result = 0 with self.assertRaises(TypeError): result = c.add(x,y) print '{0} + {1} = {2}'.format(x, y, result)
class Calc_Test2(unittest.TestCase): simple_calc_two = Calc() def test_remainder(self): #self.assertTrue(self.simple_calc_two.remainder(9,9), ) self.assertEqual(self.simple_calc_two.remainder(9, 9), 0)
def test_three_of_kind(self): hand = [ Card("2", "H", 2), Card("3", "H", 3), Card("4", "H", 4), Card("6", "C", 6), Card("6", "D", 6), Card("6", "S", 6), Card("A", "D", 14) ] result = sorted(hand, reverse=True) result = sorted(result, key=result.count, reverse=True)[:5] test_calc = Calc(hand) self.assertEqual(test_calc.get_rank(), 4) self.assertEqual(str(test_calc), "ThreeOfKind") self.assertEqual(test_calc.best_hand(), result)
def test_two_pair(self): hand = [ Card("2", "H", 2), Card("4", "D", 4), Card("4", "H", 4), Card("6", "S", 6), Card("6", "D", 6), Card("8", "S", 8), Card("A", "D", 14) ] result = sorted(hand, reverse=True) result = sorted(result, key=result.count, reverse=True)[:5] test_calc = Calc(hand) self.assertEqual(test_calc.get_rank(), 3) self.assertEqual(str(test_calc), "TwoPair") self.assertEqual(test_calc.best_hand(), result)
def test_royal_flush(self): hand = [ Card("10", "H", 10), Card("Q", "H", 12), Card("9", "H", 9), Card("J", "H", 11), Card("K", "H", 13), Card("6", "S", 6), Card("A", "H", 14) ] result = [c for c in hand if c.get_suit() == "H"] result = sorted(result, reverse=True)[:5] test_calc = Calc(hand) self.assertEqual(test_calc.get_rank(), 10) self.assertEqual(str(test_calc), "RoyalFlush") self.assertEqual(test_calc.best_hand(), result)
def test_straight_flush(self): hand = [ Card("2", "H", 2), Card("3", "H", 3), Card("4", "H", 4), Card("6", "H", 6), Card("5", "H", 5), Card("6", "S", 6), Card("A", "D", 14) ] result = [c for c in hand if c.get_suit() == "H"][:5] result = sorted(result, reverse=True) test_calc = Calc(hand) self.assertEqual(test_calc.get_rank(), 9) self.assertEqual(str(test_calc), "StraightFlush") self.assertEqual(test_calc.best_hand(), result)
def test_full_house(self): hand = [ Card("A", "H", 14), Card("A", "H", 14), Card("4", "H", 4), Card("6", "C", 6), Card("6", "D", 6), Card("6", "S", 6), Card("A", "D", 14) ] result = sorted(hand, reverse=True) result = sorted(result, key=result.count, reverse=True)[:5] test_calc = Calc(hand) self.assertEqual(test_calc.get_rank(), 7) self.assertEqual(str(test_calc), "FullHouse") self.assertEqual(test_calc.best_hand(), result)
def test_flush(self): hand = [ Card("2", "H", 2), Card("3", "H", 3), Card("4", "H", 4), Card("6", "H", 6), Card("7", "H", 7), Card("8", "S", 8), Card("A", "H", 14) ] result = [c for c in hand if c.get_suit() == "H"] result = sorted(result, reverse=True)[:5] test_calc = Calc(hand) self.assertEqual(test_calc.get_rank(), 6) self.assertEqual(str(test_calc), "Flush") self.assertEqual(test_calc.best_hand(), result)
def test_basic(self): """Test that the intializer is correct""" calc = Calc() self.assertEqual( calc.functions['EXP'].execute(calc.operators['ADD'].execute( 1, calc.operators['MULTIPLY'].execute(2, 3))), 1096.6331584284585)
class Test_calc(): def setup_class(self): self.calc = Calc() @pytest.mark.parametrize('a,b,c', [(1, 2, 3), (0.1, 0.2, 0.3), (1, 0.1, 1.1), (-1, -2, -3), (1, -2, -1), (-2, 1, -1), (-1, 0.2, -0.8)]) def test_add(self, a, b, c): assert self.calc.add(a, b) == c @pytest.mark.parametrize('a,b,c', [(6, 2, 3), (6, -2, -3), (-6, 2, -3), (-6, -2, 3), (6, 0.5, 12), (0.6, 2, 0.3), (0.6, 0.2, 3), (6, 0, 0)]) def test_div(self, a, b, c): assert self.calc.div(a, b) == c
def makeJob(job): if isinstance(job[0],TrajDataBulk): bulk = BulkTraj(job[0].name) else: bulk=BulkPure(job[0]) dft = job[1] calc = Calc(*job[2:]) return BulkJob(bulk,calc,dft)
class TestCalc(unittest.TestCase): """Basic calculator with add, subrtract, multiply and divide functions """ def setUp(self): self.calc = Calc() def test_add(self): self.assertEqual(self.calc.add(20, 10), 30, "incorrect addition") def test_subtract(self): self.assertEqual(self.calc.subtract(20, 10), 10, "incorrect subtraction") def test_multiply(self): self.assertEqual(self.calc.multiply(20, 10), 200, "incorrect multiplication") def test_divide(self): self.assertEqual(self.calc.divide(20, 10), 2, "incorrect division")
class ModuleTest(unittest.TestCase): # 在每一个测试用例开始时执行,执行测试用例执行前的初始化工作,如初始化变量,生成测试数据等 def setUp(self): self.cal = Calc(6, 4) # 在每一个测试用例结束时执行,执行测试用例的清理工作,如关闭数据库、关闭文件、删除数据等 def tearDown(self): pass # 方法必须以 test 开头 def test_add(self): result = self.cal.add() self.assertEqual(result, 10) def test_sub(self): result = self.cal.sub() self.assertEqual(result, 2)
def test_input(): c = Calc() c.update( '1' ) c.update( '2' ) c.update( '3' ) s = str( c.result() ) assert s == '123.0'
class TestCalcAddFunc(): """ A class used to test add function in class Calc. """ calc = Calc() # 有效测试用例1 # 相加的两个数都是整数 test_data_for_add_validcase_1 = [(1, 2, 3), (-1, -2, -3), (1, -2, -1), (-1, 2, 1), (1, 0, 1), (0, 2, 2), (0, -2, -2), (-1, 0, -1), (0, 0, 0)] @pytest.mark.parametrize("x, y, expect", test_data_for_add_validcase_1) def test_add_validcase_1(self, x, y, expect): result = self.calc.add(x, y) assert expect == result # 有效测试用例2 # 相加的两个数中有浮点数 test_data_for_add_validcase_2 = [(1.1, 2.2, 3.3), (-1.1, -2.2, -3.3), (1.1, -2.2, -1.1), (-1.1, 2.2, 1.1), (1.1, 0, 1.1), (0, 2.2, 2.2), (0, -2.2, -2.2), (-1.1, 0, -1.1)] @pytest.mark.parametrize("x, y, expect", test_data_for_add_validcase_2) def test_add_validcase_2(self, x, y, expect): result = self.calc.add(x, y) assert expect == round(result, 1) # 无效测试用例1 # 给定的参数中有非数字 test_data_for_add_invalidcase_1 = [('a', 'b'), ('a', 2), (1, 'b')] @pytest.mark.parametrize("x, y", test_data_for_add_invalidcase_1) def test_add_invalidcase_1(self, x, y): with pytest.raises(ValueError) as ErrInfo: self.calc.add(x, y) print(ErrInfo.type) assert ErrInfo.type == ValueError # 无效测试用例2 # 给定的参数个数大于两个 def test_add_invalidcase_2(self): with pytest.raises(TypeError) as ErrInfo: self.calc.add(1, 2, 3) print(ErrInfo.type) assert ErrInfo.type == TypeError # 无效测试用例3 # 给定的参数个数少于两个 def test_add_invalidcase_3(self): with pytest.raises(TypeError) as ErrInfo: self.calc.add(1) print(ErrInfo.type) assert ErrInfo.type == TypeError
def test_div(self): comb1 = Calc(4, 2) comb2 = Calc(4, 0) div = comb1.div() self.assertEqual(div, 2) with self.assertRaises(ValueError): comb2.div()
class TestAdd(unittest.TestCase): def setUp(self): self.calc = Calc() def test_add_int(self): result = self.calc.add(10, 15) self.assertEqual(result, 25) def test_add_float(self): result = self.calc.add(10.1, 15.2) self.assertEqual(round(result, 1), 25.3) def test_add_str(self): result = self.calc.add('aaa', 'bbb') self.assertEqual(result, 'aaabbb') def test_add_int_str(self): with self.assertRaises(TypeError): self.calc.add(1, 'aa')
class TestMultiply(unittest.TestCase): def setUp(self): self.calc = Calc() def test_multiply_int(self): result = self.calc.multiply(10, 15) self.assertEqual(result, 150) def test_multiply_float(self): result = self.calc.multiply(15.1, 10.2) self.assertEqual(round(result, 2), 154.02) def test_multiply_str(self): with self.assertRaises(TypeError): self.calc.multiply('aaa', 'bbb') def test_multiply_int_str(self): result = self.calc.multiply(2, 'aa') self.assertEqual(result, 'aaaa')
class TestCalc: def setup(self): self.calc = Calc() @pytest.mark.parametrize("a,b,expected", [ (1, 1, 2), (-1, 0, -1), (0.1, 0.1, 0.2), (1234567890, 987654321, 2222222211), ("a", 1, TypeError), ([1], 1, TypeError), ({1}, 1, TypeError), ((1,), 1, TypeError), (None, 1, TypeError) ]) def add_test(self, a, b, expected): # a,b 为整数或浮点数 if isinstance(a, (int, float)) and isinstance(b, (int, float)): result = self.calc.add(a, b) assert result == expected # a,b 为其他数据类型时 else: with pytest.raises(expected): self.calc.add(a, b) @pytest.mark.parametrize("a,b,expected", [ (9, 3, 3), (8, 3, 8/3), (-1, 1, -1), (1.1, 0.1, 11.0), (0, 1, 0), (987654310, 123456789, 987654310/123456789), (0, 0, ZeroDivisionError), ("a", 1, TypeError), ([1], 1, TypeError), ({1}, 1, TypeError), ((1,), 1, TypeError), (None, 1, TypeError), ]) def div_test(self, a, b, expected): # 除数为0 if b == 0: with pytest.raises(expected): self.calc.div(a, b) # a,b 为整数或浮点数 elif isinstance(a, (int, float)) and isinstance(b, (int, float)): result = self.calc.div(a, b) assert result == expected # a,b 为其他数据类型 else: with pytest.raises(expected): self.calc.div(a, b)
def __init__(self, _parent, _width, _height): ''' This Constructor sets default values for the main drawing Window''' self.NegativValueBool = 0 #This 'Bool' decides which Grid-form is drawn self.ALLSETGO = 0 #This 'Bool'is needed because of resize problems during initialisation self.width = _width #initial width of canvas self.height = _height #initial height of canvas self.parent = _parent #parent window of canvas self.bgcolor = "white" self.fgcolor = "black" self.canvas = Canvas(self.parent, width=self.width, height=self.height, bg=self.bgcolor) self.repaint(self.fgcolor) self.canvas.bind('<Configure>', self.resize) self.colorList = [ '#0000FF', '#FF0000', '#00FF00', '#FFCC00', '#FF66FF', '#00FFFF' ] #blue,red,green,yellow,pink,turky self.calc = Calc( ) #Calculating Object, used regression and maxima search self.gridtransform = GridTransform() #Object, used for scaling
class TestCalc: def setup(self): self.calc = Calc() @pytest.mark.parametrize( "a,b,expected", [(1, 1, 2), (-1, 0, -1), (0.1, 0.1, 0.2), (1234567890, 987654321, 2222222211), ("a", 1, 'can only concatenate str (not "int") to str'), ([1], 1, 'can only concatenate list (not "int") to list'), ({1}, 1, "unsupported operand type(s) for +: 'set' and 'int'"), ((1, ), 1, 'can only concatenate tuple (not "int") to tuple'), (None, 1, "unsupported operand type(s) for +: 'NoneType' and 'int'")]) def test_add(self, a, b, expected): # a,b 为整数或浮点数 if isinstance(a, (int, float)) and isinstance(b, (int, float)): result = self.calc.add(a, b) assert result == expected # a,b 为其他数据类型时 else: with pytest.raises(TypeError): self.calc.add(a, b) @pytest.mark.parametrize("a,b,expected", [ (9, 3, 3), (8, 3, 8 / 3), (-1, 1, -1), (1.1, 0.1, 11.0), (0, 1, 0), (987654310, 123456789, 987654310 / 123456789), (0, 0, "division by zero"), ("a", 1, "unsupported operand type(s) for /: 'str' and 'int'"), ([1], 1, "unsupported operand type(s) for /: 'list' and 'int'"), ({1}, 1, "unsupported operand type(s) for /: 'set' and 'int'"), ((1, ), 1, "unsupported operand type(s) for /: 'tuple' and 'int'"), (None, 1, "unsupported operand type(s) for /: 'NoneType' and 'int'"), ]) def test_div(self, a, b, expected): # 除数为0 if b == 0: with pytest.raises(ZeroDivisionError): self.calc.div(a, b) # a,b 为整数或浮点数 elif isinstance(a, (int, float)) and isinstance(b, (int, float)): result = self.calc.div(a, b) assert result == expected # a,b 为其他数据类型 else: with pytest.raises(TypeError): self.calc.div(a, b)
def operacao(m=0): if request.method == 'POST': x = Calc(request.form.get['X'], request.form.get['Y']) if m == 'divisao': r = {'resultado': x.divisao()} return jsonify(r) elif m == "multiplicacao": r = {'resultado': x.multiplicacao()} return jsonify(r) elif m == 'soma': r = {'resultado': x.soma()} return jsonify(r) elif m == 'sub': r = {'resultado': x.sub()} return jsonify(r) elif request.method == 'GET': return "FACA UM POST PARA USAR A CALCULADORA" else: return "Defina uma operacao basica"
def test_straight(self): hand = [ Card("2", "H", 2), Card("3", "H", 3), Card("4", "H", 4), Card("6", "S", 6), Card("5", "D", 5), Card("8", "S", 8), Card("A", "D", 14) ] result = [ Card("2", "H", 2), Card("3", "H", 3), Card("4", "H", 4), Card("6", "S", 6), Card("5", "D", 5) ] result = sorted(result, reverse=True) test_calc = Calc(hand) self.assertEqual(test_calc.get_rank(), 5) self.assertEqual(str(test_calc), "Straight") self.assertEqual(test_calc.best_hand(), result)
def main(): calc = Calc(int(input('첫번째 수: ')), int(input('두번재 수: '))) print(calc.first) print(calc.second) print('{} + {} = {}'.format(calc.first, calc.second, calc.sum())) print('{} * {} = {}'.format(calc.first, calc.second, calc.mul())) print('{} - {} = {}'.format(calc.first, calc.second, calc.sub())) print('{} / {} = {}'.format(calc.first, calc.second, calc.div()))
def main(): calc = Calc(int(input("첫번째 수 : ")),int(input("두번째 수 : "))) print(calc.first) print(calc.second) print("{}+{}={}".format(calc.first, calc.second, calc.sum())) print("{}x{}={}".format(calc.first, calc.second, calc.mul())) print("{}-{}={}".format(calc.first, calc.second, calc.sub())) print("{}/{}={}".format(calc.first, calc.second, calc.div()))
def calc(self): entered_numbers = [] for row in range(self.ROWS_WITH_NUMBERS_COUNT): try: tmp = int(self.tbl_rng.item(row, 6).text()) tmp = abs(tmp) entered_numbers.append(tmp) except: self.show_error_message() return calc = Calc(entered_numbers) calc.work() for row in range(self.ROWS_WITH_NUMBERS_COUNT): for col in range(3): rng = str(calc.rngs[col][row * 100]) self.tbl_rng.setItem(row, col, QTableWidgetItem(rng)) for col in range(3, 6): seed = entered_numbers[row] rng = str(calc.rngs[col][seed]) self.tbl_rng.setItem(row, col, QTableWidgetItem(rng)) for col in range(7): row = self.show_final_result(col, self.ROWS_WITH_NUMBERS_COUNT, calc.result[col]['max_val']['digit']) row = self.show_final_result(col, row, calc.result[col]['min_val']['digit']) row = self.show_final_result( col, row, calc.result[col]['scope_of_variation']) row = self.show_final_result(col, row, calc.result[col]['dispersion']) row = self.show_final_result(col, row, calc.result[col]['stddev'])
class Clac_Test(unittest.TestCase): simple_calc = Calc() def test_add(self): self.assertEqual(self.simple_calc.add(2, 3), 5) def test_sub(self): self.assertEqual(self.simple_calc.sub(2, 3), -1) def test_multi(self): self.assertEqual(self.simple_calc.multi(2, 3), 5) def test_divide(self): self.assertEqual(self.simple_calc.divide(10, 5), 3)
class TestRandom(unittest.TestCase): def setUp(self): self.calc = Calc() def test_add_called(self): with patch('random.randint', return_value=1): result = self.calc.random_operation(20, 2) self.assertEqual(result, 22) def test_sub_called(self): with patch('random.randint', return_value=2): result = self.calc.random_operation(20, 10) self.assertEqual(result, 10) def test_multiply_called(self): with patch('random.randint', return_value=3): result = self.calc.random_operation(20, 10) self.assertEqual(result, 200) def test_divide_called(self): with patch('random.randint', return_value=4): result = self.calc.random_operation(20, 10) self.assertEqual(result, 2)
def test_calc_can_consume_valid_token(): """Test that a :class:`Calc` can consume a valid :class:`Token`.""" input_text = "1+1" calc = Calc(text=input_text) # Note: Since _next_token advances position one cannot simply # >>> calc.current_token = Token(INTEGER, 1) # The _next_token method MUST be called or this test will fail. calc.current_token = calc._next_token() calc._consume_token(INTEGER) assert calc.current_token.type == PLUS
def __init__(self,_parent,_width,_height): ''' This Constructor sets default values for the main drawing Window''' self.NegativValueBool = 0 #This 'Bool' decides which Grid-form is drawn self.ALLSETGO = 0 #This 'Bool'is needed because of resize problems during initialisation self.width=_width #initial width of canvas self.height=_height #initial height of canvas self.parent=_parent #parent window of canvas self.bgcolor="white" self.fgcolor="black" self.canvas = Canvas(self.parent,width=self.width,height=self.height,bg=self.bgcolor) self.repaint(self.fgcolor) self.canvas.bind('<Configure>',self.resize) self.colorList = ['#0000FF','#FF0000','#00FF00', '#FFCC00', '#FF66FF','#00FFFF'] #blue,red,green,yellow,pink,turky self.calc = Calc() #Calculating Object, used regression and maxima search self.gridtransform = GridTransform() #Object, used for scaling
def test_expressions_with_floats(self): expression = "100+2.345*3-10/2" c1 = Calc(expression) expected = 'Expression contains float number(s)' actual = c1.expression_result() self.assertEqual(actual, expected) expression = "100,34+2*3-10/2" c2 = Calc(expression) expected = 'Expression contains float number(s)' actual = c2.expression_result() self.assertEqual(actual, expected)
def test_expression_with_missing_operator(self): expression = "((100+20)3-10/2+11-1*(10+34)-54)" c1 = Calc(expression) expected = 'missing operator near parentheses' actual = c1.expression_result() self.assertEqual(actual, expected) expression = "((100+20)*3-10/2+11-2(10+34)-54)" c2 = Calc(expression) expected = 'missing operator near parentheses' actual = c2.expression_result() self.assertEqual(actual, expected)
def get_ranking(user_list, user_id): """ ユーザidだけ渡して,おすすめユーザのidランキングを返す """ gd = GetData(user_list) cl = Calc() rank1 = cl.make_skill_level_ranking(gd.get_user_skill_level(user_id), gd.get_others_skill_level(user_id)) rank2 = cl.make_skill_type_ranking(gd.get_user_skill_type(user_id), gd.get_others_skill_type(user_id)) rank3 = cl.make_design_favorite_ranking(gd.get_user_design_favor(user_id), gd.get_others_design_favor(user_id)) rank4 = cl.make_character_ranking(gd.get_user_character(user_id), gd.get_others_character(user_id)) final_ranking = cl.final_ranking(rank1, rank2, rank3, rank4) return final_ranking
clusters[clustCount][1] = elemCount else: loc_ = Point(float(line[0]), float(line[1])) #tuples for location clusters[clustCount] = [[loc_],elemCount,Point(0,0),0] else: clustCount += 1 print "Processing Cluster:" + str(clustCount) elemCount = 1 #Number of elements in the cluster else: algoName=line[0] flag = 1 print str(clustCount) + " Clusters found" # finding centroid of each cluster and average distance of all elements in cluster to its centroid for key in clusters: cal = Calc(clusters[key][0]) centroid = cal.centroid(clusters[key][1]) clusters[key][2] = Point(centroid.latit,centroid.longit) #Centroid of the cluster clusters[key][3] = cal.avgDist(centroid,clusters[key][1]) #Average distance of the points of the cluster from the centroid dbIndex = 0 print "Calculated Centorid and Average Distance" for key1 in clusters: numer = 0 denom = 0 maximum = 0 for key2 in clusters: if key1 != key2: numer = clusters[key1][3] + clusters[key2][3] denom = cal.distance(clusters[key1][2].latit,clusters[key1][2].longit,clusters[key2][2].latit,clusters[key2][2].longit)
def test_mul(self): c = Calc() assert c.mul(2,3) == 6 assert c.mul(-1,3) == -3
def test_add(self): c = Calc() assert c.add(2,3) == 5 assert c.add(2,5) != 10
# it under the terms of the GNU General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # Klak is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with Klak. If not, see <http://www.gnu.org/licenses/>. from calc import Calc c = Calc() def t(testdesc,inp,ans): global c print("Testing:"), print(testdesc), print(' '), if c.calc(inp) == ans: print('PASS') else: print('FAIL') exit() t('operator +','1234+4321','5555') t('operator -','9999-1111','8888') t('operator *','12345*12345','152399025')
class XYPlot: """ The XYPlot Class is responsible for everything concerning the Canvas.It contains several drawing functions and scales the given data points onto the drawing layer. """ def __init__(self,_parent,_width,_height): ''' This Constructor sets default values for the main drawing Window''' self.NegativValueBool = 0 #This 'Bool' decides which Grid-form is drawn self.ALLSETGO = 0 #This 'Bool'is needed because of resize problems during initialisation self.width=_width #initial width of canvas self.height=_height #initial height of canvas self.parent=_parent #parent window of canvas self.bgcolor="white" self.fgcolor="black" self.canvas = Canvas(self.parent,width=self.width,height=self.height,bg=self.bgcolor) self.repaint(self.fgcolor) self.canvas.bind('<Configure>',self.resize) self.colorList = ['#0000FF','#FF0000','#00FF00', '#FFCC00', '#FF66FF','#00FFFF'] #blue,red,green,yellow,pink,turky self.calc = Calc() #Calculating Object, used regression and maxima search self.gridtransform = GridTransform() #Object, used for scaling def repaint(self,_color,maxima = None): '''The repaint method is called initionally and everytime something in the canvas is changed. It is splittet into two parts, one Drawing the main L Grid for just positive Values and one in cross Format for positiv and negativ Values.Every drawn Object is scaled with width and height of the canvas''' # ----------------------------------------------------------------- # ---------------------Setting Up L Grid # ----------------------------------------------------------------- if self.NegativValueBool == 0: #Drawing Backround of Plot-Canvas self.canvas.create_rectangle(0,0, self.width, self.height,fill=self.bgcolor) nextX = 0 nextY = 0 for i in range (0,7): #Drawing littlelines on X-Axis self.canvas.create_line((0.1)*self.width+nextX,0.9*self.height,(0.1)*self.width+nextX,0.91*self.height,width=2,fill=_color) #Drawing lightGrey BackroundGrid X-Direction self.canvas.create_line((0.1)*self.width+nextX,0.9*self.height,(0.1)*self.width+nextX,0.1*self.height,width=0.1,fill= 'LightGrey') #Drawing littlelines on Y-Axis self.canvas.create_line(0.1*self.width,0.9*self.height-nextY,(0.09)*self.width,0.9*self.height-nextY,width=2,fill=_color) #Drawing lightGrey BackroundGrid Y-Direction self.canvas.create_line(0.1*self.width,0.9*self.height-nextY,0.9*self.width,0.9*self.height-nextY,width=0.1,fill='LightGrey') nextX = nextX +(0.8*self.width)/6 nextY = nextY +(0.8*self.height)/6 #Drawing X-Axis and Y-Axis self.canvas.create_line(0.1*self.width,0.9*self.height,0.9*self.width,0.9*self.height,width=2,fill =_color) self.canvas.create_line(0.1*self.width,0.9*self.height,0.1*self.width,0.1*self.height,width=2,fill=_color) # ----------------------------------------------------------------- # --------Calculating and writing of interval labels for L Grid # ----------------------------------------------------------------- if maxima != None: next = 0 x_float = 0 for i in range(0,7): #Drawing value Labels on X-Axis if i<1: #to prevent division by zero x_float = 0 else: #stepsize on x axis is maxima divided by 6 x_float = x_float + maxima[0]/6 stringx_float = round(x_float,3) #important to use new float, to prevent rounding error x_str = str(stringx_float) if x_str != '0': self.canvas.create_text(0.1 * self.width+next,0.92*self.height, text=x_str) next = next +(0.8*self.width)/6 countMaxima = 0 for i in range (0,len(maxima)-1): #look how many values must be drawn per step if maxima[i]!= 0.0: countMaxima = countMaxima +1 newY = 0 for countY in range (1,countMaxima): #Drawing value labels on Y-Axis, depending on Maximum of each y if countY < 5: next = 0 y_float = 0 for i in range (0,7): if i<1: y_float = 0 else: y_float = y_float + maxima[countY]/6#divide maxima by 6 to get step values stringy_float = round (y_float,3) y_str = str(stringy_float) if stringy_float != 0.0: self.canvas.create_text(0.05*self.width,(0.9+newY)*self.height-next,text = y_str) next = next + (0.8*self.height)/6 newY = newY+0.018 else: Fail('It is not possible to show more than 4 Y-value Labels\n on the Y-Axis due to readability.All are drawn, but only the first 4 value Labels \n are shown, if you want to compare more than 4 you have to split up the .csv file and\n import again ') break else: # ----------------------------------------------------------------- # ---------------------Setting Up Cross Grid # ----------------------------------------------------------------- #Drawing Backround of Plot-Canvas self.canvas.create_rectangle(0,0, self.width, self.height,fill=self.bgcolor) self.canvas.create_text(0.48*self.width,0.53*self.height,text = '0') nextX = 0 nextY = 0 for i in range (0,14): #Drawing littlelines on X-Axis self.canvas.create_line((0.05)*self.width+nextX,0.5*self.height,(0.05)*self.width+nextX,0.51*self.height,width=2,fill=_color) #Drawing lightGrey BackroundGrid X-Direction self.canvas.create_line((0.05)*self.width+nextX,0.05*self.height,(0.05)*self.width+nextX,0.95*self.height,width=0.1,fill='LightGrey') #Drawing littlelines on Y-Axis self.canvas.create_line(0.5*self.width,0.95*self.height-nextY,0.49*self.width,0.95*self.height-nextY,width=2,fill=_color) #Drawing lightGrey BackroundGrid Y-Direction self.canvas.create_line(0.05*self.width,0.95*self.height-nextY,0.95*self.width,0.95*self.height-nextY,width=0.1,fill='LightGrey') nextX = nextX +(0.45*self.width)/6 nextY = nextY +(0.45*self.height)/6 #Drawing X-Axis and Y-Axis self.canvas.create_line(0.05,0.5*self.height,self.width-0.05,0.5*self.height,fill=_color) self.canvas.create_line(0.5*self.width,0.05,0.5*self.width,self.height-0.05,fill=_color) # ----------------------------------------------------------------- # -----Calculating and writing of interval labels for Cross Grid # ----------------------------------------------------------------- if maxima != None: next = 0 x_float = 0 negx_float = 0 for i in range(0,7): #Drawing text Labels on X-Axis if i==0: negx_float = -maxima[0] else: negx_float =negx_float + (maxima[0]/6) x_float = x_float + (maxima[0]/6) stringnegx_float = round(negx_float,3) stringx_float = round(x_float,3) negx_str = str(stringnegx_float) x_str = str(stringx_float) if stringnegx_float != 0.0: self.canvas.create_text(0.05 * self.width+next,0.53*self.height, text=negx_str) if stringx_float != 0.0: self.canvas.create_text(0.5 * self.width+next,0.53*self.height, text=x_str) next = next +(0.45*self.width)/6 countMaxima = 0 for i in range (0,len(maxima)-1): if maxima[i]!= 0.0: countMaxima = countMaxima +1 newY = 0 for countY in range (1,countMaxima): #Drawing text labels on Y-Axis, depending on Maximum of each y next = 0 y_float = 0 negy_float = 0 if countY < 5: for i in range (0,7): if i<1: negy_float = -maxima[countY] else: negy_float = negy_float + (maxima[countY]/6) y_float = y_float + maxima[countY]/6 stringnegy_float = round(negy_float,3) stringy_float = round(y_float,3) negy_str = str(stringnegy_float) y_str = str(stringy_float) if stringnegy_float != 0.0: self.canvas.create_text(0.45*self.width,(0.95+newY)*self.height-next,text = negy_str) if stringy_float != 0.0: self.canvas.create_text(0.45*self.width,(0.5+newY)*self.height-next,text = y_str) next = next + (0.45*self.height)/6 newY = newY + 0.018 else: Fail('It is not possible to show more than 4 Y-value Labels\n on the Y-Axis due to readability.All are drawn, but only the first 4 value Labels \n are shown, if you want to compare more than 4 you have to split up the .csv file and\n import again ') break def resize(self,event ): '''This Method is called by an event thrown by Mainwindow.It resizes the canvas. We had to post the scalefit behind the initialisatioprocess of XY-Plot by using ALLSETGO. If this isn't done the scale ends up in an endless Loop''' if self.ALLSETGO <=2: self.ALLSETGO += 1 else: self.ALLSETGO = 2 if self.ALLSETGO >= 2: self.repaint(self.bgcolor) self.width=event.width self.height=event.height self.canvas.configure(width=self.width,height=self.height) self.repaint(self.fgcolor) def clear (self): '''This method clears the canvas, it must be called on update, or when a new set is drawn so that the old drawings aren't interferring with the new.''' self.repaint(self.bgcolor) # ----------------------------------------------------------------- # -----Different drawing Functions to Draw on Canvas # ----------------------------------------------------------------- def drawControl(self,drawList,metaList,button): '''This Method decides which drawing Function is called, and gives the drawing Function the color for every Experiment and an maxima array used to scale data points''' maxima,minima = self.calc.getMax(drawList) for i in range ( 0,len(maxima)): if abs(minima[i]) > maxima[i]: maxima [i] = abs(minima[i]) absoluteMinimum = min(minima) #Here is decided which Grid is taken for the drawing by setting Negativ Value bool depending on absolute minimum of all minima if absoluteMinimum < 0: self.NegativValueBool = 1 else: self.NegativValueBool = 0 #Looking if max and min are correct to avoid dividing through zero if max(maxima)==0 and min(minima)==0: self.NegativValueBool = 2 self.repaint(self.fgcolor,maxima) self.drawMeta(metaList) if self.NegativValueBool != 2:#If this is not true an error ocurred in getMax function. #different drawing Functions are called depending on which button is pushed if button == 1 : i = 0 for element in drawList: color = self.colorList[i] self.drawDots(element,maxima,color) i = i+1 elif button == 2 : i = 0 for element in drawList: color = self.colorList[i] self.drawLine(element,maxima,color,0) i = i+1 elif button == 3 : i = 0 for element in drawList: color = self.colorList[i] self.drawRegLine(element,maxima,color) i = i+1 elif button == 4: i = 0 for element in drawList: color = self.colorList[i] self.drawLine(element,maxima,color,1) i = i+1 def drawMeta(self,metaList): '''The units the x and y Axis are drawn on canvas.X is set default on "t in Sekunden", whereas y is taken from the metadatadictionary of an given Experiment''' if self.NegativValueBool == 0: self.canvas.create_text(0.90*self.width, 0.95*self.height, text="t in Sekunden") else: self.canvas.create_text(0.93*self.width, 0.60*self.height, text="t in Sekunden") space = 0 for i in range(0,len(metaList)): if metaList[i]['vn_unit'].find('|') != -1:#Look if there is more than one MetaUnit singledata = metaList[i]['vn_unit'].split('|') down = 0 for single in range (0,len(singledata)):#Draw Meta units with fading colors exactly like their values self.canvas.create_text((0.08+space)*self.width, (0.02+down)*self.height, text=singledata[single],fill = self.colorFade(self.colorList[i],single)) down = down + 0.018 else: self.canvas.create_text((0.08+space)*self.width, 0.02*self.height, text=metaList[i]['vn_unit'],fill = self.colorList[i]) space = space+0.08 def drawLine(self,valueList,maxima,color,smooth): '''This Method is drawing an Line in the given color through every point of the valueList. The Line is scaled by the maxima array and can change into three patterns for three different y-Axis.If smooth is set True it draws an spline approximation through the points.Some Points may not lie on this approximatet line.''' self.drawDots(valueList, maxima, color)#First Draw all Dots, so that you can see the original for reference vn = len(valueList[0])# LineArray = [] i = 0 pattern = None # Is the pattern of the line if more than one y-List is in the while i < vn-1: del LineArray[:] if 0 < i < 4:#Fading color of the first 3 Experiments newcolor = self.colorFade(color,i) if i == 1: pattern = (1,2,3,4) elif i == 2: pattern =(1,2) else: pattern = None else: newcolor = color for j in range(0,len(valueList)): x1 = valueList[j][0] y1 = valueList[j][i+1] maxX = maxima[0] maxY = maxima[i+1] if self.NegativValueBool == 0 :#If set to zero, method is drawing on L-Grid scale LineArray.append(self.gridtransform.transAxisX(x1,y1,maxX,maxY,self.width)) LineArray.append(self.gridtransform.transAxisY(x1,y1,maxX,maxY,self.height)) else: # Method is drawing on Cross-Grid scale LineArray.append(self.gridtransform.negTransAxisX(x1,y1,maxX,maxY,self.width)) LineArray.append(self.gridtransform.negTransAxisY(x1,y1,maxX,maxY,self.height)) if smooth == 0: #Drawing direct Lines from point to point self.canvas.create_line(LineArray,smooth = "false",width=2,fill = newcolor,dash = pattern) else: #Drawing approximation using given points self.canvas.create_line(LineArray,smooth = "true",width=2,fill = newcolor,dash = pattern) i=i+1 def drawDots(self,valueList,maxima,color): '''Draws a dot for every x,y Koordinate in the valueList.It uses the maxima Array to scale and the color, which it can fade in case of more than one y-Axis.''' vn = len ( valueList[0]) if len(valueList) < 40: ovalsize = 3 else: ovalsize = 2 i = 0 while i < vn-1: if 0 < i < 4: newcolor = self.colorFade(color,i) else: newcolor = color for j in range (0,len(valueList)): x = valueList[j][0] y = valueList[j][i+1] maxX = maxima [0] maxY = maxima [i+1] if self.NegativValueBool == 0:#If 0,drawing on scale of L Grid self.canvas.create_oval(self.gridtransform.transAxisX(x,y,maxX,maxY,self.width)-ovalsize ,self.gridtransform.transAxisY(x,y,maxX,maxY,self.height)-ovalsize ,self.gridtransform.transAxisX(x,y,maxX,maxY,self.width)+ovalsize ,self.gridtransform.transAxisY(x,y,maxX,maxY,self.height)+ovalsize,fill = newcolor) else: #drawing on scale of Cross-Grid self.canvas.create_oval(self.gridtransform.negTransAxisX(x,y,maxX,maxY,self.width)-ovalsize ,self.gridtransform.negTransAxisY(x,y,maxX,maxY,self.height)-ovalsize ,self.gridtransform.negTransAxisX(x,y,maxX,maxY,self.width)+ovalsize ,self.gridtransform.negTransAxisY(x,y,maxX,maxY,self.height)+ovalsize,fill = newcolor) i = i+1 def drawRegLine(self,valueList,maxima,color): '''This method uses the Calc Class to draw a Linear Regression of the Data points in the valueList.I also changes color and pattern for the first 3 Lines pro Experiment''' self.drawDots(valueList, maxima, color) regList = zip(*valueList) vn = len ( valueList[0]) i = 0 pattern = None while i < vn-1: if 0 < i < 4: newcolor = self.colorFade(color,i) if i == 1: pattern = (1,2,3,4) elif i == 2: pattern =(1,2) else: pattern = None else: newcolor = color for j in range (0,len(valueList)): #using calc.linreg to generate an regression x1,y1,x2,y2=self.calc.linreg(regList[0],regList[i+1],maxima[0],maxima[i+1]) maxX = maxima [0] maxY = maxima [i+1] if self.NegativValueBool == 0: #drawing in L-Grid scale x1 = self.gridtransform.transAxisX(x1, y1, maxX, maxY, self.width) y1 = self.gridtransform.transAxisY(x1, y1, maxX, maxY, self.height) x2 = self.gridtransform.transAxisX(x2, y2, maxX, maxY, self.width) y2 = self.gridtransform.transAxisY(x2, y2, maxX, maxY, self.height) else: #drawing in Cross-Grid scale x1 = self.gridtransform.negTransAxisX(x1, y1, maxX, maxY, self.width) y1 = self.gridtransform.negTransAxisY(x1, y1, maxX, maxY, self.height) x2 = self.gridtransform.negTransAxisX(x2, y2, maxX, maxY, self.width) y2 = self.gridtransform.negTransAxisY(x2, y2, maxX, maxY, self.height) self.canvas.create_line(x1,y1,x2,y2,width=1.5,fill = newcolor,dash = pattern) i = i+1 # ----------------------------------------------------------------- # ------------Function to Fade color from bright to dark # ----------------------------------------------------------------- def colorFade(self,hexstring,fade): '''This Function converts the given hex-value into RGB, subtracts the maximum so that the color gets darker, than it reconverts into hex and returns the new color''' rgb = [] hex = hexstring.strip('#') hexlen = len(hex) for i in range(0,hexlen,hexlen/3): str = hex[i]+hex[i+1] rgb.append(int(str,16)) count = 0 index = rgb.index(max(rgb)) rgb[index]=rgb[index]-(60*fade) if rgb[index]<= 0: rgb[index]=0 rgbtuple = tuple(rgb) return "#%02x%02x%02x"%rgbtuple