Test Failed
Pull Request — master (#878)
by
unknown
04:11
created

savu.plugins.stats.statistics   F

Complexity

Total Complexity 115

Size/Duplication

Total Lines 496
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 375
dl 0
loc 496
rs 2
c 0
b 0
f 0
wmc 115

30 Methods

Rating   Name   Duplication   Size   Complexity  
A Statistics.setup() 0 12 4
A Statistics.set_stats_residuals() 0 5 1
A Statistics.calc_rmsd() 0 8 2
A Statistics._calc_rss() 0 8 2
A Statistics.calc_volume_stats() 0 13 2
A Statistics._rmsd_from_rss() 0 2 1
A Statistics._setup_iterative() 0 7 3
A Statistics.calc_stats_residuals() 0 5 2
A Statistics.calc_slice_stats() 0 20 3
A Statistics.__init__() 0 7 1
A Statistics.set_slice_stats() 0 7 3
B Statistics._setup_class() 0 23 5
A Statistics._set_loop_stats() 0 6 1
A Statistics.get_stats_from_dataset() 0 28 5
B Statistics._write_stats_to_file4() 0 21 6
B Statistics._set_pattern_info() 0 20 8
A Statistics._get_unpadded_slice_list() 0 15 3
A Statistics.get_stats_from_name() 0 18 2
A Statistics._write_stats_to_file2() 0 14 3
C Statistics.get_stats() 0 36 9
C Statistics._write_stats_to_file3() 0 28 9
A Statistics._array_to_dict() 0 5 2
A Statistics._combine_mpi_stats() 0 8 3
B Statistics.write_slice_stats_to_file() 0 26 6
A Statistics._count() 0 3 1
A Statistics._post_chain() 0 6 2
B Statistics._unpad_slice() 0 20 6
A Statistics._link_stats_to_datasets() 0 17 5
A Statistics._de_list() 0 7 3
D Statistics.set_volume_stats() 0 44 12

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
25
26
    def __init__(self):
27
        self.calc_stats = True
28
        self.stats = {'max': [], 'min': [], 'mean': [], 'std_dev': [], 'RSS': [], 'data_points': []}
29
        self.stats_before_processing = {'max': [], 'min': [], 'mean': [], 'std_dev': []}
30
        self.residuals = {'max': [], 'min': [], 'mean': [], 'std_dev': []}
31
        self._repeat_count = 0
32
        self.p_num = None
33
34
    def setup(self, plugin_self):
35
        if plugin_self.name in Statistics.no_stats_plugins:
36
            self.calc_stats = False
37
        if self.calc_stats:
38
            self.plugin = plugin_self
39
            self.plugin_name = plugin_self.name
40
            self._pad_dims = []
41
            self._already_called = False
42
            self._set_pattern_info()
43
        if self.calc_stats:
44
            Statistics._any_stats = True
45
        self._setup_iterative()
46
47
    def _setup_iterative(self):
48
        self._iterative_group = check_if_in_iterative_loop(Statistics.exp)
49
        if self._iterative_group:
50
            if self._iterative_group.start_index == Statistics.count:
51
                Statistics._loop_counter += 1
52
                Statistics.loop_stats.append({"NRMSD": np.array([])})
53
            self.l_num = Statistics._loop_counter - 1
54
55
    @classmethod
56
    def _setup_class(cls, exp):
57
        """Sets up the statistics class for the whole plugin chain (only called once)"""
58
        cls.stats_flag = True
59
        cls._any_stats = False
60
        cls.count = 2
61
        cls.global_stats = {}
62
        cls.loop_stats = []
63
        cls.exp = exp
64
        cls.n_plugins = len(exp.meta_data.plugin_list.plugin_list)
65
        for i in range(1, cls.n_plugins + 1):
66
            cls.global_stats[i] = np.array([])
67
        cls.global_residuals = {}
68
        cls.plugin_numbers = {}
69
        cls.plugin_names = {}
70
        cls._loop_counter = 0
71
        cls.path = exp.meta_data['out_path']
72
        if cls.path[-1] == '/':
73
            cls.path = cls.path[0:-1]
74
        cls.path = f"{cls.path}/stats"
75
        if MPI.COMM_WORLD.rank == 0:
76
            if not os.path.exists(cls.path):
77
                os.mkdir(cls.path)
78
79
    def set_slice_stats(self, slice, base_slice):
80
        slice_stats_before = self.calc_slice_stats(base_slice)
81
        slice_stats_after = self.calc_slice_stats(slice, base_slice)
82
        for key in list(self.stats_before_processing.keys()):
83
            self.stats_before_processing[key].append(slice_stats_before[key])
84
        for key in list(self.stats.keys()):
85
            self.stats[key].append(slice_stats_after[key])
86
87
    def calc_slice_stats(self, my_slice, base_slice=None):
88
        """Calculates and returns slice stats for the current slice.
89
90
        :param slice1: The slice whose stats are being calculated.
91
        """
92
        if my_slice is not None:
93
            slice_num = self.plugin.pcount
94
            my_slice = self._de_list(my_slice)
95
            my_slice = self._unpad_slice(my_slice)
96
            slice_stats = {'max': np.amax(my_slice).astype('float64'), 'min': np.amin(my_slice).astype('float64'),
97
                           'mean': np.mean(my_slice), 'std_dev': np.std(my_slice), 'data_points': my_slice.size}
98
            if base_slice is not None:
99
                base_slice = self._de_list(base_slice)
100
                base_slice = self._unpad_slice(base_slice)
101
                rss = self._calc_rss(my_slice, base_slice)
102
            else:
103
                rss = None
104
            slice_stats['RSS'] = rss
105
            return slice_stats
106
        return None
107
108
    def _calc_rss(self, array1, array2):  # residual sum of squares
109
        if array1.shape == array2.shape:
110
            residuals = np.subtract(array1, array2)
111
            rss = sum(value**2 for value in np.nditer(residuals))
112
        else:
113
            #print("Warning: cannot calculate RSS, arrays different sizes.")  # need to make this an actual warning
114
            rss = None
115
        return rss
116
117
    def _rmsd_from_rss(self, rss, n):
118
        return np.sqrt(rss/n)
119
120
    def calc_rmsd(self, array1, array2):
121
        if array1.shape == array2.shape:
122
            rss = self._calc_rss(array1, array2)
123
            rmsd = self._rmsd_from_rss(rss, array1.size)
124
        else:
125
            print("Warning: cannot calculate RMSD, arrays different sizes.")  # need to make this an actual warning
126
            rmsd = None
127
        return rmsd
128
129
    def calc_stats_residuals(self, stats_before, stats_after):
130
        residuals = {'max': None, 'min': None, 'mean': None, 'std_dev': None}
131
        for key in list(residuals.keys()):
132
            residuals[key] = stats_after[key] - stats_before[key]
133
        return residuals
134
135
    def set_stats_residuals(self, residuals):
136
        self.residuals['max'].append(residuals['max'])
137
        self.residuals['min'].append(residuals['min'])
138
        self.residuals['mean'].append(residuals['mean'])
139
        self.residuals['std_dev'].append(residuals['std_dev'])
140
141
    def calc_volume_stats(self, slice_stats):
142
        volume_stats = np.array([max(slice_stats['max']), min(slice_stats['min']), np.mean(slice_stats['mean']),
143
                                np.mean(slice_stats['std_dev']), np.median(slice_stats['std_dev'])])
144
        if None not in slice_stats['RSS']:
145
            total_rss = sum(slice_stats['RSS'])
146
            n = sum(slice_stats['data_points'])
147
            RMSD = self._rmsd_from_rss(total_rss, n)
148
            NRMSD = RMSD / abs(volume_stats[2])  # normalised RMSD (dividing by mean)
149
            volume_stats = np.append(volume_stats, NRMSD)
150
        else:
151
            #volume_stats = np.append(volume_stats, None)
152
            pass
153
        return volume_stats
154
155
    def _set_loop_stats(self):
156
        data_obj1 = list(self._iterative_group._ip_data_dict["iterating"].keys())[0]
157
        data_obj2 = self._iterative_group._ip_data_dict["iterating"][data_obj1]
158
        RMSD = self.calc_rmsd(data_obj1.data, data_obj2.data)
159
        NRMSD = RMSD/abs(self.get_stats(self.p_num, stat="mean", instance=self._iterative_group._ip_iteration))
160
        Statistics.loop_stats[self.l_num]["NRMSD"] = np.append(Statistics.loop_stats[self.l_num]["NRMSD"], NRMSD)
161
162
    def set_volume_stats(self):
163
        """Calculates volume-wide statistics from slice stats, and updates class-wide arrays with these values.
164
        Links volume stats with the output dataset and writes slice stats to file.
165
        """
166
        stats = self.stats
167
        combined_stats = self._combine_mpi_stats(stats)
168
        if not self.p_num:
169
            self.p_num = Statistics.count
170
        p_num = self.p_num
171
        name = self.plugin_name
172
        i = 2
173
        if not self._iterative_group:
174
            while name in list(Statistics.plugin_numbers.keys()):
175
                name = self.plugin_name + str(i)
176
                i += 1
177
        elif self._iterative_group._ip_iteration == 0:
178
            while name in list(Statistics.plugin_numbers.keys()):
179
                name = self.plugin_name + str(i)
180
                i += 1
181
182
        if p_num not in list(Statistics.plugin_names.keys()):
183
            Statistics.plugin_names[p_num] = name
184
        Statistics.plugin_numbers[name] = p_num
185
        if len(self.stats['max']) != 0:
186
            stats_array = self.calc_volume_stats(combined_stats)
187
            Statistics.global_residuals[p_num] = {}
188
            #before_processing = self.calc_volume_stats(self.stats_before_processing)
189
            #for key in list(before_processing.keys()):
190
            #    Statistics.global_residuals[p_num][key] = Statistics.global_stats[p_num][key] - before_processing[key]
191
192
            if len(Statistics.global_stats[p_num]) == 0:
193
                Statistics.global_stats[p_num] = stats_array
194
            else:
195
                Statistics.global_stats[p_num] = np.vstack([Statistics.global_stats[p_num], stats_array])
196
197
            self._link_stats_to_datasets(Statistics.global_stats[Statistics.plugin_numbers[name]])
198
199
        if self._iterative_group:
200
            if self._iterative_group.end_index == p_num and self._iterative_group._ip_iteration != 0:
201
                self._set_loop_stats()
202
203
        self._write_stats_to_file3(p_num)
204
        self._already_called = True
205
        self._repeat_count += 1
206
207
    def get_stats(self, p_num, stat=None, instance=1):
208
        """Returns stats associated with a certain plugin, given the plugin number (its place in the process list).
209
210
        :param p_num: Plugin  number of the plugin whose associated stats are being fetched.
211
            If p_num <= 0, it is relative to the plugin number of the current plugin being run.
212
            E.g current plugin number = 5, p_num = -2 --> will return stats of the third plugin.
213
        :param stat: Specify the stat parameter you want to fetch, i.e 'max', 'mean', 'median_std_dev'.
214
            If left blank will return the whole dictionary of stats:
215
            {'max': , 'min': , 'mean': , 'mean_std_dev': , 'median_std_dev': , 'NRMSD' }
216
        :param instance: In cases where there are multiple set of stats associated with a plugin
217
            due to loops or multi-parameters, specify which set you want to retrieve, i.e 3 to retrieve the
218
            stats associated with the third run of a plugin. Pass 'all' to get a list of all sets.
219
        """
220
        if p_num <= 0:
221
            try:
222
                p_num = self.p_num + p_num
223
            except TypeError:
224
                p_num = Statistics.count + p_num
225
        if Statistics.global_stats[p_num].ndim == 1 and instance in (None, 0, 1, "all"):
226
            stats_array = Statistics.global_stats[p_num]
227
        else:
228
            if instance == "all":
229
                stats_list = [self.get_stats(p_num, stat=stat, instance=1)]
230
                n = 2
231
                while n <= Statistics.global_stats[p_num].ndim:
232
                    stats_list.append(self.get_stats(p_num, stat=stat, instance=n))
233
                    n += 1
234
                return stats_list
235
            if instance > 0:
236
                instance -= 1
237
            stats_array = Statistics.global_stats[p_num][instance]
238
        stats_dict = self._array_to_dict(stats_array)
239
        if stat is not None:
240
            return stats_dict[stat]
241
        else:
242
            return stats_dict
243
244
    def get_stats_from_name(self, plugin_name, n=None, stat=None, instance=1):
245
        """Returns stats associated with a certain plugin.
246
247
        :param plugin_name: name of the plugin whose associated stats are being fetched.
248
        :param n: In a case where there are multiple instances of **plugin_name** in the process list,
249
            specify the nth instance. Not specifying will select the first (or only) instance.
250
        :param stat: Specify the stat parameter you want to fetch, i.e 'max', 'mean', 'median_std_dev'.
251
            If left blank will return the whole dictionary of stats:
252
            {'max': , 'min': , 'mean': , 'mean_std_dev': , 'median_std_dev': , 'NRMSD' }
253
        :param instance: In cases where there are multiple set of stats associated with a plugin
254
            due to loops or multi-parameters, specify which set you want to retrieve, i.e 3 to retrieve the
255
            stats associated with the third run of a plugin. Pass 'all' to get a list of all sets.
256
        """
257
        name = plugin_name
258
        if n in (None, 0, 1):
259
            name = name + str(n)
260
        p_num = Statistics.plugin_numbers[name]
261
        return self.get_stats(p_num, stat, instance)
262
263
    def get_stats_from_dataset(self, dataset, stat=None, instance=None):
264
        """Returns stats associated with a dataset.
265
266
        :param dataset: The dataset whose associated stats are being fetched.
267
        :param stat: Specify the stat parameter you want to fetch, i.e 'max', 'mean', 'median_std_dev'.
268
            If left blank will return the whole dictionary of stats:
269
            {'max': , 'min': , 'mean': , 'mean_std_dev': , 'median_std_dev': , 'NRMSD'}
270
        :param instance: In cases where there are multiple set of stats associated with a dataset
271
            due to loops or multi-parameters, specify which set you want to retrieve, i.e 3 to retrieve the
272
            stats associated with the third run of a plugin. Pass 'all' to get a list of all sets.
273
274
        """
275
        key = "stats"
276
        stats = {}
277
        if instance not in (None, 0, 1):
278
            if instance == "all":
279
                stats = [self.get_stats_from_dataset(dataset, stat=stat, instance=1)]
280
                n = 2
281
                while ("stats" + str(n)) in list(dataset.meta_data.get_dictionary().keys()):
282
                    stats.append(self.get_stats_from_dataset(dataset, stat=stat, instance=n))
283
                    n += 1
284
                return stats
285
            key = key + str(instance)
286
        stats = dataset.meta_data.get(key)
287
        if stat is not None:
288
            return stats[stat]
289
        else:
290
            return stats
291
292
    def _combine_mpi_stats(self, slice_stats):
293
        comm = MPI.COMM_WORLD
294
        combined_stats_list = comm.allgather(slice_stats)
295
        combined_stats = {'max': [], 'min': [], 'mean': [], 'std_dev': [], 'RSS': [], 'data_points': []}
296
        for single_stats in combined_stats_list:
297
            for key in list(single_stats.keys()):
298
                combined_stats[key] += single_stats[key]
299
        return combined_stats
300
301
    def _array_to_dict(self, stats_array):
302
        stats_dict = {}
303
        for i, value in enumerate(stats_array):
304
            stats_dict[Statistics._key_list[i]] = value
305
        return stats_dict
306
307
    def _set_pattern_info(self):
308
        """Gathers information about the pattern of the data in the current plugin."""
309
        in_datasets, out_datasets = self.plugin.get_datasets()
310
        try:
311
            self.pattern = self.plugin.parameters['pattern']
312
            if self.pattern == None:
313
                raise KeyError
314
        except KeyError:
315
            if not out_datasets:
316
                self.pattern = None
317
            else:
318
                patterns = out_datasets[0].get_data_patterns()
319
                for pattern in patterns:
320
                    if 1 in patterns.get(pattern)["slice_dims"]:
321
                        self.pattern = pattern
322
                        break
323
        self.calc_stats = False
324
        for dataset in out_datasets:
325
            if bool(set(Statistics._pattern_list) & set(dataset.data_info.get("data_patterns"))):
326
                self.calc_stats = True
327
328
    def _link_stats_to_datasets(self, stats):
329
        """Links the volume wide statistics to the output dataset(s)"""
330
        out_dataset = self.plugin.get_out_datasets()[0]
331
        n_datasets = self.plugin.nOutput_datasets()
332
        if self._repeat_count > 0:
333
            stats_dict = self._array_to_dict(stats[self._repeat_count])
334
        else:
335
            stats_dict = self._array_to_dict(stats)
336
        i = 2
337
        group_name = "stats"
338
        #out_dataset.data_info.set([group_name], stats)
339
        if n_datasets == 1:
340
            while group_name in list(out_dataset.meta_data.get_dictionary().keys()):
341
                group_name = f"stats{i}"
342
                i += 1
343
            for key in list(stats_dict.keys()):
344
                out_dataset.meta_data.set([group_name, key], stats_dict[key])
345
346
    def _write_stats_to_file2(self, p_num):
347
        path = Statistics.path
348
        filename = f"{path}/stats.h5"
349
        stats = Statistics.global_stats[p_num]
350
        array_dim = stats.shape
351
        self.hdf5 = Hdf5Utils(self.plugin.exp)
352
        group_name = f"{p_num}-{self.plugin_name}-stats"
353
        with h5.File(filename, "a") as h5file:
354
            if group_name not in h5file:
355
                group = h5file.create_group(group_name, track_order=None)
356
                dataset = self.hdf5.create_dataset_nofill(group, "stats", array_dim, stats.dtype)
357
                dataset[::] = stats[::]
358
            else:
359
                group = h5file[group_name]
360
361
362
    @classmethod
363
    def _write_stats_to_file4(cls):
364
        path = cls.path
365
        filename = f"{path}/stats.h5"
366
        stats = cls.global_stats
367
        cls.hdf5 = Hdf5Utils(cls.exp)
368
        for i in range(5):
369
            array = np.array([])
370
            stat = cls._key_list[i]
371
            for key in list(stats.keys()):
372
                if len(stats[key]) != 0:
373
                    if stats[key].ndim == 1:
374
                        array = np.append(array, stats[key][i])
375
                    else:
376
                        array = np.append(array, stats[key][0][i])
377
            array_dim = array.shape
378
            group_name = f"all-{stat}"
379
            with h5.File(filename, "a") as h5file:
380
                group = h5file.create_group(group_name, track_order=None)
381
                dataset = cls.hdf5.create_dataset_nofill(group, stat, array_dim, array.dtype)
382
                dataset[::] = array[::]
383
384
    def _write_stats_to_file3(self, p_num=None):
385
        if not p_num:
386
            p_num = self.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", self.plugin_names[p_num])
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
        print(Statistics.loop_stats)
493
        if cls._any_stats & cls.stats_flag:
494
            stats_utils = StatsUtils()
495
            stats_utils.generate_figures(f"{cls.path}/stats.h5", cls.path)
496