Skip to content

Commit

Permalink
Merge pull request #760 from kartoza/timlinux/issue708
Browse files Browse the repository at this point in the history
Fix #759 context menu for adding map items broken
  • Loading branch information
timlinux authored Jan 13, 2025
2 parents 6348539 + 071f05a commit d1482db
Show file tree
Hide file tree
Showing 5 changed files with 101 additions and 13 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
QgsCoordinateReferenceSystem,
)
import processing
from geest.core import JsonTreeItem
from geest.utilities import log_message, resources_path
from geest.core.algorithms import AreaIterator

Expand Down Expand Up @@ -55,6 +56,7 @@ class OpportunitiesByWeeScorePopulationProcessingTask(QgsTask):

def __init__(
self,
item: JsonTreeItem,
study_area_gpkg_path: str,
working_directory: str,
target_crs: Optional[QgsCoordinateReferenceSystem] = None,
Expand All @@ -63,6 +65,7 @@ def __init__(
super().__init__(
"Opportunities WEE Score by Population Processor", QgsTask.CanCancel
)
self.item = item
self.study_area_gpkg_path = study_area_gpkg_path

self.output_dir = os.path.join(
Expand Down Expand Up @@ -91,7 +94,8 @@ def __init__(
self.target_crs = layer.crs()
del layer
self.output_rasters: List[str] = []

self.result_file_key = "wee_by_population_by_opportunities_mask_result_file"
self.result_key = "wee_by_population_by_opportunities_mask_result"
log_message(
"Initialized Opportunities Mask by WEE SCORE by Population Processing Task"
)
Expand All @@ -102,11 +106,17 @@ def run(self) -> bool:
"""
try:
self.calculate_score()
self.generate_vrt()
vrt_path = self.generate_vrt()
self.item.setAttribute(self.result_file_key, vrt_path)
self.item.setAttribute(
self.result_key,
"WEE Score by Population by Opportunities Mask Created OK",
)
return True
except Exception as e:
log_message(f"Task failed: {e}")
log_message(traceback.format_exc())
self.item.setAttribute(self.result_key, f"Task failed: {e}")
return False

def validate_rasters(
Expand All @@ -131,7 +141,7 @@ def validate_rasters(
log_message("Validating input rasters")
log_message(f"opportunities_mask_raster: {opportunities_mask_raster.source()}")
log_message(
f"wee_score_by_population raster raster : {wee_score_by_population_raster.source()}"
f"wee_score_by_population raster : {wee_score_by_population_raster.source()}"
)

if (
Expand Down Expand Up @@ -186,7 +196,7 @@ def calculate_score(self) -> None:
)

output_path = os.path.join(
self.output_dir, f"wee_by_opportunities_mask_{index}.tif"
self.output_dir, f"wee_by_population_by_opportunities_mask_{index}.tif"
)
if not self.force_clear and os.path.exists(output_path):
log_message(f"Reusing existing raster: {output_path}")
Expand Down Expand Up @@ -215,12 +225,21 @@ def calculate_score(self) -> None:

log_message(f"Masked WEE SCORE raster saved to {output_path}")

def generate_vrt(self) -> None:
def generate_vrt(self) -> str:
"""
Combines all WEE SCORE rasters into a single VRT and ap plies a QML style.
returns:
str: Path to the generated VRT file.
"""
vrt_path = os.path.join(self.output_dir, "wee_by_opportunities_mask.vrt")
qml_path = os.path.join(self.output_dir, "wee_by_opportunities_mask.qml")
vrt_path = os.path.join(
self.output_dir, "wee_by_population_by_opportunities_mask.vrt"
)
qml_path = os.path.join(
self.output_dir, "wee_by_population_by_opportunities_mask.qml"
)
source_qml = resources_path("resources", "qml", "wee_by_population_score.qml")

params = {
Expand All @@ -239,6 +258,7 @@ def generate_vrt(self) -> None:
log_message(f"Copied QML style from {source_qml} to {qml_path}")
else:
log_message("QML style file not found. Skipping QML copy.")
return vrt_path

def finished(self, result: bool) -> None:
"""
Expand Down
19 changes: 16 additions & 3 deletions geest/core/algorithms/opportunities_by_wee_score_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
QgsCoordinateReferenceSystem,
)
import processing
from geest.core import JsonTreeItem
from geest.utilities import log_message, resources_path
from geest.core.algorithms import AreaIterator

Expand Down Expand Up @@ -45,12 +46,14 @@ class OpportunitiesByWeeScoreProcessingTask(QgsTask):

def __init__(
self,
item: JsonTreeItem,
study_area_gpkg_path: str,
working_directory: str,
target_crs: Optional[QgsCoordinateReferenceSystem] = None,
force_clear: bool = False,
):
super().__init__("Opportunities WEE Score Processor", QgsTask.CanCancel)
self.item = item
self.study_area_gpkg_path = study_area_gpkg_path

self.output_dir = os.path.join(working_directory, "opportunities_by_wee_score")
Expand All @@ -77,7 +80,8 @@ def __init__(
self.target_crs = layer.crs()
del layer
self.output_rasters: List[str] = []

self.result_file_key = "wee_by_opportunities_mask_result_file"
self.result_key = "wee_by_opportunities_mask_result"
log_message("Initialized Opportunities Mask by WEE SCORE Processing Task")

def run(self) -> bool:
Expand All @@ -86,11 +90,16 @@ def run(self) -> bool:
"""
try:
self.calculate_score()
self.generate_vrt()
vrt_filepath = self.generate_vrt()
self.item.setAttribute(self.result_file_key, vrt_filepath)
self.item.setAttribute(
self.result_key, "WEE Score by Opportunities Mask Created OK"
)
return True
except Exception as e:
log_message(f"Task failed: {e}")
log_message(traceback.format_exc())
self.item.setAttribute(self.result_key, f"Task failed: {e}")
return False

def validate_rasters(
Expand Down Expand Up @@ -183,9 +192,12 @@ def calculate_score(self) -> None:

log_message(f"Masked WEE SCORE raster saved to {output_path}")

def generate_vrt(self) -> None:
def generate_vrt(self) -> str:
"""
Combines all WEE SCORE rasters into a single VRT and ap plies a QML style.
Returns:
str: Path to the generated VRT file.
"""
vrt_path = os.path.join(self.output_dir, "wee_by_opportunities_mask.vrt")
qml_path = os.path.join(self.output_dir, "wee_by_opportunities_mask.qml")
Expand All @@ -207,6 +219,7 @@ def generate_vrt(self) -> None:
log_message(f"Copied QML style from {source_qml} to {qml_path}")
else:
log_message("QML style file not found. Skipping QML copy.")
return vrt_path

def finished(self, result: bool) -> None:
"""
Expand Down
4 changes: 3 additions & 1 deletion geest/core/algorithms/opportunities_mask_processor.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,10 +238,12 @@ def run(self) -> bool:
vrt_filepath = combine_rasters_to_vrt(
self.mask_list, self.target_crs, vrt_filepath, source_qml
)

self.item.setAttribute(self.result_file_key, vrt_filepath)
self.item.setAttribute(self.result_key, "Opportunities Mask Created OK")
except Exception as e:
log_message(f"Task failed: {e}")
log_message(traceback.format_exc())
self.item.setAttribute(self.result_key, str(e))
return False

def finished(self, result: bool) -> None:
Expand Down
21 changes: 19 additions & 2 deletions geest/gui/panels/tree_panel.py
Original file line number Diff line number Diff line change
Expand Up @@ -516,7 +516,7 @@ def update_action_text():

add_masked_scores = QAction("Add Masked Scores to Map")
add_masked_scores.triggered.connect(
lambda: self.add_masked_scoores_to_map(item)
lambda: self.add_masked_scores_to_map(item)
)
menu.addAction(add_masked_scores)

Expand Down Expand Up @@ -623,6 +623,21 @@ def update_action_text():
# Show the menu at the cursor's position
menu.exec_(self.treeView.viewport().mapToGlobal(position))

def add_masked_scores_to_map(self, item):
"""Add the masked scores to the map."""
self.add_to_map(
item,
key="wee_by_opportunities_mask_result_file",
layer_name="Masked WEE Score",
group="WEE",
)
self.add_to_map(
item,
key="wee_by_population_by_opportunities_mask_result_file",
layer_name="Masked WEE by Population Score",
group="WEE",
)

def add_aggregates_to_map(self, item):
"""Add all the aggregate produts to the map"""
self.add_to_map(
Expand Down Expand Up @@ -1425,13 +1440,15 @@ def calculate_analysis_insights(self, item: JsonTreeItem):
# WEE Score Masked by Job Opportunities
# WEE Score x Population masked by Job Opportunities
mask_processor = OpportunitiesByWeeScoreProcessingTask(
item=item,
study_area_gpkg_path=gpkg_path,
working_directory=self.working_directory,
force_clear=False,
)
mask_processor.run()

mask_processor = OpportunitiesByWeeScorePopulationProcessingTask(
item=item,
study_area_gpkg_path=gpkg_path,
working_directory=self.working_directory,
force_clear=False,
Expand All @@ -1452,7 +1469,7 @@ def calculate_analysis_insights(self, item: JsonTreeItem):
except Exception as e:
log_message(f"Failed to run subnational aggregation: {e}")
log_message(traceback.format_exc())

self.save_json_to_working_directory()
log_message("############################################")
log_message("END")
log_message("############################################")
Expand Down
36 changes: 36 additions & 0 deletions geest/gui/views/treeview.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,33 @@ def loadJsonData(self, json_data):
"opportunities_mask_result_file", ""
)
opportunities_mask_result = json_data.get("opportunities_mask_result", "")
wee_by_opportunities_mask_result = json_data.get(
"wee_by_opportunities_mask_result", ""
)
wee_by_opportunities_mask_result_file = json_data.get(
"wee_by_opportunities_mask_result_file", ""
)
wee_by_population = json_data.get("wee_by_population", "")
wee_by_population_subnational_aggregation = json_data.get(
"wee_by_population_subnational_aggregation", ""
)
wee_score_subnational_aggregation = json_data.get(
"wee_score_subnational_aggregation", ""
)
opportunities_by_wee_score_by_population_subnational_aggregation = (
json_data.get(
"opportunities_by_wee_score_by_population_subnational_aggregation", ""
)
)
opportunities_by_wee_score_subnational_aggregation = json_data.get(
"opportunities_by_wee_score_subnational_aggregation", ""
)
wee_by_population_by_opportunities_mask_result_file = json_data.get(
"wee_by_population_by_opportunities_mask_result_file", ""
)
wee_by_population_by_opportunities_mask_result = json_data.get(
"wee_by_population_by_opportunities_mask_result", ""
)
# Store special properties in the attributes dictionary
analysis_attributes = {
"analysis_name": analysis_name,
Expand All @@ -104,6 +131,15 @@ def loadJsonData(self, json_data):
"buffer_distance_m": buffer_distance_m,
"opportunities_mask_result_file": opportunities_mask_result_file,
"opportunities_mask_result": opportunities_mask_result,
"wee_by_opportunities_mask_result": wee_by_opportunities_mask_result,
"wee_by_opportunities_mask_result_file": wee_by_opportunities_mask_result_file,
"wee_by_population": wee_by_population,
"wee_by_population_subnational_aggregation": wee_by_population_subnational_aggregation,
"wee_score_subnational_aggregation": wee_score_subnational_aggregation,
"opportunities_by_wee_score_by_population_subnational_aggregation": opportunities_by_wee_score_by_population_subnational_aggregation,
"opportunities_by_wee_score_subnational_aggregation": opportunities_by_wee_score_subnational_aggregation,
"wee_by_population_by_opportunities_mask_result_file": wee_by_population_by_opportunities_mask_result_file,
"wee_by_population_by_opportunities_mask_result": wee_by_population_by_opportunities_mask_result,
}
for prefix in [
"aggregation",
Expand Down

0 comments on commit d1482db

Please sign in to comment.