Example #1
0
 def _newModel(self):
     # create new model.
     self.newModel = NewModel()
     # connect the new model to the controller.
     self.newModel.procDone.connect(self._runNewModel)
     # set new model screen to main widget.
     self.setCentralWidget(self.newModel)
     # close ferts.
     self.newModel.closeAllFerts()
     # add status bar.
     self.statusBar().showMessage('Ready to Run New Model')
Example #2
0
 def _newModel(self):
     # create new model.
     self.newModel = NewModel()
     # connect the new model to the controller.
     self.newModel.procDone.connect(self._runNewModel)
     # set new model screen to main widget.
     self.setCentralWidget(self.newModel)
     # close ferts.
     self.newModel.closeAllFerts()
     # add status bar.
     self.statusBar().showMessage('Ready to Run New Model')
Example #3
0
 def createNewModel_returnInputs(self):
     # add title
     nm = NewModel()
     nm.leTitle.setText('title')
     # add allocation
     nm.leAllocCG.setText('.25')
     # check every check box.
     nm.selectAll.setCheckState(2)
     nm.showAll(nm.selectAll)
     # add fertilizer distributions.
     ferts = nm.getAllAtributes('leF_')
     [fert[1].setText('.2') for fert in ferts]
     # create inputs
     inputs = nm.getInputs(nm.getBoxes(), nm.leTitle.text(), nm.getFerts(),
                           nm.operations, nm.leAllocCG.text())
     return inputs
Example #4
0
 def createNewModel_returnInputs(self):
     # add title
     nm = NewModel()
     nm.leTitle.setText('title')
     # add allocation
     nm.leAllocCG.setText('.25')
     # check every check box.
     nm.selectAll.setCheckState(2)
     nm.showAll(nm.selectAll)
     # add fertilizer distributions.
     ferts = nm.getAllAtributes('leF_')
     [fert[1].setText('.2') for fert in ferts]
     # create inputs
     inputs = nm.getInputs(nm.getBoxes(), nm.leTitle.text(), nm.getFerts(), nm.operations, nm.leAllocCG.text())
     return inputs
Example #5
0
class Controller(QtGui.QMainWindow):
    
    '''
    Create the starting window.
    @param model: data from the db nicely ordered.
    '''
    def __init__(self, model):
        QtGui.QMainWindow.__init__(self)
        # model, holds data.
        self.model = model
        # used to validate user inputs.
        self.validate = Validation()
        # main view.
        self.setGeometry(300, 300, 500, 380)
        self.setWindowTitle('Air Quality Model')
        # smaller search bar.  
        self.search = Search(self.model.schemas)
        # connect search bar widget to the controler. The controller connects the search bar to the Table of data.
        self.search.procDone.connect(self._widgetSearch)
        # connection to show the table search.
        self.search.procTable.connect(self._getTables)
        # menu bar.
        self.addMenuBar()


    '''
    Add menu bar to program.
    '''
    def addMenuBar(self):
        # exit program action
        exitAction = QtGui.QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)
        # create new model action.
        modelAction = QtGui.QAction('New Model', self)
        modelAction.setStatusTip('New model')
        modelAction.triggered.connect(self._newModel)
        # View a old model action.
        viewAction = QtGui.QAction('View Model', self)
        viewAction.setStatusTip('View model')
        viewAction.triggered.connect(self._viewModel)
        # add a menu bar.
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        fileMenu.addAction(modelAction)
        fileMenu.addAction(viewAction)
        
                
    '''
    Receives signals from Search object. Creates a new table from it.
    @param schema: Message from Search. Name of the schema to create data model from.
    @return: Table view that is made into the central widget.
    @QtCore.pyqtSlot(str): Slot for receiving message.   
    '''
    def _widgetSearch(self, data):
        # convert to lower case b/c all of the db is saved as lower case.
        schema = str(data[0]).lower()
        table = str(data[1]).lower()
        # create a data model from the db. summedemissions
        self.model.newModel(schema, table)       
        # Create a new table view.
        self.table = Table(self.model.model, self.model.header, self)
        # add text to top of table.
        self.table.leSchema.setText(schema)
        self.table.leTable.setText(table)
        # make table the central widget.
        self.setCentralWidget(self.table)
        # raise any errors.
        self.raise_()
    
    '''
    Used in the Search view. Once a schema has been selected,
    then allow the user to select a table to pick data from.
    @param schema: Schema in the db corresponding to a run title.
    '''  
    def _getTables(self, schema):
        tables = self.model.getTables(schema)
        self.search.addTable(tables)
        
    '''
    Set the central widget to the NewModel widget to create a new model
    scenario.
    '''    
    def _newModel(self):
        # create new model.
        self.newModel = NewModel()
        # connect the new model to the controller.
        self.newModel.procDone.connect(self._runNewModel)
        # set new model screen to main widget.
        self.setCentralWidget(self.newModel)
        # close ferts.
        self.newModel.closeAllFerts()
        # add status bar.
        self.statusBar().showMessage('Ready to Run New Model')
    
    '''
    Run a new model.
    @param inputs: Inputs from the NewModel view. 
    A dictionary with various values such as title and run codes. dict(string, list)
    '''
    def _runNewModel(self, inputs):
        self.statusBar().showMessage('Starting New Model')  
        inputs = Inputs(inputs)
        # only used for validation purposes. Are boolean.
        self.validate.title(inputs.title)
        self.validate.runCodes(inputs.run_codes)
        self.validate.fertDist(inputs.fertDist)
        self.validate.ferts(inputs.ferts)
        self.validate.pest(inputs.pestFeed)
        
        print 'Fertilizer distribution.'
        print inputs.fertDist
        print 'Allocation from cg to ws and cs.'
        print inputs.alloc
        print 'run codes.'
        print inputs.run_codes
        print 'feed stocks using fertilizers.'
        print inputs.ferts
        print 'feed stocks using pesticides.'
        print inputs.pestFeed
        print 'Operations for feed stocks'
        print inputs.operations
        
        # make sure all of the variables to run the model have been created.
        if not self.validate.errors:
            self.statusBar().showMessage('Initiating Air Model.')    
            # get db and add schema
            db = self.model.db
            db.schema = inputs.title
            # create the subprocess module that will run NONROAD in the background.
            self.qprocess = QtCore.QProcess(self)
            # send signal when subprocess has started.
            self.qprocess.started.connect(self._processStart)
            # when the subprocess is finished, it will send a signal to the controller to finish running the air model.
            self.qprocess.finished.connect(self._processSave)
            # read any new data.
            self.qprocess.readyReadStandardOutput.connect(self._processStatus) 
            # send signal if a error has occured.
            self.qprocess.error.connect(self._processError)
            # create air model.
            self.airModel = Driver(inputs.title, inputs.run_codes, db)
            #self.airModel.setupNONROAD()
            # create progress bar before running NONROAD model, to keep track of progress.
            self.timer = 0
            #create a global fertilizer to pass to the model.
            self.fertDist = inputs.fertDist
            # weather each feed stock should calculate emmisions from fertilizers.
            self.ferts = inputs.ferts
            # weather some feedstocks should calculate emmisions from pesticides.
            self.pestFeed = inputs.pestFeed
            # which operations to use for run.
            self.operations = inputs.operations
            self.alloc = inputs.alloc
            # grab the total number of files that need to be ran.
            batchFiles = self.airModel.batch.getBatchFiles()
            self.bar = QtGui.QProgressBar()
            self.bar.setRange(self.timer, batchFiles)
            self.bar.setValue(self.timer)
            self.bar.setWindowTitle("NONROAD Progress")
            self.bar.show()
            # run NONROAD.
            #self.airModel.runNONROAD(self.qprocess)
            
            self.airModel.saveData(self.ferts, self.fertDist, self.pestFeed, self.operations, self.alloc)
            
        # if not able to validate inputs. 
        else:
            self.statusBar().showMessage('ERROR: could not run model')  
            # output errors in pop up boxes.
            for error in self.validate.getErrors():
                QtGui.QMessageBox.about(self, "Validation", error)
            
    '''
    Check if qprocess has began running the NONROAD model.
    @param qprocess: QtCore.QProcess, runs subprocess. Emits signal.
    '''    
    def _processStart(self):
        self.statusBar().showMessage('Running NONROAD')
    
    '''
    Uses a progress bar to update the user on how far the NONROAD model has ran.
    Works by seeing how many files the NONROAD model has to process and making this te range for the bar.
    The subprocess reads data from the NONROAD output, and detects when it has completed a file.
    Every time this occurs a timer is updated, and the bar increase in percentage.
    '''
    def _processStatus(self):
        # get the current data from the subprocess.
        output = self.qprocess.readAllStandardOutput()
        # check to see if a file has been finished processing.
        if 'Successful completion' in output:
            self.timer += 1
            # Increase progress bar value.
            self.bar.setValue(self.timer)
        
    '''
    Save the data from the air model, once the subprocess is finished.
    Slot connecting Air model to the Controller.
    @param qprocess: QtCore.QProcess, runs subprocess. Emits signal.
    '''  
    def _processSave(self):
        self.bar.close()
        self.statusBar().showMessage('Finished Running NONROAD')
        self.airModel.saveData(self.fertDist)
        self._newModel()
    
    '''
    Tell the user if qprocess detects a error when running NONROAD.
    @param qprocess: QtCore.QProcess, runs subprocess. Emits signal.
    '''
    def _processError(self):
        self.statusBar().showMessage('ERROR: while running NONROAD')
        
    '''
    Show the search bar to look through the data.
    '''   
    def _viewModel(self):
        self.search.show()
Example #6
0
 def setUp(self):
     self.app = QApplication(sys.argv)
     self.newModel = NewModel()
Example #7
0
class TestNewModel(unittest.TestCase):

    '''Create the GUI'''
    def setUp(self):
        self.app = QApplication(sys.argv)
        self.newModel = NewModel()
    
    '''
    Test the title line edit.
    '''
    def testTitle(self):
        self.newModel.leTitle.setText('title')
        self.assertEqual(self.newModel.leTitle.text(), 'title')
        self.newModel.leTitle.setText('reallyLongWord')
        self.assertEqual(self.newModel.leTitle.text(), 'reallyLongWord')
    
    '''
    Test ability to check check boxes.
    '''
    def testCheckBox(self):
        checkBoxes = self.newModel.getBoxes()
        for box in checkBoxes:
            var = box[1]
            self.assertEqual(var.checkState(), 0)
            var.setCheckState(2)
            self.assertEqual(var.checkState(), 2)
    
    '''
    test allocate() Used to show that allocation is being made from
    corn grain to ws and cs non-harvest.
        def allocate(self):
        try: 
            csAllocation = str(1.0 - float(self.leAllocCG.text()))
            self.leAllocCS.setText(csAllocation)
        except: 
            pass
    '''
    def testAllocate(self):
        # initially the cs le should be blank.
        self.assertEqual(self.newModel.leAllocCS.text(), '')
        # enter a number into the cg le.
        self.newModel.leAllocCG.setText('.25')
        self.newModel.allocate()
        # cs should be 1 - .25 = .75
        self.assertEqual(self.newModel.leAllocCS.text(), '0.75')
        # enter a input that makes no sense.
        self.newModel.leAllocCG.setText('a')
        self.newModel.allocate()
        # cs output should remain the same as before.
        self.assertEqual(self.newModel.leAllocCS.text(), '0.75')
        # enter a negative #.
        self.newModel.leAllocCG.setText('-.25')
        self.newModel.allocate()
        # 1.25 = 1 - (-.25). This is a error that will be caught in Validate.Validate()
        self.assertEqual(self.newModel.leAllocCS.text(), '1.25')
    
    '''
    Test getInputs, which is the data sent to the Controller.
        inputs['checkBoxes'] = boxes
        inputs['title'] = title
        inputs['fertilizers'] = fertilizers
        inputs['operations'] = operations
        inputs['alloc'] = alloc
    '''
    def testGetInputs(self):  
        m = self.newModel
        cbs = m.getBoxes()
        ferts = m.getFerts()
        
        # nothing has been entered or changed yet.
        inputs = m.getInputs(m.getBoxes(), m.leTitle.text(), m.getFerts(), m.operations, m.leAllocCG.text())           
        self.assertEqual(inputs.keys(), ['operations', 'alloc', 'checkBoxes', 'fertilizers', 'title'])
        self.assertEqual(inputs['title'], '')
        self.assertEqual(inputs['fertilizers'], ferts)
        for fert in inputs['fertilizers'].values():
            for f in fert: self.assertEqual(f[1].text(), '')
        self.assertEqual(inputs['checkBoxes'], cbs)
        for cb in inputs['checkBoxes']:
            self.assertEqual(cb[1].checkState(), 0)
        self.assertEqual(inputs['operations'], {'CG': [],
                                                'CS': [],
                                                'SG': [],
                                                'WS': []})
        self.assertEqual(inputs['alloc'], '')
           
        # check all of the cb and add a title. Shill change those 2 inputs. This is the generic entry.   
        m.leTitle.setText('reallyLongWord')
        m.selectAll.setCheckState(2)
        m.showAll(m.selectAll)
        inputs = m.getInputs(m.getBoxes(), m.leTitle.text(), m.getFerts(), m.operations, m.leAllocCG.text())           
        self.assertEqual(inputs['title'], 'reallyLongWord')
        self.assertEqual(inputs['fertilizers'], ferts)
        for fert in inputs['fertilizers'].values():
            for f in fert: self.assertEqual(f[1].text(), '')
        self.assertEqual(inputs['checkBoxes'], cbs)
        for cb in inputs['checkBoxes']:
            self.assertEqual(cb[1].checkState(), 2)
        self.assertEqual(inputs['operations'], {'CG': ['F', 'H', 'N', 'P', 'T'],
                                                'CS': ['F', 'H', 'N', 'T'],
                                                'SG': ['F', 'H', 'N', 'P', 'T'],
                                                'WS': ['F', 'H', 'N', 'T']})
        self.assertEqual(inputs['alloc'], '')
        
        # unselect the check boxes. Should remove them and the operations.
        m.selectAll.setCheckState(0)
        m.showAll(m.selectAll)
        inputs = m.getInputs(m.getBoxes(), m.leTitle.text(), m.getFerts(), m.operations, m.leAllocCG.text())           
        self.assertEqual(inputs['title'], 'reallyLongWord')
        self.assertEqual(inputs['fertilizers'], ferts)
        for fert in inputs['fertilizers'].values():
            for f in fert: self.assertEqual(f[1].text(), '')
        self.assertEqual(inputs['checkBoxes'], cbs)
        for cb in inputs['checkBoxes']:
            self.assertEqual(cb[1].checkState(), 0)
        self.assertEqual(inputs['operations'], {'CG': [],
                                                'CS': [],
                                                'SG': [],
                                                'WS': []})
  
    '''
    Test the get attrbiute fucntion. Give it a few random inputs and see what it produces.
    @attention: Can make this more comprehensive later.
    '''
    def testGetAttributes(self):
        m = self.newModel
        self.assertEqual(m.getAllAtributes('leTitle')[0][1], m.leTitle)
        self.assertEqual(m.getAllAtributes('leF_sg_an')[0][1], m.leF_sg_an)
        self.assertEqual(m.getAllAtributes('leF_cg_aa')[0][1], m.leF_cg_aa)
        self.assertEqual(m.getAllAtributes('leF_ws_ur')[0][1], m.leF_ws_ur)
        self.assertEqual(len(m.getAllAtributes('lblF_sg')), 5)

    '''
    test getFerts() Make sure it contains the correct feed stocks. and 
    has 5 input fertilizers.
    '''
    def testGetFerts(self):
        feedstock = ['CG', 'CS', 'WS', 'SG']
        fertsDist = self.newModel.getFerts()
        self.assertEqual(len(fertsDist), 4)
        for feed, fert in fertsDist.items():
            self.assertEqual(feed in feedstock, True)
    
    '''
    Test closing all of the fertlizer line edits and labels.
    '''
    def testCloseAllFerts(self):
        # start up. All ferts line edits and labels should be closed.
        feeds = ['cg', 'sg', 'ws', 'cs']
        for feed in feeds:
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), False)
            lbl = self.newModel.getAllAtributes('lblF_' + feed)
            self.assertEqual(lbl[0][1].isHidden(), False)
        self.newModel.closeAllFerts()
        for feed in feeds:
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbl = self.newModel.getAllAtributes('lblF_' + feed)
            self.assertEqual(lbl[0][1].isHidden(), True)
    
    '''
    Test showFertDist(). for the 4 feed stocks that use fertilizers.
    Needs both the feed stock cb and the fert cb to be clicked to show.
    So 4 possibilities. 
    '''
    def testShowFerts(self):
        feeds = ['cg', 'sg', 'ws', 'cs'] 
        for feed in feeds:
            # ShowFertDist called. Line edits should be closed b/c no check boxes are clicked yet.
            self.newModel.showFertDist(feed, self.newModel.cbSGF, self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), True)
            
            # check both boxes to show ferts.
            self.newModel.cbSG.setCheckState(2)
            self.newModel.cbSGF.setCheckState(2)
            self.newModel.showFertDist(feed, self.newModel.cbSGF, self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), False)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), False)
            
            # unclick the 2 cb to close the ferts.
            self.newModel.cbSG.setCheckState(0)
            self.newModel.cbSGF.setCheckState(0)
            self.newModel.showFertDist(feed, self.newModel.cbSGF, self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), True)
            
            # check the cb fert, but don't check the feed cb. Closes the fert le.
            self.newModel.cbSG.setCheckState(0)
            self.newModel.cbSGF.setCheckState(2)
            self.newModel.showFertDist(feed, self.newModel.cbSGF, self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), True)
            
            # don't check the fert cb, but click the feed cb. Closes th fert le.
            self.newModel.cbSG.setCheckState(2)
            self.newModel.cbSGF.setCheckState(0)
            self.newModel.showFertDist(feed, self.newModel.cbSGF, self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), True)

    '''
    Test showAll(). The method should open or close all of the checkboxes.
    '''
    def testShowAll(self):
        checkBoxes = self.newModel.getBoxes()
        # should start off with everything open. This will close them all.
        self.newModel.selectAll.setCheckState(0)
        self.newModel.showAll(self.newModel.selectAll)
        for box in checkBoxes:
            # operation cb that are closed.
            if len(box[0]) > 4:
                self.assertEqual(box[1].isHidden(), True)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)
                
        # open all of the checkboxes.
        self.newModel.selectAll.setCheckState(2)
        self.newModel.showAll(self.newModel.selectAll)
        for box in checkBoxes:
            # operation cb that are open.
            if len(box[0]) > 4:
                self.assertEqual(box[1].isHidden(), False)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)

    '''
    Test showMore(). Runs through all of the checkboxes and decides which
    ones should be shown or closed.
    '''
    def testShowMore(self):
        feeds = ['cg', 'sg', 'ws', 'cs'] 
        checkBoxes = self.newModel.getBoxes()
        # should initially start with all of them closed, besides the feed stock cb.
        self.newModel.showMore()
        for box in checkBoxes:
            # operation cb that are closed.
            if len(box[0]) > 5:
                self.assertEqual(box[1].isHidden(), True)
            # operation cb that are closed.
            elif len(box[0]) == 5:
                self.assertEqual(box[1].isHidden(), True)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)
        
        # check all of the feed stock cb. The upper operation cb should be shown.
        [getattr(self.newModel, 'cb'+feed.upper()).setCheckState(2) for feed in feeds]
        self.newModel.showMore()
        for box in checkBoxes:
            # operation cb that are closed.
            if len(box[0]) > 5:
                self.assertEqual(box[1].isHidden(), True)
            # operation cb that are open.
            elif len(box[0]) == 5:
                self.assertEqual(box[1].isHidden(), False)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)
                
        # check all of the operation cb. Everything should be shown.
        [box[1].setCheckState(2) for box in checkBoxes if len(box[0]) == 5]
        self.newModel.showMore()
        for box in checkBoxes:
            # operation cb that are open.
            if len(box[0]) > 5:
                self.assertEqual(box[1].isHidden(), False)
            # operation cb that are open.
            elif len(box[0]) == 5:
                self.assertEqual(box[1].isHidden(), False)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)
Example #8
0
 def setUp(self):
     self.app = QApplication(sys.argv)
     self.newModel = NewModel()
Example #9
0
class TestNewModel(unittest.TestCase):
    '''Create the GUI'''
    def setUp(self):
        self.app = QApplication(sys.argv)
        self.newModel = NewModel()

    '''
    Test the title line edit.
    '''

    def testTitle(self):
        self.newModel.leTitle.setText('title')
        self.assertEqual(self.newModel.leTitle.text(), 'title')
        self.newModel.leTitle.setText('reallyLongWord')
        self.assertEqual(self.newModel.leTitle.text(), 'reallyLongWord')

    '''
    Test ability to check check boxes.
    '''

    def testCheckBox(self):
        checkBoxes = self.newModel.getBoxes()
        for box in checkBoxes:
            var = box[1]
            self.assertEqual(var.checkState(), 0)
            var.setCheckState(2)
            self.assertEqual(var.checkState(), 2)

    '''
    test allocate() Used to show that allocation is being made from
    corn grain to ws and cs non-harvest.
        def allocate(self):
        try: 
            csAllocation = str(1.0 - float(self.leAllocCG.text()))
            self.leAllocCS.setText(csAllocation)
        except: 
            pass
    '''

    def testAllocate(self):
        # initially the cs le should be blank.
        self.assertEqual(self.newModel.leAllocCS.text(), '')
        # enter a number into the cg le.
        self.newModel.leAllocCG.setText('.25')
        self.newModel.allocate()
        # cs should be 1 - .25 = .75
        self.assertEqual(self.newModel.leAllocCS.text(), '0.75')
        # enter a input that makes no sense.
        self.newModel.leAllocCG.setText('a')
        self.newModel.allocate()
        # cs output should remain the same as before.
        self.assertEqual(self.newModel.leAllocCS.text(), '0.75')
        # enter a negative #.
        self.newModel.leAllocCG.setText('-.25')
        self.newModel.allocate()
        # 1.25 = 1 - (-.25). This is a error that will be caught in Validate.Validate()
        self.assertEqual(self.newModel.leAllocCS.text(), '1.25')

    '''
    Test getInputs, which is the data sent to the Controller.
        inputs['checkBoxes'] = boxes
        inputs['title'] = title
        inputs['fertilizers'] = fertilizers
        inputs['operations'] = operations
        inputs['alloc'] = alloc
    '''

    def testGetInputs(self):
        m = self.newModel
        cbs = m.getBoxes()
        ferts = m.getFerts()

        # nothing has been entered or changed yet.
        inputs = m.getInputs(m.getBoxes(), m.leTitle.text(), m.getFerts(),
                             m.operations, m.leAllocCG.text())
        self.assertEqual(
            inputs.keys(),
            ['operations', 'alloc', 'checkBoxes', 'fertilizers', 'title'])
        self.assertEqual(inputs['title'], '')
        self.assertEqual(inputs['fertilizers'], ferts)
        for fert in inputs['fertilizers'].values():
            for f in fert:
                self.assertEqual(f[1].text(), '')
        self.assertEqual(inputs['checkBoxes'], cbs)
        for cb in inputs['checkBoxes']:
            self.assertEqual(cb[1].checkState(), 0)
        self.assertEqual(inputs['operations'], {
            'CG': [],
            'CS': [],
            'SG': [],
            'WS': []
        })
        self.assertEqual(inputs['alloc'], '')

        # check all of the cb and add a title. Shill change those 2 inputs. This is the generic entry.
        m.leTitle.setText('reallyLongWord')
        m.selectAll.setCheckState(2)
        m.showAll(m.selectAll)
        inputs = m.getInputs(m.getBoxes(), m.leTitle.text(), m.getFerts(),
                             m.operations, m.leAllocCG.text())
        self.assertEqual(inputs['title'], 'reallyLongWord')
        self.assertEqual(inputs['fertilizers'], ferts)
        for fert in inputs['fertilizers'].values():
            for f in fert:
                self.assertEqual(f[1].text(), '')
        self.assertEqual(inputs['checkBoxes'], cbs)
        for cb in inputs['checkBoxes']:
            self.assertEqual(cb[1].checkState(), 2)
        self.assertEqual(
            inputs['operations'], {
                'CG': ['F', 'H', 'N', 'P', 'T'],
                'CS': ['F', 'H', 'N', 'T'],
                'SG': ['F', 'H', 'N', 'P', 'T'],
                'WS': ['F', 'H', 'N', 'T']
            })
        self.assertEqual(inputs['alloc'], '')

        # unselect the check boxes. Should remove them and the operations.
        m.selectAll.setCheckState(0)
        m.showAll(m.selectAll)
        inputs = m.getInputs(m.getBoxes(), m.leTitle.text(), m.getFerts(),
                             m.operations, m.leAllocCG.text())
        self.assertEqual(inputs['title'], 'reallyLongWord')
        self.assertEqual(inputs['fertilizers'], ferts)
        for fert in inputs['fertilizers'].values():
            for f in fert:
                self.assertEqual(f[1].text(), '')
        self.assertEqual(inputs['checkBoxes'], cbs)
        for cb in inputs['checkBoxes']:
            self.assertEqual(cb[1].checkState(), 0)
        self.assertEqual(inputs['operations'], {
            'CG': [],
            'CS': [],
            'SG': [],
            'WS': []
        })

    '''
    Test the get attrbiute fucntion. Give it a few random inputs and see what it produces.
    @attention: Can make this more comprehensive later.
    '''

    def testGetAttributes(self):
        m = self.newModel
        self.assertEqual(m.getAllAtributes('leTitle')[0][1], m.leTitle)
        self.assertEqual(m.getAllAtributes('leF_sg_an')[0][1], m.leF_sg_an)
        self.assertEqual(m.getAllAtributes('leF_cg_aa')[0][1], m.leF_cg_aa)
        self.assertEqual(m.getAllAtributes('leF_ws_ur')[0][1], m.leF_ws_ur)
        self.assertEqual(len(m.getAllAtributes('lblF_sg')), 5)

    '''
    test getFerts() Make sure it contains the correct feed stocks. and 
    has 5 input fertilizers.
    '''

    def testGetFerts(self):
        feedstock = ['CG', 'CS', 'WS', 'SG']
        fertsDist = self.newModel.getFerts()
        self.assertEqual(len(fertsDist), 4)
        for feed, fert in fertsDist.items():
            self.assertEqual(feed in feedstock, True)

    '''
    Test closing all of the fertlizer line edits and labels.
    '''

    def testCloseAllFerts(self):
        # start up. All ferts line edits and labels should be closed.
        feeds = ['cg', 'sg', 'ws', 'cs']
        for feed in feeds:
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), False)
            lbl = self.newModel.getAllAtributes('lblF_' + feed)
            self.assertEqual(lbl[0][1].isHidden(), False)
        self.newModel.closeAllFerts()
        for feed in feeds:
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbl = self.newModel.getAllAtributes('lblF_' + feed)
            self.assertEqual(lbl[0][1].isHidden(), True)

    '''
    Test showFertDist(). for the 4 feed stocks that use fertilizers.
    Needs both the feed stock cb and the fert cb to be clicked to show.
    So 4 possibilities. 
    '''

    def testShowFerts(self):
        feeds = ['cg', 'sg', 'ws', 'cs']
        for feed in feeds:
            # ShowFertDist called. Line edits should be closed b/c no check boxes are clicked yet.
            self.newModel.showFertDist(feed, self.newModel.cbSGF,
                                       self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), True)

            # check both boxes to show ferts.
            self.newModel.cbSG.setCheckState(2)
            self.newModel.cbSGF.setCheckState(2)
            self.newModel.showFertDist(feed, self.newModel.cbSGF,
                                       self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), False)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), False)

            # unclick the 2 cb to close the ferts.
            self.newModel.cbSG.setCheckState(0)
            self.newModel.cbSGF.setCheckState(0)
            self.newModel.showFertDist(feed, self.newModel.cbSGF,
                                       self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), True)

            # check the cb fert, but don't check the feed cb. Closes the fert le.
            self.newModel.cbSG.setCheckState(0)
            self.newModel.cbSGF.setCheckState(2)
            self.newModel.showFertDist(feed, self.newModel.cbSGF,
                                       self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), True)

            # don't check the fert cb, but click the feed cb. Closes th fert le.
            self.newModel.cbSG.setCheckState(2)
            self.newModel.cbSGF.setCheckState(0)
            self.newModel.showFertDist(feed, self.newModel.cbSGF,
                                       self.newModel.cbSG)
            ferts = self.newModel.getAllAtributes('leF_' + feed)
            for fert in ferts:
                self.assertEqual(fert[1].isHidden(), True)
            lbls = self.newModel.getAllAtributes('lblF_' + feed)
            for l in lbls:
                self.assertEqual(l[1].isHidden(), True)

    '''
    Test showAll(). The method should open or close all of the checkboxes.
    '''

    def testShowAll(self):
        checkBoxes = self.newModel.getBoxes()
        # should start off with everything open. This will close them all.
        self.newModel.selectAll.setCheckState(0)
        self.newModel.showAll(self.newModel.selectAll)
        for box in checkBoxes:
            # operation cb that are closed.
            if len(box[0]) > 4:
                self.assertEqual(box[1].isHidden(), True)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)

        # open all of the checkboxes.
        self.newModel.selectAll.setCheckState(2)
        self.newModel.showAll(self.newModel.selectAll)
        for box in checkBoxes:
            # operation cb that are open.
            if len(box[0]) > 4:
                self.assertEqual(box[1].isHidden(), False)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)

    '''
    Test showMore(). Runs through all of the checkboxes and decides which
    ones should be shown or closed.
    '''

    def testShowMore(self):
        feeds = ['cg', 'sg', 'ws', 'cs']
        checkBoxes = self.newModel.getBoxes()
        # should initially start with all of them closed, besides the feed stock cb.
        self.newModel.showMore()
        for box in checkBoxes:
            # operation cb that are closed.
            if len(box[0]) > 5:
                self.assertEqual(box[1].isHidden(), True)
            # operation cb that are closed.
            elif len(box[0]) == 5:
                self.assertEqual(box[1].isHidden(), True)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)

        # check all of the feed stock cb. The upper operation cb should be shown.
        [
            getattr(self.newModel, 'cb' + feed.upper()).setCheckState(2)
            for feed in feeds
        ]
        self.newModel.showMore()
        for box in checkBoxes:
            # operation cb that are closed.
            if len(box[0]) > 5:
                self.assertEqual(box[1].isHidden(), True)
            # operation cb that are open.
            elif len(box[0]) == 5:
                self.assertEqual(box[1].isHidden(), False)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)

        # check all of the operation cb. Everything should be shown.
        [box[1].setCheckState(2) for box in checkBoxes if len(box[0]) == 5]
        self.newModel.showMore()
        for box in checkBoxes:
            # operation cb that are open.
            if len(box[0]) > 5:
                self.assertEqual(box[1].isHidden(), False)
            # operation cb that are open.
            elif len(box[0]) == 5:
                self.assertEqual(box[1].isHidden(), False)
            # feed stock cb. Always shown.
            else:
                self.assertEqual(box[1].isHidden(), False)
Example #10
0
 def createNewModel_empty_returnInputs(self):
     nm = NewModel()
     # create inputs
     inputs = nm.getInputs(nm.getBoxes(), nm.leTitle.text(), nm.getFerts(), nm.operations, nm.leAllocCG.text())
     return inputs
Example #11
0
class Controller(QtGui.QMainWindow):
    '''
    Create the starting window.
    @param model: data from the db nicely ordered.
    '''
    def __init__(self, model):
        QtGui.QMainWindow.__init__(self)
        # model, holds data.
        self.model = model
        # used to validate user inputs.
        self.validate = Validation()
        # main view.
        self.setGeometry(300, 300, 500, 380)
        self.setWindowTitle('Air Quality Model')
        # smaller search bar.
        self.search = Search(self.model.schemas)
        # connect search bar widget to the controler. The controller connects the search bar to the Table of data.
        self.search.procDone.connect(self._widgetSearch)
        # connection to show the table search.
        self.search.procTable.connect(self._getTables)
        # menu bar.
        self.addMenuBar()

    '''
    Add menu bar to program.
    '''

    def addMenuBar(self):
        # exit program action
        exitAction = QtGui.QAction('Exit', self)
        exitAction.setShortcut('Ctrl+Q')
        exitAction.setStatusTip('Exit application')
        exitAction.triggered.connect(self.close)
        # create new model action.
        modelAction = QtGui.QAction('New Model', self)
        modelAction.setStatusTip('New model')
        modelAction.triggered.connect(self._newModel)
        # View a old model action.
        viewAction = QtGui.QAction('View Model', self)
        viewAction.setStatusTip('View model')
        viewAction.triggered.connect(self._viewModel)
        # add a menu bar.
        menubar = self.menuBar()
        fileMenu = menubar.addMenu('&File')
        fileMenu.addAction(exitAction)
        fileMenu.addAction(modelAction)
        fileMenu.addAction(viewAction)

    '''
    Receives signals from Search object. Creates a new table from it.
    @param schema: Message from Search. Name of the schema to create data model from.
    @return: Table view that is made into the central widget.
    @QtCore.pyqtSlot(str): Slot for receiving message.   
    '''

    def _widgetSearch(self, data):
        # convert to lower case b/c all of the db is saved as lower case.
        schema = str(data[0]).lower()
        table = str(data[1]).lower()
        # create a data model from the db. summedemissions
        self.model.newModel(schema, table)
        # Create a new table view.
        self.table = Table(self.model.model, self.model.header, self)
        # add text to top of table.
        self.table.leSchema.setText(schema)
        self.table.leTable.setText(table)
        # make table the central widget.
        self.setCentralWidget(self.table)
        # raise any errors.
        self.raise_()

    '''
    Used in the Search view. Once a schema has been selected,
    then allow the user to select a table to pick data from.
    @param schema: Schema in the db corresponding to a run title.
    '''

    def _getTables(self, schema):
        tables = self.model.getTables(schema)
        self.search.addTable(tables)

    '''
    Set the central widget to the NewModel widget to create a new model
    scenario.
    '''

    def _newModel(self):
        # create new model.
        self.newModel = NewModel()
        # connect the new model to the controller.
        self.newModel.procDone.connect(self._runNewModel)
        # set new model screen to main widget.
        self.setCentralWidget(self.newModel)
        # close ferts.
        self.newModel.closeAllFerts()
        # add status bar.
        self.statusBar().showMessage('Ready to Run New Model')

    '''
    Run a new model.
    @param inputs: Inputs from the NewModel view. 
    A dictionary with various values such as title and run codes. dict(string, list)
    '''

    def _runNewModel(self, inputs):
        self.statusBar().showMessage('Starting New Model')
        inputs = Inputs(inputs)
        # only used for validation purposes. Are boolean.
        self.validate.title(inputs.title)
        self.validate.runCodes(inputs.run_codes)
        self.validate.fertDist(inputs.fertDist)
        self.validate.ferts(inputs.ferts)
        self.validate.pest(inputs.pestFeed)

        print 'Fertilizer distribution.'
        print inputs.fertDist
        print 'Allocation from cg to ws and cs.'
        print inputs.alloc
        print 'run codes.'
        print inputs.run_codes
        print 'feed stocks using fertilizers.'
        print inputs.ferts
        print 'feed stocks using pesticides.'
        print inputs.pestFeed
        print 'Operations for feed stocks'
        print inputs.operations

        # make sure all of the variables to run the model have been created.
        if not self.validate.errors:
            self.statusBar().showMessage('Initiating Air Model.')
            # get db and add schema
            db = self.model.db
            db.schema = inputs.title
            # create the subprocess module that will run NONROAD in the background.
            self.qprocess = QtCore.QProcess(self)
            # send signal when subprocess has started.
            self.qprocess.started.connect(self._processStart)
            # when the subprocess is finished, it will send a signal to the controller to finish running the air model.
            self.qprocess.finished.connect(self._processSave)
            # read any new data.
            self.qprocess.readyReadStandardOutput.connect(self._processStatus)
            # send signal if a error has occured.
            self.qprocess.error.connect(self._processError)
            # create air model.
            self.airModel = Driver(inputs.title, inputs.run_codes, db)
            #self.airModel.setupNONROAD()
            # create progress bar before running NONROAD model, to keep track of progress.
            self.timer = 0
            #create a global fertilizer to pass to the model.
            self.fertDist = inputs.fertDist
            # weather each feed stock should calculate emmisions from fertilizers.
            self.ferts = inputs.ferts
            # weather some feedstocks should calculate emmisions from pesticides.
            self.pestFeed = inputs.pestFeed
            # which operations to use for run.
            self.operations = inputs.operations
            self.alloc = inputs.alloc
            # grab the total number of files that need to be ran.
            batchFiles = self.airModel.batch.getBatchFiles()
            self.bar = QtGui.QProgressBar()
            self.bar.setRange(self.timer, batchFiles)
            self.bar.setValue(self.timer)
            self.bar.setWindowTitle("NONROAD Progress")
            self.bar.show()
            # run NONROAD.
            #self.airModel.runNONROAD(self.qprocess)

            self.airModel.saveData(self.ferts, self.fertDist, self.pestFeed,
                                   self.operations, self.alloc)

        # if not able to validate inputs.
        else:
            self.statusBar().showMessage('ERROR: could not run model')
            # output errors in pop up boxes.
            for error in self.validate.getErrors():
                QtGui.QMessageBox.about(self, "Validation", error)

    '''
    Check if qprocess has began running the NONROAD model.
    @param qprocess: QtCore.QProcess, runs subprocess. Emits signal.
    '''

    def _processStart(self):
        self.statusBar().showMessage('Running NONROAD')

    '''
    Uses a progress bar to update the user on how far the NONROAD model has ran.
    Works by seeing how many files the NONROAD model has to process and making this te range for the bar.
    The subprocess reads data from the NONROAD output, and detects when it has completed a file.
    Every time this occurs a timer is updated, and the bar increase in percentage.
    '''

    def _processStatus(self):
        # get the current data from the subprocess.
        output = self.qprocess.readAllStandardOutput()
        # check to see if a file has been finished processing.
        if 'Successful completion' in output:
            self.timer += 1
            # Increase progress bar value.
            self.bar.setValue(self.timer)

    '''
    Save the data from the air model, once the subprocess is finished.
    Slot connecting Air model to the Controller.
    @param qprocess: QtCore.QProcess, runs subprocess. Emits signal.
    '''

    def _processSave(self):
        self.bar.close()
        self.statusBar().showMessage('Finished Running NONROAD')
        self.airModel.saveData(self.fertDist)
        self._newModel()

    '''
    Tell the user if qprocess detects a error when running NONROAD.
    @param qprocess: QtCore.QProcess, runs subprocess. Emits signal.
    '''

    def _processError(self):
        self.statusBar().showMessage('ERROR: while running NONROAD')

    '''
    Show the search bar to look through the data.
    '''

    def _viewModel(self):
        self.search.show()
Example #12
0
 def createNewModel_empty_returnInputs(self):
     nm = NewModel()
     # create inputs
     inputs = nm.getInputs(nm.getBoxes(), nm.leTitle.text(), nm.getFerts(),
                           nm.operations, nm.leAllocCG.text())
     return inputs