implement central and parallel projection in 3d graphs; correct axis (tick direction...
[PyX/mjg.git] / pyx / color.py
blob29cd1a44d773d84e8088bc0e2857081e752e0576
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 binascii, colorsys, math, struct, warnings
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 grey(**self.color)
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 def colorspacestring(self):
95 return "/DeviceGray"
97 def tostring8bit(self):
98 return chr(round(self.color["gray"]*255))
100 grey.black = grey(0.0)
101 grey.white = grey(1.0)
102 gray = grey
105 class rgb(color):
107 """rgb colors"""
109 def __init__(self, r=0.0, g=0.0, b=0.0):
110 color.__init__(self)
111 if r<0 or r>1 or g<0 or g>1 or b<0 or b>1: raise ValueError
112 self.color = {"r": r, "g": g, "b": b}
114 def processPS(self, file, writer, context, registry, bbox):
115 file.write("%(r)g %(g)g %(b)g setrgbcolor\n" % self.color)
117 def processPDF(self, file, writer, context, registry, bbox):
118 if context.strokeattr:
119 file.write("%(r)f %(g)f %(b)f RG\n" % self.color)
120 if context.fillattr:
121 file.write("%(r)f %(g)f %(b)f rg\n" % self.color)
123 def cmyk(self):
124 # conversion to cmy
125 c, m, y = 1 - self.color["r"], 1 - self.color["g"], 1 - self.color["b"]
126 # conversion from cmy to cmyk with device-dependent functions
127 k = min([c, m, y])
128 return cmyk(min(1, max(0, c - _UCRc(k))),
129 min(1, max(0, m - _UCRm(k))),
130 min(1, max(0, y - _UCRy(k))),
131 _BG(k))
133 def grey(self):
134 return grey(0.3*self.color["r"] + 0.59*self.color["g"] + 0.11*self.color["b"])
135 gray = grey
137 def hsb(self):
139 values = self.color.values()
140 values.sort()
141 z, y, x = values
142 r, g, b = self.color["r"], self.color["g"], self.color["b"]
143 try:
144 if r == x and g == z:
145 return hsb((5 + (x-b)/(x-z)) / 6.0, (x - z) / x, x)
146 elif r == x and g > z:
147 return hsb((1 - (x-g)/(x-z)) / 6.0, (x - z) / x, x)
148 elif g == x and b == z:
149 return hsb((1 + (x-r)/(x-z)) / 6.0, (x - z) / x, x)
150 elif g == x and b > z:
151 return hsb((3 - (x-b)/(x-z)) / 6.0, (x - z) / x, x)
152 elif b == x and r == z:
153 return hsb((3 + (x-g)/(x-z)) / 6.0, (x - z) / x, x)
154 elif b == x and r > z:
155 return hsb((5 - (x-r)/(x-z)) / 6.0, (x - z) / x, x)
156 else:
157 raise ValueError
158 except ZeroDivisionError:
159 return hsb(0, 0, x)
161 def rgb(self):
162 return rgb(**self.color)
164 def colorspacestring(self):
165 return "/DeviceRGB"
167 def tostring8bit(self):
168 return struct.pack("BBB", int(self.color["r"]*255), int(self.color["g"]*255), int(self.color["b"]*255))
170 def tohexstring(self, cssstrip=1, addhash=1):
171 hexstring = binascii.b2a_hex(self.to8bitstring())
172 if cssstrip and hexstring[0] == hexstring[1] and hexstring[2] == hexstring[3] and hexstring[4] == hexstring[5]:
173 hexstring = "".join([hexstring[0], hexstring[1], hexstring[2]])
174 if addhash:
175 hexstring = "#" + hexstring
176 return hexstring
179 def rgbfromhexstring(hexstring):
180 hexstring = hexstring.strip().lstrip("#")
181 if len(hexstring) == 3:
182 hexstring = "".join([hexstring[0], hexstring[0], hexstring[1], hexstring[1], hexstring[2], hexstring[2]])
183 elif len(hexstring) != 6:
184 raise ValueError("3 or 6 digit hex number expected (with optional leading hash character)")
185 return rgb(*[value/255.0 for value in struct.unpack("BBB", binascii.a2b_hex(hexstring))])
187 rgb.red = rgb(1, 0, 0)
188 rgb.green = rgb(0, 1, 0)
189 rgb.blue = rgb(0, 0, 1)
190 rgb.white = rgb(1, 1, 1)
191 rgb.black = rgb(0, 0, 0)
194 class hsb(color):
196 """hsb colors"""
198 def __init__(self, h=0.0, s=0.0, b=0.0):
199 color.__init__(self)
200 if h<0 or h>1 or s<0 or s>1 or b<0 or b>1: raise ValueError
201 self.color = {"h": h, "s": s, "b": b}
203 def processPS(self, file, writer, context, registry, bbox):
204 file.write("%(h)g %(s)g %(b)g sethsbcolor\n" % self.color)
206 def processPDF(self, file, writer, context, registry, bbox):
207 r, g, b = colorsys.hsv_to_rgb(self.color["h"], self.color["s"], self.color["b"])
208 rgb(r, g, b).processPDF(file, writer, context, registry, bbox)
210 def cmyk(self):
211 return self.rgb().cmyk()
213 def grey(self):
214 return self.rgb().grey()
215 gray = grey
217 def hsb(self):
218 return hsb(**self.color)
220 def rgb(self):
221 h, s, b = self.color["h"], self.color["s"], self.color["b"]
222 i = int(6*h)
223 f = 6*h - i
224 m, n, k = 1 - s, 1 - s*f, 1 - s*(1-f)
225 if i == 1:
226 return rgb(b*n, b, b*m)
227 elif i == 2:
228 return rgb(b*m, b, b*k)
229 elif i == 3:
230 return rgb(b*m, b*n, b)
231 elif i == 4:
232 return rgb(b*k, b*m, b)
233 elif i == 5:
234 return rgb(b, b*m, b*n)
235 else:
236 return rgb(b, b*k, b*m)
239 class cmyk(color):
241 """cmyk colors"""
243 def __init__(self, c=0.0, m=0.0, y=0.0, k=0.0):
244 color.__init__(self)
245 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
246 self.color = {"c": c, "m": m, "y": y, "k": k}
248 def processPS(self, file, writer, context, registry, bbox):
249 file.write("%(c)g %(m)g %(y)g %(k)g setcmykcolor\n" % self.color)
251 def processPDF(self, file, writer, context, registry, bbox):
252 if context.strokeattr:
253 file.write("%(c)f %(m)f %(y)f %(k)f K\n" % self.color)
254 if context.fillattr:
255 file.write("%(c)f %(m)f %(y)f %(k)f k\n" % self.color)
257 def cmyk(self):
258 return cmyk(**self.color)
260 def grey(self):
261 return grey(1 - min([1, 0.3*self.color["c"] + 0.59*self.color["m"] +
262 0.11*self.color["y"] + self.color["k"]]))
263 gray = grey
265 def hsb(self):
266 return self.rgb().hsb()
268 def rgb(self):
269 # conversion to cmy:
270 c = min(1, self.color["c"] + self.color["k"])
271 m = min(1, self.color["m"] + self.color["k"])
272 y = min(1, self.color["y"] + self.color["k"])
273 # conversion from cmy to rgb:
274 return rgb(1 - c, 1 - m, 1 - y)
276 def colorspacestring(self):
277 return "/DeviceCMYK"
279 def tostring8bit(self):
280 return struct.pack("BBBB", round(self.color["c"]*255), round(self.color["m"]*255), round(self.color["y"]*255), round(self.color["k"]*255))
282 cmyk.GreenYellow = cmyk(0.15, 0, 0.69, 0)
283 cmyk.Yellow = cmyk(0, 0, 1, 0)
284 cmyk.Goldenrod = cmyk(0, 0.10, 0.84, 0)
285 cmyk.Dandelion = cmyk(0, 0.29, 0.84, 0)
286 cmyk.Apricot = cmyk(0, 0.32, 0.52, 0)
287 cmyk.Peach = cmyk(0, 0.50, 0.70, 0)
288 cmyk.Melon = cmyk(0, 0.46, 0.50, 0)
289 cmyk.YellowOrange = cmyk(0, 0.42, 1, 0)
290 cmyk.Orange = cmyk(0, 0.61, 0.87, 0)
291 cmyk.BurntOrange = cmyk(0, 0.51, 1, 0)
292 cmyk.Bittersweet = cmyk(0, 0.75, 1, 0.24)
293 cmyk.RedOrange = cmyk(0, 0.77, 0.87, 0)
294 cmyk.Mahogany = cmyk(0, 0.85, 0.87, 0.35)
295 cmyk.Maroon = cmyk(0, 0.87, 0.68, 0.32)
296 cmyk.BrickRed = cmyk(0, 0.89, 0.94, 0.28)
297 cmyk.Red = cmyk(0, 1, 1, 0)
298 cmyk.OrangeRed = cmyk(0, 1, 0.50, 0)
299 cmyk.RubineRed = cmyk(0, 1, 0.13, 0)
300 cmyk.WildStrawberry = cmyk(0, 0.96, 0.39, 0)
301 cmyk.Salmon = cmyk(0, 0.53, 0.38, 0)
302 cmyk.CarnationPink = cmyk(0, 0.63, 0, 0)
303 cmyk.Magenta = cmyk(0, 1, 0, 0)
304 cmyk.VioletRed = cmyk(0, 0.81, 0, 0)
305 cmyk.Rhodamine = cmyk(0, 0.82, 0, 0)
306 cmyk.Mulberry = cmyk(0.34, 0.90, 0, 0.02)
307 cmyk.RedViolet = cmyk(0.07, 0.90, 0, 0.34)
308 cmyk.Fuchsia = cmyk(0.47, 0.91, 0, 0.08)
309 cmyk.Lavender = cmyk(0, 0.48, 0, 0)
310 cmyk.Thistle = cmyk(0.12, 0.59, 0, 0)
311 cmyk.Orchid = cmyk(0.32, 0.64, 0, 0)
312 cmyk.DarkOrchid = cmyk(0.40, 0.80, 0.20, 0)
313 cmyk.Purple = cmyk(0.45, 0.86, 0, 0)
314 cmyk.Plum = cmyk(0.50, 1, 0, 0)
315 cmyk.Violet = cmyk(0.79, 0.88, 0, 0)
316 cmyk.RoyalPurple = cmyk(0.75, 0.90, 0, 0)
317 cmyk.BlueViolet = cmyk(0.86, 0.91, 0, 0.04)
318 cmyk.Periwinkle = cmyk(0.57, 0.55, 0, 0)
319 cmyk.CadetBlue = cmyk(0.62, 0.57, 0.23, 0)
320 cmyk.CornflowerBlue = cmyk(0.65, 0.13, 0, 0)
321 cmyk.MidnightBlue = cmyk(0.98, 0.13, 0, 0.43)
322 cmyk.NavyBlue = cmyk(0.94, 0.54, 0, 0)
323 cmyk.RoyalBlue = cmyk(1, 0.50, 0, 0)
324 cmyk.Blue = cmyk(1, 1, 0, 0)
325 cmyk.Cerulean = cmyk(0.94, 0.11, 0, 0)
326 cmyk.Cyan = cmyk(1, 0, 0, 0)
327 cmyk.ProcessBlue = cmyk(0.96, 0, 0, 0)
328 cmyk.SkyBlue = cmyk(0.62, 0, 0.12, 0)
329 cmyk.Turquoise = cmyk(0.85, 0, 0.20, 0)
330 cmyk.TealBlue = cmyk(0.86, 0, 0.34, 0.02)
331 cmyk.Aquamarine = cmyk(0.82, 0, 0.30, 0)
332 cmyk.BlueGreen = cmyk(0.85, 0, 0.33, 0)
333 cmyk.Emerald = cmyk(1, 0, 0.50, 0)
334 cmyk.JungleGreen = cmyk(0.99, 0, 0.52, 0)
335 cmyk.SeaGreen = cmyk(0.69, 0, 0.50, 0)
336 cmyk.Green = cmyk(1, 0, 1, 0)
337 cmyk.ForestGreen = cmyk(0.91, 0, 0.88, 0.12)
338 cmyk.PineGreen = cmyk(0.92, 0, 0.59, 0.25)
339 cmyk.LimeGreen = cmyk(0.50, 0, 1, 0)
340 cmyk.YellowGreen = cmyk(0.44, 0, 0.74, 0)
341 cmyk.SpringGreen = cmyk(0.26, 0, 0.76, 0)
342 cmyk.OliveGreen = cmyk(0.64, 0, 0.95, 0.40)
343 cmyk.RawSienna = cmyk(0, 0.72, 1, 0.45)
344 cmyk.Sepia = cmyk(0, 0.83, 1, 0.70)
345 cmyk.Brown = cmyk(0, 0.81, 1, 0.60)
346 cmyk.Tan = cmyk(0.14, 0.42, 0.56, 0)
347 cmyk.Gray = cmyk(0, 0, 0, 0.50)
348 cmyk.Grey = cmyk.Gray
349 cmyk.Black = cmyk(0, 0, 0, 1)
350 cmyk.White = cmyk(0, 0, 0, 0)
351 cmyk.white = cmyk.White
352 cmyk.black = cmyk.Black
354 class palette(attr.changelist):
355 """color palettes
357 A color palette is a discrete, ordered list of colors"""
359 palette.clear = attr.clearclass(palette)
362 class gradient(attr.changeattr):
364 """base class for color gradients
366 A gradient is a continuous collection of colors with a single parameter ranging from 0 to 1
367 to address them"""
369 def getcolor(self, param):
370 """return color corresponding to param"""
371 pass
373 def select(self, index, n_indices):
374 """return a color corresponding to an index out of n_indices"""
375 if n_indices == 1:
376 param = 0
377 else:
378 param = index / (n_indices - 1.0)
379 return self.getcolor(param)
381 gradient.clear = attr.clearclass(gradient)
384 class lineargradient(gradient):
386 """collection of two colors for a linear transition between them"""
388 def __init__(self, mincolor, maxcolor):
389 if mincolor.__class__ != maxcolor.__class__:
390 raise ValueError
391 self.colorclass = mincolor.__class__
392 self.mincolor = mincolor
393 self.maxcolor = maxcolor
395 def getcolor(self, param):
396 colordict = {}
397 for key in self.mincolor.color.keys():
398 colordict[key] = param * self.maxcolor.color[key] + (1 - param) * self.mincolor.color[key]
399 return self.colorclass(**colordict)
402 class functiongradient(gradient):
404 """collection of colors for an arbitray non-linear transition between them
406 parameters:
407 functions: a dictionary for the color values
408 type: a string indicating the color class
411 def __init__(self, functions, type):
412 if type == "cmyk":
413 self.colorclass = cmyk
414 elif type == "rgb":
415 self.colorclass = rgb
416 elif type == "hsb":
417 self.colorclass = hsb
418 elif type == "grey" or type == "gray":
419 self.colorclass = grey
420 else:
421 raise ValueError
422 self.functions = functions
424 def getcolor(self, param):
425 colordict = {}
426 for key in self.functions.keys():
427 colordict[key] = self.functions[key](param)
428 return self.colorclass(**colordict)
431 gradient.Gray = lineargradient(gray.white, gray.black)
432 gradient.Grey = gradient.Gray
433 gradient.ReverseGray = lineargradient(gray.black, gray.white)
434 gradient.ReverseGrey = gradient.ReverseGray
435 gradient.BlackYellow = functiongradient(functions={ # compare this with reversegray above
436 "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)),
437 "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),
438 "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)},
439 type="rgb")
440 gradient.RedGreen = lineargradient(rgb.red, rgb.green)
441 gradient.RedBlue = lineargradient(rgb.red, rgb.blue)
442 gradient.GreenRed = lineargradient(rgb.green, rgb.red)
443 gradient.GreenBlue = lineargradient(rgb.green, rgb.blue)
444 gradient.BlueRed = lineargradient(rgb.blue, rgb.red)
445 gradient.BlueGreen = lineargradient(rgb.blue, rgb.green)
446 gradient.RedBlack = lineargradient(rgb.red, rgb.black)
447 gradient.BlackRed = lineargradient(rgb.black, rgb.red)
448 gradient.RedWhite = lineargradient(rgb.red, rgb.white)
449 gradient.WhiteRed = lineargradient(rgb.white, rgb.red)
450 gradient.GreenBlack = lineargradient(rgb.green, rgb.black)
451 gradient.BlackGreen = lineargradient(rgb.black, rgb.green)
452 gradient.GreenWhite = lineargradient(rgb.green, rgb.white)
453 gradient.WhiteGreen = lineargradient(rgb.white, rgb.green)
454 gradient.BlueBlack = lineargradient(rgb.blue, rgb.black)
455 gradient.BlackBlue = lineargradient(rgb.black, rgb.blue)
456 gradient.BlueWhite = lineargradient(rgb.blue, rgb.white)
457 gradient.WhiteBlue = lineargradient(rgb.white, rgb.blue)
458 gradient.Rainbow = lineargradient(hsb(0, 1, 1), hsb(2.0/3.0, 1, 1))
459 gradient.ReverseRainbow = lineargradient(hsb(2.0/3.0, 1, 1), hsb(0, 1, 1))
460 gradient.Hue = lineargradient(hsb(0, 1, 1), hsb(1, 1, 1))
461 gradient.ReverseHue = lineargradient(hsb(1, 1, 1), hsb(0, 1, 1))
464 class PDFextgstate(pdfwriter.PDFobject):
466 def __init__(self, name, extgstate, registry):
467 pdfwriter.PDFobject.__init__(self, "extgstate", name)
468 registry.addresource("ExtGState", name, self)
469 self.name = name
470 self.extgstate = extgstate
472 def write(self, file, writer, registry):
473 file.write("%s\n" % self.extgstate)
476 class transparency(attr.exclusiveattr, style.strokestyle, style.fillstyle):
478 def __init__(self, value):
479 self.value = 1-value
480 attr.exclusiveattr.__init__(self, transparency)
482 def processPS(self, file, writer, context, registry, bbox):
483 warnings.warn("Transparency not available in PostScript, proprietary ghostscript extension code inserted.")
484 file.write("%f .setshapealpha\n" % self.value)
486 def processPDF(self, file, writer, context, registry, bbox):
487 if context.strokeattr and context.fillattr:
488 registry.add(PDFextgstate("Transparency-%f" % self.value,
489 "<< /Type /ExtGState /CA %f /ca %f >>" % (self.value, self.value), registry))
490 file.write("/Transparency-%f gs\n" % self.value)
491 elif context.strokeattr:
492 registry.add(PDFextgstate("Transparency-Stroke-%f" % self.value,
493 "<< /Type /ExtGState /CA %f >>" % self.value, registry))
494 file.write("/Transparency-Stroke-%f gs\n" % self.value)
495 elif context.fillattr:
496 registry.add(PDFextgstate("Transparency-Fill-%f" % self.value,
497 "<< /Type /ExtGState /ca %f >>" % self.value, registry))
498 file.write("/Transparency-Fill-%f gs\n" % self.value)