# Python script to generate the Standard Linear Correlation Coefficient # slide for the presentation at the CCP4 Study Weekend 2001. # # Software required to run this script (this software is freely available): # Python 1.5.2, http://www.python.org/ # ReportLab 1.00, http://www.reportlab.com/ # # conversion of resulting PDF file to GIF (for import in PowerPoint): # Photoshop -> File -> Open *.pdf, Resolution = 150 pixels/inch # File -> Save for Web import math import random from reportlab.pdfgen import canvas from reportlab.lib.units import inch random.seed(123456) golden_ratio = (math.sqrt(5.) + 1.) / 2. def compute_cc(x, y): Nxy = len(x) assert Nxy == len(y) Sx = 0. Sx2 = 0. Sy = 0. Sy2 = 0. Sxy = 0. for i in xrange(Nxy): Sx = Sx + x[i] Sx2 = Sx2 + x[i] * x[i] Sy = Sy + y[i] Sy2 = Sy2 + y[i] * y[i] Sxy = Sxy + x[i] * y[i] d = ( (Sx2 - Sx * Sx / Nxy) * (Sy2 - Sy * Sy / Nxy)) c = 0. if (d > 0.): c = (Sxy - Sx * Sy / Nxy) / math.sqrt(d) return c class CCCanvas(canvas.Canvas): def __init__(self, filename): self.px = (3 * golden_ratio + 0.4) * inch self.py = 3.4 * inch canvas.Canvas.__init__(self, filename, pagesize = (self.px, self.py)) self.closing = 0 self.setup_coordiante_system() def setup_coordiante_system(self): self.translate(0.48 * inch, 0.3 * inch) self.scale(1.1 * inch, 1.1 * inch) def showPage(self): if (not self.closing): canvas.Canvas.showPage(self) self.setup_coordiante_system() def save(self): self.closing = 1 canvas.Canvas.save(self) def scatter_plot(c, origin, x, y): assert len(x) == len(y) c.saveState() c.translate(origin[0], origin[1]) c.setStrokeColorRGB(0, 0, 0) c.setLineWidth(0.01) c.line(0, 0, 1, 0) c.line(0, 0, 0, 1) c.setFillColorRGB(0, 0, 0) p = c.beginPath() p.moveTo(1, 0) p.lineTo(0.95, 0.024) p.lineTo(0.95, -0.024) p.close() c.drawPath(p, stroke = 0, fill = 1) p = c.beginPath() p.moveTo(0, 1) p.lineTo(-0.024, 0.95) p.lineTo(0.024, 0.95) p.close() c.drawPath(p, stroke = 0, fill = 1) c.setFont("Helvetica", 0.1) c.drawCentredString(0.9, -0.1, 'x') c.drawCentredString(-0.1, 0.9, 'y') cc = compute_cc(x, y) caption = 'CC = %5.2f' % (cc,) print caption c.drawCentredString(0.5, 1.07, caption) for i in xrange(len(x)): c.circle(x[i], y[i], 0.01, stroke = 0, fill = 1) c.restoreState() if (__name__ == '__main__'): origins = ( (0, 1.45), (1.4, 1.45), (2.8, 1.45), (0, 0), (1.4, 0), (2.8, 0), ) c = CCCanvas('plot.pdf') nPoints = 100 x = [0] * nPoints for i in xrange(nPoints): x[i] = random.random() y = [0] * nPoints pos = 0 for f in (0., 0.6, 1.3, -1., 0.9, 4.): if (f < 0.): for i in xrange(nPoints): y[i] = math.fmod(1. - x[i], 1.) else: for i in xrange(nPoints): while 1: y[i] = x[i] + (random.random() - 0.5) * f if (y[i] >= 0. and y[i] < 1.): break scatter_plot(c, origins[pos], x, y) pos = pos + 1 c.showPage() c.save()