# Path: pydigree/io/smartopen.py
# def smartopen(filename, mode='r'):
#     """
#     Seamlessly open compressed files. Use in place of regular open.
# 
#     .. note::
#         Python's compression modules iterate over compressed files as bytes,
#         not strings. Unless 'b' (binary) is specified in the mode, we add 't' (text)
#         to the mode to force iteration as strings, operating consistently 
#     """
#     if 't' not in mode and 'b' not in mode:
#         mode = mode + 't'
#     if filename.endswith('.gz'):
#         return gzip.open(filename, mode, compresslevel=5)
#     elif filename.endswith('.bz2'):
#         return bz2.BZ2File(filename, mode)
#     elif filename.endswith('.xz') or filename.endswith('.lzma'):
#         return lzma.open(filename, mode)
#     else:
#         return open(filename, mode)
# 
# Path: pydigree/sgs/sgs.py
# def intervals_to_array(intervals, nmark):
#     array = np.zeros(nmark)
#     for start, stop in intervals:
#         array[start:(stop + 1)] += 1
#     return array
# 
# Path: pydigree/ibs.py
# def get_ibs_states(ind1, ind2, chromosome_index, missingval=64):
# def chromwide_ibs(a, b, c, d, missingval=64):
# 
# Path: pydigree/common.py
# def count(val, iterable):
# def table(seq):
# def mode(seq):
# def random_choice(iterable):
# def flatten(x):
# def grouper(iterable, n, fillvalue=None):
# def invert_dict(d):
# def merge_dicts(*args):
# def log_base_change(value, old, new):
# def product(iter):
# def cumsum(iter):


import sys
import numpy as np
import pydigree as pyd
from pydigree.io import smartopen
from pydigree.sgs.sgs import intervals_to_array
from pydigree.ibs import ibs
from pydigree.common import table, runs
replicate = sys.argv[1]
ms = int(sys.argv[2])
prefix='null'

peds = pyd.io.plink.read_plink('{}-{}.ped'.format(prefix, replicate), '{}.map'.format(prefix))
ped = peds['1']
s = pyd.sgs.sgs_population(ped, seed_size=ms)


with smartopen('{}-{}.ibd.gz'.format(prefix, replicate)) as f:
    trueibd = {}
    for line in f:
        fam, id1, id2, ibd_states = line.strip().split(None, 3)
        trueibd[frozenset({id1,id2})] = np.array([int(x) for x in ibd_states.split()])

a = intervals_to_array(s[frozenset({ped['7'],ped['8']})][0], ped.chromosomes[0].nmark())
b = trueibd[frozenset({'7','8'})]


genos1 = zip(*ped['7'].genotypes[0])
genos2 = zip(*ped['8'].genotypes[0])
identical = [ibs(x,y) for x,y in zip(genos1, genos2)]



for start, stop in runs(list(a), lambda x: x>0, ms):
    print('Predicted segment: {}-{}'.format(start, stop))

print()


# Path: pydigree/io/smartopen.py
# def smartopen(filename, mode='r'):
#     """
#     Seamlessly open compressed files. Use in place of regular open.
# 
#     .. note::
#         Python's compression modules iterate over compressed files as bytes,
#         not strings. Unless 'b' (binary) is specified in the mode, we add 't' (text)
#         to the mode to force iteration as strings, operating consistently 
#     """
#     if 't' not in mode and 'b' not in mode:
#         mode = mode + 't'
#     if filename.endswith('.gz'):
#         return gzip.open(filename, mode, compresslevel=5)
#     elif filename.endswith('.bz2'):
#         return bz2.BZ2File(filename, mode)
#     elif filename.endswith('.xz') or filename.endswith('.lzma'):
#         return lzma.open(filename, mode)
#     else:
#         return open(filename, mode)
# 
# Path: pydigree/sgs/sgs.py
# def intervals_to_array(intervals, nmark):
#     array = np.zeros(nmark)
#     for start, stop in intervals:
#         array[start:(stop + 1)] += 1
#     return array
# 
# Path: pydigree/ibs.py
# def get_ibs_states(ind1, ind2, chromosome_index, missingval=64):
# def chromwide_ibs(a, b, c, d, missingval=64):
# 
# Path: pydigree/common.py
# def count(val, iterable):
# def table(seq):
# def mode(seq):
# def random_choice(iterable):
# def flatten(x):
# def grouper(iterable, n, fillvalue=None):
# def invert_dict(d):
# def merge_dicts(*args):
# def log_base_change(value, old, new):
# def product(iter):
# def cumsum(iter):


# Path: support/test_segments.py
import sys
import numpy as np
import pydigree as pyd
from pydigree.io import smartopen
from pydigree.sgs.sgs import intervals_to_array
from pydigree.ibs import ibs
from pydigree.common import table, runs

replicate = sys.argv[1]
ms = int(sys.argv[2])
prefix='null'

peds = pyd.io.plink.read_plink('{}-{}.ped'.format(prefix, replicate), '{}.map'.format(prefix))
ped = peds['1']
s = pyd.sgs.sgs_population(ped, seed_size=ms)


with smartopen('{}-{}.ibd.gz'.format(prefix, replicate)) as f:
    trueibd = {}
    for line in f:
        fam, id1, id2, ibd_states = line.strip().split(None, 3)
        trueibd[frozenset({id1,id2})] = np.array([int(x) for x in ibd_states.split()])

a = intervals_to_array(s[frozenset({ped['7'],ped['8']})][0], ped.chromosomes[0].nmark())
b = trueibd[frozenset({'7','8'})]


genos1 = zip(*ped['7'].genotypes[0])
genos2 = zip(*ped['8'].genotypes[0])
identical = [ibs(x,y) for x,y in zip(genos1, genos2)]



for start, stop in runs(list(a), lambda x: x>0, ms):
    print('Predicted segment: {}-{}'.format(start, stop))

print()


for start, stop in runs(list(b), lambda x: x>0, 2):