def test_none(): m = [[1, None, None], [2, 2, 1], [2, 1, 2]] t = matrix2latex(m) assertEqual(t, "none") m2 = [[1, float('NaN'), float('NaN')], [2, 2, 1], [2, 1, 2]] t2 = matrix2latex(m) assertEqual(t2, "none") t3 = matrix2latex(m, format='$%d$') assertEqual(t3, "none")
def test_none(): m = [[1,None,None], [2,2,1], [2,1,2]] t = matrix2latex(m) assertEqual(t, "none") m2 = [[1,float('NaN'),float('NaN')], [2,2,1], [2,1,2]] t2 = matrix2latex(m) assertEqual(t2, "none") t3 = matrix2latex(m, format='$%d$') assertEqual(t3, "none")
def test_pandas_columns(): try: import pandas as pd import numpy as np d = {'one' : pd.Series([1., 2., 3.], index=['a', 'b', 'c']), 'two' : pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd'])} df = pd.DataFrame(d) t = matrix2latex(df) # print 'pandas', t, df.to_records() assertEqual(t, "pandas_columns") t = matrix2latex(df, headerRow=None, headerColumn=None) assertEqual(t, "pandas_columns_noHeaders") except ImportError: pass
def test_pandas_series(): try: import pandas as pd import numpy as np s = pd.Series([2, 4, 2, 42, 5], index=['a', 'b', 'c', 'd', 'e']) # print 'PANDAS\n', s # print 'PANDAS\n', s.to_dict(), s.tolist(), hasattr(s, 'to_dict') t = matrix2latex(s) # print 'pandas Series', t t2 = matrix2latex(pd.DataFrame(s)) # print 'pandas DataFrame', t2 assertEqual(t, "pandas_series") assertEqual(t2, "pandas_series_dataFrame") except ImportError: pass
def test_pandas_series(): try: import pandas as pd import numpy as np s = pd.Series([2, 4, 2, 42, 5], index=['a', 'b', 'c', 'd', 'e']) # print 'PANDAS\n', s # print 'PANDAS\n', s.to_dict(), s.tolist(), hasattr(s, 'to_dict') t = matrix2latex(s) # print 'pandas Series', t t2 = matrix2latex(pd.DataFrame(s)) # print 'pandas DataFrame', t2 assertEqual(t, "pandas_series") assertEqual(t2, "pandas_series_dataFrame") except ImportError: pass
def test_labels2(): # only difference from above test is names, note how above function # handles having too few headerRow cl = ["a", "b"] rl = ["names", "c", "d", "e"] t = matrix2latex(m, None, headerColumn=cl, headerRow=rl) assertEqual(t, "labels2")
def test_labels3(): # pass in environment as dictionary e = dict() e['headerColumn'] = ["a", "b"] e['headerRow'] = ["names", "c", "d", "e"] t = matrix2latex(m, None, **e) assertEqual(t, "labels3")
def test_labels3(): # pass in environment as dictionary e = dict() e['headerColumn'] = ["a", "b"] e['headerRow'] = ["names", "c", "d", "e"] t = matrix2latex(m, None, **e) assertEqual(t, "labels3")
def test_labels2(): # only difference from above test is names, note how above function # handles having too few headerRow cl = ["a", "b"] rl = ["names", "c", "d", "e"] t = matrix2latex(m, None, headerColumn=cl, headerRow=rl) assertEqual(t, "labels2")
def test_alignment_withoutTable(): t = matrix2latex(m, None, "align*", "pmatrix", format="$%.2f$", alignment='c') assertEqual(t, "alignment_withoutTable")
def test_infty1(): try: import numpy as np m = [[1,np.inf,float('inf')], [2,2,float('-inf')], [-np.inf,1,2]] t = matrix2latex(m) assertEqual(t, "infty1") except (ImportError, AttributeError): pass
def test_pandas_columns(): try: import pandas as pd import numpy as np d = { 'one': pd.Series([1., 2., 3.], index=['a', 'b', 'c']), 'two': pd.Series([1., 2., 3., 4.], index=['a', 'b', 'c', 'd']) } df = pd.DataFrame(d) t = matrix2latex(df) # print 'pandas', t, df.to_records() assertEqual(t, "pandas_columns") t = matrix2latex(df, headerRow=None, headerColumn=None) assertEqual(t, "pandas_columns_noHeaders") except ImportError: pass
def test_infty1(): try: import numpy as np m = [[1, np.inf, float('inf')], [2, 2, float('-inf')], [-np.inf, 1, 2]] t = matrix2latex(m) assertEqual(t, "infty1") except (ImportError, AttributeError): pass
def test_multicolumn(): hr = [[ 'Item', 'Item', 'Item', 'Item', 'Price', 'Price', 'test', '', 'Money', 'Money', 'Money' ], ['Animal', 'Description', '(\$)']] t = matrix2latex(m, headerRow=hr) t = t.split('\n')[4].strip() # pick out only third line assert t == r"\multicolumn{4}{c}{Item} & \multicolumn{2}{c}{Price} & {test} & {} & \multicolumn{3}{c}{Money}\\\cmidrule(r){1-4}\cmidrule(r){5-6}\cmidrule(r){9-11}", t
def test_alignment2b(): rl = ["a", "b"] cl = ["names", "c", "d", "e"] t = matrix2latex(m, alignment='r', headerColumn=cl, headerRow=rl, transpose=True) t = t.split('\n')[2].strip() assert t == r"\begin{tabular}{rrr}", t
def test_format_formatColumn_Warning(): # Test for warning: http://stackoverflow.com/a/3892301/1942837 with warnings.catch_warnings(record=True) as w: warnings.simplefilter("always") # Cause all warnings to always be triggered. # specify both format and formatColumn t = matrix2latex([[123456e10, 123456e10]], format='%g', formatColumn=['%.1g', '%g']) assert len(w) == 1 assert issubclass(w[-1].category, Warning) assertEqual(t, 'format_formatColumn_Warning')
def test_numpy(): try: import numpy as np for a in (np.matrix, np.array): t = matrix2latex(a(m), None, "align*", "pmatrix") assertEqual(t, "numpy") # Systems without numpy raises import error, # pypy raises attribute since matrix is not implemented, this is ok. except (ImportError, AttributeError): pass
def test_numpy(): try: import numpy as np for a in (np.matrix, np.array): t = matrix2latex(a(m), None, "align*", "pmatrix") assertEqual(t, "numpy") # Systems without numpy raises import error, # pypy raises attribute since matrix is not implemented, this is ok. except (ImportError, AttributeError): pass
def test_format_formatColumn_Warning(): # Test for warning: http://stackoverflow.com/a/3892301/1942837 with warnings.catch_warnings(record=True) as w: warnings.simplefilter( "always") # Cause all warnings to always be triggered. # specify both format and formatColumn t = matrix2latex([[123456e10, 123456e10]], format='%g', formatColumn=['%.1g', '%g']) assert len(w) == 1 assert issubclass(w[-1].category, Warning) assertEqual(t, 'format_formatColumn_Warning')
def test_pandas_dataframe(): try: import pandas as pd import numpy as np m = [[1, 1], [2, 4], [3, 9]] # python nested list m = pd.DataFrame(m) #m = pd.DataFrame.from_csv('http://chymera.eu/data/test/r_data.csv', parse_dates=False, index_col=False) # print 'PANDAS\n', m # print 'PANDAS\n', m.to_records() t = matrix2latex(m) assertEqual(t, "pandas_dataframe") except ImportError: pass
def test_pandas_dataframe(): try: import pandas as pd import numpy as np m = [[1, 1], [2, 4], [3, 9]] # python nested list m = pd.DataFrame(m) #m = pd.DataFrame.from_csv('http://chymera.eu/data/test/r_data.csv', parse_dates=False, index_col=False) # print 'PANDAS\n', m # print 'PANDAS\n', m.to_records() t = matrix2latex(m) assertEqual(t, "pandas_dataframe") except ImportError: pass
def tableEvtsAllRange(ch): if ch == "Mu": channel = "muon" else: channel = "electron" n_2btag = evalNumEvts("lljjmass", ch) print n_2btag n_1btag = evalNumEvts("lljjmass_1btag", ch) n_0btag = evalNumEvts("lljjmass_0btag", ch) hr = [' ','0 b-tag yields', '1 b-tag yields','2 b-tag yields'] hc = ["Background"] for m in masses: hc.append(str(m)+" GeV") numbers = [] numbers.append([ n_0btag["Background"], n_1btag["Background"], n_2btag["Background"] ]) for m in masses: signal = "GluGluToHToZZTo2L2Q_M-"+str(m)+"_8TeV" numbers.append([ n_0btag[signal], n_1btag[signal], n_2btag[signal]]) t = matrix2latex(numbers, "evtsAllRange_"+ch, headerColumn=hc, headerRow=hr, format='%.2f', alignment = '|c|c|c|',caption='List of expected background and signal yields in the '+channel+' channel with 1~fb$^{-1}$of data after all selection and within the $ZZ$ invariant mass range [0,1000]')
def get_notes(self): # get notes as a latex matrix notes = self._get_notes() # used by matrix2latex # header row hr = ['dataset', 'recipe', 'note'] # format column fc = ['%s', '%s', '%s'] alignment = 'l l p{7.5cm}' m = [] for note in notes: txt = note.get('note') txt = unicode(txt).encode('utf-8').replace('æ', '\\ae ').replace('å','\\aa ').replace('ø','\\o ') m.append([note.get('dataset'), note.get('recipe_type'), txt]) caption = 'Comments to videos in questionnaire' label = 'tab:notes' t = matrix2latex(m, 'notes', headerRow=hr, caption=caption, label=label, formatColumn=fc, alignment=alignment) return t
def tableEvtsMassWind(var, ch): if ch == "Mu": channel = "$2\mu2j$" else: channel = "$2e2j$" if var == "lljjmass": cat = "2 b-tag" elif var == "lljjmass_1btag": cat = "1 b-tag" else: cat = "0 b-tag" hr = ['Mass [GeV]','Signal', '$Z$+Jets', '$tt$', 'ZZ/WZ/WW', 'TotalBkg'] hc = [str(m) for m in masses] numbers = [] for m in masses: nEvts = evalNumEvts(var, ch, m) signal = "GluGluToHToZZTo2L2Q_M-"+str(m)+"_8TeV" numbers.append([ nEvts[signal], nEvts["DYJetsToLL_M-50"], nEvts["TT"], nEvts["ZZ/WZ/WW"], nEvts["Background"] ]) t = matrix2latex(numbers, var+"_"+ch+"_evts", headerColumn=hc, headerRow=hr, format='%.2f', alignment = '|c|c|c|c|c|',caption='Expected yields of signal and background with 1~fb$^{-1}$ based on simulation in the '+cat+' category. The numbers show '+channel+' expectations. Tighter $mZZ$ mass requirements are applied as (-6\%, +\0\%) of the mass hypothesis.')
def test_empty(): t = matrix2latex([]) assertEqual(t, 'empty')
def test_environment2(): t = matrix2latex(m, None, "foo", "bar") assertEqual(t, "environment2")
def test_file(): matrix2latex(m, 'tmp.tex') f = open('tmp.tex') content = f.read() f.close() assertEqual(content, "file")
def test_transpose1(): t = matrix2latex(m, transpose=True) assertEqual(t, "transpose1")
def test_nicefloat(): t = matrix2latex([123456e-10, 1e-15, 12345e5]) assertEqual(t, 'nicefloat')
def test_non_rectangular(): """Test a nested list with 'missing' elements""" t = matrix2latex([[1, 2], [1, 2, 3], [5]]) assertEqual(t, 'non_rectangular')
def test_nicefloat_4g(): t = matrix2latex([123456e-10, 1e-15, 12345e5], format='$%.4g$') assertEqual(t, 'nicefloat_4g')
def test_file(): matrix2latex(m, 'tmp.tex') f = open('tmp.tex') content = f.read() f.close() assertEqual(content, "file")
def test_environment1(): t = matrix2latex(m, None, "table", "center", "tabular") assertEqual(t, "environment1")
def test_alignment2(): cl = ["a", "b"] rl = ["names", "c", "d", "e"] t = matrix2latex(m, alignment='r', headerColumn=cl, headerRow = rl) t = t.split('\n')[2].strip() assert t == r"\begin{tabular}{rrrr}", t
def test_labels4(): t = matrix2latex(m, None, caption="Hello", label="la") assertEqual(t, "labels4")
def test_environment2(): t = matrix2latex(m, None, "foo", "bar") assertEqual(t, "environment2")
def test_alignment1(): t = matrix2latex(m, alignment='r') t = t.split('\n')[2].strip() assert t == r"\begin{tabular}{rrr}", t
def test_labels4(): t = matrix2latex(m, None, caption="Hello", label="la") assertEqual(t, "labels4")
def test_nicefloat(): t = matrix2latex([123456e-10, 1e-15, 12345e5]) assertEqual(t, 'nicefloat')
for func in (factorialMath, factorialRecursive, factorialSequential): row = list() for n in N: res = func(n) # call func row.append(res) # append result to row table.append(row) # append row to table # convert to string for labeling cl = ["${n}$".format(n=n) for n in N] # row labels rl = ['$n$', 'Built-in', 'Recursive', 'Sequential'] caption = '''Vertifying that the different factorial implementations gives the same results''' matrix2latex(table, 'facV', caption=caption, columnLabels=cl, rowLabels=rl, alignment='r') import timeit table = list() for func in ('factorialMath', 'factorialRecursive', 'factorialSequential'): row = list() for n in N: statement = 'factorial.{func}({n})'.format(func=func, n=n) setup = 'import factorial' # measure time res = timeit.repeat(statement, setup) row.append(min(res)) # append result table.append(row) # append row to table
def test_non_rectangular(): """Test a nested list with 'missing' elements""" t = matrix2latex([[1,2], [1, 2, 3], [5]]) assertEqual(t, 'non_rectangular')
def test_transpose2(): cl = ["a", "b"] t = matrix2latex(m, transpose=True, headerRow=cl) assertEqual(t, "transpose2")
def test_nicefloat_4g(): t = matrix2latex([123456e-10, 1e-15, 12345e5], format='$%.4g$') assertEqual(t, 'nicefloat_4g')
def test_string(): t = matrix2latex([['a', 'b', '1'], ['1', '2', '3']], format='%s') assertEqual(t, "string")
def test_simple(): t = matrix2latex(m) assertEqual(t, "simple")
def test_transpose1(): t = matrix2latex(m, transpose=True) assertEqual(t, "transpose1")
def test_transpose2(): cl = ["a", "b"] t = matrix2latex(m, transpose=True, headerRow=cl) assertEqual(t, "transpose2")
def test_simple(): t = matrix2latex(m) assertEqual(t, "simple")
def test_environment1(): t = matrix2latex(m, None, "table", "center", "tabular") assertEqual(t, "environment1")
def test_infty2(): # same as above but without numpy inf = float('inf') m = [[1,inf,float('inf')], [2,2,float('-inf')], [-inf,1,2]] t = matrix2latex(m) assertEqual(t, "infty1")
def test_labels1(): cl = ["a", "b"] rl = ["c", "d", "e"] t = matrix2latex(m, None, headerColumn=cl, headerRow=rl) assertEqual(t, "labels1")
def test_multicolumn(): hr = [['Item', 'Item', 'Item', 'Item', 'Price', 'Price', 'test', '', 'Money', 'Money', 'Money'], ['Animal', 'Description', '(\$)']] t = matrix2latex(m, headerRow=hr) t = t.split('\n')[4].strip() # pick out only third line assert t == r"\multicolumn{4}{c}{Item} & \multicolumn{2}{c}{Price} & {test} & {} & \multicolumn{3}{c}{Money}\\\cmidrule(r){1-4}\cmidrule(r){5-6}\cmidrule(r){9-11}", t
def test_empty(): t = matrix2latex([]) assertEqual(t, 'empty')
def test_labels1(): cl = ["a", "b"] rl = ["c", "d", "e"] t = matrix2latex(m, None, headerColumn=cl, headerRow=rl) assertEqual(t, "labels1")
def test_alignment1(): t = matrix2latex(m, alignment='r') t = t.split('\n')[2].strip() assert t == r"\begin{tabular}{rrr}", t
from uncertainties import correlated_values from matrix2latex import matrix2latex from scipy.special import legendre #Polarplot alpha, A1, A2, A3 = np.genfromtxt('data/peaks.txt', unpack=True) hr = ['$\alpha$/°', '$A_1$', '$A_2$', '$A_3$'] m = np.zeros((19, 4)) m[:, 0] = alpha m[:, 1] = A1 m[:, 2] = A2 m[:, 3] = A3 t = matrix2latex(m, headerRow=hr, format='%.2f') print(t) # Test mit Scipy # Erklärung: Pn = legendre(n) erschafft ein Objekt namens Pn, dass ein Legendrepolynom # des Grades n ist. Damit kann man plotten, wie unten auch zu sehen ist. # Damit kriegst du auch diese Schleifen hin! plt.figure(3) P1 = legendre(1) philin = np.linspace(0, 2 * np.pi, 1000) theta = np.arccos(1 / 2 * np.cos(alpha / 360 * 2 * np.pi) - 1 / 2) plt.polar(theta, A1 / np.max(A1), "rx", mew=0.5, label="Messwerte") plt.polar(philin, np.abs(P1(np.cos(philin))), "b-", label="Theorie",
def simple(matrix, headerRow=None, headerColumn=None, Filename=None, font_size=None, clean_latex=True): """A simple pagination function, that creates a minimal LaTeX document code for an input matrix, compiles it, and removes the LaTeX traces. Arguments: matrix A numpy matrix or a nested list Filename File to place output, extension .tex is added automatically. File can be included in a LaTeX document by \input{filename}. Output will always be returned in a string. If filename is None or not a string it is ignored. headerRow A row at the top used to label the columns. Must be a list of strings. Can be a nested list for multiple headings. If two or more items are repeated, a multicolumn is inserted, so: headerRow=['a', 'a'] will produces "\multicolumn{2}{c}{Item}" with an appropriate cmidrule beneath. To avoid this behavior ensure each consecutive item is unique, for instance: headerRow=['a', 'a '] will produces the expected "a & a". headerColumn A column used to label the rows. Must be a list of strings font_size Specify the global (document and table) font size. Accepted values are integers from 1 to 10 - these are mapped on the available LaTeX font sizes https://en.wikibooks.org/wiki/LaTeX/Fonts clean_latex Used to optionally turn off the delete phase for LaTeX traces Must be bool """ latex_font_sizes = { 1: "\\tiny", 2: "\\scriptsize", 3: "\\footnotesize", 4: "\\small", 5: "\\normalsize", 6: "\\large", 7: "\\Large", 8: "\\LARGE", 9: "\\huge", 10: "\\Huge" } if not Filename: Filename = "_temp" table = matrix2latex(matrix, headerRow=headerRow, headerColumn=headerColumn, environments=['tabular']) #determine document font size if font_size: document_fontsize = latex_font_sizes[font_size]+"\n" else: document_fontsize = "" #add header elements (with the prepend operator "+"y in reverse order) tex = "\\sbox\mt{%\n" + table tex = document_fontsize + tex tex = "\\begin{document}\n" + tex tex = "\\pagenumbering{gobble}\n" + tex tex = "\\newsavebox\mt\n" + tex tex = "\\usepackage{booktabs}\n" + tex tex = "\\usepackage{geometry}\n\\geometry{a4paper,total={210mm,297mm},left=15mm,right=15mm,top=15mm,bottom=15mm}\n" + tex tex = "\\documentclass{article}\n" + tex #add footer elements tex = tex + "%\n}\n" tex = tex + \ "\\makeatletter\n" + \ "\\ifdim\\wd\\mt>\\textwidth\n" + \ "\\setlength\\@tempdima {\\paperheight}%\n" + \ "\\setlength\\paperheight {\\paperwidth}%\n" + \ "\\setlength\\paperwidth {\\@tempdima}%\n" + \ "\\setlength\\pdfpageheight{\\paperheight}%\n" + \ "\\setlength\\pdfpagewidth{\\paperwidth}%\n" + \ "\\setlength{\\textwidth}{\\paperwidth}%\n" + \ "\\addtolength{\\textwidth}{-3cm}%\n" + \ "\\setlength{\\hsize}{\\textwidth}%\n" + \ "\\fi\n" + \ "\\makeatother\n" + \ "\\begin{table}[htp]\\setlength{\\hsize}{\\textwidth}%\n" + \ "\\centering\n" + \ "\\usebox\\mt\n" + \ "\\end{table}\n" + \ "\\end{document}\n" file_ = open(Filename+".tex", 'w') file_.write(tex) file_.close() call(["pdflatex", Filename+".tex"]) if clean_latex: all_files = os.listdir(".") latex_files = [one_file for one_file in all_files if Filename in one_file] non_pdf_latex_files = [latex_file for latex_file in latex_files if ".pdf" not in latex_file] for non_pdf_latex_file in non_pdf_latex_files: os.remove(non_pdf_latex_file)
ylabel("Average performance") grid() axis([0, 410, -2.2, 8]) savefig("Exp14.pdf") # <codecell> from scipy.stats import ks_2samp from matrix2latex import matrix2latex table = zeros((len(Abcissas), 2)) for i in range(0, len(Abcissas)): y_csi = Y_CSI[i] y_scirl = Y_SCIRL[i] table[i][0] = Abcissas[i] table[i][1] = ks_2samp(y_csi, y_scirl)[1] t = matrix2latex(table, headerRow=["Number of expert samples", "$p$-value"]) print t # <codecell> def student_t(X1, X2): return abs((mean(X1) - mean(X2))) / sqrt( abs(pow(X1.var(), 2) / len(X1) - pow(X2.var(), 2) / len(X2))) [student_t(Y_SCIRL[i], Y_CSI[i]) for i in range(0, 5)] # <codecell> plot(Abcissas[-4:],