Menu

[r71]: / trunk / plotmodels.py  Maximize  Restore  History

Download this file

185 lines (153 with data), 6.7 kB

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
"""Auto-define and -update mechanism for django-dataplot images.
Comment out this line in your models.py:
# from django.db import models
Then add:
from dataplot import plotsmodels as models
"""
from django.db.models.base import ModelBase
from django.db.models import * # so we can use this as a models file
from django.utils.functional import curry
from copy import copy
import dataplot
import os,re
import pdb
class DataplotImproperlyConfigured(dataplot.PlotError): pass
UNSAFE_FILE_CHARS=re.compile(r'[^a-zA-Z0-9]')
class Dataplot(object):
"""Parsing logic for dataplot autoconfig tuples.
This is just used for DRY convenience here and should not be used
outside this module.
"""
def get_method(self):
"""Construct a data-returning method from the tuple.
"""
return curry(get_plot_args,plot_dict=self.kwargs['plot_dict'],
default_args_map=getattr(self.plot,'default_args_map',{}))
def __init__(self,plot):
"""Initialize a dataplot using sensible defaults.
This can be a
dataplot (subclass of dataplot.GenericPlot, i.e. R.Scatter) in
this case, we assume basename of scatter and a plot method
called get_scatter_args.
tuple (dataplot,dict) where dict is a dictionary of kwargs
used to initialize the dataplot. So you can use this form if
you want to override the default basename, get_plot_args
method, or other plot parameters.
"""
if type(plot)==tuple:
plot,kwargs=plot
else:
kwargs={}
self.plot=plot
self.kwargs=kwargs
# Parse plotargs
plotname=kwargs.setdefault('plotname',plot.__name__)
kwargs.setdefault('attribute',plotname)
get_plot_args=kwargs.get('get_plot_args',kwargs['attribute'])
if type(get_plot_args)==dict:
plot_dict=get_plot_args
methodname=kwargs['attribute']
elif type(get_plot_args)==str:
plot_dict=None
methodname=get_plot_args
else:
raise DataplotImproperlyConfigured(
"get_plot_args must be unassigned, dict, or str")
kwargs['plot_dict']=plot_dict
kwargs['methodname']='%s_args'%methodname
def get_plot_args(self,plot_dict,default_args_map):
new_plot_dict=dict(plot_dict)
qs=getattr(self,'plotable',self.all)()
for k,v in new_plot_dict.iteritems():
try: # to get value list from fields
vals=[getattr(row,v) for row in qs]
new=[callable(val) and val() or val for val in vals]
except: # field not specified
try: # to get a named attribute
attr=getattr(self,v,v)
new=callable(attr) and attr() or attr
except: # not a named attribute, just keep the value
new=v
new_plot_dict[k]=new
for k,v in default_args_map.iteritems(): # set default args if specified
new_plot_dict.setdefault(k,plot_dict[v])
return new_plot_dict
class ModelBase(ModelBase):
"""Extend ModelBase to initialize dataplots.
"""
def __init__(self,*posargs,**kwargs):
"""automatic dataplot construction based on DATAPLOTS syntax
"""
super(ModelBase,self).__init__(*posargs,**kwargs)
# Need to reset manager since Django guesses poorly with inheritance
# Also bad: default manager is shared across all models
# so if we don't reset we will end up setting attrs and methods
# across all default managers
self.objects=self._default_manager=copy(self.objects)
self.objects.model=self
#print self,self.objects.model._meta.db_table,self._meta.db_table
#print self.objects,self.ChangeManipulator.manager.model._meta.db_table,self._default_manager.model._meta.db_table
#pdb.set_trace()
for plotarg in getattr(self,'MANAGER_DATAPLOTS',[]):
dp=Dataplot(plotarg)
# don't overwrite an existing method of that name
no_method=not hasattr(
self.objects.__class__,dp.kwargs['methodname'])
if dp.kwargs['plot_dict'] and no_method:
setattr(
self.objects.__class__,
dp.kwargs['methodname'],
dp.get_method())
# construct basename default
diff=dp.kwargs['attribute']!=dp.kwargs['plotname']
nameitems=(
dp.kwargs['plotname'],
diff and dp.kwargs['attribute'],
)
name='_'.join([str(x) for x in nameitems if x])
subdir=getattr(
self,'DATAPLOT_SUBDIR',
os.path.join(self.__module__.split('.')[-2],self.__name__))
basename=subdir!=None and os.path.join(subdir,name) or name
method=getattr(self.objects,dp.kwargs['methodname'],None)
if method:
inst=dp.plot(basename,method)
else:
raise DataplotImproperlyConfigured(
"\nYou must define attribute "+
dp.kwargs['methodname']+
" for \n"+
str(self.objects)+
"\nsince you gave\n"+
str(plotarg)+
"\nin MANAGER_DATAPLOTS")
setattr(self.objects,dp.kwargs['attribute'],inst)
class Model(Model):
"""Enables figure autosave with Django-dataplot.
All attributes of this model which are instances of
dataplot.GenericPlot will be resaved.
"""
__metaclass__=ModelBase
def save(self):
"""Save method which allows for maximum configurability.
On a model with no custom save method, we will call django's
save first, then try to make plots for this object.
On a model with a custom save method, you should call
make_plots and Model.save yourself, depending on when it is
appropriate in terms of your data processing.
"""
super(Model,self).save()
self.make_plots()
def make_plots(self):
"""Try to remake plots related to this model.
This includes plots which are attributes of this model, and
model-level plots which are attributes of this model's
manager.
"""
for x in self,self.__class__.objects:
cancel_attr='DO_NOT_CACHE_%s_PLOTS'%(
x.__class__.__bases__[-1].__name__.upper())
if not getattr(self,cancel_attr,None):
for at in x.__dict__.values():
if at and isinstance(at,dataplot.GenericPlot):
at.makefiles()
Want the latest updates on software, tech news, and AI?
Get latest updates about software, tech news, and AI from SourceForge directly in your inbox once a month.