-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsunposition.py
207 lines (181 loc) · 8.39 KB
/
sunposition.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
"""
/***************************************************************************
* *
* 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. *
* *
***************************************************************************/
"""
import os
from datetime import timedelta
from zoneinfo import ZoneInfo
from skyfield.api import Loader, load, wgs84
from skyfield.positionlib import Geocentric
import traceback
from qgis.core import (
QgsPointXY, QgsFeature, QgsGeometry, QgsField, QgsFields, QgsVectorLayer,
QgsWkbTypes, QgsCoordinateReferenceSystem, QgsSvgMarkerSymbolLayer)
from qgis.core import (
QgsProcessing,
QgsProcessingAlgorithm,
QgsProcessingException,
QgsProcessingParameterDefinition,
QgsProcessingParameterString,
QgsProcessingLayerPostProcessorInterface,
QgsProcessingParameterBoolean,
QgsProcessingParameterDateTime,
QgsProcessingParameterFeatureSink)
from qgis.PyQt.QtGui import QIcon
from qgis.PyQt.QtCore import QVariant, QUrl, QDateTime, QTime
from .utils import epsg4326, settings, SolarObj, parse_timeseries, zeroMsec, DateTimeWidget
class SunPositionAlgorithm(QgsProcessingAlgorithm):
"""
Algorithm to display the sun directly overhead.
"""
PrmOutputLayer = 'OutputLayer'
PrmDateTime = 'DateTime'
PrmTimeSeries = 'TimeSeries'
PrmTimeIncrement = 'TimeIncrement'
PrmTimeDuration = 'TimeDuration'
PrmStyle = 'Style'
def initAlgorithm(self, config):
dt = QDateTime.currentDateTime()
# Right now the this widget only is valid up to hour and minute. I'm going to
# remove the seconds and msec
zeroMsec(dt)
"""self.addParameter(
QgsProcessingParameterDateTime(
self.PrmDateTime,
'Select date and time for calculations',
type=QgsProcessingParameterDateTime.DateTime,
defaultValue=dt,
optional=False,
)
)"""
param = QgsProcessingParameterString(
self.PrmDateTime,
'Select date and time for calculations',
defaultValue=dt,
optional=False,
)
param.setMetadata({'widget_wrapper': {"class": DateTimeWidget}})
self.addParameter(param)
self.addParameter(
QgsProcessingParameterBoolean(
self.PrmStyle,
'Automatically style output',
True,
optional=False)
)
# Time Series Support
param = QgsProcessingParameterBoolean(
self.PrmTimeSeries,
'Create sun time series',
False,
optional=True)
param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
self.addParameter(param)
param = QgsProcessingParameterString(
self.PrmTimeIncrement,
'Time increment between observations (DD:HH:MM:SS)',
defaultValue='00:01:00:00',
optional=True)
param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
self.addParameter(param)
param = QgsProcessingParameterString(
self.PrmTimeDuration,
'Total duration for sun positions (DD:HH:MM:SS)',
defaultValue='1:00:00:00',
optional=True)
param.setFlags(param.flags() | QgsProcessingParameterDefinition.FlagAdvanced)
self.addParameter(param)
self.addParameter(
QgsProcessingParameterFeatureSink(
self.PrmOutputLayer,
'Sun Position')
)
def processAlgorithm(self, parameters, context, feedback):
auto_style = self.parameterAsBool(parameters, self.PrmStyle, context)
qdt = self.parameterAsDateTime(parameters, self.PrmDateTime, context)
generate_timeseries = self.parameterAsBool(parameters, self.PrmTimeSeries, context)
time_increment = self.parameterAsString(parameters, self.PrmTimeIncrement, context)
time_duration = self.parameterAsString(parameters, self.PrmTimeDuration, context)
if generate_timeseries:
num_events, time_delta = parse_timeseries(time_increment, time_duration)
else:
num_events = 1
time_delta = 0
if num_events == -1:
raise QgsProcessingException('Invalid time increment and/or duration.')
feedback.pushInfo('Number of sun observations: {}'.format(num_events))
f = QgsFields()
f.append(QgsField("object_id", QVariant.Int))
f.append(QgsField("name", QVariant.String))
f.append(QgsField("latitude", QVariant.Double))
f.append(QgsField("longitude", QVariant.Double))
f.append(QgsField("timestamp", QVariant.Double))
f.append(QgsField("datetime", QVariant.String))
f.append(QgsField("utc", QVariant.String))
(sink, dest_id) = self.parameterAsSink(
parameters, self.PrmOutputLayer, context, f,
QgsWkbTypes.Point, epsg4326)
qutc = qdt.toUTC()
utc = qutc.toPyDateTime()
utc = utc.replace(tzinfo=ZoneInfo('UTC')) # Make sure it is an aware UTC
eph = load(settings.ephemPath())
earth = eph['earth'] # vector from solar system barycenter to geocenter
sun = eph['sun'] # vector from solar system barycenter to sun
geocentric_sun = sun - earth # vector from geocenter to sun
ts = load.timescale()
for i in range(num_events):
delta = i*time_delta
utc_cur = utc + timedelta(seconds=delta)
t = ts.from_datetime(utc_cur)
try:
sun_position = wgs84.geographic_position_of(geocentric_sun.at(t)) # geographic_position_of method requires a geocentric position
except Exception:
feedback.reportError('The ephemeris file does not cover the selected date range. Go to Settings and download and select an ephemeris file that contains your date range.')
return {}
feat = QgsFeature()
attr = [SolarObj.SUN.value, 'Sun', float(sun_position.latitude.degrees), float(sun_position.longitude.degrees), utc_cur.timestamp(), qdt.addSecs(delta).toString('yyyy-MM-dd hh:mm:ss'), qutc.addSecs(delta).toString('yyyy-MM-dd hh:mm:ss')]
feat.setAttributes(attr)
pt = QgsPointXY(sun_position.longitude.degrees, sun_position.latitude.degrees)
feat.setGeometry(QgsGeometry.fromPointXY(pt))
sink.addFeature(feat)
if auto_style and context.willLoadLayerOnCompletion(dest_id):
context.layerToLoadOnCompletionDetails(dest_id).setPostProcessor(StylePostProcessor.create())
return {self.PrmOutputLayer: dest_id}
def name(self):
return 'sunposition'
def displayName(self):
return 'Sun position directly overhead'
def icon(self):
return QIcon(os.path.dirname(__file__) + '/icons/sun.svg')
'''def helpUrl(self):
file = os.path.dirname(__file__) + '/index.html'
if not os.path.exists(file):
return ''
return QUrl.fromLocalFile(file).toString(QUrl.FullyEncoded)'''
def createInstance(self):
return SunPositionAlgorithm()
class StylePostProcessor(QgsProcessingLayerPostProcessorInterface):
instance = None
def postProcessLayer(self, layer, context, feedback):
if not isinstance(layer, QgsVectorLayer):
return
path = os.path.join(os.path.dirname(__file__), 'icons/sun.svg')
symbol = QgsSvgMarkerSymbolLayer(path)
symbol.setSize(10)
layer.renderer().symbol().changeSymbolLayer(0, symbol )
layer.triggerRepaint()
@staticmethod
def create() -> 'StylePostProcessor':
"""
Returns a new instance of the post processor keeping a reference to the sip
wrapper so that sip doesn't get confused with the Python subclass and call
the base wrapper implemenation instead.
"""
StylePostProcessor.instance = StylePostProcessor()
return StylePostProcessor.instance