Best Python code snippet using autotest_python
practice_problem3.py
Source:practice_problem3.py  
...128                                  format_string)129    actual = practice_problem3a(circles)130    print_actual_result_of_test(expected, actual, test_results)131    # SUMMARY of test results:132    print_summary_of_test_results(test_results)133def practice_problem3a(circles):134    """135    What comes in:  A sequence of rg.Circles.136    What goes out:  Returns the product of the x-coordinates137      of the centers of the rg.Circles.138      Returns 1 if the given sequence is empty.139    Side effects: None.140    Examples:141      If the sequence is a list containing these 5 rg.Circles:142        rg.Circle(rg.Point(5, 10), 20)143        rg.Circle(rg.Point(2, 20), 20)144        rg.Circle(rg.Point(7, 30), 10)145        rg.Circle(rg.Point(10, 40), 20)146        rg.Circle(rg.Point(2, 50), 10)147      then this function returns:148        5 x 2 x 7 x 10 x 2, which is 1400.149    Type hints:150      :type sequence: [rg.Circle]151    """152    ###########################################################################153    # TODO: 2. Implement and test this function.154    #     The testing code is already written for you (above).155    ###########################################################################156    # DIFFICULTY AND TIME RATINGS (see top of this file for explanation)157    #    DIFFICULTY:      7158    #    TIME ESTIMATE:   10 minutes.159    ###########################################################################160def run_test_practice_problem3b():161    """ Tests the    practice_problem3b    function. """162    print()163    print('--------------------------------------------------')164    print('Testing the   practice_problem3b  function:')165    print('--------------------------------------------------')166    format_string = '    practice_problem3b( {} )'167    test_results = [0, 0]  # Number of tests passed, failed.168    # Test 1:169    expected = True170    sequence = [12, 33, 18, 'hello', 9, 13, 3, 9]171    print_expected_result_of_test([sequence], expected, test_results,172                                  format_string)173    actual = practice_problem3b(sequence)174    print_actual_result_of_test(expected, actual, test_results)175    # Test 2:176    expected = False177    sequence = [12, 12, 33, 'hello', 5, 33, 5, 9]178    print_expected_result_of_test([sequence], expected, test_results,179                                  format_string)180    actual = practice_problem3b(sequence)181    print_actual_result_of_test(expected, actual, test_results)182    # Test 3:183    expected = True184    sequence = (77, 112, 33, 'hello', 0, 43, 5, 77)185    print_expected_result_of_test([sequence], expected, test_results,186                                  format_string)187    actual = practice_problem3b(sequence)188    print_actual_result_of_test(expected, actual, test_results)189    # Test 4:190    expected = False191    sequence = [1, 1, 1, 1, 1, 1, 2]192    print_expected_result_of_test([sequence], expected, test_results,193                                  format_string)194    actual = practice_problem3b(sequence)195    print_actual_result_of_test(expected, actual, test_results)196    # Test 5:197    expected = False198    sequence = ['aa', 'a']199    print_expected_result_of_test([sequence], expected, test_results,200                                  format_string)201    actual = practice_problem3b(sequence)202    print_actual_result_of_test(expected, actual, test_results)203    # Test 6:204    expected = True205    sequence = 'aaa'206    print_expected_result_of_test([sequence], expected, test_results,207                                  format_string)208    actual = practice_problem3b(sequence)209    print_actual_result_of_test(expected, actual, test_results)210    # Test 7:211    expected = True212    sequence = ['aa', 'a', 'b', 'a', 'b', 'a']213    print_expected_result_of_test([sequence], expected, test_results,214                                  format_string)215    actual = practice_problem3b(sequence)216    print_actual_result_of_test(expected, actual, test_results)217    # Test 8:218    expected = False219    sequence = [9]220    print_expected_result_of_test([sequence], expected, test_results,221                                  format_string)222    actual = practice_problem3b(sequence)223    print_actual_result_of_test(expected, actual, test_results)224    # Test 9:225    expected = True226    sequence = [12, 33, 18, 'hello', 9, 13, 3, 9]227    print_expected_result_of_test([sequence], expected, test_results,228                                  format_string)229    actual = practice_problem3b(sequence)230    print_actual_result_of_test(expected, actual, test_results)231    # Test 10:232    expected = False233    sequence = ['hello there', 'he', 'lo', 'hello']234    print_expected_result_of_test([sequence], expected, test_results,235                                  format_string)236    actual = practice_problem3b(sequence)237    print_actual_result_of_test(expected, actual, test_results)238    # Test 11:239    expected = False240    sequence = ((8,), '8', (4 + 4, 4 + 4), [8, 8], 7, 8)241    print_expected_result_of_test([sequence], expected, test_results,242                                  format_string)243    actual = practice_problem3b(sequence)244    print_actual_result_of_test(expected, actual, test_results)245    # Test 12:246    expected = True247    sequence = [(8,), '8', [4 + 4, 4 + 4], (8, 8), 7, [8, 8]]248    print_expected_result_of_test([sequence], expected, test_results,249                                  format_string)250    actual = practice_problem3b(sequence)251    print_actual_result_of_test(expected, actual, test_results)252    # Test 13:253    expected = False254    sequence = [(8,), '8', [4 + 4, 4 + 4], [8, 8], 7, (8, 8)]255    print_expected_result_of_test([sequence], expected, test_results,256                                  format_string)257    actual = practice_problem3b(sequence)258    print_actual_result_of_test(expected, actual, test_results)259    # SUMMARY of test results:260    print_summary_of_test_results(test_results)261def practice_problem3b(sequence):262    """263    What comes in: A non-empty sequence.264    What goes out: Returns True if the last item of the sequence265      appears again somewhere else in the sequence.  Returns False266      if the last item of the sequence does NOT appear somewhere267      else in the sequence.268    Side effects: None.269    Examples:270      If the sequence is [12, 33, 18, 'hello', 9, 13, 3, 9],271      this function returns True because the last item (9)272      DOES appear elsewhere in the sequence (namely, at index 4).273      If the sequence is [12, 12, 33, 'hello', 5, 33, 5, 9],274      this function returns False because the last item (9)275      does NOT appear elsewhere in the sequence.276      If the sequence is (77, 112, 33, 'hello', 0, 43, 5, 77),277      this function returns True because the last item (77)278      DOES appear elsewhere in the sequence (namely, at index 0).279      If the sequence is [9], this function returns False280      because the last item (9) does NOT appear elsewhere281      in the sequence.282      If the sequence is [12, 33, 8, 'hello', 99, 'hello'],283      this function returns True since the last item ('hello')284      DOES appear elsewhere in the sequence285      (namely, at indices 3 and 5).286      If the sequence is ['hello there', 'he', 'lo', 'hello'],287      this function returns False because the last item ('hello')288      does NOT appear elsewhere in the sequence.289      If the sequence is 'hello there',290      this function returns True since the last item ('e') DOES291      appear elsewhere in the sequence (namely, at indices 1 and 8).292    Type hints:293      :type: sequence: list    or tuple or string294    """295    ###########################################################################296    # TODO: 3. Implement and test this function.297    #     The testing code is already written for you (above).298    #299    # IMPLEMENTATION REQUIREMENT:  You are NOT allowed to use the300    #    'count' or 'index' methods for sequences in this problem301    #    (because here we want you to demonstrate your ability302    #    to use explicit looping).303    ###########################################################################304    # DIFFICULTY AND TIME RATINGS (see top of this file for explanation)305    #    DIFFICULTY:      5306    #    TIME ESTIMATE:   8 minutes.307    ###########################################################################308def run_test_practice_problem3c():309    """ Tests the    practice_problem3c    function. """310    print()311    print('--------------------------------------------------')312    print('Testing the   practice_problem3c  function:')313    print('--------------------------------------------------')314    format_string = '    practice_problem3c( {} )'315    test_results = [0, 0]  # Number of tests passed, failed.316    # Test 1:317    expected = [1, 3, 4, 7]318    sequence = (9, 0, 8, 0, 0, 4, 4, 0)319    print_expected_result_of_test([sequence], expected, test_results,320                                  format_string)321    actual = practice_problem3c(sequence)322    print_actual_result_of_test(expected, actual, test_results)323    # Test 2:324    expected = [4]325    sequence = (9, 9, 9, 9, 0, 9, 9, 9)326    print_expected_result_of_test([sequence], expected, test_results,327                                  format_string)328    actual = practice_problem3c(sequence)329    print_actual_result_of_test(expected, actual, test_results)330    # Test 3:331    expected = []332    sequence = (4, 5, 4, 5, 4, 5, 4)333    print_expected_result_of_test([sequence], expected, test_results,334                                  format_string)335    actual = practice_problem3c(sequence)336    print_actual_result_of_test(expected, actual, test_results)337    # Test 4:338    expected = [0, 1, 2]339    sequence = [0, 0, 0]340    print_expected_result_of_test([sequence], expected, test_results,341                                  format_string)342    actual = practice_problem3c(sequence)343    print_actual_result_of_test(expected, actual, test_results)344    # Test 5:345    expected = [0, 1]346    sequence = [0, 0]347    print_expected_result_of_test([sequence], expected, test_results,348                                  format_string)349    actual = practice_problem3c(sequence)350    print_actual_result_of_test(expected, actual, test_results)351    # Test 6:352    expected = [0]353    sequence = [0, 77]354    print_expected_result_of_test([sequence], expected, test_results,355                                  format_string)356    actual = practice_problem3c(sequence)357    print_actual_result_of_test(expected, actual, test_results)358    # Test 7:359    expected = [1]360    sequence = [-40, 0]361    print_expected_result_of_test([sequence], expected, test_results,362                                  format_string)363    actual = practice_problem3c(sequence)364    print_actual_result_of_test(expected, actual, test_results)365    # Test 8:366    expected = []367    sequence = [-40, 67]368    print_expected_result_of_test([sequence], expected, test_results,369                                  format_string)370    actual = practice_problem3c(sequence)371    print_actual_result_of_test(expected, actual, test_results)372    # Test 9:373    expected = [1, 3, 4, 5, 6, 9, 10]374    sequence = (1, 0, 2, 0, 0, 0, 0, 6, 9, 0, 0, 12)375    print_expected_result_of_test([sequence], expected, test_results,376                                  format_string)377    actual = practice_problem3c(sequence)378    print_actual_result_of_test(expected, actual, test_results)379    # SUMMARY of test results:380    print_summary_of_test_results(test_results)381def practice_problem3c(sequence):382    """383    What comes in: A non-empty sequence of integers.384    What goes out: Returns a list of integers,385      where the integers are the places (indices)386      for which the item at that place equals 0.387    Side effects: None.388    Examples:389      Given sequence (9, 0, 8, 0, 0, 4, 4, 0)390         -- this function returns [1, 3, 4, 7]391              since 0 appears at indices 1, 3, 4, and 7.392      Given sequence [9, 9, 9, 9, 0, 9, 9, 9]393         -- this function returns [4]394              since 0 appears only at index 4.395      Given sequence (4, 5, 4, 5, 4, 5, 4)396         -- this function returns []397              since none of the items are 0.398      Given sequence [0, 0, 0]399         -- this function returns [0, 1, 2]400              since 0 appears at indices 0, 1 and 2.401    Type hints:402      :type: sequence: list    or tuple or string403    """404    ###########################################################################405    # TODO: 4. Implement and test this function.406    #     The testing code is already written for you (above).407    ###########################################################################408    # DIFFICULTY AND TIME RATINGS (see top of this file for explanation)409    #    DIFFICULTY:      5410    #    TIME ESTIMATE:   8 minutes.411    ###########################################################################412def run_test_practice_problem3d():413    """ Tests the    practice_problem3d    function. """414    print()415    print('--------------------------------------------------')416    print('Testing the   practice_problem3d  function:')417    print('--------------------------------------------------')418    format_string = '    practice_problem3d( {} )'419    test_results = [0, 0]  # Number of tests passed, failed.420    # Test 1:421    expected = 1422    sequence = (9, 0, 8, 0, 0, 4, 4, 0)423    print_expected_result_of_test([sequence], expected, test_results,424                                  format_string)425    actual = practice_problem3d(sequence)426    print_actual_result_of_test(expected, actual, test_results)427    # Test 2:428    expected = 4429    sequence = (9, 9, 9, 9, 0, 9, 9, 9)430    print_expected_result_of_test([sequence], expected, test_results,431                                  format_string)432    actual = practice_problem3d(sequence)433    print_actual_result_of_test(expected, actual, test_results)434    # Test 3:435    expected = -1436    sequence = (4, 5, 4, 5, 4, 5, 4)437    print_expected_result_of_test([sequence], expected, test_results,438                                  format_string)439    actual = practice_problem3d(sequence)440    print_actual_result_of_test(expected, actual, test_results)441    # Test 4:442    expected = 0443    sequence = [0, 0, 0]444    print_expected_result_of_test([sequence], expected, test_results,445                                  format_string)446    actual = practice_problem3d(sequence)447    print_actual_result_of_test(expected, actual, test_results)448    # Test 5:449    expected = 0450    sequence = [0, 0]451    print_expected_result_of_test([sequence], expected, test_results,452                                  format_string)453    actual = practice_problem3d(sequence)454    print_actual_result_of_test(expected, actual, test_results)455    # Test 6:456    expected = 0457    sequence = [0, 77]458    print_expected_result_of_test([sequence], expected, test_results,459                                  format_string)460    actual = practice_problem3d(sequence)461    print_actual_result_of_test(expected, actual, test_results)462    # Test 7:463    expected = 1464    sequence = [-40, 0]465    print_expected_result_of_test([sequence], expected, test_results,466                                  format_string)467    actual = practice_problem3d(sequence)468    print_actual_result_of_test(expected, actual, test_results)469    # Test 8:470    expected = -1471    sequence = [-40, 67]472    print_expected_result_of_test([sequence], expected, test_results,473                                  format_string)474    actual = practice_problem3d(sequence)475    print_actual_result_of_test(expected, actual, test_results)476    # Test 9:477    expected = 1478    sequence = (1, 0, 2, 0, 0, 0, 0, 6, 9, 0, 0, 12)479    print_expected_result_of_test([sequence], expected, test_results,480                                  format_string)481    actual = practice_problem3d(sequence)482    print_actual_result_of_test(expected, actual, test_results)483    # SUMMARY of test results:484    print_summary_of_test_results(test_results)485def practice_problem3d(sequence):486    """487    What comes in: A sequence of integers.488    What goes out: Returns the first (leftmost) place (index)489      for which the item at that place equals 0.490      Returns -1 if the sequence contains no items equal to 0.491    Side effects: None.492    Examples:493      Given sequence (9, 0, 8, 0, 0, 4, 4, 0)494         -- this function returns 1495              since 0 first appears at index 1496      Given sequence [9, 9, 9, 9, 0, 9, 9, 9]497         -- this function returns 4498              since 0 first appears at index 4499      Given sequence (4, 5, 4, 5, 4, 5, 4)500         -- this function returns -1501              since none of the items are 0.502      Given sequence [0, 0, 0]503         -- this function returns 0504              since 0 first appears at index 0505    Type hints:506      :type: sequence: list    or tuple or string507    """508    ###########################################################################509    # TODO: 5. Implement and test this function.510    #     The testing code is already written for you (above).511    ###########################################################################512    # DIFFICULTY AND TIME RATINGS (see top of this file for explanation)513    #    DIFFICULTY:      5514    #    TIME ESTIMATE:   8 minutes for each part of this problem.515    ###########################################################################516    ###########################################################################517    # TODO: 6. Just ABOVE this _TODO_, you should have implemented518    #     a solution for the   practice_problem3d   function.519    #     Here, put ANOTHER solution, as follows:520    #521    #       -- Your FIRST solution (ABOVE this _TODO_)522    #            should be a solution that IGNORES523    #              practice_problem3c (the previous problem).524    #525    #       -- Your SECOND solution (BELOW this _TODO_)526    #            should be a solution that USES (calls)527    #              practice_problem3c.528    #529    #          This solution should *** HAVE NO LOOP (no FOR). ***530    ###########################################################################531def run_test_practice_problem3e():532    """ Tests the    practice_problem3e    function. """533    print()534    print('--------------------------------------------------')535    print('Testing the   practice_problem3e  function:')536    print('--------------------------------------------------')537    format_string = '    practice_problem3e( {} )'538    test_results = [0, 0]  # Number of tests passed, failed.539    # Test 1:540    expected = 161541    sequence = (12, 33, 18, 9, 13, 3, 99, 20, 19, 20)542    print_expected_result_of_test([sequence], expected, test_results,543                                  format_string)544    actual = practice_problem3e(sequence)545    print_actual_result_of_test(expected, actual, test_results)546    # Test 2:547    expected = 29548    sequence = (3, 12, 10, 8, 8, 9, 8, 11)549    print_expected_result_of_test([sequence], expected, test_results,550                                  format_string)551    actual = practice_problem3e(sequence)552    print_actual_result_of_test(expected, actual, test_results)553    # Test 3:554    expected = -9999999999555    sequence = (-9999999999, 8888888888)556    print_expected_result_of_test([sequence], expected, test_results,557                                  format_string)558    actual = practice_problem3e(sequence)559    print_actual_result_of_test(expected, actual, test_results)560    # Test 4:561    expected = 8888888888562    sequence = (8888888888, -9999999999)563    print_expected_result_of_test([sequence], expected, test_results,564                                  format_string)565    actual = practice_problem3e(sequence)566    print_actual_result_of_test(expected, actual, test_results)567    # Test 5:568    expected = -176569    sequence = (-77, 20000, -33, 40000, -55, 60000, -11)570    print_expected_result_of_test([sequence], expected, test_results,571                                  format_string)572    actual = practice_problem3e(sequence)573    print_actual_result_of_test(expected, actual, test_results)574    # Test 6:575    expected = 0576    sequence = ()577    print_expected_result_of_test([sequence], expected, test_results,578                                  format_string)579    actual = practice_problem3e(sequence)580    print_actual_result_of_test(expected, actual, test_results)581    # Test 7:582    expected = 0583    sequence = []584    print_expected_result_of_test([sequence], expected, test_results,585                                  format_string)586    actual = practice_problem3e(sequence)587    print_actual_result_of_test(expected, actual, test_results)588    # Test 8:589    expected = 8590    sequence = [8]591    print_expected_result_of_test([sequence], expected, test_results,592                                  format_string)593    actual = practice_problem3e(sequence)594    print_actual_result_of_test(expected, actual, test_results)595    # Test 9:596    expected = -77597    sequence = (-77, 8)598    print_expected_result_of_test([sequence], expected, test_results,599                                  format_string)600    actual = practice_problem3e(sequence)601    print_actual_result_of_test(expected, actual, test_results)602    # Test 10:603    expected = 0604    sequence = (-77, 8, 77)605    print_expected_result_of_test([sequence], expected, test_results,606                                  format_string)607    actual = practice_problem3e(sequence)608    print_actual_result_of_test(expected, actual, test_results)609    # Test 11:610    expected = 1611    sequence = (-77, 8, 78)612    print_expected_result_of_test([sequence], expected, test_results,613                                  format_string)614    actual = practice_problem3e(sequence)615    print_actual_result_of_test(expected, actual, test_results)616    # Test 12:617    expected = 1618    sequence = (-77, 8, 78, 100)619    print_expected_result_of_test([sequence], expected, test_results,620                                  format_string)621    actual = practice_problem3e(sequence)622    print_actual_result_of_test(expected, actual, test_results)623    # SUMMARY of test results:624    print_summary_of_test_results(test_results)625def practice_problem3e(sequence):626    """627    What comes in:628      A sequence of numbers.629    What goes out:630      Returns the sum of the numbers at EVEN INDICES of the sequence.631    Side effects: None.632    Examples:633      If the sequence is:634          (12, 33, 18, 9, 13, 3, 99, 20, 19, 20)635      then this function returns636           12 + 18 + 13 + 99 + 19, which is 161.637    Type hints:638      :type sequence: list(float)    or tuple(float)639    """640    # -------------------------------------------------------------------------641    # TODO: 7. Implement and test this function.642    #     The testing code is already written for you (above).643    ###########################################################################644    # DIFFICULTY AND TIME RATINGS (see top of this file for explanation)645    #    DIFFICULTY:      5646    #    TIME ESTIMATE:   8 minutes.647    ###########################################################################648###############################################################################649# Our tests use the following to print error messages in red.650# Do NOT change it.  You do NOT have to do anything with it.651###############################################################################652def print_expected_result_of_test(arguments, expected,653                                  test_results, format_string, suffix=''):654    testing_helper.print_expected_result_of_test(arguments, expected,655                                                 test_results, format_string,656                                                 suffix)657def print_actual_result_of_test(expected, actual, test_results,658                                precision=None):659    testing_helper.print_actual_result_of_test(expected, actual,660                                               test_results, precision)661def print_summary_of_test_results(test_results):662    testing_helper.print_summary_of_test_results(test_results)663# To allow color-coding the output to the console:664USE_COLORING = True  # Change to False to revert to OLD style coloring665testing_helper.USE_COLORING = USE_COLORING666if USE_COLORING:667    # noinspection PyShadowingBuiltins668    print = testing_helper.print_colored669else:670    # noinspection PyShadowingBuiltins671    print = testing_helper.print_uncolored672# -----------------------------------------------------------------------------673# Calls  main  to start the ball rolling.674# The   try .. except   prevents error messages on the console from being675# intermingled with ordinary output to the console.676# -----------------------------------------------------------------------------...m5_loops_within_loops_sequences.py
Source:m5_loops_within_loops_sequences.py  
...136                                  format_string)137    actual = smallest_increase(numbers)138    print_actual_result_of_test(expected, actual, test_results)139    # SUMMARY of test results:140    print_summary_of_test_results(test_results)141def smallest_increase(numbers):142    """143    What comes in:  A sequence of numbers whose length is at least 2.144    What goes out:  The smallest "increase" from one number in the sequence145      to the next number in the sequence, where the INCREASE from A to B146      is (by definition) B - A.  Note that the "increase" can be negative;147      for example, the "increase" from 10 to 2 is -8.  See examples.148    Side effects:  None.149    Examples:150        smallest_increase( [10, 15, 3, 20, 22, 28, 20, 11] )151          examines the increases:152            from 10 to 15 (increase is 15 - 10, which is 5)153            from 15 to 3 (increase is 3 - 15, which is -12)154            from 3 to 20 (increase is 20 - 3, which is 17)155            from 20 to 22 (increase is 22 - 20, which is 2)156            from 22 to 28 (increase is 28 - 22, which is 6)157            from 28 to 20 (increase is 20 - 28, which is -8)158            from 20 to 11 (increase is 11 - 20, which is -9)159          and the smallest of those increases is -12,160          so the function returns  -12  in this example.161        smallest_increase( [-4, -10, 20, 5] )162          examines the increases:163            from -4 to -10 (increase is -10 - (-4)), which is -6)164            from -10 to 20 (increase is 20 - (-10), which is 30)165            from 20 to 5 (increase is 5 - 20, which is -15)166          and the smallest of those increases is -15,167          so the function returns  -15  in this example.168        smallest_increase( [2, 5, 10, 11, 35] )169          examines the increases:170            from 2 to 5 (increase is 5 - 2, which is 3)171            from 5 to 10 (increase is 10 - 5, which is 5)172            from 10 to 11 (increase is 11 - 10, which is 1)173            from 11 to 35 (increase is 35 - 11, which is 24)174          and the smallest of those increases is 1,175          so the function returns  1  in this example.176      ** ASK YOUR INSTRUCTOR FOR HELP **177      ** if these examples and the above specification are not clear to you. **178    Type hints:179      :type numbers: list[int] | tuple[int]180    """181    ###########################################################################182    # TODO: 3. Implement and test this function.183    #          Tests have been written for you (above).184    ###########################################################################185    ###########################################################################186    # -------------------------------------------------------------------------187    # DIFFICULTY AND TIME RATINGS (see top of this file for explanation)188    #    DIFFICULTY:     5189    #    TIME ESTIMATE:  10 minutes.190    # -------------------------------------------------------------------------191def run_test_two_d_smallest_increase():192    """ Tests the   two_d_smallest_increase   function. """193    print()194    print('--------------------------------------------------')195    print('Testing the   two_d_smallest_increase  function:')196    print('--------------------------------------------------')197    format_string = '    two_d_smallest_increase( {} )'198    test_results = [0, 0]  # Number of tests passed, failed.199    sequence_of_sequences = ([10, 15, 3, 20, 22, 28, 20, 11],200                             [-4, -10, 20, 5],201                             [2, 5, 10, 11, 35],202                             [2, 5, 10, 11, 35])203    expected = [-12, -15, 1, 1]204    print_expected_result_of_test([sequence_of_sequences], expected,205                                  test_results, format_string)206    actual = two_d_smallest_increase(sequence_of_sequences)207    print_actual_result_of_test(expected, actual, test_results)208    # Test 2:  Same as previous test, but using tuples209    sequence_of_sequences = ((10, 15, 3, 20, 22, 28, 20, 11),210                             (-4, -10, 20, 5),211                             (2, 5, 10, 11, 35),212                             (2, 5, 10, 11, 35))213    expected = [-12, -15, 1, 1]214    print_expected_result_of_test([sequence_of_sequences], expected,215                                  test_results, format_string)216    actual = two_d_smallest_increase(sequence_of_sequences)217    print_actual_result_of_test(expected, actual, test_results)218    # Test 3:219    sequence_of_sequences = ((25, 18, 20, 18, 25, 30, 20, 30, 25),220                             (2, 5, 10, 11, 35))221    expected = [-10, 1]222    print_expected_result_of_test([sequence_of_sequences], expected,223                                  test_results, format_string)224    actual = two_d_smallest_increase(sequence_of_sequences)225    print_actual_result_of_test(expected, actual, test_results)226    # Test 3:227    sequence_of_sequences = ((25, 18, 20, 18, 25, 30, 20, 30, 25),228                             (2, 5, 10, 11, 35))229    expected = [-10, 1]230    print_expected_result_of_test([sequence_of_sequences], expected,231                                  test_results, format_string)232    actual = two_d_smallest_increase(sequence_of_sequences)233    print_actual_result_of_test(expected, actual, test_results)234    # Test 4:235    sequence_of_sequences = ((25, 18, 20, 18, 25, 30, 20, 30, 25),)236    expected = [-10]237    print_expected_result_of_test([sequence_of_sequences], expected,238                                  test_results, format_string)239    actual = two_d_smallest_increase(sequence_of_sequences)240    print_actual_result_of_test(expected, actual, test_results)241    # Test 5:242    sequence_of_sequences = ((25, 35),)243    expected = [10]244    print_expected_result_of_test([sequence_of_sequences], expected,245                                  test_results, format_string)246    actual = two_d_smallest_increase(sequence_of_sequences)247    print_actual_result_of_test(expected, actual, test_results)248    # Test 6:249    sequence_of_sequences = ((35, 25),)250    expected = [-10]251    print_expected_result_of_test([sequence_of_sequences], expected,252                                  test_results, format_string)253    actual = two_d_smallest_increase(sequence_of_sequences)254    print_actual_result_of_test(expected, actual, test_results)255    # SUMMARY of test results:256    print_summary_of_test_results(test_results)257def two_d_smallest_increase(sequence_of_subsequences):258    """259    What comes in:  A non-empty sequence of subsequences of numbers,260      where each subsequence has length at least 2.261    What goes out:262      A list whose length is the same as the number of subsequences,263      where the Jth item in the list is the smallest increase264      in the Jth subsequence265      (and "smallest increase" is defined as in the previous problem).266    Side effects:  None.267    Examples:268        two_d_smallest_increase(269          ( [10, 15, 3, 20, 22, 28, 20, 11],270            [-4, -10, 20, 5],271            [2, 5, 10, 11, 35],272            [2, 5, 10, 11, 35] )273        returns  [-12, , -15, 1, 1]274        (Note that the subsequences here are the examples used in the previous275        problem -- see that problems for why the smallest increases of the276        four subsequences are -12, -15, 1 and 1, respectively.)277      ** ASK YOUR INSTRUCTOR FOR HELP **278      ** if these examples and the above specification are not clear to you. **279    Type hints:280      :type sequence_of_subsequences: tuple[list[int]] | tuple[tuple[int]]281    """282    ###########################################################################283    # TODO: 4. Implement and test this function.284    #          Tests have been written for you (above).285    ###########################################################################286    ###########################################################################287    # -------------------------------------------------------------------------288    # DIFFICULTY AND TIME RATINGS (see top of this file for explanation)289    #    DIFFICULTY:     5290    #    TIME ESTIMATE:  10 minutes.291    # -------------------------------------------------------------------------292def run_test_sum_bigger_than_average():293    """ Tests the   sum_bigger_than_average   function. """294    print()295    print('--------------------------------------------------')296    print('Testing the   sum_bigger_than_average  function:')297    print('--------------------------------------------------')298    format_string = '    sum_bigger_than_average( {} )'299    test_results = [0, 0]  # Number of tests passed, failed.300    # Test 1:301    numbers = ([5, 1, 8, 3],302               [0, -3, 7, 8, 1],303               [6, 3, 5, 5, -10, 12])304    expected = 5 + 8 + 7 + 8 + 6 + 5 + 5 + 12  # which is 56 (A = 17/4 = 4.25)305    print_expected_result_of_test([numbers], expected, test_results,306                                  format_string)307    actual = sum_bigger_than_average(numbers)308    print_actual_result_of_test(expected, actual, test_results)309    # Test 2:310    numbers = ([5, 1, 1, 1, 1, 3],311               [1, 4, 4, 1, 1, 1, 1],312               [6, 3, 2, 3, 4, 5, 6, 7, 8, 9],313               [1, 2, 3, 2, 1])314    # so A = 12/6 = 2 and315    expected = 5 + 3 + 4 + 4 + 6 + 3 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 3  # = 70316    print_expected_result_of_test([numbers], expected, test_results,317                                  format_string)318    actual = sum_bigger_than_average(numbers)319    print_actual_result_of_test(expected, actual, test_results)320    # Test 3:321    numbers = ([5, 1, 1, 1, 1],322               [1, 6, 5, 1, 1, 1, 1],323               [6, 3, 2, 3, 4, 5, 6, 7, 8, 9],324               [1, 2, 3, 4, 5],325               [5, 6, 7, 8, 9, 10, 11, 12])326    expected = 151327    print_expected_result_of_test([numbers], expected, test_results,328                                  format_string)329    actual = sum_bigger_than_average(numbers)330    print_actual_result_of_test(expected, actual, test_results)331    # Test 4:332    numbers = ([1, 2, 1, 1, 1],333               [1, 6, 5, 1, 1, 1, 1],334               [6, 3, 2, 3, 4, 5, 6, 7, 8, 9],335               [1, 2, 3, 4, 5],336               [5, 6, 7, 8, 9, 10, 11, 12])337    expected = 148338    print_expected_result_of_test([numbers], expected, test_results,339                                  format_string)340    actual = sum_bigger_than_average(numbers)341    print_actual_result_of_test(expected, actual, test_results)342    # Test 5:343    numbers = ([100, 200, 1, 1, 1],344               [1, 6, 5, 1, 1, 1, 1],345               [6, 3, 2, 3, 4, 5, 6, 7, 8, 9],346               [1, 2, 3, 4, 5],347               [5],348               [5, 6, 7, 8, 9, 10, 11, 12])349    expected = 300350    print_expected_result_of_test([numbers], expected, test_results,351                                  format_string)352    actual = sum_bigger_than_average(numbers)353    print_actual_result_of_test(expected, actual, test_results)354    # Test 6:355    numbers = ([100, 200, 99],356               [300])357    expected = 500358    print_expected_result_of_test([numbers], expected, test_results,359                                  format_string)360    actual = sum_bigger_than_average(numbers)361    print_actual_result_of_test(expected, actual, test_results)362    # Test 7:363    numbers = ([98, 200, 99],364               [300])365    expected = 500366    print_expected_result_of_test([numbers], expected, test_results,367                                  format_string)368    actual = sum_bigger_than_average(numbers)369    print_actual_result_of_test(expected, actual, test_results)370    # Test 8:371    numbers = ([100, 200, 99],372               [50])373    expected = 200374    print_expected_result_of_test([numbers], expected, test_results,375                                  format_string)376    actual = sum_bigger_than_average(numbers)377    print_actual_result_of_test(expected, actual, test_results)378    # Test 9:379    numbers = ([-4],380               [],381               [],382               [-3, 0, 1, 2, 3],383               [-3.99],384               [-4.0000000001])385    expected = -0.99  # from -3 + 0 + 1 + 2 + 3 + (-3.99)386    print_expected_result_of_test([numbers], expected, test_results,387                                  format_string, suffix="(approximately)")388    actual = sum_bigger_than_average(numbers)389    print_actual_result_of_test(expected, actual, test_results, precision=6)390    # Test 10:391    numbers = ([-99999999999],392               [],393               [])394    expected = 0395    print_expected_result_of_test([numbers], expected, test_results,396                                  format_string)397    actual = sum_bigger_than_average(numbers)398    print_actual_result_of_test(expected, actual, test_results)399    # Test 11:400    numbers = ([1, 4],401               [3, 3, 3, 3],402               [],403               [2.49, 2.48, 2.49],404               [])405    expected = 4 + 3 + 3 + 3 + 3  # = 16406    print_expected_result_of_test([numbers], expected, test_results,407                                  format_string)408    actual = sum_bigger_than_average(numbers)409    print_actual_result_of_test(expected, actual, test_results)410    # Test 12:411    numbers = ([1, -1],)412    expected = 1413    print_expected_result_of_test([numbers], expected, test_results,414                                  format_string)415    actual = sum_bigger_than_average(numbers)416    print_actual_result_of_test(expected, actual, test_results)417    # SUMMARY of test results:418    print_summary_of_test_results(test_results)419def sum_bigger_than_average(numbers):420    """421    What comes in:  A non-empty sequence of sequences of numbers,422      with the first sub-sequence being non-empty.423    What goes out:  Returns the sum of all the numbers in the subsequences424      that are bigger than A,425      where A is the average of the numbers in the FIRST sub-sequence.426    Side effects:  None.427    Examples:428      Suppose that  numbers  is:429          ([5, 1, 8, 3],430           [0, -3, 7, 8, 1],431           [6, 3, 5, 5, -10, 12])432      Then: the average of the numbers in the first sub-sequence is433        (5 + 1 + 8 + 3) / 4, which is 17 / 4, which is 4.25, and so434        sum_bigger_than_average(numbers)   returns   (5 + 8 + 7 + 8 + 6 + 5 + 5 + 12),435        which is 56, since the numbers in that sum are the numbers436        in the subsequences that are bigger than 4.25.437      ** ASK YOUR INSTRUCTOR FOR HELP **438      ** if this example and the above specification are not clear to you. **439     """440    ###########################################################################441    # TODO: 5. Implement and test this function.442    #          Tests have been written for you (above).443    ###########################################################################444    ###########################################################################445    # -------------------------------------------------------------------------446    # DIFFICULTY AND TIME RATINGS (see top of this file for explanation)447    #    DIFFICULTY:      7448    #    TIME ESTIMATE:  15 minutes.449    # -------------------------------------------------------------------------450###############################################################################451# Our tests use the following to print error messages in red.452# Do NOT change it.  You do NOT have to do anything with it.453###############################################################################454def print_function_call_of_test(arguments, test_results, format_string):455    testing_helper.print_function_call_of_test(arguments, test_results,456                                               format_string)457def print_expected_result_of_test(arguments, expected,458                                  test_results, format_string, suffix=''):459    testing_helper.print_expected_result_of_test(arguments, expected,460                                                 test_results,461                                                 format_string,462                                                 suffix)463def print_actual_result_of_test(expected, actual, test_results,464                                precision=None):465    testing_helper.print_actual_result_of_test(expected, actual,466                                               test_results, precision)467def print_summary_of_test_results(test_results):468    testing_helper.print_summary_of_test_results(test_results)469# To allow color-coding the output to the console:470USE_COLORING = True  # Change to False to revert to OLD style coloring471testing_helper.USE_COLORING = USE_COLORING472if USE_COLORING:473    # noinspection PyShadowingBuiltins474    print = testing_helper.print_colored475else:476    # noinspection PyShadowingBuiltins477    print = testing_helper.print_uncolored478# -----------------------------------------------------------------------------479# Calls  main  to start the ball rolling.480# The   try .. except   prevents error messages on the console from being481# intermingled with ordinary output to the console.482# -----------------------------------------------------------------------------...report.py
Source:report.py  
...35        normalized_name = name.split("/")[-2]36    if normalized_name.endswith('.xml'):37        return normalized_name[:-4]38    return normalized_name39def build_test_results(vp_report_data, d_report_data):40    """41    Function to process line-by-line data from *voip_patrol* and *database* JSONL results file42    to a dict with a structure43    "scenario_name": {44        "status": ...45        "start_time": ...46        "end_time": ...47        "tests": {48            ...49        }50        "d_status": ...51        "d_error": {52            "stage": ...53            "text": ...54        }55    }56    """57    test_results = {}58    current_test = "orphaned"59    for test_entity in vp_report_data:60        # Scenario process start61        # We got start or end of test62        if test_entity.get("scenario"):63            previous_test = current_test64            current_test_scenario_info = test_entity.get("scenario")65            current_test = current_test_scenario_info.get("name", "orphaned")66            current_test = _normalize_test_name(current_test)67            if current_test_scenario_info.get("state") == "start":68                if current_test not in test_results:69                    test_results[current_test] = {}70                    test_results[current_test]["start_time"] = current_test_scenario_info.get("time")71                    continue72                test_results[current_test]["status"] = "FAIL"73                test_results[current_test]["status_text"] = "Multiple starts"74                continue75            if current_test_scenario_info.get("state") == "end":76                if previous_test != current_test:77                    if current_test not in test_results:78                        test_results[current_test] = {}79                    if previous_test not in test_results:80                        test_results[previous_test] = {}81                    test_results[current_test]["status"] = "FAIL"82                    test_results[current_test]["status_text"] = "Start/End are not aligned"83                    test_results[previous_test]["status"] = "FAIL"84                    test_results[previous_test]["status"] = "Start/End are not aligned"85                    current_test = "orphaned"86                    continue87                if current_test not in test_results:88                    test_results[current_test] = {}89                    test_results[current_test]["status"] = "FAIL"90                    test_results[current_test]["status_text"] = "Bug 1 in the report script, please fix"91                    current_test = "orphaned"92                    continue93                scenario_total_tasks = current_test_scenario_info.get("total tasks", "NA")94                scenario_completed_tasks = current_test_scenario_info.get("completed tasks", "NA")95                test_results[current_test]["end_time"] = current_test_scenario_info.get("time")96                test_results[current_test]["status"] = current_test_scenario_info.get("result", "FAIL")97                test_results[current_test]["counter"] = "{}/{}".format(scenario_completed_tasks, scenario_total_tasks)98                # Status PASS at this moment means only that all tests are completed99                if test_results[current_test]["status"] == "FAIL":100                    test_results[current_test]["status_text"] = "Scenario failed"101                    current_test = "orphaned"102                    continue103                if test_results[current_test].get("tests"):104                    for test_result_line in test_results[current_test]["tests"].values():105                        test_failed_count = 0106                        if test_result_line.get("result") == "FAIL":107                            test_failed_count += 1108                            test_results[current_test]["status"] = "FAIL"109                            test_results[current_test]["status_text"] = "{} tests has failed".format(test_failed_count)110                if test_results[current_test]["status"] != "FAIL":111                    test_results[current_test]["status"] = "PASS"112                    test_results[current_test]["status_text"] = "Scenario passed"113                current_test = "orphaned"114                continue115            # Scenario state not end nor start. It's a bug116            if current_test not in test_results:117                test_results[current_test] = {}118            test_results[current_test]["status"] = "FAIL"119            test_results[current_test]["status_text"] = "Problem with scenario, unknown state"120            current_test = "orphaned"121            continue122        # Scenario process end123        if len(test_entity) != 1:124            if current_test not in test_results:125                test_results[current_test] = {}126            test_results[current_test]["status"] = "FAIL"127            test_results[current_test]["status_text"] = "Problem with the test info"128            continue129        test_number = next(iter(test_entity)) # Get first and only key in test_entity130        if not test_results[current_test].get("tests"):131            test_results[current_test]["tests"] = {}132        test_results[current_test]["tests"][test_number] = test_entity[test_number]133    # Add FAIL if we have tests without end's134    for test_result_name, test_result_info in test_results.items():135        if not test_result_info.get("status"):136            test_results[test_result_name]["status"] = "FAIL"137            test_results[test_result_name]["status_text"] = "End action missing"138            continue139        if not test_result_info.get("end_time"):140            test_results[test_result_name]["status"] = "FAIL"141            test_results[test_result_name]["status_text"] = "End time missing"142    # Enrich results with DB info143    for test_entity in d_report_data:144        if not test_entity.get("scenario"):145            continue146        current_test = test_entity.get("scenario")147        if current_test not in test_results:148            continue149        current_test_d_status = test_entity.get("status", "FAIL")150        current_test_d_existing_status = test_results[current_test].get("d_status")151        if current_test_d_status == "PASS" and current_test_d_existing_status == "PASS":152            continue153        if current_test_d_status != "PASS":154            test_results[current_test]["d_status"] = "FAIL"155            if "d_error" not in test_results[current_test]:156                test_results[current_test]["d_error"] = {}157                test_results[current_test]["d_error"]["stage"] = ""158                test_results[current_test]["d_error"]["text"] = ""159            test_results[current_test]["d_error"]["stage"] += "{} ".format(test_entity.get("stage", "err"))160            test_results[current_test]["d_error"]["text"] += "{} ".format(test_entity.get("error", "err"))161            continue162        if not current_test_d_existing_status:163            test_results[current_test]["d_status"] = "PASS"164    return test_results165def align_test_results_with_test_list(test_results, test_list):166    '''167    Make sure report have all tests results, that was in initial test list168    '''169    for actual_test in test_list:170        if actual_test in test_results:171            continue172        test_results[actual_test] = {}173        test_results[actual_test]["status"] = "FAIL"174        test_results[actual_test]["status_text"] = "Scenario is not present in the results"175    for actual_test in test_results:176        if actual_test in test_list:177            continue178        test_results[actual_test]["status"] = "FAIL"179        test_results[actual_test]["status_text"] = "Scenario is not present in the scenario list"180def filter_results_default(test_results):181    '''182    Find all failed tests183    '''184    printed_results = {}185    errors = list()186    for scenario_name, scenario_details in test_results.items():187        print("Processing {}".format(scenario_name))188        if scenario_details.get("status") == "PASS" and scenario_details.get("d_status", "PASS") == "PASS":189            continue190        printed_results[scenario_name] = {}191        printed_results[scenario_name]["status"] = scenario_details.get("status")192        printed_results[scenario_name]["status_text"] = scenario_details.get("status_text")193        printed_results[scenario_name]["start_time"] = scenario_details.get("start_time")194        printed_results[scenario_name]["end_time"] = scenario_details.get("end_time")195        printed_results[scenario_name]["task_counter"] = scenario_details.get("counter")196        if scenario_details.get("d_status", "PASS") != "PASS":197            printed_results[scenario_name]["d_status"] = scenario_details.get("d_status")198            printed_results[scenario_name]["d_error"] = scenario_details.get("d_error", "")199        errors.append(scenario_name)200        failed_tests = {}201        if scenario_details.get("tests"):202            for test_name, test_details in scenario_details["tests"].items():203                if test_details.get("result") == "PASS":204                    continue205                failed_tests[test_name] = test_details206        if len(failed_tests) > 1:207            printed_results[scenario_name]["failed_tests"] = failed_tests208    status = None209    if len(errors) > 0:210        status = errors211    return status, printed_results212def print_table(print_results):213    tbl = PrettyTable()214    tbl.field_names = ["Scenario", "Test", "Status" ,"Text"]215    for scenario_name, scenario_details in print_results.items():216        vp_status_text = scenario_details.get("status")217        d_status_text = scenario_details.get("d_status", "PASS")218        if d_status_text == "PASS":219            status_text = vp_status_text220        else:221            status_text = "{}/DB:{}".format(vp_status_text, d_status_text)222        tbl.add_row([scenario_name, "", status_text, scenario_details.get("status_text")])223        if not (type(scenario_details.get("tests")) is dict):224            continue225        for test_data in scenario_details.get("tests").values():226            tbl.add_row(["", test_data.get("label"), test_data.get("result"), test_data.get("result_text")])227    tbl.align = "r"228    print(tbl)229def print_results_json_full(test_results):230    failed_scenarios, printed_results = filter_results_default(test_results)231    print(json.dumps(printed_results, sort_keys=True, indent=4))232    if failed_scenarios is not None:233        print("Scenarios {} are failed!".format(failed_scenarios))234        return235    print("All scenarios are OK!")236def print_results_table_default(test_results):237    failed_scenarios, printed_results = filter_results_default(test_results)238    if failed_scenarios is not None:239        print_table(printed_results)240        print("Scenarios {} are failed!".format(failed_scenarios))241        return242    print("All scenarios are OK!")243def print_results_json_default(test_results):244    error, printed_results = filter_results_default(test_results)245    if error is not None:246        print(json.dumps(printed_results, sort_keys=True, indent=4))247        print("Scenarios {} are failed!".format(error))248        return249    print("All scenarios are OK!")250def print_results_table_full(test_results):251    failed_scenarios, _ = filter_results_default(test_results)252    print_table(test_results)253    if failed_scenarios is not None:254        print("Scenarios {} are failed!".format(failed_scenarios))255        return256    print("All scenarios are OK!")257# Main program starts258try:259    vp_report_file_name = os.environ.get("VP_RESULT_FILE", "result.jsonl")260    vp_report_file_path = r'/opt/report/' + vp_report_file_name261    with open(vp_report_file_path) as report_file:262        process_error, vp_report_data = process_jsonl_file(report_file)263        if process_error:264            raise Exception("Error processing voip_patrol report file: {}".format(process_error))265    d_report_file_name = os.environ.get("D_RESULT_FILE", "database.jsonl")266    d_report_file_path = r'/opt/report/' + d_report_file_name267    d_report_data = {}268    if os.path.exists(d_report_file_path):269        with open(d_report_file_path) as report_file:270            process_error, d_report_data = process_jsonl_file(report_file)271            if process_error:272                raise Exception("Error processing database report file: {}".format(process_error))273    tests_list = get_tests_list()274    test_results = build_test_results(vp_report_data, d_report_data)275    align_test_results_with_test_list(test_results, tests_list)276    print_style = os.environ.get("REPORT_TYPE", "json")277    print_style = print_style.lower()278    if print_style == "json_full":279        print_results_json_full(test_results)280    elif print_style == "table_full":281        print_results_table_full(test_results)282    elif print_style.startswith("table"):283        print_results_table_default(test_results)284    else:285        print_results_json_default(test_results)286except Exception as e:...test.py
Source:test.py  
1import os.path as osp2import logging3import time4import argparse5from collections import OrderedDict6import options.options as option7import utils.util as util8from data.util import bgr2ycbcr9from data import create_dataset, create_dataloader10from models import create_model11#### options12parser = argparse.ArgumentParser()13parser.add_argument('-opt', type=str, required=True, help='Path to options YMAL file.')14opt = option.parse(parser.parse_args().opt, is_train=False)15opt = option.dict_to_nonedict(opt)16util.mkdirs(17    (path for key, path in opt['path'].items()18     if not key == 'experiments_root' and 'pretrain_model' not in key and 'resume' not in key))19util.setup_logger('base', opt['path']['log'], 'test_' + opt['name'], level=logging.INFO,20                  screen=True, tofile=True)21logger = logging.getLogger('base')22logger.info(option.dict2str(opt))23#### Create test dataset and dataloader24test_loaders = []25for phase, dataset_opt in sorted(opt['datasets'].items()):26    test_set = create_dataset(dataset_opt)27    test_loader = create_dataloader(test_set, dataset_opt)28    logger.info('Number of test images in [{:s}]: {:d}'.format(dataset_opt['name'], len(test_set)))29    test_loaders.append(test_loader)30model = create_model(opt)31for test_loader in test_loaders:32    test_set_name = test_loader.dataset.opt['name']33    logger.info('\nTesting [{:s}]...'.format(test_set_name))34    test_start_time = time.time()35    dataset_dir = osp.join(opt['path']['results_root'], test_set_name)36    util.mkdir(dataset_dir)37    test_results = OrderedDict()38    test_results['psnr'] = []39    test_results['ssim'] = []40    test_results['psnr_y'] = []41    test_results['ssim_y'] = []42    for data in test_loader:43        need_GT = False if test_loader.dataset.opt['dataroot_GT'] is None else True44        model.feed_data(data, need_GT=need_GT)45        img_path = data['GT_path'][0] if need_GT else data['LQ_path'][0]46        img_name = osp.splitext(osp.basename(img_path))[0]47        model.test()48        visuals = model.get_current_visuals(need_GT=need_GT)49        sr_img = util.tensor2img(visuals['SR'])  # uint850        # save images51        suffix = opt['suffix']52        if suffix:53            save_img_path = osp.join(dataset_dir, img_name + suffix + '.png')54        else:55            save_img_path = osp.join(dataset_dir, img_name + '.png')56        util.save_img(sr_img, save_img_path)57        # calculate PSNR and SSIM58        if need_GT:59            gt_img = util.tensor2img(visuals['GT'])60            gt_img = gt_img / 255.61            sr_img = sr_img / 255.62            crop_border = opt['crop_border'] if opt['crop_border'] else opt['scale']63            if crop_border == 0:64                cropped_sr_img = sr_img65                cropped_gt_img = gt_img66            else:67                cropped_sr_img = sr_img[crop_border:-crop_border, crop_border:-crop_border, :]68                cropped_gt_img = gt_img[crop_border:-crop_border, crop_border:-crop_border, :]69            psnr = util.calculate_psnr(cropped_sr_img * 255, cropped_gt_img * 255)70            ssim = util.calculate_ssim(cropped_sr_img * 255, cropped_gt_img * 255)71            test_results['psnr'].append(psnr)72            test_results['ssim'].append(ssim)73            if gt_img.shape[2] == 3:  # RGB image74                sr_img_y = bgr2ycbcr(sr_img, only_y=True)75                gt_img_y = bgr2ycbcr(gt_img, only_y=True)76                if crop_border == 0:77                    cropped_sr_img_y = sr_img_y78                    cropped_gt_img_y = gt_img_y79                else:80                    cropped_sr_img_y = sr_img_y[crop_border:-crop_border, crop_border:-crop_border]81                    cropped_gt_img_y = gt_img_y[crop_border:-crop_border, crop_border:-crop_border]82                psnr_y = util.calculate_psnr(cropped_sr_img_y * 255, cropped_gt_img_y * 255)83                ssim_y = util.calculate_ssim(cropped_sr_img_y * 255, cropped_gt_img_y * 255)84                test_results['psnr_y'].append(psnr_y)85                test_results['ssim_y'].append(ssim_y)86                logger.info(87                    '{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}; PSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}.'.88                    format(img_name, psnr, ssim, psnr_y, ssim_y))89            else:90                logger.info('{:20s} - PSNR: {:.6f} dB; SSIM: {:.6f}.'.format(img_name, psnr, ssim))91        else:92            logger.info(img_name)93    if need_GT:  # metrics94        # Average PSNR/SSIM results95        ave_psnr = sum(test_results['psnr']) / len(test_results['psnr'])96        ave_ssim = sum(test_results['ssim']) / len(test_results['ssim'])97        logger.info(98            '----Average PSNR/SSIM results for {}----\n\tPSNR: {:.6f} dB; SSIM: {:.6f}\n'.format(99                test_set_name, ave_psnr, ave_ssim))100        if test_results['psnr_y'] and test_results['ssim_y']:101            ave_psnr_y = sum(test_results['psnr_y']) / len(test_results['psnr_y'])102            ave_ssim_y = sum(test_results['ssim_y']) / len(test_results['ssim_y'])103            logger.info(104                '----Y channel, average PSNR/SSIM----\n\tPSNR_Y: {:.6f} dB; SSIM_Y: {:.6f}\n'....Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
