Esempio n. 1
0
def test_graphics():
    f = Figure(data=None, position=None)

    f.add_image(filename="", width=r"0.8\textwidth", placement=r"\centering")

    f.add_caption(caption="")

    # Subfigure
    s = SubFigure(data=None, position=None, width=r"0.45\linewidth", seperate_paragraph=False)

    s.add_image(filename="", width="r\linewidth", placement=None)

    s.add_caption(caption="")

    # Matplotlib
    plot = MatplotlibFigure(data=None, position=None)

    x = [0, 1, 2, 3, 4, 5, 6]
    y = [15, 2, 7, 1, 5, 6, 9]

    pyplot.plot(x, y)

    plot.add_plot(width=r"0.8\textwidth", placement=r"\centering")
    plot.add_caption(caption="I am a caption.")

    # Quantities
    Quantity(quantity=1 * pq.kg)
    Quantity(quantity=1 * pq.kg, format_cb=lambda x: str(int(x)))
Esempio n. 2
0
def test_graphics():
    f = Figure(data=None, position=None)

    f.add_image(filename='', width=r'0.8\textwidth', placement=r'\centering')

    f.add_caption(caption='')
    repr(f)

    # Subfigure
    s = SubFigure(data=None, position=None, width=r'0.45\linewidth')

    s.add_image(filename='', width='r\linewidth',
                placement=None)

    s.add_caption(caption='')
    repr(s)

    # Matplotlib
    plot = Figure(data=None, position=None)

    x = [0, 1, 2, 3, 4, 5, 6]
    y = [15, 2, 7, 1, 5, 6, 9]

    pyplot.plot(x, y)

    plot.add_plot(width=r'0.8\textwidth', placement=r'\centering')
    plot.add_caption(caption='I am a caption.')
    repr(plot)
Esempio n. 3
0
    def add_figure(self,file=None,caption=None,width='240px'):
        """ 添加图形

        :param str file: 图形文件路径
        :param str caption: 图形标题
        :param str width: 图形宽度
        :return: 无返回值
        """
        graph = Figure(position='h!')
        graph.add_image(file, width=width)
        if caption is not None:
            graph.add_caption(caption)
        self.doc.append(graph)
Esempio n. 4
0
def test_graphics():
    f = Figure(data=None, position=None)

    f.add_image(filename="", width=r"0.8\textwidth", placement=r"\centering")

    f.add_caption(caption="")

    # Subfigure
    s = SubFigure(data=None, position=None, width=r"0.45\linewidth", separate_paragraph=False)

    s.add_image(filename="", width="r\linewidth", placement=None)

    s.add_caption(caption="")

    # Matplotlib
    plot = Figure(data=None, position=None)

    x = [0, 1, 2, 3, 4, 5, 6]
    y = [15, 2, 7, 1, 5, 6, 9]

    pyplot.plot(x, y)

    plot.add_plot(width=r"0.8\textwidth", placement=r"\centering")
    plot.add_caption(caption="I am a caption.")
Esempio n. 5
0
    def pile_report(self, pile, pile2, F, factor=1.25):
        """添加桩基长度计算内容"""

        self.soil = pile.soil
        llist = pl.get_l(self.soil, pile.d, F, factor, pile.h1, pile.rho,
                         pile.t, pile.k2, pile2.type, pile2.completion)
        ra_1, ra_2 = pl.pile_l(llist, self.soil, pile.d, F, pile.h1, pile.rho,
                               pile.t, pile.k2, pile2.type, pile2.completion)

        if ra_1.max() > ra_2.max():
            ptype = '摩擦桩'
            ra = ra_1.max()
        else:
            ptype = '端承桩'
            ra = ra_2.max()

        t1 = f'''桩基直径:$d={pile.d:.2f}\,m$\n
        桩基周长:$u={pile.u:.2f}\,m$\n
        桩基截面积:$A_p={pile.pd:.2f}\,m^2$\n
        桩基密度:$\gamma={pile.rho:.1f}\,kN/m^3$\n
        容许承载力随深度的修正系数:$k_2={pile.k2:.1f}$\n
        各土层加权平均重度:$\gamma_2={self.soil.rho:.1f}\,kN/m^3$\n
        清底系数:$m_0={pile.m0:.1f}$
        '''

        t2 = '根据规范5.3.3可得,摩擦桩单桩承载力为'
        m1 = ['[R_a]', '=\\frac{1}{2}u\\sum_{i=1}^nq_{ik}l_i+A_pq_r']
        t3 = '根据规范5.3.4可得,端承桩单桩承载力为'
        m2 = [
            '[R_a]=', 'c_1A_pf_{rk}', '+u\\sum_{i=1}^mc_{2i}h_if_{rki}',
            '+\\frac{1}{2}\\xi_su\sum_{i=1}^nl_iq_{ik}'
        ]
        t4 = '考虑桩身自重与置换土重,桩基承载力为'
        m3 = ['R_a', '=[R_a]-G_p+G_s']
        t5 = '代入不同长度桩长,可得摩擦桩与端承桩承载力如下图所示'
        t6 = '不同桩长具体承载力如下表所示'
        t7 = f'由上述分析可知,当桩长为{max(llist)}m时,{ptype}承载力为{ra:.0f}kN,安全系数为{ra/F:.2f},桩基承载力可满足规范要求。'

        with self.doc.create(Section('地基基本情况')):
            with self.doc.create(LongTabu("p{4cm}XXXXX")) as soil_table:
                header_row1 = self.soil.prop.columns.to_list()[:-1]
                soil_table.add_hline()
                soil_table.add_row(header_row1, mapper=[bold])
                soil_table.add_hline()
                for i in self.soil.prop.index:
                    soil_table.add_row(self.soil.prop.iloc[i].to_list()[:-1])
                soil_table.add_hline()

        with self.doc.create(Section('桩基及其他参数取值')):
            self.doc.append(NoEscape(t1))

        with self.doc.create(Section('桩长计算')):
            self.doc.append(t2)
            self.doc.append(Math(data=m1, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t3)
            self.doc.append(Math(data=m2, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t4)
            self.doc.append(Math(data=m3, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t5)
            with self.doc.create(Figure(position='htbp')) as plot:
                plot.add_plot(width=NoEscape(r'1\textwidth'), dpi=300)
            self.doc.append(NoEscape('\n'))
            self.doc.append(t6)
            with self.doc.create(LongTable('p{1.5cm}|ll|ll')) as pll:
                pll.add_hline()
                pll.add_row(['桩长', '摩擦桩承载力', '安全系数', '端承桩承载力', '安全系数'])
                pll.add_hline()
                for i, j in enumerate(llist):
                    pll.add_row([
                        j, f'{ra_1[i]:.0f}', f'{ra_1[i]/F:.2f}',
                        f'{ra_2[i]:.0f}', f'{ra_2[i]/F:.2f}'
                    ])
                pll.add_hline()
            self.doc.append(t7)
Esempio n. 6
0
               hlines=True,
               cells=None,
               escape=False)

# MultiColumn/MultiRow.
t.add_row((MultiColumn(size=2, align='|c|', data='MultiColumn'), ))

t.add_row((MultiRow(size=2, width='*', data='MultiRow'), ))

# Command
c = Command(command='documentclass',
            arguments=None,
            options=None,
            packages=None)
# Figure
f = Figure(data=None, position=None)

f.add_image(filename='', width=r'0.8\textwidth', placement=r'\centering')

f.add_caption(caption='')

# Subfigure
s = SubFigure(data=None,
              position=None,
              width=r'0.45\linewidth',
              seperate_paragraph=False)

s.add_image(filename='', width='r\linewidth', placement=None)

s.add_caption(caption='')
Esempio n. 7
0
    def create(self):
        try:
            self.status['text'] = 'Загрузка, подождите'
            self.root.update()
            # Настройки отступов, языка
            geometry_options = {
                "tmargin": "2cm",
                "lmargin": "3cm",
                "rmargin": "1.5cm",
                "bmargin": "2cm"
            }
            doc = Document(geometry_options=geometry_options)
            doc.packages.add(
                Package('grffile',
                        options=['encoding', 'filenameencoding=utf8']))
            doc.packages.add(Package('babel', options=['russian']))

            # Вставляем логотип МИРЭА
            image_filename = os.path.join(os.path.dirname(__file__),
                                          'логотип.png')
            with doc.create(Figure(position='h!')) as logo:
                logo.add_image(image_filename, width='80px')

            # Обложка
            doc.change_length(r"\TPHorizModule", "1mm")
            doc.change_length(r"\TPVertModule", "1mm")
            with doc.create(MiniPage(width=r"\textwidth")) as page:
                # Центральная часть обложки
                with page.create(TextBlock(180, 0, 0)):
                    page.append(Command('centering'))
                    page.append('МИНОБРНАУКИ РОССИИ\n')
                    page.append(
                        'Федеральное государственное бюджетное образовательное учреждение высшего образования\n'
                    )
                    page.append(
                        MediumText(
                            bold(
                                '«МИРЭА - Российский Технологический Университет»\n'
                            )))
                    page.append(LargeText(bold('РТУ МИРЭА\n')))
                    page.append(LineBreak())
                    page.append(
                        MediumText(
                            bold(
                                'Институт комплексной безопасности и специального приборостроения\n'
                            )))
                    page.append(LineBreak())
                    page.append(
                        'Кафедра КБ-8 «Информационное Противоборство»\n')
                    page.append(LineBreak())
                    page.append(LineBreak())
                    page.append(LineBreak())
                    page.append(LargeText('Отчёт\n'))
                    page.append(f'{str(self.entry1.get())}\n')

                # Правая часть обложки
                with page.create(TextBlock(80, 88, 120)):
                    if self.your_var.get() == 0:
                        page.append('Выполнил:\n')
                        page.append(
                            f'Студент {str(self.entry2.get())} курса\n')
                    else:
                        page.append('Выполнила:\n')
                        page.append(
                            f'Студентка {str(self.entry2.get())} курса\n')
                    page.append(f'Группа {str(self.entry3.get())}\n')
                    page.append(f'Шифр {str(self.entry4.get())}\n')
                    page.append(f'{str(self.entry5.get())}\n')
                    page.append(LineBreak())
                    page.append(LineBreak())
                    if self.var.get() == 0:
                        page.append('Проверил:\n')
                    else:
                        page.append('Проверила:\n')
                    page.append(f'{str(self.entry6.get())}\n')

            # Нижний колонтитул
            header = PageStyle("header")
            with header.create(Foot("C")):
                header.append(f'Москва, {time.now().timetuple().tm_year}\n')
            doc.preamble.append(header)
            doc.change_document_style("header")

            doc.generate_pdf("title", clean_tex=False)
            self.status['text'] = 'Готово!'

        except FileNotFoundError as e:
            self.status['text'] = str(e)
Esempio n. 8
0
def generate_latex_document(trackers: List[Tracker],
                            sequences: List[Sequence],
                            results,
                            storage: Storage,
                            build=False,
                            multipart=True):

    order_marks = {1: "first", 2: "second", 3: "third"}

    def format_cell(value, order):
        cell = format_value(value)
        if order in order_marks:
            cell = Command(order_marks[order], cell)
        return cell

    logger = logging.getLogger("vot")

    table_header, table_data, table_order = extract_measures_table(
        trackers, results)
    plots = extract_plots(trackers, results)

    doc = Document(page_numbers=True)

    doc.preamble.append(Package('pgf'))
    doc.preamble.append(Package('xcolor'))
    doc.preamble.append(Package('fullpage'))

    doc.preamble.append(NoEscape(read_resource("commands.tex")))

    doc.preamble.append(
        UnsafeCommand('newcommand',
                      r'\first',
                      options=1,
                      extra_arguments=r'{\color{red} #1 }'))
    doc.preamble.append(
        UnsafeCommand('newcommand',
                      r'\second',
                      options=1,
                      extra_arguments=r'{\color{green} #1 }'))
    doc.preamble.append(
        UnsafeCommand('newcommand',
                      r'\third',
                      options=1,
                      extra_arguments=r'{\color{blue} #1 }'))

    if multipart:
        container = Chunk()
        generate_symbols(container, trackers)
        with storage.write("symbols.tex") as out:
            container.dump(out)
        doc.preamble.append(Command("input", "symbols.tex"))
    else:
        generate_symbols(doc.preamble, trackers)

    doc.preamble.append(Command('title', 'VOT report'))
    doc.preamble.append(
        Command('author', 'Toolkit version ' + toolkit_version()))
    doc.preamble.append(Command('date', datetime.datetime.now().isoformat()))
    doc.append(NoEscape(r'\maketitle'))

    if len(table_header[2]) == 0:
        logger.debug("No measures found, skipping table")
    else:

        # Generate data table
        with doc.create(LongTable("l " *
                                  (len(table_header[2]) + 1))) as data_table:
            data_table.add_hline()
            data_table.add_row([" "] + [
                MultiColumn(c[1], data=c[0].identifier)
                for c in merge_repeats(table_header[0])
            ])
            data_table.add_hline()
            data_table.add_row([" "] + [
                MultiColumn(c[1], data=c[0].title)
                for c in merge_repeats(table_header[1])
            ])
            data_table.add_hline()
            data_table.add_row(
                ["Tracker"] +
                [" " + c.abbreviation + " " for c in table_header[2]])
            data_table.add_hline()
            data_table.end_table_header()
            data_table.add_hline()

            for tracker, data in table_data.items():
                data_table.add_row([
                    UnsafeCommand("Tracker",
                                  [tracker.reference, TRACKER_GROUP])
                ] + [
                    format_cell(x,
                                order[tracker] if not order is None else None)
                    for x, order in zip(data, table_order)
                ])

    for experiment, experiment_plots in plots.items():
        if len(experiment_plots) == 0:
            continue

        doc.append(Section("Experiment " + experiment.identifier))

        for title, plot in experiment_plots:

            with doc.create(Figure(position='htbp')) as container:
                if multipart:
                    plot_name = plot.identifier + ".pdf"
                    with storage.write(plot_name, binary=True) as out:
                        plot.save(out, "PDF")
                    container.add_image(plot_name)
                else:
                    container.append(insert_figure(plot))
                container.add_caption(title)

    if build:
        temp = tempfile.mktemp()
        logger.debug("Generating to tempourary output %s", temp)
        doc.generate_pdf(temp, clean_tex=True)
        storage.copy(temp + ".pdf", "report.pdf")
    else:
        with storage.write("report.tex") as out:
            doc.dump(out)
Esempio n. 9
0
def test_graphics():
    f = Figure(data=None, position=None)

    f.add_image(filename='', width=r'0.8\textwidth', placement=r'\centering')

    f.add_caption(caption='')
    repr(f)

    # Subfigure
    s = SubFigure(data=None, position=None, width=r'0.45\linewidth')

    s.add_image(filename='', width='r\linewidth', placement=None)

    s.add_caption(caption='')
    repr(s)

    # Matplotlib
    plot = Figure(data=None, position=None)

    x = [0, 1, 2, 3, 4, 5, 6]
    y = [15, 2, 7, 1, 5, 6, 9]

    pyplot.plot(x, y)

    plot.add_plot(width=r'0.8\textwidth', placement=r'\centering')
    plot.add_caption(caption='I am a caption.')
    repr(plot)
Esempio n. 10
0
def details():
    if __name__ == '__main__':


        image_filename = os.path.join(os.path.dirname(__file__), 'kitten.jpg')
        logo_file = os.path.join(os.path.dirname(__file__),'sample-logo.png')

        geometry_options = {"tmargin": "1cm", "lmargin": "3cm"}
        doc = Document(geometry_options=geometry_options)
        header = PageStyle("header")
        with header.create(Head("R")):
            header.append(simple_page_number())
        with header.create(Foot("C")):
            header.append("Center Footer")
        first_page = PageStyle("firstpage")
        with first_page.create(Head("L")) as header_left:
        with header_left.create(MiniPage(width=NoEscape(r"0.49\textwidth"),pos='c')) as logo_wrapper

        with doc.create(MiniPage(align='l')):
            doc.append(LargeText(bold("INVESTMENT PROPERTY - BUY & HOLD")))
            doc.append(LineBreak())
            doc.append(MediumText(bold(" ")))
        logo_wrapper.append(StandAloneGraphic(image_options="width=120px",
                                              filename=logo_file))
        with doc.create(Section('Home Adress')):
            doc.append('Some regular text and some')
            doc.append(italic('italic text. '))
            doc.append('\nAlso some crazy characters: $&#{}')
            with doc.create(Subsection('Math that is incorrect')):
                doc.append(Math(data=['2*3', '=', 9]))

            with doc.create(Subsection('Table of something')):
                with doc.create(Tabular('rc|cl')) as table:
                    table.add_hline()
                    table.add_row((1, 2, 3, 4))
                    table.add_hline(1, 2)
                    table.add_empty_row()
                    table.add_row((4, 5, 6, 7))

        a = np.array([[100, 10, 20]]).T
        M = np.matrix([[2, 3, 4],
                       [0, 0, 1],
                       [0, 0, 2]])

        with doc.create(Section('The fancy stuff')):
            with doc.create(Subsection('Correct matrix equations')):
                doc.append(Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)]))

            with doc.create(Subsection('Alignat math environment')):
                with doc.create(Alignat(numbering=False, escape=False)) as agn:
                    agn.append(r'\frac{a}{b} &= 0 \\')
                    agn.extend([Matrix(M), Matrix(a), '&=', Matrix(M * a)])

            with doc.create(Subsection('Beautiful graphs')):
                with doc.create(TikZ()):
                    plot_options = 'height=4cm, width=6cm, grid=major'
                    with doc.create(Axis(options=plot_options)) as plot:
                        plot.append(Plot(name='model', func='-x^5 - 242'))

                        coordinates = [
                            (-4.77778, 2027.60977),
                            (-3.55556, 347.84069),
                            (-2.33333, 22.58953),
                            (-1.11111, -493.50066),
                            (0.11111, 46.66082),
                            (1.33333, -205.56286),
                            (2.55556, -341.40638),
                            (3.77778, -1169.24780),
                            (5.00000, -3269.56775),
                        ]

                        plot.append(Plot(name='estimate', coordinates=coordinates))

            with doc.create(Subsection('Cute kitten pictures')):
                with doc.create(Figure(position='h!')) as kitten_pic:
                    kitten_pic.add_image(image_filename, width='120px')
                    kitten_pic.add_caption('Look it\'s on its back')

        doc.generate_pdf('full', clean_tex=False)
Esempio n. 11
0
                        spacing = '2.5in'

                    doc.append(
                        NoEscape(r'\question ' +
                                 NoEscape(question['question'])))
                    doc.append(Command('vspace', spacing))
                    answerKey = np.append(answerKey, [-1])
            else:
                break

        doc.append(Command('end', 'questions'))

        big_code = pyqrcode.create(np.array_str(answerKey), mode='binary')
        big_code.png('code.png')

        with doc.create(Figure(position='b!')) as code:
            code.add_image('code.png', width='50px')

        doc.generate_pdf(clean_tex=False)
        doc.generate_tex()

    elif currentMode == 'Grade':

        filename = askopenfilename()
        image = cv2.imread(filename, cv2.IMREAD_GRAYSCALE)
        scanner = zbar.Scanner()
        results = scanner.scan(image)
        for result in results:
            print(result.type, result.data, result.quality, result.position)

        answerKey = list(str(results[0].data.decode("utf-8"))[1:-1].split("."))
Esempio n. 12
0
def create_report(system, curves, grid, filename):
    lines = system.lines
    trafos = system.trafos
    buses = system.buses

    geometry_options = {
        "tmargin": "1cm",
        "lmargin": "1cm",
        "rmargin": "1cm",
        "bmargin": "1cm",
        "includeheadfoot": True
    }
    doc = Document(page_numbers=True, geometry_options=geometry_options)
    doc.preamble.append(Command('usepackage', 'cmbright'))
    doc.preamble.append(Command('usepackage', 'tikz'))
    doc.preamble.append(Command('usepackage', 'amsmath'))
    doc.preamble.append(Command('usepackage', 'graphicx'))
    now = datetime.datetime.now()
    doc.append('Report auto-generated by ASPy at '
               '{:02d}/{:02d}/{:02d} {:02d}:{:02d}:{:02d}'.format(
                   now.day, now.month, now.year, now.hour, now.minute,
                   now.second))
    wye_comm = UnsafeCommand(
        'newcommand',
        '\\wye',
        extra_arguments=
        r'\mathbin{\text{\begin{tikzpicture}[x=1pt, y=1pt, scale=2]'
        r'\draw '
        r'(-0.9, 0) -- (0.9, 0) '
        r'(-0.6, -0.5) -- (0.6, -0.5) '
        r'(-0.3, -1) -- (0.3, -1) '
        r'(0, 0) -- ++(0, 1.5) -- ++(1.2, 0) coordinate (tmp)'
        r'-- +(0, -2) '
        r'(tmp) +(45:2) -- (tmp) -- +(135:2) ;'
        r'\end{tikzpicture}}}')
    why_comm = UnsafeCommand(
        'newcommand',
        '\\why',
        extra_arguments=
        r'\mathbin{\text{\begin{tikzpicture}[x=1pt, y=1pt, scale=2]'
        r'\draw '
        r'(1.2, 1.5) coordinate (tmp)'
        r'-- +(0, -2) '
        r'(tmp) +(45:2) -- (tmp) -- +(135:2) ;'
        r'\end{tikzpicture}}}')
    doc.append(wye_comm)
    doc.append(why_comm)
    doc.add_color(name="lightgray", model="gray", description="0.80")
    with doc.create(Section('Buses')):
        with doc.create(Subsection('Power-Flow Solution')):
            with doc.create(LongTable('c|ccccccc')) as tbl:
                tbl.add_hline()
                tbl.add_row(
                    ('Bus', NoEscape('$|V|$ (pu)'),
                     NoEscape('$\\delta$ (deg)'), NoEscape('$P_G$ (MW)'),
                     NoEscape('$Q_G$ (Mvar)'), NoEscape('$P_L$ (MW)'),
                     NoEscape('$Q_L$ (Mvar)'), NoEscape('$Z_L$ (pu)')))
                tbl.add_hline()
                tbl.end_table_header()
                tbl.add_hline()
                tbl.add_row((MultiColumn(8,
                                         align='r',
                                         data='Continued on Next Page'), ))
                tbl.add_hline()
                tbl.end_table_footer()
                tbl.add_hline()
                tbl.end_table_last_footer()

                for i, b in enumerate(buses):
                    if i % 2 == 0:
                        color = 'lightgray'
                    else:
                        color = None
                    tbl.add_row(
                        (b.bus_id + 1, NoEscape('{:.04f}'.format(b.v)),
                         NoEscape('${:.02f}$'.format(b.delta * 180 / np.pi)),
                         NoEscape('{:.02f}'.format(b.pg * 100)),
                         NoEscape('{:.02f}'.format(b.qg * 100)),
                         NoEscape('{:.02f}'.format(b.pl * 100)),
                         NoEscape('{:.02f}'.format(b.ql * 100)), check_inf(
                             b.Z)),
                        color=color)
        with doc.create(Subsection('Fault Calculations')):
            with doc.create(LongTable('c|cccccccccc')) as tbl:
                tbl.add_hline()
                tbl.add_row((MultiRow(2, data='Bus'),
                             MultiColumn(2, align='c', data=NoEscape('TPG')),
                             MultiColumn(2, align='c', data=NoEscape('SLG')),
                             MultiColumn(4, align='c', data=NoEscape('DLG')),
                             MultiColumn(2, align='c', data=NoEscape('LL'))))
                tbl.add_hline(2, 11)
                tbl.add_row(
                    ('', NoEscape('$I_A$ (pu)'), NoEscape('$\\delta_A$ (deg)'),
                     NoEscape('$I_A$ (pu)'), NoEscape('$\\delta_A$ (deg)'),
                     NoEscape('$I_B$ (pu)'), NoEscape('$\\delta_B$ (deg)'),
                     NoEscape('$I_C$ (pu)'), NoEscape('$\\delta_C$ (deg)'),
                     NoEscape('$I_B$ (pu)'), NoEscape('$\\delta_B$ (deg)')))
                tbl.add_hline()
                tbl.end_table_header()
                tbl.add_hline()
                tbl.add_row((MultiColumn(11,
                                         align='r',
                                         data='Continued on Next Page'), ))
                tbl.add_hline()
                tbl.end_table_footer()
                tbl.add_hline()
                tbl.end_table_last_footer()

                for i, b in enumerate(buses):
                    if i % 2 == 0:
                        color = 'lightgray'
                    else:
                        color = None
                    tbl.add_row((b.bus_id + 1, check_inf(np.abs(b.iTPG)),
                                 NoEscape('${:.02f}$'.format(
                                     np.angle(b.iTPG) * 180 / np.pi)),
                                 check_inf(np.abs(b.iSLG)),
                                 NoEscape('${:.02f}$'.format(
                                     np.angle(b.iSLG) * 180 / np.pi)),
                                 check_inf(np.abs(b.iDLGb)),
                                 NoEscape('${:.02f}$'.format(
                                     np.angle(b.iDLGb) * 180 / np.pi)),
                                 check_inf(np.abs(b.iDLGc)),
                                 NoEscape('${:.02f}$'.format(
                                     np.angle(b.iDLGc) * 180 / np.pi)),
                                 check_inf(np.abs(b.iLL)),
                                 NoEscape('${:.02f}$'.format(
                                     np.angle(b.iLL) * 180 / np.pi))),
                                color=color)
    with doc.create(Section('Lines')):
        with doc.create(LongTable('c|cccccccc')) as tbl:
            tbl.add_hline()
            tbl.add_row((MultiRow(2, data='Line'),
                         MultiColumn(3, align='c', data='Parametrization'),
                         MultiColumn(2, align='c', data='Loss'),
                         MultiColumn(3, align='c', data='Flow')))
            tbl.add_hline(2, 9)
            tbl.add_row(
                ('', NoEscape('$R$ (\\%pu)'), NoEscape('$X_L$ (\\%pu)'),
                 NoEscape('$B_C$ (\\%pu)'), NoEscape('$P_{loss}$ (MW)'),
                 NoEscape('$Q_{loss}$ (Mvar)'), NoEscape('$P$ (MW)'),
                 NoEscape('$Q$ (Mvar)'), NoEscape('$I/I_{max}$ (\\%)')))
            tbl.add_hline()
            tbl.end_table_header()
            tbl.add_hline()
            tbl.add_row((MultiColumn(9,
                                     align='r',
                                     data='Continued on Next Page'), ))
            tbl.add_hline()
            tbl.end_table_footer()
            tbl.add_hline()
            tbl.end_table_last_footer()

            for i, lt in enumerate(lines):
                if i % 2 == 0:
                    color = 'lightgray'
                else:
                    color = None
                tbl.add_row((NoEscape('{} -- {}'.format(
                    lt.orig.bus_id + 1, lt.dest.bus_id + 1)),
                             NoEscape('{:.04f}'.format(lt.Zpu.real * 100)),
                             NoEscape('{:.04f}'.format(lt.Zpu.imag * 100)),
                             NoEscape('{:.04f}'.format(lt.Ypu.imag * 100)),
                             NoEscape('{:.02f}'.format(lt.Sper.real * 100)),
                             NoEscape('{:.02f}'.format(lt.Sper.imag * 100)),
                             NoEscape('{:.02f}'.format(lt.S2.real * 100)),
                             NoEscape('{:.02f}'.format(lt.S2.imag * 100)),
                             NoEscape('{:.02f}'.format(
                                 np.abs(lt.Ia) / lt.imax * 100))),
                            color=color)
    with doc.create(Section('Trafos')):
        with doc.create(LongTable('c|cccccccc')) as tbl:
            tbl.add_hline()
            tbl.add_row((MultiRow(2, data='Trafo'),
                         MultiColumn(3, align='c', data='Parametrization'),
                         MultiColumn(2, align='c', data='Loss'),
                         MultiColumn(3, align='c', data='Flow')))
            tbl.add_hline(2, 9)
            tbl.add_row(
                ('', NoEscape('$x^+$ (\\%pu)'), NoEscape('$x^0$ (\\%pu)'),
                 'Configuration', NoEscape('$P_{loss}$ (MW)'),
                 NoEscape('$Q_{loss}$ (Mvar)'), NoEscape('$P$ (MW)'),
                 NoEscape('$Q$ (Mvar)'), NoEscape('$S/S_N$ (\\%)')))
            tbl.add_hline()
            tbl.end_table_header()
            tbl.add_hline()
            tbl.add_row((MultiColumn(9,
                                     align='r',
                                     data='Continued on Next Page'), ))
            tbl.add_hline()
            tbl.end_table_footer()
            tbl.add_hline()
            tbl.end_table_last_footer()

            for i, tr in enumerate(trafos):
                if i % 2 == 0:
                    color = 'lightgray'
                else:
                    color = None
                tbl.add_row((NoEscape('{} -- {}'.format(
                    tr.orig.bus_id + 1, tr.dest.bus_id + 1)),
                             NoEscape('{:.02f}'.format(tr.Z1.imag * 100)),
                             NoEscape('{:.02f}'.format(
                                 tr.Z0.imag * 100)), get_scheme(tr),
                             NoEscape('{:.02f}'.format(tr.Sper.real * 100)),
                             NoEscape('{:.02f}'.format(tr.Sper.imag * 100)),
                             NoEscape('{:.02f}'.format(tr.S2.real * 100)),
                             NoEscape('{:.02f}'.format(tr.S2.imag * 100)),
                             NoEscape('{:.02f}'.format(
                                 np.abs(tr.S2) * 1e8 / tr.snom * 100))),
                            color=color)

    filepath = filename.strip('.pdf')
    make_system_schematic(curves, grid, initial_fontsize=9)
    doc.append(NewPage())
    with doc.create(Section('System')):
        with doc.create(Figure(position='h')) as system_pic:
            system_pic.add_plot(bbox_inches='tight',
                                width=NoEscape('\\textwidth'))
    doc.generate_pdf(filepath,
                     clean_tex=True,
                     compiler='latexmk',
                     compiler_args=['-pdf'])
def odstup_generator(df):
    ''' Funkce k vytvoření kapitoly s vypočtenými odstupy

        Vstupní data musí být DataFrame o specifickém formátu o deseti
        sloupcích viz níže:

        df_result['Nazev/fasada', 'vyska', 'sirka', 'Samostatne']]
        df_result['POP'] = POP_store_list
        df_result['p_v'] = pv_list
        df_result['I_avrg'] = I_tok_list
        df_result['d'] = d_results
        df_result['d\''] = d_results_kraj
        df_result['d\'s'] = d_results_za_krajem

        Funkce tvoří přímo tabulku upravenou na míru pro prezentování
        odstupových vzdáleností v PBŘ zprávě
    '''

    '''Poznámky k tabulce'''
    list_avaiable = ['Přístřešky pro auta DP3', 'Pergoly / přístřešky']

    '''Práce s daty '''
    data_popis = df['Samostatne'].values.tolist()  # Data pro přidání popisků
    df = df.drop(columns=['Samostatne'])
    data_used = df.values.tolist()  # Data pro tvoření tabulky

    '''Přidání popisků na správné místo'''
    check = []
    if not data_popis:
        # Zjišťuje zda je nutné přidat popisky
        pass
    else:
        save_var = []
        save_id = []
        save_name = []
        save_id_check = []
        for i in range(0, len(data_popis)):
            if data_popis[i] in list_avaiable:
                check.append(i)
                save_var.append(data_popis[i])
                save_id_check.append(i)
        count = list(range(1, len(save_var)+1))
        pre = ' $^{'
        suf = ')}$'
        for i in range(0, len(save_var)):
            count[i] = pre + str(count[i])
            count[i] = str(count[i]) + suf
        for n in range(0, len(save_var)):
            if n == 0:
                new_dict = dict(zip([save_var[n]], [count[n]]))
                save_id.append(save_id_check[n])
                save_name.append(save_var[n])
                # new_dict = dict(zip([save_var[n]], str(count[n])))
            if n > 0:
                if save_var[n] in new_dict:
                    save_id.append(save_id_check[n])
                    save_name.append(save_var[n])
                else:
                    len_dict = len(new_dict)+1
                    len_dict = pre + str(len_dict)
                    len_dict = str(len_dict) + suf
                    save_id.append(save_id_check[n])
                    save_name.append(save_var[n])
                    new_dict[save_var[n]] = len_dict
        for i in range(0, len(save_id)):
            data_used[save_id[i]][0] = NoEscape(data_used[save_id[i]][0]
                                                + new_dict[save_name[i]])

    '''Přeměna čísel s . na čísla s ,'''
    for i in range(0, len(data_used)):
        data_used[i][1] = str(("%.2f" % data_used[i][1])).replace(".", ",")
        data_used[i][2] = str(("%.2f" % data_used[i][2])).replace(".", ",")
        data_used[i][3] = str(("%.2f" % data_used[i][3])).replace(".", ",")
        data_used[i][4] = str(("%.2f" % data_used[i][4])).replace(".", ",")
        data_used[i][5] = str(("%.2f" % data_used[i][5])).replace(".", ",")
        data_used[i][6] = str(("%.2f" % data_used[i][6])).replace(".", ",")
        data_used[i][7] = str(("%.2f" % data_used[i][7])).replace(".", ",")
        data_used[i][8] = str(("%.2f" % data_used[i][8])).replace(".", ",")

    '''Textová část kapitoly '''
    with doc.create(Subsection('Stanovení odstupových vzdáleností')):
        if kcni_system != 'nehořlavý':
            doc.append(NoEscape(r'Požární zatížení je v souladu s čl. 10.4.4 normy ČSN 73 0802 vzhledem k zatřídění konstrukčního systému nově navrhované budovy ({}; zatřídění viz tabulka '.format(kcni_system)))
            doc.append(NoEscape(r'\ref{PTCH}) '))
            doc.append(NoEscape(r' dále zvýšeno o {} kg/m$^2$.'.format(add_pv)))
            doc.append(NoEscape('\par'))
        doc.append(NoEscape(r'Odstupové vzdálenosti jsou stanoveny určením vzdáleností kritického tepelného toku 18,5 kW/m$^2$ od vnějšího líce požárně otevřené plochy, a to pomocí programu pro výpočet odstupových vzdáleností, který je zmíněn v kapitole \ref{cha-1}). Výsledné hodnoty odstupových vzdáleností z tohoto programu jsou názorně zakresleny v následujícím obrázku \ref{SchemaPOP2}.'))
        with doc.create(Figure(position='htb!')) as Odstup:
            Odstup.add_image('images/odstup.jpg', width='160px')
            Odstup.add_caption('Znázornění vypočtených hodnot')
            Odstup.append(Command('label', 'SchemaPOP2'))
        doc.append(NoEscape(r'Vypočtené odstupové vzdále\-nosti jsou patrné z tabulky \ref{odstup}.'))

        '''Ověření zda je možné přidat popisky + přidání popisků'''
        if len(check) > 0:
            doc.append(Command('begin', 'ThreePartTable'))
            doc.append(Command('begin', 'TableNotes'))
            doc.append(NoEscape('\small'))
            for key in new_dict.keys():
                pre_str = '\item '
                if key == 'Pergoly / přístřešky':
                    loc_str = ' Odstupová vzdálenost z domnělých stěn otevřených přístřešků je spočtena pomocí normové křivky pro vnější požár. Maximální teplota požáru je tedy v tomto případě 658$^o$C. Požární zatížení je stanoveno pomocí čl. 10.4.4 normy ČSN 73 0802.'
                    string = new_dict[key]
                    doc.append(NoEscape(pre_str + string + loc_str))
                if key == 'Přístřešky pro auta DP3':
                    loc_str = ' Odstupová vzdálenost od otevřeného přístřešku pro auta je stanovena na základě čl. I.3.1 normy ČSN 73 0804. Uvažováno je s ekvivalentní dobou požáru 30 minut (zde označeno jako p$_v$ = 30 kg/m$^2$). s výškou přístřešku 1,5 m a skutečnou délkou přístřešku.'
                    string = new_dict[key]
                    doc.append(NoEscape(pre_str + string + loc_str))

        if len(check) > 0:
            doc.append(Command('end', 'TableNotes'))
        with doc.create(LongTable("lcccccccc", pos=['htb'])) as data_table:
            doc.append(Command('caption', 'Odstupové vzdálenosti od objektu'))
            doc.append(Command('label', 'odstup'))
            doc.append(Command('\ '))
            data_table.append
            data_table.add_hline()
            data_table.add_row([" ", "Výška", "Šířka", "POP",
                                NoEscape('$p_v$'), NoEscape('$I_{avrg}$'), "d", "d\'", NoEscape("d\'$_s$")])
            data_table.add_row([" ", "[m]", "[m]", NoEscape('[\%]'), NoEscape('[kg/m$^2$]'),
                                NoEscape('[kW/m$^2$]'), "[m]", "[m]", "[m]"])
            data_table.add_hline()
            data_table.end_table_header()
            for i in range(0, len(data_used)):
                if i == 0:
                    # \multicolumn{9}{l}{\textbf{1. nadzemní podlaží - POP společné}}\\
                    data_table.add_row((MultiColumn(9, align='l', data=utils.bold(df_popis[i])),))
                if i > 0 and df_popis[i] != df_popis[i-1]:
                    data_table.add_hline()
                    data_table.add_row((MultiColumn(9, align='l', data=utils.bold(df_popis[i])),))
                if (i) % 2 == 0:
                    data_table.add_row(data_used[i], color="Hex")
                elif (i) % 2 != 0:
                    data_table.add_row(data_used[i])
            data_table.add_hline()
            if len(check) > 0:
                doc.append(NoEscape('\insertTableNotes'))
        if len(check) > 0:
            doc.append(Command('end', 'ThreePartTable'))
Esempio n. 14
0
def main():

    # copy diagram
    subprocess.run(["cp", "-r", dp.diagram_path, dp.latex_pics_path])

    # copy diagram velocity only for begin and last
    for root, dirnames, filenames in os.walk(dp.f_momentum_mass_field_path):
        # if not empty
        if filenames:
            sorted_filenames = natural_sort(filenames)
            first_filename = sorted_filenames[0]
            last_filename = sorted_filenames[-1]
            copy_filenames = [first_filename, last_filename]
            for filename in copy_filenames:
                filepath = os.path.join(root, filename)
                f_copy_path = filepath.replace(dp.diagram_path,
                                               dp.latex_pics_path)
                subprocess.run(["cp", filepath, f_copy_path])

    os.chdir(dp.latex_path)
    doc = Document(default_filepath=dp.latex_path + "plots")
    doc.packages.append(Package('placeins', "section"))

    #breakpoint()

    with doc.create(Section("Simulation Plot")):
        doc.append("Width= " + str(rr.log_variable["width_wall_dp_unit"]) +
                   " diameter")
        doc.append("\nHeight= " +
                   str(rr.log_variable["z_length_create_dp_unit"]) +
                   " diameter")
        doc.append("\nPeriodic length in shear direction = " +
                   str(rr.log_variable["x_period_dp_unit"]) + " diameter")
        doc.append("\nSavage_number = " + str(rr.log_variable["Sa"]))
        doc.append("\nV_wall = " + str(
            float(rr.log_variable["in_velocity"]) /
            float(rr.log_variable["dp"])) + " diameter/second")
        list_plot_no_errorbar = [
            ("Coord1", "mv_1"),
        ]
        list_plot_errorbar = [
            ("I_12", "mu_12_middle"),
            ("I_tensor", "mu_tensor_12"),
            ("strain", "I_12"),
            ("strain", "mu_12_middle"),
            ("strain", "I_tensor"),
            ("strain", "mu_tensor_12"),
            ("strain", "fraction"),
            ("strain", "velocity_1"),
            ("strain", "velocity_2"),
            ("strain", "velocity_3"),
            ("strain", "strain_rate_21_middle"),
            ("strain", "strain_rate_31_middle"),
            ("strain", "strain_rate_22_middle"),
            ("strain", "strain_rate_32_middle"),
            ("strain", "strain_rate_23_middle"),
            ("strain", "strain_rate_33_middle"),
            ("strain", "stress_11"),
            ("strain", "stress_22"),
            ("strain", "stress_33"),
            ("strain", "stress_12"),
            ("strain", "stress_13"),
            ("strain", "stress_23"),
            ("fraction", "mu_12_middle"),
            ("fraction", "I_12"),
            ("fraction", "mu_tensor_12"),
            ("fraction", "I_tensor"),
            ("strain", "fraction"),
            ("strain", "inwall_stress_1"),
            ("strain", "inwall_stress_2"),
            ("strain", "inwall_stress_3"),
            ("strain", "outwall_stress_1"),
            ("strain", "outwall_stress_2"),
            ("strain", "outwall_stress_3"),
            ("strain", "zbottom_stress_1"),
            ("strain", "zbottom_stress_2"),
            ("strain", "zbottom_stress_3"),
        ]
        for (x_name, y_name) in list_plot_no_errorbar:
            folder_name = y_name + "_" + x_name + "/"
            folder_path = dp.latex_pics_path + "diagram/n_ave_51/" + folder_name
            onlyfilepaths = [
                os.path.join(folder_path, f) for f in os.listdir(folder_path)
                if os.path.isfile(os.path.join(folder_path, f))
            ]
            pic_path_list = natural_sort(onlyfilepaths)

            subsection_title = y_name + " vs. " + x_name
            #breakpoint()
            with doc.create(Subsection(subsection_title.replace('_middle',
                                                                ''))):
                for pic_path in pic_path_list:
                    with doc.create(Figure(position='h!')) as pic:
                        #breakpoint()
                        pic.add_image(pic_path)
                        pic.add_caption(NoEscape("\label{fig:epsart}"))

            doc.append(NoEscape("\\FloatBarrier"))

        for (x_name, y_name) in list_plot_errorbar:
            folder_name = y_name + "_" + x_name + "/"
            folder_path = dp.latex_pics_path + "diagram/n_ave_51/" + folder_name
            onlyfilepaths = [
                os.path.join(folder_path, f) for f in os.listdir(folder_path)
                if os.path.isfile(os.path.join(folder_path, f))
            ]
            pic_path_list = natural_sort(onlyfilepaths)

            folder_path = dp.latex_pics_path + "diagram/n_ave_51/" + folder_name + "errorbar/"
            onlyfilepaths = [
                os.path.join(folder_path, f) for f in os.listdir(folder_path)
                if os.path.isfile(os.path.join(folder_path, f))
            ]
            pic_path_list_errorbar = natural_sort(onlyfilepaths)

            subsection_title = y_name + " vs. " + x_name
            #breakpoint()
            with doc.create(Subsection(subsection_title.replace('_middle',
                                                                ''))):
                for pic_path in pic_path_list:
                    with doc.create(Figure(position='h!')) as pic:
                        #breakpoint()
                        pic.add_image(pic_path)
                        pic.add_caption(NoEscape("\label{fig:epsart}"))

            doc.append(NoEscape("\\FloatBarrier"))

            with doc.create(
                    Subsection(
                        subsection_title.replace('_middle', '') +
                        " (with errorbar)")):
                for pic_path in pic_path_list_errorbar:
                    with doc.create(Figure(position='h!')) as pic:
                        pic.add_image(pic_path)
                        pic.add_caption(NoEscape("\label{fig:epsart}"))

            doc.append(NoEscape("\\FloatBarrier"))

    doc.generate_pdf(clean_tex=False)

    os.chdir(rr.lammps_directory)
    Mal_y_pos = np.arange(len(Mal_obj))
    #______________________________________


    geometry_options = {"margin":"0.5in"}
    doc = Document('matplotlib_ex-dpi', geometry_options=geometry_options,documentclass='report', document_options=['12pt, notitlepage'])
    #doc.preamble.append(NoEscape(r'\linespread{1.8}'))
    Command('linespread','1.6')
    # doc.append('Introduction.')

    # with doc.create(Section('I am a section')):
    #     doc.append('Take a look at this beautiful plot:')



    with doc.create(Figure(position='h!')) as plotgrid:
        #first graph
        plt.bar(y_pos, benchMark, align='center', alpha=0.5)
        plt.bar(y_pos, unconInvest,bottom=benchMark, align='center', alpha=1, color="#f3e151")
        plt.xticks(y_pos, objects,fontsize=9, rotation=30)
        plt.ylabel('USD bn')
        plt.title('Brazil')

        with doc.create(SubFigure(position='b',width=NoEscape(r'0.5\linewidth'))) as Leftplot:
            Leftplot.add_plot(width=NoEscape(r'\linewidth'), dpi=300)

        plt.clf()
        #Second graph
        plt.bar(mex_y_pos, mex_benchMark, align='center', alpha=0.5)
        plt.bar(mex_y_pos, mex_unconInvest,bottom=mex_benchMark, align='center', alpha=1, color="#f3e151")
        plt.xticks(mex_y_pos, mex_obj, fontsize=9, rotation=30)
Esempio n. 16
0
with doc.create(MiniPage(align='l')):

    #doc.append(NoEscape(r"\noindent\rule{\textwidth}{1pt}"))
    #doc.append(NewLine())
    doc.append('Name : ' + str(sub_info.Name[0]))
    doc.append('\nAge: ' + str(sub_info.Age[0]))
    doc.append('\nGender: ' + str(sub_info.Gender[0]))
    doc.append('\nUH Id: ' + str(sub_info.UHID[0]))
    doc.append('\nDate: ' + d2)
    doc.append(LineBreak())
    doc.append(NoEscape(r"\noindent\rule{\textwidth}{1pt}"))
    doc.append(NewLine())
    doc.append(LineBreak())

    with doc.create(MiniPage(align='c')):
        doc.append(LargeText(bold('Vowel Triangle Analysis Report')))

# Analysis result and image

with doc.create(Section('Vowel Triangle Analysis')):
    with doc.create(Figure(position='h!')) as img_plot:
        img_plot.add_image(img1, width='300px')
        img_plot.add_caption('Vowel Triangle PLot')
    with doc.create(Subsection('Vowel Triangle')):
        doc.append('Area : ' + str(area))
    doc.append(NoEscape(r"\pagebreak[4]"))

# saving the pdf and tex

doc.generate_pdf(filepath='media/VT.report1', clean_tex=False)
Esempio n. 17
0
def plot_show(caption, width=r'0.5\textwidth', *args, **kwargs):
    fig = Figure(position='htbp')
    fig.add_plot(width=NoEscapeStr(width), *args, **kwargs)
    fig.add_caption(NoEscapeStr(caption))
    return fig
Esempio n. 18
0
def writeFigure(doc, figname, soru_sayisi, scale):
    with doc.create(Figure(position="h!")) as fig:
        width = NoEscape(r"{}\textwidth".format(scale))
        fig.add_image(settings.fig_path + figname, width=width)
        fig.add_caption("Soru "+ str(soru_sayisi))
Esempio n. 19
0
def dessiner(doc, chemin):
    for photo in os.listdir(chemin):
        with doc.create(Section('Showing subfigures')):
            image_filename = os.path.join(chemin, photo)
            with doc.create(Figure(width=NoEscape(r'\linewidth'))) as frog:
                frog.add_image(image_filename, width=NoEscape(r'\linewidth'))
Esempio n. 20
0
                itemize.add_item("the second item")
                itemize.add_item("the third etc")
                # you can append to existing items
                itemize.append(Command("ldots"))


if __name__ == '__main__':
    # Basic document
    doc = Document('basic')
    fill_document(doc)

    # Document with `\maketitle` command activated
    doc = Document()
    image_filename = os.path.join(os.path.dirname(__file__), 'final.png')

    with doc.create(Figure(position='h!')) as logo:
        logo.add_image(image_filename, width='300px')
    doc.preamble.append(Command('title', 'note-o-matic Summary'))
    doc.preamble.append(Command('author', 'Generated using note-o-matic'))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))

    fill_document(doc)

    # Add stuff to the document
    with doc.create(Section('Your notes - reworked.')):
        doc.append('uwu')

    doc.generate_pdf('note-o-maticSummary',
                     clean_tex=False,
                     compiler='/Library/TeX/texbin/pdflatex')
Esempio n. 21
0
rev_c = {"A": "T", "C": "G", "G": "C", "T": "A", "$": "$"}
colors = ["red", "green", "blue", "yellow"]


def create_figure(seq, interval_dict, query):
    seq_fig = tikz_matrix("seq", body([seq, "".join(rev_c[c] for c in seq)]))
    query_fig = tikz_matrix("q", body([query]), "below=of seq")
    rec_1 = r"\node[color=%s, draw, dashed, rounded corners, fit=(seq-1-%s) (seq-1-%s)] {};"
    rec_2 = r"\node[color=%s, draw, dashed, rounded corners, fit=(seq-2-%s) (seq-2-%s)] {};"
    rec_q = r"\node[color=%s, draw, dashed, rounded corners, fit=(q-1-%s) (q-1-%s)] {};"
    lines = []
    N = len(seq)
    i = 0
    for (s, e), (intervals, reverse_intervals) in interval_dict.iteritems():
        lines.append(rec_q % (colors[i], s + 1, e))
        for (start, end) in intervals:
            lines.append(rec_1 % (colors[i], start + 1, end))

        for start, end in reverse_intervals:
            lines.append(rec_2 % (colors[i], N - end + 1, N - start))
        i += 1
    content = seq_fig + "\n" + query_fig + "\n" + "\n".join(lines)
    content = content.replace("$", r"\$")
    return content


if __name__ == "__main__":
    fig = Figure("memfig", "memfigs")
    fig.write(create_figure("ATTCT", {1: ([(0, 3), (2, 5)], [(1, 3)])}))
Esempio n. 22
0
    def save_latex(self,
                   uiObj,
                   Design_Check,
                   reportsummary,
                   filename,
                   rel_path,
                   Disp_2d_image,
                   Disp_3d_image,
                   module=''):
        companyname = str(reportsummary["ProfileSummary"]['CompanyName'])
        companylogo = str(reportsummary["ProfileSummary"]['CompanyLogo'])
        groupteamname = str(reportsummary["ProfileSummary"]['Group/TeamName'])
        designer = str(reportsummary["ProfileSummary"]['Designer'])
        projecttitle = str(reportsummary['ProjectTitle'])
        subtitle = str(reportsummary['Subtitle'])
        jobnumber = str(reportsummary['JobNumber'])
        client = str(reportsummary['Client'])

        does_design_exist = reportsummary['does_design_exist']
        osdagheader = '/ResourceFiles/images/Osdag_header_report.png'
        # Add document header
        geometry_options = {
            "top": "5cm",
            "hmargin": "2cm",
            "headheight": "100pt",
            "footskip": "100pt",
            "bottom": "5cm"
        }
        doc = Document(geometry_options=geometry_options, indent=False)
        doc.packages.append(Package('amsmath'))
        doc.packages.append(Package('graphicx'))
        doc.packages.append(Package('needspace'))
        doc.append(pyl.Command('fontsize', arguments=[8, 12]))
        doc.append(pyl.Command('selectfont'))

        doc.add_color('OsdagGreen', 'RGB', '153,169,36')
        doc.add_color('PassColor', 'RGB', '153,169,36')
        doc.add_color('Red', 'RGB', '255,0,0')
        doc.add_color('Green', 'RGB', '0,200,0')
        doc.add_color('FailColor', 'HTML', '933A16')
        header = PageStyle("header")
        # Create center header
        with header.create(Head("C")):
            with header.create(Tabularx('|l|p{4cm}|l|X|')) as table:
                table.add_hline()
                # MultiColumn(4)
                table.add_row((
                    MultiColumn(
                        2,
                        align='|c|',
                        data=('' if companylogo is '' else StandAloneGraphic(
                            image_options="height=0.95cm",
                            filename=companylogo))),
                    MultiColumn(2,
                                align='|c|',
                                data=[
                                    'Created with',
                                    StandAloneGraphic(
                                        image_options="width=4.0cm,height=1cm",
                                        filename=rel_path + osdagheader)
                                ]),
                ))
                table.add_hline()
                table.add_row(('Company Name', companyname, 'Project Title',
                               projecttitle),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Group/Team Name', groupteamname, 'Subtitle', subtitle),
                    color='OsdagGreen')
                table.add_hline()
                table.add_row(('Designer', designer, 'Job Number', jobnumber),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Date', time.strftime("%d /%m /%Y"), 'Client', client),
                    color='OsdagGreen')
                table.add_hline()

        # Create right footer
        with header.create(Foot("R")):
            header.append(NoEscape(r'Page \thepage'))
        #
        # doc.preamble.append(header)
        # doc.change_document_style("header")

        # Add Heading
        # with doc.create(MiniPage(align='c')):

        doc.preamble.append(header)
        doc.change_document_style("header")
        with doc.create(Section('Input Parameters')):
            with doc.create(
                    LongTable('|p{5cm}|p{2.5cm}|p{1.5cm}|p{3cm}|p{3.5cm}|',
                              row_height=1.2)) as table:
                table.add_hline()
                for i in uiObj:
                    # row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left'))
                    if i == "Selected Section Details" or i == KEY_DISP_ANGLE_LIST or i == KEY_DISP_TOPANGLE_LIST or i == KEY_DISP_CLEAT_ANGLE_LIST:
                        # if type(uiObj[i]) == list:
                        continue
                    if type(uiObj[i]) == dict:
                        table.add_hline()
                        sectiondetails = uiObj[i]
                        image_name = sectiondetails[KEY_DISP_SEC_PROFILE]

                        Img_path = '/ResourceFiles/images/' + image_name + '.png'
                        if (len(sectiondetails)) % 2 == 0:
                            # merge_rows = int(round_up(len(sectiondetails),2)/2 + 2)
                            merge_rows = int((len(sectiondetails) / 2)) + 2
                        else:
                            merge_rows = round_up((len(sectiondetails) / 2), 2)
                        if (len(sectiondetails)) % 2 == 0:
                            sectiondetails[''] = ''

                        a = list(sectiondetails.keys())
                        # index=0
                        for x in range(1, (merge_rows + 1)):
                            # table.add_row("Col.Det.",i,columndetails[i])
                            if x == 1:
                                table.add_row((
                                    MultiRow(
                                        merge_rows,
                                        data=StandAloneGraphic(
                                            image_options=
                                            "width=5cm,height=5cm",
                                            filename=rel_path + Img_path)),
                                    MultiColumn(2, align='|c|', data=a[x]),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=sectiondetails[a[x]]),
                                ))
                            elif x <= 4:
                                table.add_row((
                                    '',
                                    MultiColumn(2,
                                                align='|c|',
                                                data=NoEscape(a[x])),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=NoEscape(
                                                    sectiondetails[a[x]])),
                                ))
                            else:
                                table.add_row((
                                    '',
                                    NoEscape(a[x]),
                                    sectiondetails[a[x]],
                                    NoEscape(a[merge_rows + x - 4]),
                                    sectiondetails[a[merge_rows + x - 4]],
                                ))
                            table.add_hline(2, 5)
                    elif uiObj[i] == "TITLE":
                        table.add_hline()
                        table.add_row((MultiColumn(
                            5,
                            align='|c|',
                            data=bold(i),
                        ), ))
                        table.add_hline()
                    elif i == 'Section Size*':
                        table.add_hline()
                        table.add_row((
                            MultiColumn(
                                3,
                                align='|c|',
                                data=i,
                            ),
                            MultiColumn(2,
                                        align='|c|',
                                        data="Ref List of Input Section"),
                        ))
                        table.add_hline()
                    elif len(str(uiObj[i])) > 55 and type(
                            uiObj[i]) != pyl.math.Math:
                        str_len = len(str(uiObj[i]))
                        loop_len = round_up((str_len / 55), 1, 1)
                        for j in range(1, loop_len + 1):
                            b = 55 * j + 1
                            if j == 1:
                                table.add_row((
                                    MultiColumn(3,
                                                align='|c|',
                                                data=MultiRow(loop_len,
                                                              data=i)),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=uiObj[i][0:b]),
                                ))
                            else:
                                table.add_row((
                                    MultiColumn(3,
                                                align='|c|',
                                                data=MultiRow(loop_len,
                                                              data="")),
                                    MultiColumn(2,
                                                align='|c|',
                                                data=uiObj[i][b - 55:b]),
                                ))
                        table.add_hline()
                    else:
                        table.add_hline()
                        table.add_row((
                            MultiColumn(3, align='|c|', data=NoEscape(i)),
                            MultiColumn(2, align='|c|', data=uiObj[i]),
                        ))
                        table.add_hline()
            for i in uiObj:
                if i == 'Section Size*' or i == KEY_DISP_ANGLE_LIST or i == KEY_DISP_TOPANGLE_LIST or i == KEY_DISP_CLEAT_ANGLE_LIST:
                    with doc.create(Subsection("List of Input Section")):
                        # with doc.create(LongTable('|p{8cm}|p{8cm}|', row_height=1.2)) as table:
                        with doc.create(Tabularx('|p{4cm}|X|',
                                                 row_height=1.2)) as table:
                            table.add_hline()
                            table.add_row((
                                MultiColumn(
                                    1,
                                    align='|c|',
                                    data=i,
                                ),
                                MultiColumn(1,
                                            align='|X|',
                                            data=uiObj[i].strip("[]")),
                            ))
                            # str_len = len(uiObj[i])
                            # loop_len = round_up((str_len/100),1,1)
                            # table.add_hline()
                            # for j in range(1,loop_len+1):
                            #     b= 100*j+1
                            #     if j ==1:
                            #         table.add_row((MultiColumn(1, align='|c|', data=i, ),
                            #                        MultiColumn(1, align='|X|', data=uiObj[i][0:b]),))
                            #     else:
                            #         table.add_row((MultiColumn(1, align='|c|', data=" ", ),
                            #                        MultiColumn(1, align='|X|', data=uiObj[i][b-100:b]),))
                            table.add_hline()

        doc.append(
            pyl.Command('Needspace', arguments=NoEscape(r'10\baselineskip')))
        doc.append(NewPage())
        count = 0
        with doc.create(Section('Design Checks')):
            with doc.create(
                    Tabularx(
                        r'|>{\centering}p{12.5cm}|>{\centering\arraybackslash}X|',
                        row_height=1.2)) as table:
                table.add_hline()
                # Fail = TextColor("FailColor", bold("Fail"))
                # Pass = TextColor("PassColor", bold("Pass"))

                if does_design_exist != True:
                    table.add_row(bold('Design Status'),
                                  color_cell("Red", bold("Fail")))
                else:
                    table.add_row(bold('Design Status'),
                                  color_cell("OsdagGreen", bold("Pass")))
                table.add_hline()

            for check in Design_Check:

                if check[0] == 'SubSection':
                    if count >= 1:
                        # doc.append(NewPage())
                        doc.append(
                            pyl.Command(
                                'Needspace',
                                arguments=NoEscape(r'10\baselineskip')))
                    with doc.create(Subsection(check[1])):
                        #########################
                        # if uiObj== "WELDImage":
                        #     table.add_hline()
                        #     table.add_row((MultiColumn(5, align='|c|', data=bold(i), ),))
                        #     table.add_hline()
                        # else:
                        #########################
                        with doc.create(LongTable(check[2], row_height=1.2)
                                        ) as table:  # todo anjali remove
                            table.add_hline()
                            table.add_row(
                                ('Check', 'Required', 'Provided', 'Remarks'),
                                color='OsdagGreen')
                            table.add_hline()
                            table.end_table_header()
                            table.add_hline()
                            count = count + 1
                elif check[0] == "Selected":
                    if count >= 1:
                        # doc.append(NewPage())
                        doc.append(
                            pyl.Command(
                                'Needspace',
                                arguments=NoEscape(r'10\baselineskip')))
                    with doc.create(Subsection(check[1])):
                        with doc.create(LongTable(check[2],
                                                  row_height=1.2)) as table:
                            table.add_hline()
                            for i in uiObj:
                                # row_cells = ('9', MultiColumn(3, align='|c|', data='Multicolumn not on left'))

                                print(i)
                                if type(
                                        uiObj[i]
                                ) == dict and i == 'Selected Section Details':
                                    table.add_hline()
                                    sectiondetails = uiObj[i]
                                    image_name = sectiondetails[
                                        KEY_DISP_SEC_PROFILE]
                                    Img_path = '/ResourceFiles/images/' + image_name + '.png'
                                    if (len(sectiondetails)) % 2 == 0:
                                        # merge_rows = int(round_up(len(sectiondetails),2)/2 + 2)
                                        merge_rows = int(
                                            round_up((len(sectiondetails) /
                                                      2), 1, 0) + 2)
                                    else:
                                        merge_rows = int(
                                            round_up((len(sectiondetails) /
                                                      2), 1, 0) + 1)
                                    print('Hi',
                                          len(sectiondetails) / 2,
                                          round_up(len(sectiondetails), 2) / 2,
                                          merge_rows)
                                    if (len(sectiondetails)) % 2 == 0:
                                        sectiondetails[''] = ''
                                    a = list(sectiondetails.keys())
                                    # index=0
                                    for x in range(1, (merge_rows + 1)):
                                        # table.add_row("Col.Det.",i,columndetails[i])
                                        if x == 1:
                                            table.add_row((
                                                MultiRow(
                                                    merge_rows,
                                                    data=StandAloneGraphic(
                                                        image_options=
                                                        "width=5cm,height=5cm",
                                                        filename=rel_path +
                                                        Img_path)),
                                                MultiColumn(2,
                                                            align='|c|',
                                                            data=NoEscape(
                                                                a[x])),
                                                MultiColumn(
                                                    2,
                                                    align='|c|',
                                                    data=NoEscape(
                                                        sectiondetails[a[x]])),
                                            ))
                                        elif x <= 4:
                                            table.add_row((
                                                '',
                                                MultiColumn(2,
                                                            align='|c|',
                                                            data=NoEscape(
                                                                a[x])),
                                                MultiColumn(
                                                    2,
                                                    align='|c|',
                                                    data=sectiondetails[a[x]]),
                                            ))
                                        else:
                                            table.add_row((
                                                '',
                                                NoEscape(a[x]),
                                                sectiondetails[a[x]],
                                                NoEscape(a[merge_rows + x -
                                                           4]),
                                                sectiondetails[a[merge_rows +
                                                                 x - 4]],
                                            ))

                                        table.add_hline(2, 5)
                            table.add_hline()
                        count = count + 1
                else:

                    if check[3] == 'Fail':
                        table.add_row((NoEscape(check[0])), check[1], check[2],
                                      TextColor("Red", bold(check[3])))
                    else:
                        table.add_row((NoEscape(check[0])), check[1], check[2],
                                      TextColor("OsdagGreen", bold(check[3])))
                    table.add_hline()

        # 2D images
        if len(Disp_2d_image) != 0:

            if module == KEY_DISP_BCENDPLATE or module == KEY_DISP_BB_EP_SPLICE:
                if does_design_exist and sys.platform != 'darwin':
                    doc.append(NewPage())
                    weld_details = rel_path + Disp_2d_image[0]
                    detailing_details = rel_path + Disp_2d_image[1]
                    stiffener_details = rel_path + Disp_2d_image[2]

                    with doc.create(Section('2D Drawings (Typical)')):

                        with doc.create(Figure()) as image:
                            image.add_image(weld_details,
                                            width=NoEscape(r'0.7\textwidth'),
                                            placement=NoEscape(r'\centering'))
                            image.add_caption(
                                'Typical Weld Details -- Beam to End Plate Connection'
                            )
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_2:
                            image_2.add_image(
                                detailing_details,
                                width=NoEscape(r'0.7\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_2.add_caption('Typical Detailing')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_3:
                            image_3.add_image(
                                stiffener_details,
                                width=NoEscape(r'0.9\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_3.add_caption('Typical Stiffener Details')
                            # doc.append(NewPage())

            elif module == KEY_DISP_BASE_PLATE:
                if does_design_exist and sys.platform != 'darwin':
                    doc.append(NewPage())
                    bp_sketch = rel_path + Disp_2d_image[0]
                    bp_detailing = rel_path + Disp_2d_image[1]
                    bp_weld = rel_path + Disp_2d_image[2]
                    bp_anchor = rel_path + Disp_2d_image[3]
                    bp_key = rel_path + Disp_2d_image[4]

                    with doc.create(Section('2D Drawings (Typical)')):
                        with doc.create(Figure()) as image_1:
                            image_1.add_image(
                                bp_sketch,
                                width=NoEscape(r'1.0\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_1.add_caption('Typical Base Plate Details')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_2:
                            image_2.add_image(
                                bp_detailing,
                                width=NoEscape(r'1.0\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_2.add_caption('Typical Base Plate Detailing')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_3:
                            image_3.add_image(
                                bp_weld,
                                width=NoEscape(r'1.0\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_3.add_caption('Typical Weld Details')
                            # doc.append(NewPage())

                        with doc.create(Figure()) as image_4:
                            image_4.add_image(
                                bp_anchor,
                                width=NoEscape(r'0.5\textwidth'),
                                placement=NoEscape(r'\centering'))
                            image_4.add_caption('Typical Anchor Bolt Details')
                            # doc.append(NewPage())

                        if len(Disp_2d_image[-1]) > 0:
                            with doc.create(Figure()) as image_5:
                                image_5.add_image(
                                    bp_key,
                                    width=NoEscape(r'0.9\textwidth'),
                                    placement=NoEscape(r'\centering'))
                                image_5.add_caption(
                                    'Typical Shear Key Details')
                                # doc.append(NewPage())

        if does_design_exist and sys.platform != 'darwin':
            doc.append(NewPage())
            Disp_top_image = "/ResourceFiles/images/top.png"
            Disp_side_image = "/ResourceFiles/images/side.png"
            Disp_front_image = "/ResourceFiles/images/front.png"
            view_3dimg_path = rel_path + Disp_3d_image
            view_topimg_path = rel_path + Disp_top_image
            view_sideimg_path = rel_path + Disp_side_image
            view_frontimg_path = rel_path + Disp_front_image
            with doc.create(Section('3D Views')):
                with doc.create(
                        Tabularx(
                            r'|>{\centering}X|>{\centering\arraybackslash}X|',
                            row_height=1.2)) as table:
                    view_3dimg_path = rel_path + Disp_3d_image
                    view_topimg_path = rel_path + Disp_top_image
                    view_sideimg_path = rel_path + Disp_side_image
                    view_frontimg_path = rel_path + Disp_front_image
                    table.add_hline()
                    table.add_row([
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_3dimg_path),
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_topimg_path)
                    ])
                    table.add_row('(a) 3D View', '(b) Top View')
                    table.add_hline()
                    table.add_row([
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_sideimg_path),
                        StandAloneGraphic(image_options="height=4cm",
                                          filename=view_frontimg_path)
                    ])
                    table.add_row('(c) Side View', '(d) Front View')
                    table.add_hline()
                # with doc.create(Figure(position='h!')) as view_3D:
                #     view_3dimg_path = rel_path + Disp_3d_image
                #     # view_3D.add_image(filename=view_3dimg_path, width=NoEscape(r'\linewidth'))
                #
                #     view_3D.add_image(filename=view_3dimg_path,width=NoEscape(r'\linewidth,height=6.5cm'))
                #
                #     view_3D.add_caption('3D View')

        with doc.create(Section('Design Log')):
            doc.append(
                pyl.Command('Needspace',
                            arguments=NoEscape(r'10\baselineskip')))
            logger_msgs = reportsummary['logger_messages'].split('\n')
            for msg in logger_msgs:
                if ('WARNING' in msg):
                    colour = 'blue'
                elif ('INFO' in msg):
                    colour = 'OsdagGreen'
                elif ('ERROR' in msg):
                    colour = 'red'
                else:
                    continue
                doc.append(TextColor(colour, '\n' + msg))
        try:
            doc.generate_pdf(filename, compiler='pdflatex', clean_tex=False)
        except:
            pass
Esempio n. 23
0
def generateLatex(phrases, key, result, flag):

    geometry_options = {"tmargin": "1cm", "lmargin": "3cm", "rmargin": "3cm"}
    doc = Document(geometry_options=geometry_options)

    if(flag == "E"):
        with doc.create(Section('Encyption Input')):
            doc.append('Text: ' + "".join(phrases) + "\n")
            doc.append('Key: ' +key)

        with doc.create(Section("Matrix Mltiplications")):
            for phrase in phrases:
                M = createEncryptMatrix(key)
                messageMatrix =  np.array([[getCapitalAlphaMod(phrase[0]),getCapitalAlphaMod(phrase[1]),getCapitalAlphaMod(phrase[2])]]).astype("float64").T
                doc.append(Math(data=[r'1/' + str(26), Matrix(M), Matrix(messageMatrix), '=', Matrix(getModMatrix(M @ messageMatrix))]))
                doc.append("\n")
                doc.append("Encrypted chunk: " + getStringFromMatrix(getModMatrix(M @ messageMatrix)))

        with doc.create(Section('Encyption Result')):
            doc.append('Cipher: ' + result)
    elif(flag == "D"):
        image_filename = './LookupHill.png'
        
        with doc.create(Section('Introduction')):
            doc.append('In this project, I implement a 3  ×  3 Hill Cipher Machine in Python. This machine automatically generates LaTex reports to decipher user-input step by step. \n')
            doc.append('We will be deciphering: ' + "".join(phrases) + ' using the key: ' + key + '. \n')

        with doc.create(Section("Enryption Matrix")):
            with doc.create(Figure(position='h!')) as lookup_hill:
                lookup_hill.add_image(image_filename, width='120px')
                lookup_hill.add_caption('Lookup Table of Hill Cipher')
                
            doc.append('We use the Lookup Table above to create the Encryption Matrix below. \n')
            M = createEncryptMatrix(key)
            doc.append(Math(data=[Matrix(M)]))

        with doc.create(Section("Encryption Matrix Mod 26 Inverse")):
            '''iM = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]])
            E21E31 = iM.copy()
            E21E31[(1,0)] = -1 * (augM[(1,0)]/augM[(0,0)])
            E21E31[(2,0)] = -1 * (augM[(2,0)]/augM[(0,0)])
            augM = E21E31.dot(augM)
            E32 = iM.copy()
            E32[(2,1)] = -1 * (augM[(2,1)]/augM[(1,1)])
            augM = E32.dot(augM)
            E23E13 = iM.copy()
            E23E13[(1,2)] = -1 * (augM[(1,2)]/augM[(2,2)])
            E23E13[(0,2)] = -1 * (augM[(0,2)]/augM[(2,2)])
            augM = E23E13.dot(augM)
            E12 = iM.copy()
            E12[(0,1)] = -1 * (augM[(0,1)]/augM[(1,1)])
            augM = E12.dot(augM)

            det = augM[(0,0)] * augM[(1,1)] * augM[(2,2)]
            if(det == 0 or math.isnan(det)):
                raise ValueError("Matrix Non-Invertible")
            #print("Det: " + str(det))
            if(egcd(int(round(det)), 26)[0] != 1):
                raise ValueError("Key Matrix determinent not co-prime with 26")

            #print("Mod inv of det: " + str(modinv(det, 26)))
            D = iM.copy()
            D[(0,0)] = 1/augM[(0,0)]
            D[(1,1)] = 1/augM[(1,1)]
            D[(2,2)] = 1/augM[(2,2)]
            augM = D.dot(augM)

            #Here are the additional steps needed to find the modular inverse of a matrix
            augM = augM * det
            augM = augM * modinv(int(round(det)), 26)

            modAugM = getModMatrix(augM[0:, 3:])

            return modAugM'''
            invMat = gaussianInverseMod26(createEncryptMatrixAug(key))
            doc.append(Math(data=[Matrix(invMat)]))
            doc.append("\n")
        
        with doc.create(Section("Matrix Multiplications")):
            for phrase in phrases:
                M = invMat
                #print(M)
                messageMatrix =  np.array([[getCapitalAlphaMod(phrase[0]),getCapitalAlphaMod(phrase[1]),getCapitalAlphaMod(phrase[2])]]).astype("float64").T
                doc.append(Math(data=[Matrix(M), Matrix(messageMatrix), '=', Matrix(getModMatrix(M @ messageMatrix))]))
                doc.append("\n")
                doc.append("Decrypted chunk: " + getStringFromMatrix(getModMatrix(M @ messageMatrix)))

        with doc.create(Section('Decryption Result')):
            doc.append('Plaintext: ' + result)

    doc.generate_pdf('full', clean_tex=False)

    subprocess.call(['open', 'full.pdf'])
Esempio n. 24
0
    def gen_graphs(self, visu):
        '''
        function calls the graphs methods to draw from the visualization
        module according to use preferences
        takes as input a visualizer object
        '''
        # start Graphs Section in the report #
        self.doc.append(NoEscape(r'\leftskip=0pt'))
        with self.doc.create(Section('Graphs', numbering=False)):
            # uncomment after generating predictions

            if not self.regression:
                # Confusion Matrix #
                self.doc.append(NoEscape(r'\leftskip=20pt'))
                with self.doc.create(
                        Subsection('Confusion Matrix', numbering=False)):
                    self.doc.append(NoEscape(r'\leftskip=40pt'))
                    with self.doc.create(
                            Figure(position='htbp')
                    ) as conf_mat_plot:  # Create new Figure in tex
                        # get image path from the visualizer
                        file_name = visu.gen_conf_mat(
                            target_names=self.target_names,
                            predictions=self.predictions,
                            y=self.y_train,
                            dpi=300)
                        conf_mat_plot.add_image(file_name,
                                                width=NoEscape(r'1\textwidth'))

                self.doc.append(NoEscape(r'\pagebreak'))  #start new page
                # ROC Curve #
                self.doc.append(NoEscape(r'\leftskip=20pt'))
                with self.doc.create(Subsection('ROC Curve', numbering=False)):
                    self.doc.append(NoEscape(r'\leftskip=40pt'))
                    with self.doc.create(
                            Figure(position='htbp'
                                   )) as ROC_plot:  # Create new Figure in tex
                        # y_tr = self.y_train
                        y_ts = self.y_train
                        file_name = visu.gen_roc_curve(
                            probabilities=self.probabilities,
                            y=y_ts,
                            target_names=self.target_names)
                        ROC_plot.add_image(file_name,
                                           width=NoEscape(r'1.2\textwidth'))
                self.doc.append(NoEscape(r'\pagebreak'))  #start new page

            # Feature importance #
            self.doc.append(NoEscape(r'\leftskip=20pt'))
            with self.doc.create(
                    Subsection('Feature Importance', numbering=False)):
                self.doc.append(NoEscape(r'\leftskip=40pt'))
                with self.doc.create(Figure(position='htbp')) as imp_plot:
                    file_name = visu.gen_feature_imp(
                        regression=self.regression,
                        X=self.X_train,
                        y=self.y_train)
                    imp_plot.add_image(file_name,
                                       width=NoEscape(r'1.2\textwidth'))

            self.doc.append(NoEscape(r'\pagebreak'))  #start new page
            if self.experiments.iloc[0][0] == 'ensembleSelection':
                # Word Cloud #
                self.doc.append(NoEscape(r'\leftskip=20pt'))
                with self.doc.create(
                        Subsection('Models Cloud', numbering=False)):
                    self.doc.append(NoEscape(r'\leftskip=40pt'))
                    with self.doc.create(
                            Figure(position='htbp')) as cloud_plot:
                        file_name = visu.gen_word_cloud(self.experiments)
                        cloud_plot.add_image(file_name,
                                             width=NoEscape(r'1.2\textwidth'))
Esempio n. 25
0
def fill_document(doc):
    with doc.create(Section('Section 9.1', numbering=False)):
        with doc.create(Subsection('8', numbering=False)):
            with doc.create(
                    Enumerate(enumeration_symbol=r"\alph*)",
                              options={'start': 1})) as enum:
                enum.add_item('5')
                enum.add_item('3')
                enum.add_item('7')
                enum.add_item(NoEscape('$\sqrt{49+25}\\approx 8.6$'))
                enum.add_item(NoEscape('$\sqrt{9+25}\\approx 5.8$'))
                enum.add_item(NoEscape('$\sqrt{49+9}\\approx 7.6$'))
        with doc.create(Subsection('12', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'radius = \sqrt{(\sqrt{1^2+2^2})^2+3^2} &= \sqrt{14} \\')
                agn.append(r'(x-1)^2+(y-2)^2+(z-3)^2 &= (\sqrt{14})^2\\')
                agn.append(r'(x-1)^2+(y-2)^2+(z-3)^2 &= 14')
        with doc.create(Subsection('14', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(r'x^2+8x+y^2-6y+z^2+2z &= -17\\')
                agn.append(r'(x+4)^2-16+(y-3)^2-9+(z+1)^2-1 &= -17\\')
                agn.append(r'(x+4)^2+(y-3)^2+(z+1)^2 &= -17 +16+9+1\\')
                agn.append(r'(x+4)^2+(y-3)^2+(z+1)^2 &= 9\\')
            doc.append(
                'The equation represents a sphere with center (-4,3,-1) and radius = 3'
            )
        with doc.create(Subsection('16', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(r'3(x^2+y^2+z^2) &=10+6y+12z\\')
                agn.append(r'x^2+y^2+z^2 &=\frac{10}{3}+2y+4z\\')
                agn.append(r'x^2+y^2-2y+z^2-4z &=\frac{10}{3}\\')
                agn.append(r'x^2+(y-1)^2-2+(z-2)^2-4 &=\frac{10}{3}\\')
                agn.append(r'x^2+(y-1)^2+(z-2)^2 &=\frac{10}{3}+2+4\\')
                agn.append(r'x^2+(y-1)^2+(z-2)^2 &=\frac{28}{3}\\')
            doc.append(
                'The equation represents a sphere with center (0,1,2) and radius ='
            )
            doc.append(NoEscape('$2\sqrt{\\frac{7}{3}}$'))
        with doc.create(Subsection('21-32', numbering=False)):
            with doc.create(
                    Enumerate(enumeration_symbol=r"\arabic*)",
                              options={'start': 21})) as enum:
                enum.add_item(
                    'The vertical plane that lies over the line given by x=5 in the xy-plane'
                )
                enum.add_item(
                    'The vertical plane that lies over the line given by y=-2 in the xy-plane'
                )
                enum.add_item(
                    'The subspace containing all numbers smaller than the plane that goes through y=8'
                )
                enum.add_item(
                    'The subspace containing all numbes larger than the vertical plane that lies over the line given by x=-3 in the xy-plane'
                )
                enum.add_item(
                    'The subspace contained between (and including) the xy-planes that pass through z=0 and z=6'
                )
                enum.add_item(
                    'The cup-shaped shell defined by spinning the parabola given by '
                )
                doc.append(NoEscape('$z^2=1$'))
                doc.append(' spun around the z-axis')
                enum.add_item(
                    'The circle that lies in the xy-plane and is centered at (0,0,-1) and has a radius = 2'
                )
                enum.add_item(
                    'The cylindrical shell of radius = 4 that is centered around the x-axis'
                )
                enum.add_item(
                    'The subspace contained within the sphere centered at (0,0,0) with radius '
                )
                doc.append(NoEscape('$\leq\sqrt{3}$'))
                enum.add_item(
                    'The plane that extends out from the line given by x=z')
                enum.add_item(
                    'The subspace that is outside the sphere centered at (0,0,1) with a radius of 1'
                )
        with doc.create(Subsection('38', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\sqrt{(x+1)^2+(y-5)^2+(z-3)^2} &= 2\sqrt{(x-6)^2+(y-2)^2+(z+2)^2}\\'
                )
                agn.append(
                    r'x^2+2x+1+y^2-10y+25+z^2-6z+9 &= 4(x^2-12x+36+y^2-4y\\ \
                    &\textnormal{   }+4+z^2+4z+4)\\')
                agn.append(
                    r'4x^2-x^2-48x-2x+4y^2-y^2-16y+10y+4z^2-z^2+16z+6z &= -141\\'
                )
                agn.append(r'3x^2-50x+3y^2-6y+3z^2+22z &=-141\\')
                agn.append(
                    r'x^2-\frac{50}{3}x+y^2-2y+z^2+\frac{22}{3}z &=-47\\')
                agn.append(
                    r'(x-\frac{25}{3})^2+(y-1)^2+(z-\frac{11}{3})^2 &=-47+\frac{625}{9}+\frac{121}{9}\\'
                )
                agn.append(
                    r'(x-\frac{25}{3})^2+(y-1)^2+(z-\frac{11}{3})^2 &=\frac{323}{9}\\'
                )
        doc.append('The center is (25/3, 1, 11/3) and the radius is ')
        doc.append(NoEscape('$\\frac{\\sqrt{323}}{3}$'))

    with doc.create(Section('Section 9.2', numbering=False)):
        with doc.create(Subsection('22', numbering=False)):
            doc.append(
                NoEscape(
                    '$\\langle \\frac{-6}{\\sqrt{6}}, \\frac{12}{\\sqrt{6}}, \\frac{6}{\\sqrt{6}}\\rangle$'
                ))
        with doc.create(Subsection('28', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'wind = &\langle 50cos(\frac{7\pi}{4}), 50sin(\frac{7\pi}{4}) \rangle \
                    \\plane = &\langle 250cos(\frac{\pi}{6}), 250sin(\frac{\pi}{6}) \rangle\\'
                )
                agn.append(
                    r'true course = \langle 251.86, 89.64\rangle \textnormal{ and  } & \
                    ground speed = \sqrt{251.86^2 + 89.64^2} = 267.34\\')
        with doc.create(Subsection('38', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(r'\vec{i} = & \langle 1,0,0 \rangle\\')
                agn.append(r'\vec{j} = & \langle 0,1,0 \rangle\\')
                agn.append(r'\vec{k} = & \langle 0,0,1 \rangle\\')
                agn.append(
                    r'\vec{v} = &  \langle a\vec{i},b\vec{j},c\vec{k} \rangle\\'
                )
                agn.append(
                    r'hypotenuse = \rvert\rvert v\rvert\rvert = & \sqrt{a^2+b^2+c^2}\\'
                )
                agn.append(r'cos\alpha = & \frac{a}{\sqrt{a^2+b^2+c^2}}\\')
                agn.append(r'cos\beta = & \frac{b}{\sqrt{a^2+b^2+c^2}}\\')
                agn.append(r'cos\gamma = & \frac{c}{\sqrt{a^2+b^2+c^2}}\\')
                agn.append(
                    r'cos^2\alpha + cos^2\beta + cos^2\gamma = & \frac{a^2}{a^2+b^2+c^2} + \
                           \frac{b^2}{a^2+b^2+c^2} + \frac{c^2}{a^2+b^2+c^2}\\'
                )
                agn.append(r'cos^2\alpha + cos^2\beta + cos^2\gamma = & 1\\')
        with doc.create(Subsection('43', numbering=False)):
            with doc.create(Figure(position='h!')) as triangle_pic:
                image_filename = os.path.join(os.path.dirname(__file__),
                                              'tri1.jpg')
                triangle_pic.add_image(image_filename, width='255px')
Esempio n. 26
0
    def make_pdf(self, jobid, filename, dirname):
        """
        Makes a PDF for a given job id. It retrieves data from Prometheus HTTP API and calls make_plot() as well as make_pie() in order to make the graphs
        and display resource usage to users.
        Parameters
        ----------
        jobid : integer,
            Slurm job's ID
        filename : string
            File name to save the figure
        dirname : string
            directory name to save the file
        """
        geometry_options = {"right": "2cm", "left": "2cm"}
        fname = CWD + "pdf/" + str(jobid) + "_summary"
        doc = Document(fname, geometry_options=geometry_options)

        metrics = ("jobs_cpu_percent", "jobs_rss", "jobs_read_mb",
                   "jobs_write_mb")

        doc.preamble.append(
            Command("title", "Plots for job " + str(self.__jobid)))
        doc.preamble.append(Command("date", NoEscape(r"\today")))
        doc.append(NoEscape(r"\maketitle"))

        doc.append(
            "This pdf contains plots/pie charts which are representative of your job's usage of HPC resources on CC clusters"
        )
        doc.append(NewPage())

        for item in metrics:
            self.make_plot(item, filename, dirname, True)

            with doc.create(Section("Plot for " + Y_LABELS[item])):

                with doc.create(Figure(position="htbp")) as plot:
                    plot.add_plot(width=NoEscape(r"1\textwidth"))
                    plot.add_caption(Y_LABELS[item] + " variation with time")
                if item == "jobs_cpu_percent":
                    doc.append(
                        "The dashed line on this plot shows the lowest acceptable bound for CPU usage for a job with as many cores as yours"
                    )
            doc.append(NewPage())
            plt.close()

        metrics = ("jobs_user_time", "jobs_system_time")
        title = [Y_LABELS[metric] for metric in metrics]

        self.make_pie(metrics, filename, dirname, True)
        with doc.create(Section("Pie chart for " + " vs  ".join(title))):

            with doc.create(Figure(position="htbp")) as plot:
                plot.add_plot(width=NoEscape(r"1\textwidth"))
                plot.add_caption(", ".join(title) + " proportions")
        doc.append(NewPage())

        plt.close()

        metrics = ("jobs_cpu_time_core", )

        self.make_pie(metrics, filename, dirname, True)

        with doc.create(
                Section("Pie chart for " + Y_LABELS[metrics[0]] +
                        " per core")):
            with doc.create(Figure(position="htbp")) as plot:
                plot.add_plot(width=NoEscape(r"1\textwidth"))
                plot.add_caption(Y_LABELS[metrics[0]] + " proportions")
        doc.append(NewPage())

        plt.close()

        doc.generate_pdf(clean_tex=False)
Esempio n. 27
0
    with doc.create(Section('The fancy stuff')):
        with doc.create(Subsection('Correct matrix equations')):
            doc.append(Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)]))

        with doc.create(Subsection('Beautiful graphs')):
            with doc.create(TikZ()):
                plot_options = 'height=6cm, width=6cm, grid=major'
                with doc.create(Axis(options=plot_options)) as plot:
                    plot.append(Plot(name='model', func='-x^5 - 242'))

                    coordinates = [
                        (-4.77778, 2027.60977),
                        (-3.55556, 347.84069),
                        (-2.33333, 22.58953),
                        (-1.11111, -493.50066),
                        (0.11111, 46.66082),
                        (1.33333, -205.56286),
                        (2.55556, -341.40638),
                        (3.77778, -1169.24780),
                        (5.00000, -3269.56775),
                    ]

                    plot.append(Plot(name='estimate', coordinates=coordinates))

        with doc.create(Subsection('Cute kitten pictures')):
            with doc.create(Figure(position='h!')) as kitten_pic:
                kitten_pic.add_image(image_filename, width='120px')
                kitten_pic.add_caption('Look it\'s on its back')

    doc.generate_pdf('full')
Esempio n. 28
0
    with doc.create(Subsection('Summary Table')):
        with doc.create(LongTabu(fmt, spread="0pt")) as data_table:
            header_row = ['Experiment runs', 'Average Throughput(million events/second)']
            data_table.add_row(header_row, mapper=[bold])
            data_table.add_hline()
            data_table.add_empty_row()
            data_table.end_table_header()

            # Iterates through throughput array and no_file_array and append rescpective run and throughput in the row
            for x, y in np.c_[no_of_file, throughput]:
                row = [x, y]
                data_table.add_row(row)
    doc.append(NoEscape(r'\newpage'))
    # append graph into the pdf report
    with doc.create(Subsection("Graph")):
        with doc.create(Figure(position='h!')) as throughput_chart:
            throughput_chart.add_image(throughput_image_dir, width='450px')

    with doc.create(Subsection("results")):
        doc.append("Over all throughput average (million events/seconds) of")
        doc.append(NoEscape(r'\space'))
        doc.append(path)
        doc.append(NoEscape(r'\space'))
        doc.append("is")
        doc.append(NoEscape(r'\space'))
        doc.append(final_throughput_avg)

doc.append(NoEscape(r'\newpage'))
# latency summary table and chart for latency

with doc.create(
Esempio n. 29
0
t.add_hline(start=None, end=None)

t.add_row(cells=(1, 2), escape=False)

t.add_multicolumn(size=2, align='|c|', content='Multicol', cells=None, 
                  escape=False)
                  
t.add_multirow(size=3, align='*', content='Multirow', hlines=True, cells=None,
               escape=False)

# Command
c = Command('documentclass', arguments=None, options=None, packages=None)

# Figure
f = Figure(data=None, position=None)

f.add_image(filename='', width=r'0.8\textwidth', placement=r'\centering')

f.add_caption('')

# Numpy
v = VectorName(name='')

M = np.matrix([[2, 3, 4],
               [0, 0, 1],
               [0, 0, 2]])
m = Matrix(matrix=M, name='', mtype='p', alignment=None)

# Package
p = Package(name='', base='usepackage', options=None)
Esempio n. 30
0
    def _document_models(self) -> None:
        """Add model summaries to the traceability document.
        """
        with self.doc.create(Section("Models")):
            for model in humansorted(self.system.network.models,
                                     key=lambda m: m.model_name):
                if not isinstance(model, (tf.keras.Model, torch.nn.Module)):
                    continue
                self.doc.append(NoEscape(r'\FloatBarrier'))
                with self.doc.create(Subsection(f"{model.model_name}")):
                    if isinstance(model, tf.keras.Model):
                        # Text Summary
                        summary = []
                        model.summary(line_length=92,
                                      print_fn=lambda x: summary.append(x))
                        summary = "\n".join(summary)
                        self.doc.append(Verbatim(summary))
                        with self.doc.create(Center()):
                            self.doc.append(
                                HrefFEID(FEID(id(model)), model.model_name))

                        # Visual Summary
                        # noinspection PyBroadException
                        try:
                            file_path = os.path.join(
                                self.resource_dir,
                                "{}_{}.pdf".format(self.report_name,
                                                   model.model_name))
                            dot = tf.keras.utils.model_to_dot(
                                model, show_shapes=True, expand_nested=True)
                            # LaTeX \maxdim is around 575cm (226 inches), so the image must have max dimension less than
                            # 226 inches. However, the 'size' parameter doesn't account for the whole node height, so
                            # set the limit lower (100 inches) to leave some wiggle room.
                            dot.set('size', '100')
                            dot.write(file_path, format='pdf')
                        except Exception:
                            file_path = None
                            print(
                                f"FastEstimator-Warn: Model {model.model_name} could not be visualized by Traceability"
                            )
                    elif isinstance(model, torch.nn.Module):
                        if hasattr(model, 'fe_input_spec'):
                            # Text Summary
                            # noinspection PyUnresolvedReferences
                            inputs = model.fe_input_spec.get_dummy_input()
                            self.doc.append(
                                Verbatim(
                                    pms.summary(
                                        model.module if
                                        self.system.num_devices > 1 else model,
                                        inputs,
                                        print_summary=False)))
                            with self.doc.create(Center()):
                                self.doc.append(
                                    HrefFEID(FEID(id(model)),
                                             model.model_name))
                            # Visual Summary
                            # Import has to be done while matplotlib is using the Agg backend
                            old_backend = matplotlib.get_backend() or 'Agg'
                            matplotlib.use('Agg')
                            # noinspection PyBroadException
                            try:
                                # Fake the IPython import when user isn't running from Jupyter
                                sys.modules.setdefault('IPython', MagicMock())
                                sys.modules.setdefault('IPython.display',
                                                       MagicMock())
                                import hiddenlayer as hl
                                with Suppressor():
                                    graph = hl.build_graph(
                                        model.module if
                                        self.system.num_devices > 1 else model,
                                        inputs)
                                graph = graph.build_dot()
                                graph.attr(
                                    rankdir='TB'
                                )  # Switch it to Top-to-Bottom instead of Left-to-Right
                                # LaTeX \maxdim is around 575cm (226 inches), so the image must have max dimension less
                                # than 226 inches. However, the 'size' parameter doesn't account for the whole node
                                # height, so set the limit lower (100 inches) to leave some wiggle room.
                                graph.attr(size="100,100")
                                graph.attr(margin='0')
                                file_path = graph.render(
                                    filename="{}_{}".format(
                                        self.report_name, model.model_name),
                                    directory=self.resource_dir,
                                    format='pdf',
                                    cleanup=True)
                            except Exception:
                                file_path = None
                                print(
                                    "FastEstimator-Warn: Model {} could not be visualized by Traceability"
                                    .format(model.model_name))
                            finally:
                                matplotlib.use(old_backend)
                        else:
                            file_path = None
                            self.doc.append(
                                "This model was not used by the Network during training."
                            )
                    if file_path:
                        with self.doc.create(Figure(position='ht!')) as fig:
                            fig.append(
                                Label(
                                    Marker(name=str(FEID(id(model))),
                                           prefix="model")))
                            fig.add_image(
                                os.path.relpath(file_path,
                                                start=self.save_dir),
                                width=NoEscape(
                                    r'1.0\textwidth,height=0.95\textheight,keepaspectratio'
                                ))
                            fig.add_caption(
                                NoEscape(
                                    HrefFEID(FEID(id(model)),
                                             model.model_name).dumps()))
Esempio n. 31
0
def fill_document(doc):
    with doc.create(Section('Basic Concept Problems', numbering=True)):
        # Question 1: prove the pythagorean theorem
        with doc.create(Figure(position='h!')) as pythagorean_pic:
            image_filename = os.path.join(os.path.dirname(__file__),
                                          'pythagorean.jpg')
            pythagorean_pic.add_image(image_filename, width='350px')

        # Question 2: prove the law of cosines
        with doc.create(Figure(position='h!')) as tri_pic:
            image_filename = os.path.join(os.path.dirname(__file__),
                                          'triangle.jpg')
            tri_pic.add_image(image_filename, width='100px')
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'&\textnormal{Given a triangle with sides A, B, and C }')
                agn.append(
                    r'\textnormal{with height h and an angle } \theta\\')
                agn.append(
                    r'& \textnormal{we know that the left triangle will}')
                agn.append(r'\textnormal{ have the property } m^2+h^2=B^2\\')
                agn.append(
                    r'&\textnormal{and the right triangle will have the property }'
                )
                agn.append(
                    r' h^2 + n^2 = C^2\\ &\textnormal{by the pythagorean theorem.}'
                )
                agn.append(r'\textnormal{ Therefore:}\\')
                agn.append(r'&n = A - m\\')
                agn.append(r'&\textnormal{and } h^2 + (A-m)^2 = C^2\\')
                agn.append(r'&B^2-m^2+A^2-2Am+m^2 = C^2\\')
                agn.append(
                    r'&\textnormal{Furthermore, we know } cos\theta = \frac{m}{B}\\'
                )
                agn.append(r'&\textnormal{Therefore:}\\')
                agn.append(r'&B^2+A^2 -2ABcos\theta = C^2')

    with doc.create(Section('9.3', numbering=False)):
        with doc.create(Subsection('20', numbering=False)):
            with doc.create(Figure(position='h!')) as tri2_pic:
                image_filename = os.path.join(os.path.dirname(__file__),
                                              'tri2.jpg')
                tri2_pic.add_image(image_filename, width='150px')
                with doc.create(Alignat(numbering=False, escape=False)) as agn:
                    agn.append(r'\vec{u} &= <-2,3,2>\\')
                    agn.append(r'\vec{v} &= <3,-2,-4>\\')
                    agn.append(r'\vec{w} &= <1,1,-2>\\')
                    agn.append(r'\textnormal{The angle at D:} \\')
                    agn.append(
                        r'<-2,3,2>\cdot<1,1,-2> &=\|<-2,3,2>\| \|<1,1,-2>\|cosd\\'
                    )
                    agn.append(r'-3 &= \sqrt{17}\sqrt{6}cosd\\')
                    agn.append(r'cos^-1(\frac{-3}{\sqrt{102}}) &= d\\')
                    agn.append(r'd & \approx{107.28}^\circ\\')

                    agn.append(r'\textnormal{The angle at E:} \\')
                    agn.append(
                        r'-(<-2,3,2>)\cdot<3,-2,-4> &=\|<-2,3,2>\| \|<3,-2,-4>\|cose\\'
                    )
                    agn.append(r'20 &= \sqrt{17}\sqrt{29}cose\\')
                    agn.append(r'cos^-1(\frac{20}{\sqrt{493}}) &= e\\')
                    agn.append(r'e & \approx{25.74}^\circ\\')

                    agn.append(r'\textnormal{The angle at F:} \\')
                    agn.append(
                        r'-(<1,1,-2>)\cdot-(<3,-2,-4>) &=\|<1,1,-2>\| \|<3,-2,-4>\|cosf\\'
                    )
                    agn.append(r'9 &= \sqrt{6}\sqrt{29}cosf\\')
                    agn.append(r'cos^-1(\frac{9}{\sqrt{174}}) &= f\\')
                    agn.append(r'f & \approx{46.98}^\circ\\')

        # projections
        with doc.create(Subsection('30', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(r'\|a\| &= \sqrt{5}\\')
                agn.append(
                    r'comp_a b &= \frac{a \cdot b}{\|a\|} = \frac{-4+2}{\sqrt{5}} = \frac{-2}{\sqrt{5}}\\'
                )
                agn.append(r'\textnormal{The vector projection is:}\\')
                agn.append(
                    r'proj_a b &= \frac{-2}{\sqrt{5}}\frac{<1,2>}{\sqrt{5}} = \frac{-2}{5} <1,2>\\'
                )
                agn.append(r'proj_a b &= <\frac{-2}{5}, \frac{-4}{5}>')
        with doc.create(Subsection('31', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'a = <2,-1,4> & \textnormal{ and } b = <0,1,\frac{1}{2}>\\'
                )
                agn.append(r'\| a \| &= \sqrt{4+1+16} = \sqrt{21}\\')
                agn.append(
                    r'comp_a b &= \frac{a \cdot b}{\sqrt{21}} = \frac{1}{\sqrt{21}}\\'
                )
                agn.append(r'\textnormal{The vector projection is:}\\')
                agn.append(
                    r'proj_a b &= \frac{1}{\sqrt{21}}\frac{<2,-1,4>}{\sqrt{21}} = \frac{1}{21}<2,-1,4>\\'
                )
                agn.append(
                    r'proj_a b &= <\frac{2}{21},\frac{-1}{21},\frac{4}{21}>\\')
        with doc.create(Subsection('43', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\intertext{Let all sides of the cube be length = 1, and let the edges lie along the x, y, z axis}\\'
                )
                agn.append(
                    r'\text{The diagonal vector, }\vec{d}\text{ from (0,0,0) to (1,1,1) = <1,1,1>}\\'
                )
                agn.append(
                    r'\text{Let the unit vector } \vec{k} = <0,0,1> \text{be a side.}\\'
                )
                agn.append(
                    r'\text{The angle between } \vec{d} \text{ and } \vec{k} \text{ is:}\\'
                )
                agn.append(
                    r'cos\theta &= \frac{<0,0,1> \cdot <1,1,1>}{\|u\|\|v\|}\\')
                agn.append(r'&= \frac{0+0+1}{\sqrt{1}\sqrt{3}}\\')
                agn.append(r'&= \frac{1}{\sqrt{3}} \\')
                agn.append(r'\theta &= cos^-1 \frac{1}{\sqrt{3}}\\')
                agn.append(r'&= 54.74^\circ')
        with doc.create(Subsection('46', numbering=False)):
            with doc.create(Figure(position='h!')) as ang_pic:
                image_filename = os.path.join(os.path.dirname(__file__),
                                              'ang1.jpg')
                ang_pic.add_image(image_filename, width='150px')
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(r'cos\alpha &= \frac{a \cdot c}{\|a\| \|c\|}\\')
                agn.append(
                    r'&= \frac{a \cdot (\|a\|b+\|b\|a))}{\|a\| \|c\|}\\')
                agn.append(
                    r'&= \frac{a \cdot \|a\|a \cdot b + \|b\|a \cdot a}{\|a\| \|c\|}\\'
                )
                agn.append(
                    r'&= \frac{\|a\|a \cdot b + \|b\| \|a\|^2}{\|a\| \|c\|}\\')
                agn.append(r'&= \frac{a \cdot b + \|b\| \|a\|}{\|c\|}\\')
                agn.append(r'cos\beta &= \frac{b \cdot c}{\|b\| \|c\|}\\')
                agn.append(
                    r'&= \frac{b \cdot (\|a\|b+\|b\|a))}{\|b\| \|c\|}\\')
                agn.append(
                    r'&= \frac{\|a\| b \cdot b + \|b\|a \cdot b}{\|b\| \|c\|}\\'
                )
                agn.append(
                    r'&= \frac{\|a\| \|b\|^2 + \|b\| a \cdot b}{\|b\| \|c\|}\\'
                )
                agn.append(r'&= \frac{\|a\| \|b\| + a \cdot b}{\|c\|}\\')
                agn.append(
                    r'\textnormal{Now we can see that } cos \alpha = cos \beta\\'
                )
                agn.append(
                    r' \frac{a \cdot b + \|b\| \|a\|}{\|c\|} &= \frac{\|a\| \|b\| + a \cdot b}{\|c\|}\\'
                )

    with doc.create(Section('9.4', numbering=False)):
        with doc.create(Subsection('20', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\intertext{The cross product is orthogonol to both i+j+k and 2i+k:}\\'
                )
                agn.append(
                    r'i+j+k = <1,1,1> & \textnormal{ and } 2i+k = <2,0,1>\\')
                agn.append(
                    r'<1,1,1>\times <2,0,1> &= (1-0) \vec{i}+(2-1) \vec{j}+(0-2) \vec{k}\\'
                )
                agn.append(r'<1,1,1>\times <2,0,1> &= <1,1,-2>\\')
                agn.append(
                    r'\intertext{Divide by the magnitude to find the unit vector:}\\'
                )
                agn.append(
                    r'\textnormal{unit vector } &= \frac{<1,1,-2>}{\sqrt{1+1+4}}\\'
                )
                agn.append(
                    r'&= <\frac{1}{\sqrt{6}},\frac{1}{\sqrt{6}},\frac{-2}{\sqrt{6}}>\\'
                )
                agn.append(
                    r'\intertext{The second unit vector would be the negative of the first:}\\'
                )
                agn.append(
                    r'&= <\frac{-1}{\sqrt{6}},\frac{-1}{\sqrt{6}},\frac{2}{\sqrt{6}}>\\'
                )

        with doc.create(Subsection('22', numbering=False)):
            with doc.create(Figure(position='h!')) as para_pic:
                image_filename = os.path.join(os.path.dirname(__file__),
                                              'para1.jpg')
                para_pic.add_image(image_filename, width='150px')
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\vec{u} = <2,5,0> \textnormal{ and } \vec{v} = <0,1,3>\\'
                )
                agn.append(r'A &= \|<2,5,0> \times <0,1,3>\| \\')
                agn.append(r'A &= \|<-15,6,-2>\| \\')
                agn.append(r'A &= \sqrt{265}')

        with doc.create(Subsection('24', numbering=False)):
            with doc.create(Subsection('a)', numbering=False)):
                with doc.create(Alignat(numbering=False, escape=False)) as agn:
                    agn.append(
                        r'\vec{PQ} = <1,2,1> \textnormal{ and } \vec{PR} = <5,0,-2>\\'
                    )
                    agn.append(
                        r'\textnormal{The vector orthogonol to the plane = } \vec{PQ} \times \vec{PR}\\'
                    )
                    agn.append(r'\vec{PQ} \times \vec{PR} = <-5,7,-10>\\')
            with doc.create(Subsection('b)', numbering=False)):
                with doc.create(Alignat(numbering=False, escape=False)) as agn:
                    agn.append(r'A &= \frac{\|<-5,7,-10>\|}{2}\\')
                    agn.append(r'A &= \frac{\sqrt{174}}{2} \approx 6.6')

        with doc.create(Subsection('33', numbering=False)):
            with doc.create(Subsection('a)', numbering=False)):
                with doc.create(Alignat(numbering=False, escape=False)) as agn:
                    agn.append(r'd &= \|b\|sin\theta\\')
                    agn.append(r'&=\frac{\|a\|}{\|a\|}\|b\|sin\theta\\')
                    agn.append(r'&= \frac{\|a\|\|b\|sin\theta}{\|a\|}\\')
                    agn.append(r'&= \frac{\|a \times b\|}{\|a\|}\\')
            with doc.create(Subsection('b)', numbering=False)):
                with doc.create(Alignat(numbering=False, escape=False)) as agn:
                    agn.append(
                        r'\vec{a} = <-1,-2,-1> \textnormal{ and } \vec{b} = <1, -5, -7>\\'
                    )
                    agn.append(
                        r'd &= \frac{\|<-1,-2,-1> \times <1, -5, -7>\|}{\sqrt{1+4+1}}\\'
                    )
                    agn.append(r'&= \frac{\|<9,-15,7>\|}{\sqrt{6}}\\')
                    agn.append(r'&= \frac{\sqrt{355}}{\sqrt{6}}\\')
                    agn.append(r'd & \approx 7.69\\')

    with doc.create(Section('9.5', numbering=False)):
        with doc.create(Subsection('2', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\textnormal{vector equation } &= <6,-5,2> + t<1,3,\frac{-2}{3}>\\'
                )
                agn.append(r'&= <6+t, -5+3t, 2+\frac{-2}{3}t>\\')
                agn.append(r'\textnormal{The parametric equations are:}\\')
                agn.append(r'x(t) &= 6+t\\')
                agn.append(r'y(t) &= -5+3t\\')
                agn.append(r'z(t) &= 2+\frac{-2}{3}t\\')
        with doc.create(Subsection('5', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(r'x(t) &= 1+t\\')
                agn.append(r'y(t) &= 3t\\')
                agn.append(r'z(t) &= 6+t\\')
        with doc.create(Subsection('10', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\vec{n_1} = <1,2,3> \textnormal{ and } \vec{n_2} = <1,-1,1>\\'
                )
                agn.append(
                    r'<1,2,3> \times <1,-1,1> \textnormal{is a line parallel to the line of intersection.}\\'
                )
                agn.append(r'<1,2,3> \times <1,-1,1> = <5,2,-3>\\')
                agn.append(
                    r'\textnormal{Plug in z=0 to solve x, y and find a point on the line of intersection}\\'
                )
                agn.append(r'x+2y=1 \textnormal{ and } x-y &=1\\')
                agn.append(r'\textnormal{This gives us } 3y &= 0 \\')
                agn.append(
                    r'\textnormal{Therefore (1,0,0) lies on the line of intersection and the symmetric equations are:}\\'
                )
                agn.append(r'\frac{x-1}{5} &= \frac{y}{2} = \frac{-z}{3}\\')
                agn.append(r'\textnormal{And the parametric equations are:}\\')
                agn.append(r'x(t) &= 1+5t\\')
                agn.append(r'y(t) &= 2t\\')
                agn.append(r'z(t) &= -3t\\')
        with doc.create(Subsection('18', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\textnormal{Check ratio of coefficients to test if parallel:}\\'
                )
                agn.append(r'\frac{1}{-1} = \frac{3}{1} = \frac{-1}{3}\\')
                agn.append(
                    r'-1 \neq 3 \neq -3 \textnormal{therefore the lines are NOT parallel}\\'
                )
                agn.append(
                    r'\textnormal{Solve system of equations to test if intersecting:}\\'
                )
                agn.append(r'1 +2t &= -1+s\\')
                agn.append(r'3t &= 4+s\\')
                agn.append(r'2-t &= 1+3s\\')
                agn.append(r'\textnormal{Solve the first equation for t:}\\')
                agn.append(r'2t &=-2+s\\')
                agn.append(r't &= -1 + \frac{s}{2}\\')
                agn.append(r'\textnormal{Plug into the second equation:}\\')
                agn.append(r'3(-1+\frac{s}{2}) = 4+s\\')
                agn.append(r'-3+\frac{3s}{2} = 4+s\\')
                agn.append(r'\frac{s}{2} = 7\\')
                agn.append(r's = 14\\')
                agn.append(
                    r'\textnormal{Plug s=14 this into the equation for t:}\\')
                agn.append(r't=-1+\frac{14}{2} = -6\\')
                agn.append(
                    r'\textnormal{Plug s=14 and t=-6 into the third equation:}\\'
                )
                agn.append(r'2+-6 = 1+3(14)\\')
                agn.append(
                    r'-4 \neq 43 \textnormal{therefore the lines do not intersect.}\\'
                )
                agn.append(
                    r'\textnormal{Since the lines are not parallel and do not intersect, they must be skew.}\\'
                )
        with doc.create(Subsection('25', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'P(0,1,1) \textnormal{ and }Q(1,0,1) \textnormal{ and }R(1,1,0)\\'
                )
                agn.append(r'\vec{PQ} = <1-0,0-1,1-1> &= <1,-1,0>\\')
                agn.append(r'\vec{PR} = <1-0,1-1,0-1> &= <1,0,-1>\\')
                agn.append(
                    r'\textnormal{Take the cross product to get the coefficients of the plane equation:}\\'
                )
                agn.append(r'<1,-1,0> \times <1,0,-1> = <1,1,1> \\')
                agn.append(
                    r'\textnormal{Use P as the point for the equation of the plane:}\\'
                )
                agn.append(r'1(x-0)+1(y-1)+1(z-1) &= 0\\')
                agn.append(r'x+y+z &=2\\')
        with doc.create(Subsection('27', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\textnormal{The points P(6,0,-2) and Q(4,3,7) are on the plane.}\\'
                )
                agn.append(
                    r'\textnormal{Set t=1 to get a third point on the plane, R(2,8,11)}\\'
                )
                agn.append(r'\vec{PQ} = <4-6,3-0,7-(-2)> = <-2,3,9>\\')
                agn.append(r'\vec{PR} = <2-6,8-0,11-(-2)> = <-4,8,13>\\')
                agn.append(
                    r'\textnormal{Take the cross product to get the coefficients of the plane equation:}\\'
                )
                agn.append(r'<-2,3,9> \times <-4,8,13> = <-33,-10,-4>\\')
                agn.append(
                    r'\textnormal{Use P as the point for the equation of the plane:}\\'
                )
                agn.append(r'-33(x-6)+-10(y-0)+-4(z+2) &= 0\\')
                agn.append(r'-33x+198-10y-4z-8 &= 0\\')
                agn.append(r'-33x-10y-4z &= -190')
        with doc.create(Subsection('32', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\textnormal{Let Q be the plane that we are looking for.}\\'
                )
                agn.append(
                    r'\textnormal{Set z=0 to get a point on the line of intersection:}\\'
                )
                agn.append(r'(1,3,0)\\')
                agn.append(
                    r'\textnormal{To get a normal vector for Q, take the cross product of two vectors parallel to Q.}\\'
                )
                agn.append(
                    r'\textnormal{The normal vector of the plane perpendicular to Q is parallel to Q:}\\'
                )
                agn.append(r'<1,1,-2>\\')
                agn.append(
                    r'\textnormal{Get a second vector parallel to Q by taking the cross product of the normal vectors }\\'
                )
                agn.append(
                    r'\textnormal{of the two planes that form the line of intersection that Q passes through.}\\'
                )
                agn.append(r'<1,0,-1> \times <0,1,2> &= <1,-2,1>\\')
                agn.append(
                    r'\textnormal{Now take the cross product of these two vectors:}\\'
                )
                agn.append(r'<1,1,-2> \times <1,-2,1> &= <-3,-3,-3>\\')
                agn.append(
                    r'\textnormal{Plug these into the plane equation:}\\')
                agn.append(r'-3(x-1)-3(y-3)-3(z-0) &= 0\\')
                agn.append(r'-3x+3-3y+9-3z &= 0\\')
                agn.append(r'-3x-3y-3z &= -12\\')
                agn.append(r'-3(x+y+z) &= -12\\')
                agn.append(r'x+y+z &= 4\\')
        with doc.create(Subsection('56', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'd &= \frac{|1(6)+(-2)(0)+(-4)(-2) + (-8)|}{\sqrt{1^2+(-2)^2+(-4)^2}}\\'
                )
                agn.append(r'&= \frac{|6+8-8|}{\sqrt{21}}\\')
                agn.append(r'&= \frac{6}{\sqrt{21}}\\ ')
                agn.append(r'd &\approx 1.31\\')
        with doc.create(Subsection('58', numbering=False)):
            with doc.create(Alignat(numbering=False, escape=False)) as agn:
                agn.append(
                    r'\textnormal{To find the distance we need a point on one plane.}\\'
                )
                agn.append(
                    r'\textnormal{Plug in z=0 to the first equation.}\\')
                agn.append(r'0 &= 4y - 2x\\')
                agn.append(r'y &= \frac{1}{2}x\\')
                agn.append(
                    r'\textnormal{Therefore the point (2,1,0) is on the first plane.}\\'
                )
                agn.append(
                    r'\textnormal{Now we can use the distance formula.}\\')
                agn.append(
                    r'd &= \frac{|3(2) + -6(1) + 9(0) + -1|}{\sqrt{3^2+(-6)^2+9^2}}\\'
                )
                agn.append(r'&= \frac{|6-6-1|}{\sqrt{126}}\\')
                agn.append(r'&= \frac{1}{\sqrt{126}}\\')
                agn.append(r'd & \approx .09\\')
 def append_cross_section_figure(self, doc, tpdf):
     with doc.create(Section(tpdf.step_split)):
         with doc.create(Figure(position='H')) as fig_sectransv:
             fig_sectransv.add_image("figs\\sectransv", width='500px')
             fig_sectransv.add_caption(NoEscape(tpdf.figure_label))
Esempio n. 33
0
def report(context, json_report, json_varreport, rulegraph_img):

    config = json_report
    sample_config = json.load(open(json_report))
    var_config = json.load(open(get_config(json_varreport)))

    tex_path = os.path.abspath(
        os.path.join(sample_config["analysis"]["analysis_dir"],
                     "delivery_report"))

    if not rulegraph_img:
        rulegraph_img = sample_config['analysis']['dag']

    os.makedirs(tex_path, exist_ok=True)

    geometry_options = {
        "head": "40pt",
        "headheight": "130pt",
        "headsep": "1cm",
        "margin": "1.5cm",
        "bottom": "1.5cm",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    doc.packages.append(Package('lscape'))
    doc.packages.append(Package('longtable'))
    doc.packages.append(Package('float'))
    doc.packages.append(Package('caption', options='labelfont=bf'))
    doc.append(
        NoEscape(
            r'\captionsetup[table]{labelsep=space, justification=raggedright, singlelinecheck=off}'
        ))

    #Add first page style
    first_page = PageStyle("header", header_thickness=1)

    #Add Header
    with first_page.create(Head("C")) as mid_header:

        with mid_header.create(
                MiniPage(width=NoEscape(r"0.2\textwidth"),
                         pos='c')) as logo_wrapper:
            logo_file = os.path.join(os.path.dirname(__file__), '..',
                                     'assests/cg.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=50px",
                                  filename=logo_file))

        with mid_header.create(
                Tabularx(
                    "p{3cm} p{2cm} X X p{4cm} p{3cm}",
                    width_argument=NoEscape(r"0.8\textwidth"))) as mid_table:
            mid_table.add_row(
                [MultiColumn(6, align='r', data=simple_page_number())])
            mid_table.add_row([
                MultiColumn(6,
                            align='c',
                            data=MediumText("Molecular report on"))
            ])
            mid_table.add_row([
                MultiColumn(6,
                            align='c',
                            data=MediumText(get_sample_name(config)))
            ])
            mid_table.add_empty_row()
            mid_table.add_row([
                'gender', "NA", " ", " ", 'Sample recieved:',
                sample_config['analysis']['date']['sample_received']
            ])
            mid_table.add_row([
                'tumor type', "NA", " ", " ", 'Analysis completion:',
                sample_config['analysis']['date']['analysis_finish']
            ])
            mid_table.add_row([
                'analysis type', "NA", " ", " ", 'PDF Report date:',
                datetime.now().strftime("%Y-%m-%d %H:%M")
            ])
            mid_table.add_row(
                ['sample type', "NA", " ", " ", 'Delivery date', "NA"])
            mid_table.add_row([
                'sample origin', "NA", " ", " ", 'Analysis:',
                r'BALSAMIC v' + sample_config['analysis']['BALSAMIC']
            ])

    doc.preamble.append(first_page)

    #End First page

    #    doc.preamble.append(
    #        Command(
    #            'title',
    #            NoEscape(r'BALSAMIC v' + sample_config["analysis"]["BALSAMIC"] +
    #                     r'\\ \large Developer Report')))
    #    doc.preamble.append(
    #        Command('author', 'Patient ID: ' + get_sample_name(config)))
    #    doc.preamble.append(Command('date', NoEscape(r'\today')))
    #    doc.append(NoEscape(r'\maketitle'))
    doc.change_document_style("header")

    with doc.create(Section(title='Analysis report', numbering=True)):

        with doc.create(
                Subsection('Summary of variants and variant callers',
                           numbering=True)):
            doc.append(
                "Placeholder for text about BAM alignment metrics and variant callers. Here comes the info on reads, "
                +
                "QC metrics, align metrics, and general sample information. preferabily in table format."
            )
            doc.append("\n")

            summary_tables = ["TMB", "VarClass", "VarCaller", "VarCallerClass"]
            for i in summary_tables:

                shellcmd = [
                    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 "..", "..", "scripts/VariantReport.R")
                ]
                shellcmd.extend([
                    "--infile", sample_config["vcf"]["merged"]["SNV"],
                    "--genomeSize", sample_config["bed"]["genome_size"],
                    "--type", "latex", "--mode", i, "--outfile",
                    os.path.join(tex_path,
                                 sample_config['analysis']['sample_id'])
                ])
                print(" ".join(shellcmd))

                outTab = subprocess.check_output(shellcmd)
                doc.append(
                    NoEscape(
                        outTab.decode('utf-8').replace("\\centering",
                                                       "\\small")))
            doc.append(NoEscape(r'\normalsize'))
            doc.append(NewPage())

        with doc.create(Subsection("Summary of MVL report", numbering=True)):
            doc.append(
                "Placeholder for general description of MVL settings. A mention to summary "
                +
                "pipeline, summary of MVL settings. Gene coverage for identified genes should go here. Figures!"
            )
            outCov = dict()

            cmd_param = defaultdict(list)
            J = defaultdict(list)
            for i in var_config["filters"]:
                cmd_param["TUMOR_DP"].append(
                    var_config["filters"][i]["TUMOR"]["DP"])
                cmd_param["TUMOR_AD"].append(
                    var_config["filters"][i]["TUMOR"]["AD"])
                cmd_param["TUMOR_AFmax"].append(
                    var_config["filters"][i]["TUMOR"]["AF_max"])
                cmd_param["TUMOR_AFmin"].append(
                    var_config["filters"][i]["TUMOR"]["AF_min"])
                cmd_param["TUMOR_inMVL"].append(
                    var_config["filters"][i]["in_mvl"])
                cmd_param["var_type"].append(",".join(
                    ["SNP", "INDEL", "MNP", "OTHER"]))
                cmd_param["varcaller"].append(",".join(
                    var_config["filters"][i]["variantcaller"]))
                cmd_param["ann"].append(
                    ",".join(var_config["filters"][i]["annotation"]["SNV"]) +
                    "," +
                    ",".join(var_config["filters"][i]["annotation"]["INDEL"]))
                cmd_param["name"].append(i.replace("_", "\_"))
                cmd_param["outfile_tex"].append(tex_path + "/" + i + ".tex")
                cmd_param["outfile_gene"].append(tex_path + "/" + i +
                                                 ".genelist")

            for i in cmd_param:
                J[i] = ";".join(cmd_param[i])

            shellcmd = [
                os.path.join(os.path.dirname(os.path.abspath(__file__)), "..",
                             "..", "scripts/VariantReport.R")
            ]
            shellcmd.extend([
                "--infile", "'" + sample_config["vcf"]["merged"]["SNV"] + "'",
                "--dp", "'" + J["TUMOR_DP"] + "'", "--tumorad",
                "'" + J["TUMOR_AD"] + "'", "--afmax",
                "'" + J["TUMOR_AFmax"] + "'", "--afmin",
                "'" + J["TUMOR_AFmin"] + "'", "--inMVL",
                "'" + J["TUMOR_inMVL"] + "'", "--exclusiveSets", "TRUE",
                "--vartype", "'" + J["var_type"] + "'", "--varcaller",
                "'" + J["varcaller"] + "'", "--ann", "'" + J["ann"] + "'",
                "--name", "'" + J["name"] + "'", "--type", "latex"
            ])

            subprocess.check_output(
                " ".join(shellcmd +
                         ["--outfile", "'" + J["outfile_tex"] + "'"]),
                shell=True)

            print(" ".join(shellcmd +
                           ["--outfile", "'" + J["outfile_tex"] + "'"]))
            subprocess.check_output(" ".join(shellcmd + [
                "--outfile", "'" + J["outfile_gene"] + "'", "--exportGene", "T"
            ]),
                                    shell=True)

            for c, i in enumerate(var_config["filters"]):
                with doc.create(
                        Subsubsection(var_config["filters"][i]["name"],
                                      numbering=True)):
                    print(cmd_param["outfile_tex"])
                    fname = cmd_param["outfile_tex"][c]
                    if os.stat(fname).st_size > 10:
                        #get gene list
                        with open(cmd_param["outfile_gene"][c]) as myfile:
                            genes = myfile.read().replace('\n', '')

                        with open(fname, 'r') as myfile:
                            data = myfile.read()  #.replace('\n', '')

                        #doc.append(NoEscape(r'\begin{landscape}'))
                        #longtable instead of tabular makes the table span multiple pages, but the header doesn't span. Occasionally
                        #the alignment also is messed up. There must be a hidden package conflict OR general alignment issues.
                        #doc.append(NoEscape(varreport.replace("{tabular}","{longtable}")))
                        doc.append(
                            NoEscape(
                                data.replace("\\centering", "\\scriptsize")))

                        for s in sample_config["bed"]["exon_cov"]:
                            shellcmd = [
                                os.path.join(
                                    os.path.dirname(os.path.abspath(__file__)),
                                    "..", "scripts/CoverageRep.R")
                            ]
                            shellcmd.extend([
                                "--infile",
                                sample_config["bed"]["exon_cov"][s],
                                "--genename", genes, "--name",
                                s.replace("_", "\_"), "--type", "latex"
                            ])
                            outCov = subprocess.check_output(shellcmd)

                            doc.append(
                                NoEscape(
                                    outCov.decode('utf-8').replace(
                                        "\\centering", "\\scriptsize")))
                        #doc.append(NoEscape(r'\end{landscape}'))
                    else:
                        doc.append("No variants were found for this filter")

#                doc.append(NoEscape(r'\normalsize'))

            doc.append(NewPage())

        with doc.create(Subsection('Coverage report')):
            for s in sample_config["bed"]["target_cov"]:
                with doc.create(Figure(position='h!')) as cov_img:
                    covplot = ".".join(
                        [os.path.join(tex_path, s), "Coverage.pdf"])
                    shellcmd = [
                        os.path.join(
                            os.path.dirname(os.path.abspath(__file__)), "..",
                            "..", "scripts/CoveragePlot.R")
                    ]
                    shellcmd.extend([
                        "--infile", sample_config["bed"]["target_cov"][s],
                        "--outfile", covplot, "--title",
                        s.replace("_", "\_")
                    ])
                    subprocess.check_output(shellcmd)
                    cov_img.add_image(covplot, width='450px')
                    cov_img.add_caption('Coverage report for sample ' +
                                        s.replace("_", "\_"))

            doc.append(NewPage())
        with doc.create(Subsection('Analysis pipeline')):
            with doc.create(Figure(position='h!')) as pipeline_img:
                pipeline_img.add_image(rulegraph_img, width='450px')
                pipeline_img.add_caption('BALSAMIC pipeline')
            doc.append(NewPage())

    with doc.create(Section(title="Appendix", numbering=True)):
        with doc.create(Subsection("MVL settings", numbering=True)):
            fmt = "p{3cm}" * (len(var_config["filters"]) + 1)
            with doc.create(Tabular(fmt)) as data_table:
                header_row1 = [""]
                for i in var_config["filters"]:
                    header_row1.append(var_config["filters"][i]["name"])
                data_table.add_hline()
                data_table.add_row(header_row1,
                                   mapper=[bold],
                                   color="lightgray")
                data_table.add_hline()
                data_table.add_empty_row()
                column = list(var_config["filters"][next(
                    iter(var_config["filters"]))]["TUMOR"].keys())
                for i in column:
                    row = [i]
                    for j in var_config["filters"]:
                        row.append(var_config["filters"][j]["TUMOR"][i])
                    data_table.add_row(row)

                row = ["MVL"]
                for i in var_config["filters"]:
                    row.append(var_config["filters"][i]["in_mvl"])

                row = ["Variantcallers"]
                for i in var_config["filters"]:
                    row.append("\n".join(
                        var_config["filters"][i]["variantcaller"]))
                data_table.add_row(row)
                data_table.add_hline()

        with doc.create(
                Subsection("Bioinformatic tool in pipeline", numbering=True)):
            doc.append(
                "The following Bioinformatic tools were used in the analysis:\n\n"
            )
            with doc.create(Tabular("p{4cm}p{4cm}")) as data_table:
                data_table.add_hline()
                conda_env = glob.glob(
                    os.path.join(os.path.dirname(os.path.abspath(__file__)),
                                 "..", "..", "conda_yaml/*.yaml"))

                pkgs = get_package_split(conda_env)

                data_table.add_row(["Package", "Version"], color="lightgray")
                data_table.add_hline()
                data_table.add_row(
                    ["BALSAMIC", sample_config['analysis']['BALSAMIC']])

                for k, v in pkgs.items():
                    data_table.add_row([k, v])
            doc.append(NewPage())

    print(tex_path)
    doc.generate_tex(os.path.join(tex_path, get_sample_name(config)))
    #    doc.generate_pdf(
    #        os.path.join(tex_path, get_sample_name(config)), clean_tex=False)
    shellcmd = [
        "pdflatex", "-output-directory=" + tex_path,
        os.path.join(tex_path, get_sample_name(config)) + ".tex", "1>",
        "/dev/null"
    ]
    #generate_pdf doesn't run AUX files properly and ends up with incorrect total page numbers. So subprocess for
    #pdflatex is called twice instead.

    print(" ".join(shellcmd))
    subprocess.run(" ".join(shellcmd), shell=True)
    subprocess.run(" ".join(shellcmd), shell=True)
Esempio n. 34
0
def result_to_score(arr,
                    doc,
                    arr_name="",
                    n_class=5,
                    sort="asc",
                    sigma=2.5,
                    iqr_factor=1.5,
                    outliers_method="z-score"):
    '''
	convert continuous value to ranged score 
	:param str arr: input result array
	:param sec: pylatex document object
	:param str arr_name: array name
	:param str n_class: number of score classes
	:param str sort: "asc" or "dsc", order of the class count with ascending or descending order
	:param float sigma: standard deviation of the data in z-score outliers removal
	:param float iqr_factor: factor for iqr outliers removal
	:param str outliers_method: "z-score" or "iqr"
	:type sigma: float
	:return: arr score: array of converted score
	:rtype: None
	'''

    # remove outliners
    if outliers_method == "z-score":
        z = np.abs(stats.zscore(arr))
        arr_filtered = arr[(z < sigma)]
    elif outliers_method == "iqr":
        Q1 = np.quantile(arr, 0.25)
        Q3 = np.quantile(arr, 0.75)
        IQR = Q3 - Q1
        arr_filtered = arr[~((arr < (Q1 - iqr_factor * IQR)) |
                             (arr > (Q3 + iqr_factor * IQR)))]

    plt.clf()
    n, bins, patches = plt.hist(x=arr_filtered,
                                bins=n_class,
                                color='#607c8e',
                                alpha=0.7,
                                rwidth=0.9)
    plt.grid(axis='y', alpha=0.75)
    plt.xlabel('Value')
    plt.ylabel('Frequency')
    # plt.title(arr_name)
    maxfreq = n.max()
    # Set a clean upper y-axis limit.
    plt.ylim(ymax=np.ceil(maxfreq / 10) * 10 if maxfreq % 10 else maxfreq + 10)

    # print(n, bins, patches)

    # convert result to score
    score = np.zeros_like(arr)
    if sort == "asc":
        for i in range(n_class):
            if i == 0:
                score[arr < bins[1]] = 1
            elif i == n_class - 1:
                score[arr > bins[n_class - 1]] = n_class
            else:
                score[~((arr < bins[i]) | (arr > bins[i + 1]))] = i + 1
    elif sort == "dsc":
        for i in reversed(range(n_class)):
            if i == 0:
                score[arr > bins[n_class - 1]] = 1
            elif i == n_class - 1:
                score[arr < bins[1]] = n_class
            else:
                score[~((arr < bins[::-1][i + 1]) |
                        (arr > bins[::-1][i]))] = i + 1

    with doc.create(Figure(position='htbp')) as plot:
        plot.add_plot(dpi=300)
        plot.add_caption(arr_name)

    with doc.create(Center()) as centered:
        table_format = "c|"
        for i in range(n_class):
            table_format += "c"
        with centered.create(Tabular(table_format)) as table:
            table.add_row(['severity score'] + [i + 1 for i in range(n_class)])
            table.add_hline(1, n_class + 1)
            table.add_row(['range'] + [
                "{:.2f}-{:.2f}".format(bins[i], bins[i + 1])
                for i in reversed(range(n_class))
            ])
            table.add_row(['count'] + [str(int(value)) for value in n])

    doc.append(basic.NewPage())

    return score
Esempio n. 35
0
import os
from pylatex import Document, PageStyle, Head, Foot, Section, Subsection, Tabular, Math, TikZ, Axis, \
    Plot, Figure, Matrix, Alignat, StandAloneGraphic, MiniPage, LineBreak, Center, Command
from pylatex.utils import italic, bold, NoEscape

image_filename = os.path.join(os.path.dirname(__file__), 'Invoices\sus_header.png')
geometry_options = {"tmargin": "1cm", "lmargin": "1cm"}
doc = Document(geometry_options=geometry_options)

with doc.create(Figure(position='h!')) as sus_pic:
    sus_pic.add_image(image_filename, width='550px')

doc.append(Command('noindent'))
doc.append(Command('textbf', 'asdasdasd'))
doc.append(Command('linebreak'))
doc.append(Command('textbf', 'asdasdasd'))

doc.generate_pdf('test', clean_tex=False, compiler='pdflatex')