remove min and max arguments of palettes
[PyX/mjg.git] / pyx / color.py
blob68ad0b1f526f5b9f5d9eff7af43c52512a6d1fe7
1 #!/usr/bin/env python
2 # -*- coding: ISO-8859-1 -*-
5 # Copyright (C) 2002-2004, 2006 Jörg Lehmann <joergl@users.sourceforge.net>
6 # Copyright (C) 2003-2006 Michael Schindler <m-schindler@users.sourceforge.net>
7 # Copyright (C) 2002-2004 André Wobst <wobsta@users.sourceforge.net>
9 # This file is part of PyX (http://pyx.sourceforge.net/).
11 # PyX is free software; you can redistribute it and/or modify
12 # it under the terms of the GNU General Public License as published by
13 # the Free Software Foundation; either version 2 of the License, or
14 # (at your option) any later version.
16 # PyX is distributed in the hope that it will be useful,
17 # but WITHOUT ANY WARRANTY; without even the implied warranty of
18 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
19 # GNU General Public License for more details.
21 # You should have received a copy of the GNU General Public License
22 # along with PyX; if not, write to the Free Software
23 # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
25 import colorsys, math
26 import attr, style, pdfwriter
28 # device-dependend (nonlinear) functions for color conversion
29 # UCRx : [0,1] -> [-1, 1] UnderColorRemoval (removes black from c, y, m)
30 # BG : [0,1] -> [0, 1] BlackGeneration (generate the black from the nominal k-value)
31 # as long as we have no further knowledge we define them linearly with constants 1
32 def _UCRc(x): return x
33 def _UCRm(x): return x
34 def _UCRy(x): return x
35 def _BG(x): return x
37 def set(UCRc=None, UCRm=None, UCRy=None, BG=None):
38 global _UCRc
39 global _UCRm
40 global _UCRy
41 global _BG
43 if UCRc is not None:
44 _UCRc = UCRc
45 if UCRm is not None:
46 _UCRm = UCRm
47 if UCRy is not None:
48 _UCRy = UCRy
49 if BG is not None:
50 _BG = BG
53 class color(attr.exclusiveattr, style.strokestyle, style.fillstyle):
55 """base class for all colors"""
57 def __init__(self):
58 attr.exclusiveattr.__init__(self, color)
61 clear = attr.clearclass(color)
64 class grey(color):
66 """grey tones"""
68 def __init__(self, gray):
69 color.__init__(self)
70 if gray<0 or gray>1: raise ValueError
71 self.color = {"gray": gray}
73 def outputPS(self, file, writer, context):
74 file.write("%(gray)g setgray\n" % self.color)
76 def outputPDF(self, file, writer, context):
77 if context.strokeattr:
78 file.write("%(gray)f G\n" % self.color)
79 if context.fillattr:
80 file.write("%(gray)f g\n" % self.color)
82 def cmyk(self):
83 return cmyk(0, 0, 0, 1 - self.color["gray"])
85 def grey(self):
86 return self
87 gray = grey
89 def hsb(self):
90 return hsb(0, 0, self.color["gray"])
92 def rgb(self):
93 return rgb(self.color["gray"], self.color["gray"], self.color["gray"])
95 grey.black = grey(0.0)
96 grey.white = grey(1.0)
97 gray = grey
100 class rgb(color):
102 """rgb colors"""
104 def __init__(self, r=0.0, g=0.0, b=0.0):
105 color.__init__(self)
106 if r<0 or r>1 or g<0 or g>1 or b<0 or b>1: raise ValueError
107 self.color = {"r": r, "g": g, "b": b}
109 def outputPS(self, file, writer, context):
110 file.write("%(r)g %(g)g %(b)g setrgbcolor\n" % self.color)
112 def outputPDF(self, file, writer, context):
113 if context.strokeattr:
114 file.write("%(r)f %(g)f %(b)f RG\n" % self.color)
115 if context.fillattr:
116 file.write("%(r)f %(g)f %(b)f rg\n" % self.color)
118 def cmyk(self):
119 # conversion to cmy
120 c, m, y = 1 - self.color["r"], 1 - self.color["g"], 1 - self.color["b"]
121 # conversion from cmy to cmyk with device-dependent functions
122 k = min([c, m, y])
123 return cmyk(min(1, max(0, c - _UCRc(k))),
124 min(1, max(0, m - _UCRm(k))),
125 min(1, max(0, y - _UCRy(k))),
126 _BG(k))
128 def grey(self):
129 return grey(0.3*self.color["r"] + 0.59*self.color["g"] + 0.11*self.color["b"])
130 gray = grey
132 def hsb(self):
134 values = self.color.values()
135 values.sort()
136 z, y, x = values
137 r, g, b = self.color["r"], self.color["g"], self.color["b"]
138 try:
139 if r == x and g == z:
140 return hsb((5 + (x-b)/(x-z)) / 6.0, (x - z) / x, x)
141 elif r == x and g > z:
142 return hsb((1 - (x-g)/(x-z)) / 6.0, (x - z) / x, x)
143 elif g == x and b == z:
144 return hsb((1 + (x-r)/(x-z)) / 6.0, (x - z) / x, x)
145 elif g == x and b > z:
146 return hsb((3 - (x-b)/(x-z)) / 6.0, (x - z) / x, x)
147 elif b == x and r == z:
148 return hsb((3 + (x-g)/(x-z)) / 6.0, (x - z) / x, x)
149 elif b == x and r > z:
150 return hsb((5 - (x-r)/(x-z)) / 6.0, (x - z) / x, x)
151 else:
152 raise ValueError
153 except ZeroDivisionError:
154 return hsb(0, 0, x)
156 def rgb(self):
157 return self
159 rgb.red = rgb(1 ,0, 0)
160 rgb.green = rgb(0 ,1, 0)
161 rgb.blue = rgb(0 ,0, 1)
162 rgb.white = rgb(1 ,1, 1)
163 rgb.black = rgb(0 ,0, 0)
166 class hsb(color):
168 """hsb colors"""
170 def __init__(self, h=0.0, s=0.0, b=0.0):
171 color.__init__(self)
172 if h<0 or h>1 or s<0 or s>1 or b<0 or b>1: raise ValueError
173 self.color = {"h": h, "s": s, "b": b}
175 def outputPS(self, file, writer, context):
176 file.write("%(h)g %(s)g %(b)g sethsbcolor\n" % self.color)
178 def outputPDF(self, file, writer, context):
179 r, g, b = colorsys.hsv_to_rgb(self.color["h"], self.color["s"], self.color["b"])
180 rgb(r, g, b).outputPDF(file, writer, context)
182 def cmyk(self):
183 return self.rgb().cmyk()
185 def grey(self):
186 return self.rgb().grey()
187 gray = grey
189 def hsb(self):
190 return self
192 def rgb(self):
193 h, s, b = self.color["h"], self.color["s"], self.color["b"]
194 i = int(6*h)
195 f = 6*h - i
196 m, n, k = 1 - s, 1 - s*f, 1 - s*(1-f)
197 if i == 1:
198 return rgb(b*n, b, b*m)
199 elif i == 2:
200 return rgb(b*m, b, b*k)
201 elif i == 3:
202 return rgb(b*m, b*n, b)
203 elif i == 4:
204 return rgb(b*k, b*m, b)
205 elif i == 5:
206 return rgb(b, b*m, b*n)
207 else:
208 return rgb(b, b*k, b*m)
211 class cmyk(color):
213 """cmyk colors"""
215 def __init__(self, c=0.0, m=0.0, y=0.0, k=0.0):
216 color.__init__(self)
217 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
218 self.color = {"c": c, "m": m, "y": y, "k": k}
220 def outputPS(self, file, writer, context):
221 file.write("%(c)g %(m)g %(y)g %(k)g setcmykcolor\n" % self.color)
223 def outputPDF(self, file, writer, context):
224 if context.strokeattr:
225 file.write("%(c)f %(m)f %(y)f %(k)f K\n" % self.color)
226 if context.fillattr:
227 file.write("%(c)f %(m)f %(y)f %(k)f k\n" % self.color)
229 def cmyk(self):
230 return self
232 def grey(self):
233 return grey(1 - min([1, 0.3*self.color["c"] + 0.59*self.color["m"] +
234 0.11*self.color["y"] + self.color["k"]]))
235 gray = grey
237 def hsb(self):
238 return self.rgb().hsb()
240 def rgb(self):
241 # conversion to cmy:
242 c = min(1, self.color["c"] + self.color["k"])
243 m = min(1, self.color["m"] + self.color["k"])
244 y = min(1, self.color["y"] + self.color["k"])
245 # conversion from cmy to rgb:
246 return rgb(1 - c, 1 - m, 1 - y)
248 cmyk.GreenYellow = cmyk(0.15, 0, 0.69, 0)
249 cmyk.Yellow = cmyk(0, 0, 1, 0)
250 cmyk.Goldenrod = cmyk(0, 0.10, 0.84, 0)
251 cmyk.Dandelion = cmyk(0, 0.29, 0.84, 0)
252 cmyk.Apricot = cmyk(0, 0.32, 0.52, 0)
253 cmyk.Peach = cmyk(0, 0.50, 0.70, 0)
254 cmyk.Melon = cmyk(0, 0.46, 0.50, 0)
255 cmyk.YellowOrange = cmyk(0, 0.42, 1, 0)
256 cmyk.Orange = cmyk(0, 0.61, 0.87, 0)
257 cmyk.BurntOrange = cmyk(0, 0.51, 1, 0)
258 cmyk.Bittersweet = cmyk(0, 0.75, 1, 0.24)
259 cmyk.RedOrange = cmyk(0, 0.77, 0.87, 0)
260 cmyk.Mahogany = cmyk(0, 0.85, 0.87, 0.35)
261 cmyk.Maroon = cmyk(0, 0.87, 0.68, 0.32)
262 cmyk.BrickRed = cmyk(0, 0.89, 0.94, 0.28)
263 cmyk.Red = cmyk(0, 1, 1, 0)
264 cmyk.OrangeRed = cmyk(0, 1, 0.50, 0)
265 cmyk.RubineRed = cmyk(0, 1, 0.13, 0)
266 cmyk.WildStrawberry = cmyk(0, 0.96, 0.39, 0)
267 cmyk.Salmon = cmyk(0, 0.53, 0.38, 0)
268 cmyk.CarnationPink = cmyk(0, 0.63, 0, 0)
269 cmyk.Magenta = cmyk(0, 1, 0, 0)
270 cmyk.VioletRed = cmyk(0, 0.81, 0, 0)
271 cmyk.Rhodamine = cmyk(0, 0.82, 0, 0)
272 cmyk.Mulberry = cmyk(0.34, 0.90, 0, 0.02)
273 cmyk.RedViolet = cmyk(0.07, 0.90, 0, 0.34)
274 cmyk.Fuchsia = cmyk(0.47, 0.91, 0, 0.08)
275 cmyk.Lavender = cmyk(0, 0.48, 0, 0)
276 cmyk.Thistle = cmyk(0.12, 0.59, 0, 0)
277 cmyk.Orchid = cmyk(0.32, 0.64, 0, 0)
278 cmyk.DarkOrchid = cmyk(0.40, 0.80, 0.20, 0)
279 cmyk.Purple = cmyk(0.45, 0.86, 0, 0)
280 cmyk.Plum = cmyk(0.50, 1, 0, 0)
281 cmyk.Violet = cmyk(0.79, 0.88, 0, 0)
282 cmyk.RoyalPurple = cmyk(0.75, 0.90, 0, 0)
283 cmyk.BlueViolet = cmyk(0.86, 0.91, 0, 0.04)
284 cmyk.Periwinkle = cmyk(0.57, 0.55, 0, 0)
285 cmyk.CadetBlue = cmyk(0.62, 0.57, 0.23, 0)
286 cmyk.CornflowerBlue = cmyk(0.65, 0.13, 0, 0)
287 cmyk.MidnightBlue = cmyk(0.98, 0.13, 0, 0.43)
288 cmyk.NavyBlue = cmyk(0.94, 0.54, 0, 0)
289 cmyk.RoyalBlue = cmyk(1, 0.50, 0, 0)
290 cmyk.Blue = cmyk(1, 1, 0, 0)
291 cmyk.Cerulean = cmyk(0.94, 0.11, 0, 0)
292 cmyk.Cyan = cmyk(1, 0, 0, 0)
293 cmyk.ProcessBlue = cmyk(0.96, 0, 0, 0)
294 cmyk.SkyBlue = cmyk(0.62, 0, 0.12, 0)
295 cmyk.Turquoise = cmyk(0.85, 0, 0.20, 0)
296 cmyk.TealBlue = cmyk(0.86, 0, 0.34, 0.02)
297 cmyk.Aquamarine = cmyk(0.82, 0, 0.30, 0)
298 cmyk.BlueGreen = cmyk(0.85, 0, 0.33, 0)
299 cmyk.Emerald = cmyk(1, 0, 0.50, 0)
300 cmyk.JungleGreen = cmyk(0.99, 0, 0.52, 0)
301 cmyk.SeaGreen = cmyk(0.69, 0, 0.50, 0)
302 cmyk.Green = cmyk(1, 0, 1, 0)
303 cmyk.ForestGreen = cmyk(0.91, 0, 0.88, 0.12)
304 cmyk.PineGreen = cmyk(0.92, 0, 0.59, 0.25)
305 cmyk.LimeGreen = cmyk(0.50, 0, 1, 0)
306 cmyk.YellowGreen = cmyk(0.44, 0, 0.74, 0)
307 cmyk.SpringGreen = cmyk(0.26, 0, 0.76, 0)
308 cmyk.OliveGreen = cmyk(0.64, 0, 0.95, 0.40)
309 cmyk.RawSienna = cmyk(0, 0.72, 1, 0.45)
310 cmyk.Sepia = cmyk(0, 0.83, 1, 0.70)
311 cmyk.Brown = cmyk(0, 0.81, 1, 0.60)
312 cmyk.Tan = cmyk(0.14, 0.42, 0.56, 0)
313 cmyk.Gray = cmyk(0, 0, 0, 0.50)
314 cmyk.Grey = cmyk.Gray
315 cmyk.Black = cmyk(0, 0, 0, 1)
316 cmyk.White = cmyk(0, 0, 0, 0)
317 cmyk.white = cmyk.White
318 cmyk.black = cmyk.Black
321 class palette(color, attr.changeattr):
323 """base class for all palettes
325 A palette is a collection of colors with a single parameter ranging from 0 to 1
326 to address them"""
328 def __init__(self):
329 color.__init__(self)
331 def getcolor(self, param):
332 """return color corresponding to param"""
333 pass
335 def select(self, index, n_indices):
336 """return a color corresponding to an index out of n_indices"""
337 if n_indices == 1:
338 param = 0
339 else:
340 param = index / (n_indices - 1.0)
341 return self.getcolor(param)
343 def outputPS(self, file, writer, context):
344 self.getcolor(0).outputPS(file, writer, context)
346 def outputPDF(self, file, writer, context):
347 self.getcolor(0).outputPDF(file, writer, context)
350 class linearpalette(palette):
352 """linearpalette is a collection of two colors for a linear transition between them"""
354 def __init__(self, mincolor, maxcolor):
355 palette.__init__(self)
356 if mincolor.__class__ != maxcolor.__class__:
357 raise ValueError
358 self.colorclass = mincolor.__class__
359 self.mincolor = mincolor
360 self.maxcolor = maxcolor
362 def getcolor(self, param):
363 colordict = {}
364 for key in self.mincolor.color.keys():
365 colordict[key] = param * self.maxcolor.color[key] + (1 - param) * self.mincolor.color[key]
366 return self.colorclass(**colordict)
369 class functionpalette(palette):
371 """functionpalette is a collection of colors for an arbitray non-linear transition between them
373 parameters:
374 functions: a dictionary for the color values
375 type: a string indicating the color class
378 def __init__(self, functions, type):
379 palette.__init__(self)
380 if type == "cmyk":
381 self.colorclass = cmyk
382 elif type == "rgb":
383 self.colorclass = rgb
384 elif type == "hsb":
385 self.colorclass = hsb
386 elif type == "grey" or type == "gray":
387 self.colorclass = grey
388 else:
389 raise ValueError
390 self.functions = functions
392 def getcolor(self, param):
393 colordict = {}
394 for key in self.functions.keys():
395 colordict[key] = self.functions[key](param)
396 return self.colorclass(**colordict)
399 palette.Gray = linearpalette(gray.white, gray.black)
400 palette.Grey = palette.Gray
401 palette.ReverseGray = linearpalette(gray.black, gray.white)
402 palette.ReverseGrey = palette.ReverseGray
403 palette.BlackYellow = functionpalette(functions={#(compare this with reversegray above)
404 "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)),
405 "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),
406 "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)},
407 type="rgb")
408 palette.RedGreen = linearpalette(rgb.red, rgb.green)
409 palette.RedBlue = linearpalette(rgb.red, rgb.blue)
410 palette.GreenRed = linearpalette(rgb.green, rgb.red)
411 palette.GreenBlue = linearpalette(rgb.green, rgb.blue)
412 palette.BlueRed = linearpalette(rgb.blue, rgb.red)
413 palette.BlueGreen = linearpalette(rgb.blue, rgb.green)
414 palette.RedBlack = linearpalette(rgb.red, rgb.black)
415 palette.BlackRed = linearpalette(rgb.black, rgb.red)
416 palette.RedWhite = linearpalette(rgb.red, rgb.white)
417 palette.WhiteRed = linearpalette(rgb.white, rgb.red)
418 palette.GreenBlack = linearpalette(rgb.green, rgb.black)
419 palette.BlackGreen = linearpalette(rgb.black, rgb.green)
420 palette.GreenWhite = linearpalette(rgb.green, rgb.white)
421 palette.WhiteGreen = linearpalette(rgb.white, rgb.green)
422 palette.BlueBlack = linearpalette(rgb.blue, rgb.black)
423 palette.BlackBlue = linearpalette(rgb.black, rgb.blue)
424 palette.BlueWhite = linearpalette(rgb.blue, rgb.white)
425 palette.WhiteBlue = linearpalette(rgb.white, rgb.blue)
426 palette.Rainbow = linearpalette(hsb(0, 1, 1), hsb(2.0/3.0, 1, 1))
427 palette.ReverseRainbow = linearpalette(hsb(2.0/3.0, 1, 1), hsb(0, 1, 1))
428 palette.Hue = linearpalette(hsb(0, 1, 1), hsb(1, 1, 1))
429 palette.ReverseHue = linearpalette(hsb(1, 1, 1), hsb(0, 1, 1))
432 class PDFextgstate(pdfwriter.PDFobject):
434 def __init__(self, name, extgstate):
435 pdfwriter.PDFobject.__init__(self, "extgstate", name, "ExtGState")
436 self.name = name
437 self.extgstate = extgstate
439 def outputPDF(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 outputPS(self, file, writer, context):
452 raise NotImplementedError("transparency not available in PostScript")
454 def registerPDF(self, registry):
455 registry.add(PDFextgstate(self.name, self.extgstate))
457 def outputPDF(self, file, writer, context):
458 file.write("/%s gs\n" % self.name)