예제 #1
0
 def setUp(self):
     south = load_example('South')
     db = libpysal.io.open(south.get_path("south.dbf"), 'r')
     self.y_name = "HR90"
     self.y = np.array(db.by_col(self.y_name))
     self.y.shape = (len(self.y), 1)
     self.x_names = ["RD90", "PS90", "UE90", "DV90"]
     self.x = np.array([db.by_col(var) for var in self.x_names]).T
     self.w = Queen.from_shapefile(south.get_path("south.shp"))
     self.w.transform = 'r'
예제 #2
0
def _test():
    import doctest
    start_suppress = np.get_printoptions()['suppress']
    np.set_printoptions(suppress=True)
    doctest.testmod()
    np.set_printoptions(suppress=start_suppress)


if __name__ == '__main__':
    _test()
    import numpy as np
    import libpysal
    from .sur_utils import sur_dictxy, sur_dictZ
    from libpysal.examples import load_example
    from libpysal.weights import Queen

    nat = load_example('Natregimes')
    db = libpysal.io.open(nat.get_path('natregimes.dbf'), 'r')
    y_var = ['HR80', 'HR90']
    x_var = [['PS80', 'UE80'], ['PS90', 'UE90']]
    w = Queen.from_shapefile(nat.get_path("natregimes.shp"))
    w.transform = 'r'
    bigy0, bigX0, bigyvars0, bigXvars0 = sur_dictxy(db, y_var, x_var)
    reg0 = SURerrorML(bigy0,bigX0,w,regimes=regimes,name_bigy=bigyvars0,name_bigX=bigXvars0,\
        name_w="natqueen",name_ds="natregimes",vm=True,nonspat_diag=True,spat_diag=True)

    #    reg0 = SURerrorGM(bigy0,bigX0,w,regimes=regimes,name_bigy=bigyvars0,name_bigX=bigXvars0,\
    #        name_w="natqueen",name_ds="natregimes",vm=False,nonspat_diag=True,spat_diag=False)

    print(reg0.summary)
예제 #3
0
import ols as OLS
from utils import optim_moments, RegressionPropsY, get_spFilter, spdot
# import user_output as USER
# import summary_output as SUMMARY
# import regimes as REGI

# First import libpysal to load the spatial analysis tools.
import libpysal
from libpysal.examples import load_example
from libpysal.weights import Queen

# Open data on NCOVR US County Homicides (3085 areas).
nat = load_example('Natregimes')
db = libpysal.io.open(nat.get_path('natregimes.dbf'),'r')
nat_shp = libpysal.examples.get_path("natregimes.shp")
w = Queen.from_shapefile(nat_shp)
w.transform = 'r'

name_y = ['HR70','HR80','HR90']
y = np.array([db.by_col(name) for name in name_y]).T

name_x = ['RD70','RD80','RD90','PS70','PS80','PS90']
x = np.array([db.by_col(name) for name in name_x]).T

full_weights = False


def _moments_kkp(ws, u, i, trace_w2=None):
    '''
    Compute G and g matrices for the KKP model.
    ...
예제 #4
0
    def run_stats(self):
        """Main function which do the process."""

        # Get the common fields..currentField()
        self.admin_layer = self.cbx_aggregation_layer.currentLayer()
        input_name = self.admin_layer.name()
        field = self.cbx_indicator_field.currentField()

        self.layer = QgsProject.instance().mapLayersByName(input_name)[0]
        # Output.
        self.output_file_path = self.le_output_filepath.text()

        try:
            self.button_box_ok.setDisabled(True)
            # noinspection PyArgumentList
            QApplication.setOverrideCursor(Qt.WaitCursor)
            # noinspection PyArgumentList
            QApplication.processEvents()

            if not self.admin_layer:
                raise NoLayerProvidedException

            if not self.admin_layer and self.use_point_layer:
                raise NoLayerProvidedException

            crs_admin_layer = self.admin_layer.crs()

            # Output
            if not self.output_file_path:
                temp_file = NamedTemporaryFile(delete=False,
                                               suffix='-geopublichealth.shp')
                self.output_file_path = temp_file.name
                temp_file.flush()
                temp_file.close()
            else:
                with open(self.output_file_path, 'w') as document:
                    pass

            admin_layer_provider = self.layer.dataProvider()
            fields = admin_layer_provider.fields()

            if admin_layer_provider.fields().indexFromName(
                    self.name_field) != -1:
                raise FieldExistingException(field=self.name_field)

            fields.append(QgsField('LISA_P', QVariant.Double))
            fields.append(QgsField('LISA_Z', QVariant.Double))
            fields.append(QgsField('LISA_Q', QVariant.Int))
            fields.append(QgsField('LISA_I', QVariant.Double))
            fields.append(QgsField('LISA_C', QVariant.Double))

            # The QgsVectorFileWriter was Deprecated since 3.10 However,.......
            #The create() function DOEST NOT Flush the feature unless QGIS close.
            #options = QgsVectorFileWriter.SaveVectorOptions()
            #options.driverName = "ESRI Shapefile"
            #file_writer=QgsVectorFileWriter.create(self.output_file_path,fields,QgsWkbTypes.Polygon,self.admin_layer.crs(),QgsCoordinateTransformContext(),options)

            #It's currently a bug https://github.com/qgis/QGIS/issues/35021
            # So I will keep it for now

            file_writer = QgsVectorFileWriter(self.output_file_path, 'utf-8',
                                              fields, QgsWkbTypes.Polygon,
                                              self.admin_layer.crs(),
                                              'ESRI Shapefile')

            if self.cbx_contiguity.currentIndex() == 0:  # queen
                # fix_print_with_import

                print('Info: Local Moran\'s using queen contiguity')
                #Pysal 2.0 change
                #https://github.com/pysal/pysal/blob/master/MIGRATING.md

                w = Queen.from_shapefile(self.admin_layer.source())
            else:  # 1 for rook
                # fix_print_with_import
                print('Info: Local Moran\'s using rook contiguity')
                w = Rook.from_shapefile(self.admin_layer.source())

            #Pysal 2.0
            #https://stackoverflow.com/questions/59455383/pysal-does-not-have-attribute-open
            import geopandas

            f = geopandas.read_file(self.admin_layer.source().replace(
                '.shp', '.dbf'))

            y = f[str(field)]
            lm = Moran_Local(y, w, transformation="r", permutations=999)

            sig_q = lm.q * (lm.p_sim <= 0.05
                            )  # could make significance level an option
            outFeat = QgsFeature()
            i = 0

            count = self.admin_layer.featureCount()

            for i, feature in enumerate(self.admin_layer.getFeatures()):
                attributes = feature.attributes()
                attributes.append(float(lm.p_sim[i]))
                attributes.append(float(lm.z_sim[i]))
                attributes.append(int(lm.q[i]))
                attributes.append(float(lm.Is[i]))
                attributes.append(int(sig_q[i]))

                new_feature = QgsFeature()
                new_geom = QgsGeometry(feature.geometry())
                new_feature.setAttributes(attributes)
                new_feature.setGeometry(new_geom)
                file_writer.addFeature(new_feature)

            del file_writer

            self.output_layer = QgsVectorLayer(self.output_file_path,
                                               "LISA Moran's I - " + field,
                                               'ogr')
            QgsProject.instance().addMapLayer(self.output_layer)

            self.add_symbology()

            self.signalStatus.emit(3, tr('Successful process'))

        except GeoPublicHealthException as e:
            display_message_bar(msg=e.msg, level=e.level, duration=e.duration)

        finally:
            self.button_box_ok.setDisabled(False)
            # noinspection PyArgumentList
            QApplication.restoreOverrideCursor()
            # noinspection PyArgumentList
            QApplication.processEvents()