示例#1
0
def generate_tables(args):

    if args.change_directory:
        os.chdir(args.change_directory)

    config = load_experiments_config(args.config, args)

    exps = Experiment.load_all(config.experiments,
                               config_file=args.config,
                               base_path=config.options.base_path,
                               cache_dir=config.options.cache_dir,
                               seq_name_mapping=config.seq_name_mapping)

    doc = Document(geometry_options={"tmargin": "1cm", "lmargin": "1cm"})

    export_basepath = "{}-export".format(config.options.output_path)

    curr = doc

    hide_all = False
    for spec in config.results:
        if spec.show:

            if spec["class"] == "section":
                if spec.clearpage:
                    curr.append(NewPage())
                if spec.pagewidth:
                    curr.append(
                        Command("SetPageScreenWidth",
                                Arguments(spec.pagewidth)))
                else:
                    curr.append(Command("RestorePageScreenWidth"))
                hide_all = False
                curr = Section(spec.name)
                doc.append(curr)
                continue

            if hide_all:
                continue

            if spec.clearpage:
                curr.append(NewPage())

            elif spec["class"] == "results_table":
                elem = ResultsTable(
                    exps,
                    spec,
                    show_values_failed_runs=config.options.
                    show_values_failed_runs,
                    seq_displayname_mapping=config.seq_displayname_mapping,
                    export_basepath=export_basepath)
            elif spec["class"] == "summarize_sequences_table":
                elem = SummarizeSequencesTable(
                    exps,
                    spec,
                    show_values_failed_runs=config.options.
                    show_values_failed_runs,
                    seq_displayname_mapping=config.seq_displayname_mapping,
                    export_basepath=export_basepath)
            elif spec["class"] == "plot":
                elem = Plot(
                    exps,
                    spec,
                    seq_displayname_mapping=config.seq_displayname_mapping,
                    export_basepath=export_basepath)
            else:
                raise RuntimeError("Invalid results class {}".format(
                    spec["class"]))

            curr.append(elem)
        else:
            if spec["class"] == "section":
                hide_all = True
                continue

    # generate auxiliary tex files
    if config.options.screenread:
        output_dir = os.path.dirname(config.options.output_path)
        screenread_path = output_dir + "/screenread.sty"
        with open(screenread_path, "w") as f:
            f.write(screenread_sty)
        doc.packages.add(Package('screenread'))

    # create nofloatfigure environment
    doc.preamble.append(
        Command(
            "newenvironment",
            Arguments("nofloatfigure",
                      Command("captionsetup", Arguments(type="figure")), "")))
    doc.packages.add(Package('caption'))
    doc.packages.add(Package('mathtools'))

    # render latex
    doc.generate_pdf(config.options.output_path,
                     clean_tex=not args.dont_clean_tex)

    # cleanup
    if config.options.screenread and not args.dont_clean_tex:
        os.remove(screenread_path)

    # open the generated pdf
    if args.open:
        os_open_file(config.options.output_path + ".pdf")
def generate_unique(sectors_notirradiated, hv_notirradiated, spark_notirradiated):
	geometry_options = {
		"head": "40pt",
		"margin": "0.5in",
		"bottom": "1.0in",
		"includeheadfoot": True
	}
	doc = Document(indent=False,geometry_options=geometry_options)

	# Generating first page style
	first_page = PageStyle("firstpage")

	# Header image
	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:
			logo_file = os.path.join(os.path.dirname(__file__),
									 '../cernlogo.png')
			logo_wrapper.append(StandAloneGraphic(image_options="width=80px",
								filename=logo_file))

	# Add document title
	with first_page.create(Head("R")) as right_header:
		with right_header.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
								 pos='c', align='r')) as title_wrapper:
			title_wrapper.append(LargeText(bold("ATLAS New Small Wheel")))
			title_wrapper.append(LineBreak())
			title_wrapper.append(bold("Integration Tests"))
			title_wrapper.append(LineBreak())
			title_wrapper.append(bold(now.strftime("%d-%m-%Y")))
			title_wrapper.append(LineBreak())
			title_wrapper.append("\n")
			title_wrapper.append(LargeText(bold("Chamber: "+str(chambername))))
			title_wrapper.append(LineBreak())
			title_wrapper.append("ID: "+str(ID))
			title_wrapper.append(LineBreak())

	# Add footer
	with first_page.create(Foot("C")) as footer:

		with footer.create(Tabularx(
				"X X X ",
				width_argument=NoEscape(r"\textwidth"))) as footer_table:

			footer_table.add_empty_row()

			footer_table.add_hline(color="blue")

			branch_address1 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address1.append("Lorenzo Pezzotti")
			branch_address1.append("\n")
			branch_address1.append("*****@*****.**")

			branch_address2 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address2.append("Alan Peyaud")
			branch_address2.append("\n")
			branch_address2.append("*****@*****.**")

			branch_address3 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address3.append("Ivan Gnesi")
			branch_address3.append("\n")
			branch_address3.append("*****@*****.**")

			document_details = MiniPage(width=NoEscape(r"0.2\textwidth"),
										pos='t', align='r')
			document_details.append(" ")
			document_details.append(LineBreak())
			document_details.append(simple_page_number())

			footer_table.add_row([branch_address1, branch_address2,
								  branch_address3])

	doc.append(first_page)
	# End first page style
	redcircle = glob.glob("redcircle.png")
	redcircle = StandAloneGraphic(redcircle, image_options="width=220px")

	# Add customer information
	with doc.create(Tabu("X[r]")) as first_page_table:
		'''
		# Add branch information
		branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
						  align='r')
		branch.append("Chamber name: ")
		branch.append(LineBreak())
		branch.append("ID: ")
		branch.append(LineBreak())

		first_page_table.add_row([branch])
		'''
		first_page_table.add_empty_row()

	doc.change_document_style("firstpage")
	doc.add_color(name="lightgray", model="gray", description="0.85")
	doc.add_color(name="lightgray2", model="gray", description="0.6")

	with doc.create(Section('HV not irradiated', numbering=False)):
	   # Add statement table
		doc.append("\n")
		doc.append(timeslot)
		doc.append(LineBreak())
		doc.append(str(deltatime/60)+str("_min"))
		doc.append(LineBreak())
		doc.append("Spike_treshold_0.2_uA")
		doc.append(LineBreak())

		with doc.create(LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|",
								 row_height=1.5)) as data_table:
			data_table.add_hline()
			data_table.add_row(["Sector",
								"HV",
								"spark/min",
								"Efficiency",
								"Flag"],
							   mapper=bold,
							   color="lightgray2")
			data_table.add_hline()
			data_table.end_table_header()
			data_table.add_hline()
			row = ["sector", "hv","spark", "efficiency", "0 or 1"]
			acceptedlist = []
			not_acc_counter = 0
			pscolor = "blue"
			for i in range(len(hv_notirradiated)):
				if (i % 2) == 0:
					'''
					if int(hv_notirradiated[i]) > 567.9 and spark_notirradiated[i]<1.0:
						accepted = 1
						acceptedlist.append(accepted)

					else:
						accepted = 0
						acceptedlist.append(accepted)
					'''
					if int(hv_notirradiated[i]) > 567.9:
						hvcolor = "black"

					if 548.0 < int(hv_notirradiated[i]) < 567.9:
						hvcolor = "orange"

					if int(hv_notirradiated[i])< 548.0:
						hvcolor = "red"

					if spark_notirradiated[i] > 6.0:
						sparkcolor = "red"

					if spark_notirradiated[i] == 6.0:
						sparkcolor = "orange"

					if spark_notirradiated[i] < 6.0:
						sparkcolor = "black"

					if efficiency[i] < 80.0:
						effcolor = "red"

					if efficiency[i] > 80.0:
						effcolor = "black"

					if efficiency == 80.0:
						effcolor = "orange"

					if sparkcolor == "red" or hvcolor == "red" or effcolor == "red":
						acceptedcolor = "red"
						accepted = 0
						acceptedlist.append(accepted)
						not_acc_counter = not_acc_counter+1

					else:
						acceptedcolor = "black"
						accepted = 1
						acceptedlist.append(accepted)


					data_table.add_row([str(sectors_notirradiated[i]), TextColor(hvcolor,str(int(hv_notirradiated[i]))),
					TextColor(sparkcolor, str(round(spark_notirradiated[i],2))), TextColor(effcolor, str(round(efficiency[i],1))),
					TextColor(acceptedcolor, "V")])
					data_table.add_hline()
				else:
					'''
					if int(hv_notirradiated[i]) > 567.9 and spark_notirradiated[i]<1.0:
						accepted = 1
						acceptedlist.append(accepted)
					else:
						accepted = 0
						acceptedlist.append(accepted)
					'''
					if int(hv_notirradiated[i]) > 567.9:
						hvcolor = "black"

					if 548.0 < int(hv_notirradiated[i]) < 567.9:
						hvcolor = "orange"

					if int(hv_notirradiated[i])< 548.0:
						hvcolor = "red"

					if spark_notirradiated[i] > 6.0:
						sparkcolor = "red"

					if spark_notirradiated[i] == 6.0:
						sparkcolor = "orange"

					if spark_notirradiated[i] < 6.0:
						sparkcolor = "black"

					if efficiency[i] < 80.0:
						effcolor = "red"

					if efficiency[i] > 80.0:
						effcolor = "black"

					if efficiency == 80.0:
						effcolor = "orange"

					if sparkcolor == "red" or hvcolor == "red" or effcolor == "red":
						acceptedcolor = "red"
						accepted = 0
						acceptedlist.append(accepted)
						not_acc_counter = not_acc_counter+1

					else:
						acceptedcolor = "black"
						accepted = 1
						acceptedlist.append(accepted)


					data_table.add_row([str(sectors_notirradiated[i]), TextColor(hvcolor,str(int(hv_notirradiated[i]))),
					TextColor(sparkcolor, str(round(spark_notirradiated[i],2))), TextColor(effcolor, str(round(efficiency[i],1))),
					TextColor(acceptedcolor, "V")], color="lightgray")
					data_table.add_hline()

			data_table.add_hline()
			data_table.add_row("Out of spec", str(len([x for x in hv_notirradiated if x < 548.0])), str(len([x for x in spark_notirradiated if x > 6.0])), str(len([x for x in efficiency if x < 80.0])), str(not_acc_counter))

			data_table.add_empty_row()
			data_table.add_hline()
			data_table.add_row("Chamber efficiency", "","", "", str(round(total_efficiency)))
			data_table.add_hline()
			if "LM2" in chambername:
				newefficiency = efficiency
				newefficiency.pop(4)
				newefficiency.pop(4)
				newefficiency.pop(8)
				newefficiency.pop(8)
				data_table.add_row("Efficiency no LE8", "","", "", str(round(np.mean(newefficiency))))
				data_table.add_hline()

	doc.append(NoEscape('\\clearpage'))
	'''
	with doc.create(Section('Summary not irradiated', numbering=False)):
		piecart.create_pie([acceptedlist.count(1), acceptedlist.count(0)], "piechart.pdf")


		 # Add cheque images
		with doc.create(LongTabu("X[c]")) as summary1_table:
			pie = glob.iglob("piechart.pdf")
			#png_list = [StandAloneGraphic(x, image_options="width=120px") for x in png_list]
			pienew = [StandAloneGraphic(x, image_options="width=220px") for x in pie]
			summary1_table.add_row([pienew[0]])

		#here I have sectors_notirradiated, hv_notirradiated, spark_notirradiated, acceptedlist
		SM1channels = ["L1","R1","L2","R2","L3","R3","L4","R4","L5","R5"]
		SM2channels = ["L6","R6","L7","R7","L8","R8"]

		badresultsall = []
		badresultseta = []
		badresultsstereo = []

		if chambername[0:3] == "SM1":
		   channels = SM1channels
		if chambername[0:3] == "SM2":
		   channels = SM2channels
		if chambername[0:3] == "LM1":
			channels = SM1channels
		if chambername[0:3] == "LM2":
			channels = SM2channels

		for channel in channels:
		   cntall = sum(1 for x, sector in enumerate(sectors_notirradiated) if sector[2:4] == channel and acceptedlist[x] == 1)
		   cnteta = sum(1 for x, sector in enumerate(sectors_notirradiated) if sector[2:4] == channel and (sector[1:2] == "1" or sector[1:2] == "2") and acceptedlist[x] == 1)
		   cntstereo = sum(1 for x, sector in enumerate(sectors_notirradiated) if sector[2:4] == channel and (sector[1:2] == "3" or sector[1:2] == "4") and acceptedlist[x] == 1)
		   badresultsall.append(4-int(cntall))
		   badresultseta.append(2-int(cnteta))
		   badresultsstereo.append(2-int(cntstereo))

		#doc.append(NewPage())

		with doc.create(LongTabu("X[l] X[r] X[r] X[r]",
								 row_height=1.5)) as data_table2:
			data_table2.add_row(["Sector overimposed (from eta side)",
								"Eta",
								"Stereo",
								"Eta+Stereo"],
								mapper=bold,
								color="lightgray2")
			data_table2.add_empty_row()
			data_table2.add_hline()
			row = ["Sector (all layers)", "Out of spec (Eta)", "Out of spec (Stereo)", "Out of spec (E+S)"]

			for i in range(len(channels)):
				if (i % 2) == 0:
					data_table2.add_row([str(channels[i]), str(int(badresultseta[i])), str(badresultsstereo[i]), badresultsall[i]], color="lightgray")
				else:
					data_table2.add_row([str(channels[i]), str(int(badresultseta[i])), str(badresultsstereo[i]), badresultsall[i]])

		with doc.create(LongTabu("X[l] X[r]",
								 row_height=1.5)) as data_table3:
			data_table3.add_row(["Layer",
								"Mean Efficiency"],
								mapper=bold,
								color="lightgray2")
			data_table3.add_empty_row()
			data_table3.add_hline()
			row = ["layers", "efficiency"]
			channelsT3 = ["L1", "L2", "L3", "L4"]
			for i in range(len(layers_efficiency)):
				if (i % 2) == 0:
					data_table3.add_row([str(channelsT3[i]), str(round(layers_efficiency[i],1))], color="lightgray")
				else:
					data_table3.add_row([str(channelsT3[i]), str(round(layers_efficiency[i],1))])
	'''
	doc.append(NewPage())

	with doc.create(Section('Current with no irradiation', numbering=False)):

	# Add cheque images
		with doc.create(LongTabu("X[c] X[c] X[c] X[c]")) as cheque_table:
			png_list = glob.glob('BB5-i*.pdf')
			png_list.sort(key=os.path.getmtime)
			png_list = [StandAloneGraphic(x, image_options="width=120px") for x in png_list]
			print len(png_list)
			row_image = []
			i = 0
			for image in png_list:
				row_image.append(image)
				i = i +1
				if i==4:
					cheque_table.add_row([row_image[0], row_image[1], row_image[2], row_image[3]])
					row_image = []
					i=0

	png_list = []
	doc.generate_pdf("complex_report", clean_tex=False, compiler='pdflatex')
示例#3
0
def generate_unique_dw(final_hvs, hl1, hl2, sectors):
	geometry_options = {
		"head": "40pt",
		"margin": "0.5in",
		"bottom": "1.0in",
		"includeheadfoot": True
	}
	doc = Document(indent=False,geometry_options=geometry_options)

	# Generating first page style
	first_page = PageStyle("firstpage")

	# Header image
	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:
			logo_file = os.path.join(os.path.dirname(__file__),
									 '../cernlogo.png')
			logo_wrapper.append(StandAloneGraphic(image_options="width=80px",
								filename=logo_file))

	# Add document title
	with first_page.create(Head("R")) as right_header:
		with right_header.create(MiniPage(width=NoEscape(r"0.49\textwidth"),
								 pos='c', align='r')) as title_wrapper:
			title_wrapper.append(LargeText(bold("ATLAS New Small Wheel")))
			title_wrapper.append(LineBreak())
			title_wrapper.append(bold("Integration Tests"))
			title_wrapper.append(LineBreak())
			title_wrapper.append(bold(now.strftime("%d-%m-%Y")))
			title_wrapper.append(LineBreak())
			title_wrapper.append("\n")
			title_wrapper.append(LargeText(bold("Double Wedge: "+str(DW_name))))
			title_wrapper.append(LineBreak())
			title_wrapper.append("\n")
			title_wrapper.append(LargeText(bold("Chambers: "+str(chambername1IP))))
			title_wrapper.append(LineBreak())
			title_wrapper.append(LargeText(bold("          "+str(chambername2IP))))
			title_wrapper.append(LineBreak())
			title_wrapper.append(LargeText(bold("          "+str(chambername1HO))))
			title_wrapper.append(LineBreak())
			title_wrapper.append(LargeText(bold("          "+str(chambername2HO))))
			title_wrapper.append(LineBreak())


	# Add footer
	with first_page.create(Foot("C")) as footer:

		with footer.create(Tabularx(
				"X X X ",
				width_argument=NoEscape(r"\textwidth"))) as footer_table:

			footer_table.add_empty_row()

			footer_table.add_hline(color="blue")

			branch_address1 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address1.append("Lorenzo Pezzotti")
			branch_address1.append("\n")
			branch_address1.append("*****@*****.**")

			branch_address2 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address2.append("Alan Peyaud")
			branch_address2.append("\n")
			branch_address2.append("*****@*****.**")

			branch_address3 = MiniPage(
				width=NoEscape(r"0.25\textwidth"),
				pos='t')
			branch_address3.append("Ivan Gnesi")
			branch_address3.append("\n")
			branch_address3.append("*****@*****.**")

			document_details = MiniPage(width=NoEscape(r"0.2\textwidth"),
										pos='t', align='r')
			document_details.append(" ")
			document_details.append(LineBreak())
			document_details.append(simple_page_number())

			footer_table.add_row([branch_address1, branch_address2,
								  branch_address3])

	doc.append(first_page)
	# End first page style
	redcircle = glob.glob("redcircle.png")
	redcircle = StandAloneGraphic(redcircle, image_options="width=220px")

	# Add customer information
	with doc.create(Tabu("X[r]")) as first_page_table:
		first_page_table.add_empty_row()

	doc.change_document_style("firstpage")
	doc.add_color(name="lightgray", model="gray", description="0.80")
	doc.add_color(name="lightgray2", model="gray", description="0.6")

	# IP
	with doc.create(Section('IP SIDE', numbering=False)):
		# first chamber
		# Verify if its SM1, LM1, SM1 or LM2
		if chambername1IP[0:3] == "SM1" or chambername1IP[0:3] == "LM1":
			limit = 10
		else:
			limit = 6

		with doc.create(Subsection("Chambers: "+chambername1IP+" + "+chambername2IP, numbering=False)):
			with doc.create(Subsection(chambername1IP, numbering=False)):
				doc.append("\n")
				doc.append(timeslots[0])
				doc.append(LineBreak())
				with doc.create(LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
										 row_height=1.5)) as data_table:
						data_table.add_hline()
						data_table.add_row(["Sector",
											"L1",
											"L2",
											"L3",
											"L4",
											"HL1",
											"HL2"],
										   mapper=bold,
										   color="lightgray2")
						data_table.add_hline()
						data_table.end_table_header()
						data_table.add_hline()
						row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
						for i, hv in enumerate(final_hvs[0]):
							hl1_str = ""
							hl2_str = ""
							l1 = ""
							l2 = ""
							l3 = ""
							l4 = ""
							# assign each sector to a line
							if hv == hl1[0]:
								hl1_str = str(hl1[0])
							elif hv == hl2[0]:
								hl2_str = str(hl2[0])
							elif i > limit-1+limit*2:
								l4 = "570"
							elif i > limit-1+limit:
								l3 = "570"
							elif i > limit-1:
								l2 = "570"
							else:
								l1 = "570"
							if (i % 2) == 0:
								data_table.add_row([str(sectors[0][i]), l1, l2, l3, l4, hl1_str, hl2_str])
							else:
								data_table.add_row([str(sectors[0][i]), l1, l2, l3, l4, hl1_str, hl2_str],color="lightgray")
						data_table.add_hline()

			# second chamber
			if chambername2IP[0:3] == "SM1" or chambername2IP[0:3] == "LM1":
				limit = 10
			else:
				limit = 6
			with doc.create(Subsection(chambername2IP, numbering=False)):
				doc.append("\n")
				doc.append(timeslots[1])
				doc.append(LineBreak())
				with doc.create(LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
										 row_height=1.5)) as data_table2:
						data_table2.add_hline()
						data_table2.add_row(["Sector",
											"L5",
											"L6",
											"L7",
											"L8",
											"HL3",
											"HL4"],
										   mapper=bold,
										   color="lightgray2")
						data_table2.add_hline()
						data_table2.end_table_header()
						data_table2.add_hline()
						row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
						for i, hv in enumerate(final_hvs[1]):
							hl1_str = ""
							hl2_str = ""
							l1 = ""
							l2 = ""
							l3 = ""
							l4 = ""
							# assign each sector to a line
							if hv == hl1[1]:
								hl1_str = str(hl1[1])
							elif hv == hl2[1]:
								hl2_str = str(hl2[1])
							elif i > limit-1+limit*2:
								l4 = "570"
							elif i > limit-1+limit:
								l3 = "570"
							elif i > limit-1:
								l2 = "570"
							else:
								l1 = "570"

							if (i % 2) == 0:
								data_table2.add_row([str(sectors[1][i]), l1, l2, l3, l4, hl1_str, hl2_str])
							else:
								data_table2.add_row([str(sectors[1][i]), l1, l2, l3, l4, hl1_str, hl2_str],color="lightgray")
						data_table2.add_hline()
	# HO
	# Swap R an L
	final_hvs[2] = swap(final_hvs[2])
	final_hvs[3] = swap(final_hvs[3])
	if chambername1HO[0:3] == "SM1" or chambername1HO[0:3] == "LM1":
		limit = 10
	else:
		limit = 6
	doc.append(NewPage())
	with doc.create(Section('HO SIDE', numbering=False)):
		# first chamber
		with doc.create(Subsection("Chambers: "+chambername1HO+" + "+chambername2HO, numbering=False)):
			with doc.create(Subsection(chambername1HO, numbering=False)):
				doc.append("\n")
				doc.append(timeslots[2])
				doc.append(LineBreak())
				with doc.create(LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
										 row_height=1.5)) as data_table3:
						data_table3.add_hline()
						data_table3.add_row(["Sector",
											"L1",
											"L2",
											"L3",
											"L4",
											"HL1",
											"HL2"],
										   mapper=bold,
										   color="lightgray2")
						data_table3.add_hline()
						data_table3.end_table_header()
						data_table3.add_hline()
						row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
						for i, hv in enumerate(final_hvs[2]):
							hl1_str = ""
							hl2_str = ""
							l1 = ""
							l2 = ""
							l3 = ""
							l4 = ""
							# assign each sector to a line
							if hv == hl1[2]:
								hl1_str = str(hl1[2])
							elif hv == hl2[2]:
								hl2_str = str(hl2[2])
							elif i > limit-1+limit*2:
								l4 = "570"
							elif i > limit-1+limit:
								l3 = "570"
							elif i > limit-1:
								l2 = "570"
							else:
								l1 = "570"
							if (i % 2) == 0:
								data_table3.add_row([str(sectors[2][i]), l1, l2, l3, l4, hl1_str, hl2_str])
							else:
								data_table3.add_row([str(sectors[2][i]), l1, l2, l3, l4, hl1_str, hl2_str],color="lightgray")
						data_table3.add_hline()

			# second chamber
			if chambername2HO[0:3] == "SM1" or chambername2HO[0:3] == "LM1":
				limit = 10
			else:
				limit = 6
			with doc.create(Subsection(chambername2HO, numbering=False)):
				doc.append("\n")
				doc.append(timeslots[3])
				doc.append(LineBreak())
				with doc.create(LongTabu("|X[l]|X[r]|X[r]|X[r]|X[r]|X[r]|X[r]|",
										 row_height=1.5)) as data_table4:
						data_table4.add_row(["Sector",
											"L5",
											"L6",
											"L7",
											"L8",
											"HL3",
											"HL4"],
										   mapper=bold,
										   color="lightgray2")
						data_table4.add_hline()
						data_table4.end_table_header()
						data_table4.add_hline()
						row = ["blank", "l1", "l2", "l3", "l4", "hl1", "hl2"]
						for i, hv in enumerate(final_hvs[3]):
							hl1_str = ""
							hl2_str = ""
							l1 = ""
							l2 = ""
							l3 = ""
							l4 = ""
							# assign each sector to a line
							if hv == hl1[3]:
								hl1_str = str(hl1[3])
							elif hv == hl2[3]:
								hl2_str = str(hl2[3])
							elif i > limit-1+limit*2:
								l4 = "570"
							elif i > limit-1+limit:
								l3 = "570"
							elif i > limit-1:
								l2 = "570"
							else:
								l1 = "570"

							if (i % 2) == 0:
								data_table4.add_row([str(sectors[3][i]), l1, l2, l3, l4, hl1_str, hl2_str])
							else:
								data_table4.add_row([str(sectors[3][i]), l1, l2, l3, l4, hl1_str, hl2_str],color="lightgray")
						data_table4.add_hline()

	doc.append(NewPage())
	with doc.create(Section('Probability of dectecting the particle in at least 6 layers', numbering=False)):
		with doc.create(LongTabu("|X[l]|X[r]|X[r]|X[r]|",
								 row_height=1.5)) as data_table5:
				data_table5.add_hline()
				data_table5.add_row(["Sector",
									"Probability",
									"Sector",
									"Probability"],
								   mapper=bold,
								   color="lightgray2")
				data_table5.add_hline()
				row = ["L#", "probability", "R#", "probability"]
				j = 0
				for i in range(len(sector_probabilities)/2):
					if (i % 2) == 0:
						data_table5.add_row(["L" + str(i+1), round(sector_probabilities[j],5), "R" + str(i+1), round(sector_probabilities[j+1],5)])
					else:
						data_table5.add_row(["L" + str(i+1), round(sector_probabilities[j],5), "R" + str(i+1), round(sector_probabilities[j+1],5)],color="lightgray")
					j = j + 2
				data_table5.add_hline()

	doc.generate_pdf("complex_report_DW", clean_tex=False, compiler='pdflatex')
示例#4
0
def add_first_page(io_doc, i_title, i_authors):
    io_doc.preamble.append(Command('title', i_title))
    io_doc.preamble.append(Command('author', i_authors))
    io_doc.preamble.append(Command('date', NoEscape(r'\today')))
    io_doc.append(NoEscape(r'\maketitle'))
    io_doc.append(NewPage())
示例#5
0
    def fill(self):
        # with self.doc.create(Section("{} library.".format(self.config['hdl_library_name']))):
        # with self.doc.create(Section("{} library".format(self.periph_lib_name))):
        # main_section = Section("{} library".format(self.periph_lib_name))
        # self.doc.append(LargeText(bold('{} library'.format(self.periph_lib_name))))
        # periph_section = Section("Peripherals", numbering = False)
        # i = 1
        # for periph_name in self.periph_lib['peripherals'].keys():
        # self.doc.append("{} {}".format(str(i), periph_name))
        # i = i+1
        # self.doc.append(NewLine())
        # with self.doc.create(Section("Peripherals")):
        added_instances = []
        # for peri_info in self.config['peripherals']:
        # peri_class = Peripheral(peri_info)
        for periph_name, periph in self.periph_lib['peripherals'].items():
            if periph_name in added_instances:
                continue
            added_instances.append(periph_name)

            # with self.doc.create(Section(periph_name, numbering=True)):
            # with self.doc.create(Subsection(periph_name, numbering=True)):
            # self.doc.append(peri_class.get_kv('peripheral_description').replace('"', ''))
            self.doc.append(NewPage())
            periph_subsection = Section(periph_name, numbering=True)
            periph_subsection.append(periph.get_description().replace(
                '""', ''))

            # Peripheral System Map Table
            periph_subsection.append(NewLine())
            periph_subsection.append(NewLine())
            periph_subsection.append(MediumText(bold('Local Slave Port Map')))
            periph_subsection.append(NewLine())
            periph_subsection.append(NewLine())
            periph_system_table = Tabular('|c|c|c|c|')
            # periph_system_table.add_row((MultiColumn(4,data=MediumText(bold('System Map'))),))
            periph_system_table.add_hline()
            periph_system_table.add_row(
                ('Hex', 'Range (Bytes)', 'Slave Port', 'Protocol'))
            periph_system_table.add_hline()

            # peripheral system address map
            dummyFPGA = FPGA(None)
            dummyFPGA.peripherals.update({periph_name: periph})
            dummyFPGA.create_address_map()
            # for slave in periph.slaves:
            for slave_port, slave_dict in dummyFPGA.address_map.items():
                periph_system_table.add_row(
                    (str(hex(slave_dict['base'])), str(slave_dict['span']),
                     slave_port, slave_dict['type']))
                periph_system_table.add_hline()
            periph_subsection.append(periph_system_table)

            # self.doc.append(periph.get_description().replace('""',''))
            # self.doc.append(NewLine())

            #self.doc.append(MediumText(bold("slave ports.")))

            # for val_info, val_type in ((periph.registers, 'Registers'),
            # (periph.rams, 'Rams'),
            # (periph.fifos, 'Fifos')):
            periph_reg_section = Subsection(
                "{} register slave".format(periph_name), numbering=False)
            periph_reg_table = Tabular('|c|c|c|c|')
            periph_reg_table.add_hline()
            periph_reg_table.add_row(('Base Address', 'Range',
                                      'Register group', 'Number of Slaves'))
            periph_reg_table.add_hline()
            # slave_subsections = ("{} slaves".format(periph_name), numbering=False)
            # slave_subsections = []
            # slave_subsections.append(NewLine())
            # slave_subsections.append(MediumText(bold("Slave Ports for peripheral " + periph_name + "\n")))
            slave_subsections = Subsection(
                "Slave Ports for peripheral \'{}\'".format(periph_name),
                numbering=False)
            for slave in periph.slaves:

                # if len(val_info) == 0: # not sure what this is for
                # continue

                #self.doc.add(text=val_type, size="medium")

                # added_val_types = []
                # for key, val in sorted(val_info.items()):
                # if val.name() in added_val_types:
                # continue
                # added_val_types.append(val.name())
                slave_subsection = Subsection("Slave Port: {} ({})".format(
                    slave.name(),
                    'Register block' if isinstance(slave, Register) else
                    'RAM' if isinstance(slave, RAM) else 'FIFO'),
                                              numbering=True)
                slave_subsection.append(slave.get_kv('slave_description'))
                slave_subsection.append(NewLine())
                # slave_subsection.append("Slave Type: {}".format('REGISTER' if isinstance(slave, Register) else 'RAM' if isinstance(slave, RAM) else 'FIFO'))
                slave_subsection.append(NewLine())
                slave_subsection.append("Address Length: {}".format(
                    str(slave.address_length())))
                slave_subsection.append(NewLine())
                slave_subsection.append("Number of Slaves: {}".format(
                    str(slave.number_of_slaves())))
                slave_subsection.append(NewLine())
                slave_subsection.append(NewLine())

                # if val_type == 'Registers':
                if isinstance(slave, Register):  # expand registers and fields
                    for ram in slave.rams:
                        periph_reg_table.add_row(
                            (str(ram.base_address()),
                             str(ram.number_of_fields() * WIDTH_IN_BYTES),
                             ram.name() + ' (RAM)',
                             str(slave.number_of_slaves())))
                        periph_reg_table.add_hline()
                    periph_reg_table.add_row(
                        (str(slave.base_address()),
                         str(slave.address_length()), slave.name(),
                         str(slave.number_of_slaves())))
                    periph_reg_table.add_hline()
                    added_field_groups = []
                    # with self.doc.create(Subsection("{} Register Fields".format(val.name().lower()), numbering=True)):
                    # if val.get_kv('slave_description') is not None:
                    # slave_subsection.append(val.get_kv('slave_description').replace('"', ''))

                    # generate register table i.e. by word
                    group_address = -1
                    group_list = []
                    for field in slave.fields:
                        if field.address_offset() != group_address:
                            group_address = field.address_offset()
                            group_list.append(field)
                            # addr_name = field.group_name() if field.group_name() != "None" else field.name()

                            # slave_table.add_row(str(hex(field.address_offset())), addr_name)
                            # slave_table.add_hline()
                    c_max_rows = 30
                    nof_cols = ceil(
                        len(group_list) / c_max_rows
                    )  # register table has max length of c_max_rows
                    nof_rows = min(len(group_list), c_max_rows)
                    slave_table = Tabular('|c|c|' * nof_cols)
                    slave_table.add_hline()
                    slave_table.add_row(['Hex', 'Field Group'] * nof_cols)
                    # slave_table.add_row((*['Hex','Field Group']*nof_cols))
                    slave_table.add_hline()
                    for i in range(nof_rows):
                        row = []
                        for j in range(nof_cols):
                            if i + c_max_rows * j < len(group_list):
                                field.group_name() if field.group_name(
                                ) != "None" else field.name()
                                row.extend([
                                    str(
                                        hex(group_list[i + c_max_rows *
                                                       j].address_offset())),
                                    group_list[i + c_max_rows * j].name()
                                ])
                            else:
                                row.extend(['', ''])
                        slave_table.add_row(row)
                        # slave_table.add_row(*row)
                        slave_table.add_hline()

                    slave_subsection.append(slave_table)
                    slave_subsection.append(NewPage())

                    group_address = -1
                    for field in slave.fields:
                        # if field.group_name() is None or field.group_name() != last_group: # base on group_address instead
                        # print("field {} address {} bit{}".format(field.name(), str(field.address_offset()), str(field.bit_offset())))
                        if field.address_offset() != group_address:
                            group_address = field.address_offset()
                            # group_page = MiniPage()
                            group_subsection = Subsection('{} {}'.format(
                                str(hex(field.address_offset())),
                                field.name() if field.group_name() == 'None'
                                else field.group_name()),
                                                          numbering=False)
                            group_fields = [
                                field for field in slave.fields
                                if field.address_offset() == group_address
                            ]
                            if len(group_fields) > 10:
                                slave_subsection.append(NewPage())
                            group_subsection = gen_reg_tables(
                                group_subsection, group_fields)
                            for field in group_fields[::-1]:
                                field_name = field.name() if field.group_name(
                                ) == 'None' else field.name().split(
                                    field.group_name() + '_')[-1]
                                bit_string = "Bit {}".format(
                                    str(field.bit_offset())) if field.width(
                                    ) == 1 else "Bits {}:{}".format(
                                        str(field.bit_offset() +
                                            field.width() -
                                            1), str(field.bit_offset()))
                                group_subsection.append(
                                    bold("{}\t\t{} ({}):".format(
                                        bit_string, field_name,
                                        field.access_mode())))
                                group_subsection.append("\t\t{}".format(
                                    field.field_description()))
                                group_subsection.append(NewLine())
                                group_subsection.append(NewLine())
                            # group_page.append(group_subsection)
                            slave_subsection.append(group_subsection)
                else:  # RAM or FIFO
                    slave_subsection.append("Data width: {}".format(
                        slave.width()))
                    slave_subsection.append(NewLine())
                    if isinstance(slave, RAM):
                        slave_subsection.append("User data width: {}".format(
                            slave.user_width()))

                slave_subsections.append(slave_subsection)
            periph_reg_section.append(periph_reg_table)
            self.doc.append(periph_subsection)
            if any([isinstance(slave, Register) for slave in periph.slaves]):
                self.doc.append(periph_reg_section)
            # for i in range(len(slave_subsections)):
            # self.doc.append(slave_subsections[i])
            self.doc.append(slave_subsections)

            # self.doc.append(periph_section)
            self.doc.append(NewPage())
示例#6
0
def seismicity(doc,
               year1,
               month1,
               t,
               lc,
               reg,
               pac,
               car,
               volc,
               imp,
               sub_list=[["1"], ["1"], ["0"], ["0"]]):
    """Add seismicity section to the document.

    :param doc: the document
    :type doc: :class:`pylatex.document.Document` instance
    :param fun_map: name of the functioning map
    :type doc: :string:
    """
    print sub_list
    doc.append(NewPage())
    sec_sismicicdad = open(ruta + "bulletfiles/seccion_sismicidad_mes.txt",
                           "r").read()

    #doc.append(NoEscape(r"\chapterimage{"+ruta+"bulletfiles/sgc_blanco2.jpg}"))
    doc.append(
        NoEscape(r"\chapter{SISMICIDAD \textcolor{sgc2}{DE %s} \\DE %s}" %
                 (month1.upper(), year1)))

    # agregando texto desde archivo
    doc.append(NoEscape(r"\noindent "))
    doc.append(sec_sismicicdad % (month1, t, lc, reg, pac, car, volc, imp))
    with doc.create(Enumerate()) as enum:

        enum.add_item("El sismo tiene una profundidad menor a 120 km y \
	  su magnitud (ML) es mayor o igual a 4.0 en la escala de \
	  Richter o su magnitud de momento (Mw) es mayor o igual 4.0.")

        enum.add_item("El sismo tiene una profundidad mayor o igual \
	  a 120 km y su magnitud (ML) es mayor o igual a 5.0 en la \
	  escala de Richter o su magnitud de momento (Mw) es mayor o igual 5.0.")
        enum.add_item("El sismo es reportado como sentido cerca al epicentro, \
	  sin importar su magnitud o su profundidad.")

    with doc.create(Center()):
        doc.append(NoEscape(r"\sffamily\textcolor{ocre}{Convenciones}"))
    with doc.create(Tabular('ll')) as table:
        table.add_row((bold('FECHA'), "Año Mes Día"))
        table.add_row((bold('H:M:S'),
                       SmallText('Hora:Minuto:Segundo. Hora del \
	  evento en tiempo universal (UT).')))
        table.add_row((
            bold(''),
            SmallText(
                "Para la hora local en el territorio Colombiano se restan 5 horas."
            )))
        table.add_row((bold(''), SmallText("a la hora UT.")))
        table.add_row((bold('LAT'), SmallText("Latitud en grados.")))
        table.add_row((bold('LON'), SmallText("Longitud en grados.")))
        table.add_row((bold('Z'), SmallText("Profundidad en kilometros.")))
        table.add_row((bold('M'), "Magnitud del evento."))
        table.add_row((bold('UBICACION'), SmallText("Epicentro del evento.")))

    # =======================================================================
    #  tabla de sismicidad destacada
    # =======================================================================
    if sub_list[0][0] == "1":
        # tabla con eventos destacados
        doc.append(NoEscape(r"\newpage"))
        doc.append(
            NoEscape(r"\section{Tabla de sismicidad destacada %s de %s}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\vspace{0.8cm}"))

        data_list = sc_table("sc_destacados.out")

        with doc.create(
                LongTabu(
                    "X[1.3,c] X[1.2,c] X[c] X[1.1,c] X[0.4,c] X[0.4,c] X[4,l]",
                    row_height=1)) as data_table:
            data_table.add_row(
                NoEscape(r"\scriptsize\sffamily\bfseries FECHA"),
                NoEscape(r"\scriptsize\sffamily\bfseries H:M:S"),
                NoEscape(r"\scriptsize\sffamily\bfseries LAT"),
                NoEscape(r"\scriptsize\sffamily\bfseries LON"),
                NoEscape(r"\scriptsize\sffamily\bfseries Z"),
                NoEscape(r"\scriptsize\sffamily\bfseries M"),
                NoEscape(r"\scriptsize\sffamily\bfseries UBICACION"),
                color="sgc2")
            #data_table.add_empty_row()
            data_table.end_table_header()

            # para cada elemento en la lista list_to_table (lista con info de destacados)
            for i in range(len(data_list)):
                if (i % 2) == 0:
                    data_table.add_row(Command("tiny", data_list[i][0]),
                                       Command("tiny", data_list[i][1]),
                                       Command("tiny", data_list[i][2]),
                                       Command("tiny", data_list[i][3]),
                                       Command("tiny", data_list[i][4]),
                                       Command("tiny", data_list[i][5]),
                                       Command("tiny", data_list[i][6]),
                                       color="sgc2!20")
                else:
                    data_table.add_row(Command("tiny", data_list[i][0]),
                                       Command("tiny", data_list[i][1]),
                                       Command("tiny", data_list[i][2]),
                                       Command("tiny", data_list[i][3]),
                                       Command("tiny", data_list[i][4]),
                                       Command("tiny", data_list[i][5]),
                                       Command("tiny", data_list[i][6]))
            doc.append(
                NoEscape(r"\caption{Eventos destacados durante %s de %s}" %
                         (month1, year1)))

    # =======================================================================
    #  mapa de sismicidad destacada
    # =======================================================================
    if sub_list[1][0] == "1":
        file_inspector(sub_list[1][1])
        doc.append(NoEscape(r"\begin{figure}"))
        doc.append(NoEscape(r"\begin{minipage}{\textwidth}"))
        doc.append(
            NoEscape(r"\section{Mapa de sismicidad destacada %s de %s}" %
                     (month1, year1)))
        #		doc.append(NoEscape(r"\vspace{-1.5cm}"))
        doc.append(NoEscape(r"\begin{center}"))
        doc.append(
            NoEscape(r"\includegraphics[scale=0.18]{%s}\\" % sub_list[1][1]))
        doc.append(
            NoEscape(r"\caption{\small{Eventos destacados durante %s de %s}}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\end{center}"))
        #		doc.append(NoEscape(r"\vspace{-1.5cm}"))
        add_text(sub_list[1][2], doc)
        doc.append(NoEscape(r"\end{minipage}"))
        doc.append(NoEscape(r"\end{figure}"))

    # =======================================================================
    #  tabla de sismicidad mensual
    # =======================================================================
    if sub_list[2][0] == "1":

        doc.append(NoEscape(r"\newpage"))
        doc.append(
            NoEscape(r"\section{Tabla de sismicidad mensual %s de %s}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\vspace{0.8cm}"))
        data_list = sc_table("sc_mensual.out")
        with doc.create(
                LongTabu(
                    "X[1.3,c] X[1.2,c] X[c] X[1.1,c] X[0.4,c] X[0.4,c] X[4,l]",
                    row_height=1)) as data_table:
            data_table.add_row(
                NoEscape(r"\scriptsize\sffamily\bfseries FECHA"),
                NoEscape(r"\scriptsize\sffamily\bfseries H:M:S"),
                NoEscape(r"\scriptsize\sffamily\bfseries LAT"),
                NoEscape(r"\scriptsize\sffamily\bfseries LON"),
                NoEscape(r"\scriptsize\sffamily\bfseries Z"),
                NoEscape(r"\scriptsize\sffamily\bfseries M"),
                NoEscape(r"\scriptsize\sffamily\bfseries UBICACION"),
                color="sgc2")
            #data_table.add_empty_row()
            data_table.end_table_header()

            # para cada elemento en la lista list_to_table (lista con info de destacados)
            for i in range(len(data_list)):
                if (i % 2) == 0:
                    data_table.add_row(Command("tiny", data_list[i][0]),
                                       Command("tiny", data_list[i][1]),
                                       Command("tiny", data_list[i][2]),
                                       Command("tiny", data_list[i][3]),
                                       Command("tiny", data_list[i][4]),
                                       Command("tiny", data_list[i][5]),
                                       Command("tiny", data_list[i][6]),
                                       color="sgc2!20")
                else:
                    data_table.add_row(Command("tiny", data_list[i][0]),
                                       Command("tiny", data_list[i][1]),
                                       Command("tiny", data_list[i][2]),
                                       Command("tiny", data_list[i][3]),
                                       Command("tiny", data_list[i][4]),
                                       Command("tiny", data_list[i][5]),
                                       Command("tiny", data_list[i][6]),
                                       color="white")
            doc.append(
                NoEscape(r"\caption{Eventos durante %s de %s}" %
                         (month1, year1)))

    # =======================================================================
    #  mapa de sismicidad mensual
    # =======================================================================
    if sub_list[3][0] == "1":
        print sub_list[3][1]
        print sub_list[3][2]
        file_inspector(sub_list[3][1])
        doc.append(NoEscape(r"\begin{figure}"))
        doc.append(NoEscape(r"\begin{minipage}{\textwidth}"))
        doc.append(
            NoEscape(r"\section{Mapa de sismicidad mensual %s de %s}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\begin{center}"))
        #		doc.append(NoEscape(r"\vspace{-1.5cm}"))
        doc.append(
            NoEscape(r"\includegraphics[scale=0.18]{%s}" % sub_list[3][1]))
        doc.append(
            NoEscape(r"\caption{\small{Eventos durante %s de %s}}" %
                     (month1, year1)))
        doc.append(NoEscape(r"\end{center}"))
        #		doc.append(NoEscape(r"\vspace{-1.5cm}"))
        add_text(sub_list[3][2], doc)
        doc.append(NoEscape(r"\end{minipage}"))
        doc.append(NoEscape(r"\end{figure}"))
示例#7
0
def make_pdf_report():
    """ assume profile available """

    pieces = gd.sessionInfo['Pieces']
    cntrating = [cr for nm, x, cr, tl in pieces]

    # we need a (single) temp dir for intermediates.
    tmpdir = Path(tempfile.gettempdir()) / 'RtcApp'
    if not tmpdir.is_dir():
        tmpdir.mkdir()
    # subdir
    if not reportsDir().is_dir():
        reportsDir().mkdir()

    reportfile = reportsDir() / gd.config['Session']

    crewname = gd.metaData['CrewName']

    geometry_options = {
        "top": "5mm",
        "bottom": "5mm",
        "right": "5mm",
        "left": "5mm"
    }
    doc = Document(documentclass='article',
                   geometry_options=geometry_options,
                   document_options=["12pt"])

    doc.preamble.append(NoEscape(r'\usepackage{graphicx}'))

    # see https://doc.qt.io/qt-5/qml-color.html for colors
    doc.append(NoEscape(r'\definecolor{aquamarine}{HTML}{7fffd4}'))
    doc.append(NoEscape(r'\definecolor{gainsboro}{HTML}{dcdcdc}'))

    #   First page
    with doc.create(
            Section(f'Boat report {gd.metaData["CrewName"]}',
                    numbering=False)):

        r = gd.metaData["Rowers"]
        rwrcnt = gd.sessionInfo['RowerCnt']
        if rwrcnt == 1:
            doc.append('Rowers: ')
            doc.append(f'{r[0][0]} ')
        else:
            doc.append('Rowers from bow: ')
            for i in range(rwrcnt):
                doc.append(f'{r[i][0]}, ')
        doc.append(NewLine())
        doc.append(f'Boattype: {gd.metaData["BoatType"]}\n')
        doc.append(f'Calibration: {gd.metaData["Calibration"]}\n')
        doc.append(f'Misc: {gd.metaData["Misc"]}\n')
        doc.append(f'Powerline: {gd.metaData["PowerLine"]}\n')
        doc.append(f'Venue: {gd.metaData["Venue"]}\n')
        doc.append(VerticalSpace("5pt"))
        doc.append(NewLine())

        # get table from boat report
        rows = gd.boattablemodel.rowCount()
        columns = gd.boattablemodel.columnCount()
        boattab = 'l|' + ''.join(['r' for i in range(columns - 1)]) + '|'
        with doc.create(Tabular(boattab)) as table:
            table.add_hline()
            row = []
            for j in range(columns):
                index = QAbstractTableModel.index(gd.boattablemodel, 0, j)
                row.append(str(gd.boattablemodel.data(index)))
            table.add_row(row, color='aquamarine')
            table.add_hline()

            cnt = 0
            for i in range(rows):
                row = []
                if i == 0:
                    continue
                for j in range(columns):
                    index = QAbstractTableModel.index(gd.boattablemodel, i, j)
                    row.append(str(gd.boattablemodel.data(index)))
                if cnt % 2 == 0:
                    table.add_row(row, color='gainsboro')
                else:
                    table.add_row(row, color='aquamarine')
                cnt += 1
            table.add_hline()
            """

            table.add_empty_row()
            table.add_row((4, 5, 6, 7))
            """
    doc.append(NewPage())

    # for the plots
    fontP = FontProperties()
    fontP.set_size('xx-small')

    # Second page
    with doc.create(
            Section(f'Boat report {gd.metaData["CrewName"]}',
                    numbering=False)):

        av = ''
        filt = ''
        if gd.averaging:
            av = 'averaging'
        if gd.filter:
            filt = 'filtered'
        pcs = ['all'] + gd.p_names + ['average']
        doc.append(f'Using piece "{pcs[gd.boatPiece]}": {av} {filt}\n')
        doc.append(VerticalSpace("5pt"))
        doc.append(NewLine())

        sensors = gd.sessionInfo['Header']
        fig, ((ax1, ax2), (ax3, ax4)) = plt.subplots(nrows=2, ncols=2)

        ax1.set_title('Speed')
        ax1.grid(True)
        ax2.set_title('Acceleration')
        ax2.grid(True)
        ax3.set_title('Pitch')
        ax3.grid(True)
        ax4.set_title('Accel-Tempo per Piece')
        ax4.grid(True)

        piece = gd.boatPiece
        if piece == 0:
            for i in range(len(gd.p_names)):
                ax1.plot(gd.norm_arrays[i, :, sensors.index('Speed')],
                         linewidth=0.6,
                         label=gd.p_names[i])
                ax2.plot(gd.norm_arrays[i, :, sensors.index('Accel')],
                         linewidth=0.6,
                         label=gd.p_names[i])
                ax3.plot(gd.norm_arrays[i, :,
                                        sensors.index('Pitch Angle')],
                         linewidth=0.6,
                         label=gd.p_names[i])
        elif piece == 7:
            speed = np.zeros(gd.norm_arrays[0, :, 1].shape)
            accel = np.zeros(gd.norm_arrays[0, :, 1].shape)
            pitch = np.zeros(gd.norm_arrays[0, :, 1].shape)
            for i in range(len(gd.p_names)):
                speed += gd.norm_arrays[i, :, sensors.index('Speed')]
                accel += gd.norm_arrays[i, :, sensors.index('Accel')]
                pitch += gd.norm_arrays[i, :, sensors.index('Pitch Angle')]
            ax1.plot(speed / 6, linewidth=0.6, label=gd.p_names[i])
            ax2.plot(accel / 6, linewidth=0.6, label=gd.p_names[i])
            ax3.plot(pitch / 6, linewidth=0.6, label=gd.p_names[i])
        else:
            i = piece - 1
            ax1.plot(gd.norm_arrays[i, :, sensors.index('Speed')],
                     linewidth=0.6,
                     label=gd.p_names[i])
            ax2.plot(gd.norm_arrays[i, :, sensors.index('Accel')],
                     linewidth=0.6,
                     label=gd.p_names[i])
            ax3.plot(gd.norm_arrays[i, :, sensors.index('Pitch Angle')],
                     linewidth=0.6,
                     label=gd.p_names[i])

        pa = []
        for i in range(len(gd.p_names)):
            # accel and tempo per piece
            d, a = gd.prof_data[i]
            pa.append((d['Speed'], cntrating[i][1]))
        pa = list(zip(*pa))
        p = [10 * x for x in pa[0]]  # ad hoc scaling
        ax4.scatter(list(range(len(gd.p_names))), p, marker='H', color='green')
        ax4.scatter(list(range(len(gd.p_names))),
                    pa[1],
                    marker='H',
                    color='blue')

        ax1.legend(loc='lower right', prop=fontP)
        plt.tight_layout()

        tmpfig = tmpdir / gd.config['Session']
        plt.savefig(tmpfig)
        tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
        doc.append(
            NoEscape(r'\includegraphics[width=1.0\textwidth]{' + f'{tmpfig}' +
                     r'}'))
        plt.close(fig)

    ##   Third page
    doc.append(NewPage())
    with doc.create(Section('Crew report', numbering=False)):
        pcs = gd.p_names + ['average']
        doc.append(f'Piece "{pcs[gd.crewPiece]}" used.\n')

        fig = plt.figure()
        fig.subplots_adjust(hspace=0.7)
        gs = fig.add_gridspec(5, 2)
        ax1 = fig.add_subplot(gs[0:3, :])
        ax2 = fig.add_subplot(gs[3:, 0])
        ax3 = fig.add_subplot(gs[3:, 1])

        ax1.set_title('Gate Angle - GateForceX/Y')
        ax1.grid(True)
        ax2.set_title('Stretcher ForceX')
        ax2.grid(True)
        ax3.set_title('Power')
        ax3.grid(True)

        rcnt = gd.sessionInfo['RowerCnt']
        piece = gd.crewPiece
        if piece < len(gd.prof_data):
            # a seperate piece, from the tumbler
            cp = gd.crewPiece
            d, aa = gd.prof_data[cp]

            for r in range(rcnt):
                sns = rowersensors(r)
                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    i = sns['GateAngle']
                    j = sns['GateForceX']
                    k = sns['GateForceY']
                else:
                    i = sns['P GateAngle']
                    j = sns['P GateForceX']
                    k = sns['P GateForceY']

                # stretchers not always present!
                # k = sns['Stretcher Z']
                # todo: create switch to control working in this case

                ax1.plot(gd.norm_arrays[cp, :, i],
                         gd.norm_arrays[cp, :, j],
                         linewidth=0.6,
                         label=f'R {r+1}')
                ax1.plot(gd.norm_arrays[cp, :, i],
                         gd.norm_arrays[cp, :, k],
                         linestyle=stippel,
                         linewidth=0.6,
                         label=f'R {r+1}Y')

                #twee = self.ax2.plot(gd.norm_arrays[gd.crewPiece, :, i], linewidth=0.6, label=f'R {r+1}')

                ax3.plot([gd.gmin[gd.crewPiece]], [0], marker='v', color='b')
                ax3.plot([gd.gmax[gd.crewPiece]], [0], marker='^', color='b')

                # reference curve derived from the stroke
                sns = rowersensors(rcnt - 1)
                fmean = d[rcnt - 1]['GFEff']
                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    i = sns['GateAngle']
                    j = sns['GateForceX']
                else:
                    i = sns['P GateAngle']
                    j = sns['P GateForceX']
                minpos = min(gd.norm_arrays[cp, :, i])
                maxpos = max(gd.norm_arrays[cp, :, i])
                minarg = np.argmin(gd.norm_arrays[cp, :, i])
                maxarg = np.argmax(gd.norm_arrays[cp, :, i])
                fmin = gd.norm_arrays[cp, minarg, j]
                fmax = gd.norm_arrays[cp, maxarg, j]
                xstep = (maxpos - minpos) / 20
                ystep = (fmin - fmax) / 20  # assume fmin > fmax

                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    xref = np.array([
                        minpos, minpos + 0.4 * xstep, minpos + 2 * xstep,
                        minpos + 5 * xstep, minpos + 7 * xstep,
                        minpos + 9 * xstep, minpos + 11 * xstep,
                        minpos + 14 * xstep, minpos + 16 * xstep,
                        minpos + 20 * xstep
                    ])
                    yref = np.array([
                        fmin, fmin + 20, 1.1 * fmean, 1.6 * fmean,
                        1.65 * fmean, 1.7 * fmean, 1.6 * fmean, 1.25 * fmean,
                        0.8 * fmean, fmax
                    ])
                else:
                    xref = np.array([
                        minpos, minpos + 0.4 * xstep, minpos + 2 * xstep,
                        minpos + 5 * xstep, minpos + 7 * xstep,
                        minpos + 9 * xstep, minpos + 11 * xstep,
                        minpos + 14 * xstep, minpos + 16 * xstep,
                        minpos + 20 * xstep
                    ])
                    yref = np.array([
                        fmin, fmin + 20, 1.1 * fmean, 1.6 * fmean,
                        1.65 * fmean, 1.7 * fmean, 1.6 * fmean, 1.25 * fmean,
                        0.8 * fmean, fmax
                    ])

                curveref = make_interp_spline(xref, yref, 2)
                xrefnew = np.linspace(min(xref), max(xref),
                                      int(maxpos - minpos))

                ax1.plot(xrefnew,
                         curveref(xrefnew),
                         color='black',
                         linewidth=0.5,
                         linestyle=(0, (3, 6)))
                ax3.plot(aa[0 + r], linewidth=0.6, label=f'R {r+1}')
        else:
            # average
            for r in range(rcnt):
                sns = rowersensors(r)
                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    i = sns['GateAngle']
                    j = sns['GateForceX']
                else:
                    i = sns['P GateAngle']
                    j = sns['P GateForceX']
                # stretchers not always available!
                # k = sns['Stretcher Z']

                # average
                nmbrpieces = len(gd.p_names)
                angle = np.zeros((100, ))
                force = np.zeros((100, ))
                power = np.zeros((100, ))
                for p in range(nmbrpieces):
                    angle += gd.norm_arrays[p, :, i]
                    force += gd.norm_arrays[p, :, j]
                    # stretcherZ = gd.norm_arrays[p, :, k]
                    d, a = gd.prof_data[p]
                    power += aa[0 + r]

                # plot
                #ax1.plot(angle/nmbrpieces, linewidth=0.6, label=f'R {r+1}')
                #ax2.plot(force/nmbrpieces, linewidth=0.6, label=f'R {r+1}')

                ax3.plot(power / nmbrpieces, linewidth=0.6, label=f'R {r+1}')

        ax3.legend(loc='upper right', prop=fontP)
        plt.tight_layout()

        # we keep using the same name
        tmpfig = tmpdir / (gd.config['Session'] + '_crew')
        plt.savefig(tmpfig)
        tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
        doc.append(
            NoEscape(r'\includegraphics[width=1.0\textwidth]{' + f'{tmpfig}' +
                     r'}'))
        plt.close(fig)

    # Rower pages
    doc.append(NewPage())

    rwrcnt = gd.sessionInfo['RowerCnt']
    fig = [None for i in range(rwrcnt)]
    rax1 = [None for i in range(rwrcnt)]
    sax1 = [None for i in range(rwrcnt)]

    for rwr in range(rwrcnt):
        pcs = ['all'] + gd.p_names + ['average']
        with doc.create(
                Section(
                    f'Rower: {gd.metaData["Rowers"][rwr][0]}, using piece "{pcs[gd.rowerPiece[rwr]]}"',
                    numbering=False)):

            rows = gd.rowertablemodel[rwr].rowCount()
            columns = gd.rowertablemodel[rwr].columnCount()
            rowertab = 'l|' + ''.join(['r' for i in range(columns - 1)]) + '|'
            with doc.create(Tabular(rowertab)) as table:
                table.add_hline()
                row = []
                for j in range(columns):
                    index = QAbstractTableModel.index(gd.rowertablemodel[rwr],
                                                      0, j)
                    row.append(str(gd.rowertablemodel[rwr].data(index)))
                table.add_row(row, color='aquamarine')
                table.add_hline()

                cnt = 0
                for i in range(rows):
                    row = []
                    if i == 0:
                        continue
                    for j in range(columns):
                        index = QAbstractTableModel.index(
                            gd.rowertablemodel[rwr], i, j)
                        row.append(str(gd.rowertablemodel[rwr].data(index)))
                    if cnt % 2 == 0:
                        table.add_row(row, color='gainsboro')
                    else:
                        table.add_row(row, color='aquamarine')
                    cnt += 1
                table.add_hline()

            doc.append('\n')

            fig[rwr], ((rax1[rwr])) = plt.subplots(nrows=1, ncols=1)
            rax1[rwr].set_title('GateAngle - GateForceX/Y')
            rax1[rwr].grid(True)

            rsens = rowersensors(rwr)
            piece = gd.rowerPiece[rwr]

            scaleAngle = 10
            if gd.rowerPiece[rwr] == 0:
                # all
                for i in range(len(gd.p_names)):
                    if gd.sessionInfo['ScullSweep'] == 'sweep':
                        # print(f'Make rowerplot for {self.rower}')
                        rax1[rwr].plot(gd.norm_arrays[i, :,
                                                      rsens['GateAngle']],
                                       gd.norm_arrays[i, :,
                                                      rsens['GateForceX']],
                                       linewidth=0.6,
                                       label=f'{gd.p_names[i]}')
                        rax1[rwr].plot(gd.norm_arrays[i, :,
                                                      rsens['GateAngle']],
                                       gd.norm_arrays[i, :,
                                                      rsens['GateForceY']],
                                       linestyle=(0, (7, 10)),
                                       linewidth=0.6,
                                       label=f'{gd.p_names[i]}')
                    else:
                        rax1[rwr].plot(gd.norm_arrays[i, :,
                                                      rsens['P GateAngle']],
                                       gd.norm_arrays[i, :,
                                                      rsens['P GateForceX']],
                                       linewidth=0.6,
                                       label=f'{gd.p_names[i]}')
                        rax1[rwr].plot(gd.norm_arrays[i, :,
                                                      rsens['P GateAngle']],
                                       gd.norm_arrays[i, :,
                                                      rsens['P GateForceY']],
                                       linestyle=(0, (7, 10)),
                                       linewidth=0.6,
                                       label=f'{gd.p_names[i]}')
            elif gd.rowerPiece[rwr] == 7:
                # average
                angle = np.zeros((100, ))
                forceX = np.zeros((100, ))
                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    for i in range(len(gd.p_names)):
                        angle += gd.norm_arrays[i, :, rsens['GateAngle']]
                        forceX += gd.norm_arrays[i, :, rsens['GateForceX']]
                        forceY += gd.norm_arrays[i, :, rsens['GateForceY']]
                    rax1[rwr].plot(angle / 6,
                                   forceX / 6,
                                   linewidth=0.6,
                                   label='FX')
                    rax1[rwr].plot(angle / 6,
                                   forceY / 6,
                                   linestyle=(0, (7, 10)),
                                   linewidth=0.6,
                                   label='FY')
                else:
                    for i in range(len(gd.p_names)):
                        angle += gd.norm_arrays[i, :, rsens['P GateAngle']]
                        forceX += gd.norm_arrays[i, :, rsens['P GateForceX']]
                        forceY += gd.norm_arrays[i, :, rsens['P GateForceY']]
                    rax1[rwr].plot(angle / 6,
                                   forceX / 6,
                                   linewidth=0.6,
                                   label='FX')
                    rax1[rwr].plot(angle / 6,
                                   forceY / 6,
                                   linestyle=(0, (7, 10)),
                                   linewidth=0.6,
                                   label='FY')
            else:
                rp = gd.rowerPiece[rwr] - 1
                sns = rowersensors(rwr)

                # ad hoc angle x 10. Bettet via (max-min). Scale is for force
                # print(f'Create rowerplot for {self.rower}')
                outboat = [d for d, e in gd.prof_data]
                ri = [a[rwr] for a in outboat]  # rower info per piece
                fmean = ri[rp]['GFEff']

                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    i = sns['GateAngle']
                    j = sns['GateForceX']
                    k = sns['GateForceY']
                else:
                    i = sns['P GateAngle']
                    j = sns['P GateForceX']
                    k = sns['P GateForceY']

                # TESTING referentie curve
                # lengte uit tabel? Voorlopig 100, begin goed zetten
                # scale with avarage force
                minpos = min(gd.norm_arrays[rp, :, i])
                maxpos = max(gd.norm_arrays[rp, :, i])
                minarg = np.argmin(gd.norm_arrays[rp, :, i])
                maxarg = np.argmax(gd.norm_arrays[rp, :, i])
                fmin = gd.norm_arrays[rp, minarg, j]
                fmax = gd.norm_arrays[rp, maxarg, j]
                xstep = (maxpos - minpos) / 20
                ystep = (fmin - fmax) / 20  # assume fmin > fmax

                if gd.sessionInfo['ScullSweep'] == 'sweep':
                    xref = np.array([
                        minpos, minpos + 0.4 * xstep, minpos + 2 * xstep,
                        minpos + 5 * xstep, minpos + 7 * xstep,
                        minpos + 9 * xstep, minpos + 11 * xstep,
                        minpos + 14 * xstep, minpos + 16 * xstep,
                        minpos + 20 * xstep
                    ])
                    yref = np.array([
                        fmin, fmin + 20, 1.1 * fmean, 1.6 * fmean,
                        1.65 * fmean, 1.7 * fmean, 1.6 * fmean, 1.25 * fmean,
                        0.8 * fmean, fmax
                    ])
                else:
                    xref = np.array([
                        minpos, minpos + 0.4 * xstep, minpos + 2 * xstep,
                        minpos + 5 * xstep, minpos + 7 * xstep,
                        minpos + 9 * xstep, minpos + 11 * xstep,
                        minpos + 14 * xstep, minpos + 16 * xstep,
                        minpos + 20 * xstep
                    ])
                    yref = np.array([
                        fmin, fmin + 20, 1.1 * fmean, 1.6 * fmean,
                        1.65 * fmean, 1.7 * fmean, 1.6 * fmean, 1.25 * fmean,
                        0.8 * fmean, fmax
                    ])

                curveref = make_interp_spline(xref, yref, 2)
                xrefnew = np.linspace(min(xref), max(xref),
                                      int(maxpos - minpos))

                rax1[rwr].plot(gd.norm_arrays[rp, :, i],
                               gd.norm_arrays[rp, :, j],
                               linewidth=0.6,
                               label=f'{gd.p_names[rp]} FX')
                rax1[rwr].plot(gd.norm_arrays[rp, :, i],
                               gd.norm_arrays[rp, :, k],
                               linestyle=stippel,
                               linewidth=0.6,
                               label=f'{gd.p_names[rp]} FY')
                rax1[rwr].plot(xrefnew,
                               curveref(xrefnew),
                               color='black',
                               linewidth=0.5,
                               linestyle=(0, (3, 6)))

            # rax1[rwr].legend(loc='lower right', prop=fontP, bbox_to_anchor=(1.05, 1))
            rax1[rwr].legend(loc='upper right', prop=fontP)
            plt.tight_layout()

            tmpfig = tmpdir / (gd.config['Session'] + f'_{rwr}')
            plt.savefig(tmpfig)
            tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
            doc.append(
                NoEscape(r'\includegraphics[width=0.9\textwidth]{' +
                         f'{tmpfig}' + r'}'))
            plt.close(fig[rwr])

            if 'StretcherForceX' in sensors:
                doc.append('\n')

                # stretcher plot
                fig[rwr], sax1[rwr] = plt.subplots()
                sax1[rwr].set_title('Stretcher')
                sax1[rwr].grid(True)

                rsens = rowersensors(rwr)
                if gd.rowerPiece[rwr] == 0:
                    # all DOEN WE NIET
                    pass
                elif gd.rowerPiece[rwr] == len(gd.p_names) + 1:
                    # average DOEN WE NIET
                    pass
                else:
                    # a piece (alleen dit)
                    i = gd.rowerPiece[rwr] - 1
                    name, se, nr, sp = pieces[i]
                    sax1[rwr].plot(gd.dataObject[sp[0]:sp[1],
                                                 rsens['StretcherForceX']],
                                   linewidth=0.6,
                                   label='StretcherForceX')
                    sax1[rwr].plot(
                        10 * gd.dataObject[sp[0]:sp[1], rsens['Stretcher RL']],
                        linewidth=0.6,
                        label='Stretcher RL')
                    sax1[rwr].plot(
                        10 * gd.dataObject[sp[0]:sp[1], rsens['Stretcher TB']],
                        linewidth=0.6,
                        label='Stretcher TB')

                    sax1[rwr].legend(loc='lower right', prop=fontP)
                    plt.tight_layout()

            tmpfig = tmpdir / (gd.config['Session'] + f'_{rwr}_s')
            plt.savefig(tmpfig)
            tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
            doc.append(
                NoEscape(r'\includegraphics[width=0.6\textwidth]{' +
                         f'{tmpfig}' + r'}'))

            plt.close(fig[rwr])

            if rwr != rwrcnt - 1:
                doc.append(NewPage())

    # Extra page
    if gd.extraplot:
        doc.append(NewPage())

        fig, extr = plt.subplots()
        s2 = gd.config['Session2']
        if s2 == '':
            extr.set_title('Custom plot')
        else:
            extr.set_title(f'Custom plot (second session: {s2})')
        extr.grid(True)

        # data from update_plot from View piece, can we do this simpler?
        [strt, end, strttime, center, scalex, slist,
         secslist] = gd.extrasettings
        times = list(map(lambda x: x / Hz, list(range(gd.view_tr.shape[0]))))

        for i, name, scaley in slist:
            extr.plot(times,
                      gd.view_tr[:, i] * scaley,
                      linewidth=0.6,
                      label=name)
        for i, name, scale in secslist:
            extr.plot(times,
                      gd.view_tr2[:, i] * scaley,
                      linewidth=0.6,
                      label=name,
                      linestyle=stippel)

        dist = (end - strt)
        xFrom = center - scalex * dist / 2
        xTo = center + scalex * dist / 2

        extr.set_xlim(xFrom, xTo)
        # start at correct beginvalue
        locs = extr.get_xticks()
        ticks = [item + strttime for item in locs]
        extr.set_xticklabels(ticks)
        extr.legend()
        plt.tight_layout()

        # we keep using the same name
        tmpfig = tmpdir / (gd.config['Session'] + '_extra')
        plt.savefig(tmpfig)
        tmpfig = re.sub('\\\\', '/', str(tmpfig))  # for windows
        doc.append(
            NoEscape(r'\includegraphics[width=1.0\textwidth]{' + f'{tmpfig}' +
                     r'}'))
        plt.close(fig)

        doc.append(NewLine())
        doc.append(VerticalSpace("10pt"))
        doc.append(f' Piece: {gd.selPiece}')
        if gd.sd_selPiece != '':
            doc.append(NewLine())
            doc.append(VerticalSpace("5pt"))
            doc.append(f'Secondary piece: {gd.sd_selPiece}')

    # generate report
    doc.generate_pdf(reportfile, clean_tex=True)
    def save_latex(self, reportsummary, filename, rel_path, Disp_3d_image):
        companyname = str(reportsummary["ProfileSummary"]['CompanyName'])
        companylogo = str(reportsummary["ProfileSummary"]['CompanyLogo'])
        groupteamname = str(reportsummary["ProfileSummary"]['Group/TeamName'])
        designer = str(reportsummary["ProfileSummary"]['Designer'])
        projecttitle = str(reportsummary['ProjectTitle'])
        subtitle = str(reportsummary['Subtitle'])
        jobnumber = str(reportsummary['JobNumber'])
        client = str(reportsummary['Client'])

        header = PageStyle("header")
        # Create center header
        with header.create(Head("C")):
            with header.create(Tabularx('|l|p{6cm}|l|X|')) as table:
                table.add_hline()
                # MultiColumn(4)
                table.add_row(('Company Name', companyname, 'Project Title',
                               projecttitle),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Group/Team Name', groupteamname, 'Subtitle', subtitle),
                    color='OsdagGreen')
                table.add_hline()
                table.add_row(('Designer', designer, 'Job Number', jobnumber),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    ('Date', time.strftime("%d /%m /%Y"), 'Client', client),
                    color='OsdagGreen')
                table.add_hline()
        # Create right footer
        with header.create(Foot("R")):
            header.append(NoEscape(r'Page \thepage'))

        geometry_options = {
            "top": "1.2in",
            "bottom": "1in",
            "left": "0.6in",
            "right": "0.6in",
            "headsep": "0.8in"
        }
        doc = Document(geometry_options=geometry_options, indent=False)
        doc.packages.append(Package('amsmath'))
        doc.packages.append(Package('graphicx'))
        doc.packages.append(Package('needspace'))
        doc.add_color('OsdagGreen', 'HTML', 'D5DF93')
        doc.preamble.append(header)
        doc.change_document_style("header")

        with doc.create(Section('Design Conclusion')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                table.add_hline()
                table.add_row(('Section Designation', 'Remarks'),
                              color='OsdagGreen')
                table.add_hline()
                table.add_row(
                    (reportsummary['Define Section']['Section Designation'],
                     'Pass'))
                table.add_hline()

        with doc.create(Section('Section Details')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                table.add_hline()
                table.add_row(
                    (bold('Section Type'),
                     reportsummary['Define Section']['Section Type']))
                table.add_hline()
                table.add_row(
                    (bold('Section Template'),
                     reportsummary['Define Section']['Section Template']))
                table.add_hline()

        with doc.create(Section('Section Parameters')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                for parameter in reportsummary['Define Section'][
                        'Section Parameters']:
                    para = reportsummary['Define Section'][
                        'Section Parameters'][parameter]
                    table.add_hline()
                    table.add_row((bold(para[0]), para[1]))
                table.add_hline()

        labels = [
            'Area, a(cm²)',
            'Moment of Inertia',
            'I_zz(cm4)',
            'I_yy(cm4)',
            'Radius of Gyration',
            'r_zz(cm)',
            'r_yy(cm)',
            'Centriod',
            'c_z(cm)',
            'c_y(cm)',
            'Plastic Section modulus',
            'Z_pz(cm³)',
            'Z_py(cm³)',
            'Elastic Section modulus',
            'Z_zz(cm³)',
            'Z_yy(cm³)',
        ]
        values = list(reportsummary['Section Properties'].values())
        Properties = [
            (labels[0], values[0]),
            (labels[1], ""),
            (labels[2], values[1]),
            (labels[3], values[2]),
            (labels[4], ""),
            (labels[5], values[3]),
            (labels[6], values[4]),
            (labels[7], ""),
            (labels[8], values[5]),
            (labels[9], values[6]),
            (labels[10], ""),
            (labels[11], values[7]),
            (labels[12], values[8]),
            (labels[13], ""),
            (labels[14], values[9]),
            (labels[15], values[10]),
        ]

        with doc.create(Section('Section Properties')):
            with doc.create(Tabularx('|X|X|', row_height=1.2)) as table:
                for ppty in Properties:
                    table.add_hline()
                    table.add_row((bold(ppty[0]), ppty[1]))
                table.add_hline()
        doc.append(NewPage())

        if (not 'TRAVIS' in os.environ):
            with doc.create(Section('3D View')):
                with doc.create(Figure(position='h!')) as view_3D:
                    view_3dimg_path = rel_path + Disp_3d_image
                    # view_3D.add_image(filename=view_3dimg_path, width=NoEscape(r'\linewidth'))
                    view_3D.add_image(filename=view_3dimg_path)

                    view_3D.add_caption('3D View')
        try:
            doc.generate_pdf(filename, compiler='pdflatex', clean_tex=False)
        except:
            pass
示例#9
0
    def generateReport(self):
        doc = Document()

        doc.packages.append(Package('array'))
        doc.preamble.append(Command('title', 'Reporte de Rendimiento'))

        doc.preamble.append(Command('author', 'Equipo 3'))

        doc.preamble.append(Command('date', NoEscape(r'\today')))

        doc.append(NoEscape(r'\maketitle'))

        with doc.create(Section("Integrantes")):
            with doc.create(Itemize()) as itemize:
                itemize.add_item(NoEscape("Caballero Ramirez Michelle"))
                itemize.add_item(NoEscape("Garcia Lomeli Abraham Amos"))
                itemize.add_item(NoEscape("Mu\~noz Ramirez Adriana"))
                itemize.add_item(NoEscape("Rodriguez Mu\~noz Alicia Vanessa"))
                itemize.add_item(NoEscape("Sanchez Gama Erick Javier"))

        for typeS in self._servers:

            servers = self._servers[typeS]

            for server in servers:

                doc.append(NewPage())

                info = servers[server]
                status = self._manager.getAgentStatus(server)

                s = self._tyServer.format(Server=info['type'],
                                          location=info['url'],
                                          status=('UP' if status else 'DOWN'))

                if status == False:
                    doc.create(Section(s))

                else:
                    agent = self._manager.getAgent(server)

                    basic = []
                    basic.append(agent.getOS())
                    basic.append(agent.getUpTimeF())
                    basic.append(agent.getNumInterFs())

                    with doc.create(Section(s)):
                        with doc.create(Center()) as center:
                            with center.create(
                                    Tabular('| p{20em}  p{20em}|')) as table:

                                table.add_hline()
                                table.add_row((MultiColumn(
                                    2,
                                    align='|c|',
                                    data=bold('Reporte Servidor')), ))
                                table.add_hline()
                                table.add_row((MultiColumn(
                                    2,
                                    align='|c|',
                                    data=bold('Informacion General')), ))
                                table.add_hline()

                                for info, data in zip(self._iBasicInfo, basic):
                                    table.add_row((info, data))

                                if self._report[typeS][server] is None:
                                    continue

                                table.add_hline()

                                table.add_row(
                                    (MultiColumn(2,
                                                 align='|c|',
                                                 data=bold('Recursos')), ))

                                table.add_hline()

                                headers = self._report[typeS][server]

                                print self._report[typeS][server]

                                for header in headers:

                                    table.add_row(
                                        (MultiColumn(2,
                                                     align='|c|',
                                                     data=bold(header)), ))

                                    table.add_hline()

                                    points = headers[header]

                                    for point in points:

                                        table.add_row(
                                            (italic(point), points[point]))

                                    table.add_hline()

                        with doc.create(Subsection('Uso de Recursos')) as sub:
                            with sub.create(Figure(position='h!')) as image:
                                aux = self._path.format(server, 'ram')
                                path = os.path.join(os.path.dirname(__file__),
                                                    aux)
                                image.add_image(path)
                                image.add_caption('Uso de Memoria RAM')
                            print agent.getNumCPUs()
                            for i in range(agent.getNumCPUs()):
                                with sub.create(
                                        Figure(position='h!')) as image:
                                    aux = self._path.format(
                                        server, 'cpu' + str(i))
                                    path = os.path.join(
                                        os.path.dirname(__file__), aux)
                                    image.add_image(path)
                                    image.add_caption('Uso de CPU ' +
                                                      str(i + 1))

        doc.generate_pdf('rendimiento', clean_tex=False)
示例#10
0
文件: report.py 项目: atgu/GWASpy
    def individual_char(self, id_con_pre_path, id_cas_pre_path, id_all_path,
                        fstat_fig_path, data_type):
        self.append(NewPage())

        with self.create(Section('Per Individual Characteristics Analysis')):
            with self.create(Subsection('Missing Rates - pre-QC')):
                if data_type == "Case-only":
                    with self.create(Figure(position='h!')) as pre_idcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as idcr_cas_pre_images:
                            idcr_cas_pre_images.add_image(
                                id_cas_pre_path,
                                width=NoEscape(r'1\linewidth'))
                    self.append(NewPage())

                if data_type == "Control-only":
                    with self.create(Figure(position='h!')) as pre_idcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as idcr_con_pre_images:
                            idcr_con_pre_images.add_image(
                                id_con_pre_path,
                                width=NoEscape(r'1\linewidth'))
                    self.append(NewPage())

                if data_type == "no-pheno":
                    with self.create(Figure(position='h!')) as pre_idcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as idcr_all_pre_images:
                            idcr_all_pre_images.add_image(
                                id_all_path, width=NoEscape(r'1\linewidth'))
                    self.append(NewPage())

                if data_type == "Case-Control":
                    with self.create(Figure(position='h!')) as pre_idcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as idcr_con_pre_images:
                            idcr_con_pre_images.add_image(
                                id_con_pre_path,
                                width=NoEscape(r'1\linewidth'))
                    with self.create(Figure(position='h!')) as pre_idcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as idcr_cas_pre_images:
                            idcr_cas_pre_images.add_image(
                                id_cas_pre_path,
                                width=NoEscape(r'1\linewidth'))
                    self.append(NewPage())

            with self.create(Subsection('Fstat - Sex Violations')):
                with self.create(Figure(position='h!')) as fstat_image:
                    self.append(Command('centering'))
                    with self.create(
                            SubFigure(
                                position='c',
                                width=NoEscape(r'1\linewidth'))) as fstat_fig:
                        fstat_fig.add_image(fstat_fig_path,
                                            width=NoEscape(r'1\linewidth'))
示例#11
0
文件: report.py 项目: atgu/GWASpy
    def snp_char(self, var_con_pre_path, var_cas_pre_path, var_all_path,
                 data_type):
        self.append(NewPage())

        with self.create(Section('Per SNP Characteristics Analysis')):
            with self.create(Subsection('Missing Rates - pre-QC')):
                if data_type == "Case-only":
                    with self.create(
                            Figure(position='h!')) as pre_varcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as varcr_cas_pre_images:
                            varcr_cas_pre_images.add_image(
                                var_cas_pre_path,
                                width=NoEscape(r'1\linewidth'))
                    self.append(NewPage())

                if data_type == "Control-only":
                    with self.create(
                            Figure(position='h!')) as pre_varcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as varcr_con_pre_images:
                            varcr_con_pre_images.add_image(
                                var_con_pre_path,
                                width=NoEscape(r'1\linewidth'))
                    self.append(NewPage())

                if data_type == "no-pheno":
                    with self.create(
                            Figure(position='h!')) as pre_varcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as varcr_all_pre_images:
                            varcr_all_pre_images.add_image(
                                var_all_path, width=NoEscape(r'1\linewidth'))
                    self.append(NewPage())

                if data_type == "Case-Control":
                    with self.create(
                            Figure(position='h!')) as pre_varcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as varcr_con_pre_images:
                            varcr_con_pre_images.add_image(
                                var_con_pre_path,
                                width=NoEscape(r'1\linewidth'))
                    with self.create(
                            Figure(position='h!')) as pre_varcr_images:
                        self.append(Command('centering'))
                        with self.create(
                                SubFigure(position='c',
                                          width=NoEscape(r'1\linewidth'))
                        ) as varcr_cas_pre_images:
                            varcr_cas_pre_images.add_image(
                                var_cas_pre_path,
                                width=NoEscape(r'1\linewidth'))
                    self.append(NewPage())
示例#12
0
文件: report.py 项目: atgu/GWASpy
    def manhattan_sec(self, qq_pre_path, qq_pos_path, man_pre_path,
                      man_pos_path, table_results):
        self.append(NewPage())

        with self.create(Section('Manhattan')):
            with self.create(Subsection('Basic stats')):
                with self.create(Center()) as centered:
                    with centered.create(Tabular('|c|c|c|')) as table:
                        table.add_hline()
                        table.add_row((bold('Description'), bold('Pre-QC'),
                                       bold('Post-QC')))
                        table.add_hline()
                        table.add_row(('Number of GWAS hits', table_results[0],
                                       table_results[1]))
                        table.add_hline()
                        table.add_row(
                            ('Lambda GC', table_results[2], table_results[3]))
                        table.add_hline()
                        # calculate lambda 1000
                        table.add_row(('Lambda 1000', table_results[4],
                                       table_results[5]))
                        table.add_hline()

            self.append(NewPage())

            with self.create(Subsection('Manhattan Plot - pre-QC')):
                with self.create(Figure(position='h!')) as pre_man_images:
                    self.append(Command('centering'))
                    with self.create(
                            SubFigure(position='c',
                                      width=NoEscape(
                                          r'1\linewidth'))) as man_pre_images:
                        man_pre_images.add_image(
                            man_pre_path, width=NoEscape(r'1\linewidth'))
                with self.create(Figure(position='h!')) as pre_man_images:
                    self.append(Command('centering'))
                    with self.create(
                            SubFigure(
                                position='c',
                                width=NoEscape(
                                    r'0.85\linewidth'))) as qq_pre_images:
                        qq_pre_images.add_image(
                            qq_pre_path, width=NoEscape(r'0.85\linewidth'))

            self.append(NewPage())

            with self.create(Subsection('Manhattan Plot - post-QC')):
                with self.create(Figure(position='h!')) as pos_man_images:
                    self.append(Command('centering'))
                    with self.create(
                            SubFigure(position='c',
                                      width=NoEscape(
                                          r'1\linewidth'))) as man_pos_images:
                        man_pos_images.add_image(
                            man_pos_path, width=NoEscape(r'1\linewidth'))
                with self.create(Figure(position='h!')) as pos_man_images:
                    self.append(Command('centering'))
                    with self.create(
                            SubFigure(
                                position='c',
                                width=NoEscape(
                                    r'0.85\linewidth'))) as qq_pos_images:
                        qq_pos_images.add_image(
                            qq_pos_path, width=NoEscape(r'0.85\linewidth'))
示例#13
0
    def portada(Diccionario, eficiencia,T_Hornilla):
        global doc
        doc = Document()
        geometry_options = {"tmargin": "4cm", "rmargin": "2cm", "lmargin": "4cm", "bmargin": "3cm"} 
        doc = Document(geometry_options=geometry_options)
        doc.packages.append(Package('babel', options=['spanish']))
        doc.packages.append(Package('background', options=['pages=all']))
        doc.packages.append(NoEscape('\\backgroundsetup{placement=center,\n angle=0, scale=1, contents={\includegraphics{Membrete.pdf}}, opacity=1}\n'))   
        
        with doc.create(Center()) as centered:
                    centered.append(TextColor('white','HH')) 
                    for i in range(10):
                        centered.append(LineBreak())   
                    centered.append(HugeText('PROPUESTA DE VALOR PARA LA CONSTRUCCIÓN DE UNA HORNILLA '))
                    centered.append(LineBreak()) 
                    centered.append(SmallText('(Generado por HornillAPP)'))
                    for i in range(8):
                        centered.append(LineBreak()) 
                    
        with doc.create(Figure(position='h!')) as imagesRow1:
            with doc.create(SubFigure(
                    position='b',
                    width=NoEscape(r'1\linewidth'))) as left_imagesRow1:
                left_imagesRow1.add_image('IconoAPP.png')
            imagesRow1.append(LineBreak())
                                    
        with doc.create(Center()) as centered:
                    centered.append(TextColor('white','HH')) 
                    for i in range(8):
                        centered.append(LineBreak())
                    #centered.append(VerticalSpace('50')) 
                    centered.append(LargeText('Presentado por: AGROSAVIA'))
                    centered.append(LineBreak())
                    centered.append(SmallText('(Corporación Colombiana de Investigación Agropecuaria)'))
        doc.append(NewPage())
        
        with doc.create(MediumText(' ')) as tlg:
                    tlg.append(TextColor('white','HH')) 
                    tlg.append(LineBreak())
                    tlg.append('Bogotá D.C., ')
                    tlg.append(Command(' ',NoEscape('\\today')))
                    tlg.append('\n \n') #Salto de línea en parráfo
                    tlg.append(LineBreak()) #Salto de línea en parráfo
                    tlg.append('\nSeñor (es):') 
                    tlg.append('\n'+str(Diccionario['Nombre de usuario']))
                    if(str(Diccionario['Departamento'])=='--'):
                        tlg.append('\n'+str(Diccionario['Pais'])+'.')    
                    else:
                        tlg.append('\n'+str(Diccionario['Ciudad'])+', '+str(Diccionario['Departamento'])+'.')
                    tlg.append('\n \n') #Salto de línea en parráfo
                    tlg.append('\nApreciado(s) productor(es):')
                    tlg.append('\n \n') #Salto de línea en parráfo
                    Parrafo= ('Con base en la información suministrada, está aplicación propone (ver Sección 1) la construcción de una hornilla '+
                              T_Hornilla+' con capacidad de '+ str(Diccionario['Capacidad estimada de la hornilla']) +' kg/h'+' (la eficiencia estimada de la hornilla es del '+ str(round(Diccionario['Eficiencia de la hornilla']))+'%) '+'; adecuada para el procesamiento de hasta '+
                              str(Diccionario['Área cosechada al mes'])+
                              ' ha'+' de caña, con una producción de panela '+ str(round(float(Diccionario['Producción de panela por molienda [t]'])))+
                              ' t por molienda y un periodo vegetativo de '+ str(Diccionario['Periodo vegetativo'])+' meses. Teniendo en cuenta que'+
                              ' se realizan '+str(Diccionario['Número de moliendas al año'])+' moliendas al año se estableció una jornada laboral de '+
                              str(Diccionario['Días de trabajo de la hornilla por semana'])+ ' días a la semana de '+str(Diccionario['Horas de trabajo de la hornilla por día'])+ ' horas laborables cada una.'+
                              '\n Además, la aplicación estima que para garantizar una operación apropiada de la hornilla '+
                              ' se requiere de un área disponible de al menos '+str(round(Diccionario['Capacidad estimada de la hornilla']*4.3))+' m²'
                              )
                    tlg.append(Parrafo)                
                    Parrafo= (', cuya productividad puede aumentar al incorporar el sistema de recuperación de calor (hasta '+str(round(Diccionario['Capacidad estimada de la hornilla']+25))+' kg/h) como se muestra en las tablas del análisis financiero y al final del informe.'
                              +' No obstante, la corporación ofrece los siguientes servicios de asistencia técnica para ajustar los valores provistos en esta propuesta de valor:'
                              )
                    tlg.append(Parrafo)
                    
                    with tlg.create(Itemize()) as itemize:
                        itemize.add_item('Estudio detallado para la construcción e instalación de la hornilla.')
                        itemize.add_item('Al menos tres visitas técnicas de dos funcionarios de AGROSAVIA para la puesta en marcha y '+
                                         'capacitación de los operarios en el manejo de la hornilla y en la producción de panela '+
                                         'saborizada, granulada o moldeada en presentación pastilla de chocolate.')
                        itemize.add_item('Entrega de un ejemplar de la guía tecnológica para el manejo integral del sistema '+
                                         'productivo de la caña panelera y una para el mantenimiento de la hornilla.')

                    Parrafo= ('Cualquier inquietud AGROSAVIA está presta a atenderla.\n'+
                              'Cordial saludo.\n'+
                              '\n \n \n'+
                              'AGROSAVIA (Corporación colombiana de investigación agropecuaria)')            
                    tlg.append(Parrafo)            

                    Parrafo= ('\n \n Nota: Está propuesta de valor se basa en condiciones del terreno ideales y estacionarias, por lo que, '+
                              'AGROSAVIA no se hace responsable de la reproducción total o parcial del material aquí suministrado sin una aprobación '+
                              'corporativa.')
                    tlg.append(Parrafo)
                    
        doc.append(NewPage())
        
        with doc.create(MediumText(' ')) as tlg:
                    tlg.append(LargeText(bold('Contenido')))
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Sección 1')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Información del usuario.')
                                                        item.add_item('Características de la caña sembrada.')
                                                        item.add_item('Características del molino.')
                                                        item.add_item('Consideraciones generales para el manejo de la hornilla.')
                                                        item.add_item('Análisis financiero.')
                                            itemize.add_item('Sección 2')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Diagramas mecánicos de la hornilla.')
                                                        item.add_item('Diagramas mecánicos de la camára.')
                                                        item.add_item('Diagramas mecánicos de la chimenea.')
                                                        item.add_item('Diagramas mecánicos del ducto.')
                                                        item.add_item('Diagramas mecánicos de la hornilla con recuperador de calor.')
        doc.append(NewPage())

        #PORTADA PARA LA SECCIÓN 1 
        
        with doc.create(Center()) as centered:
                    centered.append(TextColor('white','HH')) 
                    for i in range(15):
                        centered.append(LineBreak())   
                    centered.append(HugeText('SECCIÓN 1:'))
                    centered.append(LineBreak())
                    centered.append(HugeText('INFORMACIÓN TÉCNICA Y FINANCIERA')) 
        doc.append(NewPage())
示例#14
0
    def seccion1(D1, D2):
        global doc
        '''>>>>>>>>>>>>>>>Presentación de los datos de usuario<<<<<<<<<<<<<<<<<'''        
        doc = Documento_Latex.titulos_I (doc, 'DATOS DEL USUARIO PARA GENERAR EL INFORME')   
        with doc.create(Tabular('lccccl')) as table:
            for i in D1:
                if(str(i)=='DATOS DE ENTRADA'):
                    break
                else:
                    if((SM(None, 'Altura', i).ratio()<0.85) and
                       (SM(None, 'Variedad de Caña', i).ratio()<0.85) and
                       (SM(None, 'Usa fertilizante', i).ratio()<0.85) and
                       (SM(None, 'Grados Brix de la panela (promedio)', i).ratio()<0.85) and
                       (SM(None, '--', str(D1[i])).ratio()<0.85)):
                        T1=str(D1[i])
                        #Arreglo para asignar unidades y mostrarlas en el informe
                        if (str(i)=='Área caña sembrada'):
                            T1=str(D1[i])+" ha" 
                        elif (str(i)=='Crecimiento aproximado del área sembrada'):
                            T1=str(D1[i])+" ha"
                        elif (str(i)=='Caña esperada por hectárea'):
                            T1=str(D1[i])+" t/ha"
                        elif (str(i)=='Número de moliendas'):
                            T1=str(D1[i])+" semanal(es)"                    
                        elif (str(i)=='Periodo vegetativo'):
                            T1=str(D1[i])+" mes(es)"                   
                        elif (str(i)=='Caña molida al mes'):
                            T1=str(D1[i])+" t/mes" 
                        elif (str(i)=='Área cosechada al mes'):
                            T1=str(D1[i])+" ha/mes" 
                        elif (str(i)=='Caña molida a la semana'):
                            T1=str(D1[i])+" t/semana" 
                        elif (str(i)=='Caña molida por Hora'):
                            T1=str(D1[i])+" t/hora"
                        elif (str(i)=='Área cosechada al mes'):
                            T1=str(D1[i]*12)+" L/año"
                        elif (str(i)=='Caña molida al año'):
                            T1=str(D1[i])+" t/año"
                        elif (str(i)=='Jugo producido al año'):
                            T1=str(D1[i])+" t/año"
                        elif (str(i)=='Bagazo secado al año'):
                            T1=str(D1[i])+" t/año"
                        table.add_row((bold(str(i)), ' ', ' ', ' ', ' ',T1))
        doc.append(NewPage())
        
        '''>>>>>>>>>>>>>>>>>>>>Presentación de los datos de la caña<<<<<<<<<<<<<<<<<<<<<<<'''
        doc = Documento_Latex.titulos_I (doc, 'CARACTERÍSTICAS DE LAS VARIEDADES DE CAÑA SELECCIONADAS')
        Canas=pd.read_excel('static/Temp/Temp4.xlsx',skipcolumn = 0,)
        Carpe=pd.read_excel('static/Temp/Temp5.xlsx',skipcolumn = 0,)
        Eti = Canas.iloc[0].values
        Val = Canas.iloc[1].values
        Car = Carpe.iloc[0].values
        
        conta=1
        for i in range (len(Car)-1):
            with doc.create(Tabular('lcccccl')) as table:
                for j in range (1,8):
                    table.add_row((bold(str(Eti[conta])), ' ', ' ', ' ', ' ', ' ', str(Val[conta])))
                    conta=conta+1
                conta=conta+1
            doc.append(LineBreak())
            doc.append('\n')
            doc.append(LineBreak())
        
        for i in range (1,len(Car),3):
            with doc.create(Figure(position='h!')) as imagesRow1:
                for j in range(3):
                    if((i+j)<len(Car)):
                        with doc.create(
                            SubFigure(width=NoEscape(r'0.33\linewidth'))) as left_imagesRow1:
                            left_imagesRow1.add_image(Car[i+j], width=NoEscape(r'0.95\linewidth'))
                            left_imagesRow1.add_caption('Variedad de caña '+str(i+j))
                imagesRow1.append(LineBreak())
                imagesRow1.append(NewPage())  
        
        doc.append(NewPage())
        doc.append(TextColor('white','HH')) 
        doc.append(NewPage())
        
        '''>>>>>>>>>>>>>>>>>>>>Presentación de los molinos seleccionados<<<<<<<<<<<<<<<<<<<<<<<'''   
        doc = Documento_Latex.titulos_I (doc, 'MOLINOS PRESELECCIONADOS PARA ESTE DISEÑO')
        Molino=pd.read_excel('static/Temp/Temp.xlsx',skipcolumn = 0,)
        Carpe=pd.read_excel('static/Temp/Temp5.xlsx',skipcolumn = 0,)
        Eti = Canas.iloc[0].values
        Val = Canas.iloc[1].values
        Car = Carpe.iloc[0].values
        Marca=Molino['Marca'].values
        Modelo=Molino['Modelo'].values
        Kilos=Molino['kg/hora'].values
        Diesel=Molino['Diesel'].values
        Electrico=Molino['Electrico'].values
        Valor=Molino['Precio'].values

        with doc.create(Tabular('lcccccl')) as table:
                table.add_row((TextColor('red',bold('VALOR APROXIMADO DE UN MOLINO: ')),
                               ' ', ' ', ' ', ' ', ' ', 
                               TextColor('red', Documento_Latex.Formato_Moneda(sum(Valor)/len(Valor), "$", 2))))
        doc.append(LineBreak())
                
        with doc.create(Tabular('ccccc')) as table:  
            table.add_row("MARCA", "MODELO", "KG POR HORA", "DIESEL O GASOLINA (HP)", "ELÉCTRICO (HP)")
            table.add_empty_row()
            for i in range(len(Marca)):
                table.add_row(str(Marca[i]),
                              str(Modelo[i]), 
                              str(Kilos[i]), 
                              str(Diesel[i]), 
                              str(Electrico[i]))
                
            doc.append(LineBreak())
            doc.append('\n')
            doc.append(LineBreak())
        
        for i in range (1,len(Modelo),3):
            with doc.create(Figure(position='h!')) as imagesRow1:
                for j in range(3):
                    if((i-1)+j<len(Modelo)):
                        with doc.create(
                            SubFigure(width=NoEscape(r'0.33\linewidth'))) as left_imagesRow1:
                            left_imagesRow1.add_image('Molinos/'+str(Modelo[(i-1)+j]+'.jpg'), width=NoEscape(r'0.95\linewidth'))
                            left_imagesRow1.add_caption(str(Modelo[(i-1)+j]))
                imagesRow1.append(LineBreak())
                imagesRow1.append(NewPage()) 
        
        doc.append(NewPage())
        doc.append(TextColor('white','HH')) 
        doc.append(NewPage())                

        #MANUAL DE OPERACIÓN DE LA HORNILLA                   
        with doc.create(MediumText(' ')) as tlg:
                    tlg.append(LargeText(bold('Consideraciones para el manejo de la hornilla')))
                    
                    Parrafo= ('\n \nEl trapiche panelero es un lugar donde se procesa la caña de azúcar para producir la panela. Está constituido por las áreas de molienda, prelimpieza, hornilla, moldeo y almacenamiento.')           
                    tlg.append(Parrafo)

                    Parrafo= ('\n La hornilla panelera, está conformada, por el cenicero, la cámara, la chimenea y el ducto, sobre el cual se asientan directamente los intercambiadores de calor, en los que se deposita el jugo. En la hornilla panelera, se genera y transfiere el calor necesario para concentrar en un sistema de evaporación abierta, el jugo de la caña; de tal forma que la cantidad de energía aprovechada se relaciona directamente con el suministro de aire y bagazo, la eficiencia de la combustión, y la cantidad de energía disipada a los alrededores. Estas variables de operación y transferencia se relacionan entre si y debido a su complejidad y cantidad, dificultan las tareas de manipulación y diseño de la hornilla.')           
                    tlg.append(Parrafo)
                    
                    tlg.append(LargeText(bold('\n \n Manejo de las hornillas paneleras')))
                    
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Tenga en cuenta las siguientes indicaciones.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Durante las pruebas iniciales y periodos de capacitación, los operarios que manejan la hornilla deben tener experiencia para evitar la disminución en la calidad de la panela y vida util de los equipos instalados.')
                                                        item.add_item('El trabajo continuo de la hornilla aumenta la capacidad de producción y evita la perdida de energía, puesto que, al no enfriarse durante las horas de la noche se reduce el efecto del cambio térmico sobre los ladrillos de la estructura.')
                                                        item.add_item('La combustión en la hornilla será buena, si se alimenta con pequeñas cantidades de bagazo cada 150 segundos y la válvula de la chimenea tiene una apertura 60° para garantizar un flujo de aire suficientemente alto que produzca llama, sin arrastrar combustible en los gases residuales.')
                                                        item.add_item('La entrada de aire por orificios diferentes a los proyectados en el diseño inicial debe evitarse a toda costa, para aumentar la eficiencia de la combustión y reducir el material particulado de los gases en la chimenea.')
                                                        item.add_item('Elimine obstáculos en las entradas de aire diseñadas para la hornilla y retire periódicamente la ceniza la parrilla para evitar la formación de escoria.')
                                                        item.add_item('El cenicero y su entrada deben mantenerse despejada a fin de no obstruir el paso del aire.')
                                                        item.add_item('El bagazo para alimentar la hornilla debe tener las condiciones de humedad mencionadas en el diseño.')
                                                        item.add_item('Almacene el bagazo por dos semanas en la bagacera, y así, obtendrá un bagazo con al menos un 30% de humedad.')
                                                        item.add_item('Ajuste el tiro de la chimenea usando la válvula mariposa cuando tenga bagazo con mayor humedad.')
                                                        item.add_item('La válvula no opera en tiempo real y cuando se encuentra a medio cerrar se aumenta la velocidad de calentamiento en la zona de evaporación al pie de la entrada del bagazo. Sin embargo, cuando se encuentra abierta el calentamiento se presenta al pie de la chimenea.')
                                                        item.add_item('El tiempo de residencia del jugo en la hornilla, influye en la calidad de la panela y este es directamente proporcional al aumento de los azucares invertidos.')
                                                        item.add_item('Las falcas en las pailas son de seguridad, no deben usarse para contener una mayor cantidad de jugo. Por tanto para aumentar la transferencia de calor al jugo y mejorar la calidad de la panela es importante manejar la cantidad de jugo mínima en cada paila.')
                                                        item.add_item('El nivel del jugo en las pailas semiesféricas, siempre debe estar por encima de la línea de contacto de los gases de combustión con la paila a fin de evitar quemadura en la panela.')
                                                        item.add_item('La paila clarificadora debe calentar lo más rápido posible para que permita remover la cachaza. Además, la velocidad mínima de calentamiento debe ser de 1.5°C/min.')
                                                        item.add_item('Elimine residuos de la caña o jugos presentes sobre la superficie de las pailas concentradoras de panela y cachaza periódicamente, para que el producto se pegue al fondo. Lo cual disminuye el paso del calor y deterioran la calidad del producto.')

                    tlg.append(LargeText(bold('Mantenimiento de la hornilla')))
                    
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Después de cada molienda.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Limpie y desinfecte las instalaciones, pailas, equipos y utensilios, antes de iniciar nuevamente la producción de panela.')
                                                        item.add_item('Un encelamiento de los moldes, utensilios de madera y prelimpiadores.')
                                                        item.add_item('Dejar en remojo con agua limpia las pailas durante el enfriamiento de la hornilla.')
                                                        item.add_item('Retirar la ceniza del cenicero y el ducto.')
                                                   
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Cada seis moliendas.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Retirar el hollín formado en la superficie de las pailas, por donde se transfiere el calor.')
                                                        item.add_item('Limpiar los ductos de las pailas piro-tubulares, con ayuda de un raspador o un costal de fique.')
    
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Cada seis meses.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('Realice una limpieza general e inspección del estado de los ductos.')
                                                        item.add_item('Realice un mantenimiento de las paredes del ducto y la cámara.')
                                                        
                    tlg.append(LargeText(bold('Recomendaciones de construcción del trapiche')))
                    
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Algunos parámetros para tener en cuenta son.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('El suministro de agua ser potable y continuo.')
                                                        item.add_item('Los alrededores de las fábricas deben estar libre de posibles focos de infección.')
                                                        item.add_item('Las áreas de trabajo de cada subproceso deben estar delimitadas.')
                                                        item.add_item('Las áreas de procesamiento y empaque deben estar separadas de las áreas de recepción y desechos.')
                                                        item.add_item('Las uniones de las baldosas deben recubrirse de materiales plásticos que faciliten la limpieza.')
                                                        item.add_item('Las salientes de las paredes, dinteles de ventanas y suspensiones del techo deben ser curvas e inclinadas.')
                                                        item.add_item('Los pisos y las paredes se deben construir con materiales anticorrosivos, no absorbentes y de alto transito.')
                                                        item.add_item('Las áreas de procesos deben tener en el centro un canal de drenaje con 3° de inclinación y una parrilla removible para realizar su limpieza.')
                                                        item.add_item('Los pisos deben tener una leve inclinación (3°) para realizar el drenado.')
                                                        item.add_item('Los desagües deben tener rejillas de seguridad para impedir el paso de animales.')
                                                        item.add_item('Los ambientes debe ser ventilados.')
                                                        item.add_item('Los vapores deben contar con su propio escape para evitar la presencia de moho en paredes y techos.')
                                                        item.add_item('Los ductos de ventilación deben estar cubiertos de mallas protectoras.')
                                                        item.add_item('Los ambientes deben estar bien iluminados.')
                                                        item.add_item('Las bases o cimientos deben ser lisos para evitar la presencia de insectos o residuos.')
                                                        item.add_item('Los espacios entre los equipos o equipos y paredes deben estar sellados.')
                                                        item.add_item('Los baños, habitaciones y casilleros, deben estar aseados y alejados de las áreas de procesamiento y producto terminado.')
                                                        item.add_item('Las diferentes áreas deben disponer de un sitio para el aseo de las manos con sus respectivos implementos, tales como; jabón líquido, cepillos y toallas desechables.')

                    tlg.append(LargeText(bold('Higiene y desinfección en el trapiche')))
                   
                    with tlg.create(Itemize()) as itemize:
                                            itemize.add_item('Tenga en cuenta las siguientes indicaciones para su cuidado personal.')
                                            with itemize.create(Itemize()) as item:
                                                        item.add_item('El objetivo de la higiene en los alimentos es alargar la vida útil del producto, y proteger al consumidor final de las enfermedades producidas al ingerir alimentos contaminados.')
                                                        item.add_item('La higienización de un trapiche requiere de una limpieza con detergente y de una esterilización industrial o satanización (desinfectante y bactericida).')
                                                        item.add_item('Los equipos y utensilios deben limpiarse y desinfectarse al final e inicio de cada molienda.')
                                                        item.add_item('La limpieza se realiza siguiendo estas pautas: proteger las materias prima y los productos terminados, raspar los residuos sólidos con una espátula sobre un recogedor y lavar con agua limpia, cepillo y detergente')
                                                        item.add_item('La esterilización se realiza con calor (vapor de agua, agua hirviendo), o un esterilizante químico (bactericida, desinfectante).Cuando se emplea agua caliente debe estar hirviendo (90°C) o en el caso del esterilizante químico puede usarse una solución clorada, de vinagre y una lechada de cal.')
                                                        item.add_item('Las soluciones desinfectantes deben aplicarse en solución con un rociador, empezando por la parte inferior.')
                                                        item.add_item('Antes de la esterilización la superficie debe estar limpia y totalmente escurrida.')
                                                        item.add_item('Las superficies en contacto con el alimento deben ser lisas, exentas de huecos, grietas y evitar las esquinas cuadradas.')
                                                        item.add_item('La industria de alimentos usa ampliamente el acero inoxidable y plásticos como el teflón por la facilidad de higienización, y su poca alteración al contacto con los alimentos.')
                                                        item.add_item('No debe usarse el cobre, bronce, estaño, aluminio, madera y zinc para las superficies que están en contacto con el alimento.')
                                                        item.add_item('No emplee en la limpieza esponjas o cepillos metálicos que rayen las superficies.')
                                                        item.add_item('Las pailas se lavan con arena de peña y esponja para desmancharla.')
                                                        item.add_item('Ningún tipo de rosca debe estar en contacto con el alimento.')
                                                        item.add_item('Se debe mantener una inclinación de superficies y tubería para el drenaje de 1 centímetro por metro.')
                                                        item.add_item('Se deben usar conexiones hidraulicas y uniones que sean de fácil limpieza.')
                                                        item.add_item('Se debe evitar la unión de acero inoxidable con otros metales.')
                                                        item.add_item('El hipoclorito ejerce una rápida acción bactericida sin dejar residuos tóxicos.')
                                                        item.add_item('No es aconsejable el uso de cloro en material de acero inoxidable.')
                                                        item.add_item('En la esterilización del acero inoxidable, puede utilizarse agua caliente, vapor o solución de 0.25 litros de vinagre en 10 litros de agua.')
                                                        item.add_item('Los materiales plásticos se deben lavar con una solución de 5.0 gramos de bicarbonato (2 cucharadas) en l0 litros de agua clorada y dejar secar durante 30 minutos.')
                                                        item.add_item('La esterilización del acero inoxidable puede hacerse con agua caliente, vapor o solución de 0.25 litros de vinagre en 10 litros de agua.')
                                                        item.add_item('Las superficies de madera se limpian con espátula para eliminar los residuos sólidos. Después remojar en detergente durante 5 minutos, luego cepillar, lavar con agua limpia, y finalmente rociar con solución de 12 gramos de cal (una cucharadita) en 10 litros de agua dejar secar.')  
                                                        item.add_item('Los utensilios de madera se dejan en un recipiente plástico limpio, con solución de 12 gramos de cal (una cucharadita) en 10 litros de agua.')  
                                                        item.add_item('Cambiar la solución donde se sumergen los utensilios de madera cada cuatro horas.') 
                                                        item.add_item('Los utensilios y gaveras no deben dejarse sobre el suelo o superficies no desinfectadas.') 
                                                        item.add_item('Evitar la caída de grasa mecánica en los alimentos.')

        doc.append(NewPage())
示例#15
0
def get_test_description(doc, testnumber):
    doc.append(NewPage())
    description = UnsafeCommand(
        'input', 'test_description/test_{}.tex'.format(testnumber))
    doc.append(description)
示例#16
0
def generate_report(main_title, name, title, email, payroll):

    # For saving the report in the Desktop folder
    dir_output=os.path.join(
        '~',
        'Desktop',
        'absconbest_payroll',
        'output'
    )
    dir_output=os.path.expanduser(dir_output)
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating
    # first page style
    first_page = PageStyle("firstpage")

    # Header image
    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:
            logo_file = 'logo.png'
            logo_wrapper.append(
                StandAloneGraphic(
                    image_options="width=120px",
                    filename=logo_file
                )
            )

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(MiniPage(
            width=NoEscape(r"0.49\textwidth"),
            pos='c',
            align='r')
        ) as title_wrapper:
            title_wrapper.append(LargeText(bold('Payroll Report')))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold(main_title)))

    # Add footer
    with first_page.create(Foot("C")):
        first_page.append(simple_page_number())

    doc.preamble.append(first_page)

    #Add employee information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        employee = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        employee.append(name)
        employee.append("\n")
        employee.append(title)
        employee.append("\n")
        employee.append(email)

        #Dummy table
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='t!',
                          align='r')
        # branch.append(bold("1181..."))
        # branch.append(LineBreak())
        # branch.append(bold("TIB Cheque"))

        first_page_table.add_row([employee, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    #Add payroll table
    with doc.create(LongTabu("X[l] X[c] X[c] X[c] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(['Work',
                            'Rate Per Hour ($)',
                            'Time in Minutes',
                            'Time in Hours',
                            'Wage ($)'],
                           mapper=bold,
                           color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()

        #Following Pandas' API
        payroll=payroll.reset_index()
        for i in range(len(payroll.index)):
            try:
                row = [payroll['Work'][i],
                       round(payroll['Rate Per Hour'][i],0),
                       round(payroll['TIM'][i],0),
                       round(payroll['TIH'][i],3),
                       round(payroll['Wage'][i],1)]
            except TypeError:
                row = [payroll['Work'][i],
                       'n/a',
                       round(payroll['TIM'][i],0),
                       round(payroll['TIH'][i],3),
                       round(payroll['Wage'][i],1)]
            if (i%2)==0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)
        # data_table.add_row([payroll['Work'][l_p],
        #                     round(payroll['TIM'][l_p],0),
        #                     round(payroll['TIH'][l_p],3),
        #                     '',
        #                     round(payroll['Wage'][l_p],1)]
        # )

    doc.append(NewPage())

    doc.generate_pdf(
        filepath=os.path.join(
dir_output,
            main_title.lower().replace(" ","_").replace(",",""),
        ),
        clean_tex=True,
        clean=True,
    )
示例#17
0
def functioning(doc, sub_list=[["1"], ["1"], ["1"]]):
    """Add a cover page to the document.

    :param doc: the document
    :type doc: :class:`pylatex.document.Document` instance
    :param fun_map: name of the functioning map
    :type doc: :string:
    """

    doc.append(NewPage())
    doc.append(NoEscape(r"\chapter{FUNCIONAMIENTO \\DE LAS ESTACIONES}"))
    #doc.append(NoEscape(r"\chapterimage{"+ruta+"bulletfiles/sgc_blanco2.jpg}"))
    if sub_list[1][0] == "0":
        if sub_list[2][0] == "1":
            doc.append(NoEscape(r"\begin{landscape}"))

    # =======================================================================
    #  Mapa estaciones
    # =======================================================================
    if sub_list[1][0] == "1":
        doc.append(
            NoEscape(r"\section{Mapa de funcionamiento de las estaciones}"))
        #doc.append(NoEscape(r"\vspace{0.1cm}"))
        doc.append(NoEscape(r"\begin{figure}[h!]"))
        doc.append(NoEscape(r"\begin{minipage}{\textwidth}"))

        file_inspector(sub_list[1][1])

        doc.append(NoEscape(r"\begin{center} "))
        doc.append(NoEscape(r"\vspace{-0.4cm}"))
        doc.append(
            NoEscape(r"\includegraphics[scale=0.14]{%s}" % sub_list[1][1]))
        #		doc.append(NoEscape(r"\vspace{-1.0cm}"))
        doc.append(
            NoEscape(
                r"\caption{\small{Localizaci\'on de las estaciones de la RSNC. Las antenas rojas y azules representan las estaciones con sensores de banda ancha y corto periodo,  respectivamente. Las antenas negras representan estaciones internacionales.}}%\\"
            ))
        doc.append(NoEscape(r"\end{center}"))

        add_text(sub_list[1][2], doc)
        doc.append(NoEscape(r"\end{minipage}"))
        doc.append(NoEscape(r"\end{figure}"))

    # =======================================================================
    #  Tabla de funcionamiento de las estaciones
    # =======================================================================
    if sub_list[0][0] == "1":
        doc.append(NoEscape(r"\newpage"))
        doc.append(
            NoEscape(r"\section{Tabla de funcionamiento de las estaciones}"))
        doc.append(NoEscape(r"\newpage"))

    # =======================================================================
    #  Histograma de funcionamiento de las estaciones
    # =======================================================================
    if sub_list[2][0] == "1":
        file_inspector(sub_list[2][1])
        if sub_list[1][0] == "1":
            doc.append(NoEscape(r"\newpage"))

        if sub_list[1][0] == "1":
            doc.append(NoEscape(r"\begin{landscape}"))
            doc.append(NoEscape(r"\begin{figure}"))
            doc.append(NoEscape(r"\begin{minipage}{\textwidth}"))
        doc.append(
            NoEscape(
                r"\section{Histograma de funcionamiento de las estaciones}"))
        doc.append(NoEscape(r"\begin{center}"))
        doc.append(
            NoEscape(r"\includegraphics[scale=0.85]{%s}" % sub_list[2][1]))
        doc.append(NoEscape(r"\end{center}"))

        # Agregando o no texto, sobre histograma de funcionamiento
        add_text(sub_list[2][2], doc)
        doc.append(NoEscape(r"\end{minipage}"))
        doc.append(NoEscape(r"\end{figure}"))
        doc.append(NoEscape(r"\end{landscape}"))
示例#18
0
              width=NoEscape(r'0.8\linewidth'))

core.pre_append(title=Command('heiti', '试卷示例'),
                author=Command('kaishu', '六个骨头'),
                date=Command('today'))
core.body_append(Command('maketitle'))
core.body_append(
    NoEscape(r'本试卷分为100分的必答题和10分的选做题,选做题做对加分,'
             r'做错不扣分,最多累计10分,整卷最高分110分。'))

core.body_append(NoEscape(r"\vspace{15cm}"))
with core.create(Center()) as centered:
    core.body_append(NoEscape(r'\bf{姓名}\ \underline{\hbox to 20mm{}}'),
                     NoEscape(r'\bf{学号}\ \underline{\hbox to 20mm{}}'),
                     NoEscape(r'\bf{编号}\ \underline{\hbox to 20mm{}}'))
core.body_append(NewPage())

#  ——————————题目内容——————————

p2 = Question(core, name="填空题", describe="", scores=7)
p3 = Question(core, name="解答题", describe="解答应写出文字说明、证明过程或演算步骤.", line_space=50)
p4 = Question(core, name="选做题", describe="考生根据心情作答,酌情给分.", line_space=50)

# with core.local_define([r"\d "], [r"\text{d}"]) as local_core:
#     local_core.append(NoEscape(r"$\d2 \d \dx<d>x$"), mode="command")

p2.set(
    r"设$\alpha \in[0.01,0.98]$, 则"
    r"$\lim_{n \to \infty}\left[(n+1)^{\alpha}-n^{\alpha}\right]=\underline{\hspace*{4em}}$",
    r"极限 $\lim_{n\to\infty}\sin^2\big(\pi\sqrt{n^2+n}\big)=\underline{\hspace*{4em}}$",
    r"设 $w=f(u,v)$ 具有二阶连续偏导数, 且 $u=x-cy$, $v=x+cy$. 其中 $c$ 为非零常数.\\"
def generate_unique():
    geometry_options = {
        "head": "40pt",
        "margin": "0.5in",
        "bottom": "0.6in",
        "includeheadfoot": True
    }
    doc = Document(geometry_options=geometry_options)

    # Generating first page style
    first_page = PageStyle("firstpage")

    # Header image
    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:
            logo_file = os.path.join(os.path.dirname(__file__),
                                     'sample-logo.png')
            logo_wrapper.append(
                StandAloneGraphic(image_options="width=120px",
                                  filename=logo_file))

    # Add document title
    with first_page.create(Head("R")) as right_header:
        with right_header.create(
                MiniPage(width=NoEscape(r"0.49\textwidth"), pos='c',
                         align='r')) as title_wrapper:
            title_wrapper.append(LargeText(bold("URCF Proteus Usage Report")))
            title_wrapper.append(LineBreak())
            title_wrapper.append(MediumText(bold("Date")))

    # Add footer
    with first_page.create(Foot("C")) as footer:
        message = "Important message please read"
        with footer.create(
                Tabularx(
                    "X X X X",
                    width_argument=NoEscape(r"\textwidth"))) as footer_table:

            footer_table.add_row(
                [MultiColumn(4, align='l', data=TextColor("blue", message))])
            footer_table.add_hline(color="blue")
            footer_table.add_empty_row()

            branch_address = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                      pos='t')
            branch_address.append("960 - 22nd street east")
            branch_address.append("\n")
            branch_address.append("Saskatoon, SK")

            document_details = MiniPage(width=NoEscape(r"0.25\textwidth"),
                                        pos='t',
                                        align='r')
            document_details.append("1000")
            document_details.append(LineBreak())
            document_details.append(simple_page_number())

            footer_table.add_row([
                branch_address, branch_address, branch_address,
                document_details
            ])

    doc.preamble.append(first_page)
    # End first page style

    # Add customer information
    with doc.create(Tabu("X[l] X[r]")) as first_page_table:
        customer = MiniPage(width=NoEscape(r"0.49\textwidth"), pos='h')
        customer.append("Verna Volcano")
        customer.append("\n")
        customer.append("For some Person")
        customer.append("\n")
        customer.append("Address1")
        customer.append("\n")
        customer.append("Address2")
        customer.append("\n")
        customer.append("Address3")

        # Add branch information
        branch = MiniPage(width=NoEscape(r"0.49\textwidth"),
                          pos='t!',
                          align='r')
        branch.append("Branch no.")
        branch.append(LineBreak())
        branch.append(bold("1181..."))
        branch.append(LineBreak())
        branch.append(bold("TIB Cheque"))

        first_page_table.add_row([customer, branch])
        first_page_table.add_empty_row()

    doc.change_document_style("firstpage")
    doc.add_color(name="lightgray", model="gray", description="0.80")

    # Add statement table
    with doc.create(LongTabu("X[l] X[2l] X[r] X[r] X[r]",
                             row_height=1.5)) as data_table:
        data_table.add_row(
            ["date", "description", "debits($)", "credits($)", "balance($)"],
            mapper=bold,
            color="lightgray")
        data_table.add_empty_row()
        data_table.add_hline()
        row = ["2016-JUN-01", "Test", "$100", "$1000", "-$900"]
        for i in range(30):
            if (i % 2) == 0:
                data_table.add_row(row, color="lightgray")
            else:
                data_table.add_row(row)

    doc.append(NewPage())

    # Add cheque images
    with doc.create(LongTabu("X[c] X[c]")) as cheque_table:
        cheque_file = os.path.join(os.path.dirname(__file__),
                                   'chequeexample.jpg')
        cheque = StandAloneGraphic(cheque_file, image_options="width=200px")
        for i in range(0, 20):
            cheque_table.add_row([cheque, cheque])

    doc.generate_pdf("simple_report", clean_tex=False)
示例#20
0
    def peripheral_fill(self, periph, periph_name):
        self.doc.append(NewPage())
        periph_subsection = Section(periph_name, numbering=True)
        periph_subsection.append(periph.get_description().replace('""', ''))
        periph_reg_section = Subsection(
            "{} register slave".format(periph_name), numbering=False)
        periph_reg_table = Tabular('|c|c|c|c|')
        periph_reg_table.add_hline()
        periph_reg_table.add_row(
            ('Base Address', 'Range', 'Register group', 'Number of Slaves'))
        periph_reg_table.add_hline()
        # slave_subsections = ("{} slaves".format(periph_name), numbering=False)
        # slave_subsections = []
        # slave_subsections.append(NewLine())
        # slave_subsections.append(MediumText(bold("Slave Ports for peripheral " + periph_name + "\n")))
        slave_subsections = Subsection(
            "Slave Ports for peripheral \'{}\'".format(periph_name),
            numbering=False)
        for slave in periph.slaves:

            #self.doc.add(text=val_type, size="medium")

            # added_val_types = []
            # for key, val in sorted(val_info.items()):
            # if val.name() in added_val_types:
            # continue
            # added_val_types.append(val.name())
            slave_subsection = Subsection("Slave Port: {} ({})".format(
                slave.name(), 'Register block' if isinstance(slave, Register)
                else 'RAM' if isinstance(slave, RAM) else 'FIFO'),
                                          numbering=True)
            slave_subsection.append(slave.get_kv('slave_description'))
            slave_subsection.append(NewLine())
            # slave_subsection.append("Slave Type: {}".format('REGISTER' if isinstance(slave, Register) else 'RAM' if isinstance(slave, RAM) else 'FIFO'))
            slave_subsection.append(NewLine())
            slave_subsection.append("Address Length: {} bytes".format(
                str(slave.address_length())))
            slave_subsection.append(NewLine())
            slave_subsection.append("Number of Slaves: {}".format(
                str(slave.number_of_slaves())))
            slave_subsection.append(NewLine())
            slave_subsection.append(NewLine())

            # if val_type == 'Registers':
            if isinstance(slave, Register):  # expand registers and fields
                for ram in slave.rams:
                    periph_reg_table.add_row(
                        (str(ram.base_address()), str(ram.number_of_fields()),
                         ram.name() + ' (RAM)', str(slave.number_of_slaves())))
                    periph_reg_table.add_hline()
                periph_reg_table.add_row(
                    (str(slave.base_address()), str(slave.address_length()),
                     slave.name(), str(slave.number_of_slaves())))
                periph_reg_table.add_hline()
                added_field_groups = []
                # with self.doc.create(Subsection("{} Register Fields".format(val.name().lower()), numbering=True)):
                # if val.get_kv('slave_description') is not None:
                # slave_subsection.append(val.get_kv('slave_description').replace('"', ''))

                # generate register table i.e. by word
                group_address = -1
                group_list = []
                for field in slave.fields:
                    if field.address_offset() != group_address:
                        group_address = field.address_offset()
                        group_list.append(field)
                        # addr_name = field.group_name() if field.group_name() != "None" else field.name()

                        # slave_table.add_row(str(hex(field.address_offset())), addr_name)
                        # slave_table.add_hline()
                c_max_rows = 30
                nof_cols = ceil(
                    len(group_list) /
                    c_max_rows)  # register table has max length of 40
                nof_rows = min(len(group_list), c_max_rows)
                slave_table = Tabular('|c|c|' * nof_cols)
                slave_table.add_hline()
                # slave_table.add_row((*['Hex','Field Group']*nof_cols))
                slave_table.add_row(['Hex', 'Field Group'] * nof_cols)
                slave_table.add_hline()
                for i in range(nof_rows):
                    row = []
                    for j in range(nof_cols):
                        if i + c_max_rows * j < len(group_list):
                            field.group_name() if field.group_name(
                            ) != "None" else field.name()
                            row.extend([
                                str(
                                    hex(group_list[i + c_max_rows *
                                                   j].address_offset())),
                                group_list[i + c_max_rows * j].name()
                            ])
                        else:
                            row.extend(['', ''])
                    # slave_table.add_row(*row)
                    slave_table.add_row(row)
                    slave_table.add_hline()

                slave_subsection.append(slave_table)
                slave_subsection.append(NewPage())

                group_address = -1
                for field in slave.fields:
                    # if field.group_name() is None or field.group_name() != last_group: # base on group_address instead
                    # print("field {} address {} bit{}".format(field.name(), str(field.address_offset()), str(field.bit_offset())))
                    if field.address_offset() != group_address:
                        group_address = field.address_offset()
                        # group_page = MiniPage()
                        group_subsection = Subsection('{} {}'.format(
                            str(hex(field.address_offset())),
                            field.name() if field.group_name() == 'None' else
                            field.group_name()),
                                                      numbering=False)
                        group_fields = [
                            field for field in slave.fields
                            if field.address_offset() == group_address
                        ]
                        if len(group_fields) > 10:
                            slave_subsection.append(NewPage())
                        group_subsection = gen_reg_tables(
                            group_subsection, group_fields)
                        for field in group_fields[::-1]:
                            field_name = field.name() if field.group_name(
                            ) == 'None' else field.name().split(
                                field.group_name() + '_')[-1]
                            bit_string = "Bit {}".format(
                                str(field.bit_offset())) if field.width(
                                ) == 1 else "Bits {}:{}".format(
                                    str(field.bit_offset() + field.width() -
                                        1), str(field.bit_offset()))
                            group_subsection.append(
                                bold("{}\t\t{} ({}):".format(
                                    bit_string, field_name,
                                    field.access_mode())))
                            group_subsection.append("\t\t{}".format(
                                field.field_description()))
                            group_subsection.append(NewLine())
                            group_subsection.append(NewLine())
                        # group_page.append(group_subsection)
                        slave_subsection.append(group_subsection)
            else:  # RAM or FIFO
                slave_subsection.append("Data width: {}".format(slave.width()))
                slave_subsection.append(NewLine())
                if isinstance(slave, RAM):
                    slave_subsection.append("User data width: {}".format(
                        slave.user_width()))

            slave_subsections.append(slave_subsection)
        periph_reg_section.append(periph_reg_table)
        self.doc.append(periph_subsection)
        if any([isinstance(slave, Register) for slave in periph.slaves]):
            self.doc.append(periph_reg_section)
        # for i in range(len(slave_subsections)):
        # self.doc.append(slave_subsections[i])
        self.doc.append(slave_subsections)

        # self.doc.append(periph_section)
        self.doc.append(NewPage())
doc.preamble.append(
    Command('title', 'Trounceflow Countries: Dominican Republic'))
doc.preamble.append(Command('author', 'Michael Trounce'))
doc.preamble.append(Command('date', NoEscape(r'\today')))
doc.append(NoEscape(r'\maketitle'))

doc.append(NoEscape(r'\begin{abstract}'))
doc.append(
    "The `Trounceflow Countries' series of `living' documents provide real-time dynamic summaries of macroeconomic data relevant to the flows-and-positions analysis of emerging market debt. These macroeconomic data concentrate on the structure of the government bond market but also include other useful but hard-to-wrangle data such as the structure of the local institutional investor base. The data is obtained from the Trounceflow App (trounceflow.com) and the document data is automatically updated in line with the automatic updates on the App; links to the underlying national sources are also given in the `living' documents."
)
doc.append(
    LargeText(
        "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nThe values presented in this report are the face values of the bonds"
    ))
doc.append(NoEscape(r'\end{abstract}'))
doc.append(NewPage())

#Table of Contents
doc.append(NoEscape(r'\tableofcontents'))
doc.append(NewPage())

#Summary Chapter 1
doc.append(NoEscape(r'\chapter{Executive Summary}'))
doc.append(NewPage())

#Chapter 2
doc.append(
    NoEscape(
        r'\chapter{Central Government Debt: Bonds, Issuers and Investors}'))
doc.append(NewPage())
示例#22
0
 def fill_document(self, data, escape=False):
     if escape:
         self.append(data)
     else:
         self.append(NoEscape(data))
     self.append(NewPage())