P4.6.2Saving a polymer image
Add a method, save_svg to the Polymer class of Example E4.19 to save an image of its polymer as an SVG file. Refer to Exercise P4.4.3 for a template of an SVG file.
Show solution
The method listed below can be added to the Polymer class and called on an instance of this class to save an SVG representation of the polymer. It centres the image on a \(500 \times 500\) pixel canvas and projects the monomer unit positions onto the \((x,y)\) plane.
def save_svg(self, svg_name="polymer.svg"): # webonly
canvas_width, canvas_height = 500, 500
background_colour = "white"
fo = open(svg_name, "w")
print(
f"""<?xml version="1.0" encoding="utf-8"?>
<svg xmlns="http://www.w3.org/2000/svg"
xmlns:xlink="http://www.w3.org/1999/xlink"
width="{canvas_width}" height="{canvas_height}"
style="background: {background_colour}">""",
file=fo,
)
ccx, ccy = canvas_width / 2, canvas_height / 2
scale = 10
x, y, z = zip(*self.xyz)
xmin, xmax, ymin, ymax = min(x), max(x), min(y), max(y)
dmax = max(xmax - xmin, ymax - ymin)
scale = min(canvas_width, canvas_height) / dmax
for i in range(1, self.N):
x1, y1 = x[i - 1] * scale + ccx, y[i - 1] * scale + ccy
x2, y2 = x[i] * scale + ccx, y[i] * scale + ccy
print(
f'<line x1="{x1:.1f}" y1="{y1:.1f}" x2="{x2:.1f}"'
f' y2="{y2:.1f}" style="stroke: "black"; stroke-width: 2;"/>',
file=fo
)
print("</svg>", file=fo)
An example output image is given below.
from polymer import Polymer
Polymer.save_svg = save_svg
N, a = 1000, 1.0
polymer = Polymer(N, a)
polymer.save_svg("polymer.svg")