def __init__(self, filepath, outname, namelist, idlist, nb="queen", factor=2): """ Initiation of modules """ f=Dbf(filepath+".dbf") #Create mapping of locations to row id self.locations = dict() i=0 for row in f: uid=unicode("".join([row[k] for k in idlist])) locnames = unicode(", ".join([row[k] for k in namelist]),"ascii","ignore") self.locations[i] = {outname:locnames,"id":uid} i+=1 self.__dict__[outname]= self.locations self.outname = outname #Get Neightbor weights by queen, rook, knn, distance if nb=="queen": self.wt = pysal.queen_from_shapefile(filepath+".shp") elif nb=="rook": self.wt = pysal.rook_from_shapefile(filepath+".shp") elif nb=="knn": self.wt = pysal.knnW_from_shapefile(filepath+".shp", k=factor) elif nb=="distance": self.wt = pysal.threshold_binaryW_from_shapefile(filepath+".shp",k) #Create dictionary of neighbors for each region self.neighbors ={} for i,j in enumerate(self.wt): self.neighbors[self.locations[i]["id"]] = {self.outname:self.locations[i][self.outname] ,"neighbors":dict([[self.locations[k]["id"],self.locations[k][self.outname]] for k in j.keys()])}
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: if pount == csaData[c]['Index']:
def test_threshold_binaryW_from_shapefile(self): w = pysal.threshold_binaryW_from_shapefile(pysal.examples.get_path( "columbus.shp"), 0.62, idVariable="POLYID") self.assertEquals(w.weights[1], [1, 1])
def run_distance(self, sfile, var): """ Invoked by main run method. """ if self.model.shapes.type == pysal.cg.Polygon: self.warn("The selected shapefile contains polygons and distance \ weights can only be computed on points. " + "The centroids of the specified polygons will be used \ instead.") elif self.model.shapes.type != pysal.cg.Point: return self.warn("The selected shapefile does not contain points \ and contiguity weights can only be computed \ on points.") if self.model.distMethod == 0: radius = None elif self.model.distMethod == 1: # 'Arc Distance (miles)' radius = pysal.cg.RADIUS_EARTH_MILES elif self.model.distMethod == 2: # 'Arc Distance (kilometers)' radius = pysal.cg.RADIUS_EARTH_KM if self.ThresholdRadio.GetValue(): try: cutoff = float(self.CutoffText.GetValue()) except: return self.warn("The cut-off point is not valid.") print "Threshold on %s, ids=%r, cutoff=%f" % (sfile, var, cutoff) W = pysal.threshold_binaryW_from_shapefile(sfile, cutoff, idVariable=var, radius=radius) W.meta = { 'shape file': sfile, 'id variable': var, 'method': 'distance', 'method options': ['Threshold', cutoff] } if radius: W.meta['Sphere Radius'] = radius self.SetW(W) elif self.KnnRadio.GetValue(): k = int(self.NumNeighSpin.GetValue()) print "Knn on %s, ids=%r, k=%d" % (sfile, var, k) W = pysal.knnW_from_shapefile(sfile, k=k, idVariable=var, radius=radius) W.meta = { 'shape file': sfile, 'id variable': var, 'method': 'distance', 'method options': ['KNN', k] } if radius: W.meta['Sphere Radius'] = radius self.SetW(W) elif self.InverseRadio.GetValue(): try: cutoff = float(self.CutoffText2.GetValue()) except: return self.warn("The cut-off point is not valid.") power = int(self.PowerSpin.GetValue()) print "Inverse on %s, ids=%r, cutoff=%f, power=%d" % \ (sfile, var, cutoff, power) try: W = pysal.threshold_continuousW_from_shapefile(sfile, cutoff, alpha=-1 * power, idVariable=var, radius=radius) W.meta = { 'shape file': sfile, 'id variable': var, 'method': 'distance', 'method options': ['Inverse', cutoff, power] } if radius: W.meta['Sphere Radius'] = radius self.SetW(W) except Exception: et, e, tb = sys.exc_info() d = wx.MessageDialog(self, "\"%s\"\n" % str(e), "Error", wx.OK | wx.ICON_ERROR) d.ShowModal()
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 generate_matrix(self): if self.dlg.txtOutput.text()=='': QtGui.QMessageBox.warning(None,"Error","Oops! Generate weight matrix. Try again...") else: filenamein=self.myfile filename = self.dlg.txtOutput.text() self.filename=filename ext=filename[-3:] """matrix""" if self.dlg.rdButtonContW.isChecked()==True: if self.dlg.rdButtonContWQ.isChecked()==True: w = pysal.queen_from_shapefile(filenamein,idVariable=None) if ext=='gal': output_file = pysal.open(filename,'w') output_file.write(w) else: output_file = pysal.open(filename,'w','arcgis_dbf') output_file.write(w, useIdIndex=True) output_file.close() if self.dlg.rdButtonContWR.isChecked()==True: w = pysal.rook_from_shapefile(filenamein,idVariable=None) if ext=='gal': output_file = pysal.open(filename,'w') output_file.write(w) else: output_file = pysal.open(filename,'w','arcgis_dbf') output_file.write(w, useIdIndex=True) output_file.close() if self.dlg.rdButtonContWB.isChecked()==True: wr = pysal.rook_from_shapefile(filenamein,idVariable=None) wq = pysal.queen_from_shapefile(filenamein,idVariable=None) wb = pysal.w_difference(wq, wr,constrained = False) if ext=='gal': output_file = pysal.open(filename,'w') output_file.write(wb) else: output_file = pysal.open(filename,'w','arcgis_dbf') output_file.write(wb, useIdIndex=True) output_file.close() if self.dlg.rdButtonDisW.isChecked()==True: w = pysal.threshold_binaryW_from_shapefile(filenamein, float(self.dlg.txtThresh.text())) if ext=='gal': output_file = pysal.open(filename,'w') output_file.write(w) else: output_file = pysal.open(filename,'w','arcgis_dbf') output_file.write(w, useIdIndex=True) output_file.close() if self.dlg.rdButtonKNW.isChecked()==True: w = pysal.knnW_from_shapefile(filenamein, k=self.dlg.spinBox.value()) if ext=='gal': output_file = pysal.open(filename,'w') output_file.write(w) else: output_file = pysal.open(filename,'w','arcgis_dbf') output_file.write(w, useIdIndex=True) output_file.close() """end matrix""" QtGui.QMessageBox.warning(None,"Complete","Weight matrix is generated")
############################## # Global Getis-Ord's G import pysal from pysal import G import numpy as np f = pysal.open(pysal.examples.get_path("stl_hom.dbf")) y = np.array(f.by_col("HR7984")) dist_w = pysal.threshold_binaryW_from_shapefile( pysal.examples.get_path('stl_hom.shp'), 0.6) dist_w.transform = "B" gg = G(y, dist_w) print gg.G print gg.EG print gg.z_norm print gg.p_norm ############################## # Local Getis-Ord's G import pysal from pysal import G_Local import numpy as np f = pysal.open(pysal.examples.get_path("stl_hom.dbf")) y = np.array(f.by_col("HR7984")) dist_w = pysal.threshold_binaryW_from_shapefile(
def run_distance(self, sfile, var): """ Invoked by main run method. """ if self.model.shapes.type == pysal.cg.Polygon: self.warn("The selected shapefile contains polygons and distance \ weights can only be computed on points. " + "The centroids of the specified polygons will be used \ instead.") elif self.model.shapes.type != pysal.cg.Point: return self.warn("The selected shapefile does not contain points \ and contiguity weights can only be computed \ on points.") if self.model.distMethod == 0: radius = None elif self.model.distMethod == 1: # 'Arc Distance (miles)' radius = pysal.cg.RADIUS_EARTH_MILES elif self.model.distMethod == 2: # 'Arc Distance (kilometers)' radius = pysal.cg.RADIUS_EARTH_KM if self.ThresholdRadio.GetValue(): try: cutoff = float(self.CutoffText.GetValue()) except: return self.warn("The cut-off point is not valid.") print "Threshold on %s, ids=%r, cutoff=%f" % (sfile, var, cutoff) W = pysal.threshold_binaryW_from_shapefile( sfile, cutoff, idVariable=var, radius=radius) W.meta = {'shape file': sfile, 'id variable': var, 'method': 'distance', 'method options': ['Threshold', cutoff]} if radius: W.meta['Sphere Radius'] = radius self.SetW(W) elif self.KnnRadio.GetValue(): k = int(self.NumNeighSpin.GetValue()) print "Knn on %s, ids=%r, k=%d" % (sfile, var, k) W = pysal.knnW_from_shapefile( sfile, k=k, idVariable=var, radius=radius) W.meta = {'shape file': sfile, 'id variable': var, 'method': 'distance', 'method options': ['KNN', k]} if radius: W.meta['Sphere Radius'] = radius self.SetW(W) elif self.InverseRadio.GetValue(): try: cutoff = float(self.CutoffText2.GetValue()) except: return self.warn("The cut-off point is not valid.") power = int(self.PowerSpin.GetValue()) print "Inverse on %s, ids=%r, cutoff=%f, power=%d" % \ (sfile, var, cutoff, power) try: W = pysal.threshold_continuousW_from_shapefile( sfile, cutoff, alpha=- 1 * power, idVariable=var, radius=radius) W.meta = {'shape file': sfile, 'id variable': var, 'method': 'distance', 'method options': ['Inverse', cutoff, power]} if radius: W.meta['Sphere Radius'] = radius self.SetW(W) except Exception: et, e, tb = sys.exc_info() d = wx.MessageDialog(self, "\"%s\"\n" % str(e), "Error", wx.OK | wx.ICON_ERROR) d.ShowModal()