Skip to content

Module dcm2bids.sidecar⚓︎

sidecars classes

None

View Source
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
# -*- coding: utf-8 -*-

"""sidecars classes"""

import itertools

import logging

import os

import re

from collections import defaultdict, OrderedDict

from fnmatch import fnmatch

from future.utils import iteritems

from .structure import Acquisition

from .utils import DEFAULT, load_json, splitext_

class Sidecar(object):

    """ A sidecar object

    Args:

        filename (str): Path of a JSON sidecar

        keyComp (list): A list of keys from the JSON sidecar to compare sidecars

                     default=["SeriesNumber","AcquisitionTime","SideCarFilename"]

    """

    def __init__(self, filename, compKeys=DEFAULT.compKeys):

        self._origData = {}

        self._data = {}

        self.filename = filename

        self.root, _ = splitext_(filename)

        self.data = filename

        self.compKeys = compKeys

    def __lt__(self, other):

        lts = []

        for key in self.compKeys:

            try:

                if all(key in d for d in (self.data, other.data)):

                    if self.data.get(key) == other.data.get(key):

                        lts.append(None)

                    else:

                        lts.append(self.data.get(key) < other.data.get(key))

                else:

                    lts.append(None)

            except:

                lts.append(None)

        for lt in lts:

            if lt is not None:

                return lt

    def __eq__(self, other):

        return self.data == other.data

    def __hash__(self):

        return hash(self.filename)

    @property

    def origData(self):

        return self._origData

    @property

    def data(self):

        return self._data

    @data.setter

    def data(self, filename):

        """

        Args:

            filename (path): path of a JSON file

        Return:

            A dictionnary of the JSON content plus the SidecarFilename

        """

        try:

            data = load_json(filename)

        except:

            data = {}

        self._origData = data.copy()

        data["SidecarFilename"] = os.path.basename(filename)

        self._data = data

class SidecarPairing(object):

    """

    Args:

        sidecars (list): List of Sidecar objects

        descriptions (list): List of dictionaries describing acquisitions

    """

    def __init__(self, sidecars, descriptions, searchMethod=DEFAULT.searchMethod,

                 caseSensitive=DEFAULT.caseSensitive):

        self.logger = logging.getLogger(__name__)

        self._searchMethod = ""

        self.graph = OrderedDict()

        self.acquisitions = []

        self.sidecars = sidecars

        self.descriptions = descriptions

        self.searchMethod = searchMethod

        self.caseSensitive = caseSensitive

    @property

    def searchMethod(self):

        return self._searchMethod

    @searchMethod.setter

    def searchMethod(self, value):

        """

        Checks if the search method is implemented

        Warns the user if not and fall back to default

        """

        if value in DEFAULT.searchMethodChoices:

            self._searchMethod = value

        else:

            self._searchMethod = DEFAULT.searchMethod

            self.logger.warning("'%s' is not a search method implemented", value)

            self.logger.warning(

                "Falling back to default: %s", DEFAULT.searchMethod

            )

            self.logger.warning(

                "Search methods implemented: %s", DEFAULT.searchMethodChoices

            )

    @property

    def caseSensitive(self):

        return self._caseSensitive

    @caseSensitive.setter

    def caseSensitive(self, value):

        if isinstance(value, bool):

            self._caseSensitive = value

        else:

            self._caseSensitive = DEFAULT.caseSensitive

            self.logger.warning("'%s' is not a boolean", value)

            self.logger.warning(

                "Falling back to default: %s", DEFAULT.caseSensitive

            )

            self.logger.warning(

                "Search methods implemented: %s", DEFAULT.caseSensitive

            )

    def build_graph(self):

        """

        Test all the possible links between the list of sidecars and the

        description dictionaries and build a graph from it

        The graph is in a OrderedDict object. The keys are the Sidecars and

        the values are a list of possible descriptions

        Returns:

            A graph (OrderedDict)

        """

        graph = OrderedDict((_, []) for _ in self.sidecars)

        possibleLinks = itertools.product(self.sidecars, self.descriptions)

        for sidecar, description in possibleLinks:

            criteria = description.get("criteria", None)

            if criteria and self.isLink(sidecar.data, criteria):

                graph[sidecar].append(description)

        self.graph = graph

        return graph

    def isLink(self, data, criteria):

        """

        Args:

            data (dict): Dictionnary data of a sidecar

            criteria (dict): Dictionnary criteria

        Returns:

            boolean

        """

        def compare(name, pattern):

            name = str(name)

            if self.searchMethod == "re":

                return bool(re.match(pattern, name))

            else:

                pattern = str(pattern)

                if not self.caseSensitive:

                    name = name.lower()

                    pattern = pattern.lower()

                return fnmatch(name, pattern)

        result = []

        for tag, pattern in iteritems(criteria):

            name = data.get(tag, '')

            if isinstance(name, list):

                try:

                    subResult = [len(name) == len(pattern), isinstance(pattern, list)]

                    for subName, subPattern in zip(name, pattern):

                        subResult.append(compare(subName, subPattern))

                except:

                    subResult = [False]

                result.append(all(subResult))

            else:

                result.append(compare(name, pattern))

        return all(result)

    def build_acquisitions(self, participant):

        """

        Args:

            participant (Participant): Participant object to create acquisitions

        Returns:

            A list of acquisition objects

        """

        acquisitions = []

        acquisitions_intendedFor = []

        self.logger.info("Sidecars pairing:")

        for sidecar, valid_descriptions in iteritems(self.graph):

            sidecarName = os.path.basename(sidecar.root)

            # only one description for the sidecar

            if len(valid_descriptions) == 1:

                desc = valid_descriptions[0]

                acq = Acquisition(participant,

                                  srcSidecar=sidecar, **desc)

                acq.indexSidecar = self.descriptions.index(desc)

                acq.setDstFile()

                if acq.intendedFor != [None]:

                    acquisitions_intendedFor.append(acq)

                else:

                    acquisitions.append(acq)

                self.logger.info("%s  <-  %s", acq.suffix, sidecarName)

            # sidecar with no link

            elif len(valid_descriptions) == 0:

                self.logger.info("No Pairing  <-  %s", sidecarName)

            # sidecar with several links

            else:

                self.logger.warning("Several Pairing  <-  %s", sidecarName)

                for desc in valid_descriptions:

                    acq = Acquisition(participant,

                                      indexSidecar=self.descriptions.index(desc),

                                      **desc)

                    self.logger.warning("    ->  %s", acq.suffix)

        self.acquisitions = acquisitions + acquisitions_intendedFor

        return self.acquisitions

    def find_runs(self):

        """

        Check if there is duplicate destination roots in the acquisitions

        and add '_run-' to the customLabels of the acquisition

        """

        def duplicates(seq):

            """ Find duplicate items in a list

            Args:

                seq (list)

            Yield:

                A tuple of 2 items (item, list of index)

            ref: http://stackoverflow.com/a/5419576

            """

            tally = defaultdict(list)

            for i, item in enumerate(seq):

                tally[item].append(i)

            for key, locs in iteritems(tally):

                if len(locs) > 1:

                    yield key, locs

        dstRoots = [_.dstRoot for _ in self.acquisitions]

        for dstRoot, dup in duplicates(dstRoots):

            self.logger.info("%s has %s runs", dstRoot, len(dup))

            self.logger.info("Adding 'run' information to the acquisition")

            for runNum, acqInd in enumerate(dup):

                runStr = DEFAULT.runTpl.format(runNum + 1)

                self.acquisitions[acqInd].customLabels += runStr

Classes⚓︎

Sidecar⚓︎

1
2
3
4
class Sidecar(
    filename,
    compKeys=['SeriesNumber', 'AcquisitionTime', 'SidecarFilename']
)

Attributes⚓︎

Name Type Description Default
filename str Path of a JSON sidecar None
keyComp list A list of keys from the JSON sidecar to compare sidecars
default=["SeriesNumber","AcquisitionTime","SideCarFilename"] None
View Source
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
class Sidecar(object):

    """ A sidecar object

    Args:

        filename (str): Path of a JSON sidecar

        keyComp (list): A list of keys from the JSON sidecar to compare sidecars

                     default=["SeriesNumber","AcquisitionTime","SideCarFilename"]

    """

    def __init__(self, filename, compKeys=DEFAULT.compKeys):

        self._origData = {}

        self._data = {}

        self.filename = filename

        self.root, _ = splitext_(filename)

        self.data = filename

        self.compKeys = compKeys

    def __lt__(self, other):

        lts = []

        for key in self.compKeys:

            try:

                if all(key in d for d in (self.data, other.data)):

                    if self.data.get(key) == other.data.get(key):

                        lts.append(None)

                    else:

                        lts.append(self.data.get(key) < other.data.get(key))

                else:

                    lts.append(None)

            except:

                lts.append(None)

        for lt in lts:

            if lt is not None:

                return lt

    def __eq__(self, other):

        return self.data == other.data

    def __hash__(self):

        return hash(self.filename)

    @property

    def origData(self):

        return self._origData

    @property

    def data(self):

        return self._data

    @data.setter

    def data(self, filename):

        """

        Args:

            filename (path): path of a JSON file

        Return:

            A dictionnary of the JSON content plus the SidecarFilename

        """

        try:

            data = load_json(filename)

        except:

            data = {}

        self._origData = data.copy()

        data["SidecarFilename"] = os.path.basename(filename)

        self._data = data

Instance variables⚓︎

1
data
1
origData

SidecarPairing⚓︎

1
2
3
4
5
6
class SidecarPairing(
    sidecars,
    descriptions,
    searchMethod='fnmatch',
    caseSensitive=True
)
View Source
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
class SidecarPairing(object):

    """

    Args:

        sidecars (list): List of Sidecar objects

        descriptions (list): List of dictionaries describing acquisitions

    """

    def __init__(self, sidecars, descriptions, searchMethod=DEFAULT.searchMethod,

                 caseSensitive=DEFAULT.caseSensitive):

        self.logger = logging.getLogger(__name__)

        self._searchMethod = ""

        self.graph = OrderedDict()

        self.acquisitions = []

        self.sidecars = sidecars

        self.descriptions = descriptions

        self.searchMethod = searchMethod

        self.caseSensitive = caseSensitive

    @property

    def searchMethod(self):

        return self._searchMethod

    @searchMethod.setter

    def searchMethod(self, value):

        """

        Checks if the search method is implemented

        Warns the user if not and fall back to default

        """

        if value in DEFAULT.searchMethodChoices:

            self._searchMethod = value

        else:

            self._searchMethod = DEFAULT.searchMethod

            self.logger.warning("'%s' is not a search method implemented", value)

            self.logger.warning(

                "Falling back to default: %s", DEFAULT.searchMethod

            )

            self.logger.warning(

                "Search methods implemented: %s", DEFAULT.searchMethodChoices

            )

    @property

    def caseSensitive(self):

        return self._caseSensitive

    @caseSensitive.setter

    def caseSensitive(self, value):

        if isinstance(value, bool):

            self._caseSensitive = value

        else:

            self._caseSensitive = DEFAULT.caseSensitive

            self.logger.warning("'%s' is not a boolean", value)

            self.logger.warning(

                "Falling back to default: %s", DEFAULT.caseSensitive

            )

            self.logger.warning(

                "Search methods implemented: %s", DEFAULT.caseSensitive

            )

    def build_graph(self):

        """

        Test all the possible links between the list of sidecars and the

        description dictionaries and build a graph from it

        The graph is in a OrderedDict object. The keys are the Sidecars and

        the values are a list of possible descriptions

        Returns:

            A graph (OrderedDict)

        """

        graph = OrderedDict((_, []) for _ in self.sidecars)

        possibleLinks = itertools.product(self.sidecars, self.descriptions)

        for sidecar, description in possibleLinks:

            criteria = description.get("criteria", None)

            if criteria and self.isLink(sidecar.data, criteria):

                graph[sidecar].append(description)

        self.graph = graph

        return graph

    def isLink(self, data, criteria):

        """

        Args:

            data (dict): Dictionnary data of a sidecar

            criteria (dict): Dictionnary criteria

        Returns:

            boolean

        """

        def compare(name, pattern):

            name = str(name)

            if self.searchMethod == "re":

                return bool(re.match(pattern, name))

            else:

                pattern = str(pattern)

                if not self.caseSensitive:

                    name = name.lower()

                    pattern = pattern.lower()

                return fnmatch(name, pattern)

        result = []

        for tag, pattern in iteritems(criteria):

            name = data.get(tag, '')

            if isinstance(name, list):

                try:

                    subResult = [len(name) == len(pattern), isinstance(pattern, list)]

                    for subName, subPattern in zip(name, pattern):

                        subResult.append(compare(subName, subPattern))

                except:

                    subResult = [False]

                result.append(all(subResult))

            else:

                result.append(compare(name, pattern))

        return all(result)

    def build_acquisitions(self, participant):

        """

        Args:

            participant (Participant): Participant object to create acquisitions

        Returns:

            A list of acquisition objects

        """

        acquisitions = []

        acquisitions_intendedFor = []

        self.logger.info("Sidecars pairing:")

        for sidecar, valid_descriptions in iteritems(self.graph):

            sidecarName = os.path.basename(sidecar.root)

            # only one description for the sidecar

            if len(valid_descriptions) == 1:

                desc = valid_descriptions[0]

                acq = Acquisition(participant,

                                  srcSidecar=sidecar, **desc)

                acq.indexSidecar = self.descriptions.index(desc)

                acq.setDstFile()

                if acq.intendedFor != [None]:

                    acquisitions_intendedFor.append(acq)

                else:

                    acquisitions.append(acq)

                self.logger.info("%s  <-  %s", acq.suffix, sidecarName)

            # sidecar with no link

            elif len(valid_descriptions) == 0:

                self.logger.info("No Pairing  <-  %s", sidecarName)

            # sidecar with several links

            else:

                self.logger.warning("Several Pairing  <-  %s", sidecarName)

                for desc in valid_descriptions:

                    acq = Acquisition(participant,

                                      indexSidecar=self.descriptions.index(desc),

                                      **desc)

                    self.logger.warning("    ->  %s", acq.suffix)

        self.acquisitions = acquisitions + acquisitions_intendedFor

        return self.acquisitions

    def find_runs(self):

        """

        Check if there is duplicate destination roots in the acquisitions

        and add '_run-' to the customLabels of the acquisition

        """

        def duplicates(seq):

            """ Find duplicate items in a list

            Args:

                seq (list)

            Yield:

                A tuple of 2 items (item, list of index)

            ref: http://stackoverflow.com/a/5419576

            """

            tally = defaultdict(list)

            for i, item in enumerate(seq):

                tally[item].append(i)

            for key, locs in iteritems(tally):

                if len(locs) > 1:

                    yield key, locs

        dstRoots = [_.dstRoot for _ in self.acquisitions]

        for dstRoot, dup in duplicates(dstRoots):

            self.logger.info("%s has %s runs", dstRoot, len(dup))

            self.logger.info("Adding 'run' information to the acquisition")

            for runNum, acqInd in enumerate(dup):

                runStr = DEFAULT.runTpl.format(runNum + 1)

                self.acquisitions[acqInd].customLabels += runStr

Instance variables⚓︎

1
caseSensitive
1
searchMethod

Methods⚓︎

build_acquisitions⚓︎

1
2
3
4
def build_acquisitions(
    self,
    participant
)

Parameters:

Name Type Description Default
participant Participant Participant object to create acquisitions None

Returns:

Type Description
None A list of acquisition objects
View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
    def build_acquisitions(self, participant):

        """

        Args:

            participant (Participant): Participant object to create acquisitions

        Returns:

            A list of acquisition objects

        """

        acquisitions = []

        acquisitions_intendedFor = []

        self.logger.info("Sidecars pairing:")

        for sidecar, valid_descriptions in iteritems(self.graph):

            sidecarName = os.path.basename(sidecar.root)

            # only one description for the sidecar

            if len(valid_descriptions) == 1:

                desc = valid_descriptions[0]

                acq = Acquisition(participant,

                                  srcSidecar=sidecar, **desc)

                acq.indexSidecar = self.descriptions.index(desc)

                acq.setDstFile()

                if acq.intendedFor != [None]:

                    acquisitions_intendedFor.append(acq)

                else:

                    acquisitions.append(acq)

                self.logger.info("%s  <-  %s", acq.suffix, sidecarName)

            # sidecar with no link

            elif len(valid_descriptions) == 0:

                self.logger.info("No Pairing  <-  %s", sidecarName)

            # sidecar with several links

            else:

                self.logger.warning("Several Pairing  <-  %s", sidecarName)

                for desc in valid_descriptions:

                    acq = Acquisition(participant,

                                      indexSidecar=self.descriptions.index(desc),

                                      **desc)

                    self.logger.warning("    ->  %s", acq.suffix)

        self.acquisitions = acquisitions + acquisitions_intendedFor

        return self.acquisitions

build_graph⚓︎

1
2
3
def build_graph(
    self
)

Test all the possible links between the list of sidecars and the

description dictionaries and build a graph from it The graph is in a OrderedDict object. The keys are the Sidecars and the values are a list of possible descriptions

Returns:

Type Description
None A graph (OrderedDict)
View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
    def build_graph(self):

        """

        Test all the possible links between the list of sidecars and the

        description dictionaries and build a graph from it

        The graph is in a OrderedDict object. The keys are the Sidecars and

        the values are a list of possible descriptions

        Returns:

            A graph (OrderedDict)

        """

        graph = OrderedDict((_, []) for _ in self.sidecars)

        possibleLinks = itertools.product(self.sidecars, self.descriptions)

        for sidecar, description in possibleLinks:

            criteria = description.get("criteria", None)

            if criteria and self.isLink(sidecar.data, criteria):

                graph[sidecar].append(description)

        self.graph = graph

        return graph

find_runs⚓︎

1
2
3
def find_runs(
    self
)

Check if there is duplicate destination roots in the acquisitions

and add '_run-' to the customLabels of the acquisition

View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
    def find_runs(self):

        """

        Check if there is duplicate destination roots in the acquisitions

        and add '_run-' to the customLabels of the acquisition

        """

        def duplicates(seq):

            """ Find duplicate items in a list

            Args:

                seq (list)

            Yield:

                A tuple of 2 items (item, list of index)

            ref: http://stackoverflow.com/a/5419576

            """

            tally = defaultdict(list)

            for i, item in enumerate(seq):

                tally[item].append(i)

            for key, locs in iteritems(tally):

                if len(locs) > 1:

                    yield key, locs

        dstRoots = [_.dstRoot for _ in self.acquisitions]

        for dstRoot, dup in duplicates(dstRoots):

            self.logger.info("%s has %s runs", dstRoot, len(dup))

            self.logger.info("Adding 'run' information to the acquisition")

            for runNum, acqInd in enumerate(dup):

                runStr = DEFAULT.runTpl.format(runNum + 1)

                self.acquisitions[acqInd].customLabels += runStr
1
2
3
4
5
def isLink(
    self,
    data,
    criteria
)

Parameters:

Name Type Description Default
data dict Dictionnary data of a sidecar None
criteria dict Dictionnary criteria None

Returns:

Type Description
None boolean
View Source
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
    def isLink(self, data, criteria):

        """

        Args:

            data (dict): Dictionnary data of a sidecar

            criteria (dict): Dictionnary criteria

        Returns:

            boolean

        """

        def compare(name, pattern):

            name = str(name)

            if self.searchMethod == "re":

                return bool(re.match(pattern, name))

            else:

                pattern = str(pattern)

                if not self.caseSensitive:

                    name = name.lower()

                    pattern = pattern.lower()

                return fnmatch(name, pattern)

        result = []

        for tag, pattern in iteritems(criteria):

            name = data.get(tag, '')

            if isinstance(name, list):

                try:

                    subResult = [len(name) == len(pattern), isinstance(pattern, list)]

                    for subName, subPattern in zip(name, pattern):

                        subResult.append(compare(subName, subPattern))

                except:

                    subResult = [False]

                result.append(all(subResult))

            else:

                result.append(compare(name, pattern))

        return all(result)

Last update: 2022-06-17
Back to top