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()
def getLatex(self): data = [] for elem in self.states: data.append(Matrix(elem)) data.append(Command('to')) data.pop() return Math(data=data).dumps()
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)
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()
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)
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)
def transitionMatrix(doc, tM): with doc.create(Subsection('Transitions')): data = ['\setcounter{MaxMatrixCols}{20}', '\Pi='] with doc.create(Alignat(numbering=False, escape=False)) as agn: agn.extend(data) agn.append(Matrix(tM, mtype='b'))
def communicationMatrix(doc, cM): with doc.create(Subsection('Communication Matrix')): data = ['\setcounter{MaxMatrixCols}{20}', 'C='] with doc.create(Alignat(numbering=False, escape=False)) as agn: agn.extend(data) agn.append(Matrix(cM, mtype='b'))
import numpy as np from pylatex import Document, Section, Subsection, Math, Matrix, VectorName if __name__ == '__main__': 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)]) subsection.append(math)
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))])
def draw_matrix(data): M = np.matrix(data['vals']).reshape([data['first_dim'], data['second_dim']]) return Math(data=[Matrix(M)])
def array(lis, **kwargs): return Matrix(np.array(lis), **kwargs)
def generateLatex(phrases, key, result, flag): geometry_options = {"tmargin": "1cm", "lmargin": "3cm", "rmargin": "3cm"} doc = Document(geometry_options=geometry_options) if(flag == "E"): with doc.create(Section('Encyption Input')): doc.append('Text: ' + "".join(phrases) + "\n") doc.append('Key: ' +key) with doc.create(Section("Matrix Mltiplications")): for phrase in phrases: M = createEncryptMatrix(key) messageMatrix = np.array([[getCapitalAlphaMod(phrase[0]),getCapitalAlphaMod(phrase[1]),getCapitalAlphaMod(phrase[2])]]).astype("float64").T doc.append(Math(data=[r'1/' + str(26), Matrix(M), Matrix(messageMatrix), '=', Matrix(getModMatrix(M @ messageMatrix))])) doc.append("\n") doc.append("Encrypted chunk: " + getStringFromMatrix(getModMatrix(M @ messageMatrix))) with doc.create(Section('Encyption Result')): doc.append('Cipher: ' + result) elif(flag == "D"): image_filename = './LookupHill.png' with doc.create(Section('Introduction')): doc.append('In this project, I implement a 3 × 3 Hill Cipher Machine in Python. This machine automatically generates LaTex reports to decipher user-input step by step. \n') doc.append('We will be deciphering: ' + "".join(phrases) + ' using the key: ' + key + '. \n') with doc.create(Section("Enryption Matrix")): with doc.create(Figure(position='h!')) as lookup_hill: lookup_hill.add_image(image_filename, width='120px') lookup_hill.add_caption('Lookup Table of Hill Cipher') doc.append('We use the Lookup Table above to create the Encryption Matrix below. \n') M = createEncryptMatrix(key) doc.append(Math(data=[Matrix(M)])) with doc.create(Section("Encryption Matrix Mod 26 Inverse")): '''iM = np.array([[1.0, 0.0, 0.0], [0.0, 1.0, 0.0], [0.0, 0.0, 1.0]]) E21E31 = iM.copy() E21E31[(1,0)] = -1 * (augM[(1,0)]/augM[(0,0)]) E21E31[(2,0)] = -1 * (augM[(2,0)]/augM[(0,0)]) augM = E21E31.dot(augM) E32 = iM.copy() E32[(2,1)] = -1 * (augM[(2,1)]/augM[(1,1)]) augM = E32.dot(augM) E23E13 = iM.copy() E23E13[(1,2)] = -1 * (augM[(1,2)]/augM[(2,2)]) E23E13[(0,2)] = -1 * (augM[(0,2)]/augM[(2,2)]) augM = E23E13.dot(augM) E12 = iM.copy() E12[(0,1)] = -1 * (augM[(0,1)]/augM[(1,1)]) augM = E12.dot(augM) det = augM[(0,0)] * augM[(1,1)] * augM[(2,2)] if(det == 0 or math.isnan(det)): raise ValueError("Matrix Non-Invertible") #print("Det: " + str(det)) if(egcd(int(round(det)), 26)[0] != 1): raise ValueError("Key Matrix determinent not co-prime with 26") #print("Mod inv of det: " + str(modinv(det, 26))) D = iM.copy() D[(0,0)] = 1/augM[(0,0)] D[(1,1)] = 1/augM[(1,1)] D[(2,2)] = 1/augM[(2,2)] augM = D.dot(augM) #Here are the additional steps needed to find the modular inverse of a matrix augM = augM * det augM = augM * modinv(int(round(det)), 26) modAugM = getModMatrix(augM[0:, 3:]) return modAugM''' invMat = gaussianInverseMod26(createEncryptMatrixAug(key)) doc.append(Math(data=[Matrix(invMat)])) doc.append("\n") with doc.create(Section("Matrix Multiplications")): for phrase in phrases: M = invMat #print(M) messageMatrix = np.array([[getCapitalAlphaMod(phrase[0]),getCapitalAlphaMod(phrase[1]),getCapitalAlphaMod(phrase[2])]]).astype("float64").T doc.append(Math(data=[Matrix(M), Matrix(messageMatrix), '=', Matrix(getModMatrix(M @ messageMatrix))])) doc.append("\n") doc.append("Decrypted chunk: " + getStringFromMatrix(getModMatrix(M @ messageMatrix))) with doc.create(Section('Decryption Result')): doc.append('Plaintext: ' + result) doc.generate_pdf('full', clean_tex=False) subprocess.call(['open', 'full.pdf'])
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)
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)])
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('Beautiful graphs')): with doc.create(TikZ()): plot_options = 'height=6cm, width=6cm, grid=major' with doc.create(Axis(options=plot_options)) as plot: plot.append(Plot(name='model', func='-x^5 - 242')) coordinates = [ (-4.77778, 2027.60977), (-3.55556, 347.84069), (-2.33333, 22.58953), (-1.11111, -493.50066), (0.11111, 46.66082), (1.33333, -205.56286), (2.55556, -341.40638),
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))])
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),
def update(self, i): i = int(i) self.parent.matrix = np.array( (self.parent.i_vector, self.parent.j_vector, self.parent.k_vector)).T self.parent.plus_matrix = np.array( (self.parent.i_plus_vector, self.parent.j_plus_vector, self.parent.k_plus_vector)).T if self.canvasFigure != None: try: self.parent.quiver.remove() self.parent.plus_quiver.remove() except: print("do nothing") self.parent.matrix = (1 - self.parent.sigmoid(i)) * np.array( (self.parent.i_origin, self.parent.j_origin, self.parent. k_origin)) + self.parent.sigmoid(i) * self.parent.matrix self.parent.plus_matrix = (1 - self.parent.sigmoid(i)) * np.array( (self.parent.i_origin, self.parent.j_origin, self.parent. k_origin)) + self.parent.sigmoid(i) * self.parent.plus_matrix else: self.parent.matrix = np.array( (self.parent.i_origin, self.parent.j_origin, self.parent.k_origin)) + self.parent.matrix self.parent.plus_matrix = np.array( (self.parent.i_origin, self.parent.j_origin, self.parent.k_origin)) + self.parent.plus_matrix # Compute a matrix that is in the middle between the full transformation matrix and the identity self.parent.vector_location = np.array( (self.parent.matrix.dot(self.parent.i_origin), self.parent.matrix.dot(self.parent.j_origin), self.parent.matrix.dot(self.parent.k_origin))).T self.parent.quiver = self.parent.ax.quiver( 0, 0, 0, self.parent.vector_location[0], self.parent.vector_location[1], self.parent.vector_location[2], length=1, color='r', arrow_length_ratio=0.1) self.parent.plus_vector_location = np.array( (self.parent.plus_matrix.dot(self.parent.i_origin), self.parent.plus_matrix.dot(self.parent.j_origin), self.parent.plus_matrix.dot(self.parent.k_origin))).T self.parent.plus_quiver = self.parent.ax.quiver( 0, 0, 0, self.parent.plus_vector_location[0], self.parent.plus_vector_location[1], self.parent.plus_vector_location[2], length=1, color='y', arrow_length_ratio=0.1) # Set vector location - must transpose since we need U and V representing x and y components # of each vector respectively (without transposing, e ach column represents each unit vector) self.parent.transform = np.array( [self.parent.matrix.dot(k) for k in self.parent.x]) #ax.view_init((1 - self.parent.sigmoid(i)) * elevation, (1 - self.parent.sigmoid(i)) * angle) if self.canvasFigure != None: self.parent.scat._offsets3d = [ self.parent.transform[:, 0], self.parent.transform[:, 1], self.parent.transform[:, 2] ] self.canvasFigure.draw() a = self.parent.plus_vector_location #with pylatex.config.active.change(indent=False): doc = Document() doc.packages.append( Package('geometry', options=['paperwidth=6in', 'paperheight=2.5in'])) section = Section('Linear Combination') subsection = Subsection('Using the dot product') V1 = np.transpose(np.array([[1, 1]])) M1 = np.array((self.parent.i_vector, self.parent.j_vector)).T math = Math(data=[ Matrix(M1), 'dot', Matrix(V1), '=', Matrix(np.dot(M1, V1)) ]) subsection.append(math) section.append(subsection) subsection = Subsection('Using vector addition') V1 = np.array([self.parent.i_vector]) V2 = np.array([self.parent.j_vector]) math = Math( data=[Matrix(V1), '+', Matrix(V2), '=', Matrix(V1 + V2)]) subsection.append(math) section.append(subsection) #doc.append(section) ''' subsection = Subsection('Product') math = Math(data=['M', vec_name, '=', Matrix(M * a)]) subsection.append(math) section.append(subsection) doc.append(section) ''' doc.append(section) latex = doc.dumps_as_content() print(latex) self.strvar.set(latex) #self.strvar.set("\prod_{p\,\mathrm{prime}}\\frac1{1-p^{-s}} = \sum_{n=1}^\infty \\frac1{n^s}") self.on_latex()