a b/dosma/tissues/patellar_cartilage.py
1
"""Analysis for patellar cartilage.
2
3
Attributes:
4
    BOUNDS (dict): Upper bounds for quantitative values.
5
"""
6
import itertools
7
import os
8
import warnings
9
10
import numpy as np
11
import pandas as pd
12
import scipy.ndimage as sni
13
14
from dosma.core.device import get_array_module
15
from dosma.core.quant_vals import QuantitativeValueType
16
from dosma.defaults import preferences
17
from dosma.tissues.tissue import Tissue, largest_cc
18
from dosma.utils import io_utils
19
20
import matplotlib.pyplot as plt
21
22
# milliseconds
23
BOUNDS = {
24
    QuantitativeValueType.T2: 60.0,
25
    QuantitativeValueType.T1_RHO: 100.0,
26
    QuantitativeValueType.T2_STAR: 50.0,
27
}
28
29
__all__ = ["PatellarCartilage"]
30
31
32
class PatellarCartilage(Tissue):
33
    """Handles analysis and visualization for patellar cartilage."""
34
35
    ID = 3
36
    STR_ID = "pc"
37
    FULL_NAME = "patellar cartilage"
38
39
    # Expected quantitative values
40
    T1_EXPECTED = 1000  # milliseconds
41
42
    # Region Keys
43
    _ANTERIOR_KEY = 0
44
    _POSTERIOR_KEY = 1
45
    _CORONAL_KEYS = [_ANTERIOR_KEY, _POSTERIOR_KEY]
46
47
    _MEDIAL_KEY = 0
48
    _LATERAL_KEY = 1
49
    _SAGITTAL_KEYS = [_MEDIAL_KEY, _LATERAL_KEY]
50
51
    _REGION_DEEP_KEY = 0
52
    _REGION_SUPERFICIAL_KEY = 1
53
    _TOTAL_AXIAL_KEY = -1
54
55
    def __init__(self, weights_dir: str = None, medial_to_lateral: bool = None):
56
        super().__init__(weights_dir=weights_dir, medial_to_lateral=medial_to_lateral)
57
58
        self.regions_mask = None
59
60
    def unroll_coronal(self, quant_map: np.ndarray):
61
        """Unroll patellar cartilage in the coronal direction.
62
63
        Because patellar cartilage is flat, "unrolling" is projecting the patellar
64
        cartilage onto the coronal axis.
65
66
        Args:
67
            quant_map (np.ndarray):
68
        """
69
        mask = self.__mask__.volume
70
71
        assert (
72
            self.regions_mask is not None
73
        ), "region_mask not initialized. Should be initialized when mask is set"
74
        region_mask_deep_superficial = self.regions_mask[..., 0]
75
76
        superficial = (
77
            (region_mask_deep_superficial == self._REGION_SUPERFICIAL_KEY) * mask * quant_map
78
        )
79
        superficial[superficial == 0] = np.nan
80
        superficial = np.nanmean(superficial, axis=2)
81
82
        deep = (region_mask_deep_superficial == self._REGION_DEEP_KEY) * mask * quant_map
83
        deep[deep == 0] = np.nan
84
        deep = np.nanmean(deep, axis=2)
85
86
        total = mask * quant_map
87
        total[total == 0] = np.nan
88
        total = np.nanmean(total, axis=2)
89
90
        return total, superficial, deep
91
92
    def split_regions(self, base_map):
93
        """Split patellar cartilage into deep/superficial regions.
94
95
        For patellar cartilage, the superficial/deep transition occurs in
96
        the anterior/posterior (A/P) direction. The boundary is determined
97
        for each non-zero 1D column spanning independently by the local
98
        center-of-mass (COM). The medial/lateral (M/L) plane is computed
99
        using the global COM.
100
101
        Args:
102
            base_map (ndarray): Binary 3D mask with orientation (SI, AP, ML/LM).
103
                If `self.medial_to_lateral`, last dimension should be ML.
104
        """
105
        if np.sum(base_map) == 0:
106
            warnings.warn("No mask for `%s` was found." % self.FULL_NAME)
107
108
        # Superficial/Deep (A/P)
109
        locs = base_map.sum(axis=1).nonzero()
110
        voxels = base_map[locs[0], :, locs[1]]
111
        com_sup_inf = np.asarray(
112
            [
113
                int(np.ceil(sni.measurements.center_of_mass(voxels[i, :])[0]))
114
                for i in range(voxels.shape[0])
115
            ]
116
        )
117
        region_mask_sup_deep = np.full(base_map.shape, self._REGION_DEEP_KEY)
118
        for i in range(len(com_sup_inf)):
119
            region_mask_sup_deep[
120
                locs[0][i], : com_sup_inf[i], locs[1][i]
121
            ] = self._REGION_SUPERFICIAL_KEY
122
123
        # M/L
124
        cum_ml = np.nonzero(base_map.sum(axis=(0, 1)))[0]  # noqa: F841
125
        # midpoint_ml = int(np.ceil((np.min(cum_ml) + np.max(cum_ml)) / 2))
126
        midpoint_ml = int(np.ceil(sni.measurements.center_of_mass(base_map)[2]))
127
        region_mask_med_lat = np.full(base_map.shape, self._LATERAL_KEY)
128
        medial_span = slice(0, midpoint_ml) if self.medial_to_lateral else slice(midpoint_ml, None)
129
        region_mask_med_lat[:, :, medial_span] = self._MEDIAL_KEY
130
131
        self.regions_mask = np.stack([region_mask_sup_deep, region_mask_med_lat], axis=-1)
132
133
    def __calc_quant_vals__(self, quant_map, map_type):
134
        subject_pid = self.pid
135
136
        super().__calc_quant_vals__(quant_map, map_type)
137
138
        assert (
139
            self.regions_mask is not None
140
        ), "region_mask not initialized. Should be initialized when mask is set"
141
142
        quant_map_volume = quant_map.volume
143
        mask = self.__mask__.volume
144
        quant_map_volume = mask * quant_map_volume
145
146
        deep_superficial_map = self.regions_mask[..., 0]
147
        med_lat_map = self.regions_mask[..., 1]
148
149
        axial_names = ["superficial", "deep", "total"]
150
        sagittal_names = ["medial", "lateral"]
151
152
        pd_header = ["Subject", "Location", "Condyle", "Mean", "Std", "Median"]
153
        pd_list = []
154
155
        regions = itertools.product(
156
            [self._REGION_SUPERFICIAL_KEY, self._REGION_DEEP_KEY, self._TOTAL_AXIAL_KEY],
157
            [self._MEDIAL_KEY, self._LATERAL_KEY],
158
        )
159
        for axial, sagittal in regions:
160
            if axial == self._TOTAL_AXIAL_KEY:
161
                axial_map = np.asarray(
162
                    deep_superficial_map == self._REGION_SUPERFICIAL_KEY, dtype=np.float32
163
                ) + np.asarray(deep_superficial_map == self._REGION_DEEP_KEY, dtype=np.float32)
164
                axial_map = np.asarray(axial_map, dtype=np.bool)
165
            else:
166
                axial_map = deep_superficial_map == axial
167
168
            sagittal_map = med_lat_map == sagittal
169
170
            curr_region_mask = quant_map_volume * axial_map * sagittal_map
171
            curr_region_mask = curr_region_mask[curr_region_mask != 0]
172
173
            # discard all values that are 0
174
            c_mean = np.nanmean(curr_region_mask)
175
            c_std = np.nanstd(curr_region_mask)
176
            c_median = np.nanmedian(curr_region_mask)
177
178
            row_info = [
179
                subject_pid,
180
                axial_names[axial],
181
                sagittal_names[sagittal],
182
                c_mean,
183
                c_std,
184
                c_median,
185
            ]
186
187
            pd_list.append(row_info)
188
189
        # Generate 2D unrolled matrix
190
        total, superficial, deep = self.unroll_coronal(quant_map.volume)
191
192
        df = pd.DataFrame(pd_list, columns=pd_header)
193
        qv_name = map_type.name
194
        maps = [
195
            {
196
                "title": "%s superficial" % qv_name,
197
                "data": superficial,
198
                "xlabel": "Slice",
199
                "ylabel": "Angle (binned)",
200
                "filename": "%s_superficial" % qv_name,
201
                "raw_data_filename": "%s_superficial.data" % qv_name,
202
            },
203
            {
204
                "title": "%s deep" % qv_name,
205
                "data": deep,
206
                "xlabel": "Slice",
207
                "ylabel": "Angle (binned)",
208
                "filename": "%s_deep" % qv_name,
209
                "raw_data_filename": "%s_deep.data" % qv_name,
210
            },
211
            {
212
                "title": "%s total" % qv_name,
213
                "data": total,
214
                "xlabel": "Slice",
215
                "ylabel": "Angle (binned)",
216
                "filename": "%s_total" % qv_name,
217
                "raw_data_filename": "%s_total.data" % qv_name,
218
            },
219
        ]
220
221
        self.__store_quant_vals__(maps, df, map_type)
222
223
    def set_mask(self, mask, use_largest_cc: bool = True):
224
        xp = get_array_module(mask.A)
225
        if use_largest_cc:
226
            msk = xp.asarray(largest_cc(mask.A), dtype=xp.uint8)
227
        else:
228
            msk = xp.asarray(mask.A, dtype=xp.uint8)
229
        mask_copy = mask._partial_clone(volume=msk)
230
        super().set_mask(mask_copy)
231
232
        self.split_regions(self.__mask__.volume)
233
234
    def __save_quant_data__(self, dirpath):
235
        """Save quantitative data and 2D visualizations of patellar cartilage
236
237
        Check which quantitative values (T2, T1rho, etc) are defined for
238
        patellar cartilage and analyze these:
239
240
        1. Save 2D total, superficial, and deep visualization maps
241
        2. Save {'medial', 'lateral'}, {'anterior', 'posterior'},
242
            {'superior', 'inferior', 'total'} data to excel file
243
244
        :param dirpath: base filepath to save data
245
        """
246
        q_names = []
247
        dfs = []
248
249
        for quant_val in QuantitativeValueType:
250
            if quant_val.name not in self.quant_vals.keys():
251
                continue
252
253
            q_names.append(quant_val.name)
254
            q_val = self.quant_vals[quant_val.name]
255
            dfs.append(q_val[1])
256
257
            q_name_dirpath = io_utils.mkdirs(os.path.join(dirpath, quant_val.name.lower()))
258
            for q_map_data in q_val[0]:
259
                filepath = os.path.join(q_name_dirpath, q_map_data["filename"])
260
                xlabel = ""
261
                ylabel = ""
262
                title = q_map_data["title"]
263
                data_map = q_map_data["data"]
264
265
                axs_bounds = self.__get_axis_bounds__(data_map, leave_buffer=True)
266
267
                plt.clf()
268
269
                upper_bound = BOUNDS[quant_val]
270
                if preferences.visualization_use_vmax:
271
                    # Hard bounds - clipping
272
                    plt.imshow(data_map, cmap="jet", vmin=0.0, vmax=BOUNDS[quant_val])
273
                else:
274
                    # Try to use a soft bounds
275
                    if np.sum(data_map <= upper_bound) == 0:
276
                        plt.imshow(data_map, cmap="jet", vmin=0.0, vmax=BOUNDS[quant_val])
277
                    else:
278
                        warnings.warn(
279
                            "%s: Pixel value exceeded upper bound (%0.1f). Using normalized scale."
280
                            % (quant_val.name, upper_bound)
281
                        )
282
                        plt.imshow(data_map, cmap="jet")
283
284
                plt.xlabel(xlabel)
285
                plt.ylabel(ylabel)
286
                plt.title(title)
287
                plt.ylim(axs_bounds[0])
288
                plt.gca().invert_yaxis()
289
                plt.xlim(axs_bounds[1])
290
                # plt.axis('tight')
291
                clb = plt.colorbar()
292
                clb.ax.set_ylabel("(ms)")
293
                plt.savefig(filepath)
294
295
                # Save data
296
                raw_data_filepath = os.path.join(
297
                    q_name_dirpath, "raw_data", q_map_data["raw_data_filename"]
298
                )
299
                io_utils.save_pik(raw_data_filepath, data_map)
300
301
        if len(dfs) > 0:
302
            io_utils.save_tables(os.path.join(dirpath, "data.xlsx"), dfs, q_names)