-
Notifications
You must be signed in to change notification settings - Fork 0
/
assimila_datacube.py
765 lines (643 loc) · 29.1 KB
/
assimila_datacube.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
# -*- coding: utf-8 -*-
"""
/***************************************************************************
AssimilaDatacCube
A QGIS plugin
This plugin let's you visualise the datacube.
Generated by Plugin Builder: http://g-sherman.github.io/Qgis-Plugin-Builder/
-------------------
begin : 2019-08-07
git sha : $Format:%H$
copyright : (C) 2019 by Assimila
email : jenny.lin@assimila.eu
***************************************************************************/
/***************************************************************************
* *
* 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
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtWidgets import QAction, QFileDialog
from qgis.core import *
from qgis.core import QgsProject, Qgis, QgsPointXY, QgsGeometry, QgsPoint, \
QgsVectorLayer
from PyQt5.QtWidgets import QApplication, QWidget, QPushButton, QMessageBox
from PyQt5 import QtCore, QtGui, QtWidgets
from PyQt5.QtGui import QColor
from qgis.gui import QgsMapCanvas, QgsRubberBand
from qgis.utils import plugins, reloadPlugin, loadPlugin, startPlugin
from qgis.PyQt.QtNetwork import QNetworkRequest, QNetworkReply, \
QNetworkAccessManager
# Initialize Qt resources from file resources.py
from .resources import *
# Import the code for the dialog
from .assimila_datacube_dialog import AssimilaDatacCubeDialog
import os.path
from os.path import expanduser
import numpy as np
import tempfile
# Import DQTools to set up connection to database
from .DQTools.DQTools import Search, Dataset
# Import Dialog windows
from .nesw_dialog import Ui_NESW_Dialog
from .canvas_dialog import Ui_canvas_Dialog
from .search_dialog import Ui_search_Dialog
from .shapefile_dialog import Ui_shapefile_Dialog
class AssimilaDatacCube:
"""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',
'AssimilaDatacCube_{}.qm'.format(locale))
if os.path.exists(locale_path):
self.translator = QTranslator()
self.translator.load(locale_path)
QCoreApplication.installTranslator(self.translator)
if qVersion() > '4.3.3':
QCoreApplication.installTranslator(self.translator)
# Declare instance attributes
self.actions = []
self.menu = self.tr(u'&Assimila Data 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
self.dlg = AssimilaDatacCubeDialog(iface)
# 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('AssimilaDatacCube', 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/assimila_datacube2/img/icon.png'
self.add_action(
icon_path,
text=self.tr(u'Visualise the datacube.'),
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'&Assimila Data Cube'),
action)
self.iface.removeToolBarIcon(action)
def check(self, north, east, south, west, start, end):
"""
Performs checks: start date is before end date, restricting frequency,
east value is larger than west, and north value is larger than south.
:param north: The name of the north point
:param east: The name of the east point
:param south: The name of the south point
:param west: The name of the west point
:param start: The start date
:param end: The end date
:return:
"""
north = float(north)
east = float(east)
south = float(south)
west = float(west)
# check start is after end date
if str(end)<str(start):
raise ValueError('End date should not be before start date')
# check that end date does not exceed 30 days from start date
# limit is 30 days 23 hours
# 01/01/2000 - 31/01/2000 -> SUCCESS
# 01/01/2000 - 01/02/2000 -> FAIL
if start.daysTo(end) > 30:
raise ValueError('Maximum number of days is limited to 30 days')
# check east value is greater than west value
if east != 0 and west != 0 and east < west:
raise ValueError('East value should be greater than west')
# check north value is greater than south value
if north != 0 and south != 0 and north < south:
raise ValueError('North value should be greater than south')
# check area of box is less than 25*25=625
#print ('N-S=' + str(north - south))
#print ('E-W=' + str(east - west))
#print ('Total area = ' + str((north - south) * (east - west)))
if (north-south)*(east-west) > 625:
raise ValueError('Exceeded maximum area of canvas')
def subproduct_selectionchange(self):
"""
Updates the subproduct combo box to give a list of subproducts
of the selected product.
:return:
"""
self.dlg.subproducts_comboBox.clear()
product = self.dlg.products_comboBox.currentText()
#print(product)
subproducts = Search.get_subproduct_list_of_product(self, product)
#print(subproducts)
self.dlg.subproducts_comboBox.addItems(subproducts)
def radio_btn_state(self, b, dt1, dt2):
"""
Enables and disables the date and hour picker widgets when
the radio buttons are selected.
:param b: The radio button for single time step -
self.dlg.single_radioButton
:param dt1: The data and time picker for the start -
self.dlg.dateTimeEdit_1
:param dt2: The date and time picker for the end -
self.dlg.dateTimeEdit_2
:return:
"""
# If single radiobutton b is checked, then enable 1 datetime widget box
if b.isChecked():
dt1.setDisabled(False)
dt2.setDisabled(True)
#print (b.text()+" is selected")
else:
# Multi radiobutton is checked, so enable both datetime widget boxes
dt1.setDisabled(False)
dt2.setDisabled(False)
#print (b.text()+" is deselected")
def get_data_from_datacube_nesw(self, product, subproduct, north, east,
south, west, start, end):
"""
The request sent to the datacube to process the data given the key file.
:param product: The name of the product
:param subproduct: The name of the subproduct
:param north: The name of the north point
:param east: The name of the east point
:param south: The name of the south point
:param west: The name of the west point
:param start: The start date
:param end: The end date
:return:
"""
# Get key_file location with access to the datacube to get_data
# from Dataset.py
key_file = self.dlg.lineEdit.displayText()
print(f"key_file location: {key_file}")
# Using DQTools
query = Dataset(product=product, subproduct=subproduct, region=None,
tile=None, res=None, key_file=key_file)
region = [north, east, south, west]
query.get_data(start = start, stop=end, region=region, tile=None,
res=None,)
# Return an Xarray
return query.data
def create_raster_file(self, product, subproduct, north, east, south,
west, y):
"""
This prepares and creates the path where the Xarray writes to netcdf
file, which can be added as a Raster layer.
:param product: The name of the product
:param subproduct: The name of the subproduct
:param north: The name of the north point
:param east: The name of the east point
:param south: The name of the south point
:param west: The name of the west point
:param start: The start date
:param end: The end date
:param y: The Xarray outputted from the datacube request
:return:
"""
# Re-formats the start and end dates and hour for filename
start_datetime = self.dlg.dateTimeEdit_1.dateTime()\
.toString("yyyyMMdd_HH")
end_datetime = self.dlg.dateTimeEdit_2.dateTime()\
.toString("yyyyMMdd_HH")
# Create filename and find its path
filename = "%s_%s_N%d_E%d_S%d_W%d_%s_%s" % (product, subproduct, north,
east, south, west,
start_datetime,
end_datetime)
#default_temp_path = f"{tempfile.gettempdir()}/{filename}.nc"
a = (self.dlg.lineEdit_2.displayText())
b = (f"{filename}.nc")
default_temp_path = os.path.join(a, b)
# Write Xarray to netcdf
y.to_netcdf(default_temp_path)
# Creates new layer and adds to current project
self.iface.addRasterLayer(default_temp_path,
"%s_%s_N%d_E%d_S%d_W%d_%s_%s" %
(product, subproduct, north, east, south,
west, start_datetime, end_datetime))
def on_nesw_radioButton_clicked(self):
"""
When the nesw coordinates radio button is toggled it will open
up a dialog window for the user to manually enter the north, east
south, west bounds.
"""
#print("nesw clicked")
NESW_Dialog = QtWidgets.QDialog()
ui = Ui_NESW_Dialog()
ui.setupUi(NESW_Dialog)
res = NESW_Dialog.exec_()
if res == QtWidgets.QDialog.Accepted:
#print("Ok button was clicked")
coordinates = ui.get_values()
#print(coordinates)
self.add_coordinates_to_UI(coordinates)
def on_set_canvas_radioButton_clicked(self):
"""
When the get canvas radio button is toggled it will open
up a dialog window for the user to click set canvas extent,
and get the coordinates of the canvas.
"""
#print("set canvas clicked")
canvas_Dialog = QtWidgets.QDialog()
ui = Ui_canvas_Dialog()
ui.setupUi(self.iface, canvas_Dialog)
res = canvas_Dialog.exec_()
if res == QtWidgets.QDialog.Accepted:
#print("Ok button was clicked")
coordinates = ui.get_values()
#print(coordinates)
self.add_coordinates_to_UI(coordinates)
def on_search_tile_radioButton_clicked(self):
"""
When the search tile radio button is toggled it will open
up a dialog window for the user to search tile, and get
the coordinates of the tile.
"""
#print("search tile clicked")
search_Dialog = QtWidgets.QDialog()
ui = Ui_search_Dialog()
ui.setupUi(search_Dialog)
res = search_Dialog.exec_()
if res == QtWidgets.QDialog.Accepted:
#print("Ok button was clicked")
coordinates = ui.get_values()
#print(coordinates)
self.add_coordinates_to_UI(coordinates)
def on_shapefile_radioButton_clicked(self):
"""
When the raster image radio button is toggled it will open
up a dialog window for the user to browse for the shapefile.
"""
#print("shapefile clicked")
shapefile_Dialog = QtWidgets.QDialog()
ui = Ui_shapefile_Dialog()
ui.setupUi(shapefile_Dialog, self.iface)
res = shapefile_Dialog.exec_()
if res == QtWidgets.QDialog.Accepted:
#print("Ok button was clicked")
coordinates = ui.get_values()
#print(coordinates)
self.add_coordinates_to_UI(coordinates)
def add_coordinates_to_UI(self, coordinates):
"""
This adds the north, east, south, west points to the widgets
on the user interface.
:param coordinates: A list with north, east, south, west bounds
:return:
"""
# Extracting bounds from the coordinates list
north=coordinates[0]
east=coordinates[1]
south=coordinates[2]
west=coordinates[3]
# Adds the north, east, south, west bounds into the display boxes
self.dlg.N_box.setText(str(north))
self.dlg.E_box.setText(str(east))
self.dlg.S_box.setText(str(south))
self.dlg.W_box.setText(str(west))
# Disables the boxes so cannot be altered
self.dlg.N_box.setDisabled(True)
self.dlg.E_box.setDisabled(True)
self.dlg.S_box.setDisabled(True)
self.dlg.W_box.setDisabled(True)
# Calls update map method
self.update_map(north, east, south, west)
def display_map(self):
"""
This displays the map in the QWidget
as soon as the plugin is run.
"""
# Creates map canvas within the widget on the UI
map_canvas = QgsMapCanvas(self.dlg.QgsMapCanvas_wid)
map_canvas.setMinimumSize(450, 250)
# Gets the base map from the server and ensures only that layer is
# displayed
self.raster = self.iface.addRasterLayer(
"url='https://server.arcgisonline.com/arcgis/rest/services/"
"World_Street_Map/MapServer' layer='0'", "tmp", "arcgismapserver")
map_canvas_layer_list = [self.raster, self.raster]
map_canvas.setLayers(map_canvas_layer_list)
# Formats the layer
map_canvas.setExtent(self.raster.extent()) # map layer extent
map_canvas.zoomScale(400000000000000) # scaling for tmp raster
map_canvas.show()
def update_map(self, north, east, south, west):
"""
This updates the map to add the new bounding box
specified by the north, east, south, west parameters.
:param north: The name of the north point
:param east: The name of the east point
:param south: The name of the south point
:param west: The name of the west point
:return:
"""
from qgis.utils import iface
from qgis.PyQt.QtCore import Qt
# Creates map canvas within the widget in the window
canvas = QgsMapCanvas(self.dlg.QgsMapCanvas_wid)
canvas.setMinimumSize(460, 250)
# Gets the basemap from the server and displays only that layer
canvas_layer_list = [self.raster, self.raster]
canvas.setLayers(canvas_layer_list)
# Sets the coordinate reference system
crsDest = QgsCoordinateReferenceSystem(4326) # destination
crsSrc = canvas.mapSettings().destinationCrs() # source
xform = QgsCoordinateTransform()
xform.setSourceCrs(crsSrc)
xform.setDestinationCrs(crsDest)
canvas.setDestinationCrs(crsDest)
# Creating the rubber band rectangle
r = QgsRubberBand(canvas, True) # True = a polygon
# Sepcifying the points of rectangle
points = [[QgsPointXY(west, north), QgsPointXY(east, north),
QgsPointXY(east, south), QgsPointXY(west, south)]]
r.setToGeometry(QgsGeometry.fromPolygonXY(points), None)
r.setFillColor(QColor(255, 0, 0, 50)) #R,G,B,Transparency
r.setWidth(3)
canvas.zoomWithCenter(north-south,east-west,True)
canvas.setExtent(self.raster.extent())
canvas.zoomToFullExtent()
canvas.zoomScale(2000000000) # scaling for tmp raster
#canvas.zoomWithCenter(north-south,east-west,True)
canvas.show()
def use_shapefile_layer(self):
"""
This uses the polygon drawn using 'digitalizing tools' accessed via
the shapefile to get the coordinates and calculate the north, east,
south, west bounds. This will then be passed to the main UI.
:return:
"""
# Remove all tmp files
#for i in QgsProject.instance().mapLayers():
# QgsProject.instance().removeMapLayer(i)
map_canvas = QgsMapCanvas
layers = QgsProject.instance().mapLayers()
layer_list = [l for l in layers.values()]
print(type(layer_list[0].__name__)== "QgsVectorLayer")
for i, j in enumerate(QgsProject.instance().mapLayers()):
#print(i)
# The layer is a vector and not raster
if type(layer_list[i]).__name__== "QgsVectorLayer":
layer = layer_list[i]
coordinates_list = []
selected_fid = []
# Get the first feature id from the layer
for feature in layer.getFeatures():
selected_fid.append(feature.id())
# Get the coordinates
for pos, ch in enumerate(feature.geometry().vertices()):
coordinates_list.append(feature.geometry().vertexAt(pos))
north, east, south, west = \
self.points_to_cardinal(coordinates_list)
# Displayed the values in the display boxes
self.dlg.N_box.setText(str(north))
self.dlg.E_box.setText(str(east))
self.dlg.S_box.setText(str(south))
self.dlg.W_box.setText(str(west))
# Disables other options of selcting the bounds
self.dlg.nesw_radioButton.setDisabled(True)
self.dlg.set_canvas_radioButton.setDisabled(True)
self.dlg.search_tile_radioButton.setDisabled(True)
self.dlg.shapfile_radioButton.setDisabled(True)
def points_to_cardinal(self, coordinates_list):
"""
This gets the coordinates, and calculates the
north, east, south, west bounds of the polygon
:param coordinates_list: The list of x,y coordinates of the polygon
:return:
"""
x_list = []
y_list = []
# Splits into lists containing x coordinates and y coordinates
for pos, ch in enumerate(coordinates_list):
x_list.append(coordinates_list[pos].x())
y_list.append(coordinates_list[pos].y())
# Setting the north, east, south, west coordinates
north = round(max(y_list), 2)
south = round(min(y_list),2)
#print(x_list)
#max_x = np.where(x_list == np.amax(x_list))
east = round(max(x_list), 2)
west = round(min(x_list), 2)
#print(y_list)
return north, east, south, west
def get_change(self, button, method):
"""
This method checks the status of the radio buttons which
allows the users to select the method they want to input
the n,e,s,w bounds into the UI map
:param button: radio button passed throug
:param method: method to run after relevant radio button
is clicked.
:return:
"""
if button.isChecked():
method()
def run(self):
"""
This prepares the user interface of the plugin and the performs
the events once "OK" is clicked.
:return:
"""
# Reloading the plugin
reloadPlugin('AssimilaDatacCube')
# Removes raster base map layers (name: tmp)
for i in QgsProject.instance().mapLayersByName("tmp"):
QgsProject.instance().removeMapLayer(i)
# 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.first_start = False
self.dlg = AssimilaDatacCubeDialog(self.iface)
# Displays map on widget canvas
self.display_map()
# If there exists a shapefile on the canvas then will get coordinates
# from that polygon
#self.use_shapefile_layer()
# Clears the values from previous run
self.dlg.lineEdit.clear() #keyfile
self.dlg.lineEdit_2.clear() #rasterfile
# Displays key file path location
self.key_file = os.path.join(expanduser("~"), "Documents",
".assimila_dq")
self.dlg.lineEdit.insert(self.key_file)
# Display default raster file path location
"""
Not using temporary location due to permissioin error if you
read the path from the lineEdit. Use tempfile.gettempdir to
access temporary directory without permission error.
raster_file = "Users\Jenny\AppData\Local\Temp"
#default_temp_path = f"{tempfile.gettempdir()}/{filename}.nc"
"""
raster_file = os.path.join(expanduser("~"), "Documents")
self.dlg.lineEdit_2.insert(raster_file)
# Display dropdowns for products
# Only runs on the first run as the products_comboBox is empty
# Instead of clearing the products combobox and then appending everytime
# Only searches for products once
if self.dlg.products_comboBox.currentIndex() == -1:
products = Search.products().name.tolist()
self.dlg.products_comboBox.setDuplicatesEnabled(False)
self.dlg.products_comboBox.addItems(products)
# Display dropdown for subproducts
# Defaulting 1st item Subprodusct is 'rfe'
self.dlg.subproducts_comboBox.addItem('rfe')
# For updating the subproduct
self.dlg.products_comboBox.currentTextChanged\
.connect(self.subproduct_selectionchange)
# Removing default subproduct value of 'rfe'
self.dlg.subproducts_comboBox.removeItem(1)
# Links the Radio buttons and datetime widgets
self.dlg.multi_radioButton.toggled\
.connect(lambda: self.radio_btn_state(self.dlg.single_radioButton,
self.dlg.dateTimeEdit_1,
self.dlg.dateTimeEdit_2))
# Links the radio buttons to their actions once clicked,
# radioButtons must be connected first before checking
# their status by calling get_change()
self.dlg.nesw_radioButton.toggled\
.connect(lambda: self.get_change(self.dlg.nesw_radioButton,
self.on_nesw_radioButton_clicked))
self.dlg.set_canvas_radioButton.toggled\
.connect(lambda: self.get_change(
self.dlg.set_canvas_radioButton,
self.on_set_canvas_radioButton_clicked))
self.dlg.search_tile_radioButton.toggled\
.connect(lambda: self.get_change(
self.dlg.search_tile_radioButton,
self.on_search_tile_radioButton_clicked))
self.dlg.shapefile_radioButton.toggled\
.connect(lambda: self.get_change(
self.dlg.shapefile_radioButton,
self.on_shapefile_radioButton_clicked ))
# Show the dialog
self.dlg.show()
# Run the dialog event loop
result = self.dlg.exec_()
# Runs when OK button is pressed
if result:
# runs process using values in widgets
product = (self.dlg.products_comboBox.currentText()).lower()
#print(f"The product being run is {product}")
subproduct = self.dlg.subproducts_comboBox.currentText()
#print(f"The subproduct being run is {subproduct}")
north = float(self.dlg.N_box.displayText())
#print('N: ' + str(north))
east = float(self.dlg.E_box.displayText())
#print('E: ' + str(east))
south = float(self.dlg.S_box.displayText())
#print('S: ' + str(south))
west = float(self.dlg.W_box.displayText())
#print('W: ' + str(west))
# Format start and end dates and hour for datecube
start = self.dlg.dateTimeEdit_1.dateTime()\
.toString("yyyy-MM-ddTHH:00:00")
if self.dlg.single_radioButton.isChecked():
end = start
# Perform check method for d1
self.check(north, east, south, west,
self.dlg.dateTimeEdit_1.dateTime(),
self.dlg.dateTimeEdit_1.dateTime())
else:
end = self.dlg.dateTimeEdit_2.dateTime()\
.toString("yyyy-MM-ddTHH:00:00")
# Perform check method for d1 d2
self.check(north, east, south, west,
self.dlg.dateTimeEdit_1.dateTime(),
self.dlg.dateTimeEdit_2.dateTime())
try:
# Get Xarray from datacube
y = self.get_data_from_datacube_nesw(product, subproduct,
north, east, south, west,
start, end)
# Write Xarray to file
self.create_raster_file(product, subproduct, north, east,
south, west, y)
except Exception as e:
print("Wrong keyfile location or contact Assimila for key file."
+ str(e))
pass