1 #!/usr/bin/env python
  2 
  3 # DESCRIPTION: Use pil and pdflib_py to build a poster
  4 
  5 # $Id: afdemag-poster.py,v 1.8 2005/02/28 03:46:20 schwehr Exp $
  6 
  7 ######################################################################
  8 #     Copyright (C) 2005  Kurt Schwehr
  9 #
 10 #    This program is free software; you can redistribute it and/or modify
 11 #    it under the terms of the GNU General Public License as published by
 12 #    the Free Software Foundation; either version 2 of the License, or
 13 #    (at your option) any later version.
 14 #
 15 #    This program is distributed in the hope that it will be useful,
 16 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
 17 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 18 #    GNU General Public License for more details.
 19 #
 20 #    You should have received a copy of the GNU General Public License
 21 #    along with this program; if not, write to the Free Software
 22 #    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
 23 ######################################################################
 24 
 25 import os	# os.remove()
 26 import sys	# sys.exit()
 27 import string
 28 import sqlite	# pysqlite
 29 import Image	# pil-py --- python image library
 30 from pdflib_py import * # PDFLib Lite
 31 
 32 import datetime # for date.today()
 33 
 34 EXIT_SUCCESS=0
 35 EXIT_FAILURE=1
 36 
 37 dbFileName = "/Users/schwehr/projects/xcore/data/BPSIO-04/bpsio04.db"
 38 
 39 
 40 def mag_get_afdemag_list(db_cx, coreNum):
 41     """Return a list of the afdemag samples for that core from shallow to deep"""
 42     cu = db_cx.cursor()
 43     searchStr  = "SELECT samplename FROM mag"
 44     searchStr += " WHERE type='afdemag' AND treatment='0' AND corenum='"+str(coreNum)+"'"
 45     searchStr += " ORDER BY depth"
 46     searchStr += ";"
 47     cu.execute(searchStr)
 48     samples = []
 49     for row in cu.fetchall():
 50         name=row['samplename']
 51         #print name
 52         if len(samples)>0:
 53             if samples[-1] == name:
 54                 #print "SKIPPING duplicate: ", name
 55                 continue
 56         samples.append(name)
 57     return samples
 58     
 59 
 60 def total_samples(db_cx):
 61     """Return the total number of unique sample names in the mag and weight tables"""
 62     cu = db_cx.cursor()
 63     s = set()
 64     cu.execute("SELECT samplename FROM weights")
 65     for row in cu.fetchall():
 66         s.add(row['samplename'])
 67     cu.execute("SELECT samplename FROM mag")
 68     for row in cu.fetchall():
 69         s.add(row['samplename'])
 70     return(len(s))
 71 
 72 
 73 ######################################################################
 74 
 75 def plotdmag_lisa(db_cx,samplename):
 76     """ Shell out to Lisa's plotdmag to make a postscript Zijderveld (sp?) demag plot"""
 77 
 78     psFileName = samplename + "-afdmag.ps"
 79     tmpMagFile = samplename + ".mag"
 80 
 81 
 82     cu = db_cx.cursor()
 83     searchStr = "SELECT * FROM mag WHERE samplename='"+samplename+"' and type='afdemag' ORDER BY treatment;"
 84     #print searchStr
 85     cu.execute (searchStr)
 86     magFile = open(tmpMagFile,"w")
 87     for row in cu.fetchall():
 88         #print row['samplename'],row['treatment'], row['csd'], row['intensity'], row['dec'], row['inc']
 89         magFile.write(row['samplename']+" "+str(row['treatment'])+" ")
 90         magFile.write(str(row['intensity'])+" "+ str(row['dec'])+" "+ str(row['inc']) +" "+ "\n")
 91     magFile.close()
 92     sysStr = "plotdmag < "+tmpMagFile+" | plotxy"
 93     print sysStr
 94     os.system (sysStr)
 95     os.rename("mypost",psFileName)
 96     os.remove(tmpMagFile)
 97     return psFileName
 98 
 99 
100 ######################################################################
101 
102 if __name__ == '__main__':
103     print "Starting to generate the data types.  Thanks for using python"
104 
105     cx = sqlite.connect (dbFileName);
106 
107     corelists=[0] # Nothing for non-existant core 0
108     for corenum in range(1,7):
109         corelists.append(mag_get_afdemag_list(cx,corenum))
110         print corenum, " --- ", len(corelists[corenum])
111 
112     total = 0
113     for corenum in range(1,7):
114         total += len(corelists[corenum])
115     print "Total number of AF demags:    ", total, "(out of ", total_samples(cx),")"
116 
117     # Create the poster-sized PDF
118 
119     pdf = PDF_new()
120     if -1 == PDF_open_file(pdf,"afdemag-poster.pdf"):
121         print "Error: " + PDF_get_errmsg(pdf) + "\n"
122         exit(EXIT_FAILURE)
123 
124     PDF_set_info(pdf, "Creator", "afdemag-poster.py")
125     PDF_set_info(pdf, "Author", "Kurt Schwehr")
126     PDF_set_info(pdf, "Title", "AF Demag of BPSIO-2004 cubes")
127 
128     points36Inches = 2592
129     points72Inches = 5184
130     PDF_begin_page(pdf,points36Inches,points72Inches);
131     #font = PDF_load_font(pdf,"Helvetica-Bold",0,"host","")
132     font = PDF_load_font(pdf,"Helvetica-Bold","iso8859-1","")
133     PDF_setfont(pdf,font, 42)
134     PDF_set_text_pos(pdf,800,5000)
135     PDF_show(pdf,"BPSIO 2004 -- AF Demagnetization -- "  + str(datetime.date.today()));
136 
137 
138     # For each core
139     for corenum in range(1,7):
140 
141         y = 4700
142         x = 10+corenum*300
143 
144         print "\n\n CORENUM: " + str(corenum)
145         print " Placing at", x, y
146 
147         bigPsFile = str(corenum)+"-afdemag.ps"  # Cat all the sample ps files into one big one
148         bigPdfFile = str(corenum)+"-afdemag.pdf"  # Cat all the sample ps files into one big one
149         if os.access(bigPsFile,os.W_OK):
150             os.remove(bigPsFile);
151 
152         PDF_set_text_pos(pdf,x + 50,y+250)
153         PDF_show(pdf,"Core "+str(corenum))
154         for sample in corelists[corenum]:
155             # For each sample...
156             print "\n  === " + sample + " ===\n"
157 
158             # first make the af demag plots with Lisa's plotdmag
159             psFileName = plotdmag_lisa(cx,sample)
160             os.system("cat " + psFileName + ">> " + bigPsFile)
161 
162             # convert ps to portable bit map
163             sampleImage=sample+".pbm"
164             finalImage=sample+".png"
165             os.system("pstopnm -pbm -dpi=150 -stdout "+psFileName+" > "+sampleImage)
166 
167             os.remove(psFileName) # All done with this!
168 
169             # Trim the plot to the minimum size
170             i = Image.open(sampleImage)
171             left = 136;  right = 1250;  upper = 172;   lower = 1200;
172             icrop = i.crop((left, upper, right, lower))
173             icrop.save(finalImage,"png")
174             os.remove(sampleImage) # Don't need the pbm any more
175 
176             # Add the trimmed png to the pdf
177             pdfImage = PDF_load_image(pdf,"auto", finalImage, "")
178             if -1 != pdfImage:
179                 PDF_fit_image(pdf,pdfImage,x,y,"scale 0.2")
180                 PDF_close_image(pdf,pdfImage)
181                 y -= 200
182                 if y< 0:
183                     print "ERROR: Ran off the bot of the page!"
184                     os.exit(EXIT_FAILURE)
185                 os.remove(finalImage)
186             else:
187                 print "ERROR: unable to load image ", finalImage
188 
189         # convert the big ps file into a multipage pdf
190         if os.access(bigPsFile,os.W_OK):
191             os.system("ps2pdf "+ bigPsFile + " " + bigPdfFile)
192             os.remove(bigPsFile);
193 
194     PDF_end_page(pdf)
195     PDF_close(pdf)
196     PDF_delete(pdf)
197     
198               
199     print "Done!"


syntax highlighted by Code2HTML, v. 0.9.1