From 305966ddfef9e3fbd23e57f7bfc200e233b56357 Mon Sep 17 00:00:00 2001 From: ehennestad Date: Mon, 9 Nov 2026 08:19:11 +0100 Subject: [PATCH 1/2] fix(path): change only the file name when deriving a related file path Several places derived a file path with strrep(filePath, '.mat', ...), which replaces the text anywhere in the path. A folder name containing it was rewritten too, as with ~/.matlab on Linux. The new nansen.util.path.appendToFilename adds a suffix before the extension, and paths that change extension use changeFilenameExtension. Removing the extension for a one-file-per-item catalog folder uses fileparts. strrep also left a path without the expected extension unchanged, so the classifier apps could write a cleaned file over the original. appendToFilename always changes the name. MotionCorrection keeps converting only .mat to .tif, so it checks the extension before calling the helper. Co-Authored-By: Claude Opus 5.5 --- .../+project/@ProjectManager/ProjectManager.m | 2 +- code/+nansen/+dataio/FileAdapter.m | 2 +- .../@MotionCorrection/MotionCorrection.m | 7 ++- code/+nansen/+util/+path/appendToFilename.m | 23 ++++++++ code/apps/+mclassifier/manualClassifier.m | 4 +- .../+nansen/@TaskProcessor/TaskProcessor.m | 2 +- code/apps/+roiclassifier/@App/App.m | 2 +- .../+nansen/+stack/+virtual/SciScanRaw.m | 4 +- code/general/+utility/+data/StorableCatalog.m | 12 +++- .../+roimanager/resources/icons/saveIcon.m | 2 +- tests/+nansen/+unittest/+util/PathUtilTest.m | 57 ++++++++++++++++++- 11 files changed, 102 insertions(+), 15 deletions(-) create mode 100644 code/+nansen/+util/+path/appendToFilename.m diff --git a/code/+nansen/+config/+project/@ProjectManager/ProjectManager.m b/code/+nansen/+config/+project/@ProjectManager/ProjectManager.m index cd59a6c1..31855043 100644 --- a/code/+nansen/+config/+project/@ProjectManager/ProjectManager.m +++ b/code/+nansen/+config/+project/@ProjectManager/ProjectManager.m @@ -704,7 +704,7 @@ function saveCatalog(obj) save(obj.CatalogPath, 'projectCatalog') elseif obj.CatalogSaveFormat == "json" jsonStr = jsonencode(projectCatalog, 'PrettyPrint', true); - jsonPath = replace(obj.CatalogPath, '.mat', '.json'); + jsonPath = nansen.util.path.changeFilenameExtension(obj.CatalogPath, '.json'); fid = fopen(jsonPath, 'w'); fwrite(fid, jsonStr); fclose(fid); diff --git a/code/+nansen/+dataio/FileAdapter.m b/code/+nansen/+dataio/FileAdapter.m index d0ed22ce..1f8cc2fb 100644 --- a/code/+nansen/+dataio/FileAdapter.m +++ b/code/+nansen/+dataio/FileAdapter.m @@ -536,7 +536,7 @@ function initializeMetadata(obj) if isTemporary filepathMat = [tempname, '.mat']; else - filepathMat = strrep(filepathNpy, '.npy', '.mat'); + filepathMat = nansen.util.path.changeFilenameExtension(filepathNpy, '.mat'); end if ispc diff --git a/code/+nansen/+processing/@MotionCorrection/MotionCorrection.m b/code/+nansen/+processing/@MotionCorrection/MotionCorrection.m index 4ab7e687..fe6290a6 100644 --- a/code/+nansen/+processing/@MotionCorrection/MotionCorrection.m +++ b/code/+nansen/+processing/@MotionCorrection/MotionCorrection.m @@ -441,7 +441,10 @@ function openTargetStack(obj, stackSize, dataType, ~) if ~isfolder(folderPath); mkdir(folderPath); end % Force file to be saved as .tif if extension was set to .mat - filePath = strrep(filePath, '.mat', '.tif'); + [~, ~, extension] = fileparts(filePath); + if strcmp(extension, '.mat') + filePath = nansen.util.path.changeFilenameExtension(filePath, '.tif'); + end % Call method of ImageStackProcessor openTargetStack@nansen.stack.ImageStackProcessor(obj, filePath, ... @@ -811,7 +814,7 @@ function resaveRGBProjectionImages(obj, projectionType) rgbArray = imArray; rgbArray(:, :, 3, :) = 0; - newFilepath = strrep(filepath, '.tif', '_rgb.tif'); + newFilepath = nansen.util.path.appendToFilename(filepath, '_rgb'); nansen.stack.utility.mat2tiffstack( rgbArray, newFilepath, true ) % true to save as rgb. end diff --git a/code/+nansen/+util/+path/appendToFilename.m b/code/+nansen/+util/+path/appendToFilename.m new file mode 100644 index 00000000..cc373e39 --- /dev/null +++ b/code/+nansen/+util/+path/appendToFilename.m @@ -0,0 +1,23 @@ +function newFilename = appendToFilename(filename, suffix) +%appendToFilename Add text to the end of a file name, before its extension +% +% newFilename = appendToFilename(filename, suffix) returns filename with +% suffix inserted between the file name and its extension. +% +% Only the name of the file is changed. Folder names are left untouched, +% including when they contain the extension of the file. +% +% Example: +% nansen.util.path.appendToFilename('/data/my.mat.bak/x.mat', '_clean') +% % Returns '/data/my.mat.bak/x_clean.mat' +% +% See also nansen.util.path.changeFilenameExtension, fileparts, fullfile + + arguments + filename (1,:) char {mustBeNonempty} + suffix (1,:) char {mustBeNonempty} + end + + [folderPath, fileName, extension] = fileparts(filename); + newFilename = fullfile(folderPath, [fileName, suffix, extension]); +end diff --git a/code/apps/+mclassifier/manualClassifier.m b/code/apps/+mclassifier/manualClassifier.m index 166c0273..40524f47 100644 --- a/code/apps/+mclassifier/manualClassifier.m +++ b/code/apps/+mclassifier/manualClassifier.m @@ -1408,7 +1408,7 @@ function saveClassification(obj, ~, ~, varargin) S.(varNames{i}) = S.(varNames{i})(keep); end - savePath = strrep(savePath, '.mat', '_clean.mat'); + savePath = nansen.util.path.appendToFilename(savePath, '_clean'); save(savePath, '-struct', 'S') fprintf('Saved classification results to %s\n', savePath) @@ -1433,7 +1433,7 @@ function saveClassification(obj, ~, ~, varargin) case 'append _classified' pickFile = false; - savePath = strrep(obj.dataFilePath, '.mat', '_classified.mat'); + savePath = nansen.util.path.appendToFilename(obj.dataFilePath, '_classified'); otherwise return diff --git a/code/apps/+nansen/@TaskProcessor/TaskProcessor.m b/code/apps/+nansen/@TaskProcessor/TaskProcessor.m index df808508..93fb794f 100644 --- a/code/apps/+nansen/@TaskProcessor/TaskProcessor.m +++ b/code/apps/+nansen/@TaskProcessor/TaskProcessor.m @@ -376,7 +376,7 @@ function loadTaskLists(obj, filePath) catch ME % Back up file dateStr = char(datetime('now'), 'yyyyMMdd_HH_mm_ss'); - filePathBackup = strrep(filePath, '.mat', sprintf('corrupted_%s.mat', dateStr)); + filePathBackup = nansen.util.path.appendToFilename(filePath, sprintf('corrupted_%s', dateStr)); movefile(filePath, filePathBackup); warning('Could not load the task list. This might be due to the file being corrupt. The file is backed up, and the task list is reset. If you see this warning several times, please report!') diff --git a/code/apps/+roiclassifier/@App/App.m b/code/apps/+roiclassifier/@App/App.m index 2e8c4307..f0836f19 100644 --- a/code/apps/+roiclassifier/@App/App.m +++ b/code/apps/+roiclassifier/@App/App.m @@ -955,7 +955,7 @@ function saveClassification(obj, ~, ~, varargin) roiGroupStruct(i).roiClassification = tempRoiGroup(i).roiClassification(keep); end - savePath = strrep(savePath, '.mat', '_clean.mat'); + savePath = nansen.util.path.appendToFilename(savePath, '_clean'); % Save roigroup using roigroup fileadapter fileObj = nansen.dataio.fileadapter.roi.RoiGroup(savePath, '-w'); diff --git a/code/datatypes/+nansen/+stack/+virtual/SciScanRaw.m b/code/datatypes/+nansen/+stack/+virtual/SciScanRaw.m index e65d78bd..1c9e4477 100644 --- a/code/datatypes/+nansen/+stack/+virtual/SciScanRaw.m +++ b/code/datatypes/+nansen/+stack/+virtual/SciScanRaw.m @@ -225,7 +225,7 @@ function updateDataSize(obj) function metadata = getSciScanRecordingInfo(obj) %getSciScanRecordingInfo Get recording info from the sciscan ini file - inifilepath = strrep(obj.FilePath, '.raw', '.ini'); + inifilepath = nansen.util.path.changeFilenameExtension(obj.FilePath, '.ini'); inistring = fileread(inifilepath); metadata = struct(); @@ -408,7 +408,7 @@ function getChannelColors(obj) isValid = false; return; else rawFilePath = fullfile(L.folder, L.name); - iniFilePath = strrep(rawFilePath, '.raw', '.ini'); + iniFilePath = nansen.util.path.changeFilenameExtension(rawFilePath, '.ini'); end elseif isfile(pathStr) diff --git a/code/general/+utility/+data/StorableCatalog.m b/code/general/+utility/+data/StorableCatalog.m index 848455eb..fe243bc4 100644 --- a/code/general/+utility/+data/StorableCatalog.m +++ b/code/general/+utility/+data/StorableCatalog.m @@ -729,7 +729,7 @@ function parseVarargin(obj, varargin) function saveToFolder(obj, S) %saveToFolder Save catalog to a folder with one file per item % Make folder if it does not exist. - folderPath = strrep(obj.FilePath, '.mat', ''); + folderPath = obj.getItemFolderPath(); if ~isfolder(folderPath); mkdir(folderPath); end % Create and save a master list @@ -759,7 +759,7 @@ function saveToFolder(obj, S) % Note: will be slower than loading from single file, but is more % modular, in that its easier to add and remove items. - folderPath = strrep(obj.FilePath, '.mat', ''); + folderPath = obj.getItemFolderPath(); L = dir(fullfile(folderPath, '*.mat')); @@ -780,6 +780,14 @@ function saveToFolder(obj, S) S.Data = cat(2, itemArray{:}); end + + function folderPath = getItemFolderPath(obj) + %getItemFolderPath Folder of a one-file-per-item catalog + % + % The folder is named after the catalog file and sits beside it. + [parentFolder, catalogName] = fileparts(obj.FilePath); + folderPath = fullfile(parentFolder, catalogName); + end end methods (Static) diff --git a/code/tools/+roimanager/resources/icons/saveIcon.m b/code/tools/+roimanager/resources/icons/saveIcon.m index 8a49b20f..58997ff9 100644 --- a/code/tools/+roimanager/resources/icons/saveIcon.m +++ b/code/tools/+roimanager/resources/icons/saveIcon.m @@ -33,7 +33,7 @@ function saveIcon(iconName) hV.Height = hV.Height/hV.Height; S.imageVector = hV.getVectorStruct; - savePath = strrep(loadPath, '.png', '.mat'); + savePath = nansen.util.path.changeFilenameExtension(loadPath, '.mat'); save(savePath, '-struct', 'S') end diff --git a/tests/+nansen/+unittest/+util/PathUtilTest.m b/tests/+nansen/+unittest/+util/PathUtilTest.m index 6cb30f68..1e2fcc55 100644 --- a/tests/+nansen/+unittest/+util/PathUtilTest.m +++ b/tests/+nansen/+unittest/+util/PathUtilTest.m @@ -1,14 +1,67 @@ classdef PathUtilTest < matlab.unittest.TestCase %PathUtilTest Unit tests for nansen.util.path utilities. % - % Covers changeFilenameExtension, which must replace only the - % extension of the file name and never alter folder names. + % Covers changeFilenameExtension and appendToFilename, which must + % change only the name of the file and never alter folder names. % % Run tests: % runtests('nansen.unittest.util.PathUtilTest') methods (Test) + % ---------------------------------------------------------------- + % appendToFilename + % ---------------------------------------------------------------- + + function testSuffixGoesBeforeTheExtension(testCase) + inputPath = fullfile('/data', 'rois.mat'); + expected = fullfile('/data', 'rois_clean.mat'); + + actual = nansen.util.path.appendToFilename(inputPath, '_clean'); + + testCase.verifyEqual(actual, expected); + end + + function testSuffixIsAddedForAnyExtension(testCase) + % A path without the expected extension must still change, so + % that a derived file can not overwrite the one it came from. + actual = nansen.util.path.appendToFilename('rois.h5', '_clean'); + + testCase.verifyEqual(actual, 'rois_clean.h5'); + end + + function testSuffixLeavesFoldersContainingTheExtensionAlone(testCase) + inputPath = fullfile('/home', '.matlab', 'archive.mat.bak', 'rois.mat'); + expected = fullfile('/home', '.matlab', 'archive.mat.bak', 'rois_clean.mat'); + + actual = nansen.util.path.appendToFilename(inputPath, '_clean'); + + testCase.verifyEqual(actual, expected); + end + + function testSuffixGoesBeforeTheFinalExtensionOnly(testCase) + actual = nansen.util.path.appendToFilename('rois.mat.mat', '_clean'); + + testCase.verifyEqual(actual, 'rois.mat_clean.mat'); + end + + function testSuffixIsAddedToANameWithoutExtension(testCase) + actual = nansen.util.path.appendToFilename('rois', '_clean'); + + testCase.verifyEqual(actual, 'rois_clean'); + end + + function testAppendAcceptsStringAndReturnsChar(testCase) + actual = nansen.util.path.appendToFilename("rois.mat", "_clean"); + + testCase.verifyEqual(actual, 'rois_clean.mat'); + end + + function testAppendRejectsEmptyInput(testCase) + testCase.verifyError(@() nansen.util.path.appendToFilename('', '_clean'), ... + 'MATLAB:validators:mustBeNonempty'); + end + % ---------------------------------------------------------------- % changeFilenameExtension - ordinary use % ---------------------------------------------------------------- From 4ddde74c7e1f1bb1663cba60df246892cb0036eb Mon Sep 17 00:00:00 2001 From: ehennestad Date: Mon, 9 Nov 2026 08:31:28 +0100 Subject: [PATCH 2/2] refactor(mclassifier): keep manualClassifier free of the nansen namespace The mclassifier package does not depend on the nansen namespace, so manualClassifier now has its own local appendToFilename. Co-Authored-By: Claude Opus 5.5 --- code/apps/+mclassifier/manualClassifier.m | 19 +++++++++++++++++-- 1 file changed, 17 insertions(+), 2 deletions(-) diff --git a/code/apps/+mclassifier/manualClassifier.m b/code/apps/+mclassifier/manualClassifier.m index 40524f47..3062ebee 100644 --- a/code/apps/+mclassifier/manualClassifier.m +++ b/code/apps/+mclassifier/manualClassifier.m @@ -1408,7 +1408,7 @@ function saveClassification(obj, ~, ~, varargin) S.(varNames{i}) = S.(varNames{i})(keep); end - savePath = nansen.util.path.appendToFilename(savePath, '_clean'); + savePath = appendToFilename(savePath, '_clean'); save(savePath, '-struct', 'S') fprintf('Saved classification results to %s\n', savePath) @@ -1433,7 +1433,7 @@ function saveClassification(obj, ~, ~, varargin) case 'append _classified' pickFile = false; - savePath = nansen.util.path.appendToFilename(obj.dataFilePath, '_classified'); + savePath = appendToFilename(obj.dataFilePath, '_classified'); otherwise return @@ -1677,6 +1677,21 @@ function removeFocusFromControl(h) end end +function newFilename = appendToFilename(filename, suffix) +%appendToFilename Add text to the end of a file name, before its extension +% +% This package does not depend on the nansen namespace, so it keeps its +% own copy of nansen.util.path.appendToFilename. + + arguments + filename (1,:) char {mustBeNonempty} + suffix (1,:) char {mustBeNonempty} + end + + [folderPath, fileName, extension] = fileparts(filename); + newFilename = fullfile(folderPath, [fileName, suffix, extension]); +end + function str = pval2str(pval, numSignificantValues) %pval2str Format a pvalue as a string