1
# -*- coding:iso8859-1 -*-
2
#-----------------------------------------------------------------------------
3
# Name: uncertaintyMiniFrame.py
4
# Purpose: Panel to specify parameters for the uncertainty analysis
6
# Author: <Fl�vio Code�o Coelho>
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.
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.
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.
25
#-----------------------------------------------------------------------------
26
#Boa:MiniFrame:uncertaintyMiniFrame
28
wxversion.select('2.6')
33
from Bayes import Melding as meld
37
return uncertaintyMiniFrame(parent)
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)]
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)
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)
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)
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)
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)
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)
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)
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)')
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')
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)
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)
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:')
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)
133
def __init__(self, parent):
134
self._init_ctrls(parent)
135
self.uncertainPars = None
138
def createVarList(self, items):
140
Re-creates varList checkListBox from items received from the main frame
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()))
148
def updatePriorList(self, n):
150
Updates the box of prior distributions with a list of uniform priors
151
based on the number of state variables elected.
153
value = 'uniform(0,10)\n'*(n-1)
154
value = value+'uniform(0,10)'
155
self.priorList.SetValue(value)
160
Saves the specs of the last analysis ran.
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}
170
pickle.dump(uncSpecs,f)
173
def loadSpecs(self, fname):
175
Load specs from last uncertainty analysis ran from file fname.
178
uncSpecs = pickle.load(f)
180
for i in range(len(uncSpecs['vars'])):
181
if uncSpecs['vars'][i] == 1:
182
self.varList.Check(i)
184
self.priorList.SetValue(uncSpecs['priors'])
185
self.likList.SetValue(uncSpecs['liks'])
186
self.spinCtrl1.SetValue(uncSpecs['nruns'])
188
def OnDonebuttonButton(self, event):
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.
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)
209
self.statusPanel.AppendText('Done!\n\n')
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
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)
227
self.statusPanel.AppendText('Done!\n\n')
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
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)
240
if dlg.ShowModal() == wx.ID_OK:
241
filename = dlg.GetPath()
246
self.statusPanel.AppendText('Done!\n\n')
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)
261
for i in range(len(data)):
263
data[i] = data[i][0:data[i].find("\\")] #remove newline characters
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
270
#---initializing lists and dictionaries to receive form data----------------------------------------------------------------------------
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
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
297
#---calculating likelihoods----------------------------------------------------------------------------
298
self.statuspanel.AppendText('calculating likelihoods...\n')
300
for l in range (nlhoods):
302
lik.append(meld.Likeli(dat, distl[l],paramsl[l])) #calculates likelihoods f
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()
313
def OnSelAllButton(self, event):
315
When this button is clicked, it checks all items on the list.
317
n = self.varList.GetCount()
319
self.varList.Check(i)
320
sel = sum(array([self.varList.IsChecked(i) for i in range(n)]))
321
self.updatePriorList(sel)
323
def OnVarListChecklistbox(self, event):
325
Every time an item is checked in the variable list box,
326
it calls for an update of prior list box.
328
n = self.varList.GetCount()
329
sel = sum(array([self.varList.IsChecked(i) for i in range(n)]))
330
self.updatePriorList(sel)
332
def OnUncertaintyMiniFrameClose(self, event):
335
def OnVarListListbox(self, event):