打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
A quick tutorial on Traits, Traits UI and Chaco
Traits is a Python package fromEnthought.  Traits allows us to easily give our variable an explicit type with optional bounds checking(this helps us to catch bugs as we develop our software).  Traits supports reactive programming, whichWikipedia defines as "Reactive programming is a programming paradigm oriented around data flows and the propagation of change.".   This sounds like exactly what we wish to do when writing a scientific application. Chaco is a visualisation package from Enthought, which produces excellent plots and integrates well with Traits.
This tutorial begins with a quick introduction to Traits and then presents and discusses a simple application.  This application will present the user with a graph and three sliders.  The sliders will set the coefficients of a polynomial.  The resulting polynomial will be displayed and updated as the sliders are moved.
Lets start with a simple demo of the traits package.
01.from enthought.traits.api import HasTraits,Int,Float,Str,Property
02.
03.class Person(HasTraits):
04.name = Str
05.age = Int
06.height = Float
07.weight = Float
08.
09.p = Person(name="Billy",age=18,height=2.,weight=90)
10.#p.height = "Raspberries"   #As height expects a float, this gives an error
11.p.configure_traits()
12.
13.print p.name,p.age,p.height,p.weight
Here we have created a class 'Person' with the attributes name,age,height,weight.  These attributes have a type associated with them, and will only accept data of that type (casting and coercion rules apply), if we give an unacceptable value Traits returns a nice descriptive error.  We then create a Person instance and call its 'configure_traits' method.  Running this program we see.
Traits has very kindly provided us with a GUI to configure this instance with, the layout can be customised to our needs.  If we supply bad data the UI highlights this and blocks us from continuing.
Make some changes and click OK, and the new values are displayed in the terminal.  All this has been achieved with minimal coding effort on the part of the user, there has been no need to pack widgets and write callbacks, Traits knows how to display a float,string etc and provides the appropriate display elements for us.  Now lets try something a little more useful.  Lets add a BMI attribute to our class.
01.from enthought.traits.api import HasTraits,Int,Float,Str,Property
02.class Person(HasTraits):
03.name = Str
04.age = Int
05.height = Float
06.weight = Float
07.
08.bmi = Property(Float,depends_on=["height","weight"])
09.
10.def _get_bmi(self):
11.return self.weight/self.height**2
12.
13.p = Person(name="Billy",age=18,height=2.,weight=90)
14.p.configure_traits()
We have specified that bmi is a property of type Float, which depends on two things height and weight.  Whenever we change one of these Traits will look for a method "_get_bmi" to calculate the new bmi (in fact Traits delays this call until the point when the attribute is actually needed).  Running this code we see the bmi field has been filled in, if we change either the height or weight, the new bmi is calculated.
Lets finish off by writing a custom view, this will enable us to
Display the traits we want in the order we want
Remove the age and name traits
Give the traits a slightly more descriptive name, including units.
Add a button to revert any changes we made to instance.
01.from enthought.traits.api import HasTraits,Int,Float,Str,Property
02.from enthought.traits.ui.api import View,Item,Label
03.from enthought.traits.ui.menu import OKButton, CancelButton,RevertButton
04.
05.class Person(HasTraits):
06.name = Str
07.age = Int
08.height = Float
09.weight = Float
10.
11.bmi = Property(Float,depends_on=["height","weight"])
12.
13.view = View(
14.Item("height",label = "Height / m"),
15.Item("weight",label = "Weight / kg"),
16.Item("bmi"),
17.buttons=[RevertButton,OKButton,CancelButton],
18.)
19.
20.def _get_bmi(self):
21.return self.weight/self.height**2
22.
23.p = Person(name="Billy",age=18,height=2.,weight=90)
24.p.configure_traits()
25.
26.print p.name,p.age.p.height,p.weight
The view is quite simple, we set three traits and give them a label, we then add some buttons.  The revert button allows us to revert any changes we have made to the instance.  Items can be grouped together easily.  To finish up lets present the graph plotting app, I believe its quite readable.
01.from enthought.traits.api import HasTraits,Int,Float,Str,Property,Range,Array
02.from enthought.traits.ui.api import View,Item,Label
03.from enthought.chaco.chaco_plot_editor import ChacoPlotItem
04.from numpy import array,poly1d,arange,linspace
05.
06.class PlotterApplication(HasTraits):
07.c0 = Range(-5.,5.)
08.c1 = Range(-5.,5.)
09.c2 = Range(-5.,5.)
10.
11.xdata = Array
12.ydata = Property(Array,depends_on=["c0","c1","c2"])
13.
14.#Set the coeffients to 0 as default
15.def _c0_default(self): return 0.
16.def _c1_default(self): return 0.
17.def _c2_default(self): return 0.
18.
19.def _xdata_default(self): return linspace(-10,10,100)
20.
21.def _get_ydata(self):
22.poly = poly1d([self.c2,self.c1,self.c0])
23.return poly(self.xdata)
24.
25.traits_view = View(
26.ChacoPlotItem("xdata","ydata", y_bounds=(-10.,10.),y_auto=False,resizable=True,show_label=False,x_label="x",y_label="y",title=""),
27.Item('c0'),
28.Item('c1'),
29.Item('c2'),
30.resizable = True,
31.width=900, height=800,
32.title="Plot App"
33.)
34.
35.if __name__ == "__main__":
36.p = PlotterApplication()
37.p.configure_traits()
We define five traits.  The first three are coefficients for the polynomial limited to the range (-5,5).  Then comes the array 'xdata' which has a default value set by '_xdata_default' .  The trait ydata is more interesting, it is defined as a being a property which depends on the coefficients, when the coefficients change the polynomial is recalculated.  The plot, an instance of 'ChacoPlotItem' knows that it depends on 'xdata' and 'ydata' and will replot itself whenever they change.  Then comes the view which displays the a plot window and the sliders.
For a little over 30 lines of code, this quite a powerful app.
本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
自定义的上拉加载更多
android加载长图宽度自适应,Android ImageView加载长图
UIImage 旋转和保存旋转 (转载)
iOS 图片平铺 drawAsPatternInRect
紧跟恺明的步伐:记录一下复现行为识别slowfast模型的全流程(附详细代码)
如何用PID算法,操控无人机悬停?
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服