Exemplo n.º 1
0
def fill_document(doc):
    cprint('Generating TeX document!', 'green')
    # Packages
    doc.packages.clear()
    doc.packages.append(Package('cmap'))
    doc.packages.append(Package('inputenc', options='utf8x'))
    doc.packages.append(Package('fontenc', options='T2A'))
    doc.packages.append(Package('babel', options=('russian', 'english')))
    doc.packages.append(Package('hyperref', options='hidelinks'))
    doc.packages.append(Package('amsthm'))
    doc.packages.append(Package('listings,lstautogobble'))
    doc.packages.append(Package('amsmath'))
    doc.packages.append(Package('amsfonts'))
    doc.packages.append(Package('amssymb'))
    doc.packages.append(Package('xcolor,colortbl'))
    doc.packages.append(Package('graphicx'))
    doc.packages.append(Package('subcaption'))
    doc.packages.append(Package('tabularx'))
    doc.packages.append(Package('fullpage'))
    doc.packages.append(Package('fancyhdr'))
    doc.packages.append(Package('tocbibind', options=('nottoc', 'numbib')))
    # Preamble - Dynamic (parsed)
    doc.preamble.append(
        Command('renewcommand',
                arguments=(NoEscape(r'\author'), args.get('author'))))
    doc.preamble.append(
        Command('newcommand',
                arguments=(NoEscape(r'\whatdo'),
                           args.get('what_do'))))  # 1. Что сделано
    doc.preamble.append(
        Command(
            'newcommand',
            arguments=(NoEscape(r'\systems'),
                       args.get('systems'))))  # 2. Затрагиваемые ИТ системы
    doc.preamble.append(
        Command(
            'newcommand',
            arguments=(NoEscape(r'\whattest'),
                       args.get('what_test'))))  # 3. Предмет тестирования/FAT
    doc.preamble.append(
        Command(
            'newcommand',
            arguments=(NoEscape(r'\whotest'),
                       args.get('who_test'))))  # 4. Участники тестирования/FAT
    doc.preamble.append(
        Command('newcommand', arguments=(
            NoEscape(r'\role'),
            args.get('role'))))  # 4. Участники тестирования/FAT - Роль
    doc.preamble.append(
        Command('newcommand',
                arguments=(NoEscape(r'\goal'),
                           args.get('goal'))))  # 5. Цель тестирования/FAT
    doc.preamble.append(
        Command('newcommand',
                arguments=(NoEscape(r'\testenvironment'),
                           args.get('test_environment')
                           )))  # 6. Среда проведения тестирования/FAT
    doc.preamble.append(
        Command(
            'newcommand', arguments=(
                NoEscape(r'\result'),
                args.get('result'))))  # 7. Результат проверки тестирования/FAT
    # Preamble - Static
    doc.preamble.append(Command('pagestyle', 'fancy'))
    doc.preamble.append(
        Command('renewcommand',
                arguments=(NoEscape(r'\headrulewidth'), r'0pt')))
    doc.preamble.append(
        Command(
            'newenvironment',
            'textbox',
            options=(NoEscape(r'1][|X|')),
            extra_arguments=[
                NoEscape(
                    r'\vspace{1pt}\centering\tabularx{\textwidth}{#1}\hline'),
                NoEscape(r'\\\hline\endtabularx\\\vspace{4.5pt}')
            ]))
    # Document
    img_rsb = resource_path('rsb.png')
    doc.append(Command('selectlanguage', 'russian'))
    doc.append(Command('thispagestyle', 'empty'))
    doc.append(
        Command('setlength',
                arguments=(NoEscape(r'\headsep'), NoEscape(r'-2cm'))))
    # Logo
    with doc.create(Figure(position='htp')) as logo:
        logo.add_image(img_rsb, width=NoEscape(r'0.3\textwidth'))
    # Page Header
    with doc.create(Center()) as centered:
        centered.append(
            NoEscape(
                r'\color{blue}{\textbf{\Huge{\underline{FAT}\textbackslash UAT Report}}}'
            ))
    # Starts
    with doc.create(Box()) as env:
        env.append(NoEscape(r'\\ 1. \whatdo \\'))
    doc.append(
        NoEscape(r'\par\noindent\textbf{2. Затрагиваемые ИТ системы}\par'))
    with doc.create(Box()) as env:
        env.append(NoEscape(r'\systems'))
    doc.append(
        NoEscape(r'\par\noindent\textbf{3. Предмет тестирования/FAT}\par'))
    with doc.create(Box()) as env:
        env.append(NoEscape(r'\whattest'))
    doc.append(
        NoEscape(r'\par\noindent\textbf{4. Участники тестирования/FAT}\par'))
    doc.append(
        NoEscape(
            r'\begin{textbox}[|X|X|X|]\textbf{Имя}&\textbf{Подразделение}&\textbf{Роль}\\\hline\whotest&ДРР&\role\end{textbox}\par'
        ))
    doc.append(NoEscape(r'\par\noindent\textbf{5. Цель тестирования/FAT}\par'))
    with doc.create(Box()) as env:
        env.append(NoEscape(r'\goal'))
    doc.append(
        NoEscape(
            r'\par\noindent\textbf{6. Среда проведения тестирования/FAT}\par'))
    with doc.create(Box()) as env:
        env.append(NoEscape(r'\testenvironment'))
    doc.append(
        NoEscape(
            r'\par\noindent\textbf{7. Результат проверки тестирования/FAT}\par'
        ))
    with doc.create(Box()) as env:
        env.append(NoEscape(r'\result'))
    doc.append(
        NoEscape(
            r'\par\noindent\textbf{8. Заключение по результату проверки тестирования/FAT}\par'
        ))
    with doc.create(Box()) as env:
        env.append(
            NoEscape(
                r'\footnotesize{\emph{В процессе проведения FAT установлено, что функциональность ПО полностью соответствует предъявленным требованиям. Установку доработок в СЕРТ среду считаем возможным.}}'
            ))
    doc.append(
        NoEscape(
            r'\par\noindent\textbf{9. Выявленные замечания по результату проверки тестирования/FAT}\par'
        ))
    with doc.create(Box()) as env:
        env.append(NoEscape(r''))
    doc.append(
        NoEscape(
            r'\par\noindent\textbf{10. Финальное решение по результату проверки тестирования/FAT}\par'
        ))
    doc.append(
        NoEscape(
            r'\begin{textbox}[|l|X|]\textbf{Test\textbackslash FAT статус}&\textbf{Пройдено}\\\hline\textbf{Комментарий}&\\&\end{textbox}\par'
        ))
    doc.append(NoEscape(r'\vspace{-7pt}\par'))
    doc.append(
        NoEscape(
            r'\begin{textbox}[|l|X|p{0.2\textwidth}|]Дата&Фамилия, Имя Бизнес представителя&Подпись\\\hline\today&\author &\end{textbox}\par'
        ))
    doc.append(NoEscape(r'\vspace{-1.5cm}'))
    doc.append(NoEscape(r'\hspace{12.5cm}\includegraphics[width=70pt]{sign}'))
    cprint('Generated!', 'red')
Exemplo n.º 2
0
def preamble(doc, template):
    # Macros
    doc.preamble.append(Command('input', NoEscape('sty/macros')))

    # Language
    doc.preamble.append(
        Command('doclanguage', NoEscape(template['LANGUAGE']['lang'])))

    doc.preamble.append(Command('docimages', NoEscape('img/')))

    # Variables
    doc.preamble.append(
        Command('doctitle', NoEscape(template['VARIABLES']['title'])))
    doc.preamble.append(
        Command('docsubtitle', NoEscape(template['VARIABLES']['subtitle'])))
    doc.preamble.append(
        Command('docauthor', NoEscape(template['VARIABLES']['author'])))
    doc.preamble.append(
        Command('doccopyright', NoEscape(template['VARIABLES']['copyright'])))
    doc.preamble.append(
        Command('docpublisher', NoEscape(template['VARIABLES']['publisher'])))
    doc.preamble.append(
        Command('docbookurl', NoEscape(template['VARIABLES']['url'])))
    doc.preamble.append(
        Command('doclicense', NoEscape(template['VARIABLES']['license'])))
    doc.preamble.append(
        Command('docedition', NoEscape(template['VARIABLES']['edition'])))

    # Packages
    doc.preamble.append(Command('usepackage', NoEscape('sty/legrand')))
    doc.preamble.append(Command('usepackage',
                                NoEscape('sty/legrand-enhanced')))
    doc.preamble.append(Command('usepackage', NoEscape('sty/custom')))

    # Style
    doc.append(Command('input', NoEscape('sty/title')))
    doc.append(Command('input', NoEscape('sty/copyright')))
    doc.append(Command('input', NoEscape('sty/toc')))
        table.add_row("Culet", bold("Very Small"))
        page.append(table)

        add_space_plus_new_line(page, 2)
        make_heading_divider(page, "inclusions")
        page.append(bold("Crystal, Feather"))

        add_space_plus_new_line(page, 1)
        page.append(NoEscape(r"\setstretch{0.7}"))
        page.append(FootnoteText(DISCLAIMER))


if __name__ == "__main__":
    doc = Document(
        documentclass=Command("documentclass",
                              options=["12pt", "landscape"],
                              arguments=["article"]),
        geometry_options={
            "margin": "0em",
            "includehead": False,
            "head": "0em",
            "includefoot": True,
            "foot": "3em"
        },
    )
    # doc.preamble.append(Command("usepackage", "helvet"))
    doc.append(
        NoEscape(
            r"\renewcommand{\footnotesize}{\fontsize{6pt}{6pt}\selectfont}"))

    setup_colors(doc)
Exemplo n.º 4
0
        doc.append(italic('italic text. '))

        with doc.create(Subsection('A subsection')):
            doc.append('Also some crazy characters: $&#{}')


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

    doc.generate_tex()

    # Document with `\maketitle` command activated
    doc = Document()

    doc.preamble.append(Command('title', 'Awesome Title'))
    doc.preamble.append(Command('author', 'Anonymous author'))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))

    fill_document(doc)

    doc.generate_tex('basic_maketitle')

    # Add stuff to the document
    with doc.create(Section('A second section')):
        doc.append('Some text.')

    doc.generate_tex('basic_maketitle2')
    tex = doc.dumps()  # The document as string in LaTeX syntax
Exemplo n.º 5
0
def test_command():
    c = Command(command='documentclass', arguments=None, options=None,
                packages=None)
    repr(c)
Exemplo n.º 6
0
    def printFacture(self):

        theSartDate = datetime.now()
        theTargetDate = theSartDate + timedelta(days=30)
        print("Début de la génération :" + str(theSartDate))
        print("TargetDate=" + str(theTargetDate))

        doc = Document()
        doc.packages.append(Package('eurosym', options=['official']))
        #doc.append(Command("title{TiLuNet}"))
        #doc.append(Command("maketitle"))

        #doc.append(Command("includegraphics","\"logo.png\""))
        image_filename = '../../Ressources/logo.png'
        with doc.create(Figure(position='h!')) as kitten_pic:
            kitten_pic.add_image(image_filename, width='120px')

        #Company info
        doc.append(Command("quad"))
        doc.append(Command("newline"))
        doc.append("FIDEL Lucette")
        doc.append(Command("newline"))
        doc.append("139 avenue Corniche Fleurie")
        doc.append(Command("newline"))
        doc.append("06200 NICE")
        doc.append(Command("newline"))
        doc.append(Command("underline", "SIRET"))
        doc.append("52148565600016")

        #
        with doc.create(
                Section(
                    "FACTURE N " + str(theSartDate.year) + "-" +
                    str(self.client.lastFactureId + 1), False)):
            doc.append("Émise le " +
                       str(theSartDate.date().strftime(self.formatDate)) +
                       ", à payer le " +
                       theTargetDate.date().strftime(self.formatDate))
            doc.append(Command("newline"))

            doc.append(Command("begin", "center"))
            doc.append(Command("begin", "bfseries"))
            doc.append(self.client.name)
            doc.append(Command("newline"))
            doc.append(self.client.adress)
            doc.append(Command("newline"))
            doc.append(Command("end", "bfseries"))
            doc.append(Command("end", "center"))

            #doc.append("Total HT" + Command("dotfill") + "291 €")
            doc.append("Total HT")
            doc.append(Command("dotfill"))
            doc.append("291")
            doc.append(Command("euro", ""))
            doc.append(Command("newline"))
            doc.append(Command("begin", "flushright"))
            doc.append("TVA 20% ")
            doc.append(Command("hspace", "1cm"))
            doc.append("51")
            doc.append(Command("euro", ""))
            doc.append(Command("end", "flushright"))

            doc.append(Command("begin", "bfseries"))
            doc.append("TOTAL DE LA FACTURE TTC")
            doc.append(Command("dotfill"))
            doc.append("242 ")
            doc.append(Command("euro", ""))
            doc.append(Command("end", "bfseries"))
            doc.append(Command("newline"))

        doc.generate_pdf(self.destination + 'Facture_' + self.client.name +
                         "-" + str(self.client.lastFactureId + 1),
                         clean=True,
                         clean_tex=False,
                         compiler="pdflatex",
                         compiler_args=None,
                         silent=True)

        theEndDate = datetime.now()
        print("Fin de la génération :" + str(theEndDate))
        self.client.lastFactureId += 1
        genTime = theEndDate - theSartDate
        print("Temps de gen=" + str(genTime))
        self.client.factureList.append(self.factureClient)
        return genTime
Exemplo n.º 7
0
from zipfile import ZipFile
import os
from os.path import basename

now = datetime.datetime.now()

titulo = "Título de meu arquivo"
resumo = "Resumo de meu arquivo"
conteudo = "Conteúdo de meu arquivo"
conclusao = "Conclusão de meu arquivo"

filepath = (r"latex_generator\output")
doc = Document(filepath)
doc.documentclass = Command(
    'documentclass',
    options=['brazilian', '12pt', 'oneside', 'a4paper'],
    arguments=['article'],
)

doc.preamble.append(NoEscape(r'\input{preamble.tex}'))
doc.preamble.append(Command('titulo', {titulo}))
doc.preamble.append(NoEscape(r'\data{\today}'))
doc.append(NoEscape(r'\setFaixa'))
doc.append(NoEscape(r'\geraTitulo'))
doc.append(NoEscape(r'\section{Resumo}'))
doc.append(resumo)
doc.append(NoEscape(r'\section{Conteúdo}'))
doc.append(conteudo)
doc.append(NoEscape(r'\section{Conclusão}'))
doc.append(conclusao)
doc.append(NoEscape(r'\section{Dados}'))
Exemplo n.º 8
0
from pylatex import Command, NewPage, Figure
from pylatex.position import Center
from pylatex.utils import NoEscape

from pytex import ExamCore
from pytex.exam import Question

core = ExamCore(packages=[["geometry", "a4paper,centering,scale=0.8"],
                          "amsmath", "graphicx", "amssymb"])
core.define([r"\dif"], [r"\text{d}"])

fig = Figure(position='h!')
fig.add_image(os.path.join(os.path.dirname(__file__), "resources/timg.jpg"),
              width=NoEscape(r'0.8\linewidth'))

core.pre_append(title=Command('heiti', '试卷示例'),
                author=Command('kaishu', '六个骨头'),
                date=Command('today'))
core.body_append(Command('maketitle'))
core.body_append(
    NoEscape(r'本试卷分为100分的必答题和10分的选做题,选做题做对加分,'
             r'做错不扣分,最多累计10分,整卷最高分110分。'))

core.body_append(NoEscape(r"\vspace{15cm}"))
with core.create(Center()) as centered:
    core.body_append(NoEscape(r'\bf{姓名}\ \underline{\hbox to 20mm{}}'),
                     NoEscape(r'\bf{学号}\ \underline{\hbox to 20mm{}}'),
                     NoEscape(r'\bf{编号}\ \underline{\hbox to 20mm{}}'))
core.body_append(NewPage())

#  ——————————题目内容——————————
Exemplo n.º 9
0
 def addRelevantCoursework(self, classes):
     self.doc.append(Command("begin", ["rSection", "Relevant Coursework"]))
     self.doc.append(Command("text", classes[0]))
     for c in classes[1:]:
         self.doc.append(Command("item", c))
     self.doc.append(Command("end", "rSection"))
Exemplo n.º 10
0
 def addTitle(self, student_name, email, number):
     self.doc.preamble.append(Command("name", student_name))
     self.doc.preamble.append(Command("address", f"{number} | {email}"))
Exemplo n.º 11
0
 def addSkills(self, type, skills):
     self.doc.append(Command("begin", ["rSection", type + " Skills"]))
     self.doc.append(", ".join(skills))
     self.doc.append(Command("end", "rSection"))
Exemplo n.º 12
0
def get_document_sizes(document_class):
    """Get useful document sizes given a LaTeX document class.

    Args:
        document_class: dict with ``documentclass`` and ``document_options``. It
            may optionally contain a list of LaTeX packages under ``packages``
            as well as any other argument acceptable by ``pylatex.document``.

    Examples:
        You may use one of the available document_classes.

         >>> from pprint import pprint
         >>> from pubplot.document_classes import ieee_infocom
         >>> sizes_dict = get_document_sizes(ieee_infocom)
         >>> pprint(sizes_dict)
         {'Huge': 24.0,
          'LARGE': 17.0,
          'Large': 14.0,
          'caption': 8.0,
          'columnwidth': 252.0,
          'footnotesize': 8.0,
          'huge': 20.0,
          'large': 12.0,
          'normalsize': 10.0,
          'scriptsize': 7.0,
          'small': 9.0,
          'textwidth': 516.0,
          'tiny': 5.0}

         Or provide your own, using a dict

         >>> document_class = {
         ...    'documentclass': 'IEEEtran',
         ...    'document_options': ['10pt', 'conference', 'letterpaper']
         ... }
         >>> sizes_dict = get_document_sizes(document_class)
         >>> pprint(sizes_dict)
         {'Huge': 24.0,
          'LARGE': 17.0,
          'Large': 14.0,
          'caption': 8.0,
          'columnwidth': 252.0,
          'footnotesize': 8.0,
          'huge': 20.0,
          'large': 12.0,
          'normalsize': 10.0,
          'scriptsize': 7.0,
          'small': 9.0,
          'textwidth': 516.0,
          'tiny': 5.0}

    Returns:
        A dictionary containing sizes

        - columnwidth
        - textwidth
        - tiny
        - scriptsize
        - footnotesize
        - small
        - normalsize
        - large
        - Large
        - LARGE
        - huge
        - Huge
        - caption
    """
    def log_with_name(name, value):
        return '\\wlog{{{}{}={}}}'.format(LOG_PATTERN, name, value)

    def log_text_size(text_size_name):
        return '\\{} a {} \n\n'.format(
            text_size_name, log_with_name(text_size_name, r'\f@size pt'))

    get_sizes_command = r"""
    \makeatletter
    \newcommand\getsizes{%
        """ + log_with_name('columnwidth', r'\the\columnwidth') + r"""
        """ + log_with_name('textwidth', r'\the\textwidth') + r"""

        \begin{figure}
            \centering
            \fbox{
                \begin{minipage}[c][0.1\textheight][c]{\columnwidth}
                \centering{Dummy Image}
                \end{minipage}
            }
            \caption{a """ + log_with_name('caption', r'\f@size pt') + r""" }
        \end{figure}

    """
    for size in LATEX_BUILT_IN_SIZES:
        get_sizes_command += log_text_size(size)

    get_sizes_command += '}'

    temp_doc_name = next(tempfile._get_candidate_names())

    document_kwargs = document_class.copy()
    packages = document_kwargs.pop('packages', [])

    doc = Document(temp_doc_name, **document_kwargs)
    doc.packages = packages
    doc.preamble.append(NoEscape(get_sizes_command))
    doc.append(Command('title', 'Title'))
    doc.append(Command('maketitle'))
    doc.append('Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam c'
               'onsectetur volutpat tellus vel ultricies. Donec ullamcorper or'
               'ci quis ante volutpat efficitur. Aenean at rhoncus nibh. Morbi'
               ' vitae justo velit. Curabitur eget condimentum quam, nec accum'
               'san nulla. Nam tempor sem id tellus consectetur condimentum. N'
               'ullam id lacus purus. Nam nisi nisi, tempus ac ligula luctus, '
               'mollis volutpat odio. Mauris euismod mi nec rutrum tempor.\n' *
               20)
    doc.append(NoEscape(r'\getsizes'))

    try:
        doc.generate_pdf(temp_doc_name, clean=False)
    except subprocess.CalledProcessError:
        pass

    with open(temp_doc_name + '.log', 'r') as f:
        lines = f.read().splitlines()

    sizes_dict = {}
    for l in lines:
        if l.startswith(LOG_PATTERN):
            variable, value = l.split('=')
            variable = variable[len(LOG_PATTERN):]
            sizes_dict[variable] = float(value[0:-2])

    list(map(os.remove, glob.glob(temp_doc_name + '.*')))

    return sizes_dict
Exemplo n.º 13
0
            if best < solution[4] or (fname in bestever
                                      and len(bestever[fname]) > 1
                                      and bestever[fname][1] < solution[4]):
                tim = maxtime
        if solution[3] == 'MAX':
            if best < solution[4] or (fname in bestever
                                      and len(bestever[fname]) > 1
                                      and bestever[fname][1] > solution[4]):
                tim = maxtime
        timPerOpt[solution[6]].append(tim)

# Then start the document
doc = Document()
doc.preamble.append(
    Command(
        'title', 'Benchmark analysis of %d problems and %d configurations.' %
        (len(fnames), len(options))))
doc.preamble.append(Command('author', "Charles Prud'homme"))
doc.append(NoEscape(r'\maketitle'))

doc.packages.append(Package('geometry'))
presec = ""
prevsubsec = ""
section = None
subsection = None

if args.plot:
    # First global view
    section = Section('Global')
    doc.append(section)
Exemplo n.º 14
0
    def __init__(self, title: str, mode: DocumentType):
        super().__init__(documentclass="exam",
                         document_options=["12pt", "addpoints"],
                         page_numbers=True,
                         geometry_options={
                             "left": "12mm",
                             "right": "15mm",
                             "top": "25mm",
                             "bottom": "30mm"
                         })

        self.brand = Command("textit",
                             "https://github.com/barnabartos/examgen")
        if mode == DocumentType.EXAM:
            self.hright = NoEscape(
                r"Name: \dotuline{\hspace{40mm}} \vspace{1mm}")
        elif mode == DocumentType.SOLSKEY:
            self.hright = ""
        else:
            raise ValueError(f"mode needs to be DocumentType not {mode}")
        self.headtitle = NoEscape(title + r"\vspace{1mm}")
        self.pgnum = Command("textbf",
                             NoEscape(r"\thepage/\pageref{LastPage}"))
        self.date = Command("textit", Command("today"))

        self.packages.append(Package("amsmath"))
        self.packages.append(Package("ulem", options=["normalem"]))
        self.preamble.append(Command("pagestyle", arguments=["headandfoot"]))
        self.preamble.append(
            Command("renewcommand",
                    arguments=[
                        Command("questionlabel"),
                        Command("textbf", Command("thequestion."))
                    ]))
        self.preamble.append(
            Command("renewcommand",
                    arguments=[
                        Command("partlabel"),
                        Command("textbf", Command("thepartno)"))
                    ]))
        self.preamble.append(
            Command("firstpageheader",
                    arguments=[self.headtitle, "", self.hright]))
        self.preamble.append(
            Command("runningheader",
                    arguments=[self.headtitle, "", self.hright]))
        self.preamble.append(NoEscape(r"\runningheadrule"))
        self.preamble.append(NoEscape(r"\firstpageheadrule"))
        self.preamble.append(
            Command("firstpagefooter",
                    arguments=[self.brand, self.pgnum, self.date]))
        self.preamble.append(
            Command("runningfooter",
                    arguments=[self.brand, self.pgnum, self.date]))
        self.preamble.append(NoEscape(r"\runningfootrule"))
        self.preamble.append(NoEscape(r"\firstpagefootrule"))
Exemplo n.º 15
0
    def _report_attack_configuration(self):
        """Create subsubsection about the attack and data configuration."""
        # Create tables for attack parameters and the data configuration.
        ap = self.attack_pars
        dc = self.data_conf
        self.report_section.append(Subsubsection("Attack Details"))
        with self.report_section.create(MiniPage()):
            with self.report_section.create(MiniPage(width=r"0.49\textwidth")):
                # -- Create table for the attack parameters.
                self.report_section.append(Command("centering"))
                with self.report_section.create(Tabular("|l|c|")) as tab_ap:
                    tab_ap.add_hline()
                    tab_ap.add_row(["Number of classes", ap["number_classes"]])
                    tab_ap.add_hline()
                    tab_ap.add_row([
                        "Number of shadow models", ap["number_shadow_models"]
                    ])
                    tab_ap.add_hline()
                    tab_ap.add_row([
                        "Shadow training set size",
                        ap["shadow_training_set_size"],
                    ])
                    tab_ap.add_hline()
                    tab_ap.add_row(["Shadow epochs", ap["shadow_epochs"]])
                    tab_ap.add_hline()
                    tab_ap.add_row(
                        ["Shadow batch size", ap["shadow_batch_size"]])
                    tab_ap.add_hline()
                    tab_ap.add_row(["Attack epochs", ap["attack_epochs"]])
                    tab_ap.add_hline()
                    tab_ap.add_row(
                        ["Attack batch size", ap["attack_batch_size"]])
                    tab_ap.add_hline()
                self.report_section.append(
                    Command("captionsetup", "labelformat=empty"))
                self.report_section.append(
                    Command(
                        "captionof",
                        "table",
                        extra_arguments="Attack parameters",
                    ))

            with self.report_section.create(MiniPage(width=r"0.49\textwidth")):
                # -- Create table for the data configuration
                self.report_section.append(Command("centering"))
                nr_targets, target_training_set_size = dc[
                    "record_indices_per_target"].shape
                with self.report_section.create(Tabular("|l|c|")) as tab_dc:
                    tab_dc.add_hline()
                    tab_dc.add_row([
                        NoEscape("Samples used to train shadow models ($S$)"),
                        len(dc["shadow_indices"]),
                    ])
                    tab_dc.add_hline()
                    tab_dc.add_row([
                        NoEscape("Samples used to train target models ($T$)"),
                        len(dc["target_indices"]),
                    ])
                    tab_dc.add_hline()
                    tab_dc.add_row([
                        "Samples used to evaluate the attack",
                        len(dc["evaluation_indices"]),
                    ])
                    tab_dc.add_hline()
                    tab_dc.add_row(["Attacked target models", nr_targets])
                    tab_dc.add_hline()
                    tab_dc.add_row([
                        "Target model's training sets size",
                        target_training_set_size
                    ])
                    tab_dc.add_hline()
                    tab_dc.add_row([
                        NoEscape("Size of $S \cap T$"),
                        len(
                            set(dc["shadow_indices"])
                            & set(dc["target_indices"])),
                    ])
                    tab_dc.add_hline()
                self.report_section.append(
                    Command("captionsetup", "labelformat=empty"))
                self.report_section.append(
                    Command(
                        "captionof",
                        "table",
                        extra_arguments="Target and Data Configuration",
                    ))
Exemplo n.º 16
0
class WorkEntry(CommandBase):
    _latex_name = 'WorkEntry'


#######################################

if __name__ == '__main__':

    doc = Document(documentclass='scrartcl',
                   document_options=["paper=a4", "fontsize=11pt"])

    ###########################

    ###########################

    doc.preamble.append(Command("usepackage", "mdframed"))
    doc.preamble.append(Command("usepackage", "babel", "english"))
    #    doc.preamble.append(Command("usepackage", "inputenc","utf8x"))
    doc.preamble.append(
        Command("usepackage", "microtype",
                ["protrusion=true", "expansion=true"]))
    doc.preamble.append(Command("usepackage", "amsmath"))
    doc.preamble.append(Command("usepackage", "amsfonts"))
    doc.preamble.append(Command("usepackage", "amsthm"))
    doc.preamble.append(Command("usepackage", "graphicx"))
    doc.preamble.append(Command("usepackage", "xcolor", "svgnames"))
    doc.preamble.append(Command("usepackage", "geometry"))
    doc.preamble.append(Command("usepackage", "url"))
    doc.preamble.append(Command("usepackage", "sectsty"))

    doc.append(Command('frenchspacing'))
Exemplo n.º 17
0
    def _report_attack_results(self, save_path):
        """
        Create subsubsection describing the most important results of the attack.

        Parameters
        ----------
        save_path :
            Path to save the tex, pdf and asset files of the attack report.

        This subsection contains results only for the first target model.
        """
        tm = 0  # Specify target model
        self.report_section.append(Subsubsection("Attack Results"))
        res = self.attack_results

        # ECDF graph (like in paper)
        precision_sorted = np.sort(res["precision_list"], axis=0)[:, tm]
        recall_sorted = np.sort(res["recall_list"], axis=0)[:, tm]
        py = np.arange(1, len(precision_sorted) + 1) / len(precision_sorted)
        ry = np.arange(1, len(recall_sorted) + 1) / len(recall_sorted)

        fig = plt.figure()
        ax = plt.axes()
        ax.set_xlabel("Accuracy")
        ax.set_ylabel("Cumulative Fraction of Classes")
        ax.plot(precision_sorted, py, "k-", label="Precision")
        ax.plot(recall_sorted, ry, "k--", label="Recall")
        ax.legend()

        alias_no_spaces = str.replace(self.attack_alias, " ", "_")
        fig.savefig(save_path + f"fig/{alias_no_spaces}-ecdf.pdf",
                    bbox_inches="tight")
        plt.close(fig)

        with self.report_section.create(MiniPage()):
            with self.report_section.create(MiniPage(width=r"0.49\textwidth")):
                self.report_section.append(Command("centering"))
                self.report_section.append(
                    Command(
                        "includegraphics",
                        NoEscape(f"fig/{alias_no_spaces}-ecdf.pdf"),
                        "width=8cm",
                    ))
                self.report_section.append(
                    Command("captionsetup", "labelformat=empty"))
                self.report_section.append(
                    Command(
                        "captionof",
                        "figure",
                        extra_arguments="Empirical CDF",
                    ))

            tp_row = []
            fp_row = []
            tn_row = []
            fn_row = []
            class_row = []
            precision_row = []
            accuracy_row = []
            recall_row = []

            # Average column
            class_row.append(f"0-{self.attack_pars['number_classes']-1}")
            tp_row.append(
                np.round(
                    np.sum(res["tp_list"], axis=0)[tm] / len(res["tp_list"]),
                    2))
            fp_row.append(
                np.round(
                    np.sum(res["fp_list"], axis=0)[tm] / len(res["fp_list"]),
                    2))
            tn_row.append(
                np.round(
                    np.sum(res["tn_list"], axis=0)[tm] / len(res["tn_list"]),
                    2))
            fn_row.append(
                np.round(
                    np.sum(res["fn_list"], axis=0)[tm] / len(res["fn_list"]),
                    2))
            accuracy_row.append(
                np.round(
                    np.sum(res["eval_accuracy_list"], axis=0)[tm] /
                    len(res["eval_accuracy_list"]),
                    3,
                ))
            precision_row.append(
                np.round(
                    np.sum(res["precision_list"], axis=0)[tm] /
                    len(res["precision_list"]),
                    3,
                ))
            recall_row.append(
                np.round(
                    np.sum(res["recall_list"], axis=0)[tm] /
                    len(res["recall_list"]), 3))

            # Maximum accuracy class
            max_class = np.argmax(res["eval_accuracy_list"], axis=0)[tm]
            class_row.append(max_class)
            tp_row.append(res["tp_list"][max_class][tm])
            fp_row.append(res["fp_list"][max_class][tm])
            tn_row.append(res["tn_list"][max_class][tm])
            fn_row.append(res["fn_list"][max_class][tm])
            accuracy_row.append(
                np.round(res["eval_accuracy_list"][max_class][tm], 3))
            precision_row.append(
                np.round(res["precision_list"][max_class][tm], 3))
            recall_row.append(np.round(res["recall_list"][max_class][tm], 3))

            # Minimum accuracy class
            min_class = np.argmin(res["eval_accuracy_list"], axis=0)[tm]
            class_row.append(min_class)
            tp_row.append(res["tp_list"][min_class][tm])
            fp_row.append(res["fp_list"][min_class][tm])
            tn_row.append(res["tn_list"][min_class][tm])
            fn_row.append(res["fn_list"][min_class][tm])
            accuracy_row.append(
                np.round(res["eval_accuracy_list"][min_class][tm], 3))
            precision_row.append(
                np.round(res["precision_list"][min_class][tm], 3))
            recall_row.append(np.round(res["recall_list"][min_class][tm], 3))

            with self.report_section.create(MiniPage(width=r"0.49\textwidth")):
                self.report_section.append(Command("centering"))
                with self.report_section.create(
                        Tabular("|l|c|c|c|")) as result_tab:
                    result_tab.add_hline()
                    result_tab.add_row(
                        list(
                            map(
                                bold,
                                [
                                    "",
                                    "Average",
                                    "max. Acc.",
                                    "min. Acc.",
                                ],
                            )))
                    result_tab.add_hline()
                    result_tab.add_row(
                        ["Class", class_row[0], class_row[1], class_row[2]])
                    result_tab.add_hline()
                    result_tab.add_row(
                        ["True Positives", tp_row[0], tp_row[1], tp_row[2]])
                    result_tab.add_hline()
                    result_tab.add_row(
                        ["False Positives", fp_row[0], fp_row[1], fp_row[2]])
                    result_tab.add_hline()
                    result_tab.add_row(
                        ["True Negatives", tn_row[0], tn_row[1], tn_row[2]])
                    result_tab.add_hline()
                    result_tab.add_row(
                        ["False Negatives", fn_row[0], fn_row[1], fn_row[2]])
                    result_tab.add_hline()
                    result_tab.add_row([
                        "Accuracy", accuracy_row[0], accuracy_row[1],
                        accuracy_row[2]
                    ])
                    result_tab.add_hline()
                    result_tab.add_row([
                        "Precision",
                        precision_row[0],
                        precision_row[1],
                        precision_row[2],
                    ])
                    result_tab.add_hline()
                    result_tab.add_row([
                        "Recall", recall_row[0], recall_row[1], recall_row[2]
                    ])
                    result_tab.add_hline()
                self.report_section.append(
                    Command("captionsetup", "labelformat=empty"))
                self.report_section.append(
                    Command("captionof",
                            "table",
                            extra_arguments="Attack Summary"))

        ap = self.attack_pars

        # Histograms
        fig, (ax0, ax1, ax2) = plt.subplots(1, 3, sharey=True, figsize=(12, 3))
        ax0.hist(res["eval_accuracy_list"][:, tm], edgecolor="black")
        ax1.hist(res["precision_list"][:, tm], edgecolor="black")
        ax2.hist(res["recall_list"][:, tm], edgecolor="black")
        ax0.set_xlabel("Accuracy")
        ax1.set_xlabel("Precision")
        ax2.set_xlabel("Recall")
        ax0.set_ylabel("Number of Classes")
        ax0.tick_params(axis="x", labelrotation=45)
        ax1.tick_params(axis="x", labelrotation=45)
        ax2.tick_params(axis="x", labelrotation=45)
        ax0.set_axisbelow(True)
        ax1.set_axisbelow(True)
        ax2.set_axisbelow(True)

        alias_no_spaces = str.replace(self.attack_alias, " ", "_")
        fig.savefig(save_path +
                    f"/fig/{alias_no_spaces}-accuracy_precision_recall.pdf",
                    bbox_inches="tight")
        plt.close(fig)

        with self.report_section.create(Figure(position="H")) as fig:
            fig.add_image(
                f"fig/{alias_no_spaces}-accuracy_precision_recall.pdf",
                width=NoEscape(r"\textwidth"))
            self.report_section.append(
                Command("captionsetup", "labelformat=empty"))
            self.report_section.append(
                Command(
                    "captionof",
                    "figure",
                    extra_arguments=
                    "Accuracy, precision and recall histogram for all "
                    "attack models",
                ))
Exemplo n.º 18
0
from Clusterize import clusterize_questions
from pylatex import Document, Section, Subsection, Itemize, Enumerate, Description, Command, NoEscape

QUEST_PATH = "../questions_raw_cleaned_aggregated.txt"
#get question per topic and questions + answer dictionary
topic_list, questions = clusterize_questions(QUEST_PATH)

doc = Document()

doc.preamble.append(
    Command('title',
            'Domande per il corso di Progettazione di Sistemi Operativi'))
doc.preamble.append(Command('author', 'Anonymous author'))
doc.preamble.append(Command('date', NoEscape(r'\today')))
doc.append(NoEscape(r'\maketitle'))

for topic in topic_list:
    with doc.create(Section(topic[0].upper())):
        for q in topic[1]:
            with doc.create(Subsection(q)):  #retrieve answers for q
                answ_list = questions[q]
                #create enumeration list
                with doc.create(
                        Enumerate(enumeration_symbol=r"\alph*)",
                                  options={'start': 1})) as enum:
                    for answ in answ_list:
                        enum.add_item(answ)

doc.generate_pdf('domande-pso', clean_tex=False)
Exemplo n.º 19
0
                table.add_hline()
                table.add_row(fila)

                jiCuadrado += (frecuenciaObs -
                               frecuenciaEsperada)**2 / frecuenciaEsperada

    doc.append(Math(data=['Total', '=', (int)(n)]))
    doc.append(Math(data=['X2(0)', '=', jiCuadrado]))


if __name__ == '__main__':
    t = datetime.today()
    print(t)
    doc = Document()
    doc.preamble.append(Command('title', 'Tarea 2 Simulacion'))
    doc.preamble.append(Command('author', 'Mauricio Arce Fernandez'))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))

    archivo = [
        "randomHaskell.txt", "randomJava.txt", "randomPerl.txt",
        "randomPython.txt", "randomProlog.txt", "randomScala.txt",
        "randomORG.txt"
    ]
    nombre = [
        "Haskell", "Java", "Perl", "Python", "Prolog", "Scala", "Random.org"
    ]

    for i in range(7):
        doc.append(Section(nombre[i]))
Exemplo n.º 20
0
# SCRIPT FOR GENERATING AND COMPILING LATEX SOURCE FILES

from pylatex import Document, Section, Subsection, Command
from pylatex.utils import NoEscape

if __name__ == '__main__':

    # Generate doc name
    doc = Document(input('Enter doc name: '))

    # Generate title
    doc.preamble.append(Command('title', input('Enter doc title: ')))
    doc.preamble.append(Command('author', input("Enter author: ")))
    doc.preamble.append(Command('date',
                                NoEscape(r'\today')))  # Set the date to today
    doc.append(NoEscape(r'\maketitle'))
    doc.append(Command('newpage'))  # New page after title

    # Generate table of contents
    doc.append(Command('tableofcontents'))
    doc.append(Command('newpage'))  # New page after table of contents

    # Generate sections and subsections
    number_sections = int(input('Introduce the number of sections: '))
    subsections = 0
    for i in range(number_sections):
        with doc.create(Section(input('Enter section name: '))):
            doc.append('texto')
        subsections = int(input("How many subsections?: "))
        if subsections > 0:
            for j in range(subsections):
Exemplo n.º 21
0
############Script##################
x = np.load(path)

y = np.reshape(x, -1)

stadistics = {
    "shape": x.shape,
    "mean": st.mean(y),
    "high median": st.median_high(y),
    "variance": st.variance(y)
}

pp.pprint(stadistics)

doc = Document('basic')
doc.preamble.append(Command('title', 'Qtable report'))
doc.preamble.append(Command('author', 'Tic Tac Toe'))
doc.preamble.append(Command('date', NoEscape(r'\today')))
doc.append(NoEscape(r'\maketitle'))

with doc.create(Section('Introducction')):
    doc.append(bold('This document was autogenerate. '))
    doc.append('Here we present the saved q values of an agent (path: ')
    doc.append(italic(path))
    doc.append('). This document present a image with the respective values of the elements on the qtable.' \
    + 'and the stadistics values obtain in the process. ')
    date = datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')
    doc.append(bold('Document generate ' + date + '.'))

with doc.create(Section('Qtable')):
    doc.append(
Exemplo n.º 22
0
    def create_pdf(self):
        """Creates the PDF using the PyLatex module.

            Notes:-


        """
        r1_summary_trim_dict, r1_stats_trim_dict, r2_summary_trim_dict = self.get_trimmed_data(
        )
        r1_stats_dict = self.get_original_data()

        doc = Document()
        doc.packages.append(Package('geometry', options=['margin=0.75in']))
        doc.packages.append(Package('subcaption'))
        doc.packages.append(Package('xcolor'))
        doc.packages.append(Package('placeins'))
        doc.append(Command('makeatletter'))
        doc.append(Command('setlength', NoEscape(r'\@fptop}{0pt')))
        doc.append(Command('makeatother'))
        doc.append(Command(NoEscape(r'renewcommand{\baselinestretch}'), '1.0'))
        doc.append(Command('begin', 'center'))
        doc.append(Command('Large', bold('Sample Quality Results')))
        doc.append(Command('end', 'center'))

        with doc.create(Section('Basic Statistics')):
            with doc.create(Description()) as desc:
                desc.add_item("Sample:",
                              "%s" % r1_stats_dict.get('Filename')[:-16])
                desc.add_item("File type:",
                              "%s" % r1_stats_dict.get('File type'))
                desc.add_item("Encoding:",
                              "%s" % r1_stats_dict.get('Encoding'))
            with doc.create(Tabular(NoEscape(r'p{5.5cm}|c|c'))) as table:
                table.add_row(('', 'Before trimming', 'After trimming'))
                table.add_hline()
                table.add_row(
                    ('Total Sequences',
                     '%s' % r1_stats_dict.get('Total Sequences'),
                     '%s' % r1_stats_trim_dict.get('Total Sequences')))
                table.add_row((
                    'Sequences flagged as poor quality', '%s' %
                    r1_stats_dict.get('Sequences flagged as poor quality'),
                    '%s' %
                    r1_stats_trim_dict.get('Sequences flagged as poor quality')
                ))
                table.add_row(
                    ('Sequence length',
                     '%s' % r1_stats_dict.get('Sequence length'),
                     '%s' % r1_stats_trim_dict.get('Sequence length')))
                table.add_row(('%GC', '%s' % r1_stats_dict.get('%GC'),
                               '%s' % r1_stats_trim_dict.get('%GC')))

        with doc.create(Section('FastQC')):
            with doc.create(
                    Figure(position='!htb',
                           placement=NoEscape(r'\centering'))) as fig:
                fig.add_caption('Per base sequence quality')
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    plot.add_image(
                        '%sR1_001_fastqc/Images/per_base_quality.png' %
                        self.sample)
                    plot.add_caption('R1 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r1_summary_trim_dict.get(
                            'Per base sequence quality') == 'PASS':
                        colour = 'green'
                    elif r1_summary_trim_dict.get(
                            'Per base sequence quality') == 'WARN':
                        colour = 'orange'
                    elif r1_summary_trim_dict.get(
                            'Per base sequence quality') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image(
                        '%sR1_001.qfilter_fastqc/Images/per_base_quality.png' %
                        self.sample)
                    plot.add_caption(
                        NoEscape(r'R1 AFTER trimming \textcolor{%s}{%s}' %
                                 (colour,
                                  r1_summary_trim_dict.get(
                                      'Per base sequence quality'))))
                with doc.create(SubFigure()) as plot:
                    plot.add_image(
                        '%sR2_001_fastqc/Images/per_base_quality.png' %
                        self.sample)
                    plot.add_caption('R2 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r2_summary_trim_dict.get(
                            'Per base sequence quality') == 'PASS':
                        colour = 'green'
                    elif r2_summary_trim_dict.get(
                            'Per base sequence quality') == 'WARN':
                        colour = 'orange'
                    elif r2_summary_trim_dict.get(
                            'Per base sequence quality') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image(
                        '%sR2_001.qfilter_fastqc/Images/per_base_quality.png' %
                        self.sample)
                    plot.add_caption(
                        NoEscape(r'R2 AFTER trimming \textcolor{%s}{%s}' %
                                 (colour,
                                  r2_summary_trim_dict.get(
                                      'Per base sequence quality'))))

            with doc.create(
                    Figure(position='!htb',
                           placement=NoEscape(r'\centering'))) as fig:
                fig.add_caption('Per sequence GC content')
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '5 mm'))
                    plot.add_image(
                        '%sR1_001_fastqc/Images/per_sequence_gc_content.png' %
                        self.sample)
                    plot.add_caption('R1 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '5 mm'))
                    if r1_summary_trim_dict.get(
                            'Per sequence GC content') == 'PASS':
                        colour = 'green'
                    elif r1_summary_trim_dict.get(
                            'Per sequence GC content') == 'WARN':
                        colour = 'orange'
                    elif r1_summary_trim_dict.get(
                            'Per sequence GC content') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image(
                        '%sR1_001.qfilter_fastqc/Images/per_sequence_gc_content.png'
                        % self.sample)
                    plot.add_caption(
                        NoEscape(r'R1 AFTER trimming \textcolor{%s}{%s}' %
                                 (colour,
                                  r1_summary_trim_dict.get(
                                      'Per sequence GC content'))))
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '5 mm'))
                    plot.add_image(
                        '%sR2_001_fastqc/Images/per_sequence_gc_content.png' %
                        self.sample)
                    plot.add_caption('R2 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '5 mm'))
                    if r2_summary_trim_dict.get(
                            'Per sequence GC content') == 'PASS':
                        colour = 'green'
                    elif r2_summary_trim_dict.get(
                            'Per sequence GC content') == 'WARN':
                        colour = 'orange'
                    elif r2_summary_trim_dict.get(
                            'Per sequence GC content') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image(
                        '%sR2_001.qfilter_fastqc/Images/per_sequence_gc_content.png'
                        % self.sample)
                    plot.add_caption(
                        NoEscape(r'R2 AFTER trimming \textcolor{%s}{%s}' %
                                 (colour,
                                  r2_summary_trim_dict.get(
                                      'Per sequence GC content'))))

            with doc.create(
                    Figure(position='!htb',
                           placement=NoEscape(r'\centering'))) as fig:
                fig.add_caption('Sequence Length Distribution')
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    plot.add_image(
                        '%sR1_001_fastqc/Images/sequence_length_distribution.png'
                        % self.sample)
                    plot.add_caption('R1 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r1_summary_trim_dict.get(
                            'Sequence Length Distribution') == 'PASS':
                        colour = 'green'
                    elif r1_summary_trim_dict.get(
                            'Sequence Length Distribution') == 'WARN':
                        colour = 'orange'
                    elif r1_summary_trim_dict.get(
                            'Sequence Length Distribution') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image(
                        '%sR1_001.qfilter_fastqc/Images/sequence_length_distribution.png'
                        % self.sample)
                    plot.add_caption(
                        NoEscape(r'R1 AFTER trimming \textcolor{%s}{%s}' %
                                 (colour,
                                  r1_summary_trim_dict.get(
                                      'Sequence Length Distribution'))))
                with doc.create(SubFigure()) as plot:
                    plot.add_image(
                        '%sR2_001_fastqc/Images/sequence_length_distribution.png'
                        % self.sample)
                    plot.add_caption('R2 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r2_summary_trim_dict.get(
                            'Sequence Length Distribution') == 'PASS':
                        colour = 'green'
                    elif r2_summary_trim_dict.get(
                            'Sequence Length Distribution') == 'WARN':
                        colour = 'orange'
                    elif r2_summary_trim_dict.get(
                            'Sequence Length Distribution') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image(
                        '%sR2_001.qfilter_fastqc/Images/sequence_length_distribution.png'
                        % self.sample)
                    plot.add_caption(
                        NoEscape(r'R2 AFTER trimming \textcolor{%s}{%s}' %
                                 (colour,
                                  r2_summary_trim_dict.get(
                                      'Sequence Length Distribution'))))

            with doc.create(
                    Figure(position='!htb',
                           placement=NoEscape(r'\centering'))) as fig:
                fig.add_caption('Adapter Content')
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    plot.add_image(
                        '%sR1_001_fastqc/Images/adapter_content.png' %
                        self.sample)
                    plot.add_caption('R1 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r1_summary_trim_dict.get('Adapter Content') == 'PASS':
                        colour = 'green'
                    elif r1_summary_trim_dict.get('Adapter Content') == 'WARN':
                        colour = 'orange'
                    elif r1_summary_trim_dict.get('Adapter Content') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image(
                        '%sR1_001.qfilter_fastqc/Images/adapter_content.png' %
                        self.sample)
                    plot.add_caption(
                        NoEscape(
                            r'R1 AFTER trimming \textcolor{%s}{%s}' %
                            (colour,
                             r1_summary_trim_dict.get('Adapter Content'))))
                with doc.create(SubFigure()) as plot:
                    plot.add_image(
                        '%sR2_001_fastqc/Images/adapter_content.png' %
                        self.sample)
                    plot.add_caption('R2 BEFORE trimming')
                with doc.create(SubFigure()) as plot:
                    if r2_summary_trim_dict.get('Adapter Content') == 'PASS':
                        colour = 'green'
                    elif r2_summary_trim_dict.get('Adapter Content') == 'WARN':
                        colour = 'orange'
                    elif r2_summary_trim_dict.get('Adapter Content') == 'FAIL':
                        colour = 'red'
                    else:
                        colour = 'black'
                    plot.add_image(
                        '%sR2_001.qfilter_fastqc/Images/adapter_content.png' %
                        self.sample)
                    plot.add_caption(
                        NoEscape(
                            r'R2 AFTER trimming \textcolor{%s}{%s}' %
                            (colour,
                             r2_summary_trim_dict.get('Adapter Content'))))
        '''
        doc.append(Command('FloatBarrier'))
        with doc.create(Section('BamStats')):
            with doc.create(Figure(position='htbp', placement=NoEscape(r'\centering'))):
                doc.append(Command('centering'))
                with doc.create(SubFigure()) as plot:
                    plot.add_image('%s.bwa.drm.sorted.bam.stats-quals-hm.png' % self.sample)
                    plot.add_caption('Base quality per cycle')
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('hspace', '10 mm'))
                    plot.add_image('%s.bwa.drm.sorted.bam.stats-insert-size.png' % self.sample)
                    plot.add_caption('Fragment size')
                with doc.create(SubFigure()) as plot:
                    doc.append(Command('vspace', '10 mm'))
                    plot.add_image('%s.bwa.drm.sorted.bam.stats-quals2.png' % self.sample)
                    plot.add_caption('Quality per cycle')
        '''

        pdflatex = '/usr/local/texlive/2015/bin/x86_64-linux/pdflatex'
        doc.generate_pdf('%s' % self.sample,
                         clean_tex=False,
                         compiler=pdflatex)
        os.system(
            'mv /home/cuser/PycharmProjects/amlpipeline/%s.pdf /media/sf_sarah_share/160620_M01622_0286_000000000-AR4UH/QC/'
            % self.sample)
Exemplo n.º 23
0
        print("Finished parsing row {}".format(v))
        print(wanted_bul)

    elif sheet.acell('A{}'.format(i)).value == "Stop":
        print("Finished parsing")

'''
Latex Section Begins:
'''

for i in range(2, 5):
    if __name__ == '__main__':
        v = i - 1
        doc = Document()
        doc.documentclass = Command('documentclass', options=['12pt'], arguments=['article'])
        doc.packages.append(pyl.Package('graphicx'))
        doc.packages.append(pyl.Package('fancyhdr'))
        doc.packages.append(pyl.Package('float'))

        doc.preamble.append(pyl.Command('pagestyle', 'fancy'))
        doc.preamble.append(pyl.Command('title', 'Notebook'))
        doc.append(date[v] + " - " + author[v])

        with doc.create(Section('Our Plan')):
            with doc.create(Itemize()) as itemize:
                for item in wanted_bul[v]:
                    itemize.add_item(item)
            doc.append(wanted_par[v])
        with doc.create(Section('What We Got Done')):
            with doc.create(Itemize()) as itemize:
def change_color(doc, color):
    doc.append(Command("color", arguments=color))
    yield
    doc.append(Command("color", arguments="MyDarkGrey"))
Exemplo n.º 25
0
 def add_part(self, part):
     r'''
     append a \part item
     '''
     self.append(Command('part'))
     self.append(part)
Exemplo n.º 26
0
    def start_doc(self):

        geometry_options = {"margin": "0.75in"}
        self.doc = Document(geometry_options=geometry_options)
        self.doc.preamble.append(Command('usepackage{float}'))
Exemplo n.º 27
0
 def add_question(self, question):
     r'''
     append a \question item
     '''
     self.append(Command('question'))
     self.append(question)
Exemplo n.º 28
0
def add_tex(doc, path):
    path = NoEscape(path)
    path = path.replace('\\', '/')
    doc.append(Command('input', NoEscape(path)))
Exemplo n.º 29
0
def _setup_doc(doc, book):
    doc.packages.append(Package('ctex'))
    doc.preamble.append(Command('title', NoEscape(book['title'])))
    doc.preamble.append(Command('author', book['user']))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    return doc
Exemplo n.º 30
0
    # Use our newly created command with different arguments
    doc.append(ExampleCommand(arguments=Arguments('blue', 'Hello', 'World!')))
    doc.append(ExampleCommand(arguments=Arguments('green', 'Hello', 'World!')))
    doc.append(ExampleCommand(arguments=Arguments('red', 'Hello', 'World!')))

with doc.create(Section('Custom environments')):
    doc.append(NoEscape(
        r"""
        The following is a demonstration of a custom \LaTeX{}
        environment using the mdframed package.
        """))

    # Define a style for our box
    mdf_style_definition = Command('mdfdefinestyle',
                                   arguments=['my_style',
                                              ('linecolor=#1,'
                                               'linewidth=#2,'
                                               'leftmargin=1cm,'
                                               'leftmargin=1cm')])

    # Define the new environment using the style definition above
    new_env = Command('newenvironment', 'exampleEnvironment', options=2,
                      extra_arguments=[
                          mdf_style_definition.dumps() +
                          r'\begin{mdframed}[style=my_style]',
                          r'\end{mdframed}'])
    doc.append(new_env)

    # Usage of the newly created environment
    with doc.create(
            ExampleEnvironment(arguments=Arguments('red', 3))) as environment:
        environment.append('This is the actual content')
Exemplo n.º 31
0
 def add_part(self, s: str, points: int = None):
     self.append(Command("part", options=[points]))
     self.append(s)