-
Notifications
You must be signed in to change notification settings - Fork 3
/
space_time_cube.py
1286 lines (1041 loc) · 64.4 KB
/
space_time_cube.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
"""
/***************************************************************************
SpaceTimeCube
A QGIS plugin
This plugin creates a space-time cube based on given data.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2021-04-26
git sha : $Format:%H$
copyright : (C) 2021 by Murat Çalışkan, Berk Anbaroğlu
email : [email protected], [email protected]
***************************************************************************/
/***************************************************************************
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
***************************************************************************/
"""
from qgis.PyQt.QtCore import QSettings, QTranslator, QCoreApplication, QDateTime
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QFileDialog, QMessageBox
from qgis.utils import iface
# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .space_time_cube_dialog import SpaceTimeCubeDialog
from qgis.core import Qgis, QgsProject
import os.path
from osgeo import ogr, gdal, osr
import numpy as np
from datetime import datetime, timedelta
from collections import Counter, defaultdict
from itertools import product
import math
import pandas as pd
try:
from matplotlib.backends.backend_qt5agg import FigureCanvasQTAgg as FigureCanvas
import matplotlib.pyplot as plt
mdlChck_plt = 1
except:
mdlChck_plt = 0
class SpaceTimeCube:
"""QGIS Plugin Implementation."""
def __init__(self, iface):
"""Constructor.
:param iface: An interface instance that will be passed to this class
which provides the hook by which you can manipulate the QGIS
application at run time.
:type iface: QgsInterface
"""
# Save reference to the QGIS interface
self.iface = iface
# initialize plugin directory
self.plugin_dir = os.path.dirname(__file__)
# initialize locale
locale = QSettings().value('locale/userLocale')[0:2]
locale_path = os.path.join(
self.plugin_dir,
'i18n',
'SpaceTimeCube_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Space Time Cube')
# Check if plugin was started the first time in current QGIS session
# Must be set in initGui() to survive plugin reloads
self.first_start = None
# noinspection PyMethodMayBeStatic
def tr(self, message):
"""Get the translation for a string using Qt translation API.
We implement this ourselves since we do not inherit QObject.
:param message: String for translation.
:type message: str, QString
:returns: Translated version of message.
:rtype: QString
"""
# noinspection PyTypeChecker,PyArgumentList,PyCallByClass
return QCoreApplication.translate('SpaceTimeCube', message)
def add_action(
self,
icon_path,
text,
callback,
enabled_flag=True,
add_to_menu=True,
add_to_toolbar=True,
status_tip=None,
whats_this=None,
parent=None):
"""Add a toolbar icon to the toolbar.
:param icon_path: Path to the icon for this action. Can be a resource
path (e.g. ':/plugins/foo/bar.png') or a normal file system path.
:type icon_path: str
:param text: Text that should be shown in menu items for this action.
:type text: str
:param callback: Function to be called when the action is triggered.
:type callback: function
:param enabled_flag: A flag indicating if the action should be enabled
by default. Defaults to True.
:type enabled_flag: bool
:param add_to_menu: Flag indicating whether the action should also
be added to the menu. Defaults to True.
:type add_to_menu: bool
:param add_to_toolbar: Flag indicating whether the action should also
be added to the toolbar. Defaults to True.
:type add_to_toolbar: bool
:param status_tip: Optional text to show in a popup when mouse pointer
hovers over the action.
:type status_tip: str
:param parent: Parent widget for the new action. Defaults None.
:type parent: QWidget
:param whats_this: Optional text to show in the status bar when the
mouse pointer hovers over the action.
:returns: The action that was created. Note that the action is also
added to self.actions list.
:rtype: QAction
"""
icon = QIcon(icon_path)
action = QAction(icon, text, parent)
action.triggered.connect(callback)
action.setEnabled(enabled_flag)
if status_tip is not None:
action.setStatusTip(status_tip)
if whats_this is not None:
action.setWhatsThis(whats_this)
if add_to_toolbar:
# Adds plugin icon to Plugins toolbar
self.iface.addToolBarIcon(action)
if add_to_menu:
self.iface.addPluginToMenu(
self.menu,
action)
self.actions.append(action)
return action
def initGui(self):
"""Create the menu entries and toolbar icons inside the QGIS GUI."""
icon_path = ':/plugins/space_time_cube/icon.png'
self.add_action(
icon_path,
text=self.tr(u'Space Time Cube'),
callback=self.run,
parent=self.iface.mainWindow())
# will be set False in run()
self.first_start = True
def unload(self):
"""Removes the plugin menu item and icon from QGIS GUI."""
for action in self.actions:
self.iface.removePluginMenu(
self.tr(u'&Space Time Cube'),
action)
self.iface.removeToolBarIcon(action)
def setExtent(self):
self.ext = self.dlg.cb_extent_list.currentText()
if self.ext == "Canvas Extent":
self.e = iface.mapCanvas().extent()
else:
self.layer = QgsProject.instance().mapLayersByName(self.ext)[0]
self.e = self.layer.extent()
self.xmax = self.e.xMaximum()
self.ymax = self.e.yMaximum()
self.xmin = self.e.xMinimum()
self.ymin = self.e.yMinimum()
self.dlg.spn_xmax.setValue(self.xmax)
self.dlg.spn_ymax.setValue(self.ymax)
self.dlg.spn_xmin.setValue(self.xmin)
self.dlg.spn_ymin.setValue(self.ymin)
def createRandomPoints(self):
self.number = int(self.dlg.spn_pointCount.value())
self.wmin = int(self.dlg.spn_wmin.value())
self.wmax = int(self.dlg.spn_wmax.value())
self.dtmin = self.dlg.dt_startTime.dateTime().toPyDateTime()
self.dtmax = self.dlg.dt_endTime.dateTime().toPyDateTime()
self.delta = int((self.dtmax - self.dtmin).total_seconds())
self.rnd_seconds = np.random.rand(self.number) * (self.delta - 0)
self.dates = [self.dtmin + timedelta(seconds=i) for i in self.rnd_seconds]
if self.wmax < self.wmin:
self.msgBox = QMessageBox()
self.msgBox.setIcon(QMessageBox.Information)
self.msgBox.setText("Maximum value of weight must be higher than minimum value!")
self.msgBox.setStandardButtons(QMessageBox.Ok)
self.returnValue = self.msgBox.exec()
return
self.out_shp = self.dlg.ln_output4.text()
self.projectCrs = QgsProject.instance().crs()
self.driver = ogr.GetDriverByName('Esri Shapefile')
self.ds = self.driver.CreateDataSource(self.out_shp)
self.srs = osr.SpatialReference()
self.srs.ImportFromWkt(self.projectCrs.toWkt())
self.layer = self.ds.CreateLayer("random_point", self.srs, ogr.wkbPoint)
self.layer.CreateField(ogr.FieldDefn("weight", ogr.OFTReal))
self.layer.CreateField(ogr.FieldDefn("X", ogr.OFTReal))
self.layer.CreateField(ogr.FieldDefn("Y", ogr.OFTReal))
self.dateField = ogr.FieldDefn("date", ogr.OFTString)
self.dateField.SetWidth(24)
self.layer.CreateField(self.dateField)
self.xmax = self.dlg.spn_xmax.value()
self.ymax = self.dlg.spn_ymax.value()
self.xmin = self.dlg.spn_xmin.value()
self.ymin = self.dlg.spn_ymin.value()
self.long = np.random.rand(self.number) * (self.xmax - self.xmin) + self.xmin
self.lat = np.random.rand(self.number) * (self.ymax - self.ymin) + self.ymin
self.weights = np.random.rand(self.number) * (self.wmax - self.wmin) + self.wmin
self.defn = self.layer.GetLayerDefn()
for e,(x,y,w,t) in enumerate(zip(self.long, self.lat, self.weights, self.dates)):
self.feat = ogr.Feature(self.defn)
self.feat.SetField('id', e)
self.feat.SetField('X', x)
self.feat.SetField('Y', y)
self.feat.SetField('weight', w)
self.feat.SetField("date", t.strftime("%Y-%m-%d %H:%M:%S"))
# Geometry
self.geom = ogr.Geometry(ogr.wkbPoint)
self.geom.AddPoint(x, y)
self.feat.SetGeometry(self.geom)
self.layer.CreateFeature(self.feat)
self.feat = None
self.ds = self.layer = self.defn = self.feat = None
iface.addVectorLayer(self.out_shp, "", "ogr")
def selectOutput(self):
self.sender = self.dlg.sender()
self.oname = self.sender.objectName()
if self.oname == "btn_browse":
self.dlg.ln_output.setText("")
self.OutputDir = QFileDialog.getExistingDirectory(None, 'Select Directory', "", QFileDialog.ShowDirsOnly)
self.dlg.ln_output.setText(self.OutputDir)
elif self.oname == "btn_browse2":
self.dlg.ln_output2.setText("")
self.csvPath, self._filter = QFileDialog.getOpenFileName(self.dlg, "Select Points File","", 'CSV(*.csv *.CSV)')
self.dlg.ln_output2.setText(self.csvPath)
elif self.oname == "btn_browse3":
self.dlg.ln_output3.setText("")
self.csvPath, self._filter = QFileDialog.getOpenFileName(self.dlg, "Select Points File","", 'CSV(*.csv *.CSV)')
self.dlg.ln_output3.setText(self.csvPath)
self.points = np.genfromtxt(self.csvPath, delimiter=',', skip_header=1, usecols=(4,5,6), dtype=np.int, encoding='utf-8')
self.xcat = self.dlg.cb_x_cat_2.currentText()
self.ycat = self.dlg.cb_y_cat_2.currentText()
self.ycats = self.points[(self.points[:,0]==self.xcat) & (self.points[:,1]==self.ycat)][:,6]
elif self.oname == "btn_browse4":
self.dlg.ln_output4.setText("")
self.shpPath, self._filter = QFileDialog.getSaveFileName(self.dlg, "Select Random Points file", "", '*.shp')
self.dlg.ln_output4.setText(self.shpPath)
def getLayers(self):
self.vector_layers = [layer.name() for layer in QgsProject.instance().mapLayers().values() if (layer.type() == 0 and layer.wkbType() in (1,4))]
self.dlg.cb_input.clear()
self.dlg.cb_extent_list.clear()
self.dlg.cb_input.addItems(self.vector_layers)
self.dlg.cb_extent_list.addItem("Canvas Extent")
self.dlg.cb_extent_list.addItems(self.vector_layers)
def fillFields(self):
self.sender = self.dlg.sender()
self.oname = self.sender.objectName()
self.dlg.cb_datetime.clear()
self.dlg.cb_timestamp.clear()
self.dlg.cb_string.clear()
self.dlg.cb_weight.clear()
self.selectedLayer = QgsProject.instance().mapLayersByName(self.dlg.cb_input.currentText())[0]
self.weight_fields = [field.name() for field in self.selectedLayer.fields()]
if self.weight_fields:
self.dlg.cb_weight.addItems(["None"] + self.weight_fields)
if self.dlg.rdo_from_date.isChecked():
self.fields = [field.name() for field in self.selectedLayer.fields() if field.typeName().lower() in ("datetime", "date")]
if self.fields:
self.dlg.cb_datetime.addItems(self.fields)
else:
self.dlg.cb_datetime.addItem("No Available Field!")
elif self.dlg.rdo_from_timestamp.isChecked():
self.fields = [field.name() for field in self.selectedLayer.fields() if (field.typeName().lower() in ("real", "date")) or (field.typeName().lower().startswith("int"))]
if self.fields:
self.dlg.cb_timestamp.addItems(self.fields)
else:
self.dlg.cb_timestamp.addItem("No Available Field!")
else:
self.fields = [field.name() for field in self.selectedLayer.fields() if field.typeName().lower() in ("string", "varchar")]
if self.fields:
self.dlg.cb_string.addItems(self.fields)
else:
self.dlg.cb_string.addItem("No Available Field!")
def change_time_field(self):
self.sending_button = self.dlg.sender()
self.oname = self.sending_button.objectName()
self.status = self.sending_button.isChecked()
self.selectedLayer = QgsProject.instance().mapLayersByName(self.dlg.cb_input.currentText())[0]
if self.oname == "rdo_from_date":
self.fields = [field.name() for field in self.selectedLayer.fields() if field.typeName().lower() in ("datetime", "date")]
if self.fields:
self.dlg.cb_datetime.addItems(self.fields)
self.dlg.cb_datetime.setEnabled(True)
else:
self.dlg.cb_datetime.addItem("No Available Field!")
self.dlg.cb_datetime.setEnabled(False)
if not self.status:
self.dlg.cb_datetime.clear()
self.dlg.cb_datetime.setEnabled(self.status)
elif self.oname == "rdo_from_timestamp":
self.fields = [field.name() for field in self.selectedLayer.fields() if (field.typeName().lower() in ("real")) or (field.typeName().lower().startswith("int"))]
if self.fields:
self.dlg.cb_timestamp.addItems(self.fields)
self.dlg.cb_timestamp.setEnabled(True)
self.dlg.cb_timestamp_type.setEnabled(True)
else:
self.dlg.cb_timestamp.addItem("No Available Field!")
self.dlg.cb_timestamp.setEnabled(False)
self.dlg.cb_timestamp_type.setEnabled(False)
if not self.status:
self.dlg.cb_timestamp.clear()
self.dlg.cb_timestamp.setEnabled(self.status)
self.dlg.cb_timestamp_type.setEnabled(self.status)
elif self.oname == "rdo_from_string":
self.formats = ["Datetime Pattern",
"%Y/%m/%d %H:%M:%S.%f",
"%Y/%m/%d %H:%M:%S",
"%Y/%m/%d %H:%M",
"%Y/%m/%d %H",
"%Y/%m/%d",
"%Y/%m",
"%Y",
"%Y-%m-%d %H:%M:%S.%f",
"%Y-%m-%d %H:%M:%S",
"%Y-%m-%d %H:%M",
"%Y-%m-%d %H",
"%Y-%m-%d",
"%Y-%m",
"%d/%m/%Y %H:%M:%S.%f",
"%d/%m/%Y %H:%M:%S",
"%d/%m/%Y %H:%M",
"%d/%m/%Y %H",
"%d/%m/%Y",
"%d-%m-%Y %H:%M:%S.%f",
"%d-%m-%Y %H:%M:%S",
"%d-%m-%Y %H:%M",
"%d-%m-%Y %H",
"%d-%m-%Y"
]
self.fields = [field.name() for field in self.selectedLayer.fields() if field.typeName().lower() in ("string", "varchar")]
if self.fields:
self.dlg.cb_string.addItems(self.fields)
self.dlg.cb_format.addItems(self.formats)
self.dlg.cb_string.setEnabled(True)
self.dlg.cb_format.setEnabled(True)
else:
self.dlg.cb_string.addItem("No Available Field!")
self.dlg.cb_string.setEnabled(False)
self.dlg.cb_format.setEnabled(False)
if not self.status:
self.dlg.cb_string.clear()
self.dlg.cb_format.clear()
self.dlg.cb_string.setEnabled(self.status)
self.dlg.cb_format.setEnabled(self.status)
def getNeighbors(self, points, x_cat, y_cat, t_cat, report=False):
if (np.array([x_cat, y_cat, t_cat]) < 1).any():
return None
self.x_cat_max, self.y_cat_max, self.t_cat_max = points[:,[4,5,6]].max(axis=0)
if (x_cat > self.x_cat_max) or (y_cat > self.y_cat_max) or (t_cat > self.t_cat_max):
return None
self.neighbors = []
self.weights = []
self.relative_coors = defaultdict()
self.relative_coors_w = defaultdict()
for i in [-1,0,1]:
for j in [-1,0,1]:
for k in [-1,0,1]:
if (i != 0) or (j != 0) or (k != 0):
if ((np.array([y_cat+j, x_cat+i, t_cat+k]) > 0).all()) and (np.array([x_cat+i <= self.x_cat_max, y_cat+j <= self.y_cat_max, t_cat+k <= self.t_cat_max]).all()):
self.nb = np.array((points[:,4] == x_cat+i) & (points[:,5] == y_cat+j) & (points[:,6] == t_cat+k)).sum()
if self.dlg.rdo_median.isChecked():
self.r = points[(points[:,4] == x_cat+i) & (points[:,5] == y_cat+j) & (points[:,6] == t_cat+k)][:,3]
self.w = np.median(self.r) if self.r.shape[0]>0 else 0
elif self.dlg.rdo_mean.isChecked():
self.r = points[(points[:,4] == x_cat+i) & (points[:,5] == y_cat+j) & (points[:,6] == t_cat+k)][:,3]
self.w = np.mean(self.r) if self.r.shape[0]>0 else 0
else:
self.w = np.sum(points[(points[:,4] == x_cat+i) & (points[:,5] == y_cat+j) & (points[:,6] == t_cat+k)][:,3])
self.neighbors.append(self.nb)
self.weights.append(self.w)
self.relative_coors[(i,j,k)] = self.nb
self.relative_coors_w[(i,j,k)] = self.w
self.relative_coors = sorted(self.relative_coors.items(), key=lambda x:x[0][-1])
self.relative_coors_w = sorted(self.relative_coors_w.items(), key=lambda x:x[0][-1])
return self.neighbors, self.relative_coors, self.weights, self.relative_coors_w
def getDatetime(self, t):
self.ref_time=datetime.min
self.time_passed = timedelta(seconds=t)
self.dt = self.ref_time + self.time_passed
return self.dt
def getValueCount(self, points, sumWeight = False):
if not sumWeight:
self.cnt=Counter()
for i in points[:,[4,5,6]]:
self.cnt.update([tuple(i)])
return self.cnt
else:
self.sumW = defaultdict(float)
for row in points[:,[3,4,5,6]]:
self.w = row[0]
self.i = row[1:]
self.sumW[tuple(self.i)] += self.w
return self.sumW
def getGetisOrd(self, points, x_cat, y_cat, t_cat, val_count, w_val_count):
self.x_cat_max, self.y_cat_max, self.t_cat_max = points[:,[4,5,6]].max(axis=0)
self.neighbors, self.relative_coors, self.weights, self.relative_coors_w = self.getNeighbors(points, x_cat, y_cat, t_cat)
self.n = self.x_cat_max * self.y_cat_max * self.t_cat_max # total number of cells
if self.dlg.cb_weight.currentText() == "None":
self.x_ = points.shape[0] / self.n
self.numerator = sum(self.neighbors) - self.x_ * len(self.neighbors)
self.sum_x2 = sum([i**2 for i in val_count.values()])
self.s = math.sqrt((self.sum_x2/self.n) - self.x_**2)
self.denom1 = self.n * len(self.neighbors)
self.denom2 = len(self.neighbors) ** 2
self.denom = (self.denom1 - self.denom2) / (self.n - 1)
self.denominator = math.sqrt(self.denom) * self.s
else:
self.x_ = points[:,3].sum() / self.n
self.numerator = sum(self.weights) - self.x_ * len(self.weights)
self.sum_x2 = sum([i**2 for i in self.w_val_count.values()])
self.s = math.sqrt((self.sum_x2/self.n) - self.x_**2)
self.denom1 = self.n * len(self.weights)
self.denom2 = len(self.weights) ** 2
self.denom = (self.denom1 - self.denom2) / (self.n - 1)
self.denominator = math.sqrt(self.denom) * self.s
return self.numerator/self.denominator
def changeArray(self, arr, x, y, t):
self.arr[:,3][(self.arr[:,0]==x) & (self.arr[:,1]==y) & (self.arr[:,2]==t)] = self.val_count.get((x,y,t), 0)
self.arr[:,4][(self.arr[:,0]==x) & (self.arr[:,1]==y) & (self.arr[:,2]==t)] = self.w_val_count.get((x,y,t), 0)
return
def localMoransI(self, points, x_cat, y_cat, t_cat, arr, n):
self.x_cat_max, self.y_cat_max, self.t_cat_max = self.points[:,[4,5,6]].max(axis=0).astype(np.int)
self.neighbors, self.relative_coors, self.weights, self.relative_coors_w = self.getNeighbors(points, x_cat, y_cat, t_cat)
self.arr_not_i = arr[~((arr[:,0]==x_cat) & (arr[:,1]==y_cat) & (arr[:,2]==t_cat))]
if self.dlg.cb_weight.currentText() == "None":
self.x_ = self.arr[:,3].mean()
self.s2_numerator = ((self.arr_not_i[:,3] - self.x_)**2).sum()
self.s2 = self.s2_numerator/(n-1)
self.xi = arr[((arr[:,0]==x_cat) & (arr[:,1]==y_cat) & (arr[:,2]==t_cat))][:,3].item()
self.I1 = (self.xi - self.x_) / self.s2
self.I2 = (np.array(self.neighbors) - self.x_).sum()
self.I = self.I1 * self.I2
self.ei = len(self.neighbors) / (n - 1) # E[I]
# E[I2^2
self.b2i_numerator = ((self.arr_not_i[:,3] - self.x_)**4).sum()
self.b2i_denominator = (((self.arr_not_i[:,3] - self.x_)**2).sum())**2
self.b2i = self.b2i_numerator / self.b2i_denominator
self.B_numerator = (2 * self.b2i - n) * len(self.neighbors)**2 # becaeuse w=1 and wik * wih = 1
self.B = self.B_numerator / ((n - 1) * (n - 2))
self.A_numerator = (self.n - self.b2i) * (len(self.neighbors)) # because w=1 and w**2 = 1
self.A = self.A_numerator / (n - 1)
self.ei2 = self.A - self.B
self.vi = self.ei2 - self.ei**2
self.zi = (self.I - self.ei) / math.sqrt(self.vi)
else:
self.x_ = arr[:,4].mean()
self.s2_numerator = ((self.arr_not_i[:,4] - self.x_)**2).sum()
self.s2 = self.s2_numerator/(n - 1)
self.xi = arr[((arr[:,0]==x_cat) & (arr[:,1]==y_cat) & (arr[:,2]==t_cat))][:,4].item()
self.I1 = (self.xi - self.x_) / self.s2
self.I2 = (np.array(self.weights) - self.x_).sum()
self.I = self.I1 * self.I2
self.ei = len(self.weights) / (n - 1) # E[I]
# E[I2]
self.b2i_numerator = ((self.arr_not_i[:,4] - self.x_)**4).sum()
self.b2i_denominator = (((self.arr_not_i[:,4] - self.x_)**2).sum())**2
self.b2i = self.b2i_numerator / self.b2i_denominator
self.B_numerator = (2 * self.b2i - self.n) * len(self.weights)**2 # becaeuse w=1 and wik * wih = 1
self.B = self.B_numerator / ((n - 1) * (n - 2))
self.A_numerator = (n - self.b2i) * (len(self.weights)) # because w=1 and w**2 = 1
self.A = self.A_numerator / (n - 1)
self.ei2 = self.A - self.B
self.vi = self.ei2 - self.ei**2
self.zi = (self.I - self.ei) / math.sqrt(self.vi)
return self.zi
def array2raster(self, newRasterSource, geotransform, srs, array):
self.cols = array.shape[1]
self.rows = array.shape[0]
self.driver = gdal.GetDriverByName('GTiff')
self.outRaster = self.driver.Create(newRasterSource, self.cols, self.rows, 1, gdal.GDT_Float32)
self.outRaster.SetGeoTransform(geotransform)
self.outband = self.outRaster.GetRasterBand(1)
self.outband.WriteArray(array)
self.outRaster.SetProjection(srs.toWkt())
self.outband.FlushCache()
del self.outRaster, self.outband
def createShp(self, gridx, gridy, out_folder, sr):
self.out_shp = os.path.join(out_folder, "grid.shp")
self.grid = []
for i in range(1,len(gridx)):
self.minx = gridx[i-1]
self.maxx = gridx[i]
for j in range(1,len(gridy)):
self.miny = gridy[j-1]
self.maxy = gridy[j]
self.geom = f"POLYGON(({self.minx} {self.maxy}, {self.maxx} {self.maxy}, {self.maxx} {self.miny}, {self.minx} {self.miny}, {self.minx} {self.maxy}))"
self.grid.append([i, j, ogr.CreateGeometryFromWkt(self.geom)])
self.driver = ogr.GetDriverByName('Esri Shapefile')
self.ds = self.driver.CreateDataSource(self.out_shp)
self.srs = osr.SpatialReference()
self.srs.ImportFromWkt(sr.toWkt())
self.layer = self.ds.CreateLayer('grid', self.srs, ogr.wkbPolygon)
self.layer.CreateField(ogr.FieldDefn('id', ogr.OFTInteger))
self.layer.CreateField(ogr.FieldDefn('x_cat', ogr.OFTInteger))
self.layer.CreateField(ogr.FieldDefn('y_cat', ogr.OFTInteger))
self.defn = self.layer.GetLayerDefn()
for e, (i,j,g) in enumerate(self.grid):
self.feat = ogr.Feature(self.defn)
self.feat.SetField('id', e)
self.feat.SetField('x_cat', i)
self.feat.SetField('y_cat', j)
# Geometry
self.feat.SetGeometry(g)
self.layer.CreateFeature(self.feat)
self.ds = self.layer = self.defn = self.feat = None
iface.addVectorLayer(self.out_shp, "", "ogr")
def getGrid(self):
self.xcat, self.ycat, self.tcat = [], [], []
self.selectedLayer = QgsProject.instance().mapLayersByName("grid")
self.sending_button = self.dlg.sender()
if self.sending_button.currentIndex() == 1:
self.dlg.cb_x_cat.clear()
self.dlg.cb_y_cat.clear()
if self.selectedLayer:
self.fields = [field.name() for field in self.selectedLayer[0].fields()]
if ("x_cat" in self.fields) and ("y_cat" in self.fields):
for feat in self.selectedLayer[0].getFeatures():
if feat["x_cat"] not in self.xcat:
self.xcat.append(feat["x_cat"])
self.dlg.cb_x_cat.addItem(str(feat["x_cat"]))
if feat["y_cat"] not in self.ycat:
self.ycat.append(feat["y_cat"])
self.dlg.cb_y_cat.addItem(str(feat["y_cat"]))
else:
pass
elif self.sending_button.currentIndex() == 2:
self.dlg.cb_x_cat_2.clear()
self.dlg.cb_y_cat_2.clear()
self.dlg.cb_t_cat.clear()
if self.selectedLayer:
self.fields = [field.name() for field in self.selectedLayer[0].fields()]
if ("x_cat" in self.fields) and ("y_cat" in self.fields):
for feat in self.selectedLayer[0].getFeatures():
if feat["x_cat"] not in self.xcat:
self.xcat.append(feat["x_cat"])
self.dlg.cb_x_cat_2.addItem(str(feat["x_cat"]))
if feat["y_cat"] not in self.ycat:
self.ycat.append(feat["y_cat"])
self.dlg.cb_y_cat_2.addItem(str(feat["y_cat"]))
else:
pass
def fillTCat(self):
try:
self.csvPath = self.dlg.ln_output3.text()
self.points = np.genfromtxt(self.csvPath, delimiter=',', skip_header=1, usecols=(4,5,6), dtype=np.int, encoding='utf-8')
except:
return
self.dlg.cb_t_cat.clear()
self.xcat = int(self.dlg.cb_x_cat_2.currentText())
self.ycat = int(self.dlg.cb_y_cat_2.currentText())
self.tcats = self.points[(self.points[:,0] == self.xcat) & (self.points[:,1] == self.ycat)][:,2]
self.tcats = np.unique(self.tcats).astype(str)
self.dlg.cb_t_cat.addItems(self.tcats)
def getSelectedFeature(self):
self.sender = self.dlg.sender()
self.oname = self.sender.objectName()
self.layer = QgsProject.instance().mapLayersByName("grid")
if self.oname == "btn_from_grid":
if self.layer:
self.selectedFeature = self.layer[0].selectedFeatures()
if self.selectedFeature:
self.x_cat = self.selectedFeature[0].attribute("x_cat")
self.y_cat = self.selectedFeature[0].attribute("y_cat")
self.dlg.cb_x_cat.setCurrentText(str(self.x_cat))
self.dlg.cb_y_cat.setCurrentText(str(self.y_cat))
if self.oname == "btn_from_grid_2":
self.dlg.cb_t_cat.clear()
if self.layer:
self.selectedFeature = self.layer[0].selectedFeatures()
if self.selectedFeature:
self.x_cat = self.selectedFeature[0].attribute("x_cat")
self.y_cat = self.selectedFeature[0].attribute("y_cat")
self.dlg.cb_x_cat_2.setCurrentText(str(self.x_cat))
self.dlg.cb_y_cat_2.setCurrentText(str(self.y_cat))
try:
self.csvPath = self.dlg.ln_output3.text()
self.points = np.genfromtxt(self.csvPath, delimiter=',', skip_header=1, usecols=(4,5,6), dtype=np.int, encoding='utf-8')
self.tcats = self.points[(self.points[:,0] == self.x_cat) & (self.points[:,1] == self.y_cat)][:,2]
self.tcats = np.unique(self.tcats).astype(str)
self.dlg.cb_t_cat.addItems(self.tcats)
except:
pass
def points2csv(self, points, out_folder):
self.out_csv = os.path.join(out_folder, "points.csv")
np.savetxt(self.out_csv, points, delimiter=',',
header='x_coor, y_coor, t_coor, weight, x_cat, y_cat, t_cat, count, weighted_count, date',
fmt=('%.18e, %.18e, %.18e, %.18e, %d, %d, %d, %d, %.18e, %s'),
comments='')
def grid2csv(self, grids, out_folder):
self.stat = "getis_ord" if self.dlg.rdo_getis.isChecked() else "local_morans_I"
self.name = "grids_getis_ord.csv" if self.dlg.rdo_getis.isChecked() else "grids_local_morans_I.csv"
self.out_csv = os.path.join(out_folder, self.name)
np.savetxt(self.out_csv, grids, delimiter=',',
header='x_cat, y_cat, t_cat, count, weighted_count, {}'.format(self.stat),
fmt=('%d, %d, %d, %d, %.18e, %.18e'),
comments='')
def plot(self):
self.sender = self.dlg.sender()
self.oname = self.sender.objectName()
if mdlChck_plt == 0:
self.msgBox = QMessageBox()
self.msgBox.setIcon(QMessageBox.Information)
self.msgBox.setText("matplotlib couldn't be impported successfully! Please check the GitHub page to learn how to install manually.!")
self.msgBox.setStandardButtons(QMessageBox.Ok)
self.returnValue = self.msgBox.exec()
return
if self.oname == "btn_plot":
try:
self.csv_file = self.dlg.ln_output2.text()
self.points = np.genfromtxt(self.csv_file, delimiter=',', skip_header=1, usecols=(3,4,5,6), dtype=np.float, encoding='utf-8')
self.dates = np.genfromtxt(self.csv_file, delimiter=',', skip_header=1, usecols=(9), dtype=np.datetime64, encoding='utf-8')
self.xcat = int(self.dlg.cb_x_cat.currentText())
self.ycat = int(self.dlg.cb_y_cat.currentText())
self.filtered_points = self.points[(self.points[:,1] == self.xcat) & (self.points[:,2] == self.ycat)]
if not self.dlg.rdo_weight.isChecked():
self.counts = np.array(np.unique(self.filtered_points[:,3], return_counts=True)).T
else:
self.unique_groups = np.unique(self.filtered_points[:,3])
self.sums = []
for group in self.unique_groups:
self.s = self.filtered_points[(self.filtered_points[:,3] == group)][:,0].sum()
self.sums.append([group, self.s])
self.counts = np.array(self.sums)
# self.title = str(self.dates.min()) + "-" + str(self.dates.max())
self.title = str(self.dates.min()) + (45 - len(str(self.dates.max())) - len(str(self.dates.min()))) * " " + str(self.dates.max())
if self.counts.shape[0] != 0:
self.figure.clear()
self.ax = self.figure.add_subplot(111)
self.ax.plot(self.counts[:,0], self.counts[:,1])
self.ax.scatter(self.counts[:,0], self.counts[:,1])
self.ax.grid(True)
self.ax.set_title(self.title, loc="left")
self.ax.set_xlabel("Time")
self.ylabel = "Weighted Number of Points" if self.dlg.rdo_weight.isChecked() else "Number of Points"
self.ax.set_ylabel(self.ylabel)
self.figure.tight_layout()
self.canvas.draw()
else:
self.figure.clear()
self.ax = self.figure.add_subplot(111)
self.ax.grid(True)
self.ax.set_title(self.title, loc="left")
self.ax.set_xlabel("Time")
self.ylabel = "Weighted Number of Points" if self.dlg.rdo_weight.isChecked() else "Number of Points"
self.ax.set_ylabel(self.ylabel)
self.figure.tight_layout()
self.canvas.draw()
except Exception as e:
print(e)
elif self.oname == "btn_plot_2":
self.xcat = int(self.dlg.cb_x_cat_2.currentText())
self.ycat = int(self.dlg.cb_y_cat_2.currentText())
try:
self.tcat = int(self.dlg.cb_t_cat.currentText())
except:
self.msgBox = QMessageBox()
self.msgBox.setIcon(QMessageBox.Information)
self.msgBox.setText("Invalid T Value!")
self.msgBox.setStandardButtons(QMessageBox.Ok)
self.returnValue = self.msgBox.exec()
return
self.csvPath = self.dlg.ln_output3.text()
self.points = np.genfromtxt(self.csvPath, delimiter=',', skip_header=1, usecols=(0,1,2,3,4,5,6), encoding='utf-8')
self.neighbors, self.relative_coors, self.weights, self.relative_coors_w = self.getNeighbors(self.points, self.xcat, self.ycat, self.tcat)
if not self.dlg.rdo_weight_2.isChecked():
self.current = ((self.points[:,4]==self.xcat) & (self.points[:,5]==self.ycat) & (self.points[:,6] == self.tcat)).sum()
self.coors = ["{},{},{}".format(*i[0]) for i in self.relative_coors]
self.y = [i[1] for i in self.relative_coors]
else:
self.current = self.points[(self.points[:,4]==self.xcat) & (self.points[:,5]==self.ycat) & (self.points[:,6] == self.tcat)][:,3].sum()
self.current = round(self.current,2)
self.coors = ["{},{},{}".format(*i[0]) for i in self.relative_coors_w]
self.y = [i[1] for i in self.relative_coors_w]
self.colors = ["#8e8efa" if i.split(",")[-1]=="-1" else "#3939fa" if i.split(",")[-1]=="0" else "#14067d" for i in self.coors]
self.x = range(2, len(self.y)+2)
self.avg = round(sum(self.y)/len(self.y), 2)
self.title = "Number of Points in Neighbor Grids"
self.figure2.clear()
self.ax2 = self.figure2.add_subplot(111)
self.ax2.grid(True)
self.ax2.bar([0], [self.current], color = "red", label="Current Grid")
self.ax2.bar([1], [self.avg], color= "green", label="Average")
self.ax2.bar(self.x, self.y, color = self.colors)
self.xticks = [self.current] + [self.avg] + self.coors
self.ax2.set_xticks([0] + [1] + list(self.x))
self.ax2.set_xticklabels(self.xticks, rotation=90)
self.ax2.legend(fontsize="x-small")
self.ax2.set_title(self.title, loc="center")
self.ylabel = "Weighted Number of Points" if self.dlg.rdo_weight_2.isChecked() else "Number of Points"
self.ax2.set_ylabel(self.ylabel)
self.ax2.set_xlabel("dx,dy,dt")
self.figure2.tight_layout()
self.canvas2.draw()
def run(self):
"""Run method that performs all the real work"""
# Create the dialog with elements (after translation) and keep reference
# Only create GUI ONCE in callback, so that it will only load when the plugin is started
if self.first_start == True:
self.dlg = SpaceTimeCubeDialog()
self.getLayers()
self.now = datetime.now()
self.now_qdatetime = QDateTime.fromString(self.now.strftime("%Y-%m-%d %H:%M:%S"), 'yyyy-M-d hh:mm:ss')
self.dlg.dt_startTime.setDateTime(self.now_qdatetime)
self.dlg.dt_endTime.setDateTime(self.now_qdatetime)
try:
self.selectedLayer = QgsProject.instance().mapLayersByName(self.dlg.cb_input.currentText())[0]
self.fields = [field.name() for field in self.selectedLayer.fields() if field.typeName().lower() in ("datetime", "date")]
self.weight_fields = [field.name() for field in self.selectedLayer.fields()]
except:
self.msgBox = QMessageBox()
self.msgBox.setIcon(QMessageBox.Information)
self.msgBox.setText("No available layer! Only Simulate function can be used!")
self.msgBox.setStandardButtons(QMessageBox.Ok)
self.returnValue = self.msgBox.exec()
self.fields, self.weight_fields = [], []
self.dlg.cb_weight.clear()
if self.weight_fields:
self.dlg.cb_weight.addItems(["None"] + self.weight_fields)
if self.fields:
self.dlg.cb_datetime.addItems(self.fields)
self.dlg.cb_datetime.setEnabled(True)
else:
self.dlg.cb_datetime.addItem("No Available Field!")
self.dlg.cb_datetime.setEnabled(False)
self.getDatetime_vec = np.vectorize(self.getDatetime)
self.dlg.cb_input.currentTextChanged.connect(self.fillFields)
self.dlg.cb_x_cat_2.activated.connect(self.fillTCat)
self.dlg.cb_y_cat_2.activated.connect(self.fillTCat)
self.dlg.rdo_from_timestamp.toggled.connect(self.change_time_field)
self.dlg.rdo_from_date.toggled.connect(self.change_time_field)
self.dlg.rdo_from_string.toggled.connect(self.change_time_field)
self.dlg.btn_browse.clicked.connect(self.selectOutput)
self.dlg.btn_browse2.clicked.connect(self.selectOutput)
self.dlg.btn_browse3.clicked.connect(self.selectOutput)
self.dlg.btn_browse4.clicked.connect(self.selectOutput)
self.dlg.btn_from_grid.clicked.connect(self.getSelectedFeature)
self.dlg.btn_from_grid_2.clicked.connect(self.getSelectedFeature)
self.dlg.btn_plot.clicked.connect(self.plot)
self.dlg.btn_plot_2.clicked.connect(self.plot)
self.dlg.btn_getExtent.clicked.connect(self.setExtent)
self.dlg.btn_createRandom.clicked.connect(self.createRandomPoints)
self.dlg.tabwidget.currentChanged.connect(self.getGrid)
self.figure = plt.figure()
self.canvas = FigureCanvas(self.figure)
self.dlg.temp_layout.addWidget(self.canvas)
self.ax = self.figure.add_subplot(111)
self.figure2 = plt.figure()
self.canvas2 = FigureCanvas(self.figure2)
self.dlg.temp_layout_2.addWidget(self.canvas2)
self.ax2 = self.figure2.add_subplot(111)
# 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.
self.layerName = self.dlg.cb_input.currentText()
self.selectedLayer = QgsProject.instance().mapLayersByName(self.layerName)[0]
self.features = self.selectedLayer.getFeatures()
self.output_folder = self.dlg.ln_output.text()
if not os.path.isdir(self.output_folder):
self.msgBox = QMessageBox()
self.msgBox.setIcon(QMessageBox.Information)
self.msgBox.setText("Output folder can't be found!")
self.msgBox.setStandardButtons(QMessageBox.Ok)
self.returnValue = self.msgBox.exec()
return
self.gridLayers = QgsProject.instance().mapLayersByName("grid")
if self.gridLayers:
self.msgBox = QMessageBox()
self.msgBox.setIcon(QMessageBox.Information)
self.msgBox.setText("Grid layer is already in the canvas. Remove it first!")
self.msgBox.setStandardButtons(QMessageBox.Ok)
self.returnValue = self.msgBox.exec()
return
self.timefieldtype = "dt" if self.dlg.rdo_from_date.isChecked() else "ts" if self.dlg.rdo_from_timestamp.isChecked() else "str"
self.px = np.array([])
self.py = np.array([])
self.pt = np.array([])
self.pw = np.array([])
self.ref_time = datetime.min
self.weight_col = self.dlg.cb_weight.currentText()
for feat in self.features:
if feat.geometry().isEmpty():
continue
self.geom = feat.geometry()
if self.geom.wkbType() == 1: # Point
self.coors = [(self.geom.asPoint().x(), self.geom.asPoint().y())]
elif self.geom.wkbType() == 4: # MultiPoint
self.coors = [(g.x(), g.y()) for g in self.geom.asMultiPoint()]
for x, y in self.coors:
if self.weight_col != "None":
self.w = feat.attribute(self.weight_col)
self.pw = np.append(self.pw, self.w)
else: