remove shebang -- see comment 3 on https://bugzilla.redhat.com/bugzilla/show_bug...
[PyX/mjg.git] / pyx / color.py
blob21dc9509e634ab33c92fadd4e251bb46c0eb21a8
1 # -*- coding: ISO-8859-1 -*-
4 # Copyright (C) 2002-2004, 2006 Jörg Lehmann <joergl@users.sourceforge.net>
5 # Copyright (C) 2003-2006 Michael Schindler <m-schindler@users.sourceforge.net>
6 # Copyright (C) 2002-2004 André Wobst <wobsta@users.sourceforge.net>
8 # This file is part of PyX (http://pyx.sourceforge.net/).
10 # PyX 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.
15 # PyX 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.
20 # You should have received a copy of the GNU General Public License
21 # along with PyX; if not, write to the Free Software
22 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 import colorsys, math
25 import attr, style, pdfwriter
27 # device-dependend (nonlinear) functions for color conversion
28 # UCRx : [0,1] -> [-1, 1] UnderColorRemoval (removes black from c, y, m)
29 # BG : [0,1] -> [0, 1] BlackGeneration (generate the black from the nominal k-value)
30 # as long as we have no further knowledge we define them linearly with constants 1
31 def _UCRc(x): return x
32 def _UCRm(x): return x
33 def _UCRy(x): return x
34 def _BG(x): return x
36 def set(UCRc=None, UCRm=None, UCRy=None, BG=None):
37 global _UCRc
38 global _UCRm
39 global _UCRy
40 global _BG
42 if UCRc is not None:
43 _UCRc = UCRc
44 if UCRm is not None:
45 _UCRm = UCRm
46 if UCRy is not None:
47 _UCRy = UCRy
48 if BG is not None:
49 _BG = BG
52 class color(attr.exclusiveattr, style.strokestyle, style.fillstyle):
54 """base class for all colors"""
56 def __init__(self):
57 attr.exclusiveattr.__init__(self, color)
60 clear = attr.clearclass(color)
63 class grey(color):
65 """grey tones"""
67 def __init__(self, gray):
68 color.__init__(self)
69 if gray<0 or gray>1: raise ValueError
70 self.color = {"gray": gray}
72 def processPS(self, file, writer, context, registry, bbox):
73 file.write("%(gray)g setgray\n" % self.color)
75 def processPDF(self, file, writer, context, registry, bbox):
76 if context.strokeattr:
77 file.write("%(gray)f G\n" % self.color)
78 if context.fillattr:
79 file.write("%(gray)f g\n" % self.color)
81 def cmyk(self):
82 return cmyk(0, 0, 0, 1 - self.color["gray"])
84 def grey(self):
85 return self
86 gray = grey
88 def hsb(self):
89 return hsb(0, 0, self.color["gray"])
91 def rgb(self):
92 return rgb(self.color["gray"], self.color["gray"], self.color["gray"])
94 grey.black = grey(0.0)
95 grey.white = grey(1.0)
96 gray = grey
99 class rgb(color):
101 """rgb colors"""
103 def __init__(self, r=0.0, g=0.0, b=0.0):
104 color.__init__(self)
105 if r<0 or r>1 or g<0 or g>1 or b<0 or b>1: raise ValueError
106 self.color = {"r": r, "g": g, "b": b}
108 def processPS(self, file, writer, context, registry, bbox):
109 file.write("%(r)g %(g)g %(b)g setrgbcolor\n" % self.color)
111 def processPDF(self, file, writer, context, registry, bbox):
112 if context.strokeattr:
113 file.write("%(r)f %(g)f %(b)f RG\n" % self.color)
114 if context.fillattr:
115 file.write("%(r)f %(g)f %(b)f rg\n" % self.color)
117 def cmyk(self):
118 # conversion to cmy
119 c, m, y = 1 - self.color["r"], 1 - self.color["g"], 1 - self.color["b"]
120 # conversion from cmy to cmyk with device-dependent functions
121 k = min([c, m, y])
122 return cmyk(min(1, max(0, c - _UCRc(k))),
123 min(1, max(0, m - _UCRm(k))),
124 min(1, max(0, y - _UCRy(k))),
125 _BG(k))
127 def grey(self):
128 return grey(0.3*self.color["r"] + 0.59*self.color["g"] + 0.11*self.color["b"])
129 gray = grey
131 def hsb(self):
133 values = self.color.values()
134 values.sort()
135 z, y, x = values
136 r, g, b = self.color["r"], self.color["g"], self.color["b"]
137 try:
138 if r == x and g == z:
139 return hsb((5 + (x-b)/(x-z)) / 6.0, (x - z) / x, x)
140 elif r == x and g > z:
141 return hsb((1 - (x-g)/(x-z)) / 6.0, (x - z) / x, x)
142 elif g == x and b == z:
143 return hsb((1 + (x-r)/(x-z)) / 6.0, (x - z) / x, x)
144 elif g == x and b > z:
145 return hsb((3 - (x-b)/(x-z)) / 6.0, (x - z) / x, x)
146 elif b == x and r == z:
147 return hsb((3 + (x-g)/(x-z)) / 6.0, (x - z) / x, x)
148 elif b == x and r > z:
149 return hsb((5 - (x-r)/(x-z)) / 6.0, (x - z) / x, x)
150 else:
151 raise ValueError
152 except ZeroDivisionError:
153 return hsb(0, 0, x)
155 def rgb(self):
156 return self
158 rgb.red = rgb(1 ,0, 0)
159 rgb.green = rgb(0 ,1, 0)
160 rgb.blue = rgb(0 ,0, 1)
161 rgb.white = rgb(1 ,1, 1)
162 rgb.black = rgb(0 ,0, 0)
165 class hsb(color):
167 """hsb colors"""
169 def __init__(self, h=0.0, s=0.0, b=0.0):
170 color.__init__(self)
171 if h<0 or h>1 or s<0 or s>1 or b<0 or b>1: raise ValueError
172 self.color = {"h": h, "s": s, "b": b}
174 def processPS(self, file, writer, context, registry, bbox):
175 file.write("%(h)g %(s)g %(b)g sethsbcolor\n" % self.color)
177 def processPDF(self, file, writer, context, registry, bbox):
178 r, g, b = colorsys.hsv_to_rgb(self.color["h"], self.color["s"], self.color["b"])
179 rgb(r, g, b).processPDF(file, writer, context, registry, bbox)
181 def cmyk(self):
182 return self.rgb().cmyk()
184 def grey(self):
185 return self.rgb().grey()
186 gray = grey
188 def hsb(self):
189 return self
191 def rgb(self):
192 h, s, b = self.color["h"], self.color["s"], self.color["b"]
193 i = int(6*h)
194 f = 6*h - i
195 m, n, k = 1 - s, 1 - s*f, 1 - s*(1-f)
196 if i == 1:
197 return rgb(b*n, b, b*m)
198 elif i == 2:
199 return rgb(b*m, b, b*k)
200 elif i == 3:
201 return rgb(b*m, b*n, b)
202 elif i == 4:
203 return rgb(b*k, b*m, b)
204 elif i == 5:
205 return rgb(b, b*m, b*n)
206 else:
207 return rgb(b, b*k, b*m)
210 class cmyk(color):
212 """cmyk colors"""
214 def __init__(self, c=0.0, m=0.0, y=0.0, k=0.0):
215 color.__init__(self)
216 if c<0 or c>1 or m<0 or m>1 or y<0 or y>1 or k<0 or k>1: raise ValueError
217 self.color = {"c": c, "m": m, "y": y, "k": k}
219 def processPS(self, file, writer, context, registry, bbox):
220 file.write("%(c)g %(m)g %(y)g %(k)g setcmykcolor\n" % self.color)
222 def processPDF(self, file, writer, context, registry, bbox):
223 if context.strokeattr:
224 file.write("%(c)f %(m)f %(y)f %(k)f K\n" % self.color)
225 if context.fillattr:
226 file.write("%(c)f %(m)f %(y)f %(k)f k\n" % self.color)
228 def cmyk(self):
229 return self
231 def grey(self):
232 return grey(1 - min([1, 0.3*self.color["c"] + 0.59*self.color["m"] +
233 0.11*self.color["y"] + self.color["k"]]))
234 gray = grey
236 def hsb(self):
237 return self.rgb().hsb()
239 def rgb(self):
240 # conversion to cmy:
241 c = min(1, self.color["c"] + self.color["k"])
242 m = min(1, self.color["m"] + self.color["k"])
243 y = min(1, self.color["y"] + self.color["k"])
244 # conversion from cmy to rgb:
245 return rgb(1 - c, 1 - m, 1 - y)
247 cmyk.GreenYellow = cmyk(0.15, 0, 0.69, 0)
248 cmyk.Yellow = cmyk(0, 0, 1, 0)
249 cmyk.Goldenrod = cmyk(0, 0.10, 0.84, 0)
250 cmyk.Dandelion = cmyk(0, 0.29, 0.84, 0)
251 cmyk.Apricot = cmyk(0, 0.32, 0.52, 0)
252 cmyk.Peach = cmyk(0, 0.50, 0.70, 0)
253 cmyk.Melon = cmyk(0, 0.46, 0.50, 0)
254 cmyk.YellowOrange = cmyk(0, 0.42, 1, 0)
255 cmyk.Orange = cmyk(0, 0.61, 0.87, 0)
256 cmyk.BurntOrange = cmyk(0, 0.51, 1, 0)
257 cmyk.Bittersweet = cmyk(0, 0.75, 1, 0.24)
258 cmyk.RedOrange = cmyk(0, 0.77, 0.87, 0)
259 cmyk.Mahogany = cmyk(0, 0.85, 0.87, 0.35)
260 cmyk.Maroon = cmyk(0, 0.87, 0.68, 0.32)
261 cmyk.BrickRed = cmyk(0, 0.89, 0.94, 0.28)
262 cmyk.Red = cmyk(0, 1, 1, 0)
263 cmyk.OrangeRed = cmyk(0, 1, 0.50, 0)
264 cmyk.RubineRed = cmyk(0, 1, 0.13, 0)
265 cmyk.WildStrawberry = cmyk(0, 0.96, 0.39, 0)
266 cmyk.Salmon = cmyk(0, 0.53, 0.38, 0)
267 cmyk.CarnationPink = cmyk(0, 0.63, 0, 0)
268 cmyk.Magenta = cmyk(0, 1, 0, 0)
269 cmyk.VioletRed = cmyk(0, 0.81, 0, 0)
270 cmyk.Rhodamine = cmyk(0, 0.82, 0, 0)
271 cmyk.Mulberry = cmyk(0.34, 0.90, 0, 0.02)
272 cmyk.RedViolet = cmyk(0.07, 0.90, 0, 0.34)
273 cmyk.Fuchsia = cmyk(0.47, 0.91, 0, 0.08)
274 cmyk.Lavender = cmyk(0, 0.48, 0, 0)
275 cmyk.Thistle = cmyk(0.12, 0.59, 0, 0)
276 cmyk.Orchid = cmyk(0.32, 0.64, 0, 0)
277 cmyk.DarkOrchid = cmyk(0.40, 0.80, 0.20, 0)
278 cmyk.Purple = cmyk(0.45, 0.86, 0, 0)
279 cmyk.Plum = cmyk(0.50, 1, 0, 0)
280 cmyk.Violet = cmyk(0.79, 0.88, 0, 0)
281 cmyk.RoyalPurple = cmyk(0.75, 0.90, 0, 0)
282 cmyk.BlueViolet = cmyk(0.86, 0.91, 0, 0.04)
283 cmyk.Periwinkle = cmyk(0.57, 0.55, 0, 0)
284 cmyk.CadetBlue = cmyk(0.62, 0.57, 0.23, 0)
285 cmyk.CornflowerBlue = cmyk(0.65, 0.13, 0, 0)
286 cmyk.MidnightBlue = cmyk(0.98, 0.13, 0, 0.43)
287 cmyk.NavyBlue = cmyk(0.94, 0.54, 0, 0)
288 cmyk.RoyalBlue = cmyk(1, 0.50, 0, 0)
289 cmyk.Blue = cmyk(1, 1, 0, 0)
290 cmyk.Cerulean = cmyk(0.94, 0.11, 0, 0)
291 cmyk.Cyan = cmyk(1, 0, 0, 0)
292 cmyk.ProcessBlue = cmyk(0.96, 0, 0, 0)
293 cmyk.SkyBlue = cmyk(0.62, 0, 0.12, 0)
294 cmyk.Turquoise = cmyk(0.85, 0, 0.20, 0)
295 cmyk.TealBlue = cmyk(0.86, 0, 0.34, 0.02)
296 cmyk.Aquamarine = cmyk(0.82, 0, 0.30, 0)
297 cmyk.BlueGreen = cmyk(0.85, 0, 0.33, 0)
298 cmyk.Emerald = cmyk(1, 0, 0.50, 0)
299 cmyk.JungleGreen = cmyk(0.99, 0, 0.52, 0)
300 cmyk.SeaGreen = cmyk(0.69, 0, 0.50, 0)
301 cmyk.Green = cmyk(1, 0, 1, 0)
302 cmyk.ForestGreen = cmyk(0.91, 0, 0.88, 0.12)
303 cmyk.PineGreen = cmyk(0.92, 0, 0.59, 0.25)
304 cmyk.LimeGreen = cmyk(0.50, 0, 1, 0)
305 cmyk.YellowGreen = cmyk(0.44, 0, 0.74, 0)
306 cmyk.SpringGreen = cmyk(0.26, 0, 0.76, 0)
307 cmyk.OliveGreen = cmyk(0.64, 0, 0.95, 0.40)
308 cmyk.RawSienna = cmyk(0, 0.72, 1, 0.45)
309 cmyk.Sepia = cmyk(0, 0.83, 1, 0.70)
310 cmyk.Brown = cmyk(0, 0.81, 1, 0.60)
311 cmyk.Tan = cmyk(0.14, 0.42, 0.56, 0)
312 cmyk.Gray = cmyk(0, 0, 0, 0.50)
313 cmyk.Grey = cmyk.Gray
314 cmyk.Black = cmyk(0, 0, 0, 1)
315 cmyk.White = cmyk(0, 0, 0, 0)
316 cmyk.white = cmyk.White
317 cmyk.black = cmyk.Black
320 class palette(color, attr.changeattr):
322 """base class for all palettes
324 A palette is a collection of colors with a single parameter ranging from 0 to 1
325 to address them"""
327 def __init__(self):
328 color.__init__(self)
330 def getcolor(self, param):
331 """return color corresponding to param"""
332 pass
334 def select(self, index, n_indices):
335 """return a color corresponding to an index out of n_indices"""
336 if n_indices == 1:
337 param = 0
338 else:
339 param = index / (n_indices - 1.0)
340 return self.getcolor(param)
342 def processPS(self, file, writer, context, registry, bbox):
343 self.getcolor(0).processPS(file, writer, context)
345 def processPDF(self, file, writer, context, registry, bbox):
346 self.getcolor(0).processPDF(file, writer, context)
349 class linearpalette(palette):
351 """linearpalette is a collection of two colors for a linear transition between them"""
353 def __init__(self, mincolor, maxcolor):
354 palette.__init__(self)
355 if mincolor.__class__ != maxcolor.__class__:
356 raise ValueError
357 self.colorclass = mincolor.__class__
358 self.mincolor = mincolor
359 self.maxcolor = maxcolor
361 def getcolor(self, param):
362 colordict = {}
363 for key in self.mincolor.color.keys():
364 colordict[key] = param * self.maxcolor.color[key] + (1 - param) * self.mincolor.color[key]
365 return self.colorclass(**colordict)
368 class functionpalette(palette):
370 """functionpalette is a collection of colors for an arbitray non-linear transition between them
372 parameters:
373 functions: a dictionary for the color values
374 type: a string indicating the color class
377 def __init__(self, functions, type):
378 palette.__init__(self)
379 if type == "cmyk":
380 self.colorclass = cmyk
381 elif type == "rgb":
382 self.colorclass = rgb
383 elif type == "hsb":
384 self.colorclass = hsb
385 elif type == "grey" or type == "gray":
386 self.colorclass = grey
387 else:
388 raise ValueError
389 self.functions = functions
391 def getcolor(self, param):
392 colordict = {}
393 for key in self.functions.keys():
394 colordict[key] = self.functions[key](param)
395 return self.colorclass(**colordict)
398 palette.Gray = linearpalette(gray.white, gray.black)
399 palette.Grey = palette.Gray
400 palette.ReverseGray = linearpalette(gray.black, gray.white)
401 palette.ReverseGrey = palette.ReverseGray
402 palette.BlackYellow = functionpalette(functions={#(compare this with reversegray above)
403 "r":(lambda x: 2*x*(1-x)**5 + 3.5*x**2*(1-x)**3 + 2.1*x*x*(1-x)**2 + 3.0*x**3*(1-x)**2 + x**0.5*(1-(1-x)**2)),
404 "g":(lambda x: 1.5*x**2*(1-x)**3 - 0.8*x**3*(1-x)**2 + 2.0*x**4*(1-x) + x**4),
405 "b":(lambda x: 5*x*(1-x)**5 - 0.5*x**2*(1-x)**3 + 0.3*x*x*(1-x)**2 + 5*x**3*(1-x)**2 + 0.5*x**6)},
406 type="rgb")
407 palette.RedGreen = linearpalette(rgb.red, rgb.green)
408 palette.RedBlue = linearpalette(rgb.red, rgb.blue)
409 palette.GreenRed = linearpalette(rgb.green, rgb.red)
410 palette.GreenBlue = linearpalette(rgb.green, rgb.blue)
411 palette.BlueRed = linearpalette(rgb.blue, rgb.red)
412 palette.BlueGreen = linearpalette(rgb.blue, rgb.green)
413 palette.RedBlack = linearpalette(rgb.red, rgb.black)
414 palette.BlackRed = linearpalette(rgb.black, rgb.red)
415 palette.RedWhite = linearpalette(rgb.red, rgb.white)
416 palette.WhiteRed = linearpalette(rgb.white, rgb.red)
417 palette.GreenBlack = linearpalette(rgb.green, rgb.black)
418 palette.BlackGreen = linearpalette(rgb.black, rgb.green)
419 palette.GreenWhite = linearpalette(rgb.green, rgb.white)
420 palette.WhiteGreen = linearpalette(rgb.white, rgb.green)
421 palette.BlueBlack = linearpalette(rgb.blue, rgb.black)
422 palette.BlackBlue = linearpalette(rgb.black, rgb.blue)
423 palette.BlueWhite = linearpalette(rgb.blue, rgb.white)
424 palette.WhiteBlue = linearpalette(rgb.white, rgb.blue)
425 palette.Rainbow = linearpalette(hsb(0, 1, 1), hsb(2.0/3.0, 1, 1))
426 palette.ReverseRainbow = linearpalette(hsb(2.0/3.0, 1, 1), hsb(0, 1, 1))
427 palette.Hue = linearpalette(hsb(0, 1, 1), hsb(1, 1, 1))
428 palette.ReverseHue = linearpalette(hsb(1, 1, 1), hsb(0, 1, 1))
431 class PDFextgstate(pdfwriter.PDFobject):
433 def __init__(self, name, extgstate, registry):
434 pdfwriter.PDFobject.__init__(self, "extgstate", name)
435 registry.addresource("ExtGState", name, self)
436 self.name = name
437 self.extgstate = extgstate
439 def write(self, file, writer, registry):
440 file.write("%s\n" % self.extgstate)
443 class transparency(attr.exclusiveattr, style.strokestyle, style.fillstyle):
445 def __init__(self, value):
446 value = 1-value
447 attr.exclusiveattr.__init__(self, transparency)
448 self.name = "Transparency-%f" % value
449 self.extgstate = "<< /Type /ExtGState /CA %f /ca %f >>" % (value, value)
451 def processPS(self, file, writer, context, registry, bbox):
452 raise NotImplementedError("transparency not available in PostScript")
454 def processPDF(self, file, writer, context, registry, bbox):
455 registry.add(PDFextgstate(self.name, self.extgstate, registry))
456 file.write("/%s gs\n" % self.name)