Skip to content

Commit

Permalink
feat: Separate recent algorithms from general application settings (#752
Browse files Browse the repository at this point in the history
)

Co-authored-by: Sourcery AI <>
Co-authored-by: sourcery-ai[bot] <58596630+sourcery-ai[bot]@users.noreply.github.com>
  • Loading branch information
Czaki and sourcery-ai[bot] authored Oct 15, 2022
1 parent ef43db3 commit 54958d1
Show file tree
Hide file tree
Showing 8 changed files with 97 additions and 63 deletions.
8 changes: 4 additions & 4 deletions azure-pipelines.yml
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@ stages:
- stage: GetTestData
jobs:
- job: linux
pool: {vmImage: 'Ubuntu-18.04'}
pool: {vmImage: 'Ubuntu-20.04'}
steps:
- script: bash build_utils/download_data.sh
displayName: "download data"
Expand Down Expand Up @@ -91,7 +91,7 @@ stages:
artifactName: docs

- job: Notebook_check
pool: {vmImage: 'Ubuntu-18.04'}
pool: {vmImage: 'Ubuntu-20.04'}
continueOnError: true
variables:
DATA_PATH: typy_neuronow2
Expand Down Expand Up @@ -150,7 +150,7 @@ stages:
dependsOn: Tests_linux
jobs:
- job: sdist
pool: {vmImage: 'Ubuntu-18.04'}
pool: {vmImage: 'Ubuntu-20.04'}
steps:
- task: UsePythonVersion@0
- bash: pip install -r requirements/requirements_dev.txt
Expand All @@ -167,7 +167,7 @@ stages:
test_path: dist/PartSeg/PartSeg _test
DISPLAY: ':99.0'
pip_cache_dir: $(Pipeline.Workspace)/.pip
pool: { vmImage: 'ubuntu-18.04' }
pool: { vmImage: 'Ubuntu-20.04' }
steps:
- template: .azure-pipelines/linux_libs.yaml
- template: .azure-pipelines/pyinstaller.yaml
Expand Down
4 changes: 2 additions & 2 deletions package/PartSeg/_roi_analysis/main_window.py
Original file line number Diff line number Diff line change
Expand Up @@ -183,7 +183,7 @@ def save_pipeline(self):
if not name:
QMessageBox.information(self, "No segmentation", "No segmentation executed", QMessageBox.Ok)
return
values = self._settings.get(f"algorithms.{name}", {})
values = self._settings.get_algorithm(f"algorithms.{name}", {})
if len(values) == 0:
QMessageBox.information(self, "Some problem", "Pleas run execution again", QMessageBox.Ok)
return
Expand Down Expand Up @@ -500,7 +500,7 @@ def next_mask(self):
def prev_mask(self):
history: HistoryElement = self.settings.history_pop()
algorithm_name = self.settings.last_executed_algorithm
algorithm_values = self.settings.get(f"algorithms.{algorithm_name}")
algorithm_values = self.settings.get_algorithm(f"algorithms.{algorithm_name}")
self.settings.fix_history(algorithm_name=algorithm_name, algorithm_values=algorithm_values)
self.settings.set("current_algorithm", history.roi_extraction_parameters["algorithm_name"])
self.settings.set(
Expand Down
6 changes: 4 additions & 2 deletions package/PartSeg/_roi_analysis/partseg_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -79,7 +79,7 @@ def _image_changed(self):
def get_project_info(self) -> ProjectTuple:
algorithm_name = self.last_executed_algorithm
if algorithm_name:
value = self.get(f"algorithms.{algorithm_name}")
value = self.get_algorithm(f"algorithms.{algorithm_name}")
if isinstance(value, EventedDict):
value = value.as_dict_deep()
algorithm_val = {
Expand Down Expand Up @@ -125,7 +125,9 @@ def set_project_info(self, data: typing.Union[ProjectTuple, MaskInfo, PointsInfo
self.set_history(data.history[:])
if data.algorithm_parameters:
self.last_executed_algorithm = data.algorithm_parameters["algorithm_name"]
self.set(f"algorithms.{self.last_executed_algorithm}", deepcopy(data.algorithm_parameters["values"]))
self.set_algorithm(
f"algorithms.{self.last_executed_algorithm}", deepcopy(data.algorithm_parameters["values"])
)
self.algorithm_changed.emit()

def get_save_list(self) -> typing.List[SaveSettingsDescription]:
Expand Down
2 changes: 1 addition & 1 deletion package/PartSeg/_roi_mask/stack_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def set_segmentation_result(self, result: ROIExtractionResult):
self._additional_layers = result.additional_layers
self.additional_layers_changed.emit()
self.last_executed_algorithm = result.parameters.algorithm
self.set(f"algorithms.{result.parameters.algorithm}", result.parameters.values)
self.set_algorithm(f"algorithms.{result.parameters.algorithm}", result.parameters.values)
self._set_roi_info(result.roi_info, True, [], parameters_dict)
if result.points is not None:
self.points = result.points
Expand Down
58 changes: 41 additions & 17 deletions package/PartSeg/common_backend/base_settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from PartSegCore import register
from PartSegCore.color_image import default_colormap_dict, default_label_dict
from PartSegCore.color_image.base_colors import starting_colors
from PartSegCore.io_utils import find_problematic_entries, load_matadata_part, load_metadata_base
from PartSegCore.io_utils import find_problematic_entries, load_metadata_base
from PartSegCore.json_hooks import PartSegEncoder
from PartSegCore.project_info import AdditionalLayerDescription, HistoryElement, ProjectInfoBase
from PartSegCore.roi_info import ROIInfo
Expand Down Expand Up @@ -459,6 +459,7 @@ def __init__(self, json_path: Union[Path, str], profile_name: str = "default"):
self.napari_settings: "NapariSettings" = napari_get_settings(napari_path)
self._current_roi_dict = profile_name
self._roi_dict = ProfileDict()
self._last_algorithm_dict = ProfileDict()
self.json_folder_path = json_path
self.last_executed_algorithm = ""
self.history: List[HistoryElement] = []
Expand Down Expand Up @@ -510,7 +511,7 @@ def set_segmentation_result(self, result: ROIExtractionResult):

self._additional_layers = result.additional_layers
self.last_executed_algorithm = result.parameters.algorithm
self.set(f"algorithms.{result.parameters.algorithm}", result.parameters.values)
self.set_algorithm(f"algorithms.{result.parameters.algorithm}", result.parameters.values)
# Fixme not use EventedDict here
try:
roi_info = result.roi_info.fit_to_image(self.image)
Expand Down Expand Up @@ -583,6 +584,7 @@ def get_save_list(self) -> List[SaveSettingsDescription]:
return [
SaveSettingsDescription("segmentation_settings.json", self._roi_dict),
SaveSettingsDescription("view_settings.json", self.view_settings_dict),
SaveSettingsDescription("algorithm_settings.json", self._last_algorithm_dict),
]

def get_path_history(self) -> List[str]:
Expand Down Expand Up @@ -643,6 +645,14 @@ def set(self, key_path: str, value):
:param key_path: dot separated path
:param value: value to store. The value need to be json serializable.
"""
if (
key_path.startswith("algorithms.")
or key_path.startswith("algorithm_widget_state.")
or key_path == "current_algorithm"
):
warnings.warn("Use `set_algorithm_state` instead of `set` for algorithm state", FutureWarning, stacklevel=2)
self.set_algorithm(key_path, value)
return
self._roi_dict.set(f"{self._current_roi_dict}.{key_path}", value)

def get(self, key_path: str, default=None):
Expand All @@ -653,8 +663,36 @@ def get(self, key_path: str, default=None):
:param key_path: dot separated path
:param default: default value if key is missed
"""
if (
key_path.startswith("algorithms.")
or key_path.startswith("algorithm_widget_state.")
or key_path == "current_algorithm"
):
warnings.warn("Use `set_algorithm_state` instead of `set` for algorithm state", FutureWarning, stacklevel=2)
return self.get_algorithm(key_path, default)
return self._roi_dict.get(f"{self._current_roi_dict}.{key_path}", default)

def set_algorithm(self, key_path: str, value):
"""
function for saving last algorithm used information. This is accessor to
:py:meth:`~.ProfileDict.set` of inner variable.
:param key_path: dot separated path
:param value: value to store. The value need to be json serializable.
"""
# if key_path.startswith("")
self._last_algorithm_dict.set(f"{self._current_roi_dict}.{key_path}", value)

def get_algorithm(self, key_path: str, default=None):
"""
Function for getting last algorithm used information. This is accessor to
:py:meth:`~.ProfileDict.get` of inner variable.
:param key_path: dot separated path
:param default: default value if key is missed
"""
return self._last_algorithm_dict.get(f"{self._current_roi_dict}.{key_path}", default)

def connect_(self, key_path, callback):
# TODO fixme fix when introduce switch profiles
self._roi_dict.connect(key_path, callback)
Expand All @@ -667,21 +705,6 @@ def dump_part(self, file_path, path_in_dict, names=None):
with open(file_path, "w", encoding="utf-8") as ff:
json.dump(data, ff, cls=self.json_encoder_class, indent=2)

@classmethod
def load_part(cls, data: Union[Path, str]) -> Tuple[dict, List[str]]: # pragma: no cover
"""
Load serialized data. Get valid entries.
:param data: path to file or string to be decoded.
:return:
"""
warnings.warn(
f"{cls.__name__}.load_part is deprecated. Please use PartSegCore.utils.load_matadata_part",
stacklevel=2,
category=FutureWarning,
)
return load_matadata_part(data)

def dump(self, folder_path: Union[Path, str, None] = None):
"""
Save current application settings to disc.
Expand Down Expand Up @@ -753,6 +776,7 @@ def load(self, folder_path: Union[Path, str, None] = None):
timestamp = datetime.now().strftime("%Y-%m-%d_%H_%M_%S")
base_path, ext = os.path.splitext(file_path)
os.rename(file_path, f"{base_path}_{timestamp}{ext}")

return errors_dict

def get_project_info(self) -> ProjectInfoBase:
Expand Down
Loading

0 comments on commit 54958d1

Please sign in to comment.