Filters

The filter module defines a class named SNPFilter. An app creates an instance of this class to act as an interface to the full set of SNPs. The general workflow is:

  • call the method that loads SNP data from a CSV file
  • assign values for filtering criteria (block size, etc)
  • call the apply method to apply the filters

SNPFilter(args)

A SNPFilter applies filtering criteria to SNPs in blocks identified by the peak finder. Pass the constructor a dictionary that has settings filtering critera. Call a method named apply to filter a data set.

Attributes:
  • chromosome –

    when filtering return SNPs in chromosomes with names that match this pattern

  • size_range –

    a pair of integers with the minimum and maximum number of SNPs in a block

  • length_range –

    a pair of integers with the minimum and maxium block length (in base pairs)

  • coverage –

    a minimum number of reads required to use a SNP

  • matched –

    True if a SNP's base genome must be the same as the HMM state

Source code in src/xo/filters.py
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
def __init__(self, args):
    c = Config()
    self._chromosome = c.filter_chromosome_pattern
    self._min_size, self._max_size = c.filter_block_size
    self._min_length, self._max_length = c.filter_block_length
    self._coverage = c.filter_coverage
    self._matched = False
    self._result = None
    self._summary = None

    filter_params = {
        'chromosomes':  'chromosome',
        'size':         'size_range',
        'length':       'length_range',
        'coverage':     'coverage',
        'match':        'matched',
    }
    for arg, attr in filter_params.items():
        if val := args.get(arg):
            setattr(self, attr, val)

chromosome property writable

Filtered SNPs must have names that match this pattern.

size_range property writable

Minimum and maximum block size (number of SNPs)

length_range property writable

Minimum and maximum block length (bp)

matched property writable

If True SNPs must have matching HMM state

coverage property writable

Minimum number of reads for a SNP

result property

Filtered data

summary property

Summary of filtered data

apply(df)

Apply the filtering criteria to a set of SNPs. The first step is to make a subset of SNPs that pass the chromosome name, coverage, and match filters.
The resulting frame is then grouped by block.

The second step makes a separate summary frame based on size and location of each block. This frame is then filtered using the block size and block length filters.

Parameters:
  • df –

    a data frame containing SNPs (including block IDs)

Returns:
  • res –

    a frame containing the filtered data

  • summary –

    a data frame with size, length, and location of each block

Source code in src/xo/filters.py
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
def apply(self, df):
    '''
    Apply the filtering criteria to a set of SNPs.  The first step is to make a 
    subset of SNPs that pass the chromosome name, coverage, and match filters.  
    The resulting frame is then grouped by block.

    The second step makes a separate summary frame based on size and location of
    each block.  This frame is then filtered using the block size and block length
    filters.

    Arguments:
      df:  a data frame containing SNPs (including block IDs)

    Returns:
      res:  a frame containing the filtered data
      summary:  a data frame with size, length, and location of each block
    '''
    logging.info(f'SNPFilter.apply {len(df)} SNPs')
    df = df[df.chrom_id.map(lambda s: bool(re.match(self._chromosome,s)))]
    logging.info(f'  chromosome:  {len(df)} match {self._chromosome}')

    if self._matched:
        df = df[df.base_geno == df.hmm_state1]
        logging.info(f'  match: {len(df)} have genome match')

    if self._coverage:
        df = df[df.var_reads + df.ref_reads >= self._coverage]
        logging.info(f'  coverage:  {len(df)} have reads ≥ {self._coverage}')

    groups = df.groupby(['chrom_id','blk_id'])
    logging.info(f'Groupd into {len(groups)} blocks')

    sf = pd.concat(
        [
            groups.size().rename('blk_size'), 
            (groups.max('position') - groups.min('position')).position.rename('blk_len'), 
            groups.mean('location').location.rename('blk_loc'),
        ],
        axis=1
    )


    min_size = sf.blk_size >= self._min_size
    max_size = sf.blk_size <= self._max_size
    min_len = sf.blk_len >= self._min_length
    max_len = sf.blk_len <= self._max_length

    sf = sf[min_size & max_size & min_len & max_len]
    logging.info(f'Summary has {sf.blk_size.sum()} SNPs in {len(sf)} blocks')

    if len(sf) > 0:
        res = pd.concat(groups.get_group(n) for n in sf.index)
    else:
        res = pd.DataFrame(columns=df.columns)

    return res, sf

NCOFilter(args)

An NCOFilter applies additional filtering criteria to blocks of SNPs.
Pass the constructor a dictionary that has settings filtering critera.
Call a method named apply to filter a data set.

Attributes:
  • min_z –

    homozygosity for type A blocks

  • delta_z –

    homozygosity for type B blocks

  • min_cover –

    minumum number of reads of each type

  • size –

    minimum block size

Source code in src/xo/filters.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
def __init__(self, args):
    c = Config()
    self._min_z = c.post_min_z
    self._delta_z = c.post_delta_z
    self._min_cover = c.post_min_cover
    self._size = c.post_block_size
    self._result = None

    filter_params = ['min_z','delta_z', 'min_cover', 'size']

    for attr in filter_params:
        if val := args.get(attr):
            logging.debug(f'{attr} {val}')
            setattr(self, attr, val)

min_z property writable

Minimum homozygosity for Type A blocks

delta_z property writable

Homozygosity range for Type B blocks

min_cover property writable

Minimum number of SNPs of each type

size property writable

Minimum block size

result property

Filtered data

apply(df)

Apply the NCO filtering criteria to a set of SNPs in filtered blocks SNPs.

Parameters:
  • df –

    a data frame of filtered SNPs

Returns:
  • res –

    a frame containing the filtered data

Source code in src/xo/filters.py
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
def apply(self, df):
    '''
    Apply the NCO filtering criteria to a set of SNPs in filtered blocks SNPs.

    Arguments:
      df:  a data frame of filtered SNPs

    Returns:
      res:  a frame containing the filtered data
    '''
    logging.info(f'NCOFilter.appy {len(df)} SNPs')

    res = []
    for name, block in df.groupby(['chrom_id','blk_id']):
        logging.debug(f'{name} {len(block)} SNPs')
        block['nco'] = self._scan(block)
        res.append(block)

    if len(res) > 0:
       self._result = pd.concat(res)
    else:
        self._result = pd.DataFrame(columns=df.columns)

    return self._result

_scan(block)

Scan a block for runs that have satisfy homozygosity requirements and have a minimum number of SNPs. Add a column to a block to show which SNPs might be part of an NCO.

Source code in src/xo/filters.py
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
def _scan(self, block):
    '''
    Scan a block for runs that have satisfy homozygosity requirements
    and have a minimum number of SNPs.  Add a column to a block to
    show which SNPs might be part of an NCO.
    '''

    def next_interval():
        nonlocal i, j
        j = i
        logging.debug(f'next_interval {i} {j}')
        while (j < len(p)):
            logging.debug(f'{i} {j} {p.iloc[j]}')
            if p.iloc[j]:
                logging.debug(f'extend {j}')
                j += 1
            elif j - i >= self.size:
                logging.debug(f'long enough {i} {j}')
                break
            else:
                logging.debug(f'restart')
                j += 1
                i = j
        logging.debug(f'exit {i} {j} {self.size}')

    # block['nco'] = 0
    col = np.zeros(len(block), dtype=np.int8)

    z = block.homozygosity
    if block.iloc[0].background == 'CB4856':
        rr = block.ref_reads
        p = (z >= self.min_z) & (rr >= self.min_cover)
    else:
        rr = block.ref_reads
        vr = block.var_reads
        p = (abs(z - 0.5) <= self.delta_z) & (rr >= self.min_cover) & (vr >= self.min_cover)

    col[p] = 1

    res = []
    i = j = 0
    while i < len(block):
        next_interval()
        if (j - i) >= self.size:
            res.append((i,j))
        i = j + 1
        if len(res) > 3:
            break
    logging.debug(f'res {res}')

    if res:
        res.sort(key=lambda p: p[1]-p[0])
        i, j = res[-1]
        logging.debug(f'nco: {i}..{j}')
        col[i:j] = 2

    return col