Exemple #1
0
    def draw_watcher_card(self, metadata, card, svg, svg_group):
        id = metadata['id']
        attrs = card

        # Validate attributes
        self.validate_attrs(attrs)
        name = attrs['name']

        # Build list of template ids and then load from svg file.
        svg_ids = []
        svg_ids.append('watcher-title')
        svg_ids.extend(['icon-star-{0}'.format(n) for n in [1,2,3]])
        svg_ids.append('watcher-image')
        svg_ids.append('watcher-flavor')
        svg_ids.extend(['attack-{0}'.format(n) for n in [2,3]])
        svg_ids.extend(['pursuit-{0}'.format(n) for n in [1,2]])
        svg_ids.extend(['detect-{0}'.format(d) for d in ['yes', 'no']])
        svg_ids.extend(['target-{0}'.format(t) for t in ['next', 'skip', 'reverse']])
        svg.load_ids(WovenWatcherCards.CARD_TEMPLATE, svg_ids)

        # Draw artifact title.
        title = svg.add_loaded_element(svg_group, 'watcher-title')
        SVG.set_text(title, "Watcher")

        svg.add_loaded_element(svg_group, 'watcher-image')
        svg.add_loaded_element(svg_group, 'attack-{0}'.format(attrs['attack']))
        svg.add_loaded_element(svg_group, 'detect-{0}'.format(attrs['detect']))
        svg.add_loaded_element(svg_group, 'pursuit-{0}'.format(attrs['pursuit']))
        svg.add_loaded_element(svg_group, 'target-{0}'.format(attrs['dir']))

        flavor = svg.add_loaded_element(svg_group, 'watcher-flavor')
        SVG.set_text(flavor, "Detect Range = 3")
        
        self.draw_vp(attrs['vp'], svg, svg_group)
 def __init__(self, width=600, height=600):
     self.width = width
     self.height = height
     self.svg = SVG(viewBox=f"0 0 {width} {height}",
                    style="stroke: black; fill: none;")
     self.background("white")
     self.tcount = 0
Exemple #3
0
    def draw_sentry_card(self, metadata, card, svg, svg_group):
        id = metadata['id']
        attrs = card

        # Validate attributes
        self.validate_attrs(attrs)

        # Build list of template ids and then load from svg file.
        svg_ids = []
        svg_ids.append('sentry-title')
        svg_ids.extend(['icon-star-{0}'.format(n) for n in [1,2,3]])
        svg_ids.append('sentry-image')
        svg_ids.append('sentry-flavor')
        svg_ids.extend(['sentry-attack-{0}'.format(d) for d in [1,2]])
        svg_ids.extend(['sentry-detect-{0}'.format(d) for d in ['yes', 'no']])
        svg_ids.extend(['respawn-{0}'.format(d) for d in ['yes', 'no']])
        svg.load_ids(WovenSentryCards.CARD_TEMPLATE, svg_ids)

        # Draw artifact title.
        title = svg.add_loaded_element(svg_group, 'sentry-title')
        SVG.set_text(title, "Sentry")

        svg.add_loaded_element(svg_group, 'sentry-image')
        svg.add_loaded_element(svg_group, 'sentry-attack-{0}'.format(attrs['attack']))
        svg.add_loaded_element(svg_group, 'sentry-detect-{0}'.format(attrs['detect']))
        svg.add_loaded_element(svg_group, 'respawn-{0}'.format(attrs['respawn']))

        flavor = svg.add_loaded_element(svg_group, 'sentry-flavor')
        SVG.set_text(flavor, "Detect Range = 1")

        self.draw_vp(attrs['vp'], svg, svg_group)
Exemple #4
0
    def __init__(self, name, colour):
        self.longName = name
        self.displayedName = name
        self.colour = colour
        self.devices = list()

        self.svgFile = SVG()
        self.svgRoot = self.svgFile.getSvg()
Exemple #5
0
 def draw_flavor(self, attrs, attr_name, svg, svg_group):
     if not attr_name in attrs:
         return
     text = attrs[attr_name]
     if text == '':
         return
     flavor = svg.add_loaded_element(svg_group, 'artifact-flavor')
     SVG.set_text(flavor, text)
Exemple #6
0
 def draw_description(self, attrs, attr_name, svg, svg_group):
     if not attr_name in attrs:
         return
     text = attrs[attr_name]
     if text == '':
         return
     desc = svg.add_loaded_element(svg_group, 'artifact-description')
     SVG.set_text(desc, text)
Exemple #7
0
def test_simple_replace_shapes_with_paths(shape: str, expected_path: str):
  actual = (SVG.fromstring(svg_string(shape))
            .shapes_to_paths(inplace=True)
            .tostring())
  expected_result = (SVG.fromstring(svg_string(f'<path d="{expected_path}"/>'))
                     .tostring())
  print(f'A: {actual}')
  print(f'E: {expected_result}')
  assert actual == expected_result
Exemple #8
0
 def draw_bonus(self, attrs, attr_name, svg, svg_group):
     if not attr_name in attrs:
         return
     text = attrs[attr_name]
     if text == '':
         return
     svg.add_loaded_element(svg_group, 'artifact-bonus-border')
     bonus = svg.add_loaded_element(svg_group, 'artifact-bonus')
     SVG.set_text(bonus, text)
Exemple #9
0
def test_path_move(path: str, move, expected_result: str):
  actual = (SVG.fromstring(svg_string(path))
            .shapes_to_paths())
  for shape in actual.shapes():
    shape.move(move.x, move.y, inplace=True)
  actual = actual.tostring()
  expected_result = (SVG.fromstring(svg_string(expected_result))
                     .tostring())
  print(f'A: {actual}')
  print(f'E: {expected_result}')
  assert actual == expected_result
Exemple #10
0
def main():
    '''
    Fonction principale
    '''
    drawing = SVG("dessin.svg", 1000, 1000)
    drawing.header()

    lines = generate_random_lines()
    lines = get_symmetric(lines)
    for line in lines:
        drawing.draw_line(line)

    drawing.footer()
    drawing.write_file()
Exemple #11
0
def Document(filename):
    tree = ElementTree.parse(filename)
    root = tree.getroot()
    if root.tag != namespace + 'svg':
        text = 'File "%s" does not seem to be a valid SVG file' % filename
        raise TypeError(text)
    return SVG(root)
def load_model(model_config):
    """
    Loads the model specified by the model config.
    """
    model_name = model_config['architecture'].lower()

    if model_name == 'vrnn':
        from vrnn import VRNN
        return VRNN(model_config)
    elif model_name == 'srnn':
        from srnn import SRNN
        return SRNN(model_config)
    # elif model_name == 'dvbf':
    #     from dvbf import DVBF
    #     return DVBF(model_config)
    elif model_name == 'svg':
        from svg import SVG
        return SVG(model_config)
    elif model_name in ['conv', 'convolutional']:
        from convolutional import ConvolutionalDLVM
        return ConvolutionalDLVM(model_config)
    elif model_name in ['fc', 'fully_connected']:
        from fully_connected import FullyConnectedDLVM
        return FullyConnectedDLVM(model_config)
    else:
        raise Exception('Model architecture not found.')
Exemple #13
0
    def __init__(self, width, height):
        self.width = width
        self.height = height

        w = self.width * 100 + 200
        h = self.height * 100 + 200
        self.svg = SVG(width=w, height=h)
        self.canvas = self.svg.translate(100, 100)
Exemple #14
0
def test_iter(shape, expected_cmds):
  svg_path = (SVG.fromstring(svg_string(shape))
              .shapes_to_paths()
              .shapes()[0])
  actual_cmds = [t for t in svg_path]
  print(f'A: {actual_cmds}')
  print(f'E: {expected_cmds}')
  assert actual_cmds == expected_cmds
Exemple #15
0
    def draw_artifact_card(self, metadata, card, svg, svg_group):
        id = metadata['id']
        name = card[0]
        attrs = card[1]

        # Validate attributes
        self.validate_attrs(name, attrs)

        # Build list of template ids and then load from svg file.
        svg_ids = []
        svg_ids.append('artifact-title')
        svg_ids.extend(['icon-star-{0}'.format(n) for n in [1,2,3]])
        svg_ids.append('artifact-description')
        svg_ids.append('artifact-extra-action')
        svg_ids.append('artifact-bonus')
        svg_ids.append('artifact-bonus-border')
        svg_ids.append('artifact-flavor')
        #svg_ids.append('separator')
        svg_ids.extend(['op-{0}'.format(op) for op in valid_ops])
        svg.load_ids(WovenArtifactCards.CARD_TEMPLATE, svg_ids)

        # Add Op masters (hidden, used for cloning).
        g_masters = SVG.group('masters')
        g_masters.set_style("display:none")
        SVG.add_node(svg_group, g_masters)
        for e in [
                'op-tapestry', 'op-eye', 'op-mmove', 'op-thread', 'op-action',
                ]:
            svg.add_loaded_element(g_masters, e)

        # Draw artifact title.
        title = svg.add_loaded_element(svg_group, 'artifact-title')
        SVG.set_text(title, name)

        self.draw_description(attrs, 'description', svg, svg_group)
        svg.add_loaded_element(svg_group, 'artifact-extra-action')
        self.draw_bonus(attrs, 'bonus', svg, svg_group)
        self.draw_flavor(attrs, 'flavor', svg, svg_group)
        
        #svg.add_loaded_element(svg_group, 'separator')

        # Draw alternate action.
        #svg.add_loaded_element(svg_group, 'op-{0}'.format(attrs['op']))

        self.draw_vp(attrs['vp'], svg, svg_group)
Exemple #16
0
    def load_svg(self, path):
        with open(path) as file:
            svg = SVG(file.read())
            self.svg = svg
            self.geojson = GeoJSON(self.svg)
            self.layer_output = list(self.svg.get_layers())
            self.update_result()

        self.ui.load_preview(path)
        layers = self.svg.get_layers()
        self.ui.load_layers(layers)
Exemple #17
0
def solving():
    alls = all_blocks()
    board = Board.from_2d(([[1, 0, 1], [1, 1, 1], [1, 1, 0], [1, 1, 1],
                            [0, 0, 1]]))
    blocks = alls.get_blocklist().sublist(["YV", "RZ", "RZ", "YT", "RL"])
    board.print()
    problem = Problem(blocks, board)

    game = PickleUtil.read("data/game4player4block3depthuniq")
    game.set_names(list(map(lambda n: "[3段] " + n, animals["fish"])))
    html = SVG.game_tate(game)
    html.save("data/game4.html")
Exemple #18
0
    def pre_card(self):
        if self._called_pre_card:
            raise Exception("pre_card() should only be called once per card")

        if self.curr_filename == '':
            self.curr_file += 1
            self.curr_filename = 'out{0:02d}'.format(self.curr_file)
            self.__create_svg_file()
            self.curr_card += 1

        layer = self.svg.add_inkscape_layer(
            'card{0:02d}'.format(self.curr_card),
            "Card {0}".format(self.curr_card))

        cut_line = SVG.rect_round(0, 0, 0, self.card_width, self.card_height,
                                  3)
        style = Style()
        style.set('fill', "#ffffff")
        style.set('stroke', "none")
        cut_line.set_style(style)
        SVG.add_node(layer, cut_line)

        self._called_pre_card = True
        return (self.svg, layer)
Exemple #19
0
class Section:
    def __init__(self, name, colour):
        self.longName = name
        self.displayedName = name
        self.colour = colour
        self.devices = list()

        self.svgFile = SVG()
        self.svgRoot = self.svgFile.getSvg()

    def __repr__(self):
        return self.longName

    def addDevice(self, device):
        device.numberInSection = len(self.devices)
        self.devices.append(device)

    def getDevice(self, number):
        if number >= len(self.devices) or number < 0:
            return None
        else:
            return self.devices[number]

    def sortDevices(self):
        self.devices = sorted(self.devices, key=lambda devices: devices.realCoordinates[0])
        self.assignNumbersInSection()

    def assignNumbersInSection(self):
        for i in range(0, len(self.devices)):
            self.devices[i].numberInSection = i
        
    def numberOfDevices(self):
        return len(self.devices)

    def setDisplayedName(self, name):
        self.displayedName = name
Exemple #20
0
    def draw_spell_card(self, metadata, card, svg, svg_group):
        id = metadata['id']
        name = card[0]
        attrs = card[1]
        desc = card[2]

        # Validate attributes
        if attrs['category'] != 'blank':
            self.validate_attrs(name, attrs)
        pattern_id = attrs['pattern']
        pattern = self.card_patterns[pattern_id]['pattern']
        if attrs['category'] != 'blank':
            self.record_spell_info(name, pattern, attrs, desc)

        if attrs['category'] != 'blank' and pattern_id != 'blank':
            pe_tag = self.pattern_key(pattern) + '-' + attrs['element']
            if pe_tag in self.pattern_elements:
                raise Exception(
                    'Pattern for "{0:s}" already used for "{1:s}"'.format(
                        name, self.pattern_elements[pe_tag]))
            self.pattern_elements[pe_tag] = name

        # Validate desc
        self.validate_desc(name, desc)

        # Verify pattern matches spell element
        element = attrs['element']
        pelem_data = self.card_patterns[pattern_id]['elements']
        pelems = []
        if pelem_data == "none":
            pelems.append("none")
        else:
            pelems = [elem_map[p] for p in pelem_data]
        if not element in pelems:
            raise Exception(
                "{0:s}: Spell pattern does not match element {1:s}".format(
                    name, element))

        # Build list of template ids and then load from svg file.
        svg_ids = []
        svg_ids.extend(['element-{0}'.format(elem_map[e]) for e in elem_map])
        svg_ids.append('spell-title')
        svg_ids.append('spell-pattern-border')
        svg_ids.append('spell-description')
        svg_ids.append('spell-id')
        svg_ids.extend(['icon-star-{0}'.format(n) for n in [1, 2, 3]])
        svg_ids.append('icon-vp')
        svg_ids.append('spell-flavor')
        svg_ids.append('separator')
        svg_ids.extend(['op-{0}'.format(op) for op in valid_ops])
        svg.load_ids(WovenSpellCards.CARD_TEMPLATE, svg_ids)

        # Add Element and Op masters (hidden, used for cloning).
        g_masters = SVG.group('masters')
        g_masters.set_style("display:none")
        SVG.add_node(svg_group, g_masters)
        for e in [
                'op-tapestry',
                'op-eye',
                'op-mmove',
                'op-thread',
                'op-action',
                'element-air',
                'element-earth',
                'element-fire',
                'element-water',
        ]:
            svg.add_loaded_element(g_masters, e)

        if attrs['category'] != 'blank':
            # Draw spell title.
            title = svg.add_loaded_element(svg_group, 'spell-title')
            SVG.set_text(title, name)

            # Draw elements in title bar
            elemaster = '#element-{0}'.format(element)
            SVG.add_node(svg_group, SVG.clone(0, elemaster, 4, 4))
            SVG.add_node(svg_group, SVG.clone(0, elemaster, 54, 4))

            # Draw spell id.
            id_text = svg.add_loaded_element(svg_group, 'spell-id')
            SVG.set_text(
                id_text, "{0:d}/{1:d}".format(spell_card_revision,
                                              attrs['id']))

            # Draw flavor text (if present).
            if 'flavor' in attrs:
                flavor_text = svg.add_loaded_element(svg_group, 'spell-flavor')
                SVG.set_text(flavor_text, attrs['flavor'])

            svg.add_loaded_element(svg_group, 'separator')

            # Draw alternate action.
            svg.add_loaded_element(svg_group, 'op-{0}'.format(attrs['op']))

        # Add spell pattern.
        self.draw_pattern(pattern_id, pattern, element, svg_group)
        svg.add_loaded_element(svg_group, 'spell-pattern-border')

        if attrs['category'] != 'blank':
            self.draw_description(attrs['id'], desc, svg, svg_group)

        self.draw_vp(attrs['vp'], svg, svg_group)
Exemple #21
0
    def draw_pattern(self, id, pattern_raw, element, svg_group):
        pattern = [x.split() for x in pattern_raw]
        pheight = len(pattern)
        if pheight == 0:
            raise Exception("Missing pattern for {0}".format(id))
        if pheight > 3:
            raise Exception("Tall pattern for {0}".format(id))
        pwidth = len(pattern[0])

        # Max pattern size that fits on the card.
        max_width = 7
        max_height = 3

        # Center of pattern area.
        pcenter_x = self.width / 2
        pcenter_y = 22.4

        # Size and spacing for each box in pattern.
        box_size = 5.5
        box_spacing = 7

        # Upper left corner of pattern area
        px0 = pcenter_x - (((max_width - 1) * box_spacing) + box_size) / 2
        py0 = pcenter_y - (((max_height - 1) * box_spacing) + box_size) / 2

        # Calc offsets to center the patterns that are less than max size.
        if pwidth % 2 == 0:
            px0 += box_spacing / 2
            max_width = 6
        else:
            max_width = 7
        if pheight % 2 == 0:
            py0 += box_spacing / 2
            max_height = 2
        else:
            max_height = 3

        dot_x0 = px0 + (box_size / 2)
        dot_y0 = py0 + (box_size / 2)

        # The x,y ranges for this pattern (to center on the card)
        x_begin = int((max_width - pwidth) / 2)
        x_end = x_begin + pwidth
        y_begin = int((max_height - pheight) / 2)
        y_end = y_begin + pheight

        for iy in range(0, max_height):
            for ix in range(0, max_width):
                if ix >= x_begin and ix < x_end and iy >= y_begin and iy < y_end:
                    x = ix * box_spacing
                    y = iy * box_spacing

                    col = ix - x_begin
                    row = iy - y_begin
                    cell = pattern[row][col]
                    if cell == '@':
                        elemaster = '#element-{0}'.format(element)
                        eleclone = SVG.clone(0, elemaster, px0 + x, py0 + y)
                        SVG.add_node(svg_group, eleclone)
                    elif cell == 'X':
                        box = SVG.rect(0, px0 + x, py0 + y, box_size, box_size)

                        style_box = Style()
                        style_box.set_fill("none")
                        style_box.set_stroke("#000000", 0.5)
                        style_box.set('stroke-linecap', "round")
                        style_box.set('stroke-miterlimit', 2)
                        box.set_style(style_box)

                        SVG.add_node(svg_group, box)
                    elif cell == '.':
                        dot = SVG.circle(0, dot_x0 + x, dot_y0 + y, 0.8)

                        style_dot = Style()
                        style_dot.set_fill("#c0c0c0")
                        style_dot.set_stroke("none")
                        dot.set_style(style_dot)

                        SVG.add_node(svg_group, dot)
                    else:
                        raise Exception(
                            "Unrecognized pattern symbol: {0}".format(cell))
Exemple #22
0
class Grid:
    def __init__(self, width, height):
        self.width = width
        self.height = height

        w = self.width * 100 + 200
        h = self.height * 100 + 200
        self.svg = SVG(width=w, height=h)
        self.canvas = self.svg.translate(100, 100)

    def hline(self, x, y, width, **attrs):
        self.line(x, y, x + width, y, **attrs)

    def vline(self, x, y, height, **attrs):
        self.line(x, y, x, y + height, **attrs)

    def line(self, x1, y1, x2, y2, **attrs):
        self.canvas.line(x1=x1 * 100, y1=y1 * 100, x2=x2 * 100, y2=y2 * 100, **attrs)

    def rect(self, x, y, width, height, **attrs):
        self.canvas.rect(x=x * 100, y=y * 100, width=width * 100, height=height * 100, **attrs)

    def circle(self, cx, cy, r, **attrs):
        cx, cy = cx * 100, cy * 100
        self.canvas.circle(cx=cx, cy=cy, r=r, **attrs)

    def draw_grid(self, **attrs):
        # draw vertical lines
        for x in range(self.width + 1):
            self.vline(x, 0, self.height, **attrs)

        # draw horizontal lines
        for y in range(self.height + 1):
            self.hline(0, y, self.width, **attrs)

    def draw_corners(self, **attrs):
        attrs.setdefault("r", 3)

        for x in range(self.width + 1):
            for y in range(self.height + 1):
                self.circle(x, y, **attrs)

    def text(self, x, y, text, **attrs):
        defaults = dict(
            font_size=48,
            text_anchor="middle",
            style="dominant-baseline: central;",
            font_family="Courier",
            font_weight="bold",
        )
        attrs = dict(defaults, **attrs)

        xoffset = attrs.pop("xoffset", 50)
        yoffset = attrs.pop("yoffset", 65)

        x, y = x * 100 + xoffset, y * 100 + yoffset
        self.canvas.text(x=x, y=y, **attrs)(text)

    def draw_numbers(self, data, **attrs):
        """Draw numbers in each cell.
        """
        for (row, col), value in data.items():
            self.text(col, row, value, **attrs)
Exemple #23
0
		# outlines
		outlines.objects.append(Path("cut",
			[m(self.material_width,self.material_width)]+
			self.make_tongues(my_width, True, True)+
			self.make_tongues(my_width, False, True)
		,closed=True))
		
		return (outlines,Group(transformation=(self.material_width,self.material_width)))

if __name__=="__main__":
	casing=Casing(100,60,30)
	
	sides=[
		("top",casing.top),
		("side13",casing.side13),
		("side24",casing.side24)
		]
	
	
	for name,func in sides:
		svg=SVG((100,60),"casing")
		
		outlines,subview=func()
		outlines.objects.append(subview)
		svg.children.append(outlines)
		
		# test rectangle
		#subview.objects.append(Rectangle(style_cut, (0,0), (10,10)))
	
		with open("cut_{}.svg".format(name),"w") as f:
			f.write(svg.get_svg())
Exemple #24
0
observation_space = env.observation_space.shape[0]

# pred_length = 13+ was ok. Too far, because of 'to point' controller (U is proportional to error)
predictor = Predictor(obs_length=10, pred_length=14)

# h_dim 100 was ok, batch normalisation does not improve
net = StochasticNet(action_space, observation_space, h_dim=100, on_bn=0)

# 1000 samples was ok
replay_buffer = SimpleReplayPool(1000, observation_space, action_space)

svg = SVG(epoch=500,
          min_buffer_size=256,
          pi_lr=1e-3,
          q_lr=1e-4,
          scale_reward=2.5,
          batch_size=64,
          tau=0.01,
          sess=tf.Session(),
          env=env,
          max_path_length=max_steps_per_episode,
          predictor=predictor,
          net=net,
          action_space=action_space,
          observation_space=observation_space,
          replay_buffer=replay_buffer)

# save_every - does not work - keep higher than the number of epoch
# steps_to_solve - defines for how many steps in succession without sampling from LSTM a run is considered solved
# resample - switch on sampling from the predictor
svg.train(plot_every=5, save_every=10000, resample=True, steps_to_solve=10)
Exemple #25
0
 def __create_svg_file(self):
     self.svg = SVG([self.card_width, self.card_height])
Exemple #26
0
class SVGCardGen(object):
    OPTIONS = {
        'out': {
            'type': 'string',
            'default': "out",
            'desc': "Output directory"
        },
        'png': {
            'type': 'bool',
            'default': False,
            'desc': "Generate PNG output files"
        },
        'per-page': {
            'type': 'int',
            'default': 1,
            'desc': "Set # of cards per page"
        },
    }

    def __init__(self, card_handler, options):
        self.card_handler = card_handler

        self.out_dir = options['out']
        self.svg_out_dir = os.path.join(self.out_dir, 'svg')
        self.png_out_dir = os.path.join(self.out_dir, 'png')
        self.gen_png = options['png']

        self.curr_filename = ''
        self.curr_file = 0  # Current file index

        self.cards_per_page = 1
        self.curr_card = 0  # Current card index on page

        self.card_width = options['width']
        self.card_height = options['height']

    def __create_svg_file(self):
        self.svg = SVG([self.card_width, self.card_height])

    def __write_svg_file(self, name):
        if not os.path.isdir(self.svg_out_dir):
            os.makedirs(self.svg_out_dir)
        out = os.path.join(self.svg_out_dir, '%s.svg' % name)
        self.svg.write(out)

        if self.gen_png:
            self.__gen_png(name)

    def __start_card_gen(self):
        self.curr_file = -1
        self.curr_card = -1
        self.curr_filename = ''

    def __end_card_gen(self):
        if self.curr_filename != '':
            print('Closing', self.curr_filename)
            self.__write_svg_file(self.curr_filename)

    # Generate PNG file.
    def __gen_png(self, name):
        if not os.path.isdir(self.png_out_dir):
            os.makedirs(self.png_out_dir)
        print("Exporting {0:s}.png".format(name))
        Inkscape.export_png(
            os.path.abspath(
                os.path.join(self.svg_out_dir, '{0:s}.svg'.format(name))),
            os.path.abspath(
                os.path.join(self.png_out_dir, '{0:s}.png'.format(name))), 300)

    #
    # PUBLIC METHODS
    #

    def generate_cards(self):
        self.__start_card_gen()

        for card_data in self.card_handler.card_data():
            metadata = {
                'file': self.curr_file,
                'id': self.curr_card,
            }
            self._called_pre_card = False
            self._called_post_card = False
            self.card_handler.process_card_data(metadata, card_data)
            if not (self._called_pre_card and self._called_post_card):
                raise Exception(
                    "card handler should call both pre_card() and post_card()")

        # Fill out last sheet with blank cards.
        while self.curr_filename != '':
            self.pre_card()
            self.post_card()

        self.__end_card_gen()

    # Creates a new layer and returns the SVG node where the card should be added.
    def pre_card(self):
        if self._called_pre_card:
            raise Exception("pre_card() should only be called once per card")

        if self.curr_filename == '':
            self.curr_file += 1
            self.curr_filename = 'out{0:02d}'.format(self.curr_file)
            self.__create_svg_file()
            self.curr_card += 1

        layer = self.svg.add_inkscape_layer(
            'card{0:02d}'.format(self.curr_card),
            "Card {0}".format(self.curr_card))

        cut_line = SVG.rect_round(0, 0, 0, self.card_width, self.card_height,
                                  3)
        style = Style()
        style.set('fill', "#ffffff")
        style.set('stroke', "none")
        cut_line.set_style(style)
        SVG.add_node(layer, cut_line)

        self._called_pre_card = True
        return (self.svg, layer)

    def post_card(self):
        if not self._called_pre_card:
            raise Exception("pre_card() should be called before post_card()")
        if self._called_post_card:
            raise Exception("post_card() should only be called once per card")

        if self.curr_card == (self.cards_per_page - 1):
            self.__write_svg_file(self.curr_filename)
            self.curr_filename = ''
            self.curr_card = -1
        self._called_post_card = True
class Sketch:
    def __init__(self, width=600, height=600):
        self.width = width
        self.height = height
        self.svg = SVG(viewBox=f"0 0 {width} {height}",
                       style="stroke: black; fill: none;")
        self.background("white")
        self.tcount = 0

    def background(self, color):
        self.svg.rect(x=0,
                      y=0,
                      width=self.width,
                      height=self.height,
                      fill=color,
                      stroke="none")

    def circle(self, x, y, d):
        self.svg.circle(cx=x, cy=y, r=d / 2)

    def line(self, x1, y1, x2, y2, **kwargs):
        self.svg.line(x1=x1, y1=y1, x2=x2, y2=y2, **kwargs)

    def rect(self, x, y, w, h):
        self.svg.rect(x=x, y=y, width=w, height=h)

    def path(self, d):
        self.svg.path(d=d, stroke="black")

    def show(self, node, margin=0, scale=False, size=260):
        if margin or scale:
            s = (self.width - 2 * margin) / size if scale else 1
            g = Node(
                "g",
                transform=f"translate({margin}, {margin}) scale({s}, {s})")
            g.add_node(node)
            self.svg.add_node(g)
        else:
            self.svg.add_node(node)

    def transform(self, node, dx, dy, sx, sy):
        g = Node("g", transform=f"translate({dx}, {dy}) scale({sx}, {sy})")
        g.add_node(node)
        return g

    def thumbnail(self, shape):
        size = 260 / 4
        x = self.tcount * (size + 20) + 20
        y = 10
        self.show(self.transform(shape, x, y, 0.25, 0.25))
        self.tcount += 1

    def clear():
        self.tcount = 0

    def tostring(self):
        return self.svg.tostring()

    def render(self, code):
        g = self.get_globals()
        exec(code, g, g)
        return self.tostring()

    def show_grid(self):
        size = 100
        for y in range(0, self.height + 1, size):
            self.line(0, y, self.width, y, stroke="#ccc")

        for x in range(0, self.width + 1, size):
            self.line(x, 0, x, self.height, stroke="#ccc")

    def get_globals(self):
        return {
            "circle": self.circle,
            "rect": self.rect,
            "line": self.line,
            "path": self.path,
            "width": self.width,
            "height": self.height,
            "show_grid": self.show_grid,
            "Node": Node,
            "show": self.show,
            "thumbnail": self.thumbnail,
            **g.exports
        }
Exemple #28
0
'''
Fichier permettant d'effectuer différents tests au fur et à mesure du
développement
'''

from svg import SVG
from math import pi
from geometry import random_line, random_point
from geometry import Point

dessin = SVG("dessin.svg", 1000, 1000)


def test_line():
    '''
    Test affichant une ligne aléatoire sur le dessin svg
    '''
    ligne = random_line()
    dessin.draw_line(ligne)


def test_multiple_random():
    '''
    Test affichant 7 lignes aléatoires sur le dessin svg
    '''
    for _ in range(7):
        ligne = random_line((500, 1000), (0, 1000))
        dessin.draw_line(ligne)


def test_symmetrical_point():
Exemple #29
0
def save_graph(histogram: Histogram, bin_color: colors.Color):
    scale = 1
    w = h = 1024 / 2 * scale
    stroke_width = 2

    left_margin = 0.075 * w
    right_margin = left_margin
    top_margin = 0.4 * h
    bottom_margin = 0.1 * h

    x_min = left_margin
    x_max = w - right_margin
    y_min = top_margin
    y_max = h - bottom_margin

    time_min = 0
    time_max = histogram.bin_width * len(histogram.counts)
    time_to_x = lambda t: (t - time_min) / (time_max - time_min) * (x_max - x_min) + x_min

    percentage_min = 0
    percentage_max = 0.3
    percentage_to_y = lambda p: (1 - (p - percentage_min) / (percentage_max - percentage_min)) * \
                                (y_max - y_min) + y_min

    # draw background
    elements: List[Element] = []
    margin = 0
    elements.append(Polygon(
        vertices=[
            Point(margin, margin),
            Point(w - margin, margin),
            Point(w - margin, h - margin),
            Point(margin, h - margin),
        ],
        fill=colors.white,
        stroke=None,
    ))

    # draw bins
    percentages = [count / histogram.total_count for count in histogram.counts]
    for (i, percentage) in enumerate(percentages):
        t1 = i * histogram.bin_width
        t2 = (i + 1) * histogram.bin_width
        x1 = time_to_x(t1) - 0.5
        x2 = time_to_x(t2) + 0.5
        y1 = percentage_to_y(0)
        y2 = percentage_to_y(percentage)

        elements.append(Polygon(
            vertices=[
                Point(x1, y1),
                Point(x2, y1),
                Point(x2, y2),
                Point(x1, y2),
            ],
            fill=bin_color,
            stroke=None,
        ))

    # draw x axis
    elements.append(Polyline(stroke=Stroke(colors.black, stroke_width), points=[
        Point(x_min - 0.5, y_max),
        Point(x_max + 0.5, y_max),
    ]))

    # draw x axis ticks
    for i in range(len(histogram.counts) + 1):
        t = i * histogram.bin_width
        x = time_to_x(t)
        elements.append(Polyline(
            stroke=Stroke(colors.black, 1),
            points=[
                Point(x, y_max),
                Point(x, y_max - 5),
            ],
        ))

    # TODO: draw x axis labels

    # draw median line
    x_median = time_to_x(histogram.median)
    elements.append(Polyline(stroke=Stroke(colors.black, 1.25), points=[
        Point(x_median, y_min),
        Point(x_median, y_max),
    ]))

    # TODO: draw median text
    # TODO: title
    # TODO: subtitle

    svg = SVG(width=w, height=h, elements=elements)
    path = os.path.join(GRAPHS_DIR, histogram.filename)
    svg.write_xml(path)
Exemple #30
0
  ]
)
def test_path_move(path: str, move, expected_result: str):
  actual = (SVG.fromstring(svg_string(path))
            .shapes_to_paths())
  for shape in actual.shapes():
    shape.move(move.x, move.y, inplace=True)
  actual = actual.tostring()
  expected_result = (SVG.fromstring(svg_string(expected_result))
                     .tostring())
  print(f'A: {actual}')
  print(f'E: {expected_result}')
  assert actual == expected_result

@pytest.mark.parametrize(
  "actual, expected_result",
  [
    (SVG.parse('clip-rect.svg'), SVG.parse('clip-rect-clipped.svg')),
    (SVG.parse('clip-ellipse.svg'), SVG.parse('clip-ellipse-clipped.svg')),
  ]
)
def test_apply_clip_path(actual, expected_result):
  actual.apply_clip_paths(inplace=True)
  drop_whitespace(actual)
  drop_whitespace(expected_result)
  print(f'A: {actual.tostring().decode("utf-8")}')
  print(f'E: {expected_result.tostring().decode("utf-8")}')
  assert actual.tostring() == expected_result.tostring()


Exemple #31
0
def test_parse_common_attrib(shape, expected_attrib):
  svg = SVG.fromstring(shape)
  field_values = dataclasses.asdict(svg.shapes()[0])
  for attrib, expected_value in expected_attrib.items():
    assert field_values[attrib] == expected_value
Exemple #32
0
 def draw_description(self, id, raw_desc, svg, svg_group):
     text = svg.add_loaded_element(svg_group, 'spell-description')
     SVG.set_text(text, self.expand_desc(raw_desc))