import os
from .graphs import Graphs, Graph, Data
from .tools import indentParagraph
import numpy as np
import colorsys
[docs]templates_tikz = os.path.join(os.path.dirname(__file__), 'templates_tikz')
[docs]def convert_linestyle(linestyle):
try:
linestyles = {"-": '', "--": "dashed", "..": "dotted", ".": "dotted"}
return linestyles[linestyle]
except KeyError:
return linestyle
[docs]def convert_color(color):
try:
colors = {"b": (0, 0, 255), "r": (255, 0, 0), "g": (0, 255, 0), "y": (255, 255, 0), "c": (0, 255, 255), "k": (0, 0, 0), "w": (255, 255, 255)}
return colors[color]
except KeyError:
return color
[docs]def find_all_colors(theGraphs):
all_colors = dict()
correspondances = dict()
for graphId in theGraphs.get_all_graphs_ids():
correspondances[graphId] = dict()
for traceId in theGraphs.get_graph(graphId).get_all_traces():
try:
r, g, b = convert_color(theGraphs.get_graph(graphId).get_trace(traceId).get_color())
except TypeError:
r, g, b = 0, 0, 0
key_format = "RGB{}_{}_{}".format(r, g, b)
all_colors[key_format] = r"\definecolor{{{}}}{{RGB}}{{{},{},{}}}".format(key_format, r, g, b)
correspondances[graphId][traceId] = key_format
return all_colors, correspondances
[docs]def convert_marker(marker):
try:
markers = {"o": "*", "t1": "triangle", "t2": "triangle", "t3": "triangle", "t": "triangle", "s": "square", "d": "diamond", "p": "pentagon"}
return markers[marker]
except KeyError:
return marker
[docs]def do_preamble():
with open(os.path.join(templates_tikz, "preamble.tex"), "r") as f:
return f.read()
[docs]def do_specific_axis_options(theGraph: Graph):
"""Get graph-specific axis options"""
theStr = ''
for key in theGraph.get_all_traces():
xlabel = theGraph.get_trace(key).get_x_label()
if xlabel:
theStr += "xlabel={{ {} }},".format(format_escape_char(xlabel))
break
for key in theGraph.get_all_traces():
ylabel = theGraph.get_trace(key).get_y_label()
if ylabel:
theStr += "ylabel={{ {} }},".format(format_escape_char(ylabel))
break
return theStr
[docs]def do_specific_trace_options(theTrace: Data, theColor):
"""Get latex trace options from Data"""
linestyle = convert_linestyle(theTrace.get_linestyle())
is_filled = theTrace.symbol_isfilled()
markerstyle = convert_marker(theTrace.get_symbol())
is_scattered = theTrace.is_scattered()
outline = theTrace.get_symbolOutline()
theStr = '\ncolor={},'.format(theColor)
if is_scattered:
theStr += "\nonly marks,"
else:
theStr += "{},".format(linestyle)
theStr += '\nmark={},'.format(markerstyle)
mark_options = '\nsolid, \nline width=0.1pt, \nmark size=1pt, \ndraw={}!{}!{},'.format(theColor, int(abs(outline-2)*100), "white" if outline < 1 else "black")
if not is_filled:
mark_options += "\nfill opacity=0,\n"
theStr += "\nmark options={{{}}}".format(indentParagraph(mark_options, 1))
return theStr
[docs]def export_to_tikz_groupGraphs(theGraphs: Graphs, foldername, additionalPreamble=lambda: '', additionalAxisOptions=lambda graphId: '', additionalTraceOptions=lambda graphId, traceId: '', debug=False):
"""
Export the graphs as group
:param theGraphs: Graphs to save
:param foldername: Foldername to save
:param additionalPreamble: method that returns string for custom tikz options
:param additionalAxisOptions: method that returns string for custom tikz options
:param additionalTraceOptions: method that returns string for custom tikz options
:return:
"""
all_colors, correspondance_colors = find_all_colors(theGraphs)
if not debug:
if not foldername:
return
os.makedirs(foldername, exist_ok=True)
source_folder = os.path.join(foldername, "source")
os.makedirs(source_folder, exist_ok=True)
# Data file creation
if not debug:
for graphId in theGraphs.get_all_graphs_ids():
theGraph = theGraphs.get_graph(graphId)
for traceId in theGraph.get_all_traces():
filename = os.path.join(source_folder, "g{}t{}.dat".format(graphId, traceId))
theTrace = theGraph.get_trace(traceId)
x, y = theTrace.get_plot_data()
np.savetxt(filename, np.array([[x[i], y[i]] for i in range(len(x))]), header='x\ty')
# add_body += "\\pgfplotstableread{{source/g{}t{}.dat}}{{\\g{}t{}}}\n".format(graphId, traceId, graphId, traceId)
# Preamble
theStr = ''
theStr += do_preamble() + additionalPreamble()
for color in all_colors.values():
theStr += "% Colors\n{}\n".format(color)
if not debug:
with open(os.path.join(foldername, "preamble.tex"), "w") as f:
f.write(theStr)
else:
print("PREAMBLE\n{}\n\n\n".format(theStr))
# Generate picture creation
theStr = ''
theStr += do_generate_figure()
if not debug:
with open(os.path.join(foldername, "generate_figure.tex"), "w") as f:
f.write(theStr)
else:
print("GENERATOR\n{}\n\n\n".format(theStr))
# picture file creation
theStr = ''
theStr += indentParagraph("\\begin{tikzpicture}\n", 1)
groupStyle = "group style={{group size=1 by {},}},".format(len(theGraphs.get_all_graphs_ids()))
theStr += indentParagraph("\\begin{{groupplot}}[default_axis_style, {}]".format(groupStyle), 3)
for graphId in theGraphs.get_all_graphs_ids():
theGraph = theGraphs.get_graph(graphId)
theStr += indentParagraph("\\nextgroupplot[{}]".format(do_specific_axis_options(theGraph) + additionalAxisOptions(graphId)), 5)
for traceId in theGraph.get_all_traces():
theTrace = theGraph.get_trace(traceId)
filename = "source/g{}t{}.dat".format(graphId, traceId)
theStr += indentParagraph("\\addplot[default_trace_style, {}] file {{\\relativepath {}}};\n".format(indentParagraph(do_specific_trace_options(theTrace, correspondance_colors[graphId][traceId]) + additionalTraceOptions(graphId, traceId), 3), filename), 7)
if theTrace.get_legend():
theStr += indentParagraph("\\addlegendentry{{{}\n}}".format(theTrace.get_legend()), 7)
theStr += indentParagraph("\\end{groupplot}\n", 2)
theStr += indentParagraph("\\end{tikzpicture}\n", 1)
if not debug:
with open(os.path.join(foldername, "figure.tex"), "w") as f:
f.write(theStr)
else:
print("FIGURE\n{}\n\n\n".format(theStr))