Changeset 1203


Ignore:
Timestamp:
02/20/23 21:11:19 (23 months ago)
Author:
Maciej Komosinski
Message:

Some assert cases changed to raising exceptions

File:
1 edited

Legend:

Unmodified
Added
Removed
  • framspy/FramsticksLib.py

    r1200 r1203  
    4949                print()
    5050
    51                 print('Performing a basic test 1/2... ', end='')
    5251                simplest = self.getSimplest("1")
    53                 assert simplest == "X" and type(simplest) is str
    54                 print('OK.')
    55                 print('Performing a basic test 2/2... ', end='')
    56                 assert self.isValid(["X[0:0],", "X[0:0]", "X[1:0]"]) == [False, True, False]
    57                 print('OK.')
     52                if not (simplest == "X" and type(simplest) is str):
     53                        raise RuntimeError('Failed getSimplest() test.')
     54                if not (self.isValid(["X[0:0],", "X[0:0]", "X[1:0]"]) == [False, True, False]):
     55                        raise RuntimeError('Failed isValid() test.')
     56
    5857                if not self.DETERMINISTIC:
    5958                        frams.Math.randomize()
     
    6160                if sim_settings_files is not None:
    6261                        self.EVALUATION_SETTINGS_FILE = sim_settings_files # overwrite defaults
    63                 print('Using settings:', self.EVALUATION_SETTINGS_FILE)
    64                 assert isinstance(self.EVALUATION_SETTINGS_FILE, list)  # ensure settings file(s) are provided as a list
    65                
     62                print('Basic tests OK. Using settings:', self.EVALUATION_SETTINGS_FILE)
     63                print()
     64                if not isinstance(self.EVALUATION_SETTINGS_FILE, list):  # ensure settings file(s) are provided as a list
     65                        raise ValueError("Evaluation settings file(s) '%s' should be provided as a list" % self.EVALUATION_SETTINGS_FILE)
     66
    6667                for simfile in self.EVALUATION_SETTINGS_FILE:
    6768                        ec = frams.MessageCatcher.new()  # catch potential errors, warnings, messages - just to detect if there are ERRORs
    68                         ec.store = 2; # store all, because they are caught by MessageCatcher and will not appear on console (which we want)
     69                        ec.store = 2;  # store all, because they are caught by MessageCatcher and will not appear in output (which we want)
    6970                        frams.Simulator.ximport(simfile, 4 + 8 + 16)
    7071                        ec.close()
    71                         print(ec.messages) # output all caught messages
     72                        print(ec.messages)  # output all caught messages
    7273                        if ec.error_count._value() > 0:
    73                                 raise ValueError("Problem while importing file '%s'" % simfile) # make missing files or incorrect paths fatal because error messages are easy to overlook in output, and these errors would not prevent Framsticks simulator from performing genetic operations, starting and running in evaluate()
     74                                raise ValueError("Problem while importing file '%s'" % simfile)  # make missing files or incorrect paths fatal because error messages are easy to overlook in output, and these errors would not prevent Framsticks simulator from performing genetic operations, starting and running in evaluate()
    7475
    7576
     
    8990                if not self.PRINT_FRAMSTICKS_OUTPUT:
    9091                        ec = frams.MessageCatcher.new()  # mute potential errors, warnings, messages
    91                         ec.store = 2; # store all, because they are caught by MessageCatcher and will not appear on console
     92                        ec.store = 2;  # store all, because they are caught by MessageCatcher and will not appear in output
    9293
    9394                frams.GenePools[0].clear()
     
    110111                        ec.close()
    111112                        if ec.error_count._value() > 0:
    112                                 print(ec.messages) # if errors occurred, output all caught messages for debugging
    113                                 raise RuntimeError("[ERROR] %d error(s) and %d warning(s) while evaluating %d genotype(s)" % (ec.error_count._value(), ec.warning_count._value()-ec.error_count._value(), len(genotype_list))) # make errors fatal; by default they stop the simulation anyway so let's not use potentially incorrect or partial results and fix the cause first.
     113                                print(ec.messages)  # if errors occurred, output all caught messages for debugging
     114                                raise RuntimeError("[ERROR] %d error(s) and %d warning(s) while evaluating %d genotype(s)" % (ec.error_count._value(), ec.warning_count._value() - ec.error_count._value(), len(genotype_list))) # make errors fatal; by default they stop the simulation anyway so let's not use potentially incorrect or partial results and fix the cause first.
    114115
    115116                results = []
     
    134135                for g in genotype_list:
    135136                        mutated.append(frams.GenMan.mutate(frams.Geno.newFromString(g)).genotype._string())
    136                 assert len(genotype_list) == len(mutated), "Submitted %d genotypes, received %d validity values" % (len(genotype_list), len(mutated))
     137                if len(genotype_list) != len(mutated):
     138                        raise RuntimeError("Submitted %d genotypes, received %d mutants" % (len(genotype_list), len(mutated)))
    137139                return mutated
    138140
     
    197199
    198200        def isValid(self, genotype_list: List[str]) -> List[bool]:
     201                """
     202                :returns: genetic validity (i.e., not based on trying to build creatures from provided genotypes). For a more thorough check, see isValidCreature().
     203                """
    199204                assert isinstance(genotype_list, list)  # because in python, str has similar capabilities as list and here it would pretend to work too, so to avoid any ambiguity
    200205                valid = []
    201206                for g in genotype_list:
    202207                        valid.append(frams.Geno.newFromString(g).is_valid._int() == 1)
    203                 assert len(genotype_list) == len(valid), "Tested %d genotypes, received %d validity values" % (len(genotype_list), len(valid))
     208                if len(genotype_list) != len(valid):
     209                        raise RuntimeError("Tested %d genotypes, received %d validity values" % (len(genotype_list), len(valid)))
    204210                return valid
    205211
     
    246252        print('\tDissimilarity of Parent1 and Offspring:', framsLib.dissimilarity([parent1, offspring], 1)[0, 1])
    247253        print('\tPerformance of Offspring:', framsLib.evaluate([offspring]))
    248         print('\tValidity of Parent1, Parent 2, and Offspring:', framsLib.isValid([parent1, parent2, offspring]))
     254        print('\tValidity (genetic) of Parent1, Parent 2, and Offspring:', framsLib.isValid([parent1, parent2, offspring]))
Note: See TracChangeset for help on using the changeset viewer.