print.py revision 1049
1all = False 2descriptions = False 3 4class Value: 5 def __init__(self, value, precision, percent = False): 6 self.value = value 7 self.precision = precision 8 self.percent = percent 9 def __str__(self): 10 if isinstance(self.value, str): 11 if self.value.lower() == 'nan': 12 value = 'NaN' 13 if self.value.lower() == 'inf': 14 value = 'Inf' 15 else: 16 if self.precision >= 0: 17 format = "%%.%df" % self.precision 18 elif self.value == 0.0: 19 format = "%.0f" 20 elif self.value % 1.0 == 0.0: 21 format = "%.0f" 22 else: 23 format = "%f" 24 value = self.value 25 if self.percent: 26 value = value * 100.0 27 value = format % value 28 29 if self.percent: 30 value = value + "%" 31 32 return value 33 34class Print: 35 def __init__(self, **vals): 36 self.__dict__.update(vals) 37 38 def __str__(self): 39 value = Value(self.value, self.precision) 40 pdf = '' 41 cdf = '' 42 if self.__dict__.has_key('pdf'): 43 pdf = Value(self.pdf, 2, True) 44 if self.__dict__.has_key('cdf'): 45 cdf = Value(self.cdf, 2, True) 46 47 output = "%-40s %12s %8s %8s" % (self.name, value, pdf, cdf) 48 49 if descriptions and self.__dict__.has_key('desc') and self.desc: 50 output = "%s # %s" % (output, self.desc) 51 52 return output 53 54 def doprint(self): 55 if display_all: 56 return True 57 if self.value == 0.0 and (self.flags & flags_nozero): 58 return False 59 if isinstance(self.value, str): 60 if self.value == 'NaN' and (self.flags & flags_nonan): 61 return False 62 return True 63 64 def display(self): 65 if self.doprint(): 66 print self 67 68class VectorDisplay: 69 def display(self): 70 p = Print() 71 p.flags = self.flags 72 p.precision = self.precision 73 74 if issequence(self.value): 75 if not len(self.value): 76 return 77 78 mytotal = reduce(lambda x,y: float(x) + float(y), self.value) 79 mycdf = 0.0 80 81 value = self.value 82 83 if display_all: 84 subnames = [ '[%d]' % i for i in range(len(value)) ] 85 else: 86 subnames = [''] * len(value) 87 88 if self.__dict__.has_key('subnames'): 89 for i,each in enumerate(self.subnames): 90 if len(each) > 0: 91 subnames[i] = '.%s' % each 92 93 subdescs = [self.desc]*len(value) 94 if self.__dict__.has_key('subdescs'): 95 for i in xrange(min(len(value), len(self.subdescs))): 96 subdescs[i] = self.subdescs[i] 97 98 for val,sname,sdesc in map(None, value, subnames, subdescs): 99 if mytotal > 0.0: 100 mypdf = float(val) / float(mytotal) 101 mycdf += mypdf 102 if (self.flags & flags_pdf): 103 p.pdf = mypdf 104 p.cdf = mycdf 105 106 if len(sname) == 0: 107 continue 108 109 p.name = self.name + sname 110 p.desc = sdesc 111 p.value = val 112 p.display() 113 114 if (self.flags & flags_total): 115 if (p.__dict__.has_key('pdf')): del p.__dict__['pdf'] 116 if (p.__dict__.has_key('cdf')): del p.__dict__['cdf'] 117 p.name = self.name + '.total' 118 p.desc = self.desc 119 p.value = mytotal 120 p.display() 121 122 else: 123 p.name = self.name 124 p.desc = self.desc 125 p.value = self.value 126 p.display() 127 128