Test Failed
Pull Request — master (#878)
by Daniil
05:05 queued 01:11
created

savu.plugins.stats.statistics   F

Complexity

Total Complexity 120

Size/Duplication

Total Lines 495
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 367
dl 0
loc 495
rs 2
c 0
b 0
f 0
wmc 120

29 Methods

Rating   Name   Duplication   Size   Complexity  
A Statistics._get_unpadded_slice_list() 0 15 3
B Statistics.write_slice_stats_to_file() 0 26 6
A Statistics._count() 0 3 1
B Statistics._unpad_slice() 0 20 6
A Statistics._de_list() 0 7 3
A Statistics.setup() 0 15 5
A Statistics._setup_iterative() 0 7 3
A Statistics.__init__() 0 7 1
A Statistics._set_loop_stats() 0 9 1
C Statistics._write_stats_to_file() 0 30 10
B Statistics.get_stats_from_dataset() 0 29 7
A Statistics._delete_stats_metadata() 0 3 1
B Statistics._set_pattern_info() 0 20 8
A Statistics.get_stats_from_name() 0 19 2
A Statistics.set_stats_residuals() 0 5 1
A Statistics.rmsd_from_rss() 0 2 1
A Statistics.calc_rmsd() 0 8 2
A Statistics.calc_rss() 0 11 3
C Statistics.get_stats() 0 41 11
A Statistics._array_to_dict() 0 5 2
A Statistics._combine_mpi_stats() 0 8 3
A Statistics.calc_volume_stats() 0 14 2
A Statistics._post_chain() 0 5 2
A Statistics.calc_stats_residuals() 0 5 2
A Statistics._link_stats_to_datasets() 0 17 5
A Statistics.calc_slice_stats() 0 21 4
A Statistics.set_slice_stats() 0 8 4
D Statistics.set_volume_stats() 0 48 13
B Statistics._setup_class() 0 29 8

How to fix   Complexity   

Complexity

Complex classes like savu.plugins.stats.statistics often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes.

Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.

1
"""
2
.. module:: statistics
3
   :platform: Unix
4
   :synopsis: Contains and processes statistics information for each plugin.
5
6
.. moduleauthor::Jacob Williamson <[email protected]>
7
8
"""
9
10
from savu.plugins.savers.utils.hdf5_utils import Hdf5Utils
11
from savu.plugins.stats.stats_utils import StatsUtils
12
from savu.core.iterate_plugin_group_utils import check_if_in_iterative_loop
13
14
import h5py as h5
15
import numpy as np
16
import os
17
from mpi4py import MPI
18
19
20
class Statistics(object):
21
    _pattern_list = ["SINOGRAM", "PROJECTION", "TANGENTOGRAM", "VOLUME_YZ", "VOLUME_XZ", "VOLUME_XY", "VOLUME_3D", "4D_SCAN", "SINOMOVIE"]
22
    _no_stats_plugins = ["BasicOperations", "Mipmap"]
23
    _key_list = ["max", "min", "mean", "mean_std_dev", "median_std_dev", "NRMSD"]
24
    #_savers = ["Hdf5Saver", "ImageSaver", "MrcSaver", "TiffSaver", "XrfSaver"]
25
26
27
    def __init__(self):
28
        self.calc_stats = True
29
        self.stats = {'max': [], 'min': [], 'mean': [], 'std_dev': [], 'RSS': [], 'data_points': []}
30
        self.stats_before_processing = {'max': [], 'min': [], 'mean': [], 'std_dev': []}
31
        self.residuals = {'max': [], 'min': [], 'mean': [], 'std_dev': []}
32
        self._repeat_count = 0
33
        self.p_num = None
34
35
    def setup(self, plugin_self, pattern=None):
36
        self.plugin_name = plugin_self.name
37
        if plugin_self.name in Statistics._no_stats_plugins:
38
            self.calc_stats = False
39
        if self.calc_stats:
40
            self.plugin = plugin_self
41
            self._pad_dims = []
42
            self._already_called = False
43
            if pattern:
44
                self.pattern = pattern
45
            else:
46
                self._set_pattern_info()
47
        if self.calc_stats:
48
            Statistics._any_stats = True
49
        self._setup_iterative()
50
51
    def _setup_iterative(self):
52
        self._iterative_group = check_if_in_iterative_loop(Statistics.exp)
53
        if self._iterative_group:
54
            if self._iterative_group.start_index == Statistics.count:
55
                Statistics._loop_counter += 1
56
                Statistics.loop_stats.append({"NRMSD": np.array([])})
57
            self.l_num = Statistics._loop_counter - 1
58
59
    @classmethod
60
    def _setup_class(cls, exp):
61
        """Sets up the statistics class for the whole plugin chain (only called once)"""
62
        try:
63
            if exp.meta_data.get("stats") == "on":
64
                cls._stats_flag = True
65
            elif exp.meta_data.get("stats") == "off":
66
                cls._stats_flag = False
67
        except KeyError:
68
            cls._stats_flag = True
69
        cls._any_stats = False
70
        cls.count = 2
71
        cls.global_stats = {}
72
        cls.loop_stats = []
73
        cls.exp = exp
74
        cls.n_plugins = len(exp.meta_data.plugin_list.plugin_list)
75
        for i in range(1, cls.n_plugins + 1):
76
            cls.global_stats[i] = np.array([])
77
        cls.global_residuals = {}
78
        cls.plugin_numbers = {}
79
        cls.plugin_names = {}
80
        cls._loop_counter = 0
81
        cls.path = exp.meta_data['out_path']
82
        if cls.path[-1] == '/':
83
            cls.path = cls.path[0:-1]
84
        cls.path = f"{cls.path}/stats"
85
        if MPI.COMM_WORLD.rank == 0:
86
            if not os.path.exists(cls.path):
87
                os.mkdir(cls.path)
88
89
    def get_stats(self, p_num=None, stat=None, instance=-1):
90
        """Returns stats associated with a certain plugin, given the plugin number (its place in the process list).
91
92
        :param p_num: Plugin  number of the plugin whose associated stats are being fetched.
93
            If p_num <= 0, it is relative to the plugin number of the current plugin being run.
94
            E.g current plugin number = 5, p_num = -2 --> will return stats of the third plugin.
95
            By default will gather stats for the current plugin.
96
        :param stat: Specify the stat parameter you want to fetch, i.e 'max', 'mean', 'median_std_dev'.
97
            If left blank will return the whole dictionary of stats:
98
            {'max': , 'min': , 'mean': , 'mean_std_dev': , 'median_std_dev': , 'NRMSD' }
99
        :param instance: In cases where there are multiple set of stats associated with a plugin
100
            due to loops or multi-parameters, specify which set you want to retrieve, i.e 3 to retrieve the
101
            stats associated with the third run of a plugin. Pass 'all' to get a list of all sets.
102
            By default will retrieve the most recent set.
103
        """
104
        if not p_num:
105
            p_num = self.p_num
106
        if p_num <= 0:
107
            try:
108
                p_num = self.p_num + p_num
109
            except TypeError:
110
                p_num = Statistics.count + p_num
111
        if Statistics.global_stats[p_num].ndim == 1 and instance in (None, 0, 1, -1, "all"):
112
            stats_array = Statistics.global_stats[p_num]
113
        else:
114
            if instance == "all":
115
                stats_list = [self.get_stats(p_num, stat=stat, instance=1)]
116
                n = 2
117
                if Statistics.global_stats[p_num].ndim != 1:
118
                    while n <= len(Statistics.global_stats[p_num]):
119
                        stats_list.append(self.get_stats(p_num, stat=stat, instance=n))
120
                        n += 1
121
                return stats_list
122
            if instance > 0:
123
                instance -= 1
124
            stats_array = Statistics.global_stats[p_num][instance]
125
        stats_dict = self._array_to_dict(stats_array)
126
        if stat is not None:
127
            return stats_dict[stat]
128
        else:
129
            return stats_dict
130
131
    def get_stats_from_name(self, plugin_name, n=None, stat=None, instance=-1):
132
        """Returns stats associated with a certain plugin.
133
134
        :param plugin_name: name of the plugin whose associated stats are being fetched.
135
        :param n: In a case where there are multiple instances of **plugin_name** in the process list,
136
            specify the nth instance. Not specifying will select the first (or only) instance.
137
        :param stat: Specify the stat parameter you want to fetch, i.e 'max', 'mean', 'median_std_dev'.
138
            If left blank will return the whole dictionary of stats:
139
            {'max': , 'min': , 'mean': , 'mean_std_dev': , 'median_std_dev': , 'NRMSD' }
140
        :param instance: In cases where there are multiple set of stats associated with a plugin
141
            due to iterative loops or multi-parameters, specify which set you want to retrieve, i.e 3 to retrieve the
142
            stats associated with the third run of a plugin. Pass 'all' to get a list of all sets.
143
            By default will retrieve the most recent set.
144
        """
145
        name = plugin_name
146
        if n not in (None, 0, 1):
147
            name = name + str(n)
148
        p_num = Statistics.plugin_numbers[name]
149
        return self.get_stats(p_num, stat, instance)
150
151
    def get_stats_from_dataset(self, dataset, stat=None, instance=-1):
152
        """Returns stats associated with a dataset.
153
154
        :param dataset: The dataset whose associated stats are being fetched.
155
        :param stat: Specify the stat parameter you want to fetch, i.e 'max', 'mean', 'median_std_dev'.
156
            If left blank will return the whole dictionary of stats:
157
            {'max': , 'min': , 'mean': , 'mean_std_dev': , 'median_std_dev': , 'NRMSD'}
158
        :param instance: In cases where there are multiple set of stats associated with a dataset
159
            due to iterative loops or multi-parameters, specify which set you want to retrieve, i.e 3 to retrieve the
160
            stats associated with the third run of a plugin. Pass 'all' to get a list of all sets.
161
            By default will retrieve the most recent set.
162
        """
163
        stats_list = [dataset.meta_data.get("stats")]
164
        n = 2
165
        while ("stats" + str(n)) in list(dataset.meta_data.get_dictionary().keys()):
166
            stats_list.append(dataset.meta_data.get("stats" + str(n)))
167
            n += 1
168
        if stat:
169
            for i in range(len(stats_list)):
170
                stats_list[i] = stats_list[i][stat]
171
        if instance in (None, 0, 1):
172
            stats = stats_list[0]
173
        elif instance == "all":
174
            stats = stats_list
175
        else:
176
            if instance >= 2:
177
                instance -= 1
178
            stats = stats_list[instance]
179
        return stats
180
181
    def set_slice_stats(self, my_slice, base_slice=None, pad=True):
182
        slice_stats_after = self.calc_slice_stats(my_slice, base_slice, pad=pad)
183
        if base_slice:
184
            slice_stats_before = self.calc_slice_stats(base_slice, pad=pad)
185
            for key in list(self.stats_before_processing.keys()):
186
                self.stats_before_processing[key].append(slice_stats_before[key])
187
        for key in list(self.stats.keys()):
188
            self.stats[key].append(slice_stats_after[key])
189
190
    def calc_slice_stats(self, my_slice, base_slice=None, pad=True):
191
        """Calculates and returns slice stats for the current slice.
192
193
        :param my_slice: The slice whose stats are being calculated.
194
        :param base_slice: Provide a base slice to calculate residuals from, to calculate RMSD.
195
        """
196
        if my_slice is not None:
197
            my_slice = self._de_list(my_slice)
198
            if pad:
199
                my_slice = self._unpad_slice(my_slice)
200
            slice_stats = {'max': np.amax(my_slice).astype('float64'), 'min': np.amin(my_slice).astype('float64'),
201
                           'mean': np.mean(my_slice), 'std_dev': np.std(my_slice), 'data_points': my_slice.size}
202
            if base_slice is not None:
203
                base_slice = self._de_list(base_slice)
204
                base_slice = self._unpad_slice(base_slice)
205
                rss = self.calc_rss(my_slice, base_slice)
206
            else:
207
                rss = None
208
            slice_stats['RSS'] = rss
209
            return slice_stats
210
        return None
211
212
    def calc_rss(self, array1, array2):  # residual sum of squares
213
        if array1.shape == array2.shape:
214
            residuals = np.subtract(array1, array2)
215
            rss = 0
216
            for value in (np.nditer(residuals)):
217
                rss += value**2
218
            # rss = sum(value**2 for value in np.nditer(residuals))
219
        else:
220
            #print("Warning: cannot calculate RSS, arrays different sizes.")
221
            rss = None
222
        return rss
223
224
    def rmsd_from_rss(self, rss, n):
225
        return np.sqrt(rss/n)
226
227
    def calc_rmsd(self, array1, array2):
228
        if array1.shape == array2.shape:
229
            rss = self.calc_rss(array1, array2)
230
            rmsd = self.rmsd_from_rss(rss, array1.size)
231
        else:
232
            print("Warning: cannot calculate RMSD, arrays different sizes.")  # need to make this an actual warning
233
            rmsd = None
234
        return rmsd
235
236
    def calc_stats_residuals(self, stats_before, stats_after):
237
        residuals = {'max': None, 'min': None, 'mean': None, 'std_dev': None}
238
        for key in list(residuals.keys()):
239
            residuals[key] = stats_after[key] - stats_before[key]
240
        return residuals
241
242
    def set_stats_residuals(self, residuals):
243
        self.residuals['max'].append(residuals['max'])
244
        self.residuals['min'].append(residuals['min'])
245
        self.residuals['mean'].append(residuals['mean'])
246
        self.residuals['std_dev'].append(residuals['std_dev'])
247
248
    def calc_volume_stats(self, slice_stats):
249
        volume_stats = np.array([max(slice_stats['max']), min(slice_stats['min']), np.mean(slice_stats['mean']),
250
                                np.mean(slice_stats['std_dev']), np.median(slice_stats['std_dev'])])
251
        if None not in slice_stats['RSS']:
252
            total_rss = sum(slice_stats['RSS'])
253
            n = sum(slice_stats['data_points'])
254
            RMSD = self.rmsd_from_rss(total_rss, n)
255
            the_range = volume_stats[0] - volume_stats[1]
256
            NRMSD = RMSD / the_range  # normalised RMSD (dividing by the range)
257
            volume_stats = np.append(volume_stats, NRMSD)
258
        else:
259
            #volume_stats = np.append(volume_stats, None)
260
            pass
261
        return volume_stats
262
263
    def _set_loop_stats(self):
264
        # NEED TO CHANGE THIS - MUST USE SLICES
265
        data_obj1 = list(self._iterative_group._ip_data_dict["iterating"].keys())[0]
266
        data_obj2 = self._iterative_group._ip_data_dict["iterating"][data_obj1]
267
        RMSD = self.calc_rmsd(data_obj1.data, data_obj2.data)
268
        the_range = self.get_stats(self.p_num, stat="max", instance=self._iterative_group._ip_iteration) -\
269
                self.get_stats(self.p_num, stat="min", instance=self._iterative_group._ip_iteration)
270
        NRMSD = RMSD/the_range
271
        Statistics.loop_stats[self.l_num]["NRMSD"] = np.append(Statistics.loop_stats[self.l_num]["NRMSD"], NRMSD)
272
273
    def set_volume_stats(self):
274
        """Calculates volume-wide statistics from slice stats, and updates class-wide arrays with these values.
275
        Links volume stats with the output dataset and writes slice stats to file.
276
        """
277
        stats = self.stats
278
        combined_stats = self._combine_mpi_stats(stats)
279
        if not self.p_num:
280
            self.p_num = Statistics.count
281
        p_num = self.p_num
282
        name = self.plugin_name
283
        i = 2
284
        if not self._iterative_group:
285
            while name in list(Statistics.plugin_numbers.keys()):
286
                name = self.plugin_name + str(i)
287
                i += 1
288
        elif self._iterative_group._ip_iteration == 0:
289
            while name in list(Statistics.plugin_numbers.keys()):
290
                name = self.plugin_name + str(i)
291
                i += 1
292
293
        if p_num not in list(Statistics.plugin_names.keys()):
294
            Statistics.plugin_names[p_num] = name
295
        Statistics.plugin_numbers[name] = p_num
296
        if len(self.stats['max']) != 0:
297
            stats_array = self.calc_volume_stats(combined_stats)
298
            Statistics.global_residuals[p_num] = {}
299
            #before_processing = self.calc_volume_stats(self.stats_before_processing)
300
            #for key in list(before_processing.keys()):
301
            #    Statistics.global_residuals[p_num][key] = Statistics.global_stats[p_num][key] - before_processing[key]
302
303
            if len(Statistics.global_stats[p_num]) == 0:
304
                Statistics.global_stats[p_num] = stats_array
305
            else:
306
                Statistics.global_stats[p_num] = np.vstack([Statistics.global_stats[p_num], stats_array])
307
308
            stats_dict = self._array_to_dict(stats_array)
309
            self._link_stats_to_datasets(stats_dict, self._iterative_group)
310
311
        if self._iterative_group:
312
            if self._iterative_group.end_index == p_num and self._iterative_group._ip_iteration != 0:
313
                #self._set_loop_stats()
314
                pass
315
316
        self._write_stats_to_file(p_num)
317
        self._already_called = True
318
        self._repeat_count += 1
319
        if self._iterative_group:
320
            self.stats = {'max': [], 'min': [], 'mean': [], 'std_dev': [], 'RSS': [], 'data_points': []}
321
322
323
324
    def _combine_mpi_stats(self, slice_stats):
325
        comm = MPI.COMM_WORLD
326
        combined_stats_list = comm.allgather(slice_stats)
327
        combined_stats = {'max': [], 'min': [], 'mean': [], 'std_dev': [], 'RSS': [], 'data_points': []}
328
        for single_stats in combined_stats_list:
329
            for key in list(single_stats.keys()):
330
                combined_stats[key] += single_stats[key]
331
        return combined_stats
332
333
    def _array_to_dict(self, stats_array):
334
        stats_dict = {}
335
        for i, value in enumerate(stats_array):
336
            stats_dict[Statistics._key_list[i]] = value
337
        return stats_dict
338
339
    def _set_pattern_info(self):
340
        """Gathers information about the pattern of the data in the current plugin."""
341
        out_datasets = self.plugin.get_out_datasets()
342
        try:
343
            self.pattern = self.plugin.parameters['pattern']
344
            if self.pattern == None:
345
                raise KeyError
346
        except KeyError:
347
            if not out_datasets:
348
                self.pattern = None
349
            else:
350
                patterns = out_datasets[0].get_data_patterns()
351
                for pattern in patterns:
352
                    if 1 in patterns.get(pattern)["slice_dims"]:
353
                        self.pattern = pattern
354
                        break
355
        self.calc_stats = False
356
        for dataset in out_datasets:
357
            if bool(set(Statistics._pattern_list) & set(dataset.data_info.get("data_patterns"))):
358
                self.calc_stats = True
359
360
    def _link_stats_to_datasets(self, stats_dict, iterative=False):
361
        """Links the volume wide statistics to the output dataset(s)"""
362
        out_dataset = self.plugin.get_out_datasets()[0]
363
        my_dataset = out_dataset
364
        if iterative:
365
            if "itr_clone" in out_dataset.group_name:
366
                my_dataset = list(iterative._ip_data_dict["iterating"].keys())[0]
367
        n_datasets = self.plugin.nOutput_datasets()
368
369
        i = 2
370
        group_name = "stats"
371
        #out_dataset.data_info.set([group_name], stats)
372
        while group_name in list(my_dataset.meta_data.get_dictionary().keys()):
373
            group_name = f"stats{i}"
374
            i += 1
375
        for key in list(stats_dict.keys()):
376
            my_dataset.meta_data.set([group_name, key], stats_dict[key])
377
378
    def _delete_stats_metadata(self, plugin):
379
        out_dataset = plugin.get_out_datasets()[0]
380
        out_dataset.meta_data.delete("stats")
381
382
    def _write_stats_to_file(self, p_num=None, plugin_name=None):
383
        if p_num is None:
384
            p_num = self.p_num
385
        if plugin_name is None:
386
            plugin_name = self.plugin_names[p_num]
387
        path = Statistics.path
388
        filename = f"{path}/stats.h5"
389
        stats = self.global_stats[p_num]
390
        self.hdf5 = Hdf5Utils(self.exp)
391
        with h5.File(filename, "a", driver="mpio", comm=MPI.COMM_WORLD) as h5file:
392
            group = h5file.require_group("stats")
393
            if stats.shape != (0,):
394
                if str(p_num) in list(group.keys()):
395
                    del group[str(p_num)]
396
                dataset = group.create_dataset(str(p_num), shape=stats.shape, dtype=stats.dtype)
397
                dataset[::] = stats[::]
398
                dataset.attrs.create("plugin_name", plugin_name)
399
                dataset.attrs.create("pattern", self.pattern)
400
            if self._iterative_group:
401
                l_stats = Statistics.loop_stats[self.l_num]
402
                group1 = h5file.require_group("iterative")
403
                if self._iterative_group._ip_iteration == self._iterative_group._ip_fixed_iterations - 1\
404
                        and self.p_num == self._iterative_group.end_index:
405
                    dataset1 = group1.create_dataset(str(self.l_num), shape=l_stats["NRMSD"].shape, dtype=l_stats["NRMSD"].dtype)
406
                    dataset1[::] = l_stats["NRMSD"][::]
407
                    loop_plugins = []
408
                    for i in range(self._iterative_group.start_index, self._iterative_group.end_index + 1):
409
                        loop_plugins.append(self.plugin_names[i])
410
                    dataset1.attrs.create("loop_plugins", loop_plugins)
411
                    dataset.attrs.create("n_loop_plugins", len(loop_plugins))
0 ignored issues
show
introduced by
The variable dataset does not seem to be defined in case stats.shape != TupleNode on line 393 is False. Are you sure this can never be the case?
Loading history...
412
413
    def write_slice_stats_to_file(self, slice_stats=None, p_num=None):
414
        """Writes slice statistics to a h5 file. Placed in the stats folder in the output directory."""
415
        if not slice_stats:
416
            slice_stats = self.stats
417
        if not p_num:
418
            p_num = self.count
419
            plugin_name = self.plugin_name
420
        else:
421
            plugin_name = self.plugin_names[p_num]
422
        combined_stats = self._combine_mpi_stats(slice_stats)
423
        slice_stats_arrays = {}
424
        datasets = {}
425
        path = Statistics.path
426
        filename = f"{path}/stats_p{p_num}_{plugin_name}.h5"
427
        self.hdf5 = Hdf5Utils(self.plugin.exp)
428
        with h5.File(filename, "a", driver="mpio", comm=MPI.COMM_WORLD) as h5file:
429
            i = 2
430
            group_name = "/stats"
431
            while group_name in h5file:
432
                group_name = f"/stats{i}"
433
                i += 1
434
            group = h5file.create_group(group_name, track_order=None)
435
            for key in list(combined_stats.keys()):
436
                slice_stats_arrays[key] = np.array(combined_stats[key])
437
                datasets[key] = self.hdf5.create_dataset_nofill(group, key, (len(slice_stats_arrays[key]),), slice_stats_arrays[key].dtype)
438
                datasets[key][::] = slice_stats_arrays[key]
439
440
    def _unpad_slice(self, slice1):
441
        """If data is padded in the slice dimension, removes this pad."""
442
        out_datasets = self.plugin.get_out_datasets()
443
        if len(out_datasets) == 1:
444
            out_dataset = out_datasets[0]
445
        else:
446
            for dataset in out_datasets:
447
                if self.pattern in list(dataset.data_info.get(["data_patterns"]).keys()):
448
                    out_dataset = dataset
449
                    break
450
        slice_dims = out_dataset.get_slice_dimensions()
0 ignored issues
show
introduced by
The variable out_dataset does not seem to be defined for all execution paths.
Loading history...
451
        if self.plugin.pcount == 0:
452
            self._slice_list, self._pad = self._get_unpadded_slice_list(slice1, slice_dims)
453
        if self._pad:
454
            #for slice_dim in slice_dims:
455
            slice_dim = slice_dims[0]
456
            temp_slice = np.swapaxes(slice1, 0, slice_dim)
457
            temp_slice = temp_slice[self._slice_list[slice_dim]]
458
            slice1 = np.swapaxes(temp_slice, 0, slice_dim)
459
        return slice1
460
461
    def _get_unpadded_slice_list(self, slice1, slice_dims):
462
        """Creates slice object(s) to un-pad slices in the slice dimension(s)."""
463
        slice_list = list(self.plugin.slice_list[0])
464
        pad = False
465
        if len(slice_list) == len(slice1.shape):
466
            #for i in slice_dims:
467
            i = slice_dims[0]
468
            slice_width = self.plugin.slice_list[0][i].stop - self.plugin.slice_list[0][i].start
469
            if slice_width != slice1.shape[i]:
470
                pad = True
471
                pad_width = (slice1.shape[i] - slice_width) // 2  # Assuming symmetrical padding
472
                slice_list[i] = slice(pad_width, pad_width + 1, 1)
473
            return tuple(slice_list), pad
474
        else:
475
            return self.plugin.slice_list[0], pad
476
477
    def _de_list(self, slice1):
478
        """If the slice is in a list, remove it from that list."""
479
        if type(slice1) == list:
480
            if len(slice1) != 0:
481
                slice1 = slice1[0]
482
                slice1 = self._de_list(slice1)
483
        return slice1
484
485
486
    @classmethod
487
    def _count(cls):
488
        cls.count += 1
489
490
    @classmethod
491
    def _post_chain(cls):
492
        if cls._any_stats & cls._stats_flag:
493
            stats_utils = StatsUtils()
494
            stats_utils.generate_figures(f"{cls.path}/stats.h5", cls.path)
495