示例#1
0
 def setUp(self):
     self.parser_94nop = Corewar.Parser(standard=Corewar.STANDARD_94_NOP)
     self.parser_88 = Corewar.Parser(standard=Corewar.STANDARD_88)
     self.parser_tiny = Corewar.Parser(coresize=800, maxprocesses=800,
                                       maxcycles=8000, maxlength=20,
                                       mindistance=20, pspacesize=50,
                                       standard=Corewar.STANDARD_94)
     self.parser_nano = Corewar.Parser(coresize=80, maxprocesses=80,
                                       maxcycles=800, maxlength=5,
                                       mindistance=5, pspacesize=5,
                                       standard=Corewar.STANDARD_94)
     self.parser_lp = Corewar.Parser(coresize=8000, maxprocesses=8,
                                     maxcycles=80000, maxlength=200,
                                     mindistance=200, pspacesize=500,
                                     standard=Corewar.STANDARD_94)
示例#2
0
def run_mp_battles(battle):
    i, w1, w2, cfg = battle
    try:
        mars = CwB.MARS_94nop(coresize=cfg.coresize,
                              maxprocesses=cfg.processes,
                              maxcycles=cfg.cycles,
                              mindistance=cfg.min_sep,
                              maxlength=cfg.max_length)

        if w1.wobj == None:
            parser = Corewar.Parser(coresize=cfg.coresize,
                                    maxprocesses=cfg.processes,
                                    maxcycles=cfg.cycles,
                                    mindistance=cfg.min_sep,
                                    maxlength=cfg.max_length,
                                    standard=Corewar.STANDARD_94)
            w1.wobj = parser.parse(w1.code)

        if cfg.p_mode is True:
            result = mars.p_run((w1.wobj, w2))
            w1_score, w2_score = result[:]
        else:
            result = mars.run((w1.wobj, w2), cfg.rounds)
            w1_score, w2_score, trash = result[:]
    except:
        print traceback.format_exc()
        raise

    return (i, w2.name, w1_score)
示例#3
0
    def test_fight_05(self):
        """Hazy Lazy ... vs. TimeScape (1.0) (100 rounds)"""

        mars = Corewar.Benchmarking.MARS_94nop()
        parser = Corewar.Parser(standard=Corewar.STANDARD_94_NOP)
        w1 = parser.parse_file('warriors/Koenigstuhl/94nop/hazylazy.red')
        w2 = parser.parse_file('warriors/Koenigstuhl/94nop/timescape10.red')
        result = mars.run((w1, w2), 100, 102165)
        self.assertEqual(result, [[47, 34, 19], [34, 47, 19]])
示例#4
0
    def test_fight_04(self):
        """Blacken vs. Willow (100 rounds)"""

        mars = Corewar.Benchmarking.MARS_94nop()
        parser = Corewar.Parser(standard=Corewar.STANDARD_94_NOP)
        w1 = parser.parse_file('warriors/Koenigstuhl/94nop/blacken.red')
        w2 = parser.parse_file('warriors/Koenigstuhl/94nop/willow.red')
        result = mars.run((w1, w2), 100, 131415)
        self.assertEqual(result, [[59, 25, 16], [25, 59, 16]])
示例#5
0
    def test_fight_01(self):
        """Son of Vain vs. Harmless Fluffy Bunny (100 rounds)"""

        mars = Corewar.Benchmarking.MARS_94nop()
        parser = Corewar.Parser(standard=Corewar.STANDARD_94_NOP)
        w1 = parser.parse_file('warriors/Koenigstuhl/94nop/sonofvain.red')
        w2 = parser.parse_file('warriors/Koenigstuhl/94nop/hfb.red')
        result = mars.run((w1, w2), 100, 6666)
        self.assertEqual(result, [[17, 28, 55], [28, 17, 55]])
示例#6
0
    def test_fight_02(self):
        """Arrow vs. nPaper II (100 rounds)"""

        mars = Corewar.Benchmarking.MARS_94nop()
        parser = Corewar.Parser(standard=Corewar.STANDARD_94_NOP)
        w1 = parser.parse_file('warriors/Koenigstuhl/94nop/arrow.red')
        w2 = parser.parse_file('warriors/Koenigstuhl/94nop/npaper2.red')
        result = mars.run((w1, w2), 100, 932487)
        self.assertEqual(result, [[41, 43, 16], [43, 41, 16]])
示例#7
0
    def test_fight_06(self):
        """Hullabaloo vs. SilKing (100 rounds)"""

        mars = Corewar.Benchmarking.MARS_94nop()
        parser = Corewar.Parser(standard=Corewar.STANDARD_94_NOP)
        w1 = parser.parse_file('warriors/Koenigstuhl/94nop/hullabaloo.red')
        w2 = parser.parse_file('warriors/Koenigstuhl/94nop/silking.red')
        result = mars.run((w1, w2), 100, 1110001)
        self.assertEqual(result, [[18, 13, 69], [13, 18, 69]])
示例#8
0
    def test_fight_10(self):
        """Arrow vs. TimeScape (1.0) vs. Porch Swing (100 rounds, mw-fight)"""

        mars = Corewar.Benchmarking.MARS_94nop()
        parser = Corewar.Parser(standard=Corewar.STANDARD_94_NOP)
        w1 = parser.parse_file('warriors/Koenigstuhl/94nop/arrow.red')
        w2 = parser.parse_file('warriors/Koenigstuhl/94nop/timescape10.red')
        w3 = parser.parse_file('warriors/Koenigstuhl/94nop/porchswing.red')
        result = mars.mw_run((w1, w2, w3), rounds=100, seed=2006)
        self.assertEqual(result, [[23, 21, 9, 47], [15, 31, 9, 45],\
                                  [22, 10, 9, 59]])
示例#9
0
    def test_fight_01(self):
        """Freight Train v0.2 vs. The Next Step '88"""

        parser = Corewar.Parser(standard=Corewar.STANDARD_88)
        mars88 = Corewar.Benchmarking.MARS_88()

        try:
            w1 = parser.parse_file('Test/warriors/freighttrainv02.red')
            w2 = parser.parse_file('Test/warriors/nextstep88.red')
        except:
            self.fail('Could not parse warriors.')

        result = mars88.run((w1, w2), 1000, 1234567)
        self.assertEqual(result, [[195, 262, 543], [262, 195, 543], 107775203])
示例#10
0
 def _reset_warrior(self):
     if (not self.init_warrior):
         self.warrior = Corewar.Warrior()
         self.warrior.start = 0
         insn = self._get_inst(self.core_size)
         self.warrior.instructions.append(insn)
     else:
         self.warrior = self.parser.parse_file(self.init_warrior)
     self.warrior.name = self.wname
     self.warrior.author = self.wauthor
     self.insns = []
     for i in range(len(self.warrior.instructions)):
         self.insns.append(self.warrior.instructions[i])
     for i in range(self.max_length - len(self.insns)):
         self.insns.append(None)
示例#11
0
    def test_invalid_insn(self):
        """Execution of invalid instruction in Corewar.Benchmarking.MARS_88"""

        parser = Corewar.Parser(standard=Corewar.STANDARD_94_NOP)
        mars88 = Corewar.Benchmarking.MARS_88()

        try:
            w1 = parser.parse_file('Test/warriors/invalid_insn_88.red')
        except:
            self.fail('Could not parse warrior.')

        try:
            result = mars88.run((w1, w1), rounds=1)
        except ValueError, e:
            pass
示例#12
0
 def test_fight_07(self):
     """Digital Swarm vs. White Noise (RBv1.5r10) (all permutations)"""
     mars = Corewar.Benchmarking.MARS_94nop(coresize=800,
                                            maxprocesses=800,
                                            maxcycles=8000,
                                            maxlength=20,
                                            mindistance=20)
     parser = Corewar.Parser(coresize=800,
                             maxprocesses=800,
                             maxcycles=800,
                             maxlength=20,
                             mindistance=20,
                             standard=Corewar.STANDARD_94_NOP)
     w1 = parser.parse_file('warriors/Koenigstuhl/tiny/digitalswarm.red')
     w2 = parser.parse_file('warriors/Koenigstuhl/tiny/whitenoise.red')
     result = mars.p_run((w1, w2))
     self.assertEqual(result, [[480, 369, 673], [369, 480, 673]])
示例#13
0
    def test_fight_09(self):
        """Taking Over Nano IX vs. toy soldier (all permutations)"""

        mars = Corewar.Benchmarking.MARS_94nop(coresize=80,
                                               maxprocesses=80,
                                               maxcycles=800,
                                               maxlength=5,
                                               mindistance=5)
        parser = Corewar.Parser(coresize=80,
                                maxprocesses=80,
                                maxcycles=80,
                                maxlength=5,
                                mindistance=5,
                                standard=Corewar.STANDARD_94_NOP)
        w1 = parser.parse_file('warriors/Koenigstuhl/nano/tonano9.red')
        w2 = parser.parse_file('warriors/Koenigstuhl/nano/toysoldier.red')
        result = mars.p_run((w1, w2))
        self.assertEqual(result, [[60, 70, 12], [70, 60, 12]])
示例#14
0
    def test_fight_08(self):
        """Tinyshot vs. Hired Sword (all permutations)"""

        mars = Corewar.Benchmarking.MARS_94nop(coresize=800,
                                               maxprocesses=800,
                                               maxcycles=8000,
                                               maxlength=20,
                                               mindistance=20)
        parser = Corewar.Parser(coresize=800,
                                maxprocesses=800,
                                maxcycles=800,
                                maxlength=20,
                                mindistance=20,
                                standard=Corewar.STANDARD_94_NOP)
        w1 = parser.parse_file('warriors/Koenigstuhl/tiny/tinyshot.red')
        w2 = parser.parse_file('warriors/Koenigstuhl/tiny/hired.red')
        result = mars.p_run((w1, w2))
        self.assertEqual(result, [[643, 779, 100], [779, 643, 100]])
示例#15
0
    def test_fight_03(self):
        """Muskrat vs. Digital Swarm (1000 rounds)"""

        mars = Corewar.Benchmarking.MARS_94nop(coresize=800,
                                               maxprocesses=800,
                                               maxcycles=8000,
                                               maxlength=20,
                                               mindistance=20)
        parser = Corewar.Parser(coresize=800,
                                maxprocesses=800,
                                maxcycles=8000,
                                mindistance=20,
                                maxlength=20,
                                pspacesize=50,
                                standard=Corewar.STANDARD_94)
        w1 = parser.parse_file('warriors/Koenigstuhl/tiny/muskrat.red')
        w2 = parser.parse_file('warriors/Koenigstuhl/tiny/digitalswarm.red')
        result = mars.run((w1, w2), 1000, 8765)
        self.assertEqual(result, [[127, 702, 171], [702, 127, 171]])
示例#16
0
    def __init__(self, cfg):
        self.cfg = cfg
        self.mars = CwB.MARS_94nop(coresize=cfg.coresize,
                                   maxprocesses=cfg.processes,
                                   maxcycles=cfg.cycles,
                                   mindistance=cfg.min_sep,
                                   maxlength=cfg.max_length)

        self.parser = Corewar.Parser(coresize=cfg.coresize,
                                     maxprocesses=cfg.processes,
                                     maxcycles=cfg.cycles,
                                     mindistance=cfg.min_sep,
                                     maxlength=cfg.max_length,
                                     standard=Corewar.STANDARD_94)

        self.entries = []
        self.bias = []
        self.hill_age = 0
        self.rounds_executed = 0

        self.hill_min = 0.0
        self.hill_max = 0.0
        self.hill_avg = 0.0
        self.hill_median = 0.0
示例#17
0
    def __init__(
            self,
            seed=None,  # random seed
            std='icws_88',  # ICWS standard
            act_type='prog_discrete',  # action space type, can be of ['prog'|'direct]_['discrete'|'continuous'|'hybrid']
            obs_type='full',  # observation space type, can be of 'full', the dumps of the full core
            coresize=8000,  # size of the core
            fieldrange=None,  # range of the fields of instructions in action space
            maxprocesses=8000,  # maximum number of warriors in the core
            maxcycles=10000,  # maximum core cycles before tie
            maxsteps=1000,  # maximum steps before 'done' is true
            dumpintv=5,  # interval of the core dump in cycles
            dumprange=None,  # range of the core dump, away from address 0
            mindistance=100,  # minimum distance between warriors
            maxlength=100,  # maximum length of all warriors
            actmaxlength=25,  # maximum length of the warrior specified by action space
            pspacesize=None,  # pspace type
            opponents='warriors/88/simplified/Imp.red',  # list of file paths to opponent warriors
            initwarrior=None,  # initial warrior
            warriorname='RL_Imp',  # name of the warrior
            warriorauthor='my computer',  # author of the warrior
            numplayers=2,  # number of corewar players
            verbose=False,  # output debug msg if true
            randomize=False,  # randomize initial positions of warriors before each run
            recordvideo=False,  # record videos based on result
            rewardfunc=None,  # custom reward function
    ):
        if (not opponents and not isinstance(opponents, str)
                and len(opponents) == 0):
            raise ValueError("specify path to opponent warriors")
        if (numplayers > 2):
            raise ValueError("multi-warrior not supported")
        if (mindistance > coresize):
            raise ValueError("mindistance > coresize")
        self.viewer = None
        self.core_size = coresize
        if not fieldrange:
            self.field_range = coresize
        else:
            self.field_range = fieldrange % coresize
        self.max_proc = maxprocesses
        self.max_cycle = maxcycles
        self.max_steps = maxsteps
        self.max_length = maxlength
        self.max_length_ac = actmaxlength
        if self.max_length_ac > self.max_length:
            self.max_length_ac = self.max_length
        self.min_dist = mindistance
        if self.min_dist < self.max_length:
            self.min_dist = self.max_length
        self.obs_dump_intv = dumpintv
        if not dumprange:
            dumprange = self.core_size
        elif (dumprange > self.core_size // 2):
            dumprange = self.core_size // 2
        self.obs_dump_range = dumprange
        self.num_players = numplayers
        self.verbose = verbose
        self.randomize = randomize
        self.record_video = recordvideo
        self._reward_func = self._default_reward
        if (rewardfunc):
            self._reward_func = rewardfunc
        if (not seed):
            self.seed(0)
        else:
            self.seed(seed)

        if std == 'icws_88':
            self.dim_opcode = dim_opcode_88
            self.dim_modifiers = dim_modifiers_88
            self.dim_addrmodes = dim_addrmodes_88
            self._get_inst = Instruction88
            self._OPCODE = OPCODE88
            self._AMODE = AMODE88
            self._BMODE = BMODE88
            # self._MODIFIER = MODIFIER
            self.parser = Corewar.Parser(coresize=self.core_size,
                                         maxprocesses=self.max_proc,
                                         maxcycles=self.max_cycle,
                                         maxlength=self.max_length,
                                         mindistance=self.min_dist,
                                         standard=Corewar.STANDARD_88)
            self.mars = Corewar.Benchmarking.MARS_88(
                coresize=self.core_size,
                maxprocesses=self.max_proc,
                maxcycles=self.max_cycle,
                mindistance=self.min_dist,
                maxlength=self.max_length)
        elif std == 'icws_94_nop':
            self.dim_opcode = dim_opcode_94_nop
            self.dim_modifiers = dim_modifiers_94_nop
            self.dim_addrmodes = dim_addrmodes_94_nop
            self._get_inst = Instruction
            self._OPCODE = OPCODE
            self._AMODE = AMODE
            self._BMODE = BMODE
            self._MODIFIER = MODIFIER
            self.parser = Corewar.Parser(coresize=self.core_size,
                                         maxprocesses=self.max_proc,
                                         maxcycles=self.max_cycle,
                                         maxlength=self.max_length,
                                         mindistance=self.min_dist,
                                         standard=Corewar.STANDARD_94_NOP)
            self.mars = Corewar.Benchmarking.MARS_94nop(
                coresize=self.core_size,
                maxprocesses=self.max_proc,
                maxcycles=self.max_cycle,
                mindistance=self.min_dist,
                maxlength=self.max_length)
        elif std == 'icws_94':
            raise ValueError("standard icws94 not supported")
        else:
            raise ValueError("invalid standard")

        self.opponents = []
        if isinstance(opponents, str):
            opponents = [opponents]
        for i in range(len(opponents)):
            self.log('reading warrior in %s' % (opponents[i]))
            self.opponents.append(self.parser.parse_file(opponents[i]))

        self.init_warrior = initwarrior
        self.wname = warriorname
        self.wauthor = warriorauthor
        self._reset_warrior()

        self.num_insn = self.dim_opcode * self.dim_addrmodes * self.dim_addrmodes
        if (act_type == 'direct_discrete'):
            self.dim_action_insn = (self.max_length_ac, )
            self.dim_action_field = (self.max_length_ac, 2)
            self._parse_act = self._parse_act_direct_disc
            self.action_space = MultiDiscrete(
                [self.num_insn] * self.max_length_ac +
                [self.field_range] * self.max_length_ac +
                [self.field_range] * self.max_length_ac)
        elif (act_type == 'direct_continuous'):
            self.dim_action_insn = (self.max_length_ac, self.num_insn)
            self.dim_action_field = (self.max_length_ac, 2)
            self._parse_act = self._parse_act_direct_cont
            ilow = np.full(self.dim_action_insn, 0.0)
            ihigh = np.full(self.dim_action_insn, 1.0)
            flow = np.full(self.dim_action_field, 0.0)
            fhigh = np.full(self.dim_action_field, self.field_range - 1)
            low = np.concatenate((ilow, flow), axis=1)
            high = np.concatenate((ihigh, fhigh), axis=1)
            self.action_space = Box(low=low, high=high, dtype=np.float32)
        elif (act_type == 'direct_hybrid'):
            self.dim_action_field = (self.max_length_ac, 2)
            self._parse_act = self._parse_act_direct_hybd
            self.action_space = Tuple(
                (MultiDiscrete([self.num_insn] * self.max_length_ac),
                 Box(low=0,
                     high=self.field_range - 1,
                     shape=self.dim_action_field,
                     dtype=np.uint16)))
        elif (act_type == 'prog_discrete'):
            self._parse_act = self._parse_act_prog_disc
            self.action_space = MultiDiscrete([
                dim_progress_act, self.max_length_ac, self.num_insn,
                self.field_range, self.field_range
            ])
        elif (act_type == 'prog_continuous'):
            self._parse_act = self._parse_act_prog_cont
            self.action_space = Box(
                low=np.array([0.0] * dim_progress_act + [0.0] +
                             [0.0] * self.num_insn + [0.0] * 2),
                high=np.array([1.0] * dim_progress_act + [self.max_length_ac] +
                              [1.0] * self.num_insn + [self.field_range] * 2),
                dtype=np.float32)
        elif (act_type == 'prog_hybrid'):
            self._parse_act = self._parse_act_prog_hybd
            self.action_space = Tuple(
                (Discrete(dim_progress_act),
                 Box(low=0,
                     high=self.max_length_ac - 1,
                     shape=(1, ),
                     dtype=np.uint16), Discrete(self.num_insn),
                 Box(low=0,
                     high=self.field_range - 1,
                     shape=(2, ),
                     dtype=np.uint16)))
        else:
            raise ValueError("invalid action space type")

        self.dim_obs_sample = int(self.max_cycle // self.obs_dump_intv)
        if (obs_type == 'full'):
            self._get_obs = self._get_obs_full
            self.dim_obs_insn = (
                self.dim_obs_sample,
                self.obs_dump_range * 2,
            )
            self.dim_obs_field = (self.dim_obs_sample, self.obs_dump_range * 2,
                                  2)
            self.observation_space = Dict({
                'op':
                Box(low=0,
                    high=self.dim_opcode - 1,
                    shape=self.dim_obs_insn,
                    dtype=np.uint8),
                'amode':
                Box(low=0,
                    high=self.dim_addrmodes - 1,
                    shape=self.dim_obs_insn,
                    dtype=np.uint8),
                'bmode':
                Box(low=0,
                    high=self.dim_addrmodes - 1,
                    shape=self.dim_obs_insn,
                    dtype=np.uint8),
                'fields':
                Box(low=0,
                    high=self.core_size - 1,
                    shape=self.dim_obs_field,
                    dtype=np.uint16),
                'proc':
                Box(low=0,
                    high=self.core_size - 1,
                    shape=(self.dim_obs_sample,
                           self.max_proc * self.num_players),
                    dtype=np.uint16)
            })
        elif (obs_type == 'warriors'):
            raise ValueError("obs space type not supported")
        else:
            raise ValueError("invalid observation space type")
示例#18
0
    def setUp(self):
        """Set up the test."""

        self.calculator = Corewar.Calculator()
示例#19
0
    def setUp(self):
        """Set up test case."""

        self.parser = Corewar.Parser(standard=Corewar.STANDARD_88)