Skip to content

Commit d3a3b04

Browse files
committed
Add latex output
1 parent 67211c7 commit d3a3b04

File tree

1 file changed

+83
-6
lines changed

1 file changed

+83
-6
lines changed

MCM/MCM.py

Lines changed: 83 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -315,6 +315,17 @@ def draw(analysis,
315315
316316
"""
317317

318+
latex_string = "\\documentclass[a4,12pt]{article}\n"
319+
latex_string += "\\usepackage{colortbl}\n"
320+
latex_string += "\\usepackage{pgfplots}\n"
321+
latex_string += "\\usepackage[margin=2cm]{geometry}\n"
322+
latex_string += "\\pgfplotsset{compat=newest}\n"
323+
latex_string += "\\begin{document}\n"
324+
latex_string += "\\begin{table}\n"
325+
latex_string += "\\footnotesize\n"
326+
latex_string += "\\sffamily\n"
327+
latex_string += "\\begin{center}\n"
328+
318329
if (col_comparates is not None) and (excluded_col_comparates is not None):
319330
print('Choose whether to include or exclude, not both!')
320331
return
@@ -381,7 +392,7 @@ def draw(analysis,
381392

382393
if analysis['include-pvalue']:
383394

384-
p_value_text = f"If in bold, then\np-value $<$ {analysis['pvalue-threshold']:.2f}"
395+
p_value_text = f"If in bold, then\np-value < {analysis['pvalue-threshold']:.2f}"
385396

386397
if analysis['pvalue-correction'] is not None:
387398

@@ -484,6 +495,9 @@ def draw(analysis,
484495
cbar.ax.tick_params(labelsize=font_size)
485496
cbar.set_label(label=capitalize_label(_colorbar_value), size=font_size)
486497

498+
cm_norm = plt.Normalize(_vmin, _vmax)
499+
cm = plt.colormaps[_colormap]
500+
487501
xticks, yticks = get_ticks(analysis, row_comparates, col_comparates, precision)
488502
ax.set_xticks(np.arange(n_cols), labels=xticks, fontsize=font_size)
489503
ax.set_yticks(np.arange(n_rows), labels=yticks, fontsize=font_size)
@@ -493,11 +507,20 @@ def draw(analysis,
493507

494508
start_j = 0
495509

510+
if analysis['order-stats'] == 'average-statistic':
511+
ordering = 'Mean-' + analysis['used-statistics']
512+
else:
513+
ordering = analysis['order-stats']
514+
515+
latex_table = []
516+
latex_table.append([f"{ordering}"] + [f"\shortstack{{{_}}}".replace('\n', ' \\\\ ') for _ in xticks])
496517

497518
for i in range(n_rows):
498519

499520
row_comparate = row_comparates[i]
500521

522+
latex_row = []
523+
501524
if can_be_symmetrical and (not show_symetry):
502525
start_j = i
503526

@@ -531,23 +554,39 @@ def draw(analysis,
531554
)
532555

533556
im.axes.text(j, i, df_annotations_np[i, j], **cell_text_arguments)
557+
558+
latex_cell = "\\rule{0em}{3ex} " + df_annotations_np[i, j].replace("\n", " \\\\ ")
559+
latex_row.append(f"\\cellcolor[rgb]{{{','.join([str(round(_, 4)) for _ in cm(cm_norm(pairwise_matrix[i, j]))[:-1]])}}}\\shortstack{{{latex_cell}}}")
560+
534561
continue
535562

536563
pairwise_key = get_keys_for_two_comparates(row_comparate, col_comparate)
537564

538565
pairwise_content = analysis[pairwise_key]
539566
pairwise_keys = list(pairwise_content.keys())
540567

568+
latex_bold = ""
569+
541570
if "pvalue" in pairwise_keys:
542571
if analysis[pairwise_key]["is-significant"]:
543572
cell_text_arguments.update(fontweight='bold')
573+
latex_bold = "\\bfseries "
544574

545575
im.axes.text(j, i, df_annotations_np[i, j], **cell_text_arguments)
546576

547-
if analysis['order-stats'] == 'average-statistic':
548-
ordering = 'Mean-' + analysis['used-statistics']
549-
else:
550-
ordering = analysis['order-stats']
577+
latex_cell = "\\rule{0em}{3ex} " + df_annotations_np[i, j].replace("\n", " \\\\ ")
578+
latex_row.append(f"{latex_bold}\\cellcolor[rgb]{{{','.join([str(round(_, 4)) for _ in cm(cm_norm(pairwise_matrix[i, j]))[:-1]])}}}\\shortstack{{{latex_cell}}}")
579+
580+
if legend_cell_location is None:
581+
latex_cell = "\\rule{0em}{3ex} " + f"{cell_legend}".replace("\n", " \\\\ ") if i == 0 else "\\null"
582+
latex_row.append(f"\\shortstack{{{latex_cell}}}")
583+
584+
latex_table.append([f"\shortstack{{{yticks[i]}}}".replace('\n', ' \\\\ ')] + latex_row)
585+
586+
# if analysis['order-stats'] == 'average-statistic':
587+
# ordering = 'Mean-' + analysis['used-statistics']
588+
# else:
589+
# ordering = analysis['order-stats']
551590
if n_cols == n_rows == 1:
552591
# special case when 1x1
553592
x = ax.get_position().x0 - 1
@@ -615,4 +654,42 @@ def draw(analysis,
615654
plt.clf()
616655
plt.close()
617656
else:
618-
plt.show()
657+
plt.show()
658+
659+
latex_string += f"\\begin{{tabular}}{{{'c' * (len(latex_table[0]) + 1)}}}\n" # +1 for labels
660+
for latex_row in latex_table:
661+
latex_string += " & ".join(latex_row) + " \\\\[1ex]" + "\n"
662+
663+
if colorbar_orientation == "horizontal":
664+
latex_string += "\\end{tabular}\\\\\n"
665+
else:
666+
latex_string += "\\end{tabular}\n"
667+
668+
latex_colorbar_0 = "\\begin{tikzpicture}[baseline=(current bounding box.center)]\\begin{axis}[hide axis,scale only axis,"
669+
latex_colorbar_1 = f"colormap={{cm}}{{rgb255(1)=({','.join([str(int(_ * 255)) for _ in cm(cm_norm(min_value))[:-1]])}) rgb255(2)=(220,220,220) rgb255(3)=({','.join([str(int(_ * 255)) for _ in cm(cm_norm(max_value))[:-1]])})}},"
670+
latex_colorbar_2 = f"colorbar horizontal,point meta min={_vmin:.02f},point meta max={_vmax:.02f},"
671+
latex_colorbar_3 = "colorbar/width=1.0em"
672+
latex_colorbar_4 = "}] \\addplot[draw=none] {0};\\end{axis}\\end{tikzpicture}"
673+
674+
if colorbar_orientation == "horizontal":
675+
latex_string += latex_colorbar_0 + "width=0sp,height=0sp,colorbar horizontal,colorbar style={width=0.25\linewidth," + latex_colorbar_1 + latex_colorbar_2 + latex_colorbar_3 + ",scaled x ticks=false,xticklabel style={/pgf/number format/fixed,/pgf/number format/precision=3}," + f"xlabel={{{_colorbar_value}}}," + latex_colorbar_4
676+
else:
677+
latex_string += latex_colorbar_0 + "width=1pt,colorbar right,colorbar style={height=0.25\linewidth," + latex_colorbar_1 + latex_colorbar_2 + latex_colorbar_3 + ",scaled y ticks=false,ylabel style={rotate=180},yticklabel style={/pgf/number format/fixed,/pgf/number format/precision=3}," + f"ylabel={{{_colorbar_value}}}," + latex_colorbar_4
678+
679+
latex_string += "\\end{center}\n"
680+
latex_string += "\\caption{[...] \\textbf{" + f"{p_value_text}".replace("\n", " ") + "} [...]}\n"
681+
latex_string += "\\end{table}\n"
682+
latex_string += "\\end{document}\n"
683+
684+
latex_string = latex_string.replace(">", "$>$")
685+
latex_string = latex_string.replace("<", "$<$")
686+
687+
if savename != "":
688+
with open(f"{output_dir}/{savename}.tex", "w", encoding = "utf8", newline = "\n") as file:
689+
file.writelines(latex_string)
690+
691+
# latex references:
692+
# * https://tex.stackexchange.com/a/120187
693+
# * https://tex.stackexchange.com/a/334293
694+
# * https://tex.stackexchange.com/a/592942
695+
# * https://tex.stackexchange.com/a/304215

0 commit comments

Comments
 (0)