示例#1
0
 def comment(self, leak):
     self.doc.append(pylatex.utils.bold("Comment:"))
     self.doc.append(NewLine())
     comment = str(leak.meta.comment)
     comment = comment if len(comment) else "[empty]"
     self.doc.append(comment)
     self.doc.append(NewLine())
示例#2
0
文件: parit.py 项目: ArthurG/parit
    def write(self):
        opening = self.config['opening'].replace(
            '$organization', self.posting.get('organization'))
        closing = self.config['closing'].replace(
            '$organization', self.posting.get('organization'))
        output = Document(documentclass='letter')
        output.preamble.append(Command('signature', self.config['sender']))
        output.preamble.append(
            Command('address', NoEscape(self.return_address())))
        output.preamble.append(Command('date', NoEscape(r'\today')))
        output.append(Command('begin', ['letter', self.employer_address()]))
        output.append(Command('opening', 'Dear Hiring Manager,'))
        output.append(opening + self.write_body())
        output.append(NewLine())
        output.append(NewLine())
        output.append(closing)
        output.append(Command('closing', 'Sincerely,'))
        output.append(Command('end', 'letter'))

        filename = '{0}_{1}'.format(
            self.posting['organization'],
            ' '.join(process_input(self.posting['job_title']))).replace(
                ' ', '_').lower()
        output.generate_pdf(filename)
        output.generate_tex(filename)
示例#3
0
def prepareDoc(course):
    geometry = settings.geometry
    title = "{} DERSİ DERS DEĞERLENDİRME ANKETİ SONUÇLARI".format(course.course_name)
    
    doc = Document(indent=False, geometry_options=geometry)
    doc.preamble.append(Command("usepackage","babel","turkish"))
    doc.preamble.append(Command("usepackage","float"))
    doc.preamble.append(Command("usepackage","framed"))
    doc.preamble.append(Command("title", title))
    doc.preamble.append(NoEscape(r"\date{\vspace{-1.5cm}\today}"))
    
    doc.append(NoEscape(r"\maketitle"))
    doc.append(Command("shorthandoff","="))
    
    doc.append(Command("begin", "framed"))
    doc.append(bold("Dersin Kodu : "))
    doc.append("{}".format(course.course_code))
    doc.append(NoEscape(r"\quad"))
    doc.append("({}. sınıf)".format(course.course_grade))
    doc.append(NewLine())
    doc.append(bold("Dersin Türü : "))
    doc.append("{}".format(course.course_type))
    doc.append(NewLine())
    doc.append(bold("Dersin Grubu : "))
    doc.append("{}".format(course.course_group))
    doc.append(NewLine())
    doc.append(bold("Dersin Dönemi : "))
    doc.append("{}".format(course.course_term))
    doc.append(NewLine())
    doc.append(bold("Öğretim Üyesi : "))
    lname = course.lecturer_name + ' ' + course.lecturer_middle + ' ' + course.lecturer_surname
    doc.append(lname)
    doc.append(Command("end", "framed"))
    
    return doc
示例#4
0
文件: pdfs.py 项目: yssmcl/fly
def gerar_pdf_parecer(parecer):
    doc = pdfutils.init_document()

    pdfutils.pacotes(doc)

    # Configurações (preâmbulo)
    pdfutils.configuracoes_preambulo(doc)

    pdfutils.cabecalho(doc)

    frase_anexo = 'ANEXO XI DA RESOLUÇÃO Nº 236/2014-CEPE, DE 13 DE NOVEMBRO DE 2014.'
    pdfutils.rodape(doc, NoEscape(r'\texttt{' + frase_anexo + '}%'))
    doc.append(NoEscape(r'{\normalsize\texttt{' + frase_anexo + '}}%'))

    pdfutils.titulo(doc, 'RELATÓRIOS ESPECÍFICOS PARA ATIVIDADES DE EXTENSÃO',
                    'FORMULÁRIO ÚNICO DE PARECER DE ATIVIDADES DE EXTENSÃO')

    # Início do formulário
    with doc.create(Enumerate()) as enum:
        pdfutils.item(doc, enum, 'PARECER CONCLUSIVO DA COMISSÃO DE EXTENSÃO DE CENTRO')

    doc.append(bold('IDENTIFICAÇÃO:'))
    doc.append(NewLine())
    doc.append(NoEscape(r'Coordenador(a): {} \\'.format(escape_latex(parecer.projeto_extensao.coordenador.nome_completo))))
    doc.append(NoEscape(r'Colegiado: {} \\'.format(escape_latex(parecer.projeto_extensao.coordenador.colegiado))))
    doc.append(NoEscape(r'Centro: {} \\'.format(parecer.projeto_extensao.centro.nome)))
    doc.append(NoEscape(r'Campus: {} \\'.format(parecer.projeto_extensao.campus.nome)))
    doc.append(NoEscape(r'Título da atividade: {} \\ \\'.format(escape_latex(parecer.projeto_extensao.titulo))))
    # TODO: referente a portaria?
    # doc.append(NoEscape(r'Parecer referente a: \\ \\'))

    doc.append(bold(NoEscape(r'COMENTÁRIOS: \\')))
    pdfutils.tabela_alternativas(doc, EstadoProjeto, '|c|X|X|c|c|', id=parecer.estado_parecer.id)
    doc.append(NewLine())
    doc.append(NewLine())
    doc.append(NoEscape(r'Ata nº: {} \\'.format(escape_latex(parecer.numero_ata))))
    data = parecer.data.strftime('%d/%m/%Y')
    doc.append(NoEscape(r'Data: {} \\'.format(data)))

    texto = 'Carimbo e Assinatura do Coordenador(a) da Comissão de Extensão ou Representante Legal'
    largura = Command('widthof', texto).dumps()
    pdfutils.assinatura(doc, texto, largura, Center())

    os.system('mkdir -p ' + PDF_DIR)

    filepath = '{}/parecer_{}_projeto_{}'.format(PDF_DIR, str(parecer.id), str(parecer.projeto_extensao.id))
    doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS)

    return filepath
示例#5
0
def local_data_assinatura(doc):
    doc.append(Command('raggedleft'))
    doc.append(Command('bigskip'))
    with doc.create(MiniPage(width=r'.5\textwidth')):
        center = Center()
        center.append(Command('hrulefill'))
        center.append(NewLine())
        center.append(Command('bigskip'))
        center.append(Command('bigskip'))
        center.append(NoEscape(r'Local e data \\'))
        center.append(Command('hrulefill'))
        center.append(NewLine())
        center.append(Command('bigskip'))
        center.append(NoEscape('Assinatura do(a) Coordenador(a) da Atividade'))
        doc.append(center)
示例#6
0
    def __init__(self, periph_lib_name,
                 periph_lib):  # accepts an item from periph_libs
        self.periph_lib_name = periph_lib_name
        self.periph_lib = periph_lib
        self.out_dir = os.path.expandvars('$HDL_BUILD_DIR/ARGS/{}'.format(
            self.periph_lib_name))
        try:
            os.stat(os.path.expandvars('$HDL_BUILD_DIR/ARGS'))
        except:
            os.mkdir(os.path.expandvars('$HDL_BUILD_DIR/ARGS'))
        try:
            os.stat(
                os.path.expandvars('$HDL_BUILD_DIR/ARGS/{}'.format(
                    self.periph_lib_name)))
        except:
            os.mkdir(
                os.path.expandvars('$HDL_BUILD_DIR/ARGS/{}'.format(
                    self.periph_lib_name)))
        # self.peripheral_filename = "./peripherals/{}.peripheral.yaml".format(peripheralname)
        # self.config = yaml.load(open(self.peripheral_filename, "r"))

        geometry_options = {"tmargin": "1cm", "lmargin": "2.5cm"}
        self.doc = Document(font_size='small',
                            geometry_options=geometry_options)
        self.doc.packages.add(Package('hyperref', 'bookmarks'))
        self.doc.preamble.append(
            Command(
                'title',
                'ARGS Documentation for Peripheral Library \'{}\''.format(
                    self.periph_lib_name)))
        self.doc.preamble.append(Command('author', 'ARGS script gen_doc.py'))
        self.doc.preamble.append(Command('date', NoEscape(r'\today')))
        self.doc.append(NoEscape(r'\hbadness=10000'))
        self.doc.append(NoEscape(r'\maketitle'))
        self.doc.append(NewLine())
        self.doc.append(bold('Peripheral library description\n'))
        self.doc.append(self.periph_lib['description'])
        self.doc.append(NewLine())
        self.doc.append(NewLine())
        self.doc.append(
            bold('Peripheral library configuration file location\n'))
        self.doc.append(
            self.periph_lib['file_path_name'].split('Firmware')[-1])
        self.doc.append(NewLine())
        self.doc.append(NewLine())
        self.doc.append('Note: All addressing is byte-wise')
        self.doc.append(Command('tableofcontents'))
        self.doc.append(NewPage())
 def addNewLine2Doc(self):
     """To add a new line to the document. If use NewLine() without
     the \leavevmode command, pdflatex will throw a 'no line to break' error.
     """
     self.doc.append(NoEscape(r'\leavevmode'))
     self.doc.append(NewLine())
     return
示例#8
0
def assinatura(doc, texto, largura, pos_env):
    doc.append(Command('bigskip'))
    doc.append(Command('bigskip'))
    doc.append(Command('bigskip'))
    with doc.create(pos_env) as pos:
        with pos.create(MiniPage(width=largura)) as mini:
            mini.append(Command('hrulefill'))
            mini.append(NewLine())
            mini.append(NoEscape(r'{}'.format(texto)))
示例#9
0
 def add_content(self, s, space=None):
     self.append(s)
     if self.standard == "XD":
         if space:
             self.append(NoEscapeStr(r"\vspace{" + space + "cm}"))
         else:
             self.append(NewLine())
     if self.key:
         self.append(self.key)
示例#10
0
    def __init__(self, fpga_name, fpga_lib):
        self.fpga_name = fpga_name
        self.out_dir = os.path.expandvars('$HDL_BUILD_DIR/ARGS/{}'.format(
            self.fpga_name))

        try:
            os.stat(
                os.path.expandvars('$HDL_BUILD_DIR/ARGS/{}'.format(
                    self.fpga_name)))
        except:
            os.mkdir(
                os.path.expandvars('$HDL_BUILD_DIR/ARGS/{}'.format(
                    self.fpga_name)))
        self.fpga = fpga_lib['fpga']
        self.fpga_lib = fpga_lib
        # self.fpga_filename = "./systems/{}.fpga.yaml".format(fpganame)
        # self.config = yaml.load(open(self.fpga_filename, "r"))

        geometry_options = {"tmargin": "1cm", "lmargin": "2.5cm"}
        self.doc = Document(geometry_options=geometry_options)
        self.doc.packages.add(Package(
            'hyperref',
            'bookmarks'))  #(Command('usepackage','bookmarks','hyperref'))
        self.doc.preamble.append(
            Command(
                'title', 'ARGS Documentation for FPGA design \'{}\''.format(
                    self.fpga_name)))
        self.doc.preamble.append(Command('author', 'ARGS script gen_doc.py'))
        self.doc.preamble.append(Command('date', NoEscape(r'\today')))
        self.doc.append(NoEscape(r'\maketitle'))
        self.doc.append(NewLine())
        self.doc.append(bold('FPGA design description\n'))
        self.doc.append(self.fpga.fpga_description)
        self.doc.append(NewLine())
        self.doc.append(NewLine())
        self.doc.append(bold('FPGA design configuration file location\n'))
        self.doc.append(self.fpga_lib['file_path_name'].split('Firmware')[-1])
        self.doc.append(NewLine())
        self.doc.append(Command('tableofcontents'))
        self.doc.append(NewPage())
示例#11
0
    def makeReport(self, reportName='report', tex_only=False):
        '''Automated generation of report structure'''
        # For section inside the folder, add sections
        sectPath = os.path.join(self.fpath, 'sections')
        # for sect in os.listdir(sectPath):
        for sect in self.sections:
            sectFile = os.path.join('../sections', sect)
            self.addText2Doc(r'\input{' + sectFile + r'}')
            self.doc.append(NewLine())
            self.doc.append(LineBreak())

        # For figures inside the folder, add figures
        figPath = os.path.join(self.fpath, 'figures')
        self.doc.create(Section('Figures'))
        for fig in os.listdir(figPath):
            self.addFig2Doc(fig)
            self.doc.append(NewLine())
            self.doc.append(LineBreak())

        # For tables inside the folder, add tables
        tblPath = os.path.join(self.fpath, 'tables')
        self.doc.create(Section('Tables'))
        for tbl in os.listdir(tblPath):
            self.addTbl2Doc(tbl)
            self.doc.append(NewLine())
            self.doc.append(LineBreak())

        # For apx inside the folder, add apx
        self.addAppendix()

        ## generate tex/pdf
        if tex_only:
            self.doc.generate_tex(os.path.join(self.outputPath, self.name))
        else:
            self.doc.generate_pdf(os.path.join(self.outputPath, self.name),
                                  clean_tex=False)

        return
示例#12
0
def tabela_gestao_recursos_financeiros(doc, enum, previsao_orcamentaria):
    item(doc, enum, NoEscape(r'GESTÃO DOS RECURSOS FINANCEIROS: '))

    doc.append(Command('noindent'))
    with doc.create(Enumerate(options={'leftmargin': '7pt'})) as subenum:
        subenum.add_item(
            bold(NoEscape(r'ÓRGÃO GESTOR DOS RECURSOS FINANCEIROS \\')))

    with doc.create(MdFramed(options=MDFRAMED_OPTIONS)):
        doc.append(NoEscape(r'IDENTIFICAÇÃO: \\'))

        for tipo_gestao in TipoGestaoRecursosFinanceiros.objects.all():
            nome_tipo_gestao = tipo_gestao.nome.upper()

            if previsao_orcamentaria.identificacao and previsao_orcamentaria.identificacao.id == tipo_gestao.id:
                marcador = TIMES
            else:
                marcador = PHANTOM

            if nome_tipo_gestao in ('PRAP', 'SECRETARIA FINANCEIRA',
                                    'UNIOESTE'):
                doc.append(
                    NoEscape(r'({}) {} \\'.format(marcador, nome_tipo_gestao)))
            elif nome_tipo_gestao in 'FUNDAÇÃO':
                doc.append(
                    NoEscape(r'({}) {}: '.format(marcador,
                                                 bold(nome_tipo_gestao))))
                if previsao_orcamentaria.fundacao:
                    doc.append(escape_latex(previsao_orcamentaria.fundacao))
                    doc.append(NewLine())
            else:  # outros
                doc.append(
                    NoEscape(r'({}) {}: '.format(marcador,
                                                 bold(nome_tipo_gestao))))
                if previsao_orcamentaria.outro_orgao_gestor:
                    doc.append(
                        escape_latex(previsao_orcamentaria.outro_orgao_gestor))
                    doc.append(NewLine())
示例#13
0
 def statistics(self, leak):
     ml = leak.status.max_leak()
     if ml is None:
         return
     self.doc.append(NewLine())
     self.doc.append(pylatex.utils.bold("Generic Test Result:"))
     self.doc.append(NewLine())
     ml_type = f"H_{ml.nstype}" if isinstance(ml, NSLeak) else f"M_{ml.sptype}"
     with self.doc.create(pylatex.Tabular("l l l l l")) as data_table:
         data_table.add_row(
             ["Source", "Kuiper", "Significance", "Confidence", "Key"]
         )
         data_table.add_hline()
         data_table.add_row(
             [
                 ml_type,
                 f"{ml.teststat:.3f}",
                 f"{ml.limit:.3f}",
                 f"{ml.confidence}",
                 str(ml.key),
             ]
         )
     self.doc.append(NewLine())
示例#14
0
def tabela_unidade_administrativa(doc, enum, unidade_administrativa, campus):
    item(doc, enum, 'UNIDADE ADMINISTRATIVA: ')
    for unidade in UnidadeAdministrativa.objects.all():
        if unidade_administrativa and unidade_administrativa.id == unidade.id:
            doc.append(NoEscape(r'{} ({}) '.format(unidade.nome, TIMES)))
        else:
            doc.append(NoEscape(r'{} ({}) '.format(unidade.nome, PHANTOM)))
    doc.append(NewLine())

    doc.append(bold('CAMPUS DE: '))
    for c in Campus.objects.all():
        if campus and campus.id == c.id:
            doc.append(NoEscape(r'{} ({}) '.format(c.nome, TIMES)))
        else:
            doc.append(NoEscape(r'{} ({}) '.format(c.nome, PHANTOM)))
示例#15
0
def mdframed_plano_trabalho(doc, objs):
    doc.append(LineBreak())

    mdframed_options_plano = 'innertopmargin=5pt, innerleftmargin=3pt, innerrightmargin=3pt, topline=false'

    with doc.create(MdFramed(options=mdframed_options_plano)):
        doc.append(bold('PLANO DE TRABALHO: '))

        planos = []
        for obj in objs:
            planos.append(obj.plano_trabalho)

        for plano in planos:
            doc.append(escape_latex(plano))
            doc.append(NewLine())
示例#16
0
    def fill(self):
        with self.doc.create(
                Section("{} FPGA system map".format(self.fpga_name))):
            self.doc.append(self.fpga.fpga_description)
            self.doc.append(NewLine())
            self.doc.append(NewLine())
            self.doc.append(MediumText(bold('Slave Port Map')))
            self.doc.append(NewLine())
            self.doc.append(NewLine())
            fpga_system_table = Tabular('|c|c|c|c|c|')
            fpga_system_table.add_hline()
            fpga_system_table.add_row(
                ('Hex', 'Range (Bytes)', 'Slave Port', 'Protocol', 'Port No.'))
            fpga_system_table.add_hline()

            for slave_port, slave_dict in self.fpga.address_map.items():
                fpga_system_table.add_row(
                    (str(hex(slave_dict['base'])), str(slave_dict['span']),
                     slave_port, slave_dict['type'], slave_dict['port_index']))
                fpga_system_table.add_hline()
            self.doc.append(fpga_system_table)

        for periph_name, periph in self.fpga.peripherals.items():
            self.peripheral_fill(periph, periph_name)
示例#17
0
def fill_paragraph(io_doc, i_specification_line, io_sections_dict,
                   io_characteristic_bloc):
    should_add_description = True
    if i_specification_line.has_sub_sub_section() and i_specification_line.sub_sub_section not in \
            io_sections_dict[i_specification_line.section][i_specification_line.sub_section]:
        io_sections_dict[i_specification_line.section][
            i_specification_line.sub_section].append(
                i_specification_line.sub_sub_section)
    elif i_specification_line.has_sub_section(
    ) and i_specification_line.sub_section not in io_sections_dict[
            i_specification_line.section]:
        io_sections_dict[i_specification_line.section][
            i_specification_line.sub_section] = []
    elif i_specification_line.has_section(
    ) and i_specification_line.section not in io_sections_dict:
        io_sections_dict[i_specification_line.section] = {}
    else:
        should_add_description = False
    if should_add_description:
        io_characteristic_bloc.bloc = None
        if i_specification_line.has_description():
            io_doc.append(i_specification_line.description)
            io_doc.append(NewLine())
    if i_specification_line.has_characteristics():
        if io_characteristic_bloc.bloc is None:
            with io_doc.create(
                    Tabular('|' +
                            'c|' * len(i_specification_line.characteristics))
            ) as table:
                io_characteristic_bloc.bloc = table
                table.add_hline()
                table.add_row(i_specification_line.characteristics.keys(),
                              color='lightgray')
                table.add_hline()
                table.add_row(i_specification_line.characteristics.values())
                table.add_hline()
        else:
            io_characteristic_bloc.bloc.add_row(
                i_specification_line.characteristics.values())
            io_characteristic_bloc.bloc.add_hline()
示例#18
0
	def _write_questions(self, info):
		self._doc.append(NoEscape(r'\flushleft'))
		i = 1
		for question, answers, options in info['questions']:
			self._doc.append('{}. {}'.format(i, question))
			self._doc.append(LineBreak())
			for image in options['images']:
				with self._doc.create(Figure(position='h!')) as fig:
					fig.add_image(image['src'], width='{}px'.format(image.get('width', 100)))
					if image.get('description'):
						fig.add_caption(image.get('description'))
			i += 1
			if len(answers) == 0:
				for _ in range(options['hints'].get('max_lines', 1)):
					self._doc.append(NewLine())
			else:
				l = options['hints'].get('max_cols', 1)
				table_data = [answers[j:j+l] for j in range(0, len(answers), l)]
				with self._doc.create(Tabular('l'*l)) as table:
					for row in table_data:
						table.add_row(row, mapper = lambda x: NoEscape(r'$\Box~~$') + x, strict=False)
			self._doc.append(LineBreak())
示例#19
0
def cabecalho(doc):
    # Remove linha horizontal no cabeçalho
    doc.append(
        Command('renewcommand', arguments=[Command('headrulewidth'), '0pt']))

    with doc.create(Head('L')) as header:
        header.append(StandAloneGraphic('logo-unioeste.png', 'width=200px'))
        header.append(NewLine())
        header.append(
            NoEscape(r'''{\footnotesize
Reitoria -- CNPJ 78680337/0001-84 \\
Rua Universitária, 1619 -- Fone: (45) 3220-3000 -- Fax: (45) 3324-4590 \\
Jardim Universitário -- Cx. P. 000701 -- CEP 85819-110 -- Cascavel -- Paraná \\
www.unioeste.br
}'''))

    doc.append(
        Head(
            'R',
            data=NoEscape(
                r'\parbox[b][4.3cm][t]{\textwidth}{\raggedleft\includegraphics[width=80px]{logo-governo.jpg}}%'
            )))  # mágica
示例#20
0
文件: args.py 项目: cmrfrd/PyLaTeX
def test_basic():
    # Tests the basic commands and environments
    # Basic commands
    new_page = NewPage()
    repr(new_page)

    new_line = NewLine()
    repr(new_line)

    line_break = LineBreak()
    repr(line_break)

    h_fill = HFill()
    repr(h_fill)

    # Basic environments
    huge = HugeText("Huge")
    huge.append("Huge 2")
    repr(huge)

    large = LargeText("Large")
    large.append("Large 2")
    repr(large)

    medium = MediumText("Medium")
    medium.append("Medium 2")
    repr(medium)

    small = SmallText("Small")
    small.append("Small 2")
    repr(small)

    footnote = FootnoteText("Footnote")
    footnote.append("Footnote 2")
    repr(footnote)

    text_color = TextColor("green", "GreenText")
    text_color.append("More Green Text")
    repr(text_color)
示例#21
0
    def peripheral_fill(self, periph, periph_name):
        self.doc.append(NewPage())
        periph_subsection = Section(periph_name, numbering=True)
        periph_subsection.append(periph.get_description().replace('""', ''))
        periph_reg_section = Subsection(
            "{} register slave".format(periph_name), numbering=False)
        periph_reg_table = Tabular('|c|c|c|c|')
        periph_reg_table.add_hline()
        periph_reg_table.add_row(
            ('Base Address', 'Range', 'Register group', 'Number of Slaves'))
        periph_reg_table.add_hline()
        # slave_subsections = ("{} slaves".format(periph_name), numbering=False)
        # slave_subsections = []
        # slave_subsections.append(NewLine())
        # slave_subsections.append(MediumText(bold("Slave Ports for peripheral " + periph_name + "\n")))
        slave_subsections = Subsection(
            "Slave Ports for peripheral \'{}\'".format(periph_name),
            numbering=False)
        for slave in periph.slaves:

            #self.doc.add(text=val_type, size="medium")

            # added_val_types = []
            # for key, val in sorted(val_info.items()):
            # if val.name() in added_val_types:
            # continue
            # added_val_types.append(val.name())
            slave_subsection = Subsection("Slave Port: {} ({})".format(
                slave.name(), 'Register block' if isinstance(slave, Register)
                else 'RAM' if isinstance(slave, RAM) else 'FIFO'),
                                          numbering=True)
            slave_subsection.append(slave.get_kv('slave_description'))
            slave_subsection.append(NewLine())
            # slave_subsection.append("Slave Type: {}".format('REGISTER' if isinstance(slave, Register) else 'RAM' if isinstance(slave, RAM) else 'FIFO'))
            slave_subsection.append(NewLine())
            slave_subsection.append("Address Length: {} bytes".format(
                str(slave.address_length())))
            slave_subsection.append(NewLine())
            slave_subsection.append("Number of Slaves: {}".format(
                str(slave.number_of_slaves())))
            slave_subsection.append(NewLine())
            slave_subsection.append(NewLine())

            # if val_type == 'Registers':
            if isinstance(slave, Register):  # expand registers and fields
                for ram in slave.rams:
                    periph_reg_table.add_row(
                        (str(ram.base_address()), str(ram.number_of_fields()),
                         ram.name() + ' (RAM)', str(slave.number_of_slaves())))
                    periph_reg_table.add_hline()
                periph_reg_table.add_row(
                    (str(slave.base_address()), str(slave.address_length()),
                     slave.name(), str(slave.number_of_slaves())))
                periph_reg_table.add_hline()
                added_field_groups = []
                # with self.doc.create(Subsection("{} Register Fields".format(val.name().lower()), numbering=True)):
                # if val.get_kv('slave_description') is not None:
                # slave_subsection.append(val.get_kv('slave_description').replace('"', ''))

                # generate register table i.e. by word
                group_address = -1
                group_list = []
                for field in slave.fields:
                    if field.address_offset() != group_address:
                        group_address = field.address_offset()
                        group_list.append(field)
                        # addr_name = field.group_name() if field.group_name() != "None" else field.name()

                        # slave_table.add_row(str(hex(field.address_offset())), addr_name)
                        # slave_table.add_hline()
                c_max_rows = 30
                nof_cols = ceil(
                    len(group_list) /
                    c_max_rows)  # register table has max length of 40
                nof_rows = min(len(group_list), c_max_rows)
                slave_table = Tabular('|c|c|' * nof_cols)
                slave_table.add_hline()
                # slave_table.add_row((*['Hex','Field Group']*nof_cols))
                slave_table.add_row(['Hex', 'Field Group'] * nof_cols)
                slave_table.add_hline()
                for i in range(nof_rows):
                    row = []
                    for j in range(nof_cols):
                        if i + c_max_rows * j < len(group_list):
                            field.group_name() if field.group_name(
                            ) != "None" else field.name()
                            row.extend([
                                str(
                                    hex(group_list[i + c_max_rows *
                                                   j].address_offset())),
                                group_list[i + c_max_rows * j].name()
                            ])
                        else:
                            row.extend(['', ''])
                    # slave_table.add_row(*row)
                    slave_table.add_row(row)
                    slave_table.add_hline()

                slave_subsection.append(slave_table)
                slave_subsection.append(NewPage())

                group_address = -1
                for field in slave.fields:
                    # if field.group_name() is None or field.group_name() != last_group: # base on group_address instead
                    # print("field {} address {} bit{}".format(field.name(), str(field.address_offset()), str(field.bit_offset())))
                    if field.address_offset() != group_address:
                        group_address = field.address_offset()
                        # group_page = MiniPage()
                        group_subsection = Subsection('{} {}'.format(
                            str(hex(field.address_offset())),
                            field.name() if field.group_name() == 'None' else
                            field.group_name()),
                                                      numbering=False)
                        group_fields = [
                            field for field in slave.fields
                            if field.address_offset() == group_address
                        ]
                        if len(group_fields) > 10:
                            slave_subsection.append(NewPage())
                        group_subsection = gen_reg_tables(
                            group_subsection, group_fields)
                        for field in group_fields[::-1]:
                            field_name = field.name() if field.group_name(
                            ) == 'None' else field.name().split(
                                field.group_name() + '_')[-1]
                            bit_string = "Bit {}".format(
                                str(field.bit_offset())) if field.width(
                                ) == 1 else "Bits {}:{}".format(
                                    str(field.bit_offset() + field.width() -
                                        1), str(field.bit_offset()))
                            group_subsection.append(
                                bold("{}\t\t{} ({}):".format(
                                    bit_string, field_name,
                                    field.access_mode())))
                            group_subsection.append("\t\t{}".format(
                                field.field_description()))
                            group_subsection.append(NewLine())
                            group_subsection.append(NewLine())
                        # group_page.append(group_subsection)
                        slave_subsection.append(group_subsection)
            else:  # RAM or FIFO
                slave_subsection.append("Data width: {}".format(slave.width()))
                slave_subsection.append(NewLine())
                if isinstance(slave, RAM):
                    slave_subsection.append("User data width: {}".format(
                        slave.user_width()))

            slave_subsections.append(slave_subsection)
        periph_reg_section.append(periph_reg_table)
        self.doc.append(periph_subsection)
        if any([isinstance(slave, Register) for slave in periph.slaves]):
            self.doc.append(periph_reg_section)
        # for i in range(len(slave_subsections)):
        # self.doc.append(slave_subsections[i])
        self.doc.append(slave_subsections)

        # self.doc.append(periph_section)
        self.doc.append(NewPage())
示例#22
0
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', 'PyTex特色功能展示'),
                author=Command('kaishu', '六个骨头'),
                date=Command('today'))
core.body_append(Command('maketitle'))

#  ——————————特色功能展示——————————
core.body_append(Command("noindent"))

with core.local_define([r"d"], [r"b"]) as local_core:  # 用r字符写正则表达式
    local_core.append(NoEscape(r"定义简单局部替换:$dif d d dx$"), mode="str")
core.body_append(NewLine())

# with core.local_define([r"\\d"], [r"\\text{d}"]) as local_core:
#     local_core.append(NoEscape(r"定义简单局部符号:$\dif \d \d dx$"), mode="re")
# core.body_append(NewLine())

with core.local_define(
    [re.compile(r"<a>(\S+)</a>"),
     re.compile(r"<a href=(\S+)>(\S+)</a>")],  # 用r字符写正则表达式
    [
        lambda m: r"\href{" + m.group(1) + "}{" + m.group(1) + "}",
        lambda m: r"\href{" + m.group(1) + "}{" + m.group(2) + "}"
    ],
        package="hyperref") as local_core:
    local_core.append(
        r"使用正则表达式定义复杂局部符号:<a href=www.baidu.com>百度</a> <a>www.baidu.com</a>",
示例#23
0
            'Date', 'Domestic Ordinary Shares', 'Foreign Ordinary Shares',
            'FGN Securities', 'State Government Securities',
            'Corporate Debt Securities', 'Local Money Market Securities',
            'Foreign Money Market Securities', 'Supra-National Bonds')
        table.add_hline()
        for index, row in dfPensionUSD.iterrows():
            table.add_row(row['date'], row['domestic ordinary shares'],
                          row['foreign ordinary shares'],
                          row['fgn securities'],
                          row['state government securities'],
                          row['corporate debt securities'],
                          row['local money market securities'],
                          row['foreign money market securities'],
                          row['supra-national bonds'])
    doc.append(NoEscape(r'}'))
    doc.append(NewLine())
    doc.append('\n\n...')
    doc.append(NoEscape(r'\scalebox{0.6}{'))
    with doc.create(Tabular('r|r|r|r|r|r')) as table:
        table.add_row('Mutual Funds', 'Real Estate Properties',
                      'Private Equity Fund', 'Infrastructure Fund',
                      'Cash & Other Assets', 'Other Liabilities')
        table.add_hline()
        for index, row in dfPensionUSD.iterrows():
            table.add_row(row['mutual funds'], row['real estate properties'],
                          row['private equity fund'],
                          row['infrastructure fund'],
                          row['cash & other assets'], row['other liabilities'])
    doc.append(NoEscape(r'}'))

    doc.append(bold('\n\nNGN bn\n'))
示例#24
0
    def fill(self):
        with self.doc.create(
                Section("{} system.".format(self.config['system_name']))):
            self.doc.append(self.system.system_description)

        with self.doc.create(Section("Peripherals.")):
            added_instances = []
            for peri_name, peri_class in sorted(
                    self.system.peripherals.items()):
                if peri_class.name() in added_instances:
                    continue
                added_instances.append(peri_class.name())

                with self.doc.create(Section(peri_class.name(),
                                             numbering=True)):
                    self.doc.append(
                        peri_class.get_kv('peripheral_description').replace(
                            '"', ''))
                    self.doc.append(NewLine())

                    #self.doc.append(MediumText(bold("slave ports.")))

                    for val_info, val_type in ((peri_class.registers,
                                                'Registers'), (peri_class.rams,
                                                               'Rams'),
                                               (peri_class.fifos, 'Fifos')):

                        if len(val_info) == 0:
                            continue

                        #self.doc.add(text=val_type, size="medium")

                        added_val_types = []
                        for key, val in sorted(val_info.items()):
                            if val.name() in added_val_types:
                                continue
                            added_val_types.append(val.name())

                            with self.doc.create(
                                    Subsection("{} slave.".format(
                                        val.name().lower()),
                                               numbering=True)):
                                if val.get_kv('slave_description') is not None:
                                    self.doc.append(
                                        val.get_kv(
                                            'slave_description').replace(
                                                '"', ''))
                                added_fields = []
                                for field_key, field_val in sorted(
                                        val.fields.items()):
                                    real_name = field_val.name().strip().split(
                                        '.')[0]
                                    if real_name in added_fields:
                                        continue
                                    added_fields.append(real_name)
                                    with self.doc.create(
                                            Subsubsection("{} field.".format(
                                                "{}".format(real_name)),
                                                          numbering=True)):
                                        self.doc.append(
                                            field_val.get_kv(
                                                'field_description').replace(
                                                    '"', ''))
示例#25
0
文件: pdfs.py 项目: yssmcl/fly
def gerar_pdf_certificado(certificado):

    # Configurações da classe
    geometry_options = {'landscape': True,
                        'left': '2cm',
                        'right': '1cm'}
    doc = Document(geometry_options=geometry_options, lmodern=False, document_options=['a4paper', 'brazil'],
                   inputenc=None, fontenc=None, font_size='footnotesize')

    # Pacotes
    doc.packages.add(Package('microtype'))
    doc.packages.add(Package('indentfirst'))
    doc.packages.add(Package('graphicx'))
    doc.packages.add(Package('calc'))
    doc.packages.add(Package('fontspec'))
    options_background = ['scale=1',
                          'opacity=1',
                          'angle=0']
    doc.packages.add(Package('background', options=options_background))
    doc.packages.add(Package('csquotes'))

    # Configurações (preâmbulo)
    doc.preamble.append(Command('MakeOuterQuote', '\"'))  # coverte aspas automaticamente, sem precisar de `` e ''
    doc.preamble.append(Command('renewcommand', arguments=[Command('baselinestretch'), '1.5']))
    doc.preamble.append(Command('setlength', arguments=[Command('parindent'), NoEscape(r'.35\textwidth')]))
    doc.preamble.append(Command('setlength', arguments=[Command('parskip'), '0.2cm']))
    doc.preamble.append(Command('setlength', arguments=[Command('emergencystretch'), '5pt']))

    # Imagem de fundo
    doc.preamble.append(NoEscape(r'\backgroundsetup{ contents=\includegraphics{modelo-certificado-20.pdf} }'))

    # Diretório das imagens
    img_dir = '{}/base/static/img/'.format(BASE_DIR)  # necessário barra no final
    doc.preamble.append(UnsafeCommand('graphicspath', '{{{}}}'.format(img_dir)))

    # Início do documento
    doc.append(UnsafeCommand('setmainfont', 'Latin Modern Sans', ['SizeFeatures={Size=16}', 'Ligatures=TeX']))

    doc.append(Command('pagestyle', 'empty'))
    doc.append(Command('BgThispage'))

    doc.append(VerticalSpace(size='2cm', star=True))

    with doc.create(FlushRight()) as fr:
        fr.append(StandAloneGraphic('titulo-certificado.pdf', 'width=6.5cm'))
        fr.append(LineBreak())

    doc.append(VerticalSpace(size=NoEscape('-1cm'), star=True))
    doc.append(Command('Large'))

    # Usado para o nome dos meses ('%B')
    locale.setlocale(locale.LC_ALL, 'pt_BR.UTF-8')

    inicio = certificado.relatorio.periodo_inicio.strftime('%d de %B de %Y').lower()
    fim = certificado.relatorio.periodo_inicio.strftime('%d de %B de %Y').lower()
    # TODO: tá faltando coisa
    texto_principal = r'''

    Certificamos que \textbf{{{nome}}} atuou como {funcao}, {sob_coordenacao}no período de {inicio} a {fim}, na cidade de Foz do Iguaçu -- Paraná, com a atividade de extensão: "\textbf{{{titulo}}}", com carga horária de {carga_horaria_total} horas.

    '''

    if certificado.funcao.nome == 'Coordenador(a)':
        sob_coordenacao = ''
    else:
        nome_coordenador = certificado.relatorio.projeto_extensao.coordenador.nome_completo
        sob_coordenacao = r'sob a coordenação de \textbf{{{}}}, '.format(escape_latex(nome_coordenador))

    texto_principal = texto_principal.format(nome=escape_latex(certificado.nome),
                                             funcao=certificado.funcao.nome.lower(),
                                             sob_coordenacao=sob_coordenacao,
                                             inicio=inicio,
                                             fim=fim,
                                             titulo=escape_latex(certificado.relatorio.projeto_extensao.titulo),
                                             carga_horaria_total=str(certificado.carga_horaria_total).split('.')[0])

    # texto_principal = NoEscape(r'''

    # Certificamos que \textbf{Adriana de Oliveira Gomes} participou como bolsista do Programa de Apoio a Inclusão Social em Atividades de Extensão -- Convênio No 750/2014 -- Fundação Araucária, Edital 05/2014-PROEX, sob a orientação do (a) professor (a) \textbf{Fernando Amâncio Aragão}, no período de outubro/2014 a setembro/2015, com a atividade de extensão: \textbf{''Atendimento fisioterapêutico para pacientes com sequelas neurológicas baseada em tarefas funcionais.''}, com carga horária de 960 (novecentas e sessenta) horas.

    # ''')

    doc.append(NoEscape(texto_principal))

    doc.append(VerticalSpace(size='1.5cm', star=True))

    doc.append(HorizontalSpace(size='7cm', star=True))
    dia = timezone.now().strftime('%d')
    mes = timezone.now().strftime('%B')
    ano = timezone.now().strftime('%Y')

    data = NoEscape(r'Foz do Iguaçu, {} de {} de {}'.format(dia, mes, ano))
    largura = Command('widthof', data).dumps()
    with doc.create(MiniPage(width=largura)) as mini:
        with mini.create(Center()) as center:
            center.append(data)
            center.append(NewLine())
            center.append(NewLine())
            center.append(NewLine())
            center.append('Coordenador do Projeto de Extensão')
            center.append(NewLine())
            center.append(NewLine())
            center.append(NewLine())
            center.append('Diretor de Centro')

    os.system('mkdir -p ' + PDF_DIR)

    filepath = '{}/certificado_{}'.format(PDF_DIR, str(certificado.id))
    doc.generate_pdf(filepath, clean_tex=False, compiler=pdfutils.COMPILER, compiler_args=pdfutils.COMPILER_ARGS)

    return filepath
示例#26
0
def make_pdf_report():
    """ assume profile available """

    pieces = gd.sessionInfo['Pieces']
    cntrating = [cr for nm, x, cr, tl in pieces]

    # we need a (single) temp dir for intermediates.
    tmpdir = Path(tempfile.gettempdir()) / 'RtcApp'
    if not tmpdir.is_dir():
        tmpdir.mkdir()
    # subdir
    if not reportsDir().is_dir():
        reportsDir().mkdir()

    reportfile = reportsDir() / gd.config['Session']

    crewname = gd.metaData['CrewName']

    geometry_options = {
        "top": "5mm",
        "bottom": "5mm",
        "right": "5mm",
        "left": "5mm"
    }
    doc = Document(documentclass='article',
                   geometry_options=geometry_options,
                   document_options=["12pt"])

    doc.preamble.append(NoEscape(r'\usepackage{graphicx}'))

    # see https://doc.qt.io/qt-5/qml-color.html for colors
    doc.append(NoEscape(r'\definecolor{aquamarine}{HTML}{7fffd4}'))
    doc.append(NoEscape(r'\definecolor{gainsboro}{HTML}{dcdcdc}'))

    #   First page
    with doc.create(
            Section(f'Boat report {gd.metaData["CrewName"]}',
                    numbering=False)):

        r = gd.metaData["Rowers"]
        rwrcnt = gd.sessionInfo['RowerCnt']
        if rwrcnt == 1:
            doc.append('Rowers: ')
            doc.append(f'{r[0][0]} ')
        else:
            doc.append('Rowers from bow: ')
            for i in range(rwrcnt):
                doc.append(f'{r[i][0]}, ')
        doc.append(NewLine())
        doc.append(f'Boattype: {gd.metaData["BoatType"]}\n')
        doc.append(f'Calibration: {gd.metaData["Calibration"]}\n')
        doc.append(f'Misc: {gd.metaData["Misc"]}\n')
        doc.append(f'Powerline: {gd.metaData["PowerLine"]}\n')
        doc.append(f'Venue: {gd.metaData["Venue"]}\n')
        doc.append(VerticalSpace("5pt"))
        doc.append(NewLine())

        # get table from boat report
        rows = gd.boattablemodel.rowCount()
        columns = gd.boattablemodel.columnCount()
        boattab = 'l|' + ''.join(['r' for i in range(columns - 1)]) + '|'
        with doc.create(Tabular(boattab)) as table:
            table.add_hline()
            row = []
            for j in range(columns):
                index = QAbstractTableModel.index(gd.boattablemodel, 0, j)
                row.append(str(gd.boattablemodel.data(index)))
            table.add_row(row, color='aquamarine')
            table.add_hline()

            cnt = 0
            for i in range(rows):
                row = []
                if i == 0:
                    continue
                for j in range(columns):
                    index = QAbstractTableModel.index(gd.boattablemodel, i, j)
                    row.append(str(gd.boattablemodel.data(index)))
                if cnt % 2 == 0:
                    table.add_row(row, color='gainsboro')
                else:
                    table.add_row(row, color='aquamarine')
                cnt += 1
            table.add_hline()
            """

            table.add_empty_row()
            table.add_row((4, 5, 6, 7))
            """
    doc.append(NewPage())

    # for the plots
    fontP = FontProperties()
    fontP.set_size('xx-small')

    # Second page
    with doc.create(
            Section(f'Boat report {gd.metaData["CrewName"]}',
                    numbering=False)):

        av = ''
        filt = ''
        if gd.averaging:
            av = 'averaging'
        if gd.filter:
            filt = 'filtered'
        pcs = ['all'] + gd.p_names + ['average']
        doc.append(f'Using piece "{pcs[gd.boatPiece]}": {av} {filt}\n')
        doc.append(VerticalSpace("5pt"))
        doc.append(NewLine())

        sensors = gd.sessionInfo['Header']
        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)

        ax1.set_title('Speed')
        ax1.grid(True)
        ax2.set_title('Acceleration')
        ax2.grid(True)
        ax3.set_title('Pitch')
        ax3.grid(True)
        ax4.set_title('Accel-Tempo per Piece')
        ax4.grid(True)

        piece = gd.boatPiece
        if piece == 0:
            for i in range(len(gd.p_names)):
                ax1.plot(gd.norm_arrays[i, :, sensors.index('Speed')],
                         linewidth=0.6,
                         label=gd.p_names[i])
                ax2.plot(gd.norm_arrays[i, :, sensors.index('Accel')],
                         linewidth=0.6,
                         label=gd.p_names[i])
                ax3.plot(gd.norm_arrays[i, :,
                                        sensors.index('Pitch Angle')],
                         linewidth=0.6,
                         label=gd.p_names[i])
        elif piece == 7:
            speed = np.zeros(gd.norm_arrays[0, :, 1].shape)
            accel = np.zeros(gd.norm_arrays[0, :, 1].shape)
            pitch = np.zeros(gd.norm_arrays[0, :, 1].shape)
            for i in range(len(gd.p_names)):
                speed += gd.norm_arrays[i, :, sensors.index('Speed')]
                accel += gd.norm_arrays[i, :, sensors.index('Accel')]
                pitch += gd.norm_arrays[i, :, sensors.index('Pitch Angle')]
            ax1.plot(speed / 6, linewidth=0.6, label=gd.p_names[i])
            ax2.plot(accel / 6, linewidth=0.6, label=gd.p_names[i])
            ax3.plot(pitch / 6, linewidth=0.6, label=gd.p_names[i])
        else:
            i = piece - 1
            ax1.plot(gd.norm_arrays[i, :, sensors.index('Speed')],
                     linewidth=0.6,
                     label=gd.p_names[i])
            ax2.plot(gd.norm_arrays[i, :, sensors.index('Accel')],
                     linewidth=0.6,
                     label=gd.p_names[i])
            ax3.plot(gd.norm_arrays[i, :, sensors.index('Pitch Angle')],
                     linewidth=0.6,
                     label=gd.p_names[i])

        pa = []
        for i in range(len(gd.p_names)):
            # accel and tempo per piece
            d, a = gd.prof_data[i]
            pa.append((d['Speed'], cntrating[i][1]))
        pa = list(zip(*pa))
        p = [10 * x for x in pa[0]]  # ad hoc scaling
        ax4.scatter(list(range(len(gd.p_names))), p, marker='H', color='green')
        ax4.scatter(list(range(len(gd.p_names))),
                    pa[1],
                    marker='H',
                    color='blue')

        ax1.legend(loc='lower right', prop=fontP)
        plt.tight_layout()

        tmpfig = tmpdir / gd.config['Session']
        plt.savefig(tmpfig)
        tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
        doc.append(
            NoEscape(r'\includegraphics[width=1.0\textwidth]{' + f'{tmpfig}' +
                     r'}'))
        plt.close(fig)

    ##   Third page
    doc.append(NewPage())
    with doc.create(Section('Crew report', numbering=False)):
        pcs = gd.p_names + ['average']
        doc.append(f'Piece "{pcs[gd.crewPiece]}" used.\n')

        fig = plt.figure()
        fig.subplots_adjust(hspace=0.7)
        gs = fig.add_gridspec(5, 2)
        ax1 = fig.add_subplot(gs[0:3, :])
        ax2 = fig.add_subplot(gs[3:, 0])
        ax3 = fig.add_subplot(gs[3:, 1])

        ax1.set_title('Gate Angle - GateForceX/Y')
        ax1.grid(True)
        ax2.set_title('Stretcher ForceX')
        ax2.grid(True)
        ax3.set_title('Power')
        ax3.grid(True)

        rcnt = gd.sessionInfo['RowerCnt']
        piece = gd.crewPiece
        if piece < len(gd.prof_data):
            # a seperate piece, from the tumbler
            cp = gd.crewPiece
            d, aa = gd.prof_data[cp]

            for r in range(rcnt):
                sns = rowersensors(r)
                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    i = sns['GateAngle']
                    j = sns['GateForceX']
                    k = sns['GateForceY']
                else:
                    i = sns['P GateAngle']
                    j = sns['P GateForceX']
                    k = sns['P GateForceY']

                # stretchers not always present!
                # k = sns['Stretcher Z']
                # todo: create switch to control working in this case

                ax1.plot(gd.norm_arrays[cp, :, i],
                         gd.norm_arrays[cp, :, j],
                         linewidth=0.6,
                         label=f'R {r+1}')
                ax1.plot(gd.norm_arrays[cp, :, i],
                         gd.norm_arrays[cp, :, k],
                         linestyle=stippel,
                         linewidth=0.6,
                         label=f'R {r+1}Y')

                #twee = self.ax2.plot(gd.norm_arrays[gd.crewPiece, :, i], linewidth=0.6, label=f'R {r+1}')

                ax3.plot([gd.gmin[gd.crewPiece]], [0], marker='v', color='b')
                ax3.plot([gd.gmax[gd.crewPiece]], [0], marker='^', color='b')

                # reference curve derived from the stroke
                sns = rowersensors(rcnt - 1)
                fmean = d[rcnt - 1]['GFEff']
                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    i = sns['GateAngle']
                    j = sns['GateForceX']
                else:
                    i = sns['P GateAngle']
                    j = sns['P GateForceX']
                minpos = min(gd.norm_arrays[cp, :, i])
                maxpos = max(gd.norm_arrays[cp, :, i])
                minarg = np.argmin(gd.norm_arrays[cp, :, i])
                maxarg = np.argmax(gd.norm_arrays[cp, :, i])
                fmin = gd.norm_arrays[cp, minarg, j]
                fmax = gd.norm_arrays[cp, maxarg, j]
                xstep = (maxpos - minpos) / 20
                ystep = (fmin - fmax) / 20  # assume fmin > fmax

                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    xref = np.array([
                        minpos, minpos + 0.4 * xstep, minpos + 2 * xstep,
                        minpos + 5 * xstep, minpos + 7 * xstep,
                        minpos + 9 * xstep, minpos + 11 * xstep,
                        minpos + 14 * xstep, minpos + 16 * xstep,
                        minpos + 20 * xstep
                    ])
                    yref = np.array([
                        fmin, fmin + 20, 1.1 * fmean, 1.6 * fmean,
                        1.65 * fmean, 1.7 * fmean, 1.6 * fmean, 1.25 * fmean,
                        0.8 * fmean, fmax
                    ])
                else:
                    xref = np.array([
                        minpos, minpos + 0.4 * xstep, minpos + 2 * xstep,
                        minpos + 5 * xstep, minpos + 7 * xstep,
                        minpos + 9 * xstep, minpos + 11 * xstep,
                        minpos + 14 * xstep, minpos + 16 * xstep,
                        minpos + 20 * xstep
                    ])
                    yref = np.array([
                        fmin, fmin + 20, 1.1 * fmean, 1.6 * fmean,
                        1.65 * fmean, 1.7 * fmean, 1.6 * fmean, 1.25 * fmean,
                        0.8 * fmean, fmax
                    ])

                curveref = make_interp_spline(xref, yref, 2)
                xrefnew = np.linspace(min(xref), max(xref),
                                      int(maxpos - minpos))

                ax1.plot(xrefnew,
                         curveref(xrefnew),
                         color='black',
                         linewidth=0.5,
                         linestyle=(0, (3, 6)))
                ax3.plot(aa[0 + r], linewidth=0.6, label=f'R {r+1}')
        else:
            # average
            for r in range(rcnt):
                sns = rowersensors(r)
                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    i = sns['GateAngle']
                    j = sns['GateForceX']
                else:
                    i = sns['P GateAngle']
                    j = sns['P GateForceX']
                # stretchers not always available!
                # k = sns['Stretcher Z']

                # average
                nmbrpieces = len(gd.p_names)
                angle = np.zeros((100, ))
                force = np.zeros((100, ))
                power = np.zeros((100, ))
                for p in range(nmbrpieces):
                    angle += gd.norm_arrays[p, :, i]
                    force += gd.norm_arrays[p, :, j]
                    # stretcherZ = gd.norm_arrays[p, :, k]
                    d, a = gd.prof_data[p]
                    power += aa[0 + r]

                # plot
                #ax1.plot(angle/nmbrpieces, linewidth=0.6, label=f'R {r+1}')
                #ax2.plot(force/nmbrpieces, linewidth=0.6, label=f'R {r+1}')

                ax3.plot(power / nmbrpieces, linewidth=0.6, label=f'R {r+1}')

        ax3.legend(loc='upper right', prop=fontP)
        plt.tight_layout()

        # we keep using the same name
        tmpfig = tmpdir / (gd.config['Session'] + '_crew')
        plt.savefig(tmpfig)
        tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
        doc.append(
            NoEscape(r'\includegraphics[width=1.0\textwidth]{' + f'{tmpfig}' +
                     r'}'))
        plt.close(fig)

    # Rower pages
    doc.append(NewPage())

    rwrcnt = gd.sessionInfo['RowerCnt']
    fig = [None for i in range(rwrcnt)]
    rax1 = [None for i in range(rwrcnt)]
    sax1 = [None for i in range(rwrcnt)]

    for rwr in range(rwrcnt):
        pcs = ['all'] + gd.p_names + ['average']
        with doc.create(
                Section(
                    f'Rower: {gd.metaData["Rowers"][rwr][0]}, using piece "{pcs[gd.rowerPiece[rwr]]}"',
                    numbering=False)):

            rows = gd.rowertablemodel[rwr].rowCount()
            columns = gd.rowertablemodel[rwr].columnCount()
            rowertab = 'l|' + ''.join(['r' for i in range(columns - 1)]) + '|'
            with doc.create(Tabular(rowertab)) as table:
                table.add_hline()
                row = []
                for j in range(columns):
                    index = QAbstractTableModel.index(gd.rowertablemodel[rwr],
                                                      0, j)
                    row.append(str(gd.rowertablemodel[rwr].data(index)))
                table.add_row(row, color='aquamarine')
                table.add_hline()

                cnt = 0
                for i in range(rows):
                    row = []
                    if i == 0:
                        continue
                    for j in range(columns):
                        index = QAbstractTableModel.index(
                            gd.rowertablemodel[rwr], i, j)
                        row.append(str(gd.rowertablemodel[rwr].data(index)))
                    if cnt % 2 == 0:
                        table.add_row(row, color='gainsboro')
                    else:
                        table.add_row(row, color='aquamarine')
                    cnt += 1
                table.add_hline()

            doc.append('\n')

            fig[rwr], ((rax1[rwr])) = plt.subplots(nrows=1, ncols=1)
            rax1[rwr].set_title('GateAngle - GateForceX/Y')
            rax1[rwr].grid(True)

            rsens = rowersensors(rwr)
            piece = gd.rowerPiece[rwr]

            scaleAngle = 10
            if gd.rowerPiece[rwr] == 0:
                # all
                for i in range(len(gd.p_names)):
                    if gd.sessionInfo['ScullSweep'] == 'sweep':
                        # print(f'Make rowerplot for {self.rower}')
                        rax1[rwr].plot(gd.norm_arrays[i, :,
                                                      rsens['GateAngle']],
                                       gd.norm_arrays[i, :,
                                                      rsens['GateForceX']],
                                       linewidth=0.6,
                                       label=f'{gd.p_names[i]}')
                        rax1[rwr].plot(gd.norm_arrays[i, :,
                                                      rsens['GateAngle']],
                                       gd.norm_arrays[i, :,
                                                      rsens['GateForceY']],
                                       linestyle=(0, (7, 10)),
                                       linewidth=0.6,
                                       label=f'{gd.p_names[i]}')
                    else:
                        rax1[rwr].plot(gd.norm_arrays[i, :,
                                                      rsens['P GateAngle']],
                                       gd.norm_arrays[i, :,
                                                      rsens['P GateForceX']],
                                       linewidth=0.6,
                                       label=f'{gd.p_names[i]}')
                        rax1[rwr].plot(gd.norm_arrays[i, :,
                                                      rsens['P GateAngle']],
                                       gd.norm_arrays[i, :,
                                                      rsens['P GateForceY']],
                                       linestyle=(0, (7, 10)),
                                       linewidth=0.6,
                                       label=f'{gd.p_names[i]}')
            elif gd.rowerPiece[rwr] == 7:
                # average
                angle = np.zeros((100, ))
                forceX = np.zeros((100, ))
                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    for i in range(len(gd.p_names)):
                        angle += gd.norm_arrays[i, :, rsens['GateAngle']]
                        forceX += gd.norm_arrays[i, :, rsens['GateForceX']]
                        forceY += gd.norm_arrays[i, :, rsens['GateForceY']]
                    rax1[rwr].plot(angle / 6,
                                   forceX / 6,
                                   linewidth=0.6,
                                   label='FX')
                    rax1[rwr].plot(angle / 6,
                                   forceY / 6,
                                   linestyle=(0, (7, 10)),
                                   linewidth=0.6,
                                   label='FY')
                else:
                    for i in range(len(gd.p_names)):
                        angle += gd.norm_arrays[i, :, rsens['P GateAngle']]
                        forceX += gd.norm_arrays[i, :, rsens['P GateForceX']]
                        forceY += gd.norm_arrays[i, :, rsens['P GateForceY']]
                    rax1[rwr].plot(angle / 6,
                                   forceX / 6,
                                   linewidth=0.6,
                                   label='FX')
                    rax1[rwr].plot(angle / 6,
                                   forceY / 6,
                                   linestyle=(0, (7, 10)),
                                   linewidth=0.6,
                                   label='FY')
            else:
                rp = gd.rowerPiece[rwr] - 1
                sns = rowersensors(rwr)

                # ad hoc angle x 10. Bettet via (max-min). Scale is for force
                # print(f'Create rowerplot for {self.rower}')
                outboat = [d for d, e in gd.prof_data]
                ri = [a[rwr] for a in outboat]  # rower info per piece
                fmean = ri[rp]['GFEff']

                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    i = sns['GateAngle']
                    j = sns['GateForceX']
                    k = sns['GateForceY']
                else:
                    i = sns['P GateAngle']
                    j = sns['P GateForceX']
                    k = sns['P GateForceY']

                # TESTING referentie curve
                # lengte uit tabel? Voorlopig 100, begin goed zetten
                # scale with avarage force
                minpos = min(gd.norm_arrays[rp, :, i])
                maxpos = max(gd.norm_arrays[rp, :, i])
                minarg = np.argmin(gd.norm_arrays[rp, :, i])
                maxarg = np.argmax(gd.norm_arrays[rp, :, i])
                fmin = gd.norm_arrays[rp, minarg, j]
                fmax = gd.norm_arrays[rp, maxarg, j]
                xstep = (maxpos - minpos) / 20
                ystep = (fmin - fmax) / 20  # assume fmin > fmax

                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    xref = np.array([
                        minpos, minpos + 0.4 * xstep, minpos + 2 * xstep,
                        minpos + 5 * xstep, minpos + 7 * xstep,
                        minpos + 9 * xstep, minpos + 11 * xstep,
                        minpos + 14 * xstep, minpos + 16 * xstep,
                        minpos + 20 * xstep
                    ])
                    yref = np.array([
                        fmin, fmin + 20, 1.1 * fmean, 1.6 * fmean,
                        1.65 * fmean, 1.7 * fmean, 1.6 * fmean, 1.25 * fmean,
                        0.8 * fmean, fmax
                    ])
                else:
                    xref = np.array([
                        minpos, minpos + 0.4 * xstep, minpos + 2 * xstep,
                        minpos + 5 * xstep, minpos + 7 * xstep,
                        minpos + 9 * xstep, minpos + 11 * xstep,
                        minpos + 14 * xstep, minpos + 16 * xstep,
                        minpos + 20 * xstep
                    ])
                    yref = np.array([
                        fmin, fmin + 20, 1.1 * fmean, 1.6 * fmean,
                        1.65 * fmean, 1.7 * fmean, 1.6 * fmean, 1.25 * fmean,
                        0.8 * fmean, fmax
                    ])

                curveref = make_interp_spline(xref, yref, 2)
                xrefnew = np.linspace(min(xref), max(xref),
                                      int(maxpos - minpos))

                rax1[rwr].plot(gd.norm_arrays[rp, :, i],
                               gd.norm_arrays[rp, :, j],
                               linewidth=0.6,
                               label=f'{gd.p_names[rp]} FX')
                rax1[rwr].plot(gd.norm_arrays[rp, :, i],
                               gd.norm_arrays[rp, :, k],
                               linestyle=stippel,
                               linewidth=0.6,
                               label=f'{gd.p_names[rp]} FY')
                rax1[rwr].plot(xrefnew,
                               curveref(xrefnew),
                               color='black',
                               linewidth=0.5,
                               linestyle=(0, (3, 6)))

            # rax1[rwr].legend(loc='lower right', prop=fontP, bbox_to_anchor=(1.05, 1))
            rax1[rwr].legend(loc='upper right', prop=fontP)
            plt.tight_layout()

            tmpfig = tmpdir / (gd.config['Session'] + f'_{rwr}')
            plt.savefig(tmpfig)
            tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
            doc.append(
                NoEscape(r'\includegraphics[width=0.9\textwidth]{' +
                         f'{tmpfig}' + r'}'))
            plt.close(fig[rwr])

            if 'StretcherForceX' in sensors:
                doc.append('\n')

                # stretcher plot
                fig[rwr], sax1[rwr] = plt.subplots()
                sax1[rwr].set_title('Stretcher')
                sax1[rwr].grid(True)

                rsens = rowersensors(rwr)
                if gd.rowerPiece[rwr] == 0:
                    # all DOEN WE NIET
                    pass
                elif gd.rowerPiece[rwr] == len(gd.p_names) + 1:
                    # average DOEN WE NIET
                    pass
                else:
                    # a piece (alleen dit)
                    i = gd.rowerPiece[rwr] - 1
                    name, se, nr, sp = pieces[i]
                    sax1[rwr].plot(gd.dataObject[sp[0]:sp[1],
                                                 rsens['StretcherForceX']],
                                   linewidth=0.6,
                                   label='StretcherForceX')
                    sax1[rwr].plot(
                        10 * gd.dataObject[sp[0]:sp[1], rsens['Stretcher RL']],
                        linewidth=0.6,
                        label='Stretcher RL')
                    sax1[rwr].plot(
                        10 * gd.dataObject[sp[0]:sp[1], rsens['Stretcher TB']],
                        linewidth=0.6,
                        label='Stretcher TB')

                    sax1[rwr].legend(loc='lower right', prop=fontP)
                    plt.tight_layout()

            tmpfig = tmpdir / (gd.config['Session'] + f'_{rwr}_s')
            plt.savefig(tmpfig)
            tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
            doc.append(
                NoEscape(r'\includegraphics[width=0.6\textwidth]{' +
                         f'{tmpfig}' + r'}'))

            plt.close(fig[rwr])

            if rwr != rwrcnt - 1:
                doc.append(NewPage())

    # Extra page
    if gd.extraplot:
        doc.append(NewPage())

        fig, extr = plt.subplots()
        s2 = gd.config['Session2']
        if s2 == '':
            extr.set_title('Custom plot')
        else:
            extr.set_title(f'Custom plot (second session: {s2})')
        extr.grid(True)

        # data from update_plot from View piece, can we do this simpler?
        [strt, end, strttime, center, scalex, slist,
         secslist] = gd.extrasettings
        times = list(map(lambda x: x / Hz, list(range(gd.view_tr.shape[0]))))

        for i, name, scaley in slist:
            extr.plot(times,
                      gd.view_tr[:, i] * scaley,
                      linewidth=0.6,
                      label=name)
        for i, name, scale in secslist:
            extr.plot(times,
                      gd.view_tr2[:, i] * scaley,
                      linewidth=0.6,
                      label=name,
                      linestyle=stippel)

        dist = (end - strt)
        xFrom = center - scalex * dist / 2
        xTo = center + scalex * dist / 2

        extr.set_xlim(xFrom, xTo)
        # start at correct beginvalue
        locs = extr.get_xticks()
        ticks = [item + strttime for item in locs]
        extr.set_xticklabels(ticks)
        extr.legend()
        plt.tight_layout()

        # we keep using the same name
        tmpfig = tmpdir / (gd.config['Session'] + '_extra')
        plt.savefig(tmpfig)
        tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
        doc.append(
            NoEscape(r'\includegraphics[width=1.0\textwidth]{' + f'{tmpfig}' +
                     r'}'))
        plt.close(fig)

        doc.append(NewLine())
        doc.append(VerticalSpace("10pt"))
        doc.append(f' Piece: {gd.selPiece}')
        if gd.sd_selPiece != '':
            doc.append(NewLine())
            doc.append(VerticalSpace("5pt"))
            doc.append(f'Secondary piece: {gd.sd_selPiece}')

    # generate report
    doc.generate_pdf(reportfile, clean_tex=True)
示例#27
0
def gen_reg_tables(subsection, group_fields):
    """
    Takes a list of fields belonging to a field group and a register subsection
    Returns the subsection with fully formatted variable width tables for a field group 

    Needs to support field splitting in the case when field width exceeds 16 

    """
    c_max_chars = 64
    char_sum = 0
    last_bit_boundary = 0
    bit_bounds = [32]
    i = 0
    # iterate through fields and break whenever max chars has been exceeded
    #print("New field group")
    for field in group_fields[::-1]:
        i = i + 1
        field_name = field.name() if field.group_name(
        ) == 'None' else field.name().split(field.group_name() + '_')[-1]
        char_sum = char_sum + len(field_name)
        if char_sum > c_max_chars:
            char_sum = len(field_name)
            bit_bounds.append(last_bit_boundary)
        last_bit_boundary = field.bit_offset()
        if (bit_bounds[-1] - last_bit_boundary) > 16:
            bit_bounds.append(bit_bounds[-1] - 16)  # still limit to max of  16
            last_bit_boundary = bit_bounds[-1]
        #print("field {} upper {} lower {}".format(field.name(), str(field.bit_offset() + field.width() -1), str(field.bit_offset())))
        #print(*bit_bounds)
    if bit_bounds[-1] != 0: bit_bounds.append(0)

    bit_bounds = [32, 16, 0] if len(bit_bounds) < 3 else bit_bounds
    nof_tables = len(bit_bounds)

    # generate columns for fields, mostly useful for gaps, can make it less bulky than the column dictionary
    for i in range(1, nof_tables):  # starts from second bound
        col_list = []
        nof_cols = bit_bounds[
            i - 1] - bit_bounds[i] + 1  # nof bits + bit label column
        group_table = Tabular('|c' * nof_cols + '|')
        group_table.add_hline()
        group_table.add_row(
            (MultiColumn(nof_cols,
                         align='|c|',
                         data='Addr: {}h'.format(
                             str(hex(field.address_offset()))[2:])), ))
        group_table.add_hline()
        # group_table.add_row(('Bit',*range(bit_bounds[i-1]-1,bit_bounds[i]-1,-1)))
        row = ['Bit'] + [
            str(bit)
            for bit in range(bit_bounds[i - 1] - 1, bit_bounds[i] - 1, -1)
        ]
        group_table.add_row(row)
        group_table.add_hline()
        gap_bit = bit_bounds[i - 1] - 1  # next available bit, inclusive
        end_bit = bit_bounds[i]
        #print("Table {} bounding {} and {}".format(str(i),str(gap_bit+1), str(end_bit)))
        for field in group_fields[::-1]:
            field_name = field.name() if field.group_name(
            ) == 'None' else field.name().split(field.group_name() + '_')[-1]
            upper_bit = field.bit_offset() + field.width() - 1  # inclusive
            # print("field {} has upper bit {} gap bit is {}".format(field_name,str(upper_bit), str(gap_bit)))
            if upper_bit < gap_bit:
                gap_width = min(gap_bit - upper_bit, nof_cols - 1)
                col_list.append(MultiColumn(gap_width, align='|c|',
                                            data='RES'))
                gap_bit = max(upper_bit,
                              bit_bounds[i] - 1)  #gap_bit-(nof_cols-1))
                #print("added gap before field {} of width {}".format(field_name, str(gap_width)))
                if gap_bit == (end_bit - 1): break

            #print("field {} bit offset {} should be more or equal to {} and upper bit {} should be less than {}".format(field_name, str(field.bit_offset()), str(bit_bounds[i]), str(upper_bit), str(bit_bounds[i-1])))
            if field.bit_offset() >= end_bit and upper_bit < bit_bounds[
                    i - 1]:  # field fully contained
                col_list.append(
                    MultiColumn(field.width(), align='|c|', data=field_name))
                #print("added complete field {} of width {}".format(field_name, str(field.width())))
                gap_bit = field.bit_offset() - 1
            elif upper_bit >= end_bit and field.bit_offset(
            ) < end_bit:  # upper partial
                col_list.append(
                    MultiColumn(upper_bit - bit_bounds[i] + 1,
                                align='|c|',
                                data=field_name))
                #print("added upper partial for field {} of width {}".format(field_name, str(upper_bit - bit_bounds[i]+1)))
                gap_bit = bit_bounds[i] - 1  # end of table
                break
            elif upper_bit >= bit_bounds[i - 1] and field.bit_offset(
            ) < bit_bounds[i - 1]:  # lower partial field
                col_list.append(
                    MultiColumn(bit_bounds[i - 1] - field.bit_offset(),
                                align='|c|',
                                data=field_name))
                #print("added lower partial for field {} of width {}".format(field_name, str(bit_bounds[i-1]-field.bit_offset())))
                gap_bit = field.bit_offset() - 1

            if field.bit_offset() == (bit_bounds[i]): break

        if gap_bit != (bit_bounds[i] - 1):  # bottom gap
            gap_width = max(0, gap_bit - (bit_bounds[i] - 1))
            col_list.append(MultiColumn(gap_width, align='|c|', data='RES'))
            #print("added gap after field {} of width {}".format(field_name, str(gap_width)))
        row = ['Name'] + col_list
        group_table.add_row(row)
        # group_table.add_row(('Name',*col_list,))# add
        group_table.add_hline()
        subsection.append(group_table)
        subsection.append(NewLine())
        subsection.append(NewLine())
        subsection.append(NewLine())

    return subsection
示例#28
0
    def fill(self):
        # with self.doc.create(Section("{} library.".format(self.config['hdl_library_name']))):
        # with self.doc.create(Section("{} library".format(self.periph_lib_name))):
        # main_section = Section("{} library".format(self.periph_lib_name))
        # self.doc.append(LargeText(bold('{} library'.format(self.periph_lib_name))))
        # periph_section = Section("Peripherals", numbering = False)
        # i = 1
        # for periph_name in self.periph_lib['peripherals'].keys():
        # self.doc.append("{} {}".format(str(i), periph_name))
        # i = i+1
        # self.doc.append(NewLine())
        # with self.doc.create(Section("Peripherals")):
        added_instances = []
        # for peri_info in self.config['peripherals']:
        # peri_class = Peripheral(peri_info)
        for periph_name, periph in self.periph_lib['peripherals'].items():
            if periph_name in added_instances:
                continue
            added_instances.append(periph_name)

            # with self.doc.create(Section(periph_name, numbering=True)):
            # with self.doc.create(Subsection(periph_name, numbering=True)):
            # self.doc.append(peri_class.get_kv('peripheral_description').replace('"', ''))
            self.doc.append(NewPage())
            periph_subsection = Section(periph_name, numbering=True)
            periph_subsection.append(periph.get_description().replace(
                '""', ''))

            # Peripheral System Map Table
            periph_subsection.append(NewLine())
            periph_subsection.append(NewLine())
            periph_subsection.append(MediumText(bold('Local Slave Port Map')))
            periph_subsection.append(NewLine())
            periph_subsection.append(NewLine())
            periph_system_table = Tabular('|c|c|c|c|')
            # periph_system_table.add_row((MultiColumn(4,data=MediumText(bold('System Map'))),))
            periph_system_table.add_hline()
            periph_system_table.add_row(
                ('Hex', 'Range (Bytes)', 'Slave Port', 'Protocol'))
            periph_system_table.add_hline()

            # peripheral system address map
            dummyFPGA = FPGA(None)
            dummyFPGA.peripherals.update({periph_name: periph})
            dummyFPGA.create_address_map()
            # for slave in periph.slaves:
            for slave_port, slave_dict in dummyFPGA.address_map.items():
                periph_system_table.add_row(
                    (str(hex(slave_dict['base'])), str(slave_dict['span']),
                     slave_port, slave_dict['type']))
                periph_system_table.add_hline()
            periph_subsection.append(periph_system_table)

            # self.doc.append(periph.get_description().replace('""',''))
            # self.doc.append(NewLine())

            #self.doc.append(MediumText(bold("slave ports.")))

            # for val_info, val_type in ((periph.registers, 'Registers'),
            # (periph.rams, 'Rams'),
            # (periph.fifos, 'Fifos')):
            periph_reg_section = Subsection(
                "{} register slave".format(periph_name), numbering=False)
            periph_reg_table = Tabular('|c|c|c|c|')
            periph_reg_table.add_hline()
            periph_reg_table.add_row(('Base Address', 'Range',
                                      'Register group', 'Number of Slaves'))
            periph_reg_table.add_hline()
            # slave_subsections = ("{} slaves".format(periph_name), numbering=False)
            # slave_subsections = []
            # slave_subsections.append(NewLine())
            # slave_subsections.append(MediumText(bold("Slave Ports for peripheral " + periph_name + "\n")))
            slave_subsections = Subsection(
                "Slave Ports for peripheral \'{}\'".format(periph_name),
                numbering=False)
            for slave in periph.slaves:

                # if len(val_info) == 0: # not sure what this is for
                # continue

                #self.doc.add(text=val_type, size="medium")

                # added_val_types = []
                # for key, val in sorted(val_info.items()):
                # if val.name() in added_val_types:
                # continue
                # added_val_types.append(val.name())
                slave_subsection = Subsection("Slave Port: {} ({})".format(
                    slave.name(),
                    'Register block' if isinstance(slave, Register) else
                    'RAM' if isinstance(slave, RAM) else 'FIFO'),
                                              numbering=True)
                slave_subsection.append(slave.get_kv('slave_description'))
                slave_subsection.append(NewLine())
                # slave_subsection.append("Slave Type: {}".format('REGISTER' if isinstance(slave, Register) else 'RAM' if isinstance(slave, RAM) else 'FIFO'))
                slave_subsection.append(NewLine())
                slave_subsection.append("Address Length: {}".format(
                    str(slave.address_length())))
                slave_subsection.append(NewLine())
                slave_subsection.append("Number of Slaves: {}".format(
                    str(slave.number_of_slaves())))
                slave_subsection.append(NewLine())
                slave_subsection.append(NewLine())

                # if val_type == 'Registers':
                if isinstance(slave, Register):  # expand registers and fields
                    for ram in slave.rams:
                        periph_reg_table.add_row(
                            (str(ram.base_address()),
                             str(ram.number_of_fields() * WIDTH_IN_BYTES),
                             ram.name() + ' (RAM)',
                             str(slave.number_of_slaves())))
                        periph_reg_table.add_hline()
                    periph_reg_table.add_row(
                        (str(slave.base_address()),
                         str(slave.address_length()), slave.name(),
                         str(slave.number_of_slaves())))
                    periph_reg_table.add_hline()
                    added_field_groups = []
                    # with self.doc.create(Subsection("{} Register Fields".format(val.name().lower()), numbering=True)):
                    # if val.get_kv('slave_description') is not None:
                    # slave_subsection.append(val.get_kv('slave_description').replace('"', ''))

                    # generate register table i.e. by word
                    group_address = -1
                    group_list = []
                    for field in slave.fields:
                        if field.address_offset() != group_address:
                            group_address = field.address_offset()
                            group_list.append(field)
                            # addr_name = field.group_name() if field.group_name() != "None" else field.name()

                            # slave_table.add_row(str(hex(field.address_offset())), addr_name)
                            # slave_table.add_hline()
                    c_max_rows = 30
                    nof_cols = ceil(
                        len(group_list) / c_max_rows
                    )  # register table has max length of c_max_rows
                    nof_rows = min(len(group_list), c_max_rows)
                    slave_table = Tabular('|c|c|' * nof_cols)
                    slave_table.add_hline()
                    slave_table.add_row(['Hex', 'Field Group'] * nof_cols)
                    # slave_table.add_row((*['Hex','Field Group']*nof_cols))
                    slave_table.add_hline()
                    for i in range(nof_rows):
                        row = []
                        for j in range(nof_cols):
                            if i + c_max_rows * j < len(group_list):
                                field.group_name() if field.group_name(
                                ) != "None" else field.name()
                                row.extend([
                                    str(
                                        hex(group_list[i + c_max_rows *
                                                       j].address_offset())),
                                    group_list[i + c_max_rows * j].name()
                                ])
                            else:
                                row.extend(['', ''])
                        slave_table.add_row(row)
                        # slave_table.add_row(*row)
                        slave_table.add_hline()

                    slave_subsection.append(slave_table)
                    slave_subsection.append(NewPage())

                    group_address = -1
                    for field in slave.fields:
                        # if field.group_name() is None or field.group_name() != last_group: # base on group_address instead
                        # print("field {} address {} bit{}".format(field.name(), str(field.address_offset()), str(field.bit_offset())))
                        if field.address_offset() != group_address:
                            group_address = field.address_offset()
                            # group_page = MiniPage()
                            group_subsection = Subsection('{} {}'.format(
                                str(hex(field.address_offset())),
                                field.name() if field.group_name() == 'None'
                                else field.group_name()),
                                                          numbering=False)
                            group_fields = [
                                field for field in slave.fields
                                if field.address_offset() == group_address
                            ]
                            if len(group_fields) > 10:
                                slave_subsection.append(NewPage())
                            group_subsection = gen_reg_tables(
                                group_subsection, group_fields)
                            for field in group_fields[::-1]:
                                field_name = field.name() if field.group_name(
                                ) == 'None' else field.name().split(
                                    field.group_name() + '_')[-1]
                                bit_string = "Bit {}".format(
                                    str(field.bit_offset())) if field.width(
                                    ) == 1 else "Bits {}:{}".format(
                                        str(field.bit_offset() +
                                            field.width() -
                                            1), str(field.bit_offset()))
                                group_subsection.append(
                                    bold("{}\t\t{} ({}):".format(
                                        bit_string, field_name,
                                        field.access_mode())))
                                group_subsection.append("\t\t{}".format(
                                    field.field_description()))
                                group_subsection.append(NewLine())
                                group_subsection.append(NewLine())
                            # group_page.append(group_subsection)
                            slave_subsection.append(group_subsection)
                else:  # RAM or FIFO
                    slave_subsection.append("Data width: {}".format(
                        slave.width()))
                    slave_subsection.append(NewLine())
                    if isinstance(slave, RAM):
                        slave_subsection.append("User data width: {}".format(
                            slave.user_width()))

                slave_subsections.append(slave_subsection)
            periph_reg_section.append(periph_reg_table)
            self.doc.append(periph_subsection)
            if any([isinstance(slave, Register) for slave in periph.slaves]):
                self.doc.append(periph_reg_section)
            # for i in range(len(slave_subsections)):
            # self.doc.append(slave_subsections[i])
            self.doc.append(slave_subsections)

            # self.doc.append(periph_section)
            self.doc.append(NewPage())
示例#29
0
 def status(self, leak, color):
     tooltip = getIconTooltipById(leak.meta.flag)
     string = f"Status: {TextColorExt(color, tooltip, options='HTML').dumps()}"
     self.doc.append(pylatex.utils.bold(NoEscape(string)))
     self.doc.append(NewLine())
示例#30
0
 def criticality(self, leak):
     crit_level = f"{leak.status.max_leak_normalized():.3f}"
     if float(crit_level) == 0 and leak.meta.flag == LeakFlags.LEAK:
         crit_level = "Flagged by user"
     self.doc.append(pylatex.utils.bold(f"Criticality level: {crit_level}"))
     self.doc.append(NewLine())