Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Latex decoupling #31

Merged
merged 4 commits into from
Dec 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion cli.py
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ def main(filepath, ship_plots, pressure_plots):
Logger.info('Outputting Data to /out.json file...')
IO.ship_save(ship, 'out.json')
Logger.info('Generating LaTeX Report Data to /out.json file...')
generate_latex_rep(logger, path='./essay/', _standalone=False)
generate_latex_rep(logger, path='./essay/', standalone=False)
Logger.success('Program terminated successfully!')


Expand Down
36 changes: 30 additions & 6 deletions modules/baseclass/ship.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@


import math
from modules.baseclass.block import Block
from modules.baseclass.subblocks.atm_sur_block import AtmSur
Expand Down Expand Up @@ -29,8 +27,20 @@ class Ship:
stiff_plates (list[StiffPlate]): _description_
blocks (list[Block]): _description_
"""
def __init__(self, LBP : float, Lsc: float, B: float, T: float, Tmin: float, Tsc: float, D: float, Cb: float, Cp: float, Cm: float, DWT: float, # PSM_spacing,
stiff_plates: list[StiffPlate], blocks: list[Block]):
def __init__(self,
LBP: float,
Lsc: float,
B: float,
T: float,
Tmin: float,
Tsc: float,
D: float,
Cb: float,
Cp: float,
Cm: float,
DWT: float, # PSM_spacing,
stiff_plates: list[StiffPlate],
blocks: list[Block]):
self.symmetrical = True # Checks that implies symmetry. For the time being is arbitrary constant
self.LBP = LBP
self.Lsc = Lsc # Rule Length
Expand Down Expand Up @@ -63,8 +73,8 @@ def __init__(self, LBP : float, Lsc: float, B: float, T: float, Tmin: float, Tsc
self.n50_Ixx, self.n50_Iyy = self.Calculate_I(n50=True)
self.kappa = 1.0 # material factor

self.a0 = (1.58 - 0.47 * self.Cb) * (2.4 / math.sqrt(
self.Lsc) + 34 / self.Lsc - 600 / self.Lsc ** 2) # Acceleration parameter Part 1 Chapter 4 Section 3 pp.180
# Acceleration parameter Part 1 Chapter 4, Section 3 pp.180
self.a0 = (1.58 - 0.47 * self.Cb) * (2.4 / math.sqrt(self.Lsc) + 34 / self.Lsc - 600 / self.Lsc ** 2)
self.evaluate_kappa()

def evaluate_kappa(self):
Expand Down Expand Up @@ -224,3 +234,17 @@ def data_input(self, text):
if "data" not in self.__dict__:
self.data = text
self.data += text

def map_members(self):
v = vars(self)
v["kappa"] = f"{self.kappa: 0.3g}"
v["Mwh"] = round(self.Mwh, 2)
v["Mws"] = round(self.Mws, 2)
v["Msw_h_mid"] = round(self.Msw_h_mid, 2)
v["Msw_s_mid"] = round(self.Msw_s_mid, 2)
v["Cw"] = round(self.Cw, 3)
v["yo"] = round(self.yo, 3)
v["Ixx"] = round(self.Ixx, 2)
v["n50_Ixx"] = round(self.n50_Ixx, 2)
v["a0"] = round(self.a0, 5)
return v
171 changes: 43 additions & 128 deletions modules/io/latex.py
Original file line number Diff line number Diff line change
@@ -1,154 +1,69 @@
from typing import Iterable

import modules.render as rnr
from modules.io.datalogger import DataLogger
from modules.io.templates import TemplateFactory
from modules.utils.logger import Logger


TEX_PREAMBLE = (
'\\documentclass[12pt,a4paper]{report}\n'
'\\usepackage[a4paper,headheight =15pt]{geometry}\n'
'\\usepackage{array}\n'
'\\usepackage{multirow}\n'
'\\usepackage{longtable}\n'
'\\usepackage{pdflscape}\n'
'\\usepackage{amsmath}\n'
'\\usepackage{comment}\n'
'\\usepackage{caption}\n'
'\\usepackage{graphicx}\n'
'\\usepackage{fancyhdr}\n'
'\\usepackage{typearea}\n'
'\\usepackage[absolute]{textpos}\n'
'\\fancypagestyle{normal}{\\fancyhf{}\\rhead{\\thepage}\\lhead{\\leftmark}\\setlength{\\headheight}{15pt}\n'
'\\renewcommand{\\headrulewidth}{1pt} \n'
'\\renewcommand{\\footrulewidth}{0pt}}\n'
'\\fancypagestyle{lscape}{% \n'
'\\fancyhf{} % clear all header and footer fields \n'
'\\fancyhead[L]{%\n'
'\\begin{textblock}{0}(1,12){\\rotatebox{90}{\\underline{\\leftmark}}}\\end{textblock}\n'
'\\begin{textblock}{2}(1,1){\\rotatebox{90}{\\underline{\\thepage}}}\\end{textblock}}\n'
'\\setlength{\\headheight}{15pt}\n'
'\\setlength{\\footheight}{0pt}\n'
'\\renewcommand{\\headrulewidth}{0pt} \n'
'\\renewcommand{\\footrulewidth}{0pt}}\n'
'\\graphicspath{{./}}\n'
)
preamble_template = TemplateFactory.get_latex_template("report", "preamble.tex")
particulars_data_template = TemplateFactory.get_latex_template("chapters", "particulars.tex")
figure_template = TemplateFactory.get_latex_template("report", "figure.tex")
pressure_data_template = TemplateFactory.get_latex_template("chapters", "pressure_data.tex")
plating_data_template = TemplateFactory.get_latex_template("chapters", "plating_data.tex")
stiffeners_data_template = TemplateFactory.get_latex_template("chapters", "stiffeners_data.tex")
stiffened_data_template = TemplateFactory.get_latex_template("chapters", "stiffened_data.tex")
stiffened_ordinary_data_template = TemplateFactory.get_latex_template("chapters", "stiffened_ordinary_data.tex")
content_template = TemplateFactory.get_latex_template("report", "content.tex")
Logger.debug("Done loading LaTeX templates.")


def generate_latex_rep(data: DataLogger, path='./', _standalone=True):
out = latex_output(data, standalone=_standalone, figs=('id_plt.pdf', 'tag_plt.pdf', 'PSM_plt.pdf'))
def generate_latex_rep(data: DataLogger, path='./', standalone=True):
out = latex_output(data, embeddable=not standalone, figs=('id_plt.pdf', 'tag_plt.pdf', 'PSM_plt.pdf'))
with open(path + 'tabs.tex', 'w') as file:
file.write(out)
rnr.contour_plot(data.ship, key="id", path=path + 'id_plt.pdf', cmap='jet')
rnr.contour_plot(data.ship, key="spacing", path=path + 'PSM_plt.pdf', cmap='jet')
rnr.contour_plot(data.ship, key="tag", path=path + 'tag_plt.pdf', cmap='jet')


def latex_output(data_logger : DataLogger, standalone=False, figs=()):
def latex_output(data_logger: DataLogger, embeddable=True, figs: Iterable = ()) -> str:
"""
Output Function that generates a .tex file for use in LaTeX
Generates a latex document.
:param embeddable: If True, returns an embeddable LaTeX string.
:param figs: Iterable of figures to embed in the document.
"""
data_logger.create_tabular_data()
ship = data_logger.ship
mid = ''
GeneralPart = (
'\\chapter{General Input Data Particulars}\n'
'\\label{sec:General Particulars}\n'
'\\begin{table}[h]\n'
'\\caption{Ship\'s General Input Data Particulars}\n'
'\\label{tab:Gen_Part}\n'
'\\begin{tabular}{{>{\centering}m{6cm}}*{2}{>{\centering}m{4cm}}}\n'
'\\hline\n'
'$L_{BP}$ '+f'&{ship.LBP}&'+' [m]\\tabularnewline \\hline\n'
'$L_{sc} = L$ '+f'&{ship.Lsc}&'+' [m]\\tabularnewline \\hline\n'
'$B$ '+f'&{ship.B}&'+' [m]\\tabularnewline \\hline\n'
'$T$ '+f'&{ship.T}&'+' [m]\\tabularnewline \\hline\n'
'$T_{min}$ '+f'&{ship.Tmin}&'+' [m]\\tabularnewline \\hline\n'
'$T_{sc}$ '+f'&{ship.Tsc}&'+' [m]\\tabularnewline \\hline\n'
'$D$ '+f'&{ship.D}&'+' [m]\\tabularnewline \\hline\n'
'$C_b$ '+f'&{ship.Cb}&'+' \\tabularnewline \\hline\n'
'$C_p$ '+f'&{ship.Cp}&'+' \\tabularnewline \\hline\n'
'$C_m$ '+f'&{ship.Cm}&'+' \\tabularnewline \\hline\n'
'$DWT$ '+f'&{ship.DWT}&'+' \\tabularnewline \\hline\n'
'k (material factor) '+f'&{ship.kappa : 0.3g}&'+' [m]\\tabularnewline \\hline\n'
'$M_{wh}$ '+f'&{round(ship.Mwh,2)}&'+' [kNm]\\tabularnewline \\hline\n'
'$M_{ws}$ '+f'&{round(ship.Mws,2)}&'+' [kNm]\\tabularnewline \\hline\n'
'$M_{sw,h-mid}$ '+f'&{round(ship.Msw_h_mid,2)}&'+' [kNm]\\tabularnewline \\hline\n'
'$M_{sw,s-mid}$ '+f'&{round(ship.Msw_s_mid,2)}&'+' [kNm]\\tabularnewline \\hline\n'
'$C_w$ '+f'&{round(ship.Cw,3)}&'+' \\tabularnewline \\hline\n'
'$y_{neutral}$ '+f'&{round(ship.yo,3)}&'+' [m]\\tabularnewline \\hline\n'
'$I_{net,\, v}$ '+f'&{round(ship.Ixx,2)}&'+' [$m^4$]\\tabularnewline \\hline\n'
'$I_{n-50,\, v}$ '+f'&{round(ship.n50_Ixx,2)}&'+' [$m^4$]\\tabularnewline \\hline\n'
'$a_0$ '+f'&{round(ship.a0,5)}&'+' \\tabularnewline \\hline\n'
'\\end{tabular}\n'
'\\end{table}\n\n')
figures = ''
if len(figs) != 0:
for i in figs:
figures +=(
'\\begin{figure}[h]\n'
'\\centering\n'
'\\includegraphics[width=\linewidth]{'
f'{i}'
'}\n\\end{figure}\n'
)
pressure = (
'\\newgeometry{margin=1.5cm}\n'
'\\chapter{Pressure Data}\n'
'\\label{sec:Pressure_Data}\n'
+ data_logger.get_tabular_pressure_data()
)
plates = (
'\\chapter{Plating Data}\n'
'\\label{sec:Plating_Data}\n'
'\\newpage\n'
'\\thispagestyle{lscape}\n'
'\\pagestyle{lscape}\n'
'\\begin{landscape}\n'
+ data_logger.get_tabular_plating_data() +
'\\end{landscape}\n'
'\\thispagestyle{normal}\n'
'\\pagestyle{normal}\n'
)
stiffeners = (
'\\chapter{Stiffeners Data}\n'
'\\label{sec:Stiffeners_Data}\n'
'\\newpage\n'
'\\thispagestyle{lscape}\n'
'\\pagestyle{lscape}\n'
'\\begin{landscape}\n'
+ data_logger.get_tabular_stiffeners_data() +
'\\end{landscape}\n'
'\\thispagestyle{normal}\n'
'\\pagestyle{normal}\n'
)
stiff_plates = (
'\\clearpage'
'\\chapter{Stiffened Plates Data}\n'
'\\label{sec:Stiffened_Plates_Data}\n'
+ data_logger.get_tabular_stiffened_plates_data()
)

disclaimer = ""
if ship.symmetrical:
if data_logger.ship.symmetrical:
disclaimer = (
"Due to the vessel having a symmetrical cross section, "
"Area and Area Inertia Moments are double the stiffened plates sums.\n"
"Area and Area Inertia Moments are double the stiffened plates sums."
)

ordinary_section = (
'\\chapter{Ordinary Section\'s Stiffened Plates Data}\n'
'\\label{sec:Stiffeners Data}\n'
+ disclaimer + data_logger.get_tabular_ordinary_stiffeners_data()
particulars = particulars_data_template.substitute(data_logger.ship.map_members())
figures = TemplateFactory.substitute_template_values(figure_template, list(map(lambda o: str(o), figs)))
pressure = pressure_data_template.substitute(data=data_logger.get_tabular_pressure_data())
plates = plating_data_template.substitute(data=data_logger.get_tabular_plating_data())
stiffeners = stiffeners_data_template.substitute(data=data_logger.get_tabular_stiffeners_data())
stiffened_plates = stiffened_data_template.substitute(data=data_logger.get_tabular_stiffened_plates_data())
ordinary_section = stiffened_ordinary_data_template.substitute(
disclaimer=disclaimer,
data=data_logger.get_tabular_ordinary_stiffeners_data()
)
content = content_template.substitute(
particulars=particulars,
figures=figures,
pressure=pressure,
plates=plates,
stiffeners=stiffeners,
stiffened_plates=stiffened_plates,
ordinary_section=ordinary_section
)

mid += GeneralPart + figures + pressure + plates + stiffeners + stiff_plates + ordinary_section + '\\clearpage\\restoregeometry'

if standalone:
out = TEX_PREAMBLE + '\\begin{document}' + mid + '\\end{document}'
else:
out = mid

Logger.debug(out)
if embeddable:
Logger.debug(content)
return content

out = preamble_template.substitute(content=content)
Logger.debug(out)

return out
26 changes: 26 additions & 0 deletions modules/io/templates.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,26 @@
from string import Template
from typing import Iterable

from modules.utils.resource import Resource


class LatexTemplate(Template):
delimiter = "^^^"


class TemplateFactory:

def __init__(self):
raise RuntimeError("Cannot instantiate static factory!")

@staticmethod
def get_latex_template(*path: str) -> LatexTemplate:
"""
:param path: path of the latex template file; omit the toplevel "latex" "templates" directory
"""
with Resource("templates", "latex", *path) as tex:
return LatexTemplate(tex.handle.read())

@staticmethod
def substitute_template_values[T: Template](template: T, values: Iterable, separator: str = "\n") -> str:
return separator.join([template.substitute(v) for v in values])
11 changes: 8 additions & 3 deletions modules/utils/resource.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@
from io import TextIOWrapper
from typing import Self, Iterator

from modules.utils.logger import Logger


class FileNotOpenError(Exception):
pass
Expand Down Expand Up @@ -39,16 +41,19 @@ def __enter__(self) -> Self:
return self

def __exit__(self, exc_type, exc_val, exc_tb):
if self.file_descriptor is None:
raise RuntimeError("self.file_descriptor is none in __exit__?!")

self.close()

def open(self):
self.__cache_resource()
if not self.is_closed():
raise Logger.error("File descriptor is not closed?!")

self.file_descriptor = self.resource.open("rb" if self.bmode else "r", **self.kwargs)

def close(self):
if self.file_descriptor is None:
Logger.error("file descriptor is none?!")

if not self.file_descriptor.closed:
self.file_descriptor.close()

Expand Down
31 changes: 31 additions & 0 deletions resources/templates/latex/chapters/particulars.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
\chapter{General Input Data Particulars}
\label{ch:general-particulars}
\begin{table}[h]
\caption{Ship\'s General Input Data Particulars}
\label{tab:Gen_Part}
\begin{tabular}{{>{\centering}m{6cm}}*{2}{>{\centering}m{4cm}}}
\hline
\(L_{BP}\) &^^^LBP& [m] \tabularnewline \hline
\(L_{sc} = L\) &^^^Lsc& [m] \tabularnewline \hline
\(B\) &^^^B& [m] \tabularnewline \hline
\(T\) &^^^T& [m] \tabularnewline \hline
%! suppress = MathOperatorEscape
\(T_{min}\) &^^^Tmin& [m] \tabularnewline \hline
\(T_{sc}\) &^^^Tsc& [m] \tabularnewline \hline
\(D\) &^^^D& [m] \tabularnewline \hline
\(C_b\) &^^^Cb& \tabularnewline \hline
\(C_p\) &^^^Cp& \tabularnewline \hline
\(C_m\) &^^^Cm& \tabularnewline \hline
\(DWT\) &^^^DWT& \tabularnewline \hline
k (material factor) &^^^kappa& [m] \tabularnewline \hline
\(M_{wh}\) &^^^Mwh& [kNm] \tabularnewline \hline
\(M_{ws}\) &^^^Mws& [kNm]\tabularnewline \hline
\(M_{sw,h-mid}\) &^^^Msw_h_mid& [kNm]\tabularnewline \hline
\(M_{sw,s-mid}\) &^^^Msw_s_mid& [kNm]\tabularnewline \hline
\(C_w\) &^^^Cw& \tabularnewline \hline
\(y_{neutral}\) &^^^yo& [m]\tabularnewline \hline
\(I_{net,\, v}\) &^^^Ixx& [\(m^^^4\)]\tabularnewline \hline
\(I_{n-50,\, v}\) &^^^n50_Ixx& [\(m^^^4\)]\tabularnewline \hline
\(a_0\) &^^^a0& \tabularnewline \hline
\end{tabular}
\end{table}
10 changes: 10 additions & 0 deletions resources/templates/latex/chapters/plating_data.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
\chapter{Plating Data}
\label{ch:plating_data}
\newpage
\thispagestyle{lscape}
\pagestyle{lscape}
\begin{landscape}
^^^data
\end{landscape}
\thispagestyle{normal}
\pagestyle{normal}
4 changes: 4 additions & 0 deletions resources/templates/latex/chapters/pressure_data.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
\newgeometry{margin=1.5cm}
\chapter{Pressure Data}
\label{ch:pressure_data}
^^^data
4 changes: 4 additions & 0 deletions resources/templates/latex/chapters/stiffened_data.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
\clearpage
\chapter{Stiffened Plates Data}
\label{ch:stiffened_plates_data}
^^^data
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
\chapter{Ordinary Section\'s Stiffened Plates Data}
\label{ch:ordinary_stiffeners_data}
^^^disclaimer
^^^data
10 changes: 10 additions & 0 deletions resources/templates/latex/chapters/stiffeners_data.tex
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
\chapter{Stiffeners Data}
\label{ch:stiffeners_data}
\newpage
\thispagestyle{lscape}
\pagestyle{lscape}
\begin{landscape}
^^^data
\end{landscape}
\thispagestyle{normal}
\pagestyle{normal}
Loading