예제 #1
0
    def _build_drawing(self):
        doc = Document()
        with doc.create(TikZ()) as tikz_pic:

            # create a node
            node_options = {
                'align': 'center',
                'inner sep': '20pt',
                'label': '{{270:{}}}'.format(self.module.name)
            }
            box = TikZNode(handle='module',
                           options=TikZOptions('draw', 'rounded corners',
                                               **node_options))

            tikz_pic.append(box)
            for port in self.module.ports:
                if port.direction == 'in':
                    tikz_pic.append(
                        TikZNode(text=port.name,
                                 options=TikZOptions(anchor='west'),
                                 at=TikZCoordinate(-1, 1)))
                    break

        doc.generate_tex('test')
        return doc
예제 #2
0
 def add_node(handle, text, x, y, options=node_opts):
     temp = TikZNode(text=format_text + text,
                     handle=handle,
                     options=options,
                     at=c(x, y))
     pic.append(temp)
     nodes.append(temp)
예제 #3
0
파일: utils.py 프로젝트: ncbi/JUDI
def paste_pdfs_base(inpaths, outpath, title='', flow='below'):
    print("--------", title, "-----------")
    if isinstance(inpaths, str): inpaths = [inpaths]
    print("--------", inpaths, "-----------")
    prefix = os.path.splitext(outpath)[0]
    infiles = [latex_tolerate(os.path.abspath(path)) for path in inpaths]
    doc = Document(documentclass='standalone')
    doc.preamble.append(NoEscape(r'\usetikzlibrary{chains}'))
    with doc.create(
            TikZ(options=NoEscape(
                f'start chain = going {flow}, node distance=0'))) as pic:
        for infile in infiles:
            pic.append(
                TikZNode(text=NoEscape(f'\includegraphics{{{infile}}}'),
                         options='on chain'))
        top = TikZNode(text=NoEscape('\\large\\bfseries ' +
                                     latex_tolerate(title)),
                       options='above',
                       at=TikZCoordinate(0, 0))
        top._position = '(current bounding box.north)'
        pic.append(top)
    doc.generate_pdf(NoEscape(prefix), clean_tex=False)
예제 #4
0
파일: utils.py 프로젝트: ncbi/JUDI
def pdf_matrix(big, small, title='', row=None, col=None):
    prefix = os.path.splitext(small['path'].tolist()[0])[0]
    if isinstance(row, str): row = [row]
    if isinstance(col, str): col = [col]
    df = big[row + col + ['path']].set_index(row + col)
    for cl in col:
        df = df.unstack(cl)
    df = df['path']
    df = df.applymap(os.path.abspath)
    df = df.applymap(latex_tolerate)
    doc = Document(documentclass='standalone')
    doc.preamble.append(NoEscape(r'\usetikzlibrary{matrix}'))
    with doc.create(TikZ()) as pic:
        mbody = """\\tikzset{mylabel/.style={color=blue, font=\\large \\bfseries \\ttfamily}}
               \\matrix (m) [matrix of nodes, row sep = 2ex] {
            """
        mbody += ' \\\\\n'.join([
            r' & '.join([
                f'\includegraphics{{{df.iloc[r,c]}}}'
                for c in range(df.shape[1])
            ]) for r in range(df.shape[0])
        ])
        mbody += '\\\\\n};\n'
        for r in range(df.shape[0]):
            for c in range(df.shape[1]):
                tmp = df.iloc[r:r + 1, c:c + 1]
                names = tmp.index.names + tmp.columns.names
                vals = tmp.index.values.tolist() + tmp.columns.values.tolist()
                label = ','.join([f'{k}~{v}' for k, v in zip(names, vals)])
                label = latex_tolerate(label)
                mbody += f'\\node[above, mylabel] at (m-{r+1}-{c+1}.north) {{{label}}};\n'
        pic.append(NoEscape(mbody))
        top = TikZNode(text=NoEscape(latex_tolerate(title)),
                       options=['above', 'mylabel'],
                       at=TikZCoordinate(0, 0))
        top._position = '(current bounding box.north)'
        pic.append(top)
    doc.generate_pdf(NoEscape(prefix), clean_tex=False)
예제 #5
0
    def dud(self):
        with self.q_doc.create(TikZ()) as pic:

            # options for our node
            node_kwargs = {
                'align': 'center',
                'minimum size': '100pt',
                'fill': 'black!20'
            }

            # create our test node
            box = TikZNode(text='My block',
                           handle='box',
                           options=TikZOptions('draw', 'rounded corners',
                                               **node_kwargs))

            # add to tikzpicture
            pic.append(box)

            # draw a few paths
            pic.append(
                TikZDraw([
                    TikZCoordinate(0, -6), 'rectangle',
                    TikZCoordinate(2, -8)
                ],
                         options=TikZOptions(fill='red')))

            # show use of anchor, relative coordinate
            pic.append(TikZDraw([box.west, '--', '++(-1,0)']))

            # demonstrate the use of the with syntax
            with pic.create(TikZDraw()) as path:

                # start at an anchor of the node
                path.append(box.east)

                # necessary here because 'in' is a python keyword
                path_options = {'in': 90, 'out': 0}
                path.append(
                    TikZUserPath('edge', TikZOptions('-latex',
                                                     **path_options)))

                path.append(TikZCoordinate(1, 0, relative=True))
예제 #6
0
def generate_organigram(schema: PLDSchema, locale: LocaleDictionary,
                        document: Document) -> Document:
    document.append(NewPage())
    with document.create(Figure()) as figure:
        figure: Figure
        with figure.create(Section(title=locale.organigram)) as section:
            section: Section
            section.append(Command("centering"))
            with section.create(Center()) as center:
                center: Center
                with center.create(TikZ()) as forest:
                    forest: TikZ

                    node_kwargs = {'align': 'center', 'minimum size': '20pt'}

                    # noinspection PyTypeChecker
                    top_box = TikZNode(text=schema.title,
                                       handle=f"project-box",
                                       options=TikZOptions(
                                           'draw', 'rounded corners',
                                           **node_kwargs))
                    forest.append(top_box)
                    last_box_handle = top_box.handle

                    for n_deliverable, deliverable in enumerate(
                            schema.deliverables, start=1):
                        # noinspection PyTypeChecker
                        box = TikZNode(
                            text=f"{n_deliverable}. {deliverable.name}",
                            handle=f"deliverable-box-{n_deliverable}",
                            options=TikZOptions(
                                'draw', 'rounded corners',
                                f'below = of {last_box_handle}'
                                if top_box.handle == last_box_handle else
                                f'right = of {last_box_handle}',
                                **node_kwargs))

                        last_box_handle = box.handle
                        # noinspection PyTypeChecker
                        path = TikZDraw(
                            TikZPathList(top_box.get_anchor_point("south"),
                                         "--", box.get_anchor_point("north")))
                        forest.append(box)
                        forest.append(path)
    document.append(VerticalSpace("2cm"))
    return document
예제 #7
0
                    options=TikZOptions({
                        "line width": "0.1pt",
                        "opacity": "0.1",
                        "fill": "black",
                    }),
                ))

    # labels
    for t in range(1, T):
        t0 = dt * t / T
        z0 = dz * -1.8 / C
        pic.append(
            TikZNode(
                handle=f"x{t}",
                at=TikZCoordinate(t0, z0),
                options={
                    #"fill": "white",
                },
                text=f"$x_{t}$",
            ))

    # dots
    for t, z in grid:
        partition = partitions[t]
        in_partition = (z // S) == partition
        color = 'white'  #if in_partition else "black"
        size = dsize  #if in_partition else ssize
        pic.append(
            TikZDraw(
                [
                    TikZCoordinate(dt * t / T, dz * z / C),
                    'circle',
예제 #8
0
    doc = Document()

    # add our sample drawings
    with doc.create(TikZ()) as pic:

        # options for our node
        node_kwargs = {
            'align': 'center',
            'minimum size': '100pt',
            'fill': 'black!20'
        }

        # create our test node
        box = TikZNode(text='My block',
                       handle='box',
                       at=TikZCoordinate(0, 0),
                       options=TikZOptions('draw', 'rounded corners',
                                           **node_kwargs))

        # add to tikzpicture
        pic.append(box)

        # draw a few paths
        pic.append(
            TikZDraw(
                [TikZCoordinate(0, -6), 'rectangle',
                 TikZCoordinate(2, -8)],
                options=TikZOptions(fill='red')))

        # show use of anchor, relative coordinate
        pic.append(TikZDraw([box.west, '--', '++(-1,0)']))
예제 #9
0
파일: test_args.py 프로젝트: JelteF/PyLaTeX
def test_tikz():
    # PGFPlots
    t = TikZ(data=None)
    repr(t)

    a = Axis(data=None, options=None)
    repr(a)

    p = Plot(name=None, func=None, coordinates=None, error_bar=None,
             options=None)
    repr(p)

    opt = TikZOptions(None)
    repr(opt)

    scope = TikZScope(data=None)
    repr(scope)

    c = TikZCoordinate.from_str("(0,0)")
    c = TikZCoordinate(x=0, y=0, relative=False)
    d = c + (0, 1)
    e = c - (0, 1)
    f = (0, 1) + c
    c.distance_to(d)
    repr(c)
    repr(d)
    repr(e)
    repr(f)

    bool(c == (1, 1))
    bool(c == TikZCoordinate(1, 1))
    bool(TikZCoordinate(1, 1, relative=True) == (1, 1))
    bool(TikZCoordinate(1, 1, relative=False) == (1, 1))
    bool(TikZCoordinate(1, 1, relative=True) == TikZCoordinate(1,
                                                               1,
                                                               relative=False))

    # test expected to fail
    try:
        g = TikZCoordinate(0, 1, relative=True) +\
            TikZCoordinate(1, 0, relative=False)
        repr(g)
        raise Exception
    except ValueError:
        pass

    a = TikZNodeAnchor(node_handle=None, anchor_name=None)
    repr(a)

    n = TikZNode(handle=None, options=None, at=None, text=None)
    repr(n)

    p = n.get_anchor_point("north")
    repr(p)

    p = n.get_anchor_point('_180')
    repr(p)

    p = n.west
    repr(p)

    up = TikZUserPath(path_type="edge", options=TikZOptions('bend right'))
    repr(up)

    pl = TikZPathList('(0, 1)', '--', '(2, 0)')
    pl.append((0.5, 0))
    repr(pl)

    # generate a failure, illegal start
    try:
        pl = TikZPathList('--', '(0, 1)')
        raise Exception
    except TypeError:
        pass

    # fail with illegal path type
    try:
        pl = TikZPathList('(0, 1)', 'illegal', '(0, 2)')
        raise Exception
    except ValueError:
        pass

    # fail with path after path
    try:
        pl = TikZPathList('(0, 1)', '--', '--')
        raise Exception
    except ValueError:
        pass

    # other type of failure: illegal identifier after path
    try:
        pl = TikZPathList('(0, 1)', '--', 'illegal')
        raise Exception
    except (ValueError, TypeError):
        pass

    pt = TikZPath(path=None, options=TikZOptions("->"))
    pt.append(TikZCoordinate(0, 1, relative=True))
    repr(pt)

    pt = TikZPath(path=[n.west, 'edge', TikZCoordinate(0, 1, relative=True)])
    repr(pt)

    pt = TikZPath(path=pl, options=None)
    repr(pt)

    dr = TikZDraw(path=None, options=None)
    repr(dr)
예제 #10
0
def test_tikz():
    # PGFPlots
    t = TikZ(data=None)
    repr(t)

    a = Axis(data=None, options=None)
    repr(a)

    p = Plot(name=None,
             func=None,
             coordinates=None,
             error_bar=None,
             options=None)
    repr(p)

    opt = TikZOptions(None)
    repr(opt)

    scope = TikZScope(data=None)
    repr(scope)

    c = TikZCoordinate.from_str("(0,0)")
    c = TikZCoordinate(x=0, y=0, relative=False)
    d = c + (0, 1)
    e = c - (0, 1)
    f = (0, 1) + c
    c.distance_to(d)
    repr(c)
    repr(d)
    repr(e)
    repr(f)

    bool(c == (1, 1))
    bool(c == TikZCoordinate(1, 1))
    bool(TikZCoordinate(1, 1, relative=True) == (1, 1))
    bool(TikZCoordinate(1, 1, relative=False) == (1, 1))
    bool(
        TikZCoordinate(1, 1, relative=True) == TikZCoordinate(
            1, 1, relative=False))

    # test expected to fail
    try:
        g = TikZCoordinate(0, 1, relative=True) +\
            TikZCoordinate(1, 0, relative=False)
        repr(g)
        raise Exception
    except ValueError:
        pass

    a = TikZNodeAnchor(node_handle=None, anchor_name=None)
    repr(a)

    n = TikZNode(handle=None, options=None, at=None, text=None)
    repr(n)

    p = n.get_anchor_point("north")
    repr(p)

    p = n.get_anchor_point('_180')
    repr(p)

    p = n.west
    repr(p)

    up = TikZUserPath(path_type="edge", options=TikZOptions('bend right'))
    repr(up)

    pl = TikZPathList('(0, 1)', '--', '(2, 0)')
    pl.append((0.5, 0))
    repr(pl)

    # generate a failure, illegal start
    try:
        pl = TikZPathList('--', '(0, 1)')
        raise Exception
    except TypeError:
        pass

    # fail with illegal path type
    try:
        pl = TikZPathList('(0, 1)', 'illegal', '(0, 2)')
        raise Exception
    except ValueError:
        pass

    # fail with path after path
    try:
        pl = TikZPathList('(0, 1)', '--', '--')
        raise Exception
    except ValueError:
        pass

    # other type of failure: illegal identifier after path
    try:
        pl = TikZPathList('(0, 1)', '--', 'illegal')
        raise Exception
    except (ValueError, TypeError):
        pass

    pt = TikZPath(path=None, options=TikZOptions("->"))
    pt.append(TikZCoordinate(0, 1, relative=True))
    repr(pt)

    pt = TikZPath(path=[n.west, 'edge', TikZCoordinate(0, 1, relative=True)])
    repr(pt)

    pt = TikZPath(path=pl, options=None)
    repr(pt)

    dr = TikZDraw(path=None, options=None)
    repr(dr)
예제 #11
0
    def draw_calendar(self, month: int):
        scope_kwargs = {
            'shift': f'{{({self.x:.4f}, {self.y:.4f})}}',
            'rotate': f'{self.rot:.4f}'
        }
        scope_options = TikZOptions(**scope_kwargs)
        scope = TikZScope(options=scope_options)

        rotation = {'rotate': f'{self.rot:.4f}'}

        if self.debug:
            debug_options = TikZOptions(**rotation)
            scope.append(
                TikZNode(text=r'\color{red} x',
                         at=TikZCoordinate(0.0, 0.0),
                         options=debug_options))

        ## First, the title
        title_xy = (0.0, 2.5 * self.DY)
        title_coords = TikZCoordinate(*title_xy)
        title_options = TikZOptions(**rotation)
        title_text = f'{{\\bfseries\\color{{blue!50}} {self.MONTH_NAMES[month]}}} {self.year}'
        title_node = TikZNode(text=title_text,
                              at=title_coords,
                              options=title_options)

        scope.append(title_node)

        ## Now the days
        default_options = TikZOptions(align='right', anchor='base', **rotation)
        special_options = TikZOptions(draw='none',
                                      radius='0.2',
                                      anchor='base',
                                      fill='blue!20')
        magical_options = TikZOptions(draw='blue!30',
                                      radius='0.2',
                                      anchor='base',
                                      fill='none')

        day = dt.date(self.year, month, 1)
        col = (day.weekday() + 1) % 7
        row = 0 if col != 0 else -1

        x0 = -3 * self.DX
        y0 = self.DY

        while day.month == month:
            col = (day.weekday() + 1) % 7
            if col == 0:
                color = 'blue!50'
                row += 1
            else:
                color = 'black'

            x = x0 + float(self.DX * col)
            y = y0 - float(self.DY * row)

            if day in self.dates:
                if col == 0:
                    scope.append(
                        TikZDraw([f'({x:.5f}, {y+0.125:.5f})', 'circle'],
                                 options=magical_options))
                else:
                    scope.append(
                        TikZDraw([f'({x:.5f}, {y+0.125:.5f})', 'circle'],
                                 options=special_options))

            xy = TikZCoordinate(x, y)

            node = TikZNode(text=f'\\color{{{color}}} {day.day}',
                            at=xy,
                            options=default_options)

            scope.append(node)

            day = day + self.DAY_DELTA

        self.pic.append(scope)
예제 #12
0
                    TikZCoordinate(t0, z0),
                    'rectangle',
                    TikZCoordinate(t1, z1),
                ],
                options=TikZOptions({
                    "line width": "0.2pt",
                }),
            ))

    # labels
    pic.append(
        TikZNode(
            handle=f"b",
            at=TikZCoordinate(0, dz * -1.5 / C),
            options={
                #"fill": "white",
                "inner sep": "0",
            },
            text="$\mathbf{b}$",
        ))
    for t in range(1, T):
        t0 = dt * t / T
        z0 = dz * -1.8 / C
        pic.append(
            TikZNode(
                handle=f"x{t}",
                at=TikZCoordinate(t0, z0),
                options={
                    #"fill": "white",
                },
                text=f"$x_{t}$",