diff --git a/ShoulderCase/Acromion.m b/ShoulderCase/Acromion.m index c4b6868..457db77 100644 --- a/ShoulderCase/Acromion.m +++ b/ShoulderCase/Acromion.m @@ -1,214 +1,216 @@ classdef Acromion < handle %ACROMION Properties and methods associted to the acromion. % Detailed explanation goes here properties AI % Acromion Inddex (doi:10.2106/JBJS.D.03042) CSA % Critital Shoulder Angle (doi:10.1302/0301-620X.95B7.31028) PSA % Posterior Slope Angle (10.1016/S1058-2746(05)80036-9) PSL % Length of segment beteeen AA and AC AAA % Angulus Angle Angle (Angle between AA-origin and PA axis) AAL % Length of segment between origine and AA AAx % PA (x) position of AA AAy % IS (y) position of AA AAz % ML (z) position of AA ACx % PA (x) position of AC ACy % IS (y) position of AC ACz % ML (z) position of AC comment end properties (Hidden = true) SCase scapula end methods (Access = ?Scapula) % Only Scapula is allowed to construct a Acromion function obj = Acromion(SCase) %ACROMION Construct an instance of this class % Instance of the acromion objet set all properties to zero; obj.AI = []; obj.CSA = []; obj.PSA = []; obj.PSL = []; obj.AAA = []; obj.AAL = []; obj.AAx = []; obj.AAy = []; obj.AAz = []; obj.ACx = []; obj.ACy = []; obj.ACz = []; obj.comment = ''; obj.SCase = SCase; obj.scapula = []; end end methods function outputArg = morphology(obj) %MORPHOLOGY Performs morphology analysis of the acromion. % It caluculates acromion index (AI), critical shoulder angle % (CSA), and posterior slope (PS). The glenoid and scapula % surface are re-oriented (rotated and translated) in the % scapular coordinate system. For AI nd CSA, glenoid and % scapula points are projected in the scapular plane, which is % [1 0 0] after the re-orientation. % TODO: % Might be removed anatomy for concistency SCase = obj.SCase; %% Get local coordinate system from parent scapula origin = obj.scapula.coordSys.origin; xAxis = obj.scapula.coordSys.PA; yAxis = obj.scapula.coordSys.IS; zAxis = obj.scapula.coordSys.ML; % Rotation matrix to align to scapula coordinate system R = [xAxis' yAxis', zAxis']; %% Scapula, glenoid, and scapula landmarks in scapula coordinate system % Scapula surface alignment is done in next section, for the % caulation of AI, because of mix between auto, manual and no % segmentation. This should be corrected when there will be two % scapula object per shoulder (manual and auto). % Glenoid surface in scapular coordinate system glenSurf = (obj.scapula.glenoid.surface.points - origin) * R; % Glenoid center in scapular coordinate system glenCenter = (obj.scapula.glenoid.center - origin) * R; % Scapula landmarks in scapular coordinate system AC = (obj.scapula.acromioClavicular - origin) * R; % Acromio-clavicular landmark AA = (obj.scapula.angulusAcromialis - origin) * R; % Angulus acromialis landmark obj.ACx = AC(1); obj.ACy = AC(2); obj.ACz = AC(3); obj.AAx = AA(1); obj.AAy = AA(2); obj.AAz = AA(3); %% Acromion Index (AI) % Adapted by AT (2018-07-18) from Valerie Mafroy Camine (2017) % AI = GA/GH, where: % GA: GlenoAcromial distance in scapula plane = distance from % AL to glenoid principal axis % GH: GlenoHumeral distance = 2*HHRadius, humeral head diameter (radius*2) % AL: most lateral point of the acromion % Get all required data, aligned in scapular plane, and % project in scapular plane. ScapPlaneNormal = [1 0 0]; % Normal of the scapular plane in the scapular coordinate system PlaneMean = [0 0 0]; % Origin of scapular system in scapular coordinate system % Project glenoid surface in scapular plane glenSurf = project2Plane(glenSurf,ScapPlaneNormal,PlaneMean,size(glenSurf,1)); % Project glenoid center in scapular plane glenCenter = project2Plane(glenCenter,ScapPlaneNormal,PlaneMean,size(glenCenter,1)); % If scapula is segmented, get AL from most lateral part of the % scapula, otherwise use acromio-clavicular landmark % Get segmentation propertiy from parent scapula segmentedScapula = obj.scapula.segmentation; segmentedScapula = strcmp(segmentedScapula,'A') || strcmp(segmentedScapula,'M'); if segmentedScapula == 1 % Rotate scapula surface to align the scapular plane with % the YZ plane, and then take the max Z (lateral) point % Transform scapula surface to scapula coordinate system scapSurf = obj.scapula.surface.points; scapSurf = (scapSurf - origin) * R; scapSurf = project2Plane(scapSurf,ScapPlaneNormal,PlaneMean,size(scapSurf,1)); % Take the most lateral point of the scapula, assuming that % this point is the most lateral point of the acromion [~,ALpositionInScapula] = max(scapSurf(:,3)); AL = scapSurf(ALpositionInScapula,:); else % No scapula points, we approximate AL with the acromioClavicular % landmark, in the scapula coordinate system AL = AC; % Acroomio-clavicalar scapula landmark AL = project2Plane(AL,ScapPlaneNormal,PlaneMean,size(AL,1)); end % Find glenoid principal axis with most superior and most inferior projected % glenoid points % AT: This method is not ideal. PCA would be better. It is also % used below by the CSA glenPrinAxis = [... glenSurf(glenSurf(:,2) == min(glenSurf(:,2)),:) ;... glenSurf(glenSurf(:,2) == max(glenSurf(:,2)),:)... ]; % Compute GA (distance from AL to glenoid principal axis) % Most inferior point of the scapula surface IG = glenPrinAxis(1, :); % Most superior point of the scapula surface SG = glenPrinAxis(2, :); GA = norm(cross(SG - IG, AL - IG))/norm(SG - IG); % GH (Humeral head diameter) % get humeral head radius from associated humerus GH = 2 * SCase.shoulder.humerus.radius; % Acromion index - obj.AI = GA/GH; + if ~isempty(GH) + obj.AI = GA/GH; + end %% Critical Shoulder Angle (CSA) % Adapted by AT (2018-07-18) from Bharath Narayanan (2018) % [radCSA, degCSA] = computeCSA(GlenoidPtsinScapulaPlane, ALinScapulaPlane); % Vectors connecting IG to SG, and IG to AL IGSG = SG - IG; IGAL = AL - IG; CSA = vrrotvec(IGSG,IGAL); CSA = CSA(4); CSA = rad2deg(CSA); obj.CSA = CSA; %% Posterior Slope Angle and length (PSA & PSL) % By AT (2018-08-10) % Project AA & AC in PA-IS plane AAxy = [AA(1:2) 0]; % Juste take x and y component ACxy = [AC(1:2) 0]; % Juste take x and y component PSv = ACxy - AAxy; % Posterior slope vector ISv = [1 0 0]; % IS axis PSA = vrrotvec(PSv, ISv); PSA = PSA(4); PSA = rad2deg(PSA); PSL = norm(PSv); obj.PSA = PSA; obj.PSL = PSL; %% Acromial Angle Angle and length (AAA & AAL) % By AT (2018-09-13) % Vector between scapular origin and AA in the plane PA-IS AAv = [AA(1:2) 0]; % Angle between AAvect and PA axis PAv = [1 0 0]; % PS axis AAA = vrrotvec(AAv, PAv); AAA = AAA(4); AAA = rad2deg(AAA); AAA = 180 - AAA; AAL = norm(AAv); obj.AAA = AAA; obj.AAL = AAL; %% We might save an image of AI, CSA, PS outputArg = 1; end end end diff --git a/ShoulderCase/Humerus.m b/ShoulderCase/Humerus.m index d253caf..8ba5343 100644 --- a/ShoulderCase/Humerus.m +++ b/ShoulderCase/Humerus.m @@ -1,258 +1,258 @@ classdef Humerus < handle %HUMERUS Properties and methods associated to the humerus % Detailed explanation goes here % Author: Alexandre Terrier, EPFL-LBO % Creation date: 2018-07-01 % Revision date: 2019-06-29 % % TO DO: % Local coordinate system properties landmarks % 5 3D points center % Center of the humeral head (sphere fit on 5 points radius % Radius of the humeral head (sphere fit on 5 points jointRadius % Radius of cuvature of the articular surface (todo) SHSAngle % Scapulo-humeral subluxation angle SHSPA % Scapulo-humeral subluxation angle in the postero-anterior direction (posterior is negative, as for glenoid version) SHSIS % Scapulo-humeral subluxation angle in the infero-superior direction SHSAmpl % Scapulo-humeral subluxation (center ofset / radius) SHSOrient % Scapulo-humral subluxation orientation (0 degree is posterior) GHSAmpl % Gleno-humeral subluxation (center ofset / radius) GHSOrient % Gleno-humral subluxation orientation (0 degree is posterior) end properties (Hidden = true) SCase end methods (Access = ?Shoulder) % Only Shoulder is allowed to construct Humerus function obj = Humerus(SCase) %HUMERUS Construct an instance of this class % Detailed explanation goes here obj.landmarks = []; obj.center = []; obj.radius = []; obj.jointRadius = []; obj.SHSAngle = []; obj.SHSPA = []; obj.SHSIS = []; obj.SHSAmpl = []; obj.SHSOrient = []; obj.GHSAmpl = []; obj.GHSOrient = []; obj.SCase = SCase; end end methods function outputArg = load(obj) %LOAD Load 5 humeral head landmarks % TODO: Should be check for 'old' vs 'new' file definition SCase = obj.SCase; SCaseId4C = SCase.id4C; amiraDir = SCase.dataAmiraPath; % Try 1st with new defiunition of HHLandmarks fileName = ['newHHLandmarks' SCaseId4C '.landmarkAscii']; fileName = [amiraDir '/' fileName]; if exist(fileName,'file') == 2 importedData = importdata(fileName, ' ', 14); else % Check for old version of HHLandmarks fileName = ['HHLandmarks' SCaseId4C '.landmarkAscii']; fileName = [amiraDir '/' fileName]; if exist(fileName,'file') == 2 importedData = importdata(fileName, ' ', 14); - warning([SCaseId4C ' is using old humeral landmarks definition']) + warning([SCaseId4C ' is using old humeral landmarks definition']) else - error('MATLAB:rmpath:DirNotFound',... - 'Could not find file: %s',fileName) + outputArg = 0; + return end end % with other methods % Check validity of data in file % Variable points belos should be renamed landmarks, for consistency try points = importedData.data; catch % Cant get landarks from file warning([SCaseId4C ' cant load humeral landmarks']) outputArg = 0; return; end % We should add a test for validity of points obj.landmarks = points; outputArg = 1; % Should report on loading result end function outputArg = subluxation(obj,scapula) % Calcul of humeral head subluxation % The function also get center and radius of the humeral head. % TODO: % Calcul would be simpler in the scapular cordinate system, as % done in Acromion object. % Radius of curvature of humeral head articular surface % Might be removed anatomy for concistency SCase = obj.SCase; %% Get data from parent shoulder object % Shoulder side side = SCase.shoulder.side; %% Get data from parent scapula object % Scapula coordinate system xAxis = scapula.coordSys.PA; yAxis = scapula.coordSys.IS; zAxis = scapula.coordSys.ML; %% Get data from parent glenoid object % Glenoid center glenCenter = scapula.glenoid.center; % Glenoid centerLine from parent glenoid object glenCenterline = scapula.glenoid.centerLine; %% Get data from humerus % humeral head landmarks (5 or ?) humHead = obj.landmarks; % Humeral head landmarks %% Anatomical measurements % Fit sphere on humeral head landmarks [humHeadCenter,humHeadRadius,HHResiduals, R2HH] = fitSphere(humHead); humHeadCenter = humHeadCenter'; % transform vertical to horizantal vector %% Scapulo-humeral subluxation (SHS) % Vector from glenoid center to humeral head center SHSvect = humHeadCenter - glenCenter; % Vector from humeral head center to scapular (z) axis, % perpendicular to z-axis --> similar to projection in xy plane % This might be rewritten more clearly SHSvectxy = SHSvect - (dot(SHSvect,zAxis)*zAxis); % SHS amplitude (ratio rather than amplitude) SHSAmpl = norm(SHSvectxy) / humHeadRadius; % SHS orientation xProj = dot(SHSvectxy, xAxis); yProj = dot(SHSvectxy, yAxis); if xProj > 0 % anterior side if yProj > 0 % ant-sup quadran SHSOrient = pi - atan(yProj/xProj); else % ant-inf quadran SHSOrient = -pi - atan(yProj/xProj); end elseif xProj < 0 % posterior side SHSOrient = - atan(yProj/xProj); else % xProj = 0 SHSOrient = pi/2 - pi * (yProj < 0); end SHSOrient = rad2deg(SHSOrient); % SHSAngle: angle between glenHumHead and zAxis SHSAngle = vrrotvec(SHSvect,zAxis); SHSAngle = SHSAngle(4); SHSAngle = rad2deg(SHSAngle); % SHSAP is angle between zxProjection and zAxis % Project glenHumHead on yAxis yProjVect = dot(SHSvectxy, yAxis)*yAxis; % Remove projection from glenHumHead --> zxProjection glenHumHeadzx = SHSvect - yProjVect; a = glenHumHeadzx; b = zAxis; rotVect4 = vrrotvec(a,b); % Unit rotation vector to align a to b rotVect3 = rotVect4(1:3); rotAngle = rotVect4(4); rotSign = sign(dot(rotVect3,yAxis)); % Sign of rotation SHSPA = rotAngle * rotSign; SHSPA = -SHSPA; % Convention that posterior is negative if strcmp(side,'L') % Change signe for left-handed scapula coordinate system SHSPA = -SHSPA; end SHSPA = rad2deg(SHSPA); % Angle in degrees % SHSIS is angle between yzProjection and zAxis % Project glenHumHead on xAxis xProjVect = dot(SHSvectxy, xAxis)*xAxis; % Remove projection from glenHumHead --> yzProjection glenHumHeadyz = SHSvect - xProjVect; a = glenHumHeadyz; b = zAxis; rotVect4 = vrrotvec(a,b); % Unit rotation vector to align a to b rotVect3 = rotVect4(1:3); rotAngle = rotVect4(4); rotSign = sign(dot(rotVect3,xAxis)); % Sign of rotation SHSIS = rotAngle * rotSign; SHSIS = SHSIS; % Convention that superior is positive if strcmp(side,'L') % Change signe for left-handed scapula coordinate system SHSIS = -SHSIS; end SHSIS = rad2deg(SHSIS); % Angle in degrees %% Angle between plane of maximum SH subluxation and CT axis [0,0,1] % Not used anymore % SHSPlane = cross(glenHumHead, zAxis); % G = vrrotvec(SHSPlane, [0 0 1]); % SHSPlaneAngle = rad2deg(G(4)); % if SHSPlaneAngle > 90 % SHSPlaneAngle = 180 - SHSPlaneAngle; % end %% Gleno-humeral subluxation (GHS) % Vector from glenoid sphere centre to glenoid centerline (perpendicular) glenCenterlineNorm = glenCenterline/norm(glenCenterline); GHS = SHSvect - dot(SHSvect, glenCenterlineNorm)*glenCenterlineNorm; % GHS amplitude GHSAmpl = norm(GHS) / humHeadRadius; % GHS orientation xProj = dot(GHS, -xAxis); yProj = dot(GHS, yAxis); if xProj ~= 0 if yProj ~= 0 GHSOrient = atan(yProj/xProj); else GHSOrient = pi * (xProj > 0); end else GHSOrient = pi/2 - pi * (yProj > 0); end GHSOrient = rad2deg(GHSOrient); %% Angle between plane of maximum GH subluxation and CT axis [0,0,1] % Not used anymore % GHSPlane = cross(glenCenterline, glenHumHead); % GHSPlaneAngle = vrrotvec(GHSPlane, [0 0 1]); % GHSPlaneAngle = rad2deg(GHSPlaneAngle(4)); % if GHSPlaneAngle > 90 % GHSPlaneAngle = 180 - GHSPlaneAngle; % end %% Set humerus properties obj.center = humHeadCenter; obj.radius = humHeadRadius; obj.SHSAngle = SHSAngle; obj.SHSPA = SHSPA; obj.SHSIS = SHSIS; obj.SHSAmpl = SHSAmpl; obj.SHSOrient = SHSOrient; obj.GHSAmpl = GHSAmpl; obj.GHSOrient = GHSOrient; % Commented ince not used % outputArgStruct = struct('HHResiduals',HHResiduals,'R2HH',R2HH); % Useful? outputArg = 1; end end end diff --git a/measureSCase.m b/measureSCase.m index 6c9e68e..0cf370a 100755 --- a/measureSCase.m +++ b/measureSCase.m @@ -1,675 +1,677 @@ function [status,message] = measureSCase(varargin) % MEASURESCASE Update the entire SCase DB with anatomical measurements. % The function can be run from (lbovenus) server with the following shell command % cd /home/shoulder/methods/matlab/database; matlab -nodisplay -nosplash -r "measureSCase;quit" % Progress can be checked through log file with following shell command % cd /home/shoulder/methods/matlab/database;tail -f log/measureSCase.log % It take ~30 min for 700 cases when run from server. % After run from server, the output file % /shoulder/data/Excel/xlsFromMatlab/anatomy.csv % must be open from Excel and saved % as xls at the same location. Excel file % /shoulder/data/Excel/ShoulderDataBase.xlsx should also be open, updated, and saved. % The script measureSCase was replacing 3 previous functions % 1) rebuildDatabaseScapulaMeasurements.m --> list of all SCases --> execute scapula_measure.m % 2) scapula_measure.m --> execute scapula_calculation and save results in Excel and SQL % 3) scapula_calculation.m --> perform anatomical analysis --> results varaiable % Input arguments can be one or several among: % {Empty,'GlenoidDensity', 'update', '[NP][1-999]', '[NP]'} % % If there is no argument the function will measure every new case. % The last 'N' or 'P' given as an argument will force the function to be % executed on all the corresponding 'N' or 'P' cases. This will overwrite % every other ShoulderCase argument '[NP][1-999]' given before. % % Examples: % measureSCase('GlenoidDensity') % is a valid instruction where every new case is measured % including its glenoid density. % measureSCase('P400','N520') % is a valid instruction where the cases 'P400' and 'N520' are % measured only if they have not already been measured yet (new % cases). % measureSCase('P400','N520','update') % is a valid instruction where the cases 'P400' and 'N520' are % measured whether they have already been measured or not. % measureSCase('GlenoidDensity','P400','N520','update','P') % is a valid instruction where all the 'P' cases are measured % including their glenoid density whether they have been % measured or not. % measureSCase('Z1590','trollingArgumentLol') % is a valid instruction which raises a warning about the % arguments and will result in the same as executing % measureSCase() i.e. every new case is calculated. % Output % File /shoulder/data/Excel/xlsFromMatlab/anatomy.csv % File /shoulder/data/Excel/xlsFromMatlab/anatomy.xls (only windows) % File /home/shoulder/data/matlab/SCaseDB.mat % File {SCaseId}.mat in each {SCaseId}/{CT}/matlab directory % logs in /log/measureSCase.log % Example: measureSCase % Author: Alexandre Terrier, EPFL-LBO % Creation date: 2018-07-01 % Revision date: 2019-06-29 % TO DO: % Read first last anatomy.csv and/or SCaseDB.mat % Fill with patient and clinical data, from excel or MySQL % use argument to redo or update % Save csv within the main loop (not sure it's a good idea) % Add more message in log % Add more test to assess validity of data % Update MySQL % Rename all objects with a capital % Make it faster by not loading scapula surface if already in SCaseDB.mat % Add argument 'load' to force reload files even if they are alerady in DB % Add argument 'measure' to force re-measuring event if measurement is already in DB % Add "scapula_addmeasure.m" --> should be coded in ShoulderCase class startTime = datetime('now'); %% Open log file logFileID = openLogFile('measureSCase.log'); %% Set the data directory from the configuration file config.txt dataDir = openConfigFile('config.txt', logFileID); %% Location of the XLS ShoulderDatabase xlsDir = [dataDir '/Excel/xlsFromMatlab']; matlabDir = [dataDir '/matlab']; %% Get list of all SCase % Get list of SCases from varargin % Delault value for varargin calcGlenoidDensity = false; updateCalculations = false; specificCases = true; fprintf(logFileID, '\n\nList of SCase'); cases = {}; for argument = 1:nargin switch lower(varargin{argument}) % Test every argument in varargin. case 'glenoiddensity' calcGlenoidDensity = true; case 'update' updateCalculations = true; case regexp(lower(varargin{argument}),'[np]','match') specificCases = false; % Detect if argument is 'N' or 'P'. cases = {varargin{argument}}; % ends here. case regexp(lower(varargin{argument}),'[np][1-9][0-9]{0,2}','match') % Test for a correct argument [NP][1-999] if specificCases cases{end+1} = upper(varargin{argument}); % for element = 1:length(cases)-1 % Check if the case has already been added to the case list before if and( (upper(varargin{argument}(1))==cases{element}(1)),... % (upper(varargin{argument}(end-2:end))==cases{element}(end-2:end)) ) cases = cases(1:end-1); % Delete the last element added to cases if it is already in the list end end end otherwise warning(['\n "%s" is not a valid argument and has not been added to the'... ' list of cases.\n measureSCase arguments format must be "[npNP]",'... ' "[npNP][1-999]", "GlenoidDensity", or "update"'],varargin{argument}) end end SCaseList = listSCase(cases); %% Load current xls database (for clinical data) fprintf(logFileID, '\nLoad xls database\n\n'); addpath('XLS_MySQL_DB'); filename = [dataDir '/Excel/ShoulderDataBase.xlsx']; excelRaw = rawFromExcel(filename); % cell array excelSCaseID = excelRaw(2:end, 1); excelDiagnosis = excelRaw(2:end, 4); excelPatientHeight = excelRaw(2:end, 23); excelGlenoidWalch = excelRaw(2:end, 55); % Lines below adapted from XLS_MySQL_DB/MainExcel2XLS % Excel.diagnosisList = diagnosisListFromExcel(Excel.Raw); % Excel.treatmentList = treatmentListFromExcel(Excel.Raw); % ExcelData.Patient = patientFromExcel(excelRaw); % Structure with patient data % Excel.shoulder = shoulderFromExcel(Excel.patient, Excel.Raw); % [Excel.SCase, Excel.diagnosis, Excel.treatment, Excel.outcome, Excel.study] = SCaseFromExcel(... % Excel.shoulder, Excel.patient, Excel.diagnosisList, Excel.treatmentList, Excel.Raw); % fprintf(logFileID, ': OK'); %% Add path to ShoulderCase class addpath('ShoulderCase'); %% Instance of a ShoulderCase object if (exist('SCase','var') > 0) clear SCase; % Check for delete method end SCase = ShoulderCase; % Instanciate a ShoulderCase object SCaseDB = ShoulderCase; SCase.dataPath = dataDir; % Set dataDir for SCase %%%% definition of analysis variables % % % manual % ok = {}; amira = {}; scapulaLoad = {}; scapulaCoord = {}; degeneration = {}; glenoidLoad = {}; glenoidMorphology = {}; glenoidDensity = {}; humerusLoad = {}; humerusSubluxation = {}; acromionMorphology = {}; % % % auto % autoOk = {}; autoScapulaLoad = {}; autoScapulaCoord = {}; %autoDegeneration = {}; autoGlenoidLoad = {}; autoGlenoidMorphology = {}; autoGlenoidDensity = {}; %autoHumerusLoad = {}; %autoHumerusSubluxation = {}; autoAcromionMorphology = {}; % %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% %% Start loop over SCases in SCaseList nSCase = length(SCaseList); % Number of SCases for iSCaseID = 1:nSCase SCaseID = SCaseList(iSCaseID).id; SCase(iSCaseID).id = SCaseID; SCase(iSCaseID).dataPath = dataDir; % Set dataDir for SCase output = SCase(iSCaseID).path; % Set data path of this SCase percentProgress = num2str(iSCaseID/nSCase*100, '%3.1f'); fprintf(logFileID, ['\n___________________________________\n|\n| SCaseID: ' SCaseID ' (' percentProgress '%%)']); % There are 3 parts within this SCase loop: % 1) Load & analyses manual data from amira % 2) Load & analyses auto data from matlab (Statistical Shape Model) % 3) Load clinical data from Excel database, and set them to SCase % 4) Save SCase in file SCaseID/matlab/SCase.mat % 1) Load & analyses manual data from amira if (exist([SCase(iSCaseID).dataMatlabPath '/SCase.mat'],'file') && ~updateCalculations) % New calculation of SCase.mat or update the current calculation continue end while true tic; fprintf(logFileID, '\n| Segmentation manual '); if ~output % Continue if amira dir exists in SCase fprintf(logFileID, '\n| No amira folder'); amira{end+1} = SCaseID; break end fprintf(logFileID, '\n| Load scapula surface and landmarks'); output = SCase(iSCaseID).shoulder.scapula.load; if ~output fprintf(logFileID, ': ERROR'); scapulaLoad{end+1} = SCaseID; break end fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Set coord. syst.'); output = SCase(iSCaseID).shoulder.scapula.coordSysSet; if ~output fprintf(logFileID, ': ERROR'); scapulaCoord{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Load glenoid surface'); output = SCase(iSCaseID).shoulder.scapula.glenoid.load; if ~output fprintf(logFileID, '\n| glenoid surface loading error'); glenoidLoad{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Measure glenoid anatomy'); output = SCase(iSCaseID).shoulder.scapula.glenoid.morphology; if ~output fprintf(logFileID, ': ERROR'); glenoidMorphology{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); if calcGlenoidDensity fprintf(logFileID, '\n| Measure glenoid density'); output = SCase(iSCaseID).shoulder.scapula.glenoid.calcDensity; if ~output fprintf(logFileID, ': Density calculus error. Could not read dicom'); glenoidDensity{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); end fprintf(logFileID, '\n| Load humerus data'); output = SCase(iSCaseID).shoulder.humerus.load; if ~output fprintf(logFileID, ': ERROR'); humerusLoad{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Measure humerus subluxation'); output = SCase(iSCaseID).shoulder.humerus.subluxation(SCase(iSCaseID).shoulder.scapula); if ~output fprintf(logFileID, ': ERROR'); humerusSubluxation{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Measure acromion anatomy'); % Should be run after SCase.shoulder.humerus (for AI) output = SCase(iSCaseID).shoulder.scapula.acromion.morphology; if ~output fprintf(logFileID, ': ERROR'); acromionMorphology{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Measure muscle''s degeneration'); output = SCase(iSCaseID).shoulder.muscles.degeneration(logFileID); switch output % output is reversed here to differenciate different types of degeneration errors case 1 degeneration{1,end+1} = SCaseID; degeneration{2,end} = output; degeneration{3,end} = 'dicomRead() error'; break; case 2 degeneration{1,end+1} = SCaseID; degeneration{2,end} = output; degeneration{3,end} = 'slice() error'; break; case 3 degeneration{1,end+1} = SCaseID; degeneration{2,end} = output; degeneration{3,end} = 'slice is to small'; break; case 4 degeneration{1,end+1} = SCaseID; degeneration{2,end} = output; degeneration{3,end} = 'crop error'; break; case 5 degeneration{1,end+1} = SCaseID; degeneration{2,end} = output; degeneration{3,end} = 'imwrite() gave black image'; break; case 6 degeneration{1,end+1} = SCaseID; degeneration{2,end} = output; degeneration{3,end} = 'automatic segmentation error'; break; end fprintf(logFileID, ': OK'); ok{end+1} = SCaseID; % 2) Set clinical data from Excel database to SCase fprintf(logFileID, '\n| Set clinical data from Excel'); % Get idx of excelRaw for SCaseID % Use cell2struct when dots are removed from excel headers idx = find(strcmp(excelRaw, SCaseID)); % Index of SCaseID in excelRaw SCase(iSCaseID).diagnosis = excelRaw{idx,4}; SCase(iSCaseID).treatment = excelRaw{idx,9}; SCase(iSCaseID).patient.gender = excelRaw{idx,19}; SCase(iSCaseID).patient.age = excelRaw{idx,21}; SCase(iSCaseID).patient.height = excelRaw{idx,23}; SCase(iSCaseID).patient.weight = excelRaw{idx,24}; SCase(iSCaseID).patient.BMI = excelRaw{idx,25}; SCase(iSCaseID).shoulder.scapula.glenoid.walch = excelRaw{idx,55}; break; % Patient data --> TO DO % find patient id (in SQL) corresponding to iSCaseID % % % idxSCase = find(contains(ExcelData, SCaseID)); % SCase(iSCaseID).patient.id = ExcelData(idxSCase).patient.patient_id; % SQL patient id % SCase(iSCaseID).patient.idMed = ExcelData(idxSCase).patient.IPP; % IPP to be replace by coded (anonymized) IPP from SecuTrial % SCase(iSCaseID).patient.gender = ExcelData(idxSCase).patient.gender; % SCase(iSCaseID).patient.age = []; % Age (years) at treatment, or preop CT (we might also add birthdate wi day et at 15 of the month) % SCase(iSCaseID).patient.ethnicity = ExcelData(idxSCase).patient.IPP; % SCase(iSCaseID).patient.weight = ExcelData(idxSCase).patient.weight; % SCase(iSCaseID).patient.height = ExcelData(idxSCase).patient.height; % SCase(iSCaseID).patient.BMI = ExcelData(idxSCase).pateint.BMI; % SCase(iSCaseID).patient.comment = ExcelData(idxSCase).patient.comment; end fprintf(logFileID, '\n| Elapsed time (s): %s\n|', num2str(toc)); %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% if (exist([SCase(iSCaseID).dataMatlabPath '/scapulaLandmarksAutoR.mat'],'file') && ~updateCalculations) continue end while true tic; fprintf(logFileID, '\n| Segmentation auto '); fprintf(logFileID, '\n| Load scapula surface and landmarks'); output = SCase(iSCaseID).shoulder.scapulaAuto.loadAuto; % Load auto data from matlab directory if ~output fprintf(logFileID, ': ERROR'); autoScapulaLoad{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Set coord. syst.'); output = SCase(iSCaseID).shoulder.scapulaAuto.coordSysSet; if ~output fprintf(logFileID, ': ERROR'); autoScapulaCoord{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Load glenoid surface'); output = SCase(iSCaseID).shoulder.scapulaAuto.glenoid.loadAuto; if ~output fprintf(logFileID, ': ERROR'); autoGlenoidLoad{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Measure glenoid anatomy'); output = SCase(iSCaseID).shoulder.scapulaAuto.glenoid.morphology; if ~output fprintf(logFileID, ': ERROR'); autoGlenoidMorphology{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); if calcGlenoidDensity fprintf(logFileID, '\n| Measure glenoid density'); output = SCase(iSCaseID).shoulder.scapulaAuto.glenoid.calcDensity; if ~output fprintf(logFileID, ': Density calculus error. Could not read dicom'); autoGlenoidDensity{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); end fprintf(logFileID, '\n| Load humerus data'); output = SCase(iSCaseID).shoulder.humerus.load; if ~output fprintf(logFileID, ': ERROR'); - if humerusLoad{end} ~= SCaseID; - humerusLoad{end+1} = SCaseID; + if ~isempty(humerusLoad) + if humerusLoad{end} ~= SCaseID; + humerusLoad{end+1} = SCaseID; + end end - break; + else + fprintf(logFileID, ': OK'); + fprintf(logFileID, '\n| Measure humerus subluxation'); + output = SCase(iSCaseID).shoulder.humerus.subluxation(SCase(iSCaseID).shoulder.scapulaAuto); + + if ~output + fprintf(logFileID, ': ERROR'); + humerusSubluxation{end+1} = SCaseID; + break; + else + fprintf(logFileID, ': OK'); + end end - fprintf(logFileID, ': OK'); - fprintf(logFileID, '\n| Measure humerus subluxation'); - output = SCase(iSCaseID).shoulder.humerus.subluxation(SCase(iSCaseID).shoulder.scapulaAuto); - - if ~output - fprintf(logFileID, ': ERROR'); - humerusSubluxation{end+1} = SCaseID; - break; - end - - fprintf(logFileID, ': OK'); fprintf(logFileID, '\n| Measure acromion anatomy'); % Should be run after SCase.shoulder.humerus (for AI) output = SCase(iSCaseID).shoulder.scapulaAuto.acromion.morphology; if ~output fprintf(logFileID, ': ERROR'); autoAcromionMorphology{end+1} = SCaseID; break; end fprintf(logFileID, ': OK'); autoOk{end+1} = SCaseID; fprintf(logFileID, '\n| Save SCase.mat'); output = SCase(iSCaseID).saveMatlab; if ~output fprintf(logFileID, ': ERROR'); break; end fprintf(logFileID, ': OK'); break; end fprintf(logFileID, '\n| Elapsed time (s): %s\n|___________________________________\n\n', num2str(toc)); % 4) Load & analyses auto data from matlab (Statistical Shape Model) % Load scapula surface and landmarks save('measureSCase_analysis.mat',... 'ok','amira','scapulaLoad','scapulaCoord',... 'degeneration','glenoidLoad','glenoidMorphology','glenoidDensity',... 'humerusLoad','humerusSubluxation','acromionMorphology',... 'autoOk','autoScapulaLoad','autoScapulaCoord','autoGlenoidLoad',... 'autoGlenoidMorphology','autoGlenoidDensity','autoAcromionMorphology') end % End of loop on SCaseList %% Write csv file % This might be a function (SCase.csvSave()). The input would be a filename and a structure % data % Replace header and data by structure. Currently not working %{ txtFilename = [xlsDir, '/anatomy.txt']; % Name of the txt file DataStruc = struc(... 'SCase_id', SCase.id, ... 'shoulder_side', SCase.shoulder.side,... 'glenoid_radius', SCase.shoulder.scapula.glenoid.radius,... 'glenoid_sphereRMSE', SCase.shoulder.scapula.glenoid.sphereRMSE,... 'glenoid_depth', SCase.shoulder.scapula.glenoid.depth,... 'glenoid_width', SCase.shoulder.scapula.glenoid.width,... 'glenoid_height', SCase.shoulder.scapula.glenoid.height,... 'glenoid_centerPA', SCase.shoulder.scapula.glenoid.centerLocal(1),... 'glenoid_centerIS', SCase.shoulder.scapula.glenoid.centerLocal(2),... 'glenoid_centerML', SCase.shoulder.scapula.glenoid.centerLocal(3),... 'glenoid_versionAmpl', SCase.shoulder.scapula.glenoid.versionAmpl,... 'glenoid_versionOrient', SCase.shoulder.scapula.glenoid.versionOrient,... 'glenoid_version', SCase.shoulder.scapula.glenoid.version,... 'glenoid_inclination', SCase.shoulder.scapula.glenoid.inclination,... 'humerus_jointRadius', SCase.shoulder.humerus.jointRadius,... 'humerus_headRadius', SCase.shoulder.humerus.radius,... 'humerus_GHSAmpl', SCase.shoulder.humerus.GHSAmpl,... 'humerus_GHSOrient', SCase.shoulder.humerus.GHSOrient,... 'humerus_SHSAmpl', SCase.shoulder.humerus.SHSAmpl,... 'humerus_SHSOrient', SCase.shoulder.humerus.SHSOrient,... 'humerus_SHSAngle', SCase.shoulder.humerus.SHSAngle,... 'humerus_SHSPA', SCase.shoulder.humerus.SHSPA,... 'humerus_SHSIS', SCase.shoulder.humerus.SHSIS,... 'acromion_AI', SCase.shoulder.scapula.acromion.AI,... 'acromion_CSA', SCase.shoulder.scapula.acromion.CSA,... 'acromion_PS', SCase.shoulder.scapula.acromion.PS... ); DataTable = strct2table(Data); writetable(DataTable,filename); %} % Header of the csv file dataHeader = [... 'SCase_id,' ... 'shoulder_side,' ... 'glenoid_radius,' ... 'glenoid_sphereRMSE,' ... 'glenoid_depth,' ... 'glenoid_width,' ... 'glenoid_height,' ... 'glenoid_centerPA,' ... 'glenoid_centerIS,' ... 'glenoid_centerML,' ... 'glenoid_versionAmpl,' ... 'glenoid_versionOrient,' ... 'glenoid_version,' ... 'glenoid_inclination,' ... 'humerus_jointRadius,' ... 'humerus_headRadius,' ... 'humerus_GHSAmpl,' ... 'humerus_GHSOrient,' ... 'humerus_SHSAmpl,' ... 'humerus_SHSOrient,' ... 'humerus_SHSAngle,' ... 'humerus_SHSPA,' ... 'humerus_SHSIS,' ... 'acromion_AI,' ... 'acromion_CSA,' ... 'acromion_PSA,'... 'acromion_AAA\n'... ]; updateList = listSCase; % The list of SCase to use to construct anatomy.csv and SCaseDB.mat fprintf(logFileID, '\n\nSave anatomy.csv file'); fid = fopen([xlsDir, '/anatomy.csv'],'w'); %Last csv is deleted and a new one, updated is being created fprintf(fid,dataHeader); fclose(fid); % The following lines re-create the SCaseDB.mat and contruct the anatomy.csv file S = ShoulderCase; for Case=1:length(updateList) S(Case).id = updateList(Case).id; % S(Case).dataPath = dataDir; % S(Case).path; % Compute the SCase.dataMatlabPath loaded = load([S(Case).dataMatlabPath '/SCase.mat']); % Load SCase.mat SCaseDB(Case) = loaded.SCase; SCaseDB(Case).appendToCSV('anatomy.csv'); end fprintf(logFileID, ': OK'); %% Save the entire SCaseDB array as a matlab file fprintf(logFileID, '\n\nSave SCase database'); filename = 'SCaseDB'; filename = [matlabDir '/' filename '.mat']; try save(filename, 'SCaseDB'); fprintf(logFileID, ': OK'); catch fprintf(logFileID, ': Error'); end %fprintf(logFileID, [': ' csvFilename]); %% Write xls file (Windows only) % [~,message] = csv2xlsSCase(csvFilename); % fprintf(logFileID, message); % If run from non-windows system, only csv will be produced. The xls can be % produced by opening the csv from Excel and save as xls. % Could be a function with 1 input (cvsFilenames %{ xlsFilename = strrep(csvFilename, '.csv', '.xls'); % Replace .csv by .xls if ispc % Check if run from windows! % Read cvs file as table and write the table as xls cvsTable = readtable(csvFilename); % Get table from csv (only way to read non-numeric data) cvsCell = table2cell(cvsTable); % Tranform table cell array dataHeader = cvsTable.Properties.VariableNames; % Get header cvsCell = [dataHeader; cvsCell]; % Add header sheet = 'anatomy'; % Sheet name of the xls file [status,message] = xlswrite(xlsFilename, cvsCell, sheet); % Save xls if status fprintf(logFileId, ['\nSaved ' xlsFilename]); else fprintf(logFileId, ['\nCould not save ' xlsFilename]); fprintf(logFileId, ['\n' message.identifier]); fprintf(logFileId, ['\n' message.message]); end else fprintf(logFileId, ['\n' xlsFilename ' not saved. Open and save as xls from Excel']); end %} %% Close log file fprintf(logFileID, '\n\nSCase measured: %s', num2str(length(SCaseList))); % Number of SCases measured elapsedTime = char(datetime('now')-startTime); elapsedTime = [elapsedTime(1:2) ' hours ' elapsedTime(4:5) ' minutes ' elapsedTime(7:8) ' seconds']; fprintf(logFileID, ['\nTotal Elapsed time: ' elapsedTime ]); fprintf(logFileID, '\n'); fclose(logFileID); % Close log file %% Output of the SCase if required by argument % SCase.output % inputArg = abaqus/density/references/ % update mySQL % SCase.sqlSave status = 1; message = 'OK'; end