示例#1
0
class Mineral_Params(QDialog, QTableView):
    def __init__(self,
                 Pressure=1e5,
                 Temperature=300,
                 Volume=None,
                 VolumeOff=True):
        super(Mineral_Params, self).__init__()
        self.Solidsolution = [an,ab,sp,hc,en,fs,mgts,odi,hpcen,hpcfs,di,he,cen,cats,jd,py,al,gr,mgmj,jdmj, \
                          capv,fo,fa,mgwa,fewa,mgri,feri,mgil,feil,co,mgpv,fepv,alpv,mppv,fppv,appv,mgcf,fecf, \
                          nacf,pe,wu,qtz,coes,st,an,ky,neph]
        self.row = len(self.Solidsolution)
        self.layout = QGridLayout(self)

        self.Pressure = Pressure
        self.Temperature = Temperature

        self.table = QTableView()
        self.model = QStandardItemModel(10, 10, self)
        if Volume is None:
            self.Volume = Volume
            self.model.setHorizontalHeaderLabels([
                'Name', 'formuala', 'Vp (km/s)', 'Vs (km/s)', 'Rho (kg/m³)',
                'F (KJ/mol)', 'V (cm³/mol)', 'K (GPa)', "k'", 'θ' + '(K)', 'γ',
                'q', 'G (GPa)', "G'", 'η'
            ])
        else:
            self.Volume = Volume[:-3]
            self.model.setHorizontalHeaderLabels([
                'Name', 'formuala', 'Vp (km/s)', 'Vs (km/s)', 'Rho (kg/m³)',
                'F (KJ/mol)', 'V (cm³/mol)', 'K (GPa)', "k'", 'θ' + '(K)', 'γ',
                'q', 'G (GPa)', "G'", 'η', 'Volume fraction'
            ])

        #self.model.setHorizontalHeaderLabels(['Name','formuala','Vp (km/s)','Vs (km/s)','Rho (kg/m³)','F (KJ/mol)','V (cm³/mol)','K (GPa)',"k'",'θ'+'(K)','γ','q','G (GPa)',"G'",'η','Volume fraction'])

        self.table.setModel(self.model)

        self.layout.addWidget(self.table, 0, 0, 1, 5)

        self.BTN()
        self.table_view()
        self.resize(1800, 800)
        #self.restore()

    def BTN(self):
        return 0
        self.Update = QPushButton(self)
        self.Update.setText("Update")
        self.Update.clicked.connect(self.update_data)
        self.Update.setAutoDefault(False)

        self.Restore = QPushButton(self)
        self.Restore.setText("Restore")
        self.Restore.clicked.connect(self.restore)
        self.Restore.setAutoDefault(False)

        self.Random = QPushButton(self)
        self.Random.setText("Random within error")
        self.Random.clicked.connect(self.random)
        self.Random.setAutoDefault(False)

        self.Save = QPushButton(self)
        self.Save.setText("Save")
        self.Save.clicked.connect(self.save)
        self.Save.setAutoDefault(False)

        self.Iutput = QPushButton(self)
        self.Iutput.setText("Load")
        self.Iutput.clicked.connect(self.iutput)
        self.Iutput.setAutoDefault(False)

        self.layout.addWidget(self.Update, 1, 0, 1, 1)
        self.layout.addWidget(self.Restore, 1, 1, 1, 1)
        self.layout.addWidget(self.Random, 1, 2, 1, 1)
        self.layout.addWidget(self.Save, 1, 3, 1, 1)
        self.layout.addWidget(self.Iutput, 1, 4, 1, 1)

    def save(self):
        options = QFileDialog.Options()
        fileName = QFileDialog.getSaveFileName(
            self,
            "QFileDialog.getSaveFileName()",
            "",
            "All Files (*);;Text Files (*.txt)",
            options=options)
        #except:
        #    fileName, _= QFileDialog.getSaveFileName(self,"QFileDialog.getSaveFileName()","","All Files (*);;Text Files (*.txt)", options=options)
        if PYQT == 5:
            fileName = fileName[0]
        else:
            pass
        if fileName:
            file1 = open(fileName, 'w')
            #print ('open',fileName)
            file1.write(
                'name, F_0,V_0,K_0,Kprime_0 Debye_0,grueneisen-0,q_0,G_0,Gprime_0, eta_s0 '
            )
            file1.write('\n')
            for i in self.Solidsolution:
                for j in i.parameters(self.Pressure, self.Temperature):
                    file1.write('{:8.8}'.format(j))
                    file1.write(' ')
                file1.write('\n')
            file1.close()
            #print ('save')

    def iutput(self):
        fileName = QFileDialog.getOpenFileName(self, 'Open file', '/home')
        if PYQT == 5:
            fileName = fileName[0]
        else:
            pass
        if fileName:
            file1 = open(fileName, 'r')
            next(file1)
            for i, line in enumerate(file1):
                line = line.split()
                newItem = QStandardItem(self.Solidsolution[i].name)
                self.model.setItem(i, 0, newItem)
                for col in range(len(line)):
                    try:
                        string = "{:5.2f}".format(line[col])
                    except:
                        string = line[col]
                    item = QStandardItem(string)
                    self.model.setItem(i, col, item)
            file1.close()
            #print (string)
        #print ('input')

        #self.table_view()

    def table_view(self):
        #self.row_list=[]
        for i in range(self.row):
            newItem = QStandardItem(self.Solidsolution[i].name)
            self.model.setItem(i, 0, newItem)
            params = self.Solidsolution[i].parameters(1e5, 300)
            for col in range(len(params)):
                try:
                    string = "{:5.2f}".format(params[col])
                except:
                    string = params[col]
                item = QStandardItem(string)
                self.model.setItem(i, col, item)
        if self.Volume is not None:
            for num, i in enumerate(self.Volume):
                newItem = QStandardItem(str(self.Volume[num]))
                self.model.setItem(num, 15, newItem)

    def random(self):
        for i in range(self.row):
            newItem = QStandardItem(self.Solidsolution[i].name)
            self.model.setItem(i, 0, newItem)
            params = self.Solidsolution[i].parameters_random(
                self.Pressure, self.Temperature)
            #print ('random')
            for col in range(len(params)):
                try:
                    string = "{:5.2f}".format(params[col])
                except:
                    string = params[col]
                item = QStandardItem(string)
                self.model.setItem(i, col, item)

        #self.table_view()
        #print ('random')

    def update_data(self):
        for i in range(len(self.Solidsolution)):
            params = []
            for j in range(15):
                index = self.model.index(i, j)
                params.append(self.model.itemData(index)[0])
            self.Solidsolution[i].change_parameters(params)
            a, b, c = self.Solidsolution[i].Vp_Vs(self.Pressure * 1e4,
                                                  self.Temperature)
            c *= 1000
            item = QStandardItem("{:5.2f}".format(a))
            self.model.setItem(i, 2, item)
            item = QStandardItem("{:5.2f}".format(b))
            self.model.setItem(i, 3, item)
            item = QStandardItem("{:5.2f}".format(c))
            self.model.setItem(i, 4, item)
        #print ('wf')

    def restore(self):
        try:
            address = os.path.join(os.path.dirname(__file__), 'EXPDATA',
                                   'All.txt')
            self.address = address
            file1 = open(address, 'r+')
        except:
            address = os.path.join(os.path.dirname(__file__),
                                   'Mineral_Physics', 'EXPDATA', 'All.txt')
            self.address = address
            file1 = open(address, 'r')
            next(file1)
            for i, line in enumerate(file1):
                line = line.split()
                newItem = QStandardItem(self.Solidsolution[i].name)
                self.model.setItem(i, 0, newItem)
                for col in range(len(line)):
                    try:
                        string = "{:5.2f}".format(line[col])
                    except:
                        string = line[col]
                    item = QStandardItem(string)
                    self.model.setItem(i, col, item)
            file1.close()
        self.update_data()
示例#2
0
class Regression_PLOT_PyQt(QDialog):
    """
    This calss return a PyQt GUI with a regression plot
    """
    def __init__(self, Minerals=None, string=None, flag=None):
        super(Regression_PLOT_PyQt, self).__init__()
        if string is not None:
            self.stringK, self.stringG, self.stringRho, self.user_input = string
        else:
            self.stringK = None
            self.stringG = None
            self.stringRho = None
            self.user_input = False
        self.resize(1400, 600)
        self.Minerals = Minerals

        self.dirty = False
        #self.user_input = user_input

        self.Minerals.original_flag()
        self.Minerals.read_data()
        self.table = QTableView()
        self.model = QStandardItemModel(25, 7, self)
        self.model.setHorizontalHeaderLabels([
            'flag', 'Water Content', 'Iron Content', 'K (Gpa)', 'G (Gpa)',
            'Rho (g/cm³)', 'Reference'
        ])
        for i in range(len(self.Minerals.Flag)):
            a = self.Minerals.Return_original_data(i)
            for j in range(0, 7):
                item = QStandardItem(str(a[j]))
                self.model.setItem(i, j, item)
                if j != 0:
                    item.setFlags(Qt.ItemIsEnabled)
                    item.setBackground(QColor(211, 211, 211))

        if flag is not None:
            self.Minerals.change_flag(flag)
            for i in range(len(self.Minerals.Flag)):
                item = QStandardItem(str(self.Minerals.Flag[i]))
                self.model.setItem(i, 0, item)

        self.table.setModel(self.model)

        self.button = QPushButton('Update and use in thermoelastic model')
        self.button.clicked.connect(self.Update)
        self.button.setAutoDefault(False)
        self.button1 = QPushButton('Add data file ')
        self.button1.clicked.connect(self.Export)
        self.button1.setAutoDefault(False)
        self.layout = QGridLayout()

        self.label = QLabel()
        self.label.setText('''
        Please input equation, Water: water content (wt%) and Fe: iron content (mol%)
        for example -2.41*Water-30*Fe+81,K'=4.1,  
        ''')

        self.Kinput_formula = QLineEdit()
        self.Ginput_formula = QLineEdit()
        self.Rhoinput_formula = QLineEdit()
        if self.stringK is not None:
            self.Kinput_formula.setText(self.stringK)
            self.Ginput_formula.setText(self.stringG)
            self.Rhoinput_formula.setText(self.stringRho)
            self.Userinput()
        else:
            self.Kinput_formula.setText(
                self.Minerals.Show_fit_function(self.Minerals.function_K()[0],
                                                self.Minerals.function_K()[1],
                                                "K'",
                                                error=False))
            self.Ginput_formula.setText(
                self.Minerals.Show_fit_function(self.Minerals.function_G()[0],
                                                self.Minerals.function_G()[1],
                                                "G'",
                                                error=False))
            self.Rhoinput_formula.setText(
                self.Minerals.Show_fit_function(
                    self.Minerals.function_Rho()[0],
                    self.Minerals.function_Rho()[1],
                    '',
                    error=False))
        self.Kinput_formula.returnPressed.connect(self.Kformula)
        self.Ginput_formula.returnPressed.connect(self.Gformula)
        self.Rhoinput_formula.returnPressed.connect(self.Rhoformula)
        #self.connect(self.Kinput_formula,SIGNAL("returnPressed()"),self.Kformula)
        #self.connect(self.Ginput_formula,SIGNAL("returnPressed()"),self.Gformula)
        #self.connect(self.Rhoinput_formula,SIGNAL("returnPressed()"),self.Rhoformula)

        self.user_change_confrim = QPushButton('Change to user input')
        self.user_change_confrim.clicked.connect(self.Userinput)
        self.user_change_confrim.setAutoDefault(False)

        self.extension = QWidget()
        self.extensionLayout = QGridLayout()
        self.extensionLayout.setContentsMargins(0, 0, 0, 0)

        labelK = QLabel()
        labelK.setText('K<sub>0</sub>=')
        labelG = QLabel()
        labelG.setText('G<sub>0</sub>=')
        labelRho = QLabel()
        labelRho.setText('Rho<sub>0</sub>=')

        self.extensionLayout.addWidget(labelK, 0, 0, 1, 3)
        self.extensionLayout.addWidget(labelG, 1, 0, 1, 3)
        self.extensionLayout.addWidget(labelRho, 2, 0, 1, 3)
        self.extensionLayout.addWidget(self.Kinput_formula, 0, 1, 1, 3)
        self.extensionLayout.addWidget(self.Ginput_formula, 1, 1, 1, 3)
        self.extensionLayout.addWidget(self.Rhoinput_formula, 2, 1, 1, 3)
        self.extensionLayout.addWidget(self.user_change_confrim, 3, 0, 9, 4)

        self.extension.setLayout(self.extensionLayout)

        self.check_change = QCheckBox("user input")
        self.check_change.setChecked(False)
        self.check_change.toggled.connect(self.extension.setVisible)

        #self.PLOT(switch=True)
        self.PLOT()
        self.layout.addWidget(self.table, 0, 1, 1, 17)
        self.layout.addWidget(self.button, 2, 0, 1, 9)
        self.layout.addWidget(self.button1, 2, 9, 1, 9)
        self.layout.addWidget(self.check_change, 3, 0, 1, 1)
        self.layout.addWidget(self.label, 3, 3, 1, 5)
        self.layout.addWidget(self.extension, 4, 0, 1, 9)
        self.setLayout(self.layout)

        self.extension.hide()

    def Kformula(self):
        self.stringK = str(self.Kinput_formula.text())
        self.K0 = np.array(
            re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?",
                       self.stringK))
        return self.K0, self.stringK

    def Gformula(self):
        self.stringG = str(self.Ginput_formula.text())
        self.G0 = np.array(
            re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?",
                       self.stringG))
        return self.G0, self.stringG

    def Rhoformula(self):
        self.stringRho = str(self.Rhoinput_formula.text())
        self.Rho0 = np.array(
            re.findall(r"[+-]? *(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?",
                       self.stringRho))
        return self.Rho0, self.stringRho

    def Userinput(self):
        self.Minerals.User_Change(self.Kformula(), self.Gformula(),
                                  self.Rhoformula())
        self.user_input = True
        self.PLOT()

    def PLOT(self, switch=True):
        if self.dirty == False:
            #self.Minerals.Clean_content()
            params = []
            for i in range(20):
                index = self.model.index(i, 0)
                try:
                    aa = (float(self.model.itemData(index)[0]))
                    #print (aa)
                    params.append(aa)
                except:
                    break
            #print (params)
            self.Minerals.Change_data_from_table(params)
            #print ('wf')
        else:
            self.model.setHorizontalHeaderLabels([
                'flag', 'Water Content', 'Iron Content', 'K (Gpa)', 'G (Gpa)',
                'Rho (g/cm3)', 'Reference'
            ])
            for i in range(len(self.Minerals.Flag)):
                #a=self.Minerals.Return_original_data(i)
                item = QStandardItem(str(self.Minerals.Flag[i]))
                self.model.setItem(i, 0, item)


#==============================================================================
#                 for j in range(1,7):
#                     item = QStandardItem(str(a[j]))
#                     self.model.setItem(i, j,item)
#                     if j != 0:
#                         item.setFlags(Qt.ItemIsEnabled)
#                         item.setBackground(QColor(211,211,211))
#==============================================================================

#print (self.Minerals.Change)

        if self.user_input == False:
            self.a, self.b, self.c = self.Minerals.PLOT(return_fig=False)
            #print (self.Minerals.number_of_data)
            self.Kinput_formula.setText(
                self.Minerals.Show_fit_function(self.Minerals.function_K()[0],
                                                self.Minerals.function_K()[1],
                                                "K'",
                                                error=False))
            self.Ginput_formula.setText(
                self.Minerals.Show_fit_function(self.Minerals.function_G()[0],
                                                self.Minerals.function_G()[1],
                                                "G'",
                                                error=False))
            self.Rhoinput_formula.setText(
                self.Minerals.Show_fit_function(
                    self.Minerals.function_Rho()[0],
                    self.Minerals.function_Rho()[1],
                    '',
                    error=False))

        else:
            self.a, self.b, self.c = self.Minerals.PLOT_input_formula(
                return_fig=False)

        self.canvas1 = FigureCanvas3D(self.a)
        self.canvas2 = FigureCanvas3D(self.b)
        self.canvas3 = FigureCanvas3D(self.c)
        self.canvas1.mpl_connect('pick_event', self.onpick)
        self.canvas2.mpl_connect('pick_event', self.onpick)
        self.canvas3.mpl_connect('pick_event', self.onpick)

        self.toolbar1 = NavigationToolbar(self.canvas1, self)
        self.toolbar2 = NavigationToolbar(self.canvas2, self)
        self.toolbar3 = NavigationToolbar(self.canvas3, self)

        self.layout1_widget = QWidget()
        self.layout1 = QGridLayout(self.layout1_widget)
        self.layout1_widget.setFixedSize(600, 600)
        self.layout1.addWidget(self.canvas1, 0, 1, 5, 5)
        self.layout1.addWidget(self.toolbar1, 5, 1, 1, 5)
        self.layout1.addWidget(self.canvas2, 6, 1, 5, 5)
        self.layout1.addWidget(self.toolbar2, 11, 1, 1, 5)
        self.layout1.addWidget(self.canvas3, 12, 1, 5, 5)
        self.layout1.addWidget(self.toolbar3, 17, 1, 1, 5)
        self.layout.addWidget(self.layout1_widget, 0, 0, 1, 1)

    def onpick(self, event):
        try:
            for i in range(6):
                self.model.item(self.ind,
                                i + 1).setBackground(QColor(211, 211, 211))
        except:
            pass

        count = -1
        for j in range(len((self.Minerals.Flag))):
            if self.Minerals.Flag[j] == 1:
                count += 1
                if count == event.ind[0]:
                    self.ind = j
                    break
        #print (self.ind)
        #self.ind = event.ind
        for i in range(6):
            self.model.item(self.ind,
                            i + 1).setBackground(QColor(111, 111, 111))

    def Update(self):
        self.user_input = False
        self.dirty = False
        self.check_change.setChecked(False)
        self.PLOT()

    def Export(self):
        self.dirty = True
        dialog = TextEditor(name=self.Minerals.name)
        if dialog.exec_():
            pass
        self.Minerals.read_data()
        self.PLOT()

    def ReturnString(self):
        aa = self.Minerals.Flag
        bb = str(int(aa[0]))
        for i in range(1, len(aa)):
            bb += str(int(aa[i]))
        return [self.stringK, self.stringG, self.stringRho,
                self.user_input], bb
示例#3
0
class Dialog(QDialog, Ui_nbEditor_dialog):         
    def __init__(self, iface, ml, mc):
        """Constructor for the dialog.
        
        Args:
          iface: QgsInterface instance.
        """
        
        QDialog.__init__(self, iface.mainWindow())                               
                        
        self.setupUi(self)
        
        self.ml = ml
        self.mCanvas = mc         
        self.mRubberBand = QgsRubberBand(self.mCanvas, True)
        self.mRubberBand.reset(QGis.Polygon)
        self.mRubberBand.setColor(Qt.red)
        self.mRubberBand.setWidth(2)
        self.ids = []
        
        self.ini(0)
        
        self.pushCancel.clicked.connect(self.close)
        self.pushOK.clicked.connect(self.convert)
        self.comboBox.addItems(['','Intersections','Touches','Within distance']) 
        
        self.comboBox.currentIndexChanged.connect(self.nbMethod)         
        self.ml.selectionChanged.connect(self.map2tab)
        
        
    def ini(self, n):
        self.model = QStandardItemModel(n, 1)
        self.tableView.setModel(self.model)
        self.model.setHeaderData(0, Qt.Horizontal, 'Neighbouring IDs')
        self.tableView.setSelectionMode(QAbstractItemView.SingleSelection)        
        self.selectionModel = QItemSelectionModel(self.model)
        self.tableView.setSelectionModel(self.selectionModel)
        self.tableView.horizontalHeader().setStretchLastSection(True)    
        self.tableView.selectionModel().selectionChanged.connect(self.tab2map)
        self.progressBar.setValue(0)


    def settings(self):
        self.mod = min(self.ids)
        self.p = 1
        if self.mod==1:
            self.p = 0


    def map2tab(self):
        s = ''
        idx = self.tableView.selectionModel().selectedIndexes()[0]
        ts = str(self.model.itemData(idx)[0])
        
        for fid in sorted(self.ml.selectedFeaturesIds()):
            s += '%s,' % str(int(fid)+self.p)                   
 
        s = s[:-1]
         
        if s!=ts:
            self.model.setData(idx, s)
         
        # in order to handle the symmetry
        if len(s)>len(ts):
             iLst = s.strip().replace(' ', '').split(',')
             jLst = ts.strip().replace(' ', '').split(',')
        else:
             iLst = ts.strip().replace(' ', '').split(',')
             jLst = s.strip().replace(' ', '').split(',')
              
        cent = str(idx.row()+self.p)
        dLst = list(set(iLst)-set(jLst))
          
        for d in dLst:              
            row = int(d)-self.p
            sor = str(self.model.itemData(self.model.index(row, 0))[0])
            eLst = sor.strip().replace(' ', '').split(',')            
            res = ''
            if cent in set(eLst):
                ii = eLst.index(cent)                
                del eLst[ii]
                eLst = sorted(map(int, eLst))                
                for e in eLst:
                    res += '%s,' % e
                res = res[:-1]
            else:
                u = sor + ',%s' % cent
                eLst = sorted(map(int, u.strip().replace(' ', '').split(',')))
                for e in eLst:
                    res += '%s,' % e
                res = res[:-1]                 
                               
            self.model.setData(self.model.index(row, 0, QModelIndex()), res)
                   
                
    def nbWithinDist(self):
        dlg = xdist.Dialog()
        dlg.setModal(True)
        dlg.setWindowTitle("Between two objects")
                
        if dlg.exec_() == QDialog.Accepted:
            lDist = float(dlg.lineEdit.text())
            if lDist==0:
                return

            feat = QgsFeature()
            provider = self.ml.dataProvider()
            e = provider.featureCount()

            self.settings()

            for ne in range(self.mod, e + self.mod):
                feat = QgsFeature()
                geom = QgsGeometry()
                fiter = self.ml.getFeatures(QgsFeatureRequest(ne))
                if fiter.nextFeature(feat):
                    geom = QgsGeometry(feat.geometry())

                neighbours = self.hdist(feat, lDist)
                row = feat.id()-self.mod
                self.model.setData(self.model.index(row, 0, QModelIndex()), neighbours)
                self.progressBar.setValue(100*ne/e)


    def hdist(self, feata, lDist):
        geoma = QgsGeometry(feata.geometry()) 
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        feats = provider.getFeatures()
        self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
        self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, provider.featureCount())) 
        ne = 0              
        neighbours = ""
        while feats.nextFeature(feat):
            ne += 1
            self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne)                       
            geomb = QgsGeometry(feat.geometry())            
            if feata.id()!=feat.id():
                if geoma.distance(geomb)<=lDist:
                    neighbours = neighbours + '%s,' % (feat.id()+self.p)
        return neighbours[:-1]            
    
    
    def tab2map(self):        
        QApplication.setOverrideCursor(Qt.WaitCursor)
        
        self.ml.selectionChanged.disconnect(self.map2tab)
        
        idx = self.tableView.selectionModel().selectedIndexes()[0]
        featureId = idx.row() + self.p
        
        s = self.model.itemData(idx)
        lst = s[0].strip().replace(' ', '').split(',')
        
        self.ml.removeSelection()
        
        for sid in lst:
            self.ml.select(int(sid)-self.p)
              
        provider = self.ml.dataProvider()        
        
        feat = QgsFeature()
        layer = QgsVectorLayerCache(self.ml, provider.featureCount())
        layer.featureAtId(idx.row()+self.mod, feat)
        geom = QgsGeometry(feat.geometry())   
        
        self.mRubberBand.setToGeometry(geom, self.ml)
        self.mRubberBand.show()
        
        self.ml.selectionChanged.connect(self.map2tab)
        
        QApplication.restoreOverrideCursor()        
        
        
    def closeEvent(self,event):
        QApplication.setOverrideCursor(Qt.WaitCursor)

        self.ml.selectionChanged.disconnect(self.map2tab)
        self.ml.removeSelection()
        self.mRubberBand.hide()
        self.close()

        QApplication.restoreOverrideCursor()

        
    def convert(self):
        dlg = editor.Dialog()
        dlg.setModal(True)
        dlg.setWindowTitle("Neighbour list in BUGS format")
        num = ""
        adj = ""
        sumNumNeigh = 0
        for row in range(0, self.model.rowCount()):
            ts = self.model.itemData(self.model.index(row, 0))
            lst = ts[0].strip().replace(' ', '').split(',')
            num += '%s, ' % len(lst)
            sumNumNeigh += len(lst)
            lst.reverse()
            sor = ', '.join(lst) + ','
            adj = adj + str(sor) + '\n' 
        
        num = num[:-2]
        adj = adj[:-2]
        
        nblist = 'list(\nnum = c(%s),\nadj = c(%s),\nsumNumNeigh=%s)' % (num, adj, sumNumNeigh)
        dlg.plainTextEdit.appendPlainText(nblist)
        
        dlg.exec_()                


    def nbMethod(self):
        QApplication.setOverrideCursor(Qt.WaitCursor)

        self.ml.selectionChanged.disconnect(self.map2tab)
        self.model.removeRows(0, self.model.rowCount(QModelIndex()), QModelIndex())
        n = self.ml.dataProvider().featureCount()
        self.ini(n)

        self.ids = []

        provider = self.ml.dataProvider()
        feats = provider.getFeatures()
        self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
        self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, n))
        ne = 0
        feat = QgsFeature()
        while feats.nextFeature(feat):
            ne += 1
            self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne)
            self.ids.append(feat.id())

        if self.comboBox.currentText()=="Touches":            
            if self.ml.geometryType()==0:
                return
            else:
                self.nbTouches()
        if self.comboBox.currentText()=="Intersections":
            if self.ml.geometryType()==0:
                return
            else:
                self.nbIntersects()
        if self.comboBox.currentText()=="Within distance":
            self.nbWithinDist()

        self.ml.selectionChanged.connect(self.map2tab)

        QApplication.restoreOverrideCursor()
        
            
    def nbTouches(self):                                
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        e = provider.featureCount()

        self.settings()

        for ne in range(self.mod, e + self.mod):
            feat = QgsFeature()
            geom = QgsGeometry()
            fiter = self.ml.getFeatures(QgsFeatureRequest(ne))
            if fiter.nextFeature(feat):
                geom = QgsGeometry(feat.geometry())

            neighbours = self.htouch(feat)
            row = feat.id()-self.mod    
            self.model.setData(self.model.index(row, 0, QModelIndex()), neighbours)
            self.progressBar.setValue(100*ne/e)

         
    def htouch(self, feata):
        geoma = QgsGeometry(feata.geometry()) 
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        feats = provider.getFeatures()
        self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
        self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, provider.featureCount())) 
        ne = 0              
        neighbours = ""
        while feats.nextFeature(feat):
            ne += 1
            self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne)                       
            geomb = QgsGeometry(feat.geometry())
            if feata.id()!=feat.id():
                if geoma.touches(geomb)==True:
                    neighbours = neighbours + '%s,' % (feat.id()+self.p)                
        return neighbours[:-1]

    
    def nbIntersects(self):
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        e = provider.featureCount()

        self.settings()

        for ne in range(self.mod, e + self.mod):
            feat = QgsFeature()
            geom = QgsGeometry()
            fiter = self.ml.getFeatures(QgsFeatureRequest(ne))
            if fiter.nextFeature(feat):
                geom = QgsGeometry(feat.geometry())

            neighbours = self.hintersect(feat)
            row = feat.id()-self.mod
            self.model.setData(self.model.index(row, 0, QModelIndex()), neighbours)
            self.progressBar.setValue(100*ne/e)


    def hintersect(self, feata):
        geoma = QgsGeometry(feata.geometry())  
        feat = QgsFeature()
        provider = self.ml.dataProvider()
        feats = provider.getFeatures()
        self.emit(SIGNAL("runStatus(PyQt_PyObject)"), 0)
        self.emit(SIGNAL("runRange(PyQt_PyObject)"), (0, provider.featureCount())) 
        ne = 0              
        neighbours = ""
        while feats.nextFeature(feat):
            ne += 1
            self.emit(SIGNAL("runStatus(PyQt_PyObject)"), ne)                       
            geomb = QgsGeometry(feat.geometry())
            if feata.id()!=feat.id():
                if geoma.intersects(geomb)==True:
                    neighbours = neighbours + '%s,' % (feat.id()+self.p)
        return neighbours[:-1]