コード例 #1
0
def run_robots(exercise_options: Dict):
    start_coordinates = exercise_options['start']
    start = Point(start_coordinates['x'], start_coordinates['y'])

    field_options = exercise_options['field']
    field_height: int = int(field_options['height'])
    field_width: int = int(field_options['width'])

    sample_field = Field(field_height, field_width)
    sample_robot = SampleRobot('sample_robot', sample_field, start, Colors.RED)
    sample_robot.run(*exercise_options['run_options'])

    user_field = Field(field_height, field_width)
    user_robot = UserRobot('user_robot', user_field, start, Colors.BLUE)
    user_robot.run(*exercise_options['run_options'])

    result: Dict = {
        'correct': validate(user_field, sample_field),
        'start': {
            'x': sample_robot.initial_position.x,
            'y': sample_robot.initial_position.y
        },
        'sample': dump_robot(sample_robot),
        'user': dump_robot(user_robot)
    }

    # Write result to json file
    with open('actions.json', 'w+') as actions_file:
        actions_file.write(json.dumps(result))
コード例 #2
0
def get_augmented_iodata(i, o):
    values = list(set(np.unique(i)) | set(np.unique(o)))
    permutations = list(
        set(tuple(np.random.permutation(len(values))) for k in range(5)))
    for permutation in permutations:
        rv = {k: values[v] for k, v in zip(values, permutation)}
        inp = np.asarray([[rv[x] for x in line] for line in i])
        out = np.asarray([[rv[x] for x in line] for line in o])
        yield Field(inp), Field(out)
コード例 #3
0
 def predict(self, field):
     if isinstance(field, IOData):
         for v in self.predict(field.input_field):
             yield v
         return
     #while True:
     yield Field(field.data)
コード例 #4
0
def run_robots(exercise_options: Dict):
    # Inst. fields for both robots
    field = Field(exercise_options['field_height'],
                  exercise_options['field_width'])

    # Inst. robots
    user_robot = UserRobot('user_robot', field, exercise_options['start'],
                           Colors.BLUE)
    sample_robot = SampleRobot('sample_robot', field,
                               exercise_options['start'], Colors.RED)

    for step_count in range(max_steps):
        user_robot.act(exercise_options['run_options'])
        sample_robot.act(exercise_options['run_options'])

    result: Dict = {
        'correct': False,  # validate(user_field, sample_field),
        'user': {
            'name': user_robot.name,
            'start': str(user_robot.initial_position),
            'actions_size': len(user_robot.actions),
            'actions': list(map(str, user_robot.actions))
        },
        'sample': {
            'name': sample_robot.name,
            'start': str(sample_robot.initial_position),
            'size': len(sample_robot.actions),
            'actions': list(map(str, sample_robot.actions))
        }
    }

    # Write result to json file
    with open('actions.json', 'w+') as actions_file:
        actions_file.write(json_dump(result, indent=2))
コード例 #5
0
def __fields_equal__(user_field: Field, sample_field: Field,
                     mind_colors: bool) -> bool:
    if user_field.height != sample_field.height or user_field.width != sample_field.width:
        return False

    for row_index in range(user_field.height):
        for cell_index in range(user_field.width):

            user_cell = user_field.get_by_coordinates(row_index, cell_index)
            sample_cell = sample_field.get_by_coordinates(
                row_index, cell_index)

            if not __compare_cells__(user_cell, sample_cell, mind_colors):
                return False

    return True
コード例 #6
0
    def predict(self, field):
        if isinstance(field, IOData):
            for v in self.predict(field.input_field):
                yield v
            return
        #repainter = Repaint(field.data)
        prediction_data = np.zeros(field.shape)
        #print(self.use_zeros)
        graph_data, inputs = GraphFeatureExtractor.prepare_graph_features_for_eval(
            field, self.use_zeros)
        if inputs.shape[0] < 1:
            return field
        predictions = []
        #print(inputs.shape, len(graph_data), len(self.xgb_classifiers))
        #print(len(self.xgb_classifiers), inputs.shape)
        for i in range(min(inputs.shape[0], self.ncomponents)):
            xgb = self.xgb_classifiers[i]
            predictions.append(xgb.predict([inputs[i]]))
        #result = repainter(preds).tolist()
        for comp, pred in zip(graph_data, predictions):
            color = pred
            for i, j in comp['pos']:
                prediction_data[i, j] = color

        yield Field(prediction_data)
コード例 #7
0
ファイル: shapes.py プロジェクト: latticetower/kaggle-arc
 def predict(self, field):
     if isinstance(field, IOData):
         for v in self.predict(field.input_field):
             yield v
         return
     resizer = Resizer(self.m1, self.m2)
     result = resizer(field.data)
     yield Field(result)
コード例 #8
0
ファイル: shapes.py プロジェクト: latticetower/kaggle-arc
 def predict(self, field):
     if isinstance(field, IOData):
         for v in self.predict(field.input_field):
             yield v
         return
     fractal = Fractal(self.m1, self.m2)
     result = fractal(field.data)
     yield Field(result)
コード例 #9
0
ファイル: shapes.py プロジェクト: latticetower/kaggle-arc
 def predict(self, field):
     if isinstance(field, IOData):
         for v in self.predict(field.input_field):
             yield v
         return
     repainter = Repaint(field.data)
     for prediction in self.predictor.predict(field):
         result = self.mirror(prediction.data)
         result = repainter(result)
         yield Field(result)
コード例 #10
0
 def predict(self, field):
     if isinstance(field, IOData):
         for v in self.predict(field.input_field):
             yield v
         return
     (r, c) = get_subpattern(field.data, wildcard=0)
     if self.common_patch is not None:
         patch = self.common_patch
     else:
         patch = self.get_patch(field.data, r, c, True)
     #print(patch)
     if patch is None or np.any(patch == 0):
         yield Field(field.data)
         return
     result = field.data.copy()
     coords = np.where(result == 0)
     for (x, y) in zip(*coords):
         result[x, y] = patch[x % r, y % c]
     yield Field(result)
コード例 #11
0
ファイル: shapes.py プロジェクト: latticetower/kaggle-arc
 def predict(self, field):
     if isinstance(field, IOData):
         for v in self.predict(field.input_field):
             yield v
             #yield field.reconstruct(v)
         return
     if self.input_pattern is not None:
         color_convertor = dict(
             set(
                 list(
                     zip(*np.stack(
                         [self.input_pattern,
                          self.crop_func(field.data)], 0).reshape(2, -1)))))
         result = np.asarray([[color_convertor.get(x, x) for x in line]
                              for line in self.pattern])
         result = Field(result)
         yield result  # field.reconstruct(result)
         #return
     data = self.crop_func(field.data)
     h, w = data.shape
     h = min(self.pattern.shape[0], h)
     w = min(self.pattern.shape[1], w)
     ss = self.pattern[:h, :w]
     background_colors = np.unique(data[np.where(ss == 0)])
     colormap = {
         i: [
             c for c in np.unique(data[np.where(ss == i)])
             if i == 0 or c not in background_colors
         ]
         for i in np.unique(ss)
     }
     result = np.zeros(self.pattern.shape, dtype=np.uint8)
     result[:h, :w] = data[:h, :w]
     for key in colormap:
         if key == 0:
             continue
         value = colormap[key]
         if len(value) < 1:
             continue
         coords = np.where(self.pattern == key)
         result[coords] = value[0]
     yield Field(result)  # field.reconstruct(Field(result))
コード例 #12
0
ファイル: complex.py プロジェクト: latticetower/kaggle-arc
 def validate(self, iodata_list, k=3):
     scores = []
     for iodata in iodata_list:
         pred_scores = []
         for res in islice(self.predict(iodata.input_field), k):
             score = Field.score(res, iodata.output_field)
             pred_scores.append(score)
         scores.append(max(pred_scores))
     # for p in self.predictors[:3]:
     #     score = p.validate(iodata_list)
     #     scores.append(score)
     if len(scores) == 0:
         return 0.0
     return np.mean(scores)
コード例 #13
0
    def predict(self, field, return_binary=False):
        if isinstance(field, IOData):
            for v in self.predict(field.input_field):
                yield v
            return
        #repainter = Repaint(field.data)
        nrows, ncols = field.shape
        prediction_data = np.zeros(field.shape, dtype=np.uint8)
        #print(self.use_zeros)
        graph_data, inputs = GraphFeatureExtractor.prepare_graph_features_for_eval(
            field, self.use_zeros)
        if inputs.shape[0] < 1:
            #return field
            preds_binary = []
        else:
            preds_binary = self.xgb_binary.predict(inputs)

        feat = BTFeatureExtractor.make_features_v2(field)
        preds = self.xgb.predict(feat).reshape(nrows, ncols)
        preds = preds.astype(int)  #.tolist()
        #result = repainter(preds).tolist()
        prediction_data = preds
        if len(preds) > 0 and np.sum(preds) > 0:
            for comp, cbin in zip(graph_data, preds_binary):
                #color = int(new_col) if cbin > 0.5 else comp['color']
                #if cbin > 0.5:
                #    print("new color", new_col, "old_color", comp['color'])
                for i, j in comp['pos']:
                    if cbin > 0.5:
                        prediction_data[i, j] = preds[i, j]
                    else:
                        prediction_data[i, j] = comp['color']
        if return_binary:
            print(111)
            yield preds_binary, graph_data, Field(prediction_data)
        else:
            yield Field(prediction_data)
コード例 #14
0
 def predict(self, field):
     if isinstance(field, IOData):
         for v in self.predict(field.input_field):
             yield v
         return
     #repainter = Repaint(field.data)
     nrows, ncols = field.shape
     feat = BTFeatureExtractor.make_features_v3(field,
                                                all_square=self.all_square)
     preds = self.xgb.predict(feat).reshape(nrows, ncols)
     preds = preds.astype(int)  #.tolist()
     #preds = field.reconstruct(Field(preds))
     #preds = repainter(preds).tolist()
     preds = Field(preds)
     yield preds
コード例 #15
0
    def validate(self, iodata_list, k=3):
        if isinstance(iodata_list, IOData):
            ps = islice(self.predict(iodata_list.input_field), k)
            #print(list(ps))
            scores = [Field.score(p, iodata_list.output_field) for p in ps]
            if len(scores) < 1:
                return 0.0
            return max(scores)

        scores = []
        for iodata in iodata_list:
            score = self.validate(iodata)
            scores.append(score)
        if len(scores) < 1:
            return 0.0
        #print(scores)
        return np.mean(scores)
コード例 #16
0
ファイル: shapes.py プロジェクト: latticetower/kaggle-arc
def process_iodata_input(iodata, pattern, crop_func=crop_data):
    i = iodata.input_field
    o = iodata.output_field
    #bg = {c: 0 for c in o.data[np.where(pattern == 0)]}
    bg = dict(list(zip(*np.stack([o.data, pattern], 0).reshape(2, -1))))
    # current_id = 1
    cropped_data = crop_func(i.data)
    # #print(cropped_data, id(i.data))
    # for line in cropped_data:
    #     for x in line:
    #         if x in bg:
    #             continue
    #         bg[x] = current_id
    #         current_id += 1
    #return np.asarray([ [ bg[x] for x in line ] for line in cropped_data ])
    data = [[bg.get(x, 0) for x in line] for line in cropped_data]
    data = Field(data)
    return iodata.reconstruct(data).data
コード例 #17
0
    def predict(self, field):
        if isinstance(field, IOData):
            for v in self.predict(field.input_field):
                yield v
            return
        #while True:
        if self.best_Dict is None:
            return

        n, k = field.shape
        answer = np.zeros(field.shape, dtype=field.dtype)
        for i in range(n):
            for j in range(k):
                p1, p2 = get_p1_p2(i, j, n, k, self.best_v, self.best_Q1,
                                   self.best_Q2)
                color1 = field.data[i, j]
                rule = (p1, p2, color1)
                answer[i, j] = self.best_Dict.get(rule, color1)
        yield Field(answer)
コード例 #18
0
    def predict(self, field):
        if isinstance(field, IOData):
            for v in self.predict(field.input_field):
                yield v
            return
        #repainter = Repaint(field.data)
        prediction_data = np.zeros(field.shape)
        graph_data, inputs = GraphFeatureExtractor.prepare_graph_features_for_eval(
            field)
        preds_binary = self.xgb_binary.predict(inputs)
        preds_colors = self.xgb.predict(inputs)  #.tolist()
        #result = repainter(preds).tolist()
        for comp, cbin, new_col in zip(graph_data, preds_binary, preds_colors):
            color = int(new_col) if cbin > 0.5 else comp['color']
            #if cbin > 0.5:
            #    print("new color", new_col, "old_color", comp['color'])
            for i, j in comp['pos']:
                prediction_data[i, j] = color

        yield Field(prediction_data)
コード例 #19
0
    def get_features(iodata_list,
                     all_square=False,
                     features_maker=make_features):
        feat = []
        target = []

        for i, iodata in enumerate(iodata_list):
            if isinstance(iodata, IOData):
                input_field = iodata.input_field.data
                output_field = iodata.output_field.data
            else:
                input_field, output_field = iodata
                input_field = input_field.data
                output_field = output_field.data
            nrows, ncols = input_field.shape
            #output_field = output_field.data

            target_rows, target_cols = output_field.shape
            if output_field.shape == (
                    1, 1):  #and input_field.shape != output_field.shape:
                #print(input_field.shape)
                #print(input_field)
                output_field = increase2shape(output_field, input_field.shape)
                # i = np.asarray([[ np.sum(input_field == i) for i in range(10)]])
                # o = output_field
                # print(i.shape, o.shape)
                # feat.extend(i)
                # target.extend(o)
                # continue
            elif (target_rows != nrows) or (target_cols != ncols):
                print('Number of input rows:', nrows, 'cols:', ncols)
                print('Number of target rows:', target_rows, 'cols:',
                      target_cols)
                not_valid = 1
                return None, None, 1

            feat.extend(
                features_maker(Field(input_field), all_square=all_square))
            target.extend(np.array(output_field).reshape(-1, ))
        return np.array(feat), np.array(target), 0