Test Failed
Pull Request — master (#878)
by Yousef
04:34
created

savu.plugins.stats.statistics   F

Complexity

Total Complexity 120

Size/Duplication

Total Lines 496
Duplicated Lines 0 %

Importance

Changes 0
Metric Value
eloc 368
dl 0
loc 496
rs 2
c 0
b 0
f 0
wmc 120

29 Methods

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