def main(): A4_lsc = document.paperformat( document.paperformat.A4.height, document.paperformat.A4.width) text.set(text.UnicodeEngine, fontname="cmss12", size=12) pages = [] for i in ( ('C', 'Am', 'C#', 'A#m'), ('D', 'Bm', 'D#', 'Cm'), ('E', 'C#m', 'F', 'Dm'), ('F#', 'D#m', 'G', 'Em'), ('G#', 'Fm', 'A', 'F#m'), ('A#', 'Gm', 'B', 'G#m') ): c = canvas.canvas() c.text(0, 32, f'{i[0]} Pentatonic Scale') Pentatonic(0, 26, i[0]).render(c, intervals=True) c.text(0, 24, f'{i[1]} Pentatonic Scale') Pentatonic(0, 18, i[1]).render(c, intervals=True) c.text(0, 16, f'{i[2]} Pentatonic Scale') Pentatonic(0, 10, i[2]).render(c, intervals=True) c.text(0, 8, f'{i[3]} Pentatonic Scale') Pentatonic(0, 2, i[3]).render(c, intervals=True) page = document.page(c, paperformat=A4_lsc, fittosize=1, margin=2) pages.append(page) doc = document.document(pages=pages) doc.writePDFfile("pentatonic")
def flush(ca, name): posterformat = document.paperformat(unit.length(24, unit="inch"), unit.length(24, unit="inch")) #p = document.page(ca, paperformat = posterformat) p = document.page(ca, paperformat=document.paperformat.A4, fittosize=1) d = document.document(pages=[p]) d.writePSfile(name)
def backup(): inFolder = Path(args.input) memTar = BytesIO() tar = tarfile.open(fileobj=memTar, mode="x") for itm in inFolder.iterdir(): tar.add(itm.resolve(), arcname=itm.relative_to(inFolder)) tar.close() content = memTar.getvalue() memTar.close() content = compress(content) b85Content = b85encode(content).decode("UTF-8") pdf = document() pdfPage = None counter = 0 while b85Content: b85Content = str(counter) + ">" + b85Content chunk, b85Content = maxSplit(b85Content) if b85Content is None: chunk = chunk[:chunk.index(">")] + "<" + chunk[ chunk.index(">") + 1:] #Signal last chunk print("Generating QRCode for chunk " + str(counter) + ", " + (str(len(b85Content)) if b85Content else "0") + " bytes remaining") qrCode = QRencode(chunk) #Used for debugging if args.plainChunk: f = open("chunk" + str(counter) + ".chunk", "w") f.write(chunk) f.close if counter % 6 == 0: pdfPage = page(canvas(), paperformat=paperformat.A4, centered=0) pdf.append(pdfPage) pdfPage.canvas.insert( bitmap(**pdfImagePlacement(counter), image=qrCode.convert("LA"))) if args.makeBmp: qrCode.save("chunk" + str(counter) + ".bmp") counter += 1 print("Writing to pdf...") outFile = Path(args.output) if (outFile.suffix == ".pdf"): pdf.writePDFfile(args.output) else: pdf.writePDFfile(args.output + ".pdf") print("Done")
def generate_tile(item): title = item['title'] print(title) image = item['image'] if item['quantity'] > 1: handle_multiple(item) return #72dpi is illustrator default drawing = svgfile.svgfile(0, 0, 'images%s' % image, parsed=True, resolution=72) setEtch(drawing.canvas) canvas_size = get_canvas_size(item) drawing_size = (drawing.bbox().width(), drawing.bbox().height()) dir = 'tiles/%s' % item['type'] if not os.path.exists(dir): os.makedirs(dir) c = canvas.canvas() center = ( (canvas_size[0] - drawing_size[0]) / 2, (canvas_size[1] - drawing_size[1]) / 2 ) c.insert(drawing, [trafo.translate(center[0], center[1])]) yMargin = (canvas_size[1] - drawing_size[1]) / 2 yPos = yMargin - yMargin / 2 baseline = text.parbox.middle textbox = '{\large %s}' % title if 'subtitle' in item: textbox += '\n\n' textbox += item['subtitle'] if yPos < (unit.t_inch / 2): baseline = text.parbox.bottom c.text(canvas_size[0] / 2, yPos, textbox, [ text.halign.boxcenter, text.halign.flushcenter, text.parbox(canvas_size[0] - .25 * unit.t_inch, baseline = baseline) ]) #draw Cut line if CUT_LINE: c.stroke( path.rect(0, 0, canvas_size[0], canvas_size[1]), [ style.linewidth(0.001), color.rgb.red ] ) p = document.page(c, bbox=bbox.bbox(0, 0, canvas_size[0], canvas_size[1])) d = document.document([p]) d.writeSVGfile('%s/%s.svg' % (dir, slugify(title)))
def clear(self): """ Clears the grader, creating all new canvases for drawing. """ from pyx import canvas from pyx import bbox from pyx import document from .window import Window self._canvas = canvas.canvas() bounds = bbox.bbox(self.x, self.y, self.width, self.height) self._page = document.page(self._canvas, paperformat=document.paperformat.Letter, bbox=bounds) self._submitted = Window() self._submitted.title = 'Student Submission' self._solution = Window() self._solution.title = 'Instructor Solution' self._comments = []
from pyx import canvas, document, path from ent import factor from math import sin, cos, sqrt, pi n = 100_000 ca = canvas.canvas() phi = (1 + sqrt(5)) / 2.0 for j in range(n): i = j + 1 r = sqrt(i) theta = i * 2 * pi / (phi * phi) x = cos(theta) * r y = -sin(theta) * r factors = factor(i) if (len(factors) > 1): radius = 0.05 * pow(2, len(factors) - 1) ca.fill(path.circle(x, y, radius)) d = document.document(pages=[ document.page(ca, paperformat=document.paperformat.A4, fittosize=1) ]) d.writePDFfile('spiral_vogel_1e5.pdf')
def plot_scores(self, fname, binsize=10000, show_lads=False, show_dips=False, show_means=False, show_partitions=False): """Plot a PDF of score data with optional indicators of partitions, " partition means, LADs, and DIPs.""" # Make sure that the PYX module is available try: from pyx import canvas, path, document, color, text, style except ImportError: self.logger.warn("The package pyx must be installed to plot data") return None # Make sure desired data is present if self.focus != 'binned': if (self.data is None or numpy.nanmin(self.data['score']) == 0): self.logger.warn("Requested data is not available for " "plotting") return None elif (self.binned is None or numpy.nanmin(self.binned['score']) == 0): self.logger.warn("Requested binned data is not available for " "plotting") return None self.logger.info("Plotting data") # Determine which data to use if self.focus == 'binned': data = self.binned chr_indices = self.bin_indices else: data = self.data chr_indices = self.chr_indices # Plot each chromosome on its own page pages = [] for i in range(self.chroms.shape[0]): valid = numpy.where( numpy.logical_not( numpy.isnan( data['score'][chr_indices[i]:chr_indices[i + 1]])))[0] valid += chr_indices[i] # Skip chromosomes without valid data if valid.shape[0] == 0: continue mids = (data['coords'][valid, 0] + data['coords'][valid, 1]) // 2 if binsize > 0: # Bin data to the resolution requested start = (mids[0] // binsize) * binsize stop = (mids[-1] // binsize + 1) * binsize indices = (mids - start) // binsize counts = numpy.bincount(indices) Ys = numpy.bincount( indices, weights=data['score'][valid]) / numpy.maximum( 1, counts) mids = (start + numpy.arange( (stop - start) // binsize) * binsize + binsize / 2) valid = numpy.where(counts > 0)[0] Ys = Ys[valid] mids = mids[valid] coords = numpy.zeros((Ys.shape[0], 2), dtype=numpy.float64) coords[:, 0] = start + valid * binsize coords[:, 1] = start + valid * binsize + binsize else: Ys = data['score'][valid] start = data['coords'][valid, 0] stop = data['coords'][valid[-1], 1] coords = data['coords'][valid, :].astype(numpy.float64) c = canvas.canvas() width = (stop - start) / 5000000. height = 5. maxscore = numpy.amax(numpy.abs(Ys)) if show_means and self.partitions is not None: where = numpy.where(self.partitions['chr'] == i)[0] maxscore = max( maxscore, numpy.amax(numpy.abs(self.partitions['score'][where]))) Ys /= maxscore Ys *= height * 0.5 Xs = (mids - start) / float(stop - start) * width coords -= start coords /= (stop - start) coords *= width lpath = path.path(path.moveto(0, 0)) for j in range(valid.shape[0]): if j == 0 or valid[j] - valid[j - 1] > 1: lpath.append(path.lineto(coords[j, 0], 0)) lpath.append(path.lineto(Xs[j], Ys[j])) if j == Xs.shape[0] - 1 or valid[j + 1] - valid[j] > 1: lpath.append(path.lineto(coords[j, 1], 0)) lpath.append(path.lineto(width, 0)) lpath.append(path.closepath()) # add lads if requests and already determined if show_lads and self.LADs is not None: where = numpy.where(self.LADs['chr'] == i)[0] if where.shape[0] == 0: continue for j in where: X0 = ((self.LADs['coords'][j, 0] - start) / float(stop - start) * width) X1 = ((self.LADs['coords'][j, 1] - start) / float(stop - start) * width) c.fill(path.rect(X0, -height / 2, X1 - X0, height), [color.gray(0.85)]) # add dips if requests and already determined if show_dips and self.DIPs is not None: print(self.DIPs.shape) where = numpy.where(self.DIPs['chr'] == i)[0] if where.shape[0] == 0: continue for j in where: X0 = ((self.DIPs['coords'][j, 0] - start) / float(stop - start) * width) X1 = ((self.DIPs['coords'][j, 1] - start) / float(stop - start) * width) c.fill(path.rect(X0, -height / 2, X1 - X0, height), [color.rgb.red]) # add signal track c.fill(lpath) c.stroke(path.line(0, -height / 2, width, -height / 2)) # add partition mean line if requested and already determined if show_means and self.partitions is not None: where = numpy.where(self.partitions['chr'] == i)[0] coords = ((self.partitions['coords'][where, :] - start) / float(stop - start) * width) Ys = ((self.partitions['score'][where] / maxscore) * height * 0.5) lpath = path.path(path.moveto(0, 0)) for j in range(Ys.shape[0]): if j == 0 or coords[j, 0] != coords[j - 1, 1]: lpath.append(path.lineto(coords[j, 0], 0)) lpath.append(path.lineto(coords[j, 0], Ys[j])) lpath.append(path.lineto(coords[j, 1], Ys[j])) if (j == Ys.shape[0] - 1 or coords[j, 1] != coords[j + 1, 0]): lpath.append(path.lineto(coords[j, 1], 0)) lpath.append(path.lineto(width, 0)) c.stroke(lpath, [ color.rgb.blue, style.linewidth.THIN, color.transparency(0.5) ]) # add partition lines if requested and already determined if show_partitions and self.partitions is not None: where = numpy.where(self.partitions['chr'] == i)[0] coords = ((self.partitions['coords'][where, :] - start) / float(stop - start) * width) for j in range(coords.shape[0] - 1): c.stroke( path.line(coords[j, 1], -height * 0.5, coords[j, 1], height * 0.5), [style.linewidth.THin]) if coords[j, 1] != coords[j + 1, 0]: c.stroke( path.line(coords[j + 1, 0], -height * 0.5, coords[j + 1, 0], height * 0.5), [style.linewidth.THin]) # add coordinates for j in range(int(numpy.ceil(start / 10000000.)), int(numpy.floor(stop / 10000000.) + 1)): X = (j * 10000000. - start) / (stop - start) * width c.stroke(path.line(X, -height / 2, X, -height / 2 - 0.2)) c.text(X, -height / 2 - 0.25, "%i Mb" % (j * 10), [text.halign.center, text.valign.top]) c.text(width * 0.5, -height / 2 - 0.6, "%s" % self.chroms[i].replace('_', ' '), [text.halign.center, text.valign.top]) pages.append(document.page(c)) doc = document.document(pages) doc.writePDFfile(fname)
def overlay_print(plateid, numbers=False, noguides=False, renumber=False, rotate180=False): ''' This function returns a plate overlay as a pyx.document object. The calling script can determine what to do with it. To print this object as a PDF: overlay = overlay_print(plateid=12345) overlay.writePDFfile(destination_path) ''' # Get the needed files plateHolesSorted_file = sdssPath.full('plateHolesSorted', plateid=plateid) if not os.path.isfile(plateHolesSorted_file): raise IOError("File not found: {0}".format(plateHolesSorted_file)) platePlans_file = sdssPath.full('platePlans') if not os.path.isfile(platePlans_file): raise IOError("File not found: {0}".format(platePlans_file)) # Read in holes data, extract meta data holes_yanny = yanny.yanny(plateHolesSorted_file) racen = holes_yanny['raCen'] deccen = holes_yanny['decCen'] designid = holes_yanny['designid'] ha = holes_yanny['ha'] holes = holes_yanny['STRUCT1'] if (rotate180): holes['xfocal'] = -np.array(holes['xfocal']) holes['yfocal'] = -np.array(holes['yfocal']) # Read in plans plans = yanny.yanny(platePlans_file) iplan = np.nonzero(np.array(plans['PLATEPLANS']['plateid']) == plateid)[0] survey = plans['PLATEPLANS']['survey'][iplan[0]].decode() programname = plans['PLATEPLANS']['programname'][iplan[0]].decode() # Texify the string programname_str = str(programname) programname_str = re.sub("_", "\_", programname_str) # Create information string information = r"\font\myfont=cmr10 at 40pt {\myfont" information += " Plate=" + str(plateid) + "; " information += "Design=" + str(designid) + "; " information += "Survey=" + str(survey) + "; " information += "Program=" + str(programname_str) + "; " information += "RA=" + str(racen) + "; " information += "Dec=" + str(deccen) + "; " information += "HA=" + str(np.float32((ha.split())[0])) + "." information += "}" # Create message message = "Una placa para APOGEE Sur" message_tex = r"\font\myfont=cmr10 at 40pt {\myfont " + message + "}" apogee = apogee_layer(holes, numbers=numbers, renumber=renumber) if (noguides is False): guide = guide_layer(holes) else: guide = None whiteout = whiteout_layer(holes) plate_circle = plate_circle_layer(plateid, information, message_tex) outline = outline_layer() # pyx.canvas object acquisition = acquisition_layer(holes) outline.insert(apogee) if (guide is not None): outline.insert(guide) outline.insert(plate_circle) if (acquisition is not None): outline.insert(acquisition) outline.insert(whiteout) pformat = document.paperformat(limit_radius * 2., limit_radius * 2.) final = document.page(outline, paperformat=pformat) return document.document(pages=[final])
from pyx import canvas, document, path from ent import factor from math import sin, cos, sqrt, pi n = 100_000 ca = canvas.canvas() phi = (1 + sqrt(5)) / 2.0 for j in range(n): i = j + 1 r = sqrt(i) theta = i * 2 * pi / (phi*phi) x = cos(theta)*r y = sin(theta)*r if i <= n: factors = factor(i) n_fac = 0 for f in factors: n_fac += f[1] if(n_fac>1): radius = 0.05*pow(2,(n_fac-1)/2.5) ca.fill(path.circle(x,y, radius)) d = document.document(pages = [document.page(ca, paperformat=document.paperformat.A4, fittosize=1)]) d.writePDFfile("spiral_vogel_all.pdf")
def plot(logn, logt, opsn, opst, pages, graphs, no_clean, debug): fname = str(datetime.now()).replace(' ', '_') plt.rc('font', family='Input Mono') cwd = sys.path[0] try: os.mkdir(cwd + '/../tmp') if debug > 0: err.log('../tmp/ directory created for temporary storage.') except FileExistsError: if debug > 0: err.log( '../tmp/ directory exists; using it for temporary storage.') new_logn = [] new_logt = [] new_pairs = set() for i, t in enumerate(logt): p = (t, logn[i]) if p not in new_pairs: new_logn.append(logn[i]) new_logt.append(t) logn = new_logn logt = new_logt xmax = int(max(logn)) xmin = int(min(logn)) ymax = int(max(logt)) ymin = int(min(logt)) xrng = max(xmax - xmin, 0) yrng = max(ymax - ymin, 0) roots = {} t_counts = np.zeros(yrng + 1) n_counts = np.zeros(xrng + 1) t_pairs = set() n_pairs = set() ylist = range(ymin, ymax + 1) xlist = range(xmin, xmax + 1) xticker_base = 1.0 if xrng > ticker.MultipleLocator.MAXTICKS - 50: xticker_base = xrng / ticker.MultipleLocator.MAXTICKS * 1.5 yticker_base = 1.0 if yrng > ticker.MultipleLocator.MAXTICKS - 50: yticker_base = yrng / ticker.MultipleLocator.MAXTICKS * 1.5 yloc = ticker.MultipleLocator(base=yticker_base) xloc = ticker.MultipleLocator(base=xticker_base) fig = plt.figure(figsize=(10, 10)) fontP = FontProperties() fontP.set_size('small') gs = gridspec.GridSpec(2, 2) kx = dict(aspect='auto') ax_main = plt.subplot(gs[1, 0], **kx) ax_count = plt.subplot(gs[1, 1], **kx) ax_vcount = plt.subplot(gs[0, 0], **kx) ax_none = plt.subplot(gs[0, 1], **kx) ax_small = plt.axes([0.73, 0.11, 0.17, 0.17]) ax_main.yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) ax_main.xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) ax_count.yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) ax_count.xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) ax_vcount.yaxis.set_major_locator(ticker.MaxNLocator(integer=True)) ax_vcount.xaxis.set_major_locator(ticker.MaxNLocator(integer=True)) plt.xticks([]) plt.yticks([]) ax_small.yaxis.set_minor_locator(yloc) ax_small.yaxis.grid(True, which='minor', color=colors.h_light_gray) ax_small.set_axisbelow(True) gs.update(wspace=0.00, hspace=-0.00) log_marker = 'x' if len(opst) > 50: if debug > 1: err.log('Input size is ' + str(len(opst)) + ', using marker \'o\'') log_marker = 'o' elif debug > 1: err.log('Input size is ' + str(len(opst)) + ', using marker \'x\'') if pages: partial_logn = [] partial_logt = [] partial_opst = [] partial_opsn = [] last_logt_i = 0 logt_i = 0 for i in range(0, len(opst)): if debug > 1: err.log("Generating data plot number " + str(i)) partial_opst = [opst[i]] partial_opsn = [opsn[i]] op_t = opst[i] last_logt_i = logt_i + 1 roots = {} while logt_i + 1 < len(logt) and logt[logt_i + 1] <= op_t: logt_i += 1 roots[logt[last_logt_i]] = logn[last_logt_i] partial_logn = [] partial_logt = [] for j in range(last_logt_i, logt_i + 1): partial_logt.append(logt[j]) partial_logn.append(logn[j]) if debug > 1: err.log("Starting plot generation") add_plot(fname, cwd, fig, partial_logn, partial_logt, partial_opsn, partial_opst, t_counts, n_counts, t_pairs, n_pairs, log_marker, xloc, yloc, ax_main, ax_count, ax_vcount, ax_none, ax_small, xmax, xmin, ymax, ymin, xrng, yrng, xlist, ylist, roots, graphs, i, debug) if len(graphs) > 0: del graphs[0] else: for i, t in enumerate(logt): if t not in roots.keys(): roots[t] = logn[i] add_plot(fname, cwd, fig, logn, logt, opsn, opst, t_counts, n_counts, t_pairs, n_pairs, log_marker, xloc, yloc, ax_main, ax_count, ax_vcount, ax_none, ax_small, xmax, xmin, ymax, ymin, xrng, yrng, xlist, ylist, roots, graphs, 0, debug) plt.close() page_list = [] page_size = document.paperformat(200, 200) num_plots = 1 if pages: num_plots = len(opsn) for i in range(0, num_plots): if debug > 0: err.log("Concatenating PS pages for plot #" + str(i)) plots_name = cwd + '/../tmp/' + fname + '_' + str(i) + '.eps' tree_name = cwd + '/../tmp/' + fname + '_' + str(i) + '.gv.eps' got_tree = True try: tree_file = open(tree_name, 'r') tree_w = 0 tree_h = 0 for line in tree_file: if line.startswith("%%BoundingBox:"): bbline = line.split() tree_w = bbline[3] tree_h = bbline[4] if debug > 1: err.log( "In EPS #{} got height: {} and width {} from line {}" .format(i, tree_h, tree_w, line.replace('\n', ''))) break else: err.err( "BoundingBox line not found in EPS file for tree diagram.") tree_file.close() except: got_tree = False c = canvas.canvas() plots_file = epsfile.epsfile(0, 0, plots_name, height=160, width=160) c.insert(plots_file) if got_tree: if tree_w > tree_h: tree_file = epsfile.epsfile(120, 120, tree_name, align='cc', width=70) else: tree_file = epsfile.epsfile(120, 120, tree_name, align='cc', height=70) c.insert(tree_file) p = document.page(c, fittosize=True, centered=True, paperformat=page_size) if no_clean: c.writeEPSfile(cwd + '/../tmp/' + fname + '_' + str(i) + '.zipped.eps') page_list.append(p) d = document.document(page_list) out_name = cwd + '/../outputs/' + fname + '.ps' if debug > 0: err.log("Saving final output " + out_name) d.writePSfile(out_name) if not no_clean: for tmpf in os.listdir(cwd + '/../tmp/'): os.remove(cwd + '/../tmp/' + tmpf) os.rmdir(cwd + '/../tmp/')