Skip to content

TLSpectrum_mod

Contains triallelic Spectrum object

TLSpectrum

Bases: masked_array

Represents a two-locus frequency spectrum.

The constructor has the format

fs = dadi.Triallele.TLSpectrum(data, mask, mask_infeasible, data_folded, extrap_x, extrap_t)

data: The triallelic frequency spectrum data

mask: An optional array of the same size as data, similar to dadi.Spectrum

data_folded: If True, it is assumed that the input data is folded

check_folding: If True and data_folded=True, the data and mask will be checked to ensure they are consistent

extrap_x: Optional floating point value specifying x value to use in extrapolation.

extrap_t: Optional floating point value specifying t value to use in extrapolation.

from_file(fid, mask_infeasible=True, return_comments=False) staticmethod

Read frequency spectrum from file.

Parameters:

Name Type Description Default
fid str

string with file name to read from or an open file object.

required
mask_infeasible bool

If True, mask the infeasible entries in the triallelic spectrum.

True
return_comments bool

If true, the return value is (fs, comments), where comments is a list of strings containing the comments from the file (without #'s).

False

See to_file method for details on the file format.

Source code in dadi/TwoLocus/TLSpectrum_mod.py
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
@staticmethod
def from_file(fid, mask_infeasible=True, return_comments=False):
    """
    Read frequency spectrum from file.

    Args:
        fid (str): string with file name to read from or an open file object.
        mask_infeasible (bool, optional): If True, mask the infeasible entries in the triallelic spectrum.
        return_comments (bool, optional): If true, the return value is (fs, comments), where
                        comments is a list of strings containing the comments
                        from the file (without #'s).

    See to_file method for details on the file format.
    """
    newfile = False
    # Try to read from fid. If we can't, assume it's something that we can
    # use to open a file.
    if not hasattr(fid, 'read'):
        newfile = True
        fid = open(fid, 'r')

    line = fid.readline()
    # Strip out the comments
    comments = []
    while line.startswith('#'):
        comments.append(line[1:].strip())
        line = fid.readline()

    # Read the shape of the data
    shape,folded,extrap_x,extrap_t = line.split()
    shape = [int(shape)+1,int(shape)+1,int(shape)+1]

    data = np.fromstring(fid.readline().strip(), 
                            count=np.prod(shape), sep=' ')
    # fromfile returns a 1-d array. Reshape it to the proper form.
    data = data.reshape(*shape)

    maskline = fid.readline().strip()
    mask = np.fromstring(maskline, 
                            count=np.prod(shape), sep=' ')
    mask = mask.reshape(*shape)

    if folded == 'folded':
        folded = True
    else:
        folded = False
    if extrap_x == 'None':
        extrap_x = None
    else:
        extrap_x = float(extrap_x)
    if extrap_t == 'None':
        extrap_t = None
    else:
        extrap_t = float(extrap_t)

    # If we opened a new file, clean it up.
    if newfile:
        fid.close()

    fs = TLSpectrum(data, mask, mask_infeasible, data_folded=folded)
    fs.extrap_x = extrap_x
    fs.extrap_t = extrap_t
    if not return_comments:
        return fs
    else:
        return fs,comments

marginalA()

Marginal 1D frequency spectrum for A locus.

Source code in dadi/TwoLocus/TLSpectrum_mod.py
290
291
292
293
294
295
296
297
298
299
300
301
302
def marginalA(self):
    """
    Marginal 1D frequency spectrum for A locus.
    """
    ns = self.shape[0] - 1
    marg = dadi.Spectrum(np.zeros(ns+1))
    for fAB in range(ns):
        for fAb in range(ns-fAB):
            marg[fAB+fAb] += self[fAB,fAb,:].sum()

    marg.extrap_x = self.extrap_x
    marg.extrap_t = self.extrap_t
    return marg

marginalB()

Marginal 1D frequency spectrum for B locus.

Source code in dadi/TwoLocus/TLSpectrum_mod.py
304
305
306
307
308
309
310
311
312
313
314
315
316
def marginalB(self):
    """
    Marginal 1D frequency spectrum for B locus.
    """
    ns = self.shape[0] - 1
    marg = dadi.Spectrum(np.zeros(ns+1))
    for fAB in range(ns):
        for faB in range(ns-fAB):
            marg[fAB+faB] += self[fAB,:,faB].sum()

    marg.extrap_x = self.extrap_x
    marg.extrap_t = self.extrap_t
    return marg

mask_infeasible()

Mask any infeasible entries.

Source code in dadi/TwoLocus/TLSpectrum_mod.py
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
def mask_infeasible(self):
    """
    Mask any infeasible entries.
    """
    ns = len(self)-1
    self.mask[0,0,0] = True
    self.mask[0,:,0] = True
    self.mask[0,0,:] = True
    for ii in range(len(self)):
        for jj in range(len(self)):
            for kk in range(len(self)):
                if ii+jj+kk > ns:
                    self.mask[ii,jj,kk] = True

    for ii in range(len(self)):
        self.mask[ii,ns-ii,0] = True
        self.mask[ii,0,ns-ii] = True

    return self

mean_r2()

Mean of normalized squared correlation coefficient between A and B loci.

Source code in dadi/TwoLocus/TLSpectrum_mod.py
318
319
320
321
322
323
324
325
326
def mean_r2(self):
    """
    Mean of normalized squared correlation coefficient between A and B loci.
    """
    from . import numerics
    ns = self.shape[0] - 1
    norm = self.sum()
    Dbin, r2bin = numerics.LD_per_bin(ns)
    return (self*r2bin).sum()/self.sum()

to_file(fid, precision=16, comment_lines=[], foldmaskinfo=True, extrapinfo=True)

Write frequency spectrum to file.

Parameters:

Name Type Description Default
fid str

string with file name to write to or an open file object.

required
precision int

precision with which to write out entries of the SFS. (They are formated via %.

g, where

is the precision.)

16
comment_lines list[str]

list of strings to be used as comment lines in the header of the output file.

[]
foldmaskinfo bool

If False, folding and mask and population label information will not be saved. This conforms to the file format for dadi versions prior to 1.3.0.

True
extrapinfo bool

If False, extrapolation information will not be saved.

True
The file format is

Any number of comment lines beginning with a '#'

A single line containing N integers giving the dimensions of the fs array. So this line would be '5 5 3' for an SFS that was 5x5x3. (That would be 4x4x2 samples.)

On the same line, the string 'folded' or 'unfolded' denoting the folding status of the array

A single line giving the array elements. The order of elements is e.g.: fs[0,0,0] fs[0,0,1] fs[0,0,2] ... fs[0,1,0] fs[0,1,1] ...

A single line giving the elements of the mask in the same order as the data line. '1' indicates masked, '0' indicates unmasked.

Source code in dadi/TwoLocus/TLSpectrum_mod.py
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
def to_file(self, fid, precision=16, comment_lines=[], foldmaskinfo=True, extrapinfo=True):
    """
    Write frequency spectrum to file.

    Args:
        fid (str): string with file name to write to or an open file object.
        precision (int, optional): precision with which to write out entries of the SFS. (They 
                are formated via %.<p>g, where <p> is the precision.)
        comment_lines (list[str], optional): list of strings to be used as comment lines in the header
                    of the output file.
        foldmaskinfo (bool, optional): If False, folding and mask and population label
                    information will not be saved. This conforms to the file
                    format for dadi versions prior to 1.3.0.
        extrapinfo (bool, optional): If False, extrapolation information will not be saved.

    The file format is:
        Any number of comment lines beginning with a '#'

        A single line containing N integers giving the dimensions of the fs
            array. So this line would be '5 5 3' for an SFS that was 5x5x3.
            (That would be 4x4x2 *samples*.)

        On the *same line*, the string 'folded' or 'unfolded' 
          denoting the folding status of the array

        A single line giving the array elements. The order of elements is 
             e.g.: fs[0,0,0] fs[0,0,1] fs[0,0,2] ... fs[0,1,0] fs[0,1,1] ...

        A single line giving the elements of the mask in the same order as
             the data line. '1' indicates masked, '0' indicates unmasked.
    """
    # Open the file object.
    newfile = False
    if not hasattr(fid, 'write'):
        newfile = True
        fid = open(fid, 'w')

    # Write comments
    for line in comment_lines:
        fid.write('# ')
        fid.write(line.strip())
        fid.write(os.linesep)

    # Write out the shape of the fs
    fid.write('{0} '.format(self.sample_size))

    if foldmaskinfo:
        if not self.folded:
            fid.write('unfolded ')
        else:
            fid.write('folded ')

    if extrapinfo:
        if not self.extrap_x:
            fid.write('None ')
        else:
            fid.write('{0} '.format(self.extrap_x))
        if not self.extrap_t:
            fid.write('None')
        else:
            fid.write('{0}'.format(self.extrap_t))

    fid.write(os.linesep)

    # Write the data to the file
    self.data.tofile(fid, ' ', '%%.%ig' % precision)
    fid.write(os.linesep)

    if foldmaskinfo:
        # Write the mask to the file
        np.asarray(self.mask,int).tofile(fid, ' ')
        fid.write(os.linesep)

    # Close file
    if newfile:
        fid.close()