示例#1
0
def add_header(doc, meal):
    doc.append(
        Command('renewcommand',
                arguments=Command('arraystretch'),
                extra_arguments='1.75'))
    doc.append(NoEscape(r'\definecolor{light-gray}{gray}{0.85}'))
    doc.append(Command('arrayrulecolor', arguments=NoEscape(r'light-gray')))

    with doc.create(Table()):
        with doc.create(Tabularx(
                "X r",
                width_argument=NoEscape(r'\textwidth'))) as table_content:
            # add header
            table_content.add_row([
                NoEscape(r'\LARGE \textbf{' + meal['meal_name'] + '}'),
                NoEscape(r'\color{gray} \large \textbf{' +
                         meal['meal_date'].strftime("%a, %d. %b") + '}')
            ])

            table_content.add_row([
                NoEscape(r'\small \textit{(' + meal['meal_weekview_name'] +
                         ')}'),
                NoEscape(r'\color{gray} \large \textbf{' +
                         meal['meal_used_as'] + '}')
            ])
            table_content.add_hline()
示例#2
0
    def _document_test_result(self) -> None:
        """Document test results including test summary, passed tests, and failed tests.
        """
        self.test_id = 1
        instance_pass_tests, aggregate_pass_tests, instance_fail_tests, aggregate_fail_tests = [], [], [], []

        for test in self.json_summary["tests"]:
            if test["test_type"] == "per-instance" and test["passed"]:
                instance_pass_tests.append(test)
            elif test["test_type"] == "per-instance" and not test["passed"]:
                instance_fail_tests.append(test)
            elif test["test_type"] == "aggregate" and test["passed"]:
                aggregate_pass_tests.append(test)
            elif test["test_type"] == "aggregate" and not test["passed"]:
                aggregate_fail_tests.append(test)

        with self.doc.create(Section("Test Summary")):
            with self.doc.create(Itemize()) as itemize:
                itemize.add_item(
                    escape_latex("Execution time: {:.2f} seconds".format(
                        self.json_summary['execution_time(s)'])))

            with self.doc.create(Table(position='H')) as table:
                table.append(NoEscape(r'\refstepcounter{table}'))
                self._document_summary_table(
                    pass_num=len(instance_pass_tests) +
                    len(aggregate_pass_tests),
                    fail_num=len(instance_fail_tests) +
                    len(aggregate_fail_tests))

        if instance_fail_tests or aggregate_fail_tests:
            with self.doc.create(Section("Failed Tests")):
                if len(aggregate_fail_tests) > 0:
                    with self.doc.create(Subsection("Failed Aggregate Tests")):
                        self._document_aggregate_table(
                            tests=aggregate_fail_tests)
                if len(instance_fail_tests) > 0:
                    with self.doc.create(
                            Subsection("Failed Per-Instance Tests")):
                        self._document_instance_table(
                            tests=instance_fail_tests,
                            with_id=bool(self.data_id))

        if instance_pass_tests or aggregate_pass_tests:
            with self.doc.create(Section("Passed Tests")):
                if aggregate_pass_tests:
                    with self.doc.create(Subsection("Passed Aggregate Tests")):
                        self._document_aggregate_table(
                            tests=aggregate_pass_tests)
                if instance_pass_tests:
                    with self.doc.create(
                            Subsection("Passed Per-Instance Tests")):
                        self._document_instance_table(
                            tests=instance_pass_tests,
                            with_id=bool(self.data_id))

        self.doc.append(NoEscape(r'\newpage'))  # For QMS report
示例#3
0
    def __init__(
        self,
        *args,
        folders_path="Latex/",
        outer_folder_name="Tables",
        inner_folder_name="Tabulars",
        position=None,
        **kwargs,
    ):

        LatexSaving.__init__(
            self,
            outer_folder=outer_folder_name,
            inner_folder=inner_folder_name,
            folders_path=folders_path,
        )

        TableOriginal.__init__(self, *args, position=position, **kwargs)
        self._label = "tbl"
    def render_table(self,
                     doc: Document,
                     name_override: Optional[LatexObject] = None,
                     toc_ref: Optional[str] = None,
                     extra_rows: Optional[List[Tuple[str, Any]]] = None) -> None:
        """Write this table into a LaTeX document.

        Args:
            doc: The LaTeX document to be appended to.
            name_override: An optional replacement for this table's name field.
            toc_ref: A reference to be added to the table of contents.
            extra_rows: Any extra rows to be added to the table before the kwargs.
        """
        with doc.create(Table(position='htp!')) as table:
            table.append(NoEscape(r'\refstepcounter{table}'))
            table.append(Label(Marker(name=str(self.fe_id), prefix="tbl")))
            if toc_ref:
                table.append(NoEscape(r'\addcontentsline{toc}{subsection}{' + escape_latex(toc_ref) + '}'))
            with doc.create(Tabularx('|lX|', booktabs=True)) as tabular:
                package = Package('xcolor', options='table')
                if package not in tabular.packages:
                    # Need to invoke a table color before invoking TextColor (bug?)
                    tabular.packages.append(package)
                package = Package('seqsplit')
                if package not in tabular.packages:
                    tabular.packages.append(package)
                tabular.add_row((name_override if name_override else bold(self.name),
                                 MultiColumn(size=1, align='r|', data=TextColor('blue', self.fe_id))))
                tabular.add_hline()
                type_str = f"{self.type}"
                match = re.fullmatch(r'^<.* \'(?P<typ>.*)\'>$', type_str)
                type_str = match.group("typ") if match else type_str
                tabular.add_row(("Type: ", escape_latex(type_str)))
                if self.path:
                    if isinstance(self.path, LatexObject):
                        tabular.add_row(("", self.path))
                    else:
                        tabular.add_row(("", escape_latex(self.path)))
                for k, v in self.fields.items():
                    tabular.add_hline()
                    tabular.add_row((f"{k.capitalize()}: ", v))
                if self.args:
                    tabular.add_hline()
                    tabular.add_row(("Args: ", self.args))
                if extra_rows:
                    for (key, val) in extra_rows:
                        tabular.add_hline()
                        tabular.add_row(key, val)
                if self.kwargs:
                    tabular.add_hline()
                    for idx, (kwarg, val) in enumerate(self.kwargs.items()):
                        tabular.add_row((italic(kwarg), val), color='white' if idx % 2 else 'black!5')
示例#5
0
def createSimpleTable(tableColumns, d, filename):
    doc = Document()

    with doc.create(Table('|c|c|c|c|c|c|c|c|c|')) as table:

        for row in d:

            row[0] = row[0].replace('_', '\_')
            row[0] = "\\textbf{" + row[0] + "}"
            table.add_hline()
            table.add_row(tuple(row))
        table.add_hline()

    a = open(filename, 'wr')
    table.dump(a)
示例#6
0
def add_recipe(doc, recipe):
    doc.append(Command('vspace', arguments='0.75cm'))

    doc.append(
        Command('renewcommand',
                arguments=Command('arraystretch'),
                extra_arguments='1.25'))

    if 'ingredients' in recipe and len(recipe['ingredients']) > 0:
        with doc.create(Table(position='h')) as table:

            table.add_caption(recipe['recipe_name'] + ' (für ' +
                              str(recipe['recipe_participants']) + ' Per.)')

            # add section for 'recipe_description' or 'recipe_notes' if one is none-empty
            if recipe['recipe_description'] + recipe['recipe_notes'] != '':
                with table.create(
                        Tabularx('l X', width_argument=NoEscape(
                            r'\textwidth'))) as table_content:
                    if recipe['recipe_description'] != '':
                        table_content.add_row(
                            ['Beschreibung: ', recipe['recipe_description']])
                    if recipe['recipe_notes'] != '':
                        table_content.add_row(
                            ['Notizen:', recipe['recipe_notes']])

            table.append(NoEscape(r'\par'))

            with table.create(Tabularx('| r | r | l | l | X |', width_argument=NoEscape(r'\textwidth'))) \
                    as table_content:
                table_content.add_hline()
                table_content.add_row([
                    NoEscape(r'\tiny{1 Per.}'),
                    NoEscape(r'\tiny{' + str(recipe['recipe_participants']) +
                             ' Per.}'),
                    NoEscape(r'\tiny{Einheit}'),
                    NoEscape(r'\tiny{Lebensmittel}'),
                    NoEscape(r'\tiny{Kommentar}')
                ])
                table_content.add_hline()
                for ingredient in recipe['ingredients']:
                    add_ingredient(table_content, ingredient)
                    table_content.add_hline()
示例#7
0
def varianceExplainedTable(doc, pcs, name, nbPca, nb):
    doc.append(
        'By applying the PCA to the sportsmen\'s dataset, the first three PCs were computed and explain more than 95% of the variance for each body part.'
    )
    doc.append(
        'The percentage of variance explained by the PCs are shown in Table 1.'
    )
    with doc.create(Table(position='h!')) as table:
        with doc.create(Tabular('ccc')) as tabular:
            tabular.add_hline()
            tabular.add_row(('Variable', 'PC number', 'Variance explained'))
            for i in range(nb):
                tabular.add_hline()
                tabular.add_row((name[i], '', ''))
                tabular.add_hline()
                for j in range(nbPca):
                    tabular.add_row(
                        ('', 'PC' + str(j + 1), pcs[nbPca * i + j]))
        table.add_caption(
            "Percent variation explained for the first " + str(nbPca) +
            " Principle Components of the players’ body variables")
示例#8
0
def create_tables(pwn_data, pdf, start_entry, stop_entry, counter):
    """
	Creates tables for use in the PDF document. It takes the output of the check_pwn
	function as a variable pwn_data. PDF equals the LaTeX document object. The start_entry,
	stop_entry and counter are used to limit the size of the table. Otherwise the result
	will be written to one big table. Which turns out ugly in the document.

	The counter value in particular is being used to loop through the classess of data that
	were leaked in the breach. The looping is done to construct a bullet list of classes that
	were breached.

	This function doesn't return anything. It only alters the state of the PDF document object.
	"""
    with pdf.create(Center()) as centered:
        with centered.create(Table(position='h')):
            with pdf.create(Tabular('|l|c|')) as table:
                table.add_hline()
                for entry in pwn_data[start_entry:stop_entry]:
                    table.add_row(bold("Title"), pwn_data[counter]["Title"])
                    table.add_hline()
                    table.add_row(bold("Domain"), pwn_data[counter]["Domain"])
                    table.add_hline()
                    table.add_row(bold("Date of breach"),
                                  pwn_data[counter]["BreachDate"])
                    table.add_hline()
                    first_class = True
                    for dataclasses in pwn_data[counter]["DataClasses"]:
                        if first_class:
                            table.add_row(bold("Affected classes"),
                                          dataclasses)
                            first_class = False
                        else:
                            table.add_row("", dataclasses)
                    table.add_hline()
                    counter = counter + 1
                    table.add_hline()
示例#9
0
def add_table(doc, path, caption):
    table_data = pd.read_csv(path)

    alignment = 'X'
    n_columns = table_data.shape[1]
    fmt = '{}|{}'.format(alignment, alignment * (n_columns - 1))

    with doc.create(Table()) as table:
        with doc.create(Tabularx(fmt)) as tabularx:
            # Table header
            tabularx.add_hline()
            empty_title_columns = table_data.columns.str.contains('unnamed',
                                                                  case=False)
            title_columns = table_data.columns.values
            title_columns[empty_title_columns] = ''
            tabularx.add_row(title_columns)
            tabularx.add_hline()

            # Data
            for row in table_data.itertuples(index=False):
                tabularx.add_row(row)
            tabularx.add_hline()

        table.add_caption(caption)
示例#10
0
    Plot, Figure, Package
from pylatex.numpy import Matrix
from pylatex.utils import italic, escape_latex

doc = Document()
doc.packages.append(
    Package('geometry', options=['tmargin=1cm', 'lmargin=10cm']))

with doc.create(Section('The simple stuff')):
    doc.append('Some regular text and some ' + italic('italic text. '))
    doc.append(escape_latex('\nAlso some crazy characters: $&#{}'))
    with doc.create(Subsection('Math that is incorrect')):
        doc.append(Math(data=['2*3', '=', 9]))

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

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

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

    with doc.create(Subsection('Beautiful graphs')):
        with doc.create(TikZ()):
示例#11
0
def s2string(sbmlArgument, file_path=None):
    ''' Convert sbml to a latex string
    
    Args: 
        param1 (string): file name to sbml OR sbml string
        
        file_path (string, optional): path for creation of a pdf file, only works with latexmk or pdflatex installed
    Returns:
        LaTeX string
    '''
    try:
        import tesbml as libsbml
    except:
        import libsbml

    try:
        from libsbml import formulaToL3String, writeMathMLToString, parseFormula, readMathMLFromString
    except:
        from tesbml import formulaToL3String, writeMathMLToString, parseFormula, readMathMLFromString

    import math
    import pathlib  # For extracting file extensions
    import os

    def getLaTeXFromAST(tree):
        #        xmlstr = writeMathMLToString(tree)
        #        # Strip out the header
        #        xmlstr = xmlstr.replace ('<?xml version="1.0" encoding="UTF-8"?>', '')
        #
        #        return  mathml2latex_yarosh(xmlstr).strip ('$')
        from MATH import convertToInfix

        return convertToInfix(tree)

    #The zeroes are out of nessessity, I don't know why, but just having a single obj variable does not work
    #So, predefined all classes that are used later
    def listfiller(Commands,
                   obj=0,
                   R=0,
                   Sp=0,
                   ass=0,
                   Par=0,
                   tr=0,
                   libsbml=libsbml,
                   tofill=[],
                   twoD=1):
        '''
        Uses a dismal method of evaluating a piece of code 
        from 'Commands' to fit a specific string into 'tofill' 
        takes in a libsbml object as obj
        
        if twoD = 0, then does not fill 'tofill' with the templin as one element
        but returns the compiled templin as 1-D list
        '''
        l = len(Commands)
        templin = [None] * l
        for i in range(l):
            templin[i] = eval(Commands[i])
        if twoD == 1:
            tofill.append(templin)
            return tofill
        elif twoD == 0:
            return templin

    def round_half_up(n, decimals=0):
        '''
        use this to round numbers that are way to big to put in a table
        '''
        multiplier = 10**decimals
        return math.floor(n * multiplier + 0.5) / multiplier

    def lawcutter(prefix):
        '''
        cuts up the string version of the KineticLaw object into something the 
        mathml converter can read
        '''
        lis = prefix.split('\n')
        i = len(lis) - 1
        if ('  <listOfParameters>' in lis):
            i = lis.index('  <listOfParameters>')
        lis = lis[1:i]
        for n in range(0, len(lis)):
            lis[n] = lis[n][
                2:]  #so, here we are messing with indentation, not sure if it will be consistent
            #for all models or even if it is nessessary, but it's here
        newstr = '\n'.join(lis)
        return newstr

    def notecutter(prefix):
        '''
        same as lawcutter but for notes
        
        '''
        prefix = prefix.replace("\n", "")
        lis = prefix.split('>')
        i = len(lis) - 2
        lis = lis[1:i]
        #for n in range(0, len(lis)):
        #   lis[n] =lis[n][1:]
        newstr = '>'.join(lis)
        newstr = newstr + '>'
        return newstr

    # ----------------------------------------------
    # Start of sb2l
    # ----------------------------------------------
    reader = libsbml.SBMLReader()
    # Check if its a file name
    if os.path.isfile(sbmlArgument):
        suff = pathlib.Path(sbmlArgument).suffix
        if suff == '.xml' or suff == '.sbml':
            sbmldoc = reader.readSBMLFromFile(sbmlArgument)
    else:
        # If it's not a file, assume it's an sbml string
        sbmldoc = reader.readSBMLFromString(
            sbmlArgument)  # Reading in the model

    errors = sbmldoc.getNumErrors()
    numReadErr = 0
    numReadWarn = 0
    for i in range(errors):
        severity = sbmldoc.getError(i).getSeverity()
        if (severity == libsbml.LIBSBML_SEV_ERROR) or (
                severity == libsbml.LIBSBML_SEV_FATAL):
            seriousErrors = True
            numReadErr += 1
        else:
            numReadWarn += 1

        oss = libsbml.ostringstream()
        sbmldoc.printErrors(oss)
        errMsgRead = oss.str()
        raise RuntimeError(errMsgRead)

    Model_id = sbmldoc.model.getName(
    )  # This is essentially how each list is filled, using commands from LibSBML
    if len(Model_id) < 1:
        Model_id = sbmldoc.model.getId()
    Model_id = Model_id.replace(r'_', r'\_')

    Compartments = []
    Species = []
    Parameters = []
    Reactions = []
    Events = []
    Rules = []
    FunctionDefinitions = []
    FunctionArgList = []

    # making a notes list
    lis = None
    notes = sbmldoc.model.getNotesString()
    if len(notes) != 0:
        lis = notecutter(notes).split('<')
        lis = lis[2:len(lis)]
    del notes

    l = sbmldoc.model.getNumCompartments()
    if l != 0:
        ComList = [
            'obj.getId()', 'obj.getSBOTerm()', 'obj.getSpatialDimensions()',
            'obj.getSize()', 'obj.getConstant()'
        ]
        for x in range(0, l):
            obj = sbmldoc.model.getCompartment(x)
            Compartments = listfiller(
                ComList, obj=obj,
                tofill=Compartments)  # see the function above
        del (ComList)

    l = sbmldoc.model.getNumSpecies()
    if l != 0:
        SpecList = [
            'obj.getId()', 'obj.getInitialConcentration()',
            'obj.getHasOnlySubstanceUnits()', ' obj.getBoundaryCondition()',
            'obj.getConstant()'
        ]
        for x in range(0, l):
            obj = sbmldoc.model.getSpecies(x)
            Species = listfiller(SpecList, obj=obj, tofill=Species)
            if not math.isnan(Species[x][1]):
                if (Species[x][1] * 1000 <
                        1):  # need this to round things to fit in the table
                    Species[x][1] = round_half_up(Species[x][1], decimals=6)
                else:
                    Species[x][1] = round_half_up(Species[x][1], decimals=4)

        del (SpecList)

    l = sbmldoc.model.getNumParameters()
    if l != 0:
        ParList = ['obj.getId()', 'obj.getValue()', 'obj.getConstant()']
        for x in range(0, l):
            obj = sbmldoc.model.getParameter(x)
            Parameters = listfiller(ParList, obj=obj, tofill=Parameters)
        del (ParList)

    l = sbmldoc.model.getNumReactions()
    if l != 0:
        Rlist = ['R.getId()', 'R.getReversible()', 'R.getFast()']
        ReProlist = [
            'Sp.getSpecies()', 'Sp.getStoichiometry()', 'Sp.getConstant()'
        ]
        Modlist = ['obj.getSpecies()']
        for x in range(0, l):
            R = sbmldoc.model.getReaction(x)
            RL = listfiller(
                Rlist, R=R, twoD=0
            )  #starting the element of common matrix/list to append at the end

            #making the list for reactants
            lRe = R.getNumReactants()
            ReL = []
            for y in range(0, lRe):
                Sp = R.getReactant(y)
                ReL = listfiller(ReProlist, Sp=Sp, tofill=ReL)
            RL.append(ReL)
            del (lRe, ReL)  #Adding reactants list to RL

            #making the list for products
            lPro = R.getNumProducts()
            ProL = []
            for y in range(0, lPro):
                Sp = R.getProduct(y)
                ProL = listfiller(ReProlist, Sp=Sp, tofill=ProL)
            RL.append(ProL)
            del (Sp, ProL, y, lPro)  #Adiing products list to RL

            #making the law thing
            law = R.getKineticLaw()
            prefix = law.toSBML()
            Formula = lawcutter(prefix)
            # repeating the deleted list for now, so that code works consitstnently
            ParList = [
                'Par.getId()', 'Par.getValue()',
                'Par.getDerivedUnitDefinition()', 'Par.getConstant()'
            ]
            lPar = law.getNumParameters()
            ParL = []
            for y in range(0, lPar):
                Par = law.getParameter(y)
                ParL = listfiller(ParList, Par=Par, tofill=ParL)
            KinLaw = [Formula, ParL]
            RL.append(KinLaw)
            del (Formula, law)

            lMod = R.getNumModifiers()
            if lMod > 0:
                ModL = []
                for y in range(0, lMod):
                    obj = R.getModifier(y)
                    ModL = listfiller(Modlist, obj=obj, tofill=ModL)
                RL.append(ModL)

            Reactions.append(
                RL
            )  #Appending all info about a given reaction to the common list
        del (RL, R, Rlist, ReProlist, ParList, lPar, ParL, KinLaw, prefix)

    l = sbmldoc.model.getNumEvents()
    if l != 0:
        TrList = ['tr.getInitialValue()', 'tr.getPersistent()', 'tr.getMath()']
        AsList = ['ass.getId()', 'ass.getMath()']
        for x in range(0, l):
            eve = sbmldoc.model.getEvent(x)  #get the event
            tr = eve.getTrigger()
            TrigL = [0, 0, 0]
            TrigL = listfiller(TrList, tr=tr, tofill=TrigL,
                               twoD=0)  #define trigger things
            m = eve.getNumEventAssignments()
            AssL = []
            for i in range(0, m):
                ass = eve.getEventAssignment(i)
                AssL = listfiller(
                    AsList, ass=ass, tofill=AssL
                )  #add up all of the ID = Formula in a single list
            del (i, m)

            Events.append([eve.getId(), eve.getName(), TrigL, AssL])
        del (TrList, AsList, eve, tr, TrigL, ass, AssL)

    l = sbmldoc.model.getNumRules()
    if l != 0:
        RuList = ['obj.getVariable()', 'obj.getFormula()']
        for x in range(0, l):
            obj = sbmldoc.model.getRule(x)
            Rules = listfiller(RuList, obj=obj, tofill=Rules)
        del (RuList)
        del (obj)

    l1 = sbmldoc.model.getNumFunctionDefinitions()
    if l1 != 0:
        FuncList = ['obj.getId()', 'obj.getBody()']
        for x in range(0, l1):
            obj = sbmldoc.model.getFunctionDefinition(x)
            FunctionDefinitions = listfiller(FuncList,
                                             obj=obj,
                                             tofill=FunctionDefinitions)
            l2 = obj.getNumArguments()
            if l2 != 0:
                for k in range(0, l2):
                    FunctionArgList.append(obj.getArgument(k))

    del (libsbml, lawcutter, l, notecutter, listfiller)

    # The part where everything is compiled into the TeX file

    from pylatex import Document, Section, Subsection, Subsubsection, Command, Math, Tabular, LongTable
    from pylatex import Table, LineBreak
    from pylatex.utils import italic, NoEscape, bold

    doc = Document()  # start a doc

    doc.packages.append(NoEscape(r'\usepackage{xcolor}'))
    doc.packages.append(NoEscape(r'\usepackage{titlesec}'))
    doc.packages.append(NoEscape(r"\usepackage{hyperref}"))
    doc.packages.append(
        NoEscape(r"\hypersetup{colorlinks=true,linkcolor=blue,urlcolor=blue}"))
    doc.packages.append(NoEscape(r"\usepackage{amsmath}"))
    doc.packages.append(NoEscape(r"\usepackage{breqn}"))

    doc.preamble.append(NoEscape(r'\definecolor{blue}{cmyk}{.93, .59, 0, 0}'))
    doc.preamble.append('')
    doc.preamble.append(NoEscape(r'\titleformat{\chapter}[display]'))
    doc.preamble.append(
        NoEscape(r'  {\normalfont\sffamily\huge\bfseries\color{blue}}'))
    doc.preamble.append(
        NoEscape(r'  {\chaptertitlename\ \thechapter}{20pt}{\Huge}'))
    doc.preamble.append(NoEscape(r'\titleformat{\section}'))
    doc.preamble.append(
        NoEscape(r'  {\normalfont\sffamily\Large\bfseries\color{blue}}'))
    doc.preamble.append(NoEscape(r'  {\thesection}{1em}{}'))
    doc.preamble.append(NoEscape(r'\titleformat{\subsection}'))
    doc.preamble.append(
        NoEscape(r'  {\normalfont\sffamily\large\bfseries\color{blue}}'))
    doc.preamble.append(NoEscape(r'  {\thesubsection}{1em}{}'))
    doc.preamble.append(NoEscape(r'\titleformat{\subsubsection}'))
    doc.preamble.append(
        NoEscape(r'  {\normalfont\sffamily\normalsize\bfseries\color{blue}}'))
    doc.preamble.append(NoEscape(r'  {\thesubsubsection}{1em}{}'))

    doc.append(NoEscape(r'\begin{center}'))
    doc.append(
        NoEscape(r'{\normalfont\sffamily\huge\bfseries SBML Model Report}\\'))

    doc.append(NoEscape(r'\vspace{5mm}'))
    doc.append(
        NoEscape(
            r'{\normalfont\sffamily\LARGE\bfseries\color{blue} Model name: ' +
            Model_id + r'}\\'))

    doc.append(NoEscape(r'\vspace{5mm}'))
    doc.append(NoEscape(r'\large\today'))
    doc.append(NoEscape(r'\end{center}'))

    def rxn_eq(Reaction, Command=Command):
        '''
        Stitches up a list to plug into Math function for reaction equations
        
        '''
        numRe = len(
            Reaction[3])  # the products info is stored as a list in position 3
        numPr = len(Reaction[4])
        try:
            numMod = len(Reaction[6])
        except:
            numMod = 0
        arrow = []
        plus = ['+']
        Re = []
        Pr = []

        if numRe > 0:
            for i in range(0, numRe):
                if (i > 0):
                    Re = Re + plus
                Re.append(Command(
                    command='text', arguments=Reaction[3][i]
                    [0]))  #Appends with IDs of species that are reactannts
        else:
            Re.append(Command(command='text', arguments=['None']))

        if numPr > 0:
            for i in range(0,
                           numPr):  # Put in the form Math class can interpret
                if (i > 0):
                    Pr = Pr + plus
                Pr.append(Command(command='text', arguments=Reaction[4][i][0]))
        else:
            Pr.append(Command(command='text', arguments=['None']))

        if numMod > 0:
            arg = []
            for i in range(0, numMod):
                arg.append(Reaction[6][i][0])
            arg = ", ".join(arg)
            arrow = [
                Command(command='xrightarrow',
                        arguments=Command(command='text', arguments=arg))
            ]
        else:
            arrow = [Command('longrightarrow')]

        DaList = Re + arrow + Pr
        return DaList

    if lis != None:
        # NOTES -- made from html string, can recognize:
        # <a href...>, <b>, <i>,<br/> and treats emphasis as italic or bold
        # there is a known issue with special characters such as # not being interpreted right
        # to fix that, follow the structure below
        leng = len(lis)
        with doc.create(Section('Notes')):

            def findOccurrences(s, ch):
                return [i for i, letter in enumerate(s) if letter == ch]

            doc.append(Command('raggedright'))
            doc.append(Command('frenchspacing'))
            for i in range(0, leng):
                if (leng < 2):
                    doc.append(lis[i])
                    continue
                if (
                        '&apos;' in lis[i]
                ):  #THIS if statement is being referenced above, &apos; is the HTML code for
                    #the apostrophe
                    lis[i] = lis[i].replace("&apos;", "'")
                if ('&amp;' in lis[i]):
                    lis[i] = lis[i].replace("&amp;", "&")
                if ('&dollar;' in lis[i]):
                    lis[i] = lis[i].replace("&dollar;", "$")
                if ('&num;' in lis[i]):
                    lis[i] = lis[i].replace("&num;", "#")
                if ('&plus;' in lis[i]):
                    lis[i] = lis[i].replace("&plus;", "+")
                if ('&excl;' in lis[i]):
                    lis[i] = lis[i].replace("&excl;", "!")
                if ('&quest;' in lis[i]):
                    lis[i] = lis[i].replace("&quest;", "?")
                if ('/' in lis[i] and 'br/>' not in lis[i]
                        and '//' not in lis[i]
                        and len(lis[i].replace(" ", "")) < 4
                        and 'strong>' not in lis[i]):
                    continue  #! trying to skip every instance of </something> assuming the 4 length as cutoff

                elif ('br/>' in lis[i] and len(lis[i].replace(" ", "")) < 4):
                    doc.append(LineBreak())
                elif ('br/>' in lis[i]):
                    doc.append(LineBreak())
                    doc.append(lis[i].replace("br/>", ""))
                elif ('p>' in lis[i]):
                    doc.append(Command('par'))
                    doc.append(lis[i][2:len(lis[i])])
                elif ('sub>' in lis[i] and '/sub>' not in lis[i]):
                    temp = lis[i].replace("sub>", "")
                    doc.append(NoEscape("$_{\\text{" + temp + "}}$"))

                elif (('b>' in lis[i] or 'strong>' in lis[i])
                      and ('/b>' not in lis[i]) and ('/strong>' not in lis[i])
                      and ('/sub>' not in lis[i])):
                    temp = lis[i].replace("b>", "")
                    temp = temp.replace("strong>", "")
                    doc.append(bold(temp))

                elif (('i>' in lis[i] or 'em>' in lis[i])
                      and ('/i>' not in lis[i]) and ('/em>' not in lis[i])):
                    temp = lis[i].replace("i>", "")
                    temp = temp.replace("em>", "")
                    doc.append(italic(temp))
                elif (('/b>' in lis[i]) or ('/strong>' in lis[i])
                      or ('/i>' in lis[i]) or ('/em>' in lis[i])
                      or ('/sub>' in lis[i])):
                    temp = lis[i].replace("/i>", "")
                    temp = temp.replace("/em>", "")
                    temp = temp.replace("/b>", "")
                    temp = temp.replace("/strong>", "")
                    temp = temp.replace("/sub>", "")

                    doc.append(temp)
                elif ('a href=' in lis[i]):
                    t_list = lis[i].split('>')
                    pos = findOccurrences(t_list[0], '\"')
                    link = t_list[0][pos[0] + 1:pos[
                        1]]  #! Assuming that the first to places with " \" "
                    #will surround the link
                    doc.append(
                        NoEscape("\href{" + link + "}" + "{" + t_list[1] +
                                 "}"))
                    #! Assuming that in a hyperlink notation:
                    # i. e <a href="http://link.com">text that the author wants to be seen</a>
                else:
                    pos = findOccurrences(lis[i], '>')
                    doc.append(lis[i][pos[0] + 1:])

            del (leng)

    with doc.create(Section('Contents')):
        # Summary of contents of sbml model
        doc.append('The number of components in this model:')
        doc.append(NoEscape(r'\\[2mm]'))

        with doc.create(Table(position='htpb')) as table1:
            doc.append(NoEscape(r'\centering'))
            tbl_cmnd = ''
            tbl_cmnd = 'l|c|l|c'
            with doc.create(Tabular(tbl_cmnd, booktabs=True)) as table:
                table.add_row('Element', 'Quantity', 'Element', 'Quantity')
                table.add_hline()
                table.add_row('Compartment', str(len(Compartments)), 'Species',
                              str(len(Species)))
                table.add_row('Reactions', str(len(Reactions)), 'Events',
                              str(len(Events)))
                table.add_row('Global Parameters', str(len(Parameters)),
                              'Function Definitions',
                              str(len(FunctionDefinitions)))
            table1.add_caption('Components in this model.')

    # COMPARTMENTS TABLE
    listlen = len(Compartments)  #number of rows
    sublistlen = len(Compartments[0])  #number of columns
    tbl_cmnd = ''
    tbl_cmnd = tbl_cmnd.join('c|' for i in range(0, sublistlen))
    tbl_cmnd = tbl_cmnd[:-1]

    with doc.create(Section('Compartments')):
        doc.append('Table of comparments in the model:')
        with doc.create(LongTable(tbl_cmnd, booktabs=True)) as table:
            table.add_row(('ID', 'SBO ', 'Spatial ', 'Size', 'Constant'))
            table.add_row(('', 'Term', 'Dimensions', '', ''))
            table.add_hline()
            for i in range(0, listlen):
                if math.isnan(Compartments[i][1]):
                    Species[i][1] = 'undefined'
                table.add_row(tuple(Compartments[i]))

    # SPECIES TABLE
    # getting info from the list
    listlen = len(Species)  #number of rows
    sublistlen = len(Species[0])  #number of columns
    tbl_cmnd = ''
    #tbl_cmnd.join('X|' for i in range(0, sublistlen))
    tbl_cmnd = tbl_cmnd.join('c|' for i in range(0, sublistlen))
    tbl_cmnd = tbl_cmnd[:-1]  # Remove last character, dont want verical line

    # making a tble for latex
    # As the most simple way of doing this, we can convert the lists into tuples and just paste into
    # the add_row command. For something more complicated: some if statements would be useful
    with doc.create(Section('Species')):
        doc.append('Table of species in the model:')
        with doc.create(LongTable(tbl_cmnd, booktabs=True)) as table:
            table.add_row(('ID', 'Initial ', 'Only ', 'Boundary', 'Constant'))
            table.add_row(
                ('', 'Concentration', 'Substance Units', ' Conditions', ''))
            table.add_hline()
            for i in range(0, listlen):
                if math.isnan(Species[i][1]):
                    Species[i][1] = 'undefined'
                table.add_row(tuple(Species[i]))

    # GLOBAL PARAMETER TABLE
    listlen = len(Parameters)  #number of rows
    if (listlen < 1):
        with doc.create(Section('Parameters')):
            doc.append(
                'The function could not identify any global Parameters in the model'
            )
    else:
        sublistlen = len(Parameters[0])  #number of columns
        tbl_cmnd = ''
        #tbl_cmnd.join('X|' for i in range(0, sublistlen))
        tbl_cmnd = tbl_cmnd.join('c|' for i in range(0, sublistlen))
        tbl_cmnd = tbl_cmnd[:
                            -1]  # Remove last character, dont want verical line

        with doc.create(Section('Parameters')):
            doc.append(
                'The following table is the list of Parameters in the model.')
            with doc.create(LongTable(tbl_cmnd, booktabs=True)) as table:
                table.add_row(('ID', 'Value', 'Constant'))
                table.add_hline()
                for i in range(0, listlen):
                    table.add_row(tuple(Parameters[i]))

    # PROCESS RULES
    listlen = len(Rules)
    if (listlen >= 1):
        with doc.create(Section('Rules')):
            doc.append('Number of rules in the model: ' + str(listlen))
            for i in range(0, listlen):
                with doc.create(
                        Subsection('Rule ' + str(i + 1) + ': ' + Rules[i][0])):
                    doc.append(Math(data=[Rules[i][0] + '=' + Rules[i][1]]))

    # PROCESS FUNCTION DEDFINITIONS
    listlen = len(FunctionDefinitions)
    if (listlen >= 1):
        with doc.create(Section('Function Definitions')):
            doc.append('Number of usr defined functions in the model: ' +
                       str(listlen))
            for i in range(0, listlen):
                latexstr = getLaTeXFromAST(FunctionDefinitions[i][1])

                with doc.create(Subsection('Function ' + str(i + 1))):
                    doc.append(Command("begin", "dmath*"))
                    doc.append(
                        NoEscape(
                            '$$' + '\\text{' +
                            FunctionDefinitions[i][0].replace('_', '\\_') +
                            '}\ ('))
                    for j in range(0, len(FunctionArgList)):

                        latexarg = getLaTeXFromAST(FunctionArgList[j])
                        if j == len(FunctionArgList) - 1:
                            doc.append(
                                NoEscape(str(latexarg.replace('_', '\\_'))))
                        else:
                            doc.append(
                                NoEscape(latexarg.replace('_', '\\_') + ','))
                    doc.append(
                        NoEscape('): ' + latexstr.replace('_', '\\_') + '$$'))
                    doc.append(Command("end", "dmath*"))

    # PROCESS EVENTS
    listlen = len(Events)
    if (listlen >= 1):
        with doc.create(Section('Events')):
            doc.append('Number of events defined in the model: ' +
                       str(listlen))
            for i in range(0, listlen):
                with doc.create(
                        Subsection('Event ' + str(i + 1) + ': ' +
                                   Events[i][0])):
                    if (len(Events[i][1]) > 0):
                        with doc.create(Subsubsection('Name',
                                                      numbering=False)):
                            doc.append(Events[i][1])
                    with doc.create(Subsubsection('Trigger', numbering=False)):
                        doc.append(
                            NoEscape('$$' + getLaTeXFromAST(Events[i][2][2]) +
                                     '$$'))
                    with doc.create(
                            Subsubsection('Assignments', numbering=False)):
                        for j in range(0, len(Events[i][3])):
                            assTree = parseFormula(Events[i][3][j][0])
                            ass = '$$' + getLaTeXFromAST(
                                assTree) + '=' + getLaTeXFromAST(
                                    Events[i][3][j][1]) + '$$'
                            doc.append(NoEscape(ass))

    # PROCESS REACTIONS
    listlen = len(Reactions)  # number of rows

    with doc.create(Section('Reactions')):
        doc.append('Number of reactions in the model: ' + str(listlen))
        for i in range(0, listlen):
            with doc.create(
                    Subsection('Reaction ' + str(i + 1) + ': ' +
                               Reactions[i][0])):

                with doc.create(
                        Subsubsection('Reaction equation', numbering=False)):
                    doc.append(Math(data=rxn_eq(Reaction=Reactions[i])))
                with doc.create(Subsubsection('Kinetic Law', numbering=False)):
                    m = readMathMLFromString(Reactions[i][5][0])
                    formula = getLaTeXFromAST(m)
                    formula = formula.replace('\mathrm', '\ \mathrm')
                    doc.append(Command("begin", "dmath*"))
                    doc.append(
                        NoEscape('$$v =' + formula.replace('_', '\\_') + '$$'))
                    doc.append(Command("end", "dmath*"))
                with doc.create(Subsubsection('Local Parameters')):
                    if len(Reactions[i][5][1]) != 0:
                        sublistlen = len(Reactions[i][5][1][0])
                        tbl_cmnd = ''
                        tbl_cmnd = '||' + tbl_cmnd.join(
                            'c|' for n in range(0, sublistlen)) + '|'
                        with doc.create(LongTable(tbl_cmnd,
                                                  booktabs=False)) as table:
                            table.add_hline()
                            table.add_row(('ID', 'Value', 'Units', 'Constant'))
                            table.add_hline()
                            table.add_hline()
                            listleng = len(Reactions[i][5][1])
                            for j in range(0, listleng):
                                table.add_row(tuple(Reactions[i][5][1][j]))
                                table.add_hline()
                    else:
                        doc.append('No LOCAL Parameters found')

    del (Command, Document, NoEscape, Section, Subsection, italic)
    return doc.dumps()
示例#12
0
    stats.kurtosis(spf_bal_HICP_1Y.iloc[:, 0].values, axis=0),
    stats.kurtosis(spf_bal_HICP_2Y.iloc[:, 0].values, axis=0),
    stats.kurtosis(spf_bal_UNEM_1Y.iloc[:, 0].values, axis=0),
    stats.kurtosis(spf_bal_UNEM_2Y.iloc[:, 0].values, axis=0),
])
spf_desc_stat.iloc[8, :] = np.array([
    stats.skew(spf_bal_RGDP_1Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_RGDP_2Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_HICP_1Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_HICP_2Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_UNEM_1Y.iloc[:, 0].values, axis=0),
    stats.skew(spf_bal_UNEM_2Y.iloc[:, 0].values, axis=0),
])

# create table object
tabl = Table()
tabl.add_caption(
    "Descriptive statistics of the SPF target macroeconomic variables for the euro area"
)
tabl.append(NoEscape('\label{tab: spf_Desc_Stats}'))
# create tabular object
tabr = Tabular(table_spec="l|cc|cc|cc")
tabr.add_hline()
tabr.add_hline()
# header row

tabr.add_row(
    (MultiRow(2, data="Statistic"), MultiColumn(2, align='|c|', data="RGDP"),
     MultiColumn(2, align='|c|',
                 data="HICP"), MultiColumn(2, align='|c', data="UNEM")))
tabr.add_hline(start=2, end=3, cmidruleoption="lr")
        options=['tmargin=2cm', 'lmargin=1cm', 'rmargin=1cm', 'bmargin=2cm']))
doc.packages.append(Package('floatrow'))
doc.preamble.append(r'\DeclareFloatFont{huge}{\huge}')
doc.preamble.append(r'\floatsetup[table]{font=huge}')

# doc.append(r'\DeclareFloatFont{tiny}{\tiny}')
# doc.append(r'\floatsetup[table]{font=tiny}')

#Main section manuscript
with doc.create(Section('HII Galaxies properties:')):

    for i in range(len(HII_Galaxy_List)):
        Galaxy = HII_Galaxy_List[i]

        with doc.create(Subsection('Galaxy ' + Galaxy)):
            with doc.create(Table('|c|c|')) as table:
                for parameter in parameter_List:
                    Label = Properties_dict[parameter]['label']
                    value = str(Data_Dict[Galaxy][parameter])
                    table.add_hline()
                    table.add_row((Label, value))

            doc.append(r'\newpage')
            doc.append(r'\tiny')

            with doc.create(Table('|c|c|c|c|c|c|c|c|')) as table:
                #                 List_Headers = Lines_Dict[CodeName].keys() + [r'$F_{Nebular}$', r'$F_{Stellar}$']
                List_Lines = Lines_Dict[CodeName]['Ion']
                table.add_hline()
                table.add_row(Labels_list +
                              [r'$F_{Nebular}$', r'$F_{Stellar}$'])
示例#14
0
def gen_tex_table(tbl, cap, file_name, r):
    """
    The function creates a tex file to which it export the given table from
    python.

    Parameters
    ----------
    tbl : DataFrame
        DataFrame containing the table to be exported.

    cap : Str
        Table caption.

    file_name : Str
        Name of the tex file in the "Tables" directory.


    r : Int
       Number of decimals to round up the metrics.
    """

    # create tabule object
    tabl = Table()
    tabl.add_caption(cap)
    tabl.append(NoEscape("\label{tab: " + cap + "}"))

    # create tabular object
    tabr = Tabular(table_spec="lccc")
    tabr.add_hline()
    tabr.add_hline()

    # header row
    tabr.add_row(["Forecast Combination Method"] + list(tbl))
    tabr.add_hline()

    # number of combination methods + additional rows
    R = tbl.shape[0]

    # specify format
    fmt = "{:." + str(r) + "f}"

    # fill in the rows for each combination method (-3 for individuals)
    for i in range(R-3):

        tabr.add_row([tbl.index[i]] + [
                fmt.format(item) for item in tbl.iloc[i, :]])

    tabr.add_hline()

    # additional rows
    for i in range(R-3, R):

        tabr.add_row([tbl.index[i]] + [
                fmt.format(item) for item in tbl.iloc[i, :]])

    # end of table
    tabr.add_hline()
    tabr.add_hline()

    # add tabular to table
    tabl.append(tabr)

    # export the table
    tabl.generate_tex("C:/Users/Marek/Dropbox/Master_Thesis/Latex/Tables/" +
                      file_name)

    return
示例#15
0
    maketitle=False
)

doc.append('Some text.')

doc.generate_tex(filename='')
doc.generate_pdf(filename='', clean=True)

# SectionBase
s = Section(title='', numbering=True, data=None)

# Math
m = Math(data=None, inline=False)

# Table
t = Table(table_spec='|c|c|', data=None, pos=None, table_type='tabular')

t.add_hline(start=None, end=None)

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

t.add_multicolumn(size=2, align='|c|', content='Multicol', cells=None,
                  escape=False)

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

# Command
c = Command(command='documentclass', arguments=None, options=None,
            packages=None)
# Figure
doc.packages.append(Package('preview', options=[
    'active',
    'tightpage',
]))

#Define font size
doc.append(r'\tiny')

#String with the columns format : |c|c|c|
columns_latexformat = '|c' * (len(HII_Galaxy_List) + 1) + '|'
print columns_latexformat
print len(HII_Galaxy_List)
print len(HII_Galaxy_List) + 1
#Generate table
doc.append(r'\begin{preview}')
with doc.create(Table(columns_latexformat)) as table:

    Table_Headers = ['Parameter'] + HII_Galaxy_List
    table.add_hline()
    table.add_row(Table_Headers)

    for parameter in parameter_List:
        row_list = []
        Label = Properties_dict[parameter]['label']
        row_list.append(Properties_dict[parameter]['label'])

        for Galaxy in HII_Galaxy_List:
            value = str(Data_Dict[Galaxy][parameter])
            row_list.append(value)

        table.add_hline()
示例#17
0
sorted(eqs)
bto = getBothTimedOut(results1, results2)
bst1 = getBest(results1, results2)
bst2 = getBest(results2, results1)
inc1 = getIncomparable(results1, results2)
inc2 = getIncomparable(results2, results1)
print(bst2)
connection.close()

# Now start document
doc = Document(title='Comparing %s and %s' % (biddics[bid1], biddics[bid2]),
               author='Charles Prud\'homme')
doc.packages.append(Package('geometry'))

with doc.create(Section('Overview')):
    with doc.create(Table('l|c')) as table:
        table.add_hline()
        table.add_row(("Comment", "Number"))
        table.add_hline()
        table.add_row(("Equality", len(eqs)))
        table.add_row((biddics[bid1], len(bst1)))
        table.add_row((biddics[bid2], len(bst2)))
        table.add_row(("Both TO", len(bto)))
        table.add_row(("%s only" % biddics[bid1], len(inc1)))
        table.add_row(("%s only" % biddics[bid2], len(inc2)))
        table.add_hline()

    with doc.create(Subsection('Equality')):
        with doc.create(Table('r|l|r')) as table:
            table.add_hline()
            table.add_row(("pid", "Name", "Time (sec)"))
示例#18
0
#!/usr/bin/python

from pylatex import Document, Section, Subsection, Table

doc = Document(filename="multirow")
section = Section('Multirow Test')

test1 = Subsection('Multicol')
test2 = Subsection('Multirow')

table1 = Table('|c|c|')
table1.add_hline()
table1.add_multicolumn(2, '|c|', 'Multicol')
table1.add_hline()
table1.add_row((1, 2))
table1.add_hline()
table1.add_row((3, 4))
table1.add_hline()

table2 = Table('|c|c|c|')
table2.add_hline()
table2.add_multirow(3, '*', 'Multirow', cells=((1, 2), (3, 4), (5, 6)))
table2.add_hline()
table2.add_multirow(3, '*', 'Multirow2')
table2.add_hline()

test1.append(table1)
test2.append(table2)

section.append(test1)
section.append(test2)
示例#19
0
    maketitle=False
)

doc.append('Some text.')

doc.generate_tex(filename='')
doc.generate_pdf(filename='', clean=True)

# SectionBase
s = Section(title='', numbering=True, data=None)

# Math
m = Math(data=None, inline=False)

# Table
t = Table(table_spec='|c|c|', data=None, pos=None, table_type='tabular')

t.add_hline(start=None, end=None)

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

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

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

# Figure
示例#20
0
    def build_latex(metrics: List[Metric], invert=False, caption=""):
        models, metric_labels, splits = {}, {}, {}
        score_map = defaultdict(lambda: "-")
        for metric in metrics:
            metric_vals = metric()
            score, metric_label, model_name, split_name = (
                metric_vals[SCORE],
                metric_vals[METRIC_LABEL],
                metric_vals[MODEL_NAME],
                metric_vals[SPLIT_NAME],
            )
            metric_labels[metric_label] = 1
            models[model_name] = 1
            splits[split_name] = 1
            score_map[(metric_label, model_name,
                       split_name)] = ("-" if math.isnan(score) else score)

        models = list(models.keys())
        splits = list(splits.keys())
        metric_labels = list(metric_labels.keys())

        if not invert:
            model_split_cols = "".join(
                ["c|" for _ in range(len(models) * len(splits))])
            table = Tabular("|c|" + model_split_cols)
            table.add_hline()
            row = (MultiRow(
                2, data="Metric"), ) if len(splits) > 1 else ("Metric", )
            for model_name in models:
                row += (MultiColumn(len(splits), align="|c|",
                                    data=model_name), )
            table.add_row(row)
            table.add_hline(1 if len(splits) == 1 else 2)
            if (len(splits)) > 1:
                row = ("", )
                for _ in range(len(models)):
                    for split_name in splits:
                        row += (split_name, )
                table.add_row(row)
                table.add_hline()
            for metric_label in metric_labels:
                row = (metric_label, )
                for model_name in models:
                    for split_name in splits:
                        row += (score_map[(metric_label, model_name,
                                           split_name)], )
                table.add_row(row)
                table.add_hline()
        else:
            metric_split_labels = "".join(
                ["c|" for _ in range(len(metric_labels))])
            table = Tabular("|c|" if len(splits) == 1 else "|c|c|" +
                            metric_split_labels)
            table.add_hline()
            row = (MultiColumn(2, align="|c|",
                               data=""), ) if len(splits) > 1 else ("", )
            for metric_label in metric_labels:
                row += (metric_label, )
            table.add_row(row)
            table.add_hline()
            for model_name in models:
                row = (MultiRow(len(splits), data=model_name), )
                for split_name in splits:
                    row += (split_name, )
                    for metric_label in metric_labels:
                        row += (score_map[(metric_label, model_name,
                                           split_name)], )
                    table.add_row(row)
                    if len(splits) > 1:
                        table.add_hline(start=2)
                    row = ("", )
                table.add_hline()

        latex_table = Table(position="h")
        latex_table.append(table)
        latex_table.add_caption(caption)
        return latex_table
示例#21
0
        subsection = Subsection('%s' % (prevsubsec.replace("_", "\_")))
        section.append(subsection)
        print("create subsection: " + prevsubsec)

    if len(parts) > 2:
        subsubsection = Subsubsection('%s' % (parts[2].replace("_", "\_")))
        subsection.append(subsubsection)
        print("create subsubsection: " + parts[2])
    else:
        subsubsection = Subsubsection('%s' % (parts[1].replace("_", "\_")))
        subsection.append(subsubsection)
        print("create subsubsection: " + parts[1])

    if solutions[0][3] == 'SAT':
        solutions.sort(key=lambda x: (x[3], x[1]))
        table = Table('l|r|l|r|r')
        subsubsection.append(table)
        table.add_hline()
        table.add_row(("Param.", 'Status', "\#Sol", 'Time(sec)', 'Nodes'))
        table.add_hline()
        for i in range(0, len(solutions)):
            table.add_row((solutions[i][6], solutions[i][5], solutions[i][0], solutions[i][1], solutions[i][2]))
            coords[solutions[i][6]].append((k, solutions[i][1]))
        table.add_hline()
    else:
        # sort for MIN
        type = 'MIN'
        solutions.sort(key=lambda x: (x[3], x[4], x[1]))
        best = solutions[0][4]
        # check first row and last row
        if solutions[0][3] == 'MAX' or solutions[len(solutions) - 1][3] == 'MAX':
示例#22
0
    def to_tex(self):

        tab = self._create_tabular()
        tab.add_hline()
        for i in range(self.sheet.nrows):
            line = []
            merge_set = set()
            for j in range(self.sheet.ncols):
                res, mindex = self.in_merge_cell(i, j)

                if res == -1:
                    line.append(self.cell(i, j))
                else:
                    merge_set.add(mindex)
                    cres, cnum = self.ismulticol(mindex)
                    rres, rnum = self.ismultirow(mindex)
                    if res == 0:
                        if cres:
                            if rres:
                                line.append(
                                    MultiColumn(
                                        cnum,
                                        align=self._cacu_multicol_align(j),
                                        data=MultiRow(rnum,
                                                      data=self.cell(i, j))))
                            else:
                                line.append(
                                    MultiColumn(
                                        cnum,
                                        align=self._cacu_multicol_align(j),
                                        data=self.cell(i, j)))
                        else:
                            line.append(MultiRow(rnum, data=self.cell(i, j)))
                    elif res == 1:  # 不同行同列
                        if cres and rres:
                            line.append(
                                MultiColumn(cnum,
                                            align=self._cacu_multicol_align(j),
                                            data=""))
                        else:
                            line.append("")
                    elif res == 2:  # 不同列同行
                        pass

            tab.add_row(line)

            all_range = [[0, self.sheet.ncols - 1]]
            for mi in merge_set:
                merge_range = self.merge_col[mi]

                if merge_range[1] - merge_range[0] > 0 and merge_range[
                        1] - i > 0:
                    all_range = self._extract_range(all_range,
                                                    merge_range[2:4])

            if all_range[0][0] == 0 and all_range[0][1] == self.sheet.ncols - 1:
                tab.add_hline()
            else:
                for r in all_range:
                    tab.add_hline(r[0] + 1, r[1] + 1)

        table = TexTable(position=self.params["position"])
        table.append(tab)

        res = table
        if self.params["center"]:
            c = Center()
            c.append(
                NoEscape(
                    r"% \newlength\tablewidth % if haven't define the length 'tablewidth'"
                ))
            c.append(
                NoEscape(
                    rf"\setlength\tablewidth{{\dimexpr (\textwidth -{2*self.sheet.ncols}\tabcolsep)}}"
                ))
            c.append(table)
            res = c

        return self._format_tex(res.dumps())
示例#23
0
def json2latex2pdf(json, mode="clean"):

    # on construit le nom du rapport
    #rapFile = "_TEX_report"
    name = json["comp_details"]["general"]["job_type"][0]
    rapFile = (name + "_report")

    #####################################################################
    #                                                                   #
    ## production du rapport en .tex                                 #
    #                                                                   #
    #####################################################################

    ### create document and import needed packages

    doc = (Document("article"))

    # packages
    doc.packages.append(Package('datetime'))
    doc.packages.append(NoEscape(r'\usepackage[margin=2cm]{geometry}'))
    doc.packages.append(NoEscape(r'\usepackage{extramarks}'))
    doc.packages.append(NoEscape(r'\usepackage{fancyhdr}'))
    doc.packages.append(NoEscape(r'\usepackage{svg}'))
    doc.packages.append(NoEscape(r'\usepackage[utf8]{inputenc}'))
    doc.packages.append(NoEscape(r'\usepackage{titlesec}'))
    #
    doc.packages.append(NoEscape(r'\pagestyle{fancy}'))
    doc.packages.append(NoEscape(r'\fancyhf{}'))
    # define header / footer texts
    doc.packages.append(NoEscape(r'\lhead{MOLECULAR CALCULATION REPORT}'))
    doc.packages.append(NoEscape(r'\rhead{Generated by QuChemReport}'))
    doc.packages.append(NoEscape(r'\lfoot{\today ~  \currenttime}'))
    doc.packages.append(NoEscape(r'\rfoot{Page \thepage}'))
    doc.packages.append(NoEscape(r'\cfoot{}'))
    # redefine rules for header / footer
    doc.packages.append(NoEscape(r'\renewcommand\headrulewidth{0.4pt}'))
    doc.packages.append(NoEscape(r'\renewcommand\footrulewidth{0.4pt}'))
    # redefine section
    doc.packages.append(NoEscape(r'\definecolor{ufrblue}{RGB}{0,161,140}'))
    doc.packages.append(NoEscape(r'\definecolor{bordeau}{RGB}{125,31,31}'))
    doc.packages.append(
        NoEscape(
            r'\titleformat{name=\section}[block]{\sc\large}{}{0pt}{\colorsection}'
        ))
    doc.packages.append(
        NoEscape(r'\titlespacing*{\section}{0pt}{\baselineskip}{5pt}'))
    doc.packages.append(
        NoEscape(r'\titlespacing{\subsection}{4pt}{\baselineskip}{5pt}'))
    doc.packages.append(
        NoEscape(
            r'\newcommand{\colorsection}[1]{' +
            r'\colorbox{ufrblue}{\parbox{\dimexpr\textwidth-2\fboxsep}{\textcolor{white}{'
            + r'\textbf{{\thesection.\ #1}}}}}}'))

    ### section 1 : authorship TODO with the DB !
    #########################################
    #    with doc.create(Section('AUTHORSHIP')):
    #        with doc.create(LongTabu("X[1,l] X[2,l]")) as tab:
    #            tab.add_row(['Original file', json["authorship"]["log_file"]])
    #            tab.add_row(['Primary author',  json["authorship"]["primary_author"]])
    #            add_row_filter(tab, ['ORCID',  json["authorship"]["primary_author_orcid"]])
    #            add_row_filter(tab, ['Affiliation',  json["authorship"]["primary_author_affiliation"]])
    #            add_row_filter(tab, ['Publication DOI',  json["authorship"]["publication_DOI"]])

    ### section 2 : molecule

    with doc.create(Section('MOLECULE')):
        taillePng = "6cm"
        nomPng = "img-TOPOLOGY.png"
        if (not os.path.isfile("img-TOPOLOGY.png")):
            print("No PNG named " + nomPng + " found. STOP.\n")
            sys.exit()

        # figure with Chemical structure diagram
        doc.append(NoEscape(r'\begin{figure}[h]'))
        doc.append(NoEscape(r'\begin{center}'))
        doc.append(
            NoEscape(r'\includegraphics[width=' + taillePng + ']{' + nomPng +
                     '}'))
        doc.append(NoEscape(r'\end{center}'))
        doc.append(NoEscape(r'\vspace{-5mm}'))
        doc.append(
            NoEscape(
                r'\caption*{Chemical structure diagram with atomic numbering.}'
            ))
        doc.append(NoEscape(r'\end{figure}'))

        with doc.create(LongTabu("X[1,l] X[2,l]")) as mol_table:
            inchi = (json["molecule"]["inchi"])[0].rstrip().split("=")[-1]
            mol_table.add_row(['InChI', inchi])
            mol_table.add_row(['SMILES', json["molecule"]["smi"]])
            mol_table.add_row([
                'Monoisotopic mass',
                "%.5f Da" % json["molecule"]["monoisotopic_mass"]
            ])
            mol_table.add_row(['Formula', json["molecule"]["formula"]])
            mol_table.add_row(['Charge', json["molecule"]["charge"]])
            mol_table.add_row(
                ['Spin multiplicity', json["molecule"]["multiplicity"]])

    ### section 2 : computational details
    #########################################
    software = json["comp_details"]["general"]["package"]
    with doc.create(Section('COMPUTATIONAL DETAILS')):
        #with doc.create(Subsection('General parameters')) :
        with doc.create(LongTabu("X[1,l] X[1,l]")) as param_table:
            try:
                param_table.add_row([
                    'Software',
                    json["comp_details"]["general"]["package"] + ' (' +
                    json["comp_details"]["general"]["package_version"] + ')'
                ])
            except KeyError:
                pass
            param_table.add_row([
                'Computational method',
                json["comp_details"]["general"]["last_theory"]
            ])
            add_row_filter(
                param_table,
                ['Functional', json["comp_details"]["general"]["functional"]])
            try:
                add_row_filter(param_table, [
                    'Basis set name',
                    json["comp_details"]["general"]["basis_set_name"]
                ])
            except KeyError:
                pass
            param_table.add_row([
                'Number of basis set functions',
                json["comp_details"]["general"]["basis_set_size"]
            ])
            param_table.add_row([
                'Closed shell calculation',
                json["comp_details"]["general"]["is_closed_shell"]
            ])
            add_row_filter(param_table, [
                'Integration grid',
                json["comp_details"]["general"]["integration_grid"]
            ])
            add_row_filter(
                param_table,
                ['Solvent', json["comp_details"]["general"]["solvent"]])
            #  TODO Test if solvent = gas in this case no Solvent reaction filed method
            #          add_row_filter(param_table, ['Solvent reaction filed method',
            #                                         json["comp_details"]["general"]["solvent_reaction_field"]])

            scfTargets = json["comp_details"]["general"]["scf_targets"][-1]
            if software == "Gaussian":  # Gaussian or GAUSSIAN (upper/lower?
                param_table.add_row([
                    "Requested SCF convergence on RMS density matrix",
                    scfTargets[0]
                ])
                param_table.add_row([
                    "Requested SCF convergence on MAX density matrix",
                    scfTargets[1]
                ])
                param_table.add_row(
                    ["Requested SCF convergence on energy", scfTargets[2]])
            if software == "GAMESS":
                param_table.add_row(
                    ["Requested SCF convergence on density", scfTargets[0]])

            #with doc.create(Subsection('Thermochemistry and normal modes calculation parameters')) :
            ## TODO tester si freq
            try:
                add_row_filter(param_table, [
                    'Temperature',
                    "%.2f K" % json["comp_details"]["freq"]["temperature"]
                ])
            except:
                pass
            T_len = False

            try:
                len(json["comp_details"]["freq"]["temperature"])
            except KeyError:
                json["comp_details"]["freq"]["temperature"] = []
            except TypeError:
                T_len = True
                if T_len is True:
                    try:
                        add_row_filter(param_table, [
                            'Anharmonic effects',
                            json["comp_details"]["freq"]["anharmonicity"]
                        ])

                    except KeyError:
                        pass
            if (json["comp_details"]["freq"]["temperature"]) != []:
                try:
                    add_row_filter(param_table, [
                        'Anharmonic effects',
                        json["comp_details"]["freq"]["anharmonicity"]
                    ])

                except KeyError:
                    pass

            #with doc.create(Subsection('Excited states calculation parameters')) :
            try:
                add_row_filter(param_table, [
                    'Number of excited states',
                    json["comp_details"]["excited_states"]["nb_et_states"]
                ])
            except KeyError:
                pass

    ### section 3 : results
    #########################################
    with doc.create(Section('RESULTS')):
        with doc.create(Subsection('Wavefunction')):

            with doc.create(LongTabu("X[l] X[l]")) as wavef_table:
                wavef_table.add_row([
                    'Total molecular energy',
                    "%.5f Hartrees" %
                    json["results"]["wavefunction"]["total_molecular_energy"]
                ])
                homo_indexes = [
                    i + 1
                    for i in json["results"]["wavefunction"]["homo_indexes"]
                ]
                wavef_table.add_row([
                    'H**O number', ("%s" % homo_indexes)[1:-1]
                ])  # indice begins at 0, remove brackets

            MO_energies = json["results"]["wavefunction"]["MO_energies"][-1]
            homo_nb = json["results"]["wavefunction"]["homo_indexes"][-1]
            doc.append(NoEscape(r'\begin{center}'))
            with doc.create(Table()) as motab:
                doc.append(NoEscape(r'\centering'))
                with doc.create(Tabular('p{1cm}ccccp{1cm}')) as mo_table:
                    row_cells = MultiColumn(
                        6,
                        align='c',
                        data=
                        'Calculated energies for the frontier molecular orbitals (in eV)'
                    )
                    mo_table.add_row([row_cells])
                    mo_table.add_row(
                        ['', 'H**O-1', 'H**O', 'LUMO', 'LUMO+1', ''])
                    mo_table.add_hline()
                    mo_table.add_row([
                        '',
                        "%.2f" % MO_energies[homo_nb - 1],
                        "%.2f" % MO_energies[homo_nb],
                        "%.2f" % MO_energies[homo_nb + 1],
                        "%.2f" % MO_energies[homo_nb + 2], ''
                    ])
            doc.append(NoEscape(r'\end{center}'))

            # figure with MO
            #### TODO : test autosize
            try:
                if len(json["results"]["excited_states"]['MO_png_list']) > 0:
                    figure_MO_table(
                        doc, ["LU1", "LUMO", "H**O", "HO1"],
                        json["results"]["excited_states"]['MO_png_list'],
                        caption=
                        ("Representation of the frontier molecular orbitals with a cutoff "
                         "value of 0.05. From up to bottom: LUMO+1, LUMO, H**O, H**O-1."
                         ))
            except:
                pass

            # figure skel for Atom numbering scheme
            try:
                figure_two_col(doc,
                               "skel",
                               json["results"]["geometry"]['skel_png_list'],
                               caption="Atom numbering scheme.",
                               pos="h")
            except:
                pass

            # Mulliken partial charges table
            try:
                mulliken = json["results"]["wavefunction"][
                    "Mulliken_partial_charges"]
            except KeyError:
                mulliken = []
            if len(mulliken) != 0:
                mulliken = np.array(mulliken)
                mean_m = np.mean(mulliken)
                dev_m = np.std(mulliken)
                thres_max = mean_m + dev_m
                thres_min = mean_m - dev_m
                doc.append(NoEscape(r'\begin{center}'))
                ind = np.argsort(mulliken)
                with doc.create(Tabular('p{0.5cm}rrrp{0.5cm}')) as tableau:
                    row_cells = [
                        MultiColumn(
                            5,
                            align='c',
                            data='Most intense Mulliken atomic charges')
                    ]
                    tableau.add_row(row_cells)
                    row_cells = [
                        MultiColumn(5,
                                    align='c',
                                    data='mean = %.3f e, std = %.3f' %
                                    (mean_m, dev_m))
                    ]
                    tableau.add_row(row_cells)
                    tableau.add_row(
                        ["", "Atom", "number", "Mulliken charges", ""])
                    tableau.add_hline()

                    for ielt in ind:
                        if (mulliken[ielt] > thres_max) or (mulliken[ielt] <
                                                            thres_min):
                            tableau.add_row([
                                "",
                                PeriodicTable().element[json['molecule']
                                                        ["atoms_Z"][ielt]],
                                (1 + ielt),
                                "%.3f" % mulliken[ielt], ""
                            ])
                    tableau.add_hline()
                doc.append(NoEscape(r'\end{center}'))

            # figure MEP
            try:
                if len(json["results"]["wavefunction"]['MEP_png_list']) > 0:
                    figure_two_col(
                        doc,
                        "MEP",
                        json["results"]["wavefunction"]['MEP_png_list'],
                        caption=
                        ("Representation of the molecular electrostatic potential "
                         "at the distance of the van der Waals radii of the atoms. "
                         "The red/blue regions depict the most negative (-0.1) / "
                         "positive (+0.1) regions."),
                        pos="h")
            except:
                pass

        with doc.create(Subsection('Geometry')):
            ######## PB
            atomic = json["results"]["geometry"][
                "elements_3D_coords_converged"]
            oxtrf, oytrf, oxtrd, oytrd = ('N/A', 'N/A', 'N/A', 'N/A')

            ### TODO
            # if singlePoint==1 :
            #      doc.append('This calculation is a single point ')
            try:
                is_opt = json["results"]["geometry"]["OPT_DONE"] == True
            except KeyError:
                is_opt = []
            if is_opt:
                doc.append(
                    NoEscape(
                        r"This calculation is the result of a geometry optimization process."
                    ))
            else:
                doc.append(
                    NoEscape(
                        r"\textcolor{bordeau}{Warning : this calculation does not include a geometry "
                        "optimization process. This geometry may not be a stationary "
                        "point for those computational parameters. In this case, results must be "
                        "used with caution.}"))

            if is_opt:
                ### TODO tests gaussian
                doc.append(NoEscape(r'\begin{center}'))
                geomTargets = json["comp_details"]["geometry"][
                    "geometric_targets"]
                geomValues = json["results"]["geometry"]["geometric_values"][
                    -1]
                with doc.create(Tabular('p{0cm}lrrp{0cm}')) as param_table:
                    row_cells = [
                        MultiColumn(
                            5,
                            align='c',
                            data='Geometry optimization convergence criteria')
                    ]
                    param_table.add_row(row_cells)
                    param_table.add_row(["", "", "Value", "Threshold", ""])
                    param_table.add_hline()
                    if software == "Gaussian":
                        param_table.add_row([
                            "", "Maximum Force",
                            "%.6f" % geomValues[0],
                            "%.6f" % geomTargets[0], ""
                        ])
                        param_table.add_row([
                            "", "RMS Force",
                            "%.6f" % geomValues[1],
                            "%.6f" % geomTargets[1], ""
                        ])
                        param_table.add_row([
                            "", "Maximum Displacement",
                            "%.6f" % geomValues[2],
                            "%.6f" % geomTargets[2], ""
                        ])
                        param_table.add_row([
                            "", "RMS Displacement",
                            "%.6f" % geomValues[3],
                            "%.6f" % geomTargets[3], ""
                        ])
                    if software == "GAMESS":
                        # in Hartrees per Bohr
                        param_table.add_row([
                            "", "Maximum Force",
                            "%.5f" % geomValues[0],
                            "%.5f" % geomTargets[0], ""
                        ])
                        param_table.add_row([
                            "", "RMS Force",
                            "%.5f" % geomValues[1],
                            "%.5f" % geomTargets[1], ""
                        ])
                    param_table.add_hline()
                doc.append(NoEscape(r'\end{center}'))

            with doc.create(LongTabu("X[l] X[l]")) as geom_table:
                geom_table.add_row([
                    'Nuclear repulsion energy',
                    "%.5f Hartrees" % json["results"]["geometry"]
                    ["nuclear_repulsion_energy_from_xyz"]
                ])

            doc.append(NoEscape(r'\begin{center}'))
            with doc.create(Tabular('p{0.5cm}rrrrp{0.5cm}')) as tableau:
                row_cells = [
                    MultiColumn(
                        6,
                        align='c',
                        data='Cartesian atomic coordinates in Angstroms')
                ]
                tableau.add_row(row_cells)
                tableau.add_row([
                    "", "Atom",
                    MultiColumn(1, align='c', data='X'),
                    MultiColumn(1, align='c', data='Y'),
                    MultiColumn(1, align='c', data='Z'), ""
                ])
                tableau.add_hline()
                atoms = np.array(json["results"]["geometry"]
                                 ["elements_3D_coords_converged"]).reshape(
                                     (-1, 3))
                for i, a in enumerate(atoms):
                    tableau.add_row([
                        "",
                        PeriodicTable().element[json['molecule']["atoms_Z"]
                                                [i]],
                        "%.4f" % a[0],
                        "%.4f" % a[1],
                        "%.4f" % a[2], ""
                    ])
                tableau.add_hline()
            doc.append(NoEscape(r'\end{center}'))

        ### Freq
        #### TODO : tests

        with doc.create(Subsection('Thermochemistry and normal modes')):
            rtemper = json["comp_details"]["freq"]["temperature"]
            # ND-arrays
            try:
                vibrational_int = np.array(
                    json["results"]["freq"]["vibrational_int"])
            except KeyError:
                vibrational_int = []
            try:
                vibrational_freq = np.array(
                    json["results"]["freq"]["vibrational_freq"])
            except KeyError:
                vibrational_freq = []

            try:
                vibrational_sym = np.array(
                    json["results"]["freq"]["vibrational_sym"])
            except KeyError:
                vibrational_sym = []

            # filtering & orderering
            if len(vibrational_int) == 0:
                vibrational_int = []
            else:
                vib_filter = vibrational_int > 50.
                vib_order = np.argsort(vibrational_freq[vib_filter])[::-1]
                vibrational_int = vibrational_int[vib_filter][vib_order]
                vibrational_freq = vibrational_freq[vib_filter][vib_order]
                vibrational_sym = vibrational_sym[vib_filter][vib_order]

            if (len(vibrational_int) != 0) and (rtemper != "N/A"):
                with doc.create(LongTabu("X[l] X[l]")) as thermo_table:
                    thermo_table.add_row([
                        'Sum of electronic and zero-point energy in Hartrees',
                        json["results"]["freq"]["zero_point_energy"]
                    ])
                    thermo_table.add_row([
                        "Sum of electronic and thermal at "
                        "%f K energies in atomic units" % rtemper,
                        json["results"]["freq"]["electronic_thermal_energy"]
                    ])
                    thermo_table.add_row([
                        "Entropy at %f K in atomic units" % rtemper,
                        json["results"]["freq"]["entropy"]
                    ])
                    thermo_table.add_row([
                        "Enthalpy at %f K in atomic units" % rtemper,
                        json["results"]["freq"]["enthalpy"]
                    ])
                    thermo_table.add_row([
                        "Gibbs free energy at %f K in atomic units" % rtemper,
                        json["results"]["freq"]["free_energy"]
                    ])

                doc.append(
                    "Table of the most intense molecular vibrations (> 20 km/mol) (%d)\n"
                    % len(vibrational_int))
                with doc.create(Tabular('rrrc')) as tableau:
                    tableau.add_row(
                        ["", "Frequencies", "Intensity", "Symmetry"])
                    for i in range(len(vibrational_freq)):
                        tableau.add_row([
                            "",
                            "%.4f" % vibrational_freq[i],
                            "%.4f" % vibrational_int[i], vibrational_sym[i]
                        ])
            else:
                doc.append(
                    NoEscape(
                        r"\textcolor{bordeau}{Warning : force constants and the "
                        "resulting vibrational frequencies were not computed.}"
                    ))

        ### Excited states
        try:
            et_energies = json["results"]["excited_states"]["et_energies"]
        except KeyError:
            et_energies = []
        rnbExci = len(et_energies)
        if rnbExci != 0 and et_energies != 'N/A':
            with doc.create(Subsection('Excited states')):
                doc.append(NoEscape(r'\begin{center}'))
                with doc.create(Tabular('p{0cm}rrrrrrp{0cm}')) as tableau:
                    row_cells = [
                        MultiColumn(
                            8,
                            align='c',
                            data="Calculated mono-electronic excitations")
                    ]
                    tableau.add_row(row_cells)
                    tableau.add_row([
                        "", "Number", "Energy", "Symmetry",
                        "Oscillator strength", "Rotatory strength",
                        "Transitions", ""
                    ])
                    tableau.add_hline()
                    for i in range(rnbExci):
                        etr_i = (json["results"]["excited_states"]["et_rot"][i]
                                 if json["results"]["excited_states"]["et_rot"]
                                 != 'N/A' else 'N/A')
                        tableau.add_row([
                            "", (1 + i),
                            "%.2f" % et_energies[i],
                            json["results"]["excited_states"]["et_sym"][i],
                            "%.6f" %
                            json["results"]["excited_states"]["et_oscs"][i],
                            etr_i,
                            len(json["results"]["excited_states"]
                                ["et_transitions"][i]), ""
                        ])
                    tableau.add_hline()
                doc.append(NoEscape(r'\end{center}'))

    #####################################################################
    #                                                                   #
    ## 3. compilation LaTeX                                             #
    #                                                                   #
    #####################################################################

    # on compile
    # on previent si le fichier PDF est present ou pas
    # par defaut dans pylatex tout ce qui concerne latex est efface

    ### compile and output

    # doc.generate_pdf(rapFile, clean_tex=True) # comportement en routine, avec False en mode dev/debug
    # OK sans SVG doc.generate_pdf(rapFile, clean_tex=False)
    # pas de chance !! doc.generate_pdf(rapFile, clean_tex=False,compiler="pdflatex  --shell-escape")

    texFile = rapFile + ".tex"
    if (os.path.isfile(texFile)):
        os.remove(texFile)

    pdfFile = rapFile + ".pdf"
    if (os.path.isfile(pdfFile)):
        os.remove(pdfFile)

    doc.generate_tex(rapFile)
    cmd = "pdflatex  --shell-escape " + rapFile

    # si cleanMode = "--clean" on redirige vers /dev/null
    if mode == "clean":
        cmd += " > /dev/null"

    # compilation LaTeX

    os.system(cmd)

    # un peu de nettoyage si cleanMode = "--clean"

    if mode == "clean":
        if os.path.isfile(rapFile + '.aux'):
            os.remove(rapFile + '.aux')
        if os.path.isfile(rapFile + '.log'):
            os.remove(rapFile + '.log')
        if os.path.isfile(rapFile + '.tex'):
            os.remove(rapFile + '.tex')

    # message de fin

    if (os.path.isfile(pdfFile)):
        print('Report file is ' + rapFile + ".pdf")
    else:
        print('Probably a LateX error.')
示例#24
0
#State preamble commands
doc.preamble.append(r'\setcounter{table}{0}')

#Load packages
doc.packages.append(Package('preview', options=['active', 'tightpage',])) #Package to crop pdf to a figure

#Table pre-commands

doc.append(r'\begin{table*}')
doc.append(r'\begin{preview}') 
doc.append(r'{\footnotesize')
doc.append(r'\centering')

#Declare table
with doc.create(Table('l c c c c c c c')) as tab:
    
    row1 = ['Date'  , 'Spectral range',     'Disp.' ,   'R$^a_{\rm{FWHM}}$',    'Spatial res.' ,            'PA',          'Exposure Time' ,  r'{seeing $_{\rm{FWHM}}$}']
    row2 = [' '     , '(\AA\,px$^{-1}$)',   ' ' ,       ' ',                    '("\,px$^{-1}$)' ,         '($ ^{o} $)',   '(sec)' ,         '($"$)']
    row3 = ['2000 February 4' ,             '4779-5199','0.21',                 '$\sim$\,12500'  ,          '0.38'  ,       '50'    ,        '3\,$\cdot$\,1200' , '{1.2}']
    row4 = ['',                             '8363-8763','0.39',                 '$\sim$\,12200'  ,          '0.36'  ,       '50'    ,        '3\,$\cdot$\,1200' , ' ']
    row5 = ['2000 February 5' ,             '4779-5199','0.21',                 '$\sim$\,12500'  ,          '0.38'  ,       '50'    ,        '3\,$\cdot$\,1200' , '{1.2}']
    row6 = ['',                             '8363-8763','0.39',                 '$\sim$\,12200'  ,          '0.36'  ,       '50'    ,        '3\,$\cdot$\,1200' , ' ']
    row7 = MultiRow(7, '|l|', '$^a$R$_{\rm{FWHM}}$\,=\,$\lambda$/$\Delta\lambda_{\rm{FWHM}}$') 
  
    tab.add_hline()
    tab.add_row(row1)
    tab.add_row(row2)
    tab.add_hline()
    tab.add_row(row3)
    tab.add_row(row4)
def build_document(transcript):
    """
    Processes a Transcript object to build a LaTeX document.
    """
    # Open temporary file
    doc = Document(documentclass='scrartcl', title=transcript.title,
                   subtitle=transcript.school,
                   author=transcript.student,
                   date=transcript.date.strftime('%d %B %Y'), temporary=True)

    doc.packages.append(Package('geometry', option='margin=1.0in'))
    doc.preamble.append(Command('renewcommand', argument=['\\familydefault', '\\sfdefault']))

    doc.append(Command('maketitle'))

    # Iterate through each transcript section
    for t_section in transcript.sections:
        # Create new section
        s = Section(escape_latex(t_section.title))
        # Add content to section
        for s_line in t_section.content:
            s_line = '\t'.join(s_line)
            s.append(escape_latex(s_line) + ' \\\n')

        # Add subsections to section
        for t_subsection in t_section.subsections:
            ss = Subsection(escape_latex(t_subsection.title))
            num_cols = max(len(l) for l in t_subsection.content)
            ss_table = Table(' l ' * num_cols)
            # Add content to subsection
            for ss_line in t_subsection.content:

                ss_line = '\t'.join(ss_line)
                if ss_line.startswith('Course Topic'):
                    ss_table.append('&')
                    ss_table.add_multicolumn(num_cols-1, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                elif not ss_line[:3].isupper() and not ss_line.startswith('Test'):
                    ss_table.add_multicolumn(num_cols, 'l', escape_latex(ss_line))
                    ss_table.append(r'\\')
                else:
                    if ss_line.startswith('TERM'):
                        ss_table.add_hline()
                    filled = escape_latex(ss_line).split('\t')
                    filled += (num_cols - len(filled)) * ['']
                    ss_table.add_row(filled)

            ss.append(ss_table)
            s.append(ss)

        doc.append(s)
    doc.generate_pdf(clean=True)

    return doc
示例#26
0
def createFullTable(tableColumns, d_challange, d_pool, d_weighted, filename):
    doc = Document()

    order = [x[0] for x in d_challange]

    # delete unnecessary data

    deleteColumns(d_challange, 4, 6)
    deleteColumns(d_pool, 1, 6)
    #deleteColumns(d_weighted,5,7)

    d_challange = colorTopResults(d_challange)
    d_pool = colorTopResults(d_pool)
    #d_weighted=colorTopResults(d_weighted)

    print d_challange
    print d_pool

    # find top 3 in each column replace 1 with red color, 2 with blue, 3 with red. If there is tie same color
    # should be used

    addBoldLate = lambda x: "\\textbf{" + x + "}"

    with doc.create(Table('|c|c|c|c|c|c|c|c|c|c|')) as table:

        topLine = list()

        table.add_hline()
        topLine.append("Experiment ")
        topLine.append("\multicolumn{3}{ | c |}{Baseline} ")
        topLine.append("\multicolumn{3}{ | c |}{Region pertubation} ")
        topLine.append("\multicolumn{3}{ | c |}{Averaged} ")

        table.add_row(topLine)

        normalizationLine = list()

        table.add_hline()
        normalizationLine.append("Normalization ")
        normalizationLine.append("\multicolumn{3}{ | c |}{sequence - pooled} ")
        normalizationLine.append("\multicolumn{3}{ | c |}{sequence - pooled} ")
        normalizationLine.append("\multicolumn{3}{ | c |}{per - attribute} ")

        table.add_row(normalizationLine)

        # \hline
        # Normalization & \multicolumn
        # {3}
        # { | c |}{sequence - pooled} & \multicolumn
        # {3}
        # { | c |}{sequence - pooled} & \multicolumn
        # {3}
        # { | c |}{per - attribute} \ \
        #         \hline
        table.add_hline()
        header3 = list()

        header3.append('Ranking measure')
        for i in range(0, 3):
            header3.append('A')
            header3.append('R')
            header3.append('Avg.')

        table.add_row(header3)
        table.add_hline()
        table.add_hline()

        for tracker in order:

            line1 = [x for x in d_challange if x[0] == tracker][0]
            line2 = [x for x in d_pool if x[0] == tracker][0]

            tracker = tracker.replace('_', '\_')
            trackerName = tracker
            #table.add_hline()

            row = list()

            row.append(trackerName)

            row = row + line2[1:] + line1[1:]

            # find line corresponding
            table.add_row(row)
        table.add_hline()

    #print table
    a = open(filename, 'wr')
    table.dump(a)
示例#27
0
def latex_table(inner_tabular: str,
                position="H",
                caption=None,
                escape_caption=False,
                label=None,
                output_filepath=None):
    table = Table(position=position)
    table.append(NoEscape(inner_tabular))

    if caption:
        caption_ = caption if escape_caption else NoEscape(caption)
        table.add_caption(caption_)

    if label:
        table.append(NoEscape("\label{{tab:{label}}}".format(label=label)))

    if output_filepath:
        table.generate_tex(output_filepath)

    return table.dumps()
示例#28
0
        df_summary = df[30:].copy()
        df_summary.drop(['snapnum', 'weight', 'sapt_basis'], axis=1, inplace=True)
        df_summary.set_index('Unnamed: 0', drop=True, inplace=True)
        df_summary = df_summary.transpose()

        df_data.to_csv(stub + '_cleaned_data.csv', index=False)
        df_summary.to_csv(stub + '_cleaned_summary.csv')

        doc_summary = Document(stub + '_cleaned_summary')
        doc_summary.packages.append(booktabs)
        doc_summary.packages.append(siunitx)
        # table = Tabular()

        df_table = df_summary.to_latex(
            escape=False,
            header=False,
            column_format=column_format,
        )
        df_table = NoEscape(df_table)

        with doc_summary.create(Table()) as table:
            table.append(df_table)
            # caption = """"""
            # caption = NoEscape(caption)
            # table.add_caption(caption)

        # save just the table source so it can be inserted into the
        # main document
        with open(stub + '_cleaned_summary_table.tex', 'w') as fh:
            fh.write(df_table)
示例#29
0
#!/usr/bin/python3

import numpy as np

from pylatex import Document, Section, Subsection, Table, Math, TikZ, Axis, \
    Plot
from pylatex.numpy import Matrix
from pylatex.utils import italic

doc = Document(filename="multirow")
section = Section('Multirow Test')

test1 = Subsection('Multicol')
test2 = Subsection('Multirow')

table1 = Table('|c|c|')
table1.add_hline()
table1.add_multicolumn(2, '|c|', 'Multicol')
table1.add_hline()
table1.add_row((1, 2))
table1.add_hline()
table1.add_row((3, 4))
table1.add_hline()

table2 = Table('|cc|c|c|')
table2.add_hline()
table2.add_multirow(2, '*', 'Multirow', cells=((1, 2), (3, 4)))
table2.add_hline()

test1.append(table1)
test2.append(table2)
示例#30
0
import numpy as np

from pylatex import Document, Section, Subsection, Table, Math, TikZ, Axis, \
    Plot
from pylatex.numpy import Matrix
from pylatex.utils import italic

doc = Document()
section = Section('Yaay the first section, it can even be ' + italic('italic'))

section.append('Some regular text')

math = Subsection('Math that is incorrect', data=[Math(data=['2*3', '=', 9])])

section.append(math)
table = Table('rc|cl')
table.add_hline()
table.add_row((1, 2, 3, 4))
table.add_hline(1, 2)
table.add_empty_row()
table.add_row((4, 5, 6, 7))

table = Subsection('Table of something', data=[table])

section.append(table)

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

math = Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)])
equation = Subsection('Matrix equation', data=[math])
示例#31
0
import numpy as np

from pylatex import Document, Section, Subsection, Table, Math
from pylatex.numpy import Matrix
from pylatex.utils import italic

doc = Document()
section = Section('Yaay the first section, it can even be ' + italic('italic'))

section.append('Some regular text')

math = Subsection('Math', data=[Math(data=['2*3', '=', 6])])

section.append(math)
table = Table('rc|cl')
table.add_hline()
table.add_row((1, 2, 3, 4))
table.add_hline(1, 2)
table.add_empty_row()
table.add_row((4, 5, 6, 7))

table = Subsection('Table of something', data=[table])

section.append(table)

a = np.array([[100, 10, 20]]).T
M = np.matrix([[2, 3, 4],
               [0, 0, 1],
               [0, 0, 2]])
示例#32
0
def build_document(transcript):
    """
    Processes a Transcript object to build a LaTeX document.
    """
    # Open temporary file
    doc = Document(documentclass='scrartcl',
                   title=transcript.title,
                   subtitle=transcript.school,
                   author=transcript.student,
                   date=transcript.date.strftime('%d %B %Y'),
                   temporary=True)

    doc.packages.append(Package('geometry', option='margin=1.0in'))
    doc.preamble.append(
        Command('renewcommand', argument=['\\familydefault', '\\sfdefault']))

    doc.append(Command('maketitle'))

    # Iterate through each transcript section
    for t_section in transcript.sections:
        # Create new section
        s = Section(escape_latex(t_section.title))
        # Add content to section
        for s_line in t_section.content:
            s_line = '\t'.join(s_line)
            s.append(escape_latex(s_line) + ' \\\n')

        # Add subsections to section
        for t_subsection in t_section.subsections:
            ss = Subsection(escape_latex(t_subsection.title))
            num_cols = max(len(l) for l in t_subsection.content)
            ss_table = Table(' l ' * num_cols)
            # Add content to subsection
            for ss_line in t_subsection.content:

                ss_line = '\t'.join(ss_line)
                if ss_line.startswith('Course Topic'):
                    ss_table.append('&')
                    ss_table.add_multicolumn(num_cols - 1, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                elif not ss_line[:3].isupper() and not ss_line.startswith(
                        'Test'):
                    ss_table.add_multicolumn(num_cols, 'l',
                                             escape_latex(ss_line))
                    ss_table.append(r'\\')
                else:
                    if ss_line.startswith('TERM'):
                        ss_table.add_hline()
                    filled = escape_latex(ss_line).split('\t')
                    filled += (num_cols - len(filled)) * ['']
                    ss_table.add_row(filled)

            ss.append(ss_table)
            s.append(ss)

        doc.append(s)
    doc.generate_pdf(clean=True)

    return doc
示例#33
0
import numpy as np

from pylatex import Document, Section, Subsection, Table, Math, TikZ, Axis, \
    Plot
from pylatex.numpy import Matrix
from pylatex.utils import italic

doc = Document()
section = Section('Yaay the first section, it can even be ' + italic('italic'))

section.append('Some regular text')

math = Subsection('Math that is incorrect', data=[Math(data=['2*3', '=', 9])])

section.append(math)
table = Table('rc|cl')
table.add_hline()
table.add_row((1, 2, 3, 4))
table.add_hline(1, 2)
table.add_empty_row()
table.add_row((4, 5, 6, 7))

table = Subsection('Table of something', data=[table])

section.append(table)

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

from pylatex import Document, Section, Subsection, Table, Math, TikZ, Axis,         Plot
from pylatex.numpy import Matrix
from pylatex.utils import italic

doc = Document()
section = Section('Yaay the first section, it can even be ' + italic('italic'))

section.append('Some regular text')

math = Subsection('Math that is incorrect', data=[Math(data=['2*3', '=', 9])])

section.append(math)
table = Table('rc|cl')
table.add_hline()
table.add_row((1, 2, 3, 4))
table.add_hline(1, 2)
table.add_empty_row()
table.add_row((4, 5, 6, 7))

table = Subsection('Table of something', data=[table])

section.append(table)

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

math = Math(data=[Matrix(M), Matrix(a), '=', Matrix(M*a)])
示例#35
0
    Section,
    Subsection,
    Table,
    MultiColumn,
    MultiRow
)

doc = Document("multirow")
section = Section('Multirow Test')

test1 = Subsection('MultiColumn')
test2 = Subsection('MultiRow')
test3 = Subsection('MultiColumn and MultiRow')
test4 = Subsection('Vext01')

table1 = Table('|c|c|c|c|')
table1.add_hline()
table1.add_row((MultiColumn(4, '|c|', 'Multicolumn'),))
table1.add_hline()
table1.add_row((1, 2, 3, 4))
table1.add_hline()
table1.add_row((5, 6, 7, 8))
table1.add_hline()
row_cells = ('9', MultiColumn(3, '|c|', 'Multicolumn not on left'))
table1.add_row(row_cells)
table1.add_hline()

table2 = Table('|c|c|c|')
table2.add_hline()
table2.add_row((MultiRow(3, '*', 'Multirow'), 1, 2))
table2.add_hline(2, 3)
示例#36
0
    acc_table_UNEM_2Y = ft.create_acc_table(df=spf_bal_UNEM_2Y,
                                            w=w,
                                            proc="multiple",
                                            df_name="spf_bal_UNEM_2Y_" +
                                            str(w))

    # concatenate the tables together
    spf_multitable = pd.concat([
        acc_table_RGDP_1Y, acc_table_RGDP_2Y, acc_table_HICP_1Y,
        acc_table_HICP_2Y, acc_table_UNEM_1Y, acc_table_UNEM_2Y
    ],
                               axis=1,
                               join_axes=[acc_table_RGDP_1Y.index])

    # create table object
    tabl = Table()
    tabl.add_caption(
        "Performance of forecast combinations of ECB SPF forecasts using the training window of the length: "
        + str(w))
    tabl.append(NoEscape('\label{tab: spf_comb_perf_' + str(w) + '}'))
    # create tabular object
    tabr = Tabular(table_spec="c|l" + 6 * "|ccc")
    tabr.add_hline()
    tabr.add_hline()
    # header row
    tabr.add_row(
        (MultiRow(3,
                  data="Class"), MultiRow(3,
                                          data="Forecast Combination Method"),
         MultiColumn(6, align='|c|',
                     data="RGDP"), MultiColumn(6, align='|c|', data="HICP"),