~ubuntu-branches/ubuntu/karmic/model-builder/karmic

« back to all changes in this revision

Viewing changes to model_builder/uncertaintyMiniFrame.py

  • Committer: Bazaar Package Importer
  • Author(s): Varun Hiremath
  • Date: 2007-04-10 17:05:04 UTC
  • Revision ID: james.westby@ubuntu.com-20070410170504-y884ntvt656218me
Tags: upstream-0.4.0
Import upstream version 0.4.0

Show diffs side-by-side

added added

removed removed

Lines of Context:
 
1
# -*- coding:iso8859-1 -*- 
 
2
#-----------------------------------------------------------------------------
 
3
# Name:        uncertaintyMiniFrame.py
 
4
# Purpose:     Panel to specify parameters for the uncertainty analysis
 
5
#
 
6
# Author:      <Fl�vio Code�o Coelho>
 
7
#
 
8
# Created:     2003/02/04
 
9
# RCS-ID:      $Id: uncertaintyMiniFrame.py,v 1.3 2004/01/13 10:51:43 fccoelho Exp $
 
10
# Copyright:   (c) 2003 Fl�vio Code�o Coelho <fccoelho@uerj.br>
 
11
# Licence:     This program is free software; you can redistribute it and/or
 
12
# modify it under the terms of the GNU General Public License
 
13
# as published by the Free Software Foundation; either version 2
 
14
# of the License, or (at your option) any later version.
 
15
#
 
16
# This program is distributed in the hope that it will be useful,
 
17
# but WITHOUT ANY WARRANTY; without even the implied warranty of
 
18
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 
19
# GNU General Public License for more details.
 
20
#
 
21
# You should have received a copy of the GNU General Public License
 
22
# along with this program; if not, write to the Free Software
 
23
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 
24
#
 
25
#-----------------------------------------------------------------------------
 
26
#Boa:MiniFrame:uncertaintyMiniFrame
 
27
import wxversion
 
28
wxversion.select('2.6')
 
29
import wx
 
30
import wx.gizmos
 
31
from Numeric import *
 
32
from string import *
 
33
from Bayes import Melding as meld
 
34
import os
 
35
 
 
36
def create(parent):
 
37
    return uncertaintyMiniFrame(parent)
 
38
 
 
39
[wxID_UNCERTAINTYMINIFRAME, wxID_UNCERTAINTYMINIFRAMEDONEBUTTON, 
 
40
 wxID_UNCERTAINTYMINIFRAMELIKLIST, wxID_UNCERTAINTYMINIFRAMEPRIORLIST, 
 
41
 wxID_UNCERTAINTYMINIFRAMESELALL, wxID_UNCERTAINTYMINIFRAMESPINCTRL1, 
 
42
 wxID_UNCERTAINTYMINIFRAMESTATICTEXT1, wxID_UNCERTAINTYMINIFRAMESTATICTEXT2, 
 
43
 wxID_UNCERTAINTYMINIFRAMESTATICTEXT3, wxID_UNCERTAINTYMINIFRAMESTATICTEXT4, 
 
44
 wxID_UNCERTAINTYMINIFRAMESTATICTEXT5, wxID_UNCERTAINTYMINIFRAMESTATUSPANEL, 
 
45
 wxID_UNCERTAINTYMINIFRAMEVARLIST, 
 
46
] = [wx.NewId() for _init_ctrls in range(13)]
 
47
 
 
48
class uncertaintyMiniFrame(wx.MiniFrame):
 
49
    def _init_ctrls(self, prnt):
 
50
        # generated method, don't edit
 
51
        wx.MiniFrame.__init__(self, id=wxID_UNCERTAINTYMINIFRAME,
 
52
              name='uncertaintyMiniFrame', parent=prnt, pos=wx.Point(181, 159),
 
53
              size=wx.Size(683, 445), style=wx.DEFAULT_FRAME_STYLE,
 
54
              title='Bayesian Melding Uncertainty Analysis')
 
55
        self.SetClientSize(wx.Size(683, 445))
 
56
        self.SetAutoLayout(True)
 
57
        self.SetToolTipString('Melding parameters')
 
58
        self.Bind(wx.EVT_CLOSE, self.OnUncertaintyMiniFrameClose)
 
59
 
 
60
        self.staticText1 = wx.StaticText(id=wxID_UNCERTAINTYMINIFRAMESTATICTEXT1,
 
61
              label='Choose state variable(s) to be analyzed:',
 
62
              name='staticText1', parent=self, pos=wx.Point(24, 16),
 
63
              size=wx.Size(226, 16), style=0)
 
64
 
 
65
        self.staticText2 = wx.StaticText(id=wxID_UNCERTAINTYMINIFRAMESTATICTEXT2,
 
66
              label='Variables:', name='staticText2', parent=self,
 
67
              pos=wx.Point(24, 40), size=wx.Size(56, 16), style=0)
 
68
 
 
69
        self.varList = wx.CheckListBox(choices=['Y[0]', 'Y[1]'],
 
70
              id=wxID_UNCERTAINTYMINIFRAMEVARLIST, name='varList', parent=self,
 
71
              pos=wx.Point(24, 56), size=wx.Size(104, 40), style=wx.VSCROLL,
 
72
              validator=wx.DefaultValidator)
 
73
        self.varList.SetToolTipString('The checked variables will be retained in memory for analysis.')
 
74
        self.varList.SetThemeEnabled(True)
 
75
        self.varList.Bind(wx.EVT_CHECKLISTBOX, self.OnVarListChecklistbox,
 
76
              id=wxID_UNCERTAINTYMINIFRAMEVARLIST)
 
77
        self.varList.Bind(wx.EVT_LISTBOX, self.OnVarListListbox,
 
78
              id=wxID_UNCERTAINTYMINIFRAMEVARLIST)
 
79
 
 
80
        self.staticText4 = wx.StaticText(id=wxID_UNCERTAINTYMINIFRAMESTATICTEXT4,
 
81
              label='Number of runs (k):', name='staticText4', parent=self,
 
82
              pos=wx.Point(300, 16), size=wx.Size(106, 16), style=0)
 
83
 
 
84
        self.spinCtrl1 = wx.SpinCtrl(id=wxID_UNCERTAINTYMINIFRAMESPINCTRL1,
 
85
              initial=5, max=100000, min=2, name='spinCtrl1', parent=self,
 
86
              pos=wx.Point(416, 16), size=wx.Size(95, 22),
 
87
              style=wx.SP_ARROW_KEYS)
 
88
        self.spinCtrl1.SetToolTipString('Number of times model should be run.')
 
89
        self.spinCtrl1.SetRange(2, 100000)
 
90
        self.spinCtrl1.SetThemeEnabled(True)
 
91
 
 
92
        self.Donebutton = wx.Button(id=wxID_UNCERTAINTYMINIFRAMEDONEBUTTON,
 
93
              label='Done', name='Donebutton', parent=self, pos=wx.Point(576,
 
94
              400), size=wx.Size(80, 32), style=0)
 
95
        self.Donebutton.SetToolTipString('Hit here when done')
 
96
        self.Donebutton.SetThemeEnabled(True)
 
97
        self.Donebutton.Bind(wx.EVT_BUTTON, self.OnDonebuttonButton,
 
98
              id=wxID_UNCERTAINTYMINIFRAMEDONEBUTTON)
 
99
 
 
100
        self.priorList = wx.TextCtrl(id=wxID_UNCERTAINTYMINIFRAMEPRIORLIST,
 
101
              name='priorList', parent=self, pos=wx.Point(176, 56),
 
102
              size=wx.Size(224, 144), style=wx.VSCROLL | wx.TE_MULTILINE,
 
103
              value='uniform (0,2)')
 
104
 
 
105
        self.likList = wx.TextCtrl(id=wxID_UNCERTAINTYMINIFRAMELIKLIST,
 
106
              name='likList', parent=self, pos=wx.Point(176, 242),
 
107
              size=wx.Size(224, 144), style=wx.VSCROLL | wx.TE_MULTILINE,
 
108
              value='normal (1,1)')
 
109
        self.likList.SetToolTipString('List of likelihood functions for each state variable')
 
110
 
 
111
        self.staticText3 = wx.StaticText(id=wxID_UNCERTAINTYMINIFRAMESTATICTEXT3,
 
112
              label='Prior distributions:', name='staticText3', parent=self,
 
113
              pos=wx.Point(184, 40), size=wx.Size(99, 16), style=0)
 
114
 
 
115
        self.staticText5 = wx.StaticText(id=wxID_UNCERTAINTYMINIFRAMESTATICTEXT5,
 
116
              label='Likelihood functions:', name='staticText5', parent=self,
 
117
              pos=wx.Point(184, 224), size=wx.Size(114, 16), style=0)
 
118
 
 
119
        self.statusPanel = wx.TextCtrl(id=wxID_UNCERTAINTYMINIFRAMESTATUSPANEL,
 
120
              name='Statuspanel', parent=self, pos=wx.Point(424, 56),
 
121
              size=wx.Size(216, 328),
 
122
              style=wx.HSCROLL | wx.VSCROLL | wx.TE_MULTILINE,
 
123
              value='Status Report:')
 
124
 
 
125
        self.selAll = wx.Button(id=wxID_UNCERTAINTYMINIFRAMESELALL,
 
126
              label='Select All', name='selAll', parent=self, pos=wx.Point(24,
 
127
              112), size=wx.Size(88, 32), style=0)
 
128
        self.selAll.SetThemeEnabled(True)
 
129
        self.selAll.SetToolTipString('Press this button to select all variables in the above list.')
 
130
        self.selAll.Bind(wx.EVT_BUTTON, self.OnSelAllButton,
 
131
              id=wxID_UNCERTAINTYMINIFRAMESELALL)
 
132
 
 
133
    def __init__(self, parent):
 
134
        self._init_ctrls(parent)
 
135
        self.uncertainPars = None
 
136
        self.dataloaded = 0
 
137
 
 
138
    def createVarList(self, items):
 
139
        """
 
140
        Re-creates varList checkListBox from items received from the main frame
 
141
        """
 
142
        self.varList = wx.CheckListBox(choices=items,
 
143
            id=wxID_UNCERTAINTYMINIFRAMEVARLIST, name='varList', parent=self,
 
144
            pos= wx.Point(24, 56), size= wx.Size(142, 54), style=0,
 
145
            validator=wx.DefaultValidator)
 
146
        self.varList.SetToolTipString('the checked variables will have to be assigned prior distribution on the right, and likelihoods if available.\n'+'Total items: '+str(self.varList.GetCount()))
 
147
 
 
148
    def updatePriorList(self, n):
 
149
        """
 
150
        Updates the box of prior distributions with a list of uniform priors
 
151
        based on the number of state variables elected.
 
152
        """
 
153
        value = 'uniform(0,10)\n'*(n-1)
 
154
        value = value+'uniform(0,10)'
 
155
        self.priorList.SetValue(value)
 
156
 
 
157
 
 
158
    def saveSpecs(self):
 
159
        """
 
160
        Saves the specs of the last analysis ran.
 
161
        """
 
162
        fname = os.path.split(self.fileName)[1]
 
163
        fname = fname[:-4]+'_unc.spec'
 
164
        checkedvars = [self.varList.IsChecked(i) for i in range(self.varList.GetCount())]
 
165
        pr = self.priorList.GetValue()
 
166
        lk = self.likList.GetValue()
 
167
        nr = self.spinCtrl1.GetValue()
 
168
        uncSpecs = {'vars':checkedvars, 'priors':pr, 'liks':lk,'nruns':nr}
 
169
        f = open(fname,'w')
 
170
        pickle.dump(uncSpecs,f)
 
171
        f.close()
 
172
 
 
173
    def loadSpecs(self, fname):
 
174
        """
 
175
        Load specs from last uncertainty analysis ran from file fname.
 
176
        """
 
177
        f = open(fname,'r')
 
178
        uncSpecs = pickle.load(f)
 
179
        f.close()
 
180
        for i in range(len(uncSpecs['vars'])):
 
181
            if uncSpecs['vars'][i] == 1:
 
182
                self.varList.Check(i)
 
183
 
 
184
        self.priorList.SetValue(uncSpecs['priors'])
 
185
        self.likList.SetValue(uncSpecs['liks'])
 
186
        self.spinCtrl1.SetValue(uncSpecs['nruns'])
 
187
 
 
188
    def OnDonebuttonButton(self, event):
 
189
        """
 
190
        When clicked this button checks the information about the Bayesian melding analysis, saves it and open a dialog box for specification of a data file
 
191
        (containing the data to calculate the likelihoods).
 
192
        returns a dictionary (uncertainPars) with the data entered.
 
193
        """
 
194
        self.saveSpecs()
 
195
 
 
196
 
 
197
# TODO: Introduce more checks to avoid stupid errors!!!
 
198
#---check if the number of checked variables is the same as the number of priors available---------------------------------------------------------------
 
199
        self.statusPanel.AppendText('\nChecking selected variables...\n')
 
200
        nvars = self.varList.GetCount() # Get the totalnumber of variables in varlist
 
201
        sel = [self.varList.IsChecked(i) for i in range(nvars)] # returns a list with ones for selected variables and zeros for not selected.
 
202
        if 1 not in sel: # if no variable has been selected, warn the user
 
203
            dlg = wx.MessageDialog(self, 'Select at least one variable from the list.',
 
204
              'Caption', wx.OK | wx.ICON_INFORMATION)
 
205
            try:
 
206
                dlg.ShowModal()
 
207
            finally:
 
208
                dlg.Destroy()
 
209
        self.statusPanel.AppendText('Done!\n\n')
 
210
 
 
211
#---Check if the number of priors entered corresponds to the number of variable selected----------------------------------------------------------------------------
 
212
        self.statusPanel.AppendText('Checking number of prior distributions...\n')
 
213
        npriors = int(self.priorList.GetNumberOfLines()) # Number of priors available
 
214
        while strip(self.priorList.GetLineText(npriors-1)) == '': # avoid getting empty lines at the end of the eq. box
 
215
            npriors = npriors-1
 
216
            if npriors == 1:
 
217
                break
 
218
 
 
219
        s = sum(array(sel))
 
220
        if s != npriors:
 
221
            dlg = wx.MessageDialog(self, 'The number of priors specified must be the same as the number of variables selected.',
 
222
              'Mismatched  number of variables and priors', wx.OK | wx.ICON_INFORMATION)
 
223
            try:
 
224
                dlg.ShowModal()
 
225
            finally:
 
226
                dlg.Destroy()
 
227
        self.statusPanel.AppendText('Done!\n\n')
 
228
 
 
229
        self.statusPanel.AppendText('Checking Number of likelihoods...\n')
 
230
        nlhoods = int(self.likList.GetNumberOfLines()) # Number of Likelihoods available
 
231
        while strip(self.likList.GetLineText(nlhoods-1)) == '': # avoid getting empty lines at the end of the eq. box
 
232
            nlhoods = nlhoods-1
 
233
            if nlhoods <= 1:
 
234
                break
 
235
        self.statusPanel.AppendText('Done!\n\n')
 
236
        if not self.likList.GetLineText(0) =='': #read datafile
 
237
            self.statusPanel.AppendText('Reading data from file...\n')
 
238
            dlg = wx.FileDialog(self, "Open data file", ".", "", "*.txt", wx.OPEN)
 
239
            try:
 
240
                if dlg.ShowModal() == wx.ID_OK:
 
241
                    filename = dlg.GetPath()
 
242
                    f = open(filename)
 
243
                    data = f.readlines()
 
244
                    f.close()
 
245
                    self.dataloaded = 1
 
246
                    self.statusPanel.AppendText('Done!\n\n')
 
247
            finally:
 
248
                dlg.Destroy()
 
249
 
 
250
            if len(data) != nlhoods: #check data size
 
251
                dlg = wx.MessageDialog(self, 'Number of datasets (lines) on the chosen file do not correspond to the number of likelihoods specified. Please open the correct file.',
 
252
                  'Wrong data file size!', wx.OK | wx.ICON_INFORMATION)
 
253
                try:
 
254
                    dlg.ShowModal()
 
255
                finally:
 
256
                    dlg.Destroy()
 
257
 
 
258
 
 
259
            else:
 
260
                datafloat=[None]
 
261
                for i in range(len(data)):
 
262
                    try:
 
263
                        data[i] = data[i][0:data[i].find("\\")] #remove newline characters
 
264
                    finally:
 
265
                        data[i] = data[i].split(' ') # Split strings into lists
 
266
                        datafloat[i] = [float(j) for j in data[i]] #Turns the list elements into   floats
 
267
                data = datafloat
 
268
 
 
269
 
 
270
#---initializing lists and dictionaries to receive form data----------------------------------------------------------------------------
 
271
        priors = []
 
272
        lhoods = []
 
273
        dist = []
 
274
        params = []
 
275
        distl = []
 
276
        paramsl = []
 
277
        k = self.spinCtrl1.GetValue() #number of runs
 
278
        for i in range(npriors):
 
279
            st = strip(self.priorList.GetLineText(i)) #get prior defining strings
 
280
            dist.append(strip(st[:find(st,'(')])) #parse distribution name
 
281
            params.append(eval(st[find(st,'('):])) # parse parameters string and eval it to a tuple
 
282
        priors = (dist,params) #name of the dist and parameters
 
283
        print dist[i]
 
284
#---generating priors----------------------------------------------------------------------------
 
285
        self.statusPanel.AppendText('generating priors...\n')
 
286
        priords = [meld.genprior(dist[i],params[i],k) for i in range(npriors)] #list of arrays
 
287
        self.statusPanel.AppendText('done!\n\n')
 
288
#-------------------------------------------------------------------------------
 
289
#---check if there are likelihoods available----------------------------------------------------------------------------
 
290
        if not self.likList.GetLineText(0) == '':
 
291
            for j in range(nlhoods):
 
292
                stl = strip(self.likList.GetLineText(j))#get likelihood defining strings
 
293
                distl.append(strip(stl[:find(stl,'(')]))#parse distribution name
 
294
                paramsl.append(eval(stl[find(stl,'('):]))# parse parameters string and eval it to a tuple
 
295
            lhoods = (distl,paramsl) #name of the dist and parameters
 
296
 
 
297
#---calculating likelihoods----------------------------------------------------------------------------
 
298
            self.statuspanel.AppendText('calculating likelihoods...\n')
 
299
            lik = []
 
300
            for l in range (nlhoods):
 
301
                dat = data[l]
 
302
                lik.append(meld.Likeli(dat, distl[l],paramsl[l])) #calculates likelihoods f
 
303
        else:
 
304
            lik=[]
 
305
 
 
306
 
 
307
 
 
308
        self.statusPanel.AppendText('done!\n\n')
 
309
        self.uncertainPars = (priors, priords, lhoods, lik)
 
310
        self.statusPanel.AppendText('press the start button on the main panel.\n')
 
311
        self.Donebutton.Disable()
 
312
 
 
313
    def OnSelAllButton(self, event):
 
314
        """
 
315
        When this button is clicked, it checks all items on the list.
 
316
        """
 
317
        n = self.varList.GetCount()
 
318
        for i in range(n):
 
319
            self.varList.Check(i)
 
320
        sel = sum(array([self.varList.IsChecked(i) for i in range(n)]))
 
321
        self.updatePriorList(sel)
 
322
 
 
323
    def OnVarListChecklistbox(self, event):
 
324
        """
 
325
        Every time an item is checked in the variable list box,
 
326
        it calls for an update of prior list box.
 
327
        """
 
328
        n = self.varList.GetCount()
 
329
        sel = sum(array([self.varList.IsChecked(i) for i in range(n)]))
 
330
        self.updatePriorList(sel)
 
331
 
 
332
    def OnUncertaintyMiniFrameClose(self, event):
 
333
        event.Skip()
 
334
 
 
335
    def OnVarListListbox(self, event):
 
336
        event.Skip()