Ejemplo n.º 1
0
def mostrarCorridas(corridas, doc):
    with doc.create(Subsection('Prueba de Corridas')):
        doc.append(Math(data=['corridas', '=', corridas[0]]))
        doc.append(Math(data=['E(h)', '=', corridas[1]]))
        doc.append(Math(data=['S(h)2', '=', corridas[2]]))
        doc.append(Math(data=['S(h)', '=', corridas[3]]))
        doc.append(Math(data=['Z(0)', '=', corridas[4]]))
Ejemplo n.º 2
0
def mostrarSeries(series, doc):
    with doc.create(Subsection('Prueba de Series')):
        n = pruebasRandom.sumarLista(series)
        frecuenciaEsperada = n / 25
        jiCuadrado = 0.0

        with doc.create(Tabular('|c|c|c|c|c|c|')) as table:
            table.add_row(
                ('Celda', 'Fo', 'Fe', '(Fo-Fe)', '(Fo-Fe)2', '(Fo-Fe)2/Fe'))

            for i in range(25):
                frecuenciaObs = series[i]
                fObs_fEsp = frecuenciaObs - frecuenciaEsperada
                fObs_fEsp2 = fObs_fEsp**2

                formula = fObs_fEsp2 / frecuenciaEsperada

                fila = (i + 1, frecuenciaObs, frecuenciaEsperada, fObs_fEsp,
                        fObs_fEsp2, formula)

                table.add_hline()
                table.add_row(fila)

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

    doc.append(Math(data=['Total', '=', (int)(n)]))
    doc.append(Math(data=['X2(0)', '=', jiCuadrado]))
Ejemplo n.º 3
0
def mostrarPoker(poker, doc):
    with doc.create(Subsection('Prueba de Poker')):
        nombrePoker = [
            "Diferentes", "Un Par", "Dos Pares", "Tercia", "Full House",
            "Poker", "Quintilla"
        ]
        promedio = [0.3024, 0.504, 0.108, 0.072, 0.009, 0.0045, 0.0001]
        total = pruebasRandom.sumarPoker(poker)
        jiCuadrado = 0.0

        with doc.create(Tabular('|c|c|c|c|c|c|c|')) as table:
            table.add_row(('Clase', 'Pe', 'Fo', 'Fe', '(Fo-Fe)', '(Fo-Fe)2',
                           '(Fo-Fe)2/Fe'))
            for i in range(7):
                prom = promedio[i]
                frecuenciaObs = poker[i][1]
                frecuenciaEsperada = prom * total
                fObs_fEsp = frecuenciaObs - frecuenciaEsperada
                fObs_fEsp2 = fObs_fEsp**2
                formula = fObs_fEsp2 / frecuenciaEsperada

                fila = (nombrePoker[i], prom, frecuenciaObs,
                        frecuenciaEsperada, fObs_fEsp, fObs_fEsp2, formula)

                table.add_hline()
                table.add_row(fila)

                jiCuadrado += formula

        doc.append(Math(data=['Total', '=', total]))
        doc.append(Math(data=['X2(0)', '=', jiCuadrado]))
Ejemplo n.º 4
0
    def gen_smpl(self, idx, n_digits, n_nums, var_digits=0):
        """ generate an example of a simple addition 
        """
        assert (n_digits >= 1)
        assert (var_digits < n_digits)
        q_tab = Tabular(' c r ', row_height=1.2)

        # contents...
        nums = [gen_rnd(n_digits, var_digits) for n in range(0, n_nums)]
        sgns = [sign(randint(-1000000, 1000000)) for n in range(0, n_nums)]

        sign_syms = list(map(lambda x: '+' if x == 1 else '-', sgns))

        sum_str = ''.join(
            [sign_syms[n] + str(nums[n]) for n in range(0, n_nums)])
        if sum_str[0] == '+':
            sum_str = sum_str[1:]  # tail if leading with a '+'

        mth = Math(escape=False, inline=True)
        mth.append(NoEscape(sum_str + '='))
        q_tab.add_row((bold(str(idx) + ':'), mth))

        a_tab = Tabular(' l l ', row_height=1.1)
        a_idx = bold(str(idx) + ":")
        res = sum(multiply(nums, sgns))
        a_tab.add_row((a_idx, res))

        #print(sum_str, '=', res)
        return (q_tab, a_tab)
Ejemplo n.º 5
0
def complexStuff(doc):
    with doc.create(Section('The simple stuff')):
        doc.append('Some regular text and some')
        doc.append(italic('italic text. '))
        doc.append('\nAlso some crazy characters: $&#{}')
        with doc.create(Subsection('Math that is incorrect')):
            doc.append(Math(data=['2*3', '=', 9]))

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

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

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

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

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

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

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

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

    doc.generate_pdf('full', clean_tex=False)
Ejemplo n.º 6
0
 def gen_smpl(self, idx, n_digits, n_nums, var_digits=0):
     """ generate an example of a simple addition 
     """
     assert (n_digits >= 1)
     assert (var_digits < n_digits)
     q_tab = Tabular(' c r ', row_height=1.2)
     nums = [gen_rnd(n_digits, var_digits) for n in range(0, n_nums)]
     sum_str = functools.reduce(lambda x, y: str(x) + '-' + str(y), nums)
     mth = Math(escape=False, inline=True)
     mth.append(NoEscape(sum_str + '='))
     q_tab.add_row((bold(str(idx) + ':'), mth))
     a_tab = Tabular(' l l ', row_height=1.1)
     a_idx = bold(str(idx) + ":")
     a_tab.add_row((a_idx, nums[0] - sum(nums[1:])))
     return (q_tab, a_tab)
Ejemplo n.º 7
0
 def getLatex(self):
     data = []
     for elem in self.states:
         data.append(Matrix(elem))
         data.append(Command('to'))
     data.pop()
     return Math(data=data).dumps()
Ejemplo n.º 8
0
def test_math():
    Math(data=None, inline=False)

    VectorName(name='')

    # Numpy
    m = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]])

    Matrix(matrix=m, name='', mtype='p', alignment=None)
Ejemplo n.º 9
0
def display(ap, doc):
    properties, effects = analyze(ap)
    with doc.create(Subsection(ap['name'])):
        doc.append('Definition:')
        with doc.create(Itemize(options='noitemsep')) as itemize:
            if 'url' in ap:
                itemize.add_item('url: {}'.format(ap['url']))
            itemize.add_item('floor: {}'.format(ap['floor']))
            itemize.add_item('starting price: {:.2f} Mkr'.format(
                ap['startPrice'] / 1e6))
            if 'booliEstimate' in ap:
                itemize.add_item('Booli estimated price: {:.2f} Mkr'.format(
                    ap['booliEstimate'] / 1e6))
            itemize.add_item('fee: {:.0f} kr/month'.format(ap['fee']))
            ma = Math(inline=True, escape=False)
            ma.append('\\text{{area: }} {:.0f}\\,\\mathrm{{m}}^2'.format(
                ap['area']))
            itemize.add_item(ma)
            itemize.add_item(
                'commute time: {:.0f} min of which {:.0f} min is walking. Frequency every {:.0f} min.'
                .format(ap['commuteTime'], ap['commuteWalkTime'],
                        ap['commutePeriod']))

        doc.append('Results:')
        with doc.create(Itemize(options='noitemsep')) as itemize:
            itemize.add_item('interest: {:.1%}'.format(properties['interest']))
            itemize.add_item('amortization: {:.1%}'.format(
                properties['amortization']))
            itemize.add_item(
                'monthly cost: {a:.0f} kr/month (incl. amortization)'.format(
                    a=properties['monthlyCost']))
        # print('m2 price: {p:.0f}% of local market value'.format(p=100*ap['price']/(ap['area']*m2Price[ap['location']])))
        # print('Effective commute time: ',effectiveCommuteTime,' min')
        # print('Monthly apartment bill:',monthlyPrice)
        doc.append('Value breakdown:\n')
        with doc.create(Center()) as centered:
            with centered.create(Tabular('l|r')) as table:
                tot = 0
                for e in effects:
                    table.add_row((e, '{p}{v:.0f} kr/month'.format(
                        k=e, v=effects[e], p='+' if effects[e] > 0 else '')))
                    tot += effects[e]
                table.add_hline()
                table.add_row(('TOTAL', '{t:.0f} kr/month'.format(t=tot)))
Ejemplo n.º 10
0
Archivo: expimp.py Proyecto: xpt3/pyENL
def sols2tex(variables, file_name, user_input, autor):
    '''
    Soluciones a documento TeX
    '''
    from pylatex import Document, Section, Subsection, Command, Math, Tabular
    from pylatex.utils import italic, NoEscape
    doc = Document()
    doc.preamble.append(Command('title', 'Reporte pyENL'))
    doc.preamble.append(Command('author', autor))
    doc.preamble.append(Command('date', NoEscape(r'\today')))
    doc.append(NoEscape(r'\maketitle'))

    with doc.create(Section('Ecuaciones:')):
        # Por cada línea de user_input añadir un append y salto de línea
        #(si es comentario de usuario)
        comentario_user = False
        for eqn in user_input:
            if '<<' in eqn:
                # Entonces es un comentario de usuario
                comentario = eqn
                comentario = comentario.replace('<<', '')
                comentario = comentario.replace('>>', '')
                if comentario_user == True:
                    doc.append('\n' + comentario)
                else:
                    # Esto porque no hay necesidad de salto.
                    doc.append(comentario)
                comentario_user = True
            else:
                # Entonces no es un comentario sino una ecuación, entonces
                # insertar con símbolos matemáticos.
                doc.append(Math(data=[eqn]))
                comentario_user = False

    # Ahora insertar los resultados
    with doc.create(Section('Resultados:')):
        # Acá viene una tabla con los resultados.
        with doc.create(Tabular('rc|cl')) as table:
            table.add_hline()
            table.add_row(('Variable', 'Valor', 'Descripción', 'Unidades'))
            table.add_hline(1, 4)
            table.add_empty_row()
            # Ahora por cada variable añadir la información requerida:
            for variable in variables:
                t_var = variable.name  # Nombre variable
                t_val = variable.guess  # Valor de la variable
                t_desc = variable.comment  # Descripción de la variable
                t_unit = variable.units  # Unidades de la variable
                table.add_row((t_var, t_val, t_desc, t_unit))
            #table.add_row(('x', 5, 'Hola', 'm'))

    if file_name[-4::] == '.pdf':
        doc.generate_pdf(file_name[0:-4])
    else:
        doc.generate_tex(file_name[0:-4])
Ejemplo n.º 11
0
def de_formula(s: env.Formula):
    code = [de_line(c) for c in s.children]

    data = []
    for line in code:
        line = re.sub(chchar, lambda x: r"\text{{{}}}".format(x.group(1)),
                      line)
        data.append(NoEscape("{}\\\\".format(line)))

    m = Math(data=data)
    return m
Ejemplo n.º 12
0
    def fromFormula(self, s: Formula):
        code = [self.fromRawLine(c) for c in s.formula]

        data = []
        for line in code:
            data.append(NoEscape(f"{line}\\\\"))

        m = Math(data=data)
        # eq = Equation()
        # for line in code:
        #     eq.append(line)
        return m
Ejemplo n.º 13
0
def test_math():
    math = Math(data=None, inline=False)
    repr(math)

    vec = VectorName(name='')
    repr(vec)

    # Numpy
    m = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]])

    matrix = Matrix(matrix=m, mtype='p', alignment=None)
    repr(matrix)
Ejemplo n.º 14
0
def mostrarDigitos(digitos, doc):
    with doc.create(Subsection('Prueba de Huecos Digitos')):
        jiCuadrado = 0.0
        total = pruebasRandom.sumarTablas(digitos, 20, 10, True)
        sumaTemporal = 0
        frecuenciaTemporal = 0.0

        tablaDigitos = Tabular('|c|c|c|c|c|c|c|')
        tablaDigitos.add_row(
            ('Huecos', 'Pe', 'Fo', 'Fe', '(Fo-Fe)', '(Fo-Fe)2', '(Fo-Fe)2/Fe'))
        for i in range(21):
            if (i != 20):
                promedio = 0.1 * (0.9)**i
                frecuenciaObs = digitos[i][10]
                frecuenciaTemporal = frecuenciaObs
                sumaTemporal += frecuenciaObs

            else:
                promedio = (0.9)**i
                sumaTemporal += digitos[i][10]
                frecuenciaObs = digitos[i][10]
                frecuenciaTemporal = total - sumaTemporal
                frecuenciaTemporal += digitos[i][10]

            frecuenciaEsperada = promedio * total
            fObs_fEsp = frecuenciaTemporal - frecuenciaEsperada
            fObs_fEsp2 = fObs_fEsp**2
            formula = fObs_fEsp2 / frecuenciaEsperada

            fila = (i, promedio, frecuenciaObs, frecuenciaEsperada, fObs_fEsp,
                    fObs_fEsp2, formula)

            tablaDigitos.add_hline()
            tablaDigitos.add_row(fila)

            jiCuadrado += formula
        doc.append(tablaDigitos)
        doc.append(Math(data=['Total', '=', total]))
        doc.append(Math(data=['X2(0)', '=', jiCuadrado]))
Ejemplo n.º 15
0
def mostrarNumeros(archivo, doc):
    with doc.create(Subsection("Prueba con Numeros")):
        intervalo = [[0.0, 0.1], [0.1, 0.25], [0.25, 0.45], [0.45, 0.7],
                     [0.7, 1]]
        numeros = pruebasRandom.obtenerRandom(archivo, intervalo)
        jiCuadrado = 0.0

        for i in range(5):
            with doc.create(Tabular('|c|c|c|c|c|c|c|')) as table:
                table.add_row(('Huecos', 'Pe', 'Fo', 'Fe', '(Fo-Fe)',
                               '(Fo-Fe)2', '(Fo-Fe)2/Fe'))

                t = intervalo[i][1] - intervalo[i][0]
                jiCuadrado = 0.0
                total = numeros[21][i]

                for j in range(21):
                    if (j != 20):
                        promedio = t * (1 - t)**j
                    else:
                        promedio = (1 - t)**j
                    frecuenciaObs = numeros[j][i]
                    frecuenciaEsperada = promedio * total
                    fObs_fEsp = frecuenciaObs - frecuenciaEsperada
                    fObs_fEsp2 = fObs_fEsp**2
                    formula = fObs_fEsp2 / frecuenciaEsperada

                    fila = (j, promedio, frecuenciaObs, frecuenciaEsperada,
                            fObs_fEsp, fObs_fEsp2, formula)

                    jiCuadrado += formula
                    table.add_hline()
                    table.add_row(fila)

            doc.append(Math(data=['Intervalo', '=', intervalo[i]]))
            doc.append(Math(data=['X2(0)', '=', jiCuadrado]))
Ejemplo n.º 16
0
 def getEquivalent(self):
     left = []
     right = []
     for elem in self.elementary:
         if(elem[0] == 'l'):
             left.append(elem[1])
         else:
             right.append(elem[1])
     leftWritable = reversed(left)
     data = []
     for mat in leftWritable:
         data.append(Matrix(mat))
     data.append(Matrix(self.states[0]))
     for mat in right:
         data.append(Matrix(mat))
     return Math(data=data).dumps()
Ejemplo n.º 17
0
Archivo: latex.py Proyecto: Axlii/latex
def generatepdf(text):
    doc = Document('basic')
    textsplit = text.split('\n')

    with doc.create(Section(textsplit[0])):
        for i, line in enumerate(textsplit[1:]):
            print("LINE (" + str(i) + "): " + line)
            if len(line) == 0:
                continue

            if "=" in line:
                math = Math(data=[line])
                doc.append(math)
            else:
                doc.append(line + "\n")

    doc.generate_pdf('output/document', clean_tex=False)
Ejemplo n.º 18
0
 def getEquivalentTruncated(self):
     left = []
     right = []
     print(self.elementary)
     for elem in self.elementary:
         if(elem[0] == 'l'):
             left.append(elem[1])
         else:
             right.append(elem[1])
     leftWritable = reversed(left)
     rows, cols = self.matrix.shape
     leftMat = np.identity(rows)
     rightMat = np.identity(cols)
     for mat in leftWritable:
         leftMat = np.matmul(leftMat, mat)
     for mat in right:
         rightMat = np.matmul(rightMat, mat)
     data = [Matrix(leftMat), Matrix(self.states[0]), Matrix(rightMat)]
     print(left)
     return Math(data=data).dumps()
Ejemplo n.º 19
0
def GEPP(A, b):

    section = Section('The first section')
    
    n =  len(A)
    if b.size != n:
        raise ValueError("Invalid argument: incompatible sizes between A & b.", b.size, n)
    for k in range(n-1):
        section.append("Considering Column " + (str)(k+1))

        #Choose largest pivot element below (and including) k
        maxindex = abs(A[k:,k]).argmax() + k
        if A[maxindex, k] == 0:
            raise ValueError("Matrix is singular.")
        #Swap rows
        if maxindex != k:
            A[[k,maxindex]] = A[[maxindex, k]]
            b[[k,maxindex]] = b[[maxindex, k]]
        for row in range(k+1, n):
            
            section.append(italic("Row" +(str)(row+1)))
            section.append(Subsection('\t', data=[Math(data=["\tmultiplier", '=', A[row][k], " / ", A[k][k]])]))

            multiplier = A[row][k]/A[k][k]
            multiplier = round(multiplier,2)
            section.append(Math(data=["\t\tmultiplier", '=', multiplier]))
            section.append("\n")
            #the only one in this column since the rest are zero
            section.append("\tapplying multiplier to the row")
            section.append(Math(data=[
                NoEscape("\t\tr_"+(str)(row+1))," - ", multiplier,NoEscape("r_"+(str)(k+1))
            ]))

            for col in range(k, n):
                section.append(Math(data=["\t\t", A[row][col]," - (", multiplier, " x ", A[k][col], ")"]))
                A[row][col] = A[row][col] - multiplier * A[k][col]
                section.append(Math(data=["\t\t\t = ", A[row][col]]))
            #Equation solution column
            b[row] = b[row] - multiplier*b[k]
            section.append(Math(data=["\t\t", b[row]," - (", multiplier, " x ", b[k], ")"]))
            b[row] = b[row] - multiplier * b[k]
            section.append(Math(data=['=', b[row]]))

            section.append(Math(data=['A', '=', Matrix(A)]))
            section.append(Math(data=['b', '=', b]))
            section.append("\n")
    
    section.append("Performing back substitution")
    x = np.zeros(n)
    k = n-1
    x[k] = b[k]/A[k,k]

    section.append(Math(data=[NoEscape("\tr_"+(str)(k+1)),"=", b[k], " / ", A[k,k]]))
    x[k] = round(b[k]/A[k,k],2)
    section.append(Math(data=["\t\t= ", x[k]]))

    k-=1

    while k >= 0:
        eqn = [NoEscape("\tr_"+(str)(k+1)),"=", b[k], " - "]
        eqn.extend(print_dot(A[k,k+1:],x[k+1:]))
        eqn.extend([" / ", A[k,k]])
        section.append(Math(data=eqn))

        x[k] = (b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k]
        section.append(Math(data=["\t\t= ", x[k]]))
        k = k-1
    return x
Ejemplo n.º 20
0
    def wind_report(self, wind_beam, wind_pier):
        """添加风荷载计算内容"""

        self.wind = wind_beam.wind

        t1 = f'''桥梁抗风风险区域:R{self.wind.R}\n
        桥位地表分类:{self.wind.surface_class}\n
        十年重现期风作用水平:W1={self.wind.W1:.3f} m/s\n
        百年重现期风作用水平:W2={self.wind.W2:.3f} m/s
        '''
        t2 = '根据规范4.1可得,基本风速值为'
        m1 = [f'U_{{10}}={self.wind.W2:.3f}', '\\,m/s']

        t3 = '根据规范4.2.1可得,地表相关参数为'
        m2 = [
            f'\\alpha_0={self.wind.alpha0:.2f}', '\\quad',
            f'z_0={self.wind.z0:.2f}'
        ]

        t5 = '根据规范4.2.4可得,桥梁设计基本风速为'
        m4 = [
            'U_{s10}=k_cU_{10}=',
            f'{self.wind.kc:.3f}\\times{self.wind.U10:.3f}={self.wind.Us10:.3f}',
            '\\,m/s'
        ]

        t4 = '根据规范4.2.2可得,主梁基准高度为'
        m3 = [f'Z={wind_beam.z:.2f}', '\\,m']

        t6 = '根据规范4.2.6可得,主梁构件基准高度处的设计基准风速为'
        m5 = [
            'U_d=k_f\\left(\\frac{Z}{10}\\right)^{\\alpha_0}U_{s10}=',
            f'{self.wind.kf:.2f}\\times\\left(\\frac{{{wind_beam.z:.2f}}}{{10}}\\right)^{{{self.wind.alpha0:.2f}}}\\times{self.wind.Us10:.3f}=',
            f'{wind_beam.Ud:.3f}', '\\,m/s'
        ]

        # t7 = '根据规范4.2.9可得,施工阶段的设计风速为'
        # m6 = ['U_{sd}=k_{sf}U_{d}=', f'{self.wind.ksf}']

        t8 = '根据规范5.2.1可得,等效静阵风风速为'
        m7 = [
            'U_g=G_VU_d=',
            f'{wind_beam.GV:.2f}\\times{wind_beam.Ud:.3f}={wind_beam.Ug:.3f}',
            '\\,m/s'
        ]

        t9 = '根据规范5.3.1可得,横桥向风作用下主梁单位长度上的顺风向等效静阵风荷载为'
        m8 = [
            'F_g=\\frac{1}{2}\\rho U_g^2C_HD=',
            f'0.5\\times{wind_beam.rho:.2f}\\times{wind_beam.Ug:.3f}^2\\times{wind_beam.CH:.3f}\\times{wind_beam.D:.3f}=',
            f'{wind_beam.Fg:.3f}', '\\,N/m'
        ]

        with self.doc.create(Section('地质基本情况')):
            self.doc.append(NoEscape(t1))
        with self.doc.create(Section('风速参数')):
            self.doc.append(t2)
            self.doc.append(Math(data=m1, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t3)
            self.doc.append(Math(data=m2, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t5)
            self.doc.append(Math(data=m4, escape=False))
        with self.doc.create(Section('主梁风荷载')):
            self.doc.append(t4)
            self.doc.append(Math(data=m3, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t6)
            self.doc.append(Math(data=m5, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t8)
            self.doc.append(Math(data=m7, escape=False))
            self.doc.append(NoEscape('\n'))
            self.doc.append(t9)
            self.doc.append(Math(data=m8, escape=False))
Ejemplo n.º 21
0
def GENP(A, b):
    
    section = Section('The first section')

    n =  len(A)
    if b.size != n:
        raise ValueError("Invalid argument: incompatible sizes between A & b.", b.size, n)
    for pivot_row in range(n-1):
        section.append("Considering Column " + (str)(pivot_row+1))

        for row in range(pivot_row+1, n):
            section.append(italic("Row" +(str)(row+1)))
            section.append(Subsection('\t', data=[Math(data=["\tmultiplier", '=', A[row][pivot_row], " / ", A[pivot_row][pivot_row]])]))

            multiplier = A[row][pivot_row]/A[pivot_row][pivot_row]
            multiplier = round(multiplier,2)
            section.append(Math(data=["\t\tmultiplier", '=', multiplier]))
            section.append("\n")
            #the only one in this column since the rest are zero
            section.append("\tapplying multiplier to the row")
            section.append(Math(data=[
                NoEscape("\t\tr_"+(str)(row+1))," - ", multiplier,NoEscape("r_"+(str)(pivot_row+1))
            ]))

            for col in range(pivot_row, n):
                section.append(Math(data=["\t\t", A[row][col]," - (", multiplier, " x ", A[pivot_row][col], ")"]))
                A[row][col] = A[row][col] - multiplier * A[pivot_row][col]
                section.append(Math(data=["\t\t\t = ", A[row][col]]))
            #Equation solution column
            section.append(Math(data=["\t\t", b[row]," - (", multiplier, " x ", b[pivot_row], ")"]))
            b[row] = b[row] - multiplier * b[pivot_row]
            section.append(Subsection('\t\t\t', data=[Math(data=['=', b[row]])]))

            section.append(Math(data=['A', '=', Matrix(A)]))
            section.append(Math(data=['b', '=', b]))
            section.append("\n")

    section.append("Performing back substitution")
    x = np.zeros(n)
    k = n-1

    section.append(Math(data=[NoEscape("\tr_"+(str)(k+1)),"=", b[k], " / ", A[k,k]]))
    x[k] = round(b[k]/A[k,k],2)
    section.append(Math(data=["\t\t= ", x[k]]))

    k-=1

    while k >= 0:
        eqn = [NoEscape("\tr_"+(str)(k+1)),"=", b[k], " - "]
        eqn.extend(print_dot(A[k,k+1:],x[k+1:]))
        eqn.extend([" / ", A[k,k]])
        section.append(Math(data=eqn))

        x[k] = round((b[k] - np.dot(A[k,k+1:],x[k+1:]))/A[k,k],2)
        section.append(Math(data=["\t\t= ", x[k]]))
        k = k-1

    return section
Ejemplo n.º 22
0
def details():
    if __name__ == '__main__':


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

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

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

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

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

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

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

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

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

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

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

        doc.generate_pdf('full', clean_tex=False)
Ejemplo n.º 23
0
    def pile_report(self, pile, pile2, F, factor=1.25):
        """添加桩基长度计算内容"""

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

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

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

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

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

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

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

import numpy as np

from pylatex import Document, Section, Subsection, Math
from pylatex.numpy import Matrix, VectorName

a = np.array([[100, 10, 20]]).T

doc = Document()
section = Section('Numpy tests')
subsection = Subsection('Array')

vec = Matrix(a)
vec_name = VectorName('a')
math = Math(data=[vec_name, '=', vec])

subsection.append(math)
section.append(subsection)

subsection = Subsection('Matrix')
M = np.matrix([[2, 3, 4], [0, 0, 1], [0, 0, 2]])
matrix = Matrix(M, mtype='b')
math = Math(data=['M=', matrix])

subsection.append(math)
section.append(subsection)

subsection = Subsection('Product')

math = Math(data=['M', vec_name, '=', Matrix(M * a)])
Ejemplo n.º 25
0
if __name__ == '__main__':
    doc = Document()
    section = Section('Quantity tests')

    subsection = Subsection('Scalars with units')
    G = pq.constants.Newtonian_constant_of_gravitation
    moon_earth_distance = 384400 * pq.km
    moon_mass = 7.34767309e22 * pq.kg
    earth_mass = 5.972e24 * pq.kg
    moon_earth_force = G * moon_mass * earth_mass / moon_earth_distance**2
    q1 = Quantity(moon_earth_force.rescale(pq.newton),
                  options={
                      'round-precision': 4,
                      'round-mode': 'figures'
                  })
    math = Math(data=['F=', q1])
    subsection.append(math)
    section.append(subsection)

    subsection = Subsection('Scalars without units')
    world_population = 7400219037
    N = Quantity(world_population,
                 options={
                     'round-precision': 2,
                     'round-mode': 'figures'
                 },
                 format_cb="{0:23.17e}".format)
    subsection.append(Math(data=['N=', N]))
    section.append(subsection)

    subsection = Subsection('Scalars with uncertainties')
Ejemplo n.º 26
0
def draw_random_matrix(data):
    M = np.random.randint(1, 99, size=(data.get('first_dim'), data.get('second_dim')))
    return Math(data=[Matrix(M)])
Ejemplo n.º 27
0
def draw_random_multiply_matrix(data):
    M1 = np.random.randint(1, 99, size=(data.get('first_dim'), data.get('second_dim')))
    M2 = np.random.randint(1, 99, size=(data.get('second_dim'), data.get('third_dim')))
    return Math(data=[Matrix(M1), Matrix(M2), '=', Matrix(M1.dot(M2))])
Ejemplo n.º 28
0
def draw_inverse_matrix(data):
    M = np.matrix(data['vals']).reshape([data['first_dim'], data['second_dim']])
    return Math(data=['inv', Matrix(M), '=', Matrix(np.linalg.pinv(M))])
Ejemplo n.º 29
0
    Plot, Figure, Matrix, Alignat
from pylatex.utils import italic
import os

if __name__ == '__main__':
    image_filename = os.path.join(os.path.dirname(__file__), 'gatito.jpg')

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

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

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

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

    with doc.create(Section('The fancy stuff')):
        with doc.create(Subsection('Correct matrix equations')):
            doc.append(Math(data=[Matrix(M), Matrix(a), '=', Matrix(M * a)]))
Ejemplo n.º 30
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()