Commits

Ralph Bean committed 95936e1

Added circle packing widget.

Comments (0)

Files changed (3)

         "tw2.jqplugins.flot",
         "tw2.protovis.conventional",
         "tw2.protovis.custom",
+        "tw2.protovis.hierarchies",
         "tw2.jit",
         "pyrrd",
     ],

tw2/rrd/samples.py

 import datetime
 
 arch = ['32', '64'][sys.maxsize > 2**32]
-data_directory = '/'.join(__file__.split('/')[:-1] + ['data', arch])
+data_directory = '/'.join(__file__.split('/')[:-1] + ['data', arch]) + '/'
 
-class DemoNestedRRDJitBarChart(tw2.rrd.NestedRRDJitBarChart):
+class DemoNestedRRDProtoCirclePackingWidget(
+    tw2.rrd.NestedRRDProtoCirclePackingWidget):
+
+    start = datetime.datetime.fromtimestamp(1306557540)
+    end = datetime.datetime.fromtimestamp(1306558380)
+
     rrd_directories = [
         data_directory + 'nested/filename/' + country
         for country in [

tw2/rrd/widgets.py

 import tw2.jqplugins.flot
 import tw2.protovis.custom
 import tw2.protovis.conventional
+import tw2.protovis.hierarchies
 
 import pyrrd.rrd
 
     @classmethod
     def directory2name(cls, dname):
         """ Convert a filename to an `attribute` name """
-        return dname.split('/')[-1]
+        name = dname.split('/')[-1]
+        if name == '':
+            name = dname.split('/')[-2]
+        return name
 
     @classmethod
     def _do_flat_fetch(cls, rrd_filenames):
-        ###print "doing work on:", rrd_filenames
         # Convert to seconds since the epoch
         end_s = int(time.mktime(cls.end.timetuple()))
         start_s = int(time.mktime(cls.start.timetuple()))
         # Now we can actually get the data.
         ###################################
 
-        ###print "Singleton...."
         return cls._do_flat_fetch(rrd_filenames)
 
 
             - A list of directories containing .rrd files.
         """)
 
-    def directory_fetch(self):
+    @classmethod
+    def nested_fetch(cls):
         cls.sanity()
 
         if type(cls.rrd_directories) != list:
             raise ValueError, "rrd_directories must be of homogeneous form"
 
         _type = types[0]
-        if not isinstance(_type, str):
+        if not _type in [str]:
             raise ValueError, "rrd_directories items must be 'str'"
 
         rrd_directories = cls.rrd_directories
 
         labels = [item[0] for item in rrd_directories]
         data = []
-        for directory in rrd_directories:
-            ###print "Nested:", dir
+        for name, directory in rrd_directories:
             rrd_filenames = [
-                directory + fname for fname in os.path.listdir(directory)
-                if fname.endswith('.rrd')
+                (cls.file2name(directory+fname), directory+fname)
+                for fname in os.listdir(directory) if fname.endswith('.rrd')
             ]
             data.append(cls._do_flat_fetch(rrd_filenames))
 
 
         super(FlatRRDJitAreaChart, self).prepare()
 
-class NestedRRDJitBarChart(tw2.jit.BarChart, RRDNestedMixin):
-    data = twc.Variable("Internally produced.")
-
-    def prepare(self):
-        self.data = self.directory_fetch()
-        raise NotImplementedError
-
-        labels = [ series['label'] for series in self.data ]
-
-        values = [{ 'label' : datum[0], 'values' : [] }
-                  for datum in self.data[0]['data']]
-
-        for i in range(len(self.data)):
-            for j in range(len(self.data[0]['data'])):
-                values[j]['values'].append(self.data[i]['data'][j][1])
-
-        self.data = { 'label' : labels, 'values' : values }
-
-        super(NestedRRDJitBarChart, self).prepare()
-
-
 class FlatRRDFlotWidget(tw2.jqplugins.flot.FlotWidget, RRDFlatMixin):
     data = twc.Variable("Internally produced.")
 
     def prepare(self):
         data = self.flat_fetch()
 
-        if self.sort_data:
+        if self.series_sorter:
             data.sort(self.series_sorter)
 
         if not self.method in ['sum', 'average']:
     def prepare(self):
         data = self.flat_fetch()
 
-        if self.sort_data:
+        if self.series_sorter:
             data.sort(self.series_sorter)
 
         if not self.method in ['sum', 'average']:
 
         super(FlatRRDProtoBubbleChart, self).prepare()
 
+class NestedRRDProtoCirclePackingWidget(
+    tw2.protovis.hierarchies.CirclePackingWidget, RRDNestedMixin):
+
+    p_data = twc.Variable("Internally produced.")
+    method = twc.Param(
+        "Method for consolidating values.  Either 'sum' or 'average'",
+        default='average')
+
+    def prepare(self):
+        if not self.method in ['sum', 'average']:
+            raise ValueError, "Illegal value '%s' for method" % self.method
+
+        self.data = self.nested_fetch()
+        self.p_data = {}
+
+        for i in range(len(self.data)):
+            key1 = self.data[i]['label']
+            self.p_data[key1] = {}
+            for j in range(len(self.data[i]['data'])):
+                key2 = self.data[i]['data'][j]['label']
+                value = sum([
+                    item[1] for item in self.data[i]['data'][j]['data']
+                ])
+
+                if self.method == 'average':
+                    value = float(value) / len(self.data[i]['data'][j]['data'])
+
+                if value == 0:
+                    continue
+
+                self.p_data[key1][key2] = value
+
+        for key in list(self.p_data.keys()):
+            if not self.p_data[key]:
+                del self.p_data[key]
+
+        super(NestedRRDProtoCirclePackingWidget, self).prepare()
+
+
 class FlatRRDProtoStackedAreaChart(tw2.protovis.conventional.StackedAreaChart,
                                    RRDFlatMixin):
     p_data = twc.Variable("Internally produced")