This repository has been archived by the owner on Jun 3, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 6
/
config.py
314 lines (256 loc) · 10.4 KB
/
config.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
#!/usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright (C) 2018 Oslandia <[email protected]>
#
# This file is a piece of free software; you can redistribute it and/or
# modify it under the terms of the GNU Library General Public
# License as published by the Free Software Foundation; either
# version 2 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
# Library General Public License for more details.
# You should have received a copy of the GNU Library General Public
# License along with this library; if not, see <http://www.gnu.org/licenses/>.
#
import os
import json
from qgis.core import QgsProject, QgsVectorLayer
from PyQt5.QtXml import QDomDocument
SUBKEYS = ("stratigraphy_config", "log_measures", "timeseries")
class PlotConfig:
"""Holds the configuration of a plot (log or timeseries)
It is for now a wrapper around a dictionary object."""
def __init__(self, config, parent=None):
"""
Parameters
----------
config: dict
Dictionary of the plot configuration
parent: LayerConfig
The LayerConfig in which this PlotConfig is stored
"""
self.__parent = parent
self.__config = config
self.__filter_value = None
self.__filter_unique_values = []
def get_layerid(self):
return self.__config["source"]
def get_uom(self):
"""Gets the unit of measure"""
if self.__config["type"] == "instantaneous":
return (self.__config["uom"] if "uom" in self.__config
else "@" + self.__config["uom_column"])
else:
return self.__config["uom"]
def get_style_file(self):
style = self.__config.get("style")
return os.path.join(os.path.dirname(__file__), 'qgeologis/styles',
style if style else "stratigraphy_style.xml")
def get(self, key, default=None):
return self.__config.get(key, default)
def __getitem__(self, key):
return self.__config[key]
# TODO: filter_value and filter_unique_values setter and getter
# are only helper method and should not be part of the configuration
def set_filter_value(self, value):
self.__filter_value = value
def set_filter_unique_values(self, values):
self.__filter_unique_values = values
def get_filter_value(self):
return self.__filter_value
def get_filter_unique_values(self):
return self.__filter_unique_values
def _get_dict(self):
return self.__config
def get_symbology(self):
"""Returns the associated QGIS symbology
Return
------
A tuple (QDomDocument, int)
The QDomDocument can be loaded by QgsFeatureRenderer.load()
The int gives the renderer type
or None, None
"""
symbology = self.__config.get("symbology")
if symbology is None:
return None, None
doc = QDomDocument()
doc.setContent(symbology)
return (doc, self.__config.get("symbology_type"))
def set_symbology(self, symbology, symbology_type):
"""Sets the associated QGIS symbology
Parameters
----------
symbology: QDomDocument or None
symbology_type: Literal[0,1,2]
Type of renderer
0: points
1: lines
2: polygons
"""
if symbology is not None:
self.__config["symbology"] = symbology.toString()
self.__config["symbology_type"] = symbology_type
if self.__parent:
self.__parent.config_modified()
def __repr__(self):
return repr(self.__config)
class LayerConfig:
"""Holds the configuration of a "root" layer (the layer where stations or collars are stored).
It contains PlotConfigs
"""
def __init__(self, config, layer_id):
"""
Parameters
----------
config: dict
A dict {layer_id : dict of plot configuration} that will be updated if needed
layer_id: str
The main layer id
"""
# The "main" or "parent" configuration
self.__parent_config = config
# Part of the main configuration, for a given layer id
self.__config = config.get(layer_id)
self._wrap()
def _wrap(self):
self.__stratigraphy_plots = [PlotConfig(p, self) for p in self.__config.get("stratigraphy_config", [])]
self.__log_plots = [PlotConfig(p, self) for p in self.__config.get("log_measures", [])]
self.__timeseries = [PlotConfig(p, self) for p in self.__config.get("timeseries", [])]
self.__imageries = [PlotConfig(p, self) for p in self.__config.get("imagery_data", [])]
def get(self, key, default=None):
return self.__config.get(key, default)
def __getitem__(self, key):
return self.__config[key]
def get_stratigraphy_plots(self):
return self.__stratigraphy_plots
def get_log_plots(self):
return self.__log_plots
def get_imageries(self):
return self.__imageries
def get_timeseries(self):
return self.__timeseries
def get_vertical_plots(self):
return self.__stratigraphy_plots + self.__log_plots
def add_plot_config(self, config_type, plot_config):
"""
Parameters
----------
config_type: Literal["stratigraphy_config", "log_measures", "timeseries"]
plot_config: PlotConfig
"""
if config_type not in self.__config:
self.__config[config_type] = []
self.__config[config_type].append(plot_config._get_dict())
self._wrap()
self.config_modified()
def config_modified(self):
json_config = json.dumps(self.__parent_config)
QgsProject.instance().writeEntry("QGeoloGIS", "config", json_config)
def export_config(main_config, filename):
"""Exports the given project configuration to a filename.
Layer IDs stored in the configuration are converted into triple (source, url, provider)
Filters on layers or virtual fields will then be lost during the translation
Parameters
----------
main_config: dict
The configuration as a dict
filename: str
Name of the file where to export the configuration to
"""
# copy the input config
from copy import deepcopy
main_config = deepcopy(main_config)
new_dict = {}
# root layers at the beginning of the dict
for root_layer_id, config in main_config.items():
root_layer = QgsProject.instance().mapLayer(root_layer_id)
if not root_layer:
continue
# replace "source" keys
for subkey in SUBKEYS:
for layer_cfg in config[subkey]:
source_id = layer_cfg["source"]
source = QgsProject.instance().mapLayer(source_id)
if not source:
continue
layer_cfg["source"] = {
"source": source.source(),
"name": source.name(),
"provider": source.providerType()
}
root_key = "{}#{}#{}".format(root_layer.source(), root_layer.name(), root_layer.providerType())
new_dict[root_key] = dict(config)
# write to the output file
with open(filename, "w", encoding="utf-8") as fo:
json.dump(new_dict, fo, ensure_ascii=False, indent=4)
def import_config(filename, overwrite_existing=False):
"""Import the configuration from a given filename
Layers are created and added to the current project.
Parameters
----------
filename: str
Name of the file where to import the configuration from
overwrite_existing: bool
Whether to try to overwrite existing layers that have
the same data source definition
Returns
-------
The configuration as a dict
"""
with open(filename, "r", encoding="utf-8") as fi:
config_json = json.load(fi)
new_config = {}
def find_existing_layer_or_create(source, name, provider, do_overwrite):
if do_overwrite:
for layer_id, layer in QgsProject.instance().mapLayers().items():
if layer.source() == source and layer.providerType() == provider:
layer.setName(name)
return layer
# layer not found, create it then !
layer = QgsVectorLayer(source, name, provider)
QgsProject.instance().addMapLayer(layer)
return layer
# root layers at the beginning of the dict
for root_layer_source, config in config_json.items():
root_layer_source, root_layer_name, root_layer_provider = root_layer_source.split('#')
root_layer = find_existing_layer_or_create(root_layer_source,
root_layer_name,
root_layer_provider,
overwrite_existing)
for subkey in SUBKEYS:
for layer_cfg in config[subkey]:
source = layer_cfg["source"]
layer = find_existing_layer_or_create(source["source"],
source["name"],
source["provider"],
overwrite_existing)
layer_cfg["source"] = layer.id()
# change the main dict key
new_config[root_layer.id()] = dict(config)
return new_config
def remove_layer_from_config(config, layer_id):
"""Remove a layer reference from a configuration object
Parameters
----------
config: dict
The main plot configuration. It is modified in place.
layer_id: str
The layer whom references are to remove from the config
"""
for root_layer_id, sub_config in config.items():
if layer_id == root_layer_id:
# remove the dictionary entry
del config
return
for subkey in SUBKEYS:
if subkey in sub_config:
copy = []
for layer_cfg in sub_config[subkey]:
sub_layer_id = layer_cfg["source"]
if layer_id != sub_layer_id:
copy.append(layer_cfg)
sub_config[subkey] = copy