def moran_inverse(file): # Read in shapefile df = file # df = gpd.read_file("C:\zoovision\data\Region1.shp") # print(df.dtypes) y = df['ind_100t'] # Calculate weight # First calculate minimum threshold distance to nearest neightbor thresh = ps.min_threshold_dist_from_shapefile( "C:\zoovision\data\Region1.shp") print(thresh) # thresh = 1.1 # weight based on fixed distance,(0 if not in threshold) w = ps.weights.DistanceBand.from_shapefile("C:\zoovision\data\Region1.shp", threshold=thresh, binary=False) # weight based on non fixed distance,(0 if not in threshold) # w = ps.weights.DistanceBand.from_shapefile("C:\zoovision\data\Region1.shp", binary=False) # transform r= standardize moran_loc = ps.Moran_Local(y, w, transformation="r", permutations=999) print(moran_loc.p_sim) fig, ax = lisa_cluster(moran_loc, df, p=0.05, figsize=(15, 10)) ax.set_title( "Local Indicators of Spatial Association ", fontsize=35) # plot_moran(moran_loc, zstandard=True, figsize=(10, 4))
def get_ols_check_spatial_correlation(central_shape,location_shp_file,year): #Get the log transform of dependent and independent variables X_log = np.log(central_shape['Call_density']) Y_log = np.log(central_shape['{}_pop_density'.format(year)]) X_log = np.array(X_log).T Y_log = np.array(Y_log) Y_log.shape = (len(Y_log),1) X_log.shape = (len(X_log),1) ###fit ols model for log transformed variable################################## ls = ols.OLS(Y_log, X_log) central_ols=ls.summary ###Distance based weight matrix############################################# thresh = pysal.min_threshold_dist_from_shapefile(location_shp_file) wt = pysal.weights.DistanceBand.from_shapefile(location_shp_file, threshold=thresh, binary=True) mi_distance = pysal.Moran(ls.u, wt, two_tailed=False) #Get Moran's I P-value using distance based weight matrix a=mi_distance.p_norm if mi_distance.p_norm<0.05: #If p_value less than 0.05 then we are going ahead with lagrange's test #To check whether to go with lag model or error model #but in this case we are going with error model lms=pysal.spreg.diagnostics_sp.LMtests(ls,wt) if lms.lme[1]<0.05: spat_err = ml_error.ML_Error(Y_log, X_log, wt) central_spat_err_distance=spat_err.summary return central_ols, a,central_spat_err_distance
def generateWeightsUsingShapefile(shapeFilePath, idVariable=None, weights=None, kind="queen", k=None, binary=False): # use weights from shapefile for purely geographic w = None if weights == None: if kind == "queen": w = pysal.queen_from_shapefile(shapeFilePath, idVariable=idVariable) if kind == "rook": w = pysal.rook_from_shapefile(shapeFilePath, idVariable=idVariable) if kind == "knn" and type(k) == int: w = pysal.knnW_from_shapefile(shapefile=shapeFilePath, k=k, idVariable=idVariable) if kind == "band": threshold = pysal.min_threshold_dist_from_shapefile( shapeFilePath, idVariable=idVariable) if binary == True: w = pysal.weights.DistanceBand.from_shapefile( shapeFilePath, threshold=threshold, binary=True, idVariable=idVariable) else: w = pysal.threshold_continuousW_from_shapefile( shapefile=shapeFilePath, threshold=threshold, idVariable=idVariable) if kind == "kernel": w = pysal.adaptive_kernelW_from_shapefile(shapeFilePath, diagonal=True, k=5, idVariable=idVariable) # else use user defined weights to create "space" instead of "place" else: if kind == "rook": w = pysal.rook_from_shapefile(shapeFilePath, idVariable=idVariable) if kind == "knn": w = pysal.knnW_from_shapefile(shapeFilePath, k=k, idVariable=idVariable) else: w = pysal.queen_from_shapefile(shapeFilePath, idVariable=idVariable) neighbors = w.neighbor_offsets w = pysal.W(neighbors, weights=weights) # row standardize the matrix. better to do it here and use it somewhere else. w.transform = 'r' if binary == True: w.transform = 'b' return w
def load_comboBox(self): """Load the fields into combobox when layers are changed""" layer_shp = [] layers = self.iface.legendInterface().layers() if len(layers) != 0: # checklayers exist in the project for layer in layers: if hasattr(layer, "dataProvider"): # to not consider Openlayers basemaps in the layer list myfilepath = layer.dataProvider().dataSourceUri() # directory including filename (myDirectory, nameFile) = os.path.split(myfilepath) # splitting into directory and filename if (".shp" in nameFile): layer_shp.append(layer) selectedLayerIndex = self.dlg.comboBox.currentIndex() if selectedLayerIndex < 0 or selectedLayerIndex > len(layer_shp): return try: selectedLayer = layer_shp[selectedLayerIndex] except: return fieldnames = [field.name() for field in selectedLayer.pendingFields()] self.clear_fields() self.dlg.comboBox_C.addItems(fieldnames) self.dlg.comboBox_C_2.addItems(fieldnames) (path, layer_id) = selectedLayer.dataProvider().dataSourceUri().split('|') inDriver = ogr.GetDriverByName("ESRI Shapefile") inDataSource = inDriver.Open(path, 0) inLayer = inDataSource.GetLayer() global type type = inLayer.GetLayerDefn().GetGeomType() if type == 3: # is a polygon self.dlg.checkBox_queen.setChecked(True) self.dlg.lineEditThreshold.setEnabled(False) self.dlg.checkBox_knn.setEnabled(False) self.dlg.knn_number.setEnabled(False) self.dlg.checkBox_optimizeDistance.setChecked(False) self.dlg.checkBox_optimizeDistance.setEnabled(False) self.dlg.lineEdit_minT.setEnabled(False) self.dlg.lineEdit_maxT.setEnabled(False) self.dlg.lineEdit_dist.setEnabled(False) else: self.dlg.checkBox_queen.setChecked(False) self.dlg.checkBox_knn.setEnabled(True) self.dlg.knn_number.setEnabled(True) self.dlg.lineEditThreshold.setEnabled(True) self.dlg.checkBox_optimizeDistance.setEnabled(True) self.dlg.lineEdit_minT.setEnabled(True) self.dlg.lineEdit_dist.setEnabled(True) self.dlg.lineEdit_maxT.setEnabled(True) thresh = pysal.min_threshold_dist_from_shapefile(path) self.dlg.lineEditThreshold.setText(str(int(thresh)))
def load_comboBox(self,layers): """Load the fields into combobox when layers are changed""" selectedLayerIndex = self.dlg.comboBox.currentIndex() selectedLayer = layers[selectedLayerIndex] fieldnames = [] fieldnames = [field.name() for field in selectedLayer.pendingFields()] self.clear_fields() self.dlg.comboBox_C.addItems(fieldnames) (path,layer_id)=selectedLayer.dataProvider().dataSourceUri().split('|') thresh = pysal.min_threshold_dist_from_shapefile(path) self.dlg.lineEditThreshold.setText(str(int(thresh)))
def load_comboBox(self, layers): """Load the fields into combobox when layers are changed""" selectedLayerIndex = self.dlg.comboBox.currentIndex() selectedLayer = layers[selectedLayerIndex] fieldnames = [] fieldnames = [field.name() for field in selectedLayer.pendingFields()] self.clear_fields() self.dlg.comboBox_C.addItems(fieldnames) (path, layer_id) = selectedLayer.dataProvider().dataSourceUri().split('|') thresh = pysal.min_threshold_dist_from_shapefile(path) self.dlg.lineEditThreshold.setText(str(int(thresh)))
def test_threshold(self): md = pysal.min_threshold_dist_from_shapefile(self.polyShp) self.assertEqual(md, 0.61886415807685413) wid = pysal.threshold_continuousW_from_array(self.points, 11.2) self.assertEqual(wid.weights[0], [0.10000000000000001, 0.089442719099991588]) wid2 = pysal.threshold_continuousW_from_array( self.points, 11.2, alpha=-2.0) self.assertEqual(wid2.weights[0], [0.01, 0.0079999999999999984]) w = pysal.threshold_continuousW_from_shapefile( self.polyShp, 0.62, idVariable="POLYID") self.assertEqual(w.weights[1], [1.6702346893743334, 1.7250729841938093])
def test_threshold(self): md = pysal.min_threshold_dist_from_shapefile(self.polyShp) self.assertEqual(md, 0.61886415807685413) wid = pysal.threshold_continuousW_from_array(self.points, 11.2) self.assertEqual(wid.weights[0], [0.10000000000000001, 0.089442719099991588]) wid2 = pysal.threshold_continuousW_from_array( self.points, 11.2, alpha=-2.0) self.assertEqual(wid2.weights[0], [0.01, 0.0079999999999999984]) w = pysal.threshold_continuousW_from_shapefile( self.polyShp, 0.62, idVariable="POLYID") self.assertEqual(w.weights[1], [1.6702346893743334, 1.7250729841938093])
def changeCurrentIndex(self): self.dlg.groupBox_wm.setEnabled(False) self.dlg.groupBox_mi.setEnabled(False) self.dlg.widget_sm.setEnabled(False) self.dlg.widget_dw.setEnabled(False) self.dlg.widget_knn.setEnabled(False) self.dlg.buttonGroup_calculate.setExclusive(False) self.dlg.rdButton_nm.setChecked(False) self.dlg.rdButton_sm.setChecked(False) self.dlg.buttonGroup_calculate.setExclusive(True) self.dlg.checkBox.setChecked(0) self.dlg.txtOutput.clear() self.dlg.txtSelect.clear() self.dlg.txtMoranI.clear() self.dlg.txtMoranIp.clear() self.dlg.txtMoranIint.clear() """self.dlg.txtSelectSystemC.setPlainText("")""" try: self.selectedLayer = self.cmbBoxSelectLayer.currentLayer() myfilepath=os.path.realpath(self.selectedLayer.dataProvider().dataSourceUri()) self.myfile=myfilepath[:-10] """self.dlg.txtOutput_2.setText(self.myfile)""" self.thresh = pysal.min_threshold_dist_from_shapefile(self.myfile) array = get_points_array_from_shapefile(self.myfile) dist = scipy.spatial.distance.cdist(array,array) self.maxthresh=np.amax(dist) self.dlg.txtThresh.setText(str(round(self.thresh,5))) self.fields = self.selectedLayer.pendingFields() self.fieldnames=[] self.fieldsnumeric=[] for field in self.fields: if field.typeName()=='Real' or field.typeName()=='Integer': self.fieldnames.append(field.name()) self.fieldsnumeric.append(field) self.dlg.cmbBoxSelectField.clear() self.dlg.cmbBoxSelectField.addItems(self.fieldnames) except: QtGui.QMessageBox.warning(None,"Error","There is not layers or it is change. Try again...") self.dlg.cmbBoxSelectField.clear() self.dlg.cmbBoxSelectField.addItems(self.fieldnames)
def run(self): """Run method that performs all the real work""" self.dlg.groupBox_wm.setEnabled(False) self.dlg.groupBox_mi.setEnabled(False) self.dlg.widget_sm.setEnabled(False) self.dlg.widget_dw.setEnabled(False) self.dlg.widget_knn.setEnabled(False) """rev""" try: self.selectedLayer = self.cmbBoxSelectLayer.currentLayer() myfilepath=os.path.realpath(self.selectedLayer.dataProvider().dataSourceUri()) self.myfile=myfilepath[:-10] """self.dlg.txtOutput_2.setText(self.myfile)""" self.thresh = pysal.min_threshold_dist_from_shapefile(self.myfile) array = get_points_array_from_shapefile(self.myfile) dist = scipy.spatial.distance.cdist(array,array) self.maxthresh=np.amax(dist) self.dlg.txtThresh.setText(str(round(self.thresh,5))) self.fields = self.selectedLayer.pendingFields() self.fieldnames=[] self.fieldsnumeric=[] for field in self.fields: if field.typeName()=='Real' or field.typeName()=='Integer': self.fieldnames.append(field.name()) self.fieldsnumeric.append(field) self.dlg.cmbBoxSelectField.clear() self.dlg.cmbBoxSelectField.addItems(self.fieldnames) except: QtGui.QMessageBox.warning(None,"Error","There is not layers. Try again...") pass """rev""" # show the dialog self.dlg.show() # Run the dialog event loop result = self.dlg.exec_() # See if OK was pressed if result: # Do something useful here - delete the line containing pass and # substitute with your code. pass
def test_threshold(self): md = pysal.min_threshold_dist_from_shapefile(self.polyShp) self.assertEqual(md, 0.61886415807685413) wid = pysal.threshold_continuousW_from_array(self.points, 11.2) wds = {wid.neighbors[0][i]: v for i, v in enumerate(wid.weights[0])} self.assertEqual(wds, {1: 0.10000000000000001, 3: 0.089442719099991588}) wid2 = pysal.threshold_continuousW_from_array( self.points, 11.2, alpha=-2.0) wds = {wid2.neighbors[0][i]: v for i, v in enumerate(wid2.weights[0])} self.assertEqual(wds, {1: 0.01, 3: 0.0079999999999999984}) w = pysal.threshold_continuousW_from_shapefile( self.polyShp, 0.62, idVariable="POLYID") wds = {w.neighbors[1][i]: v for i, v in enumerate(w.weights[1])} self.assertEqual(wds, {2: 1.6702346893743334, 3: 1.7250729841938093})
def load_comboBox(self, layers): """Load the fields into combobox when layers are changed""" selectedLayerIndex = self.dlg.comboBox.currentIndex() if selectedLayerIndex < 0 or selectedLayerIndex > len(layers): return try: selectedLayer = layers[selectedLayerIndex] except: return fieldnames = [field.name() for field in selectedLayer.pendingFields()] self.clear_fields() self.dlg.comboBox_C.addItems(fieldnames) (path, layer_id) = selectedLayer.dataProvider().dataSourceUri().split('|') inDriver = ogr.GetDriverByName("ESRI Shapefile") inDataSource = inDriver.Open(path, 0) inLayer = inDataSource.GetLayer() global type type = inLayer.GetLayerDefn().GetGeomType() if type == 3: # is a polygon self.dlg.checkBox_queen.setChecked(True) self.dlg.lineEditThreshold.setEnabled(False) self.dlg.checkBox_optimizeDistance.setChecked(False) self.dlg.checkBox_optimizeDistance.setEnabled(False) self.dlg.lineEdit_minT.setEnabled(False) self.dlg.lineEdit_maxT.setEnabled(False) self.dlg.lineEdit_dist.setEnabled(False) else: self.dlg.checkBox_queen.setChecked(False) self.dlg.lineEditThreshold.setEnabled(True) self.dlg.checkBox_optimizeDistance.setEnabled(True) self.dlg.lineEdit_minT.setEnabled(True) self.dlg.lineEdit_dist.setEnabled(True) self.dlg.lineEdit_maxT.setEnabled(True) thresh = pysal.min_threshold_dist_from_shapefile(path) self.dlg.lineEditThreshold.setText(str(int(thresh)))
def test_threshold(self): md = pysal.min_threshold_dist_from_shapefile(self.polyShp) self.assertEqual(md, 0.61886415807685413) wid = pysal.threshold_continuousW_from_array(self.points, 11.2) wds = {wid.neighbors[0][i]: v for i, v in enumerate(wid.weights[0])} self.assertEqual(wds, { 1: 0.10000000000000001, 3: 0.089442719099991588 }) wid2 = pysal.threshold_continuousW_from_array(self.points, 11.2, alpha=-2.0) wds = {wid2.neighbors[0][i]: v for i, v in enumerate(wid2.weights[0])} self.assertEqual(wds, {1: 0.01, 3: 0.0079999999999999984}) w = pysal.threshold_continuousW_from_shapefile(self.polyShp, 0.62, idVariable="POLYID") wds = {w.neighbors[1][i]: v for i, v in enumerate(w.weights[1])} self.assertEqual(wds, {2: 1.6702346893743334, 3: 1.7250729841938093})
def load_comboBox(self, layers): """Load the fields into combobox when layers are changed""" selectedLayerIndex = self.dlg.comboBox.currentIndex() if selectedLayerIndex < 0 or selectedLayerIndex > len(layers): return try: selectedLayer = layers[selectedLayerIndex] except: return fieldnames = [field.name() for field in selectedLayer.pendingFields()] self.clear_fields() self.dlg.comboBox_C.addItems(fieldnames) (path, layer_id) = selectedLayer.dataProvider().dataSourceUri().split('|') inDriver = ogr.GetDriverByName("ESRI Shapefile") inDataSource = inDriver.Open(path, 0) inLayer = inDataSource.GetLayer() global type type = inLayer.GetLayerDefn().GetGeomType() if type == 3: # is a polygon self.dlg.checkBox_queen.setChecked(True) self.dlg.lineEditThreshold.setEnabled(False) self.dlg.checkBox_optimizeDistance.setChecked(False) self.dlg.checkBox_optimizeDistance.setEnabled(False) self.dlg.lineEdit_minT.setEnabled(False) self.dlg.lineEdit_maxT.setEnabled(False) self.dlg.lineEdit_dist.setEnabled(False) else: self.dlg.checkBox_queen.setChecked(False) self.dlg.lineEditThreshold.setEnabled(True) self.dlg.checkBox_optimizeDistance.setEnabled(True) self.dlg.lineEdit_minT.setEnabled(True) self.dlg.lineEdit_dist.setEnabled(True) self.dlg.lineEdit_maxT.setEnabled(True) thresh = pysal.min_threshold_dist_from_shapefile(path) self.dlg.lineEditThreshold.setText(str(int(thresh)))
def __init__(self, filename, name=None): super(Morans, self).__init__() self.filename = filename self.shapefile = filename + '.shp' self.dbf = filename + '.dbf' if name: self.name = name else: self.name = os.path.splitext(ntpath.basename(self.filename))[0] self.results = {} # Calculate the faster properties on init self._threshold = pysal.min_threshold_dist_from_shapefile( self.shapefile) self._points_array = pysal.weights.util.get_points_array_from_shapefile( self.shapefile) self._data = pysal.open(self.dbf) self._columns = self._data.by_col
def __init__(self, filename, name=None): super(Morans, self).__init__() self.filename = filename self.shapefile = filename + '.shp' self.dbf = filename + '.dbf' if name: self.name = name else: self.name = os.path.splitext(ntpath.basename(self.filename))[0] self.results = {} # Calculate the faster properties on init self._threshold = pysal.min_threshold_dist_from_shapefile( self.shapefile) self._points_array = pysal.weights.util.get_points_array_from_shapefile( self.shapefile) self._data = pysal.open(self.dbf) self._columns = self._data.by_col
if __name__ == "__main__": # Directory where embedding files are stored dir_shp_read="D:/Dial_codes/call_pop_density_shapefile/" dir_shp_write="D:/Dial_codes/" #filenames which are required year="2016" shp_pcd_year="malawi_pcd_TA_{}".format(year) shp_central_pcd_year="central_malawi_{}_new".format(year) central_shp = dir_shp_write + shp_central_pcd_year +'.shp' #configuration thresh = pysal.min_threshold_dist_from_shapefile(central_shp) #Read and write the inputs malawi_pcd=read_shape_data_file(dir_shp_read,shp_pcd_year) malawi_pcd.columns=['District', 'TA', 'Zone', 'Sum (ppp)', '{}_pop'.format(year), 'Call_density','Total_TA_area', 'geometry'] malawi_pcd['{}_pop_density'.format(year)]=malawi_pcd['{}_pop'.format(year)]/malawi_pcd['Total_TA_area'] malawi_pcd['Call_density']=malawi_pcd['Call_density']/malawi_pcd['Total_TA_area'] malawi_pcd_central=malawi_pcd[malawi_pcd['Zone']=='Central'] write_shape_data_file(dir_shp_write,shp_central_pcd_year,malawi_pcd_central) central_ols_results,p_value,spatial_error_model=get_ols_check_spatial_correlation(malawi_pcd_central,central_shp,year) random_kfold_coef=random_Kfold_results(malawi_pcd_central,year) randm_spkfold_coef=spatial_kfold(malawi_pcd_central,year,thresh)
def load_comboBox(self): """Load the fields into combobox when layers are changed""" layer_shp = [] layers = self.iface.legendInterface().layers() if len(layers) != 0: # checklayers exist in the project for layer in layers: if hasattr( layer, "dataProvider" ): # to not consider Openlayers basemaps in the layer list myfilepath = layer.dataProvider().dataSourceUri( ) # directory including filename (myDirectory, nameFile) = os.path.split( myfilepath) # splitting into directory and filename if (".shp" in nameFile): layer_shp.append(layer) selectedLayerIndex = self.dlg.comboBox.currentIndex() if selectedLayerIndex < 0 or selectedLayerIndex > len(layer_shp): return try: selectedLayer = layer_shp[selectedLayerIndex] except: return fieldnames = [field.name() for field in selectedLayer.pendingFields()] self.clear_fields() self.dlg.comboBox_C.addItems(fieldnames) self.dlg.comboBox_C_2.addItems(fieldnames) (path, layer_id) = selectedLayer.dataProvider().dataSourceUri().split('|') inDriver = ogr.GetDriverByName("ESRI Shapefile") inDataSource = inDriver.Open(path, 0) inLayer = inDataSource.GetLayer() global type type = inLayer.GetLayerDefn().GetGeomType() if type == 3: # is a polygon self.dlg.checkBox_queen.setChecked(True) self.dlg.lineEditThreshold.setEnabled(False) self.dlg.checkBox_knn.setEnabled(False) self.dlg.knn_number.setEnabled(False) self.dlg.checkBox_optimizeDistance.setChecked(False) self.dlg.checkBox_optimizeDistance.setEnabled(False) self.dlg.lineEdit_minT.setEnabled(False) self.dlg.lineEdit_maxT.setEnabled(False) self.dlg.lineEdit_dist.setEnabled(False) else: self.dlg.checkBox_queen.setChecked(False) self.dlg.checkBox_knn.setEnabled(True) self.dlg.knn_number.setEnabled(True) self.dlg.lineEditThreshold.setEnabled(True) self.dlg.checkBox_optimizeDistance.setEnabled(True) self.dlg.lineEdit_minT.setEnabled(True) self.dlg.lineEdit_dist.setEnabled(True) self.dlg.lineEdit_maxT.setEnabled(True) thresh = pysal.min_threshold_dist_from_shapefile(path) self.dlg.lineEditThreshold.setText(str(int(thresh)))
if count == fieldIndexDict['a15fee']: arecord['a15fee'] = float(item) realvalues.append(float(item)) arecord['Index'] = bigcount bigcount += 1 if count <= len(rec): count += 1 csaData[arecord['UFN']] = arecord pprint(realvalues) y = np.array(realvalues) thresh = pysal.min_threshold_dist_from_shapefile(ashploc) dist_w = pysal.threshold_binaryW_from_shapefile(ashploc, thresh) dist_w.transform = "B" lg = getisord.G_Local(y, dist_w) pprint(lg.p_sim) psimresults = lg.p_sim.tolist() pount = 0 frecords = [] for p in psimresults: for c in csaData:
def moran_gen(file): # Read in shapefile df = file # df = gpd.read_file(file) # print(df.dtypes) y = df['ind_100t'] # Calculate weight # First calculate minimum threshold distance to nearest neightbor thresh = ps.min_threshold_dist_from_shapefile( "C:\zoovision\data\Region1.shp") # thresh = 1 # print(thresh) # weight based on fixed distance, for binary(0 or 1 if within threshold) # arcgis_swm = ps.open('C:\zoovision\data\weightfiles\week1test.swm', 'r') # w = arcgis_swm.read() # arcgis_swm.close() # e = open('C:\zoovision\data\Region1_count.txt') # x = e.readlines() # print(x.head()) # gwt = ps.open('C:\zoovision\weights.gwt', 'r') # w = gwt.read() # gwt.close() # w = ps.open('C:\zoovision\data\Region1_count.txt', 'r', 'Region1_count').read() testfile = ps.open('C:\zoovision\data\Region1_count.txt', 'r', 'arcgis_text') testfile = ps.open('C:\zoovision\data\Region1_count.txt', 'r', 'arcgis_text') w = testfile.read() testfile.close() # testfile = ps.open('C:\zoovision\data\weightfiles\Region1_genweights.swm', 'r') # w = testfile.read() testfile.close() w.n # f = tempfile.NamedTemporaryFile(suffix='.txt') # fname = f.name # f.close() # o = ps.open(fname, 'w', 'Region1_count') # o.write(w) # o.close() # wnew = ps.open(fname, 'r', 'Region1_count').read() # wnew.pct_nonzero == w.pct_nonzero # os.remove(fname) # arcgis_txt.close() # w = ps.queen_from_shapefile("C:\zoovision\data\Region1.shp") # w = ps.weights.DistanceBand.from_shapefile("C:\zoovision\data\Region1.shp", threshold=thresh, binary=False) # print(tuple(w1)) # f = ps.open(ps.examples.get_path("stl_hom.txt")) # y = np.array(f.by_col['HR8893']) # w = ps.open(ps.examples.get_path("stl.gal")).read() # np.random.seed(12345) # moran_loc = ps.Moran_Local(y, w) # print(tuple(w)) # w2 = ps.lat2W(6, 4) # w = ps.w_union(w1, w2) # w = w1.multiply(w2) moran_loc = Moran_Local(y, w, transformation='r', permutations=999) # moran_loc = ps.Moran_Local(y, w, permutations=999) fig, ax = plt.subplots(figsize=(15, 10)) fig, ax = lisa_cluster(moran_loc, df, p=0.05, figsize=(15, 10)) ax.set_title( "Local Indicators of Spatial Association ", fontsize=35) # plot_moran(moran_loc, zstandard=True, figsize=(10, 4))
def test_min_threshold_dist_from_shapefile(self): f = pysal.examples.get_path('columbus.shp') min_d = pysal.min_threshold_dist_from_shapefile(f) self.assertAlmostEquals(min_d, 0.61886415807685413)
if count == fieldIndexDict['a15fee']: arecord['a15fee'] = float(item) realvalues.append(float(item)) arecord['Index'] = bigcount bigcount += 1 if count <= len(rec): count += 1 csaData[arecord['UFN']] = arecord pprint(realvalues) y = np.array(realvalues) thresh = pysal.min_threshold_dist_from_shapefile(ashploc) dist_w = pysal.threshold_binaryW_from_shapefile(ashploc, thresh) dist_w.transform = "B" lg = getisord.G_Local(y,dist_w) pprint(lg.p_sim) psimresults = lg.p_sim.tolist() pount = 0 frecords = [] for p in psimresults:
def load_comboBox(self): """Load the fields into combobox when layers are changed""" layer_shp = [] layers = [layer for layer in QgsProject.instance().mapLayers().values()] if len(layers) != 0: # checklayers exist in the project for layer in layers: if hasattr(layer, "dataProvider"): myfilepath = layer.dataProvider().dataSourceUri() (myDirectory, nameFile) = os.path.split(myfilepath) if (".shp" in nameFile): layer_shp.append(layer) selectedLayerIndex = self.dlg.layerListCombo.currentIndex() if selectedLayerIndex < 0 or selectedLayerIndex > len(layer_shp): return try: selectedLayer = layer_shp[selectedLayerIndex] except: return self.clear_fields() strname = [] catename = [] #only Float or Integer field types will be shown in combobox for field in selectedLayer.fields(): ftype = str(field.type()) if ftype == '2' or ftype == '4' or ftype == '6': strname.append(field.name()) else: catename.append(field.name()) self.dlg.comboBox.addItems(strname) self.dlg.cBox2.addItems(catename) (path, layer_id) = selectedLayer.dataProvider().dataSourceUri().split('|') inDriver = ogr.GetDriverByName("ESRI Shapefile") inDataSource = inDriver.Open(path, 0) inLayer = inDataSource.GetLayer() global type global thresh type = inLayer.GetLayerDefn().GetGeomType() if type == 3: # is a polygon thresh = pysal.min_threshold_dist_from_shapefile(path) if float(thresh) < 1: #convert decimal degree to meters thresh = round(thresh * 84244.43662,0) else: thresh = round(thresh,0) self.suggest_sweep(str(path).strip(), self.dlg.comboBox.currentText()) selectedFieldIndex = self.dlg.comboBox.currentIndex() if selectedFieldIndex < 0: return try: self.dlg.comboBox.activated.connect(lambda: self.suggest_sweep(str(path).strip(), str(self.dlg.comboBox.currentText()).strip())) #self.dlg.comboBox.currentIndexChanged.connect(lambda: self.suggest_sweep(str(path).strip(), str(self.dlg.comboBox.currentText()).strip())) except: return else: QMessageBox.warning(self.dlg.show(), self.tr("aChor:Warning"), self.tr("This is not a polygon shapefile. Please reselect from layer list"), QMessageBox.Ok)
if __name__ == "__main__": # Directory where embedding files are stored dir_shp_read = "D:/Dial_codes/call_pop_density_shapefile/" dir_shp_write = "D:/Dial_codes/" #filenames which are required year = "2016" shp_pcd_year = "malawi_pcd_TA_{}".format(year) shp_north_pcd_year = "north_malawi_{}_new".format(year) north_shp = dir_shp_write + shp_north_pcd_year + '.shp' #configuration thresh = pysal.min_threshold_dist_from_shapefile(north_shp) #Read and write the inputs malawi_pcd = read_shape_data_file(dir_shp_read, shp_pcd_year) malawi_pcd.columns = [ 'District', 'TA', 'Zone', 'Sum (ppp)', '{}_pop'.format(year), 'Call_density', 'Total_TA_area', 'geometry' ] malawi_pcd['{}_pop_density'.format(year)] = malawi_pcd['{}_pop'.format( year)] / malawi_pcd['Total_TA_area'] malawi_pcd['Call_density'] = malawi_pcd['Call_density'] / malawi_pcd[ 'Total_TA_area'] malawi_pcd_north = malawi_pcd[malawi_pcd['Zone'] == 'North'] write_shape_data_file(dir_shp_write, shp_north_pcd_year, malawi_pcd_north) north_ols_results, p_value = get_ols_check_spatial_correlation(