# Path: kipoiseq/dataloaders/sequence.py
# class BedDataset(object):
#     """Reads a tsv file in the following format:
#     ```
#     chr  start  stop  task1  task2 ...
#     ```
# 
#     # Arguments
#       tsv_file: tsv file type
#       bed_columns: number of columns corresponding to the bed file. All the columns
#         after that will be parsed as targets
#       num_chr: if specified, 'chr' in the chromosome name will be dropped
#       label_dtype: specific data type for labels, Example: `float` or `np.float32`
#       ambiguous_mask: if specified, rows containing only ambiguous_mask values will be skipped
#       incl_chromosomes: exclusive list of chromosome names to include in the final dataset.
#         if not None, only these will be present in the dataset
#       excl_chromosomes: list of chromosome names to omit from the dataset.
#       ignore_targets: if True, target variables are ignored
#     """
# 
#     # bed types accorging to
#     # https://www.ensembl.org/info/website/upload/bed.html
#     bed_types = [str,  # chrom
#                  int,  # chromStart
#                  int,  # chromEnd
#                  str,  # name
#                  str,  # score, as str to prevent issues, also its useless
#                  str,  # strand
#                  int,  # thickStart
#                  int,  # thickEnd
#                  str,  # itemRbg
#                  int,  # blockCount
#                  int,  # blockSizes
#                  int]  # blockStarts
# 
#     def __init__(self, tsv_file,
#                  label_dtype=None,
#                  bed_columns=3,
#                  num_chr=False,
#                  ambiguous_mask=None,
#                  incl_chromosomes=None,
#                  excl_chromosomes=None,
#                  ignore_targets=False):
#         # TODO - `chrom` column: use pd.Categorical for memory efficiency
#         self.tsv_file = tsv_file
#         self.bed_columns = bed_columns
#         self.num_chr = num_chr
#         self.label_dtype = label_dtype
#         self.ambiguous_mask = ambiguous_mask
#         self.incl_chromosomes = incl_chromosomes
#         self.excl_chromosomes = excl_chromosomes
#         self.ignore_targets = ignore_targets
# 
#         df_peek = pd.read_table(self.tsv_file,
#                                 header=None,
#                                 nrows=1,
#                                 sep='\t')
#         found_columns = df_peek.shape[1]
#         self.n_tasks = found_columns - self.bed_columns
#         if self.n_tasks < 0:
#             raise ValueError("BedDataset requires at least {} valid bed columns. Found only {} columns".
#                              format(self.bed_columns, found_columns))
# 
#         self.df = pd.read_table(self.tsv_file,
#                                 header=None,
#                                 dtype={i: d
#                                        for i, d in enumerate(self.bed_types[:self.bed_columns] +
#                                                              [self.label_dtype] * self.n_tasks)},
#                                 sep='\t')
#         if self.num_chr and self.df.iloc[0][0].startswith("chr"):
#             self.df[0] = self.df[0].str.replace("^chr", "")
#         if not self.num_chr and not self.df.iloc[0][0].startswith("chr"):
#             self.df[0] = "chr" + self.df[0]
# 
#         if ambiguous_mask is not None:
#             # exclude regions where only ambigous labels are present
#             self.df = self.df[~np.all(
#                 self.df.iloc[:, self.bed_columns:] == ambiguous_mask, axis=1)]
# 
#             # omit data outside chromosomes
#         if incl_chromosomes is not None:
#             self.df = self.df[self.df[0].isin(incl_chromosomes)]
#         if excl_chromosomes is not None:
#             self.df = self.df[~self.df[0].isin(excl_chromosomes)]
# 
#     def __getitem__(self, idx):
#         """Returns (pybedtools.Interval, labels)
#         """
#         row = self.df.iloc[idx]
# 
#         # TODO: use kipoiseq.dataclasses.interval instead of pybedtools
#         import pybedtools
#         interval = pybedtools.create_interval_from_list(
#                 [to_scalar(x) for x in row.iloc[:self.bed_columns]])
# 
#         if self.ignore_targets or self.n_tasks == 0:
#             labels = {}
#         else:
#             labels = row.iloc[self.bed_columns:].values.astype(
#                 self.label_dtype)
#         return interval, labels
# 
#     def __len__(self):
#         return len(self.df)
# 
#     def get_targets(self):
#         return self.df.iloc[:, self.bed_columns:].values.astype(self.label_dtype)


from kipoiseq.dataloaders.sequence import BedDataset
from pybedtools import Interval
import numpy as np
import pytest
"""Test BedDataset
"""


def write_tmp(string, tmpdir):
    p = tmpdir.mkdir("bed-files").join("file2.txt")
    p.write(string)
    return str(p)


def test_bed3(tmpdir):
    bed_file = write_tmp('chr1\t1\t2\nchr1\t1\t3', tmpdir)

# Path: kipoiseq/dataloaders/sequence.py
# class BedDataset(object):
#     """Reads a tsv file in the following format:
#     ```
#     chr  start  stop  task1  task2 ...
#     ```
# 
#     # Arguments
#       tsv_file: tsv file type
#       bed_columns: number of columns corresponding to the bed file. All the columns
#         after that will be parsed as targets
#       num_chr: if specified, 'chr' in the chromosome name will be dropped
#       label_dtype: specific data type for labels, Example: `float` or `np.float32`
#       ambiguous_mask: if specified, rows containing only ambiguous_mask values will be skipped
#       incl_chromosomes: exclusive list of chromosome names to include in the final dataset.
#         if not None, only these will be present in the dataset
#       excl_chromosomes: list of chromosome names to omit from the dataset.
#       ignore_targets: if True, target variables are ignored
#     """
# 
#     # bed types accorging to
#     # https://www.ensembl.org/info/website/upload/bed.html
#     bed_types = [str,  # chrom
#                  int,  # chromStart
#                  int,  # chromEnd
#                  str,  # name
#                  str,  # score, as str to prevent issues, also its useless
#                  str,  # strand
#                  int,  # thickStart
#                  int,  # thickEnd
#                  str,  # itemRbg
#                  int,  # blockCount
#                  int,  # blockSizes
#                  int]  # blockStarts
# 
#     def __init__(self, tsv_file,
#                  label_dtype=None,
#                  bed_columns=3,
#                  num_chr=False,
#                  ambiguous_mask=None,
#                  incl_chromosomes=None,
#                  excl_chromosomes=None,
#                  ignore_targets=False):
#         # TODO - `chrom` column: use pd.Categorical for memory efficiency
#         self.tsv_file = tsv_file
#         self.bed_columns = bed_columns
#         self.num_chr = num_chr
#         self.label_dtype = label_dtype
#         self.ambiguous_mask = ambiguous_mask
#         self.incl_chromosomes = incl_chromosomes
#         self.excl_chromosomes = excl_chromosomes
#         self.ignore_targets = ignore_targets
# 
#         df_peek = pd.read_table(self.tsv_file,
#                                 header=None,
#                                 nrows=1,
#                                 sep='\t')
#         found_columns = df_peek.shape[1]
#         self.n_tasks = found_columns - self.bed_columns
#         if self.n_tasks < 0:
#             raise ValueError("BedDataset requires at least {} valid bed columns. Found only {} columns".
#                              format(self.bed_columns, found_columns))
# 
#         self.df = pd.read_table(self.tsv_file,
#                                 header=None,
#                                 dtype={i: d
#                                        for i, d in enumerate(self.bed_types[:self.bed_columns] +
#                                                              [self.label_dtype] * self.n_tasks)},
#                                 sep='\t')
#         if self.num_chr and self.df.iloc[0][0].startswith("chr"):
#             self.df[0] = self.df[0].str.replace("^chr", "")
#         if not self.num_chr and not self.df.iloc[0][0].startswith("chr"):
#             self.df[0] = "chr" + self.df[0]
# 
#         if ambiguous_mask is not None:
#             # exclude regions where only ambigous labels are present
#             self.df = self.df[~np.all(
#                 self.df.iloc[:, self.bed_columns:] == ambiguous_mask, axis=1)]
# 
#             # omit data outside chromosomes
#         if incl_chromosomes is not None:
#             self.df = self.df[self.df[0].isin(incl_chromosomes)]
#         if excl_chromosomes is not None:
#             self.df = self.df[~self.df[0].isin(excl_chromosomes)]
# 
#     def __getitem__(self, idx):
#         """Returns (pybedtools.Interval, labels)
#         """
#         row = self.df.iloc[idx]
# 
#         # TODO: use kipoiseq.dataclasses.interval instead of pybedtools
#         import pybedtools
#         interval = pybedtools.create_interval_from_list(
#                 [to_scalar(x) for x in row.iloc[:self.bed_columns]])
# 
#         if self.ignore_targets or self.n_tasks == 0:
#             labels = {}
#         else:
#             labels = row.iloc[self.bed_columns:].values.astype(
#                 self.label_dtype)
#         return interval, labels
# 
#     def __len__(self):
#         return len(self.df)
# 
#     def get_targets(self):
#         return self.df.iloc[:, self.bed_columns:].values.astype(self.label_dtype)


# Path: tests/dataloaders/test_BedDataset.py
from kipoiseq.dataloaders.sequence import BedDataset
from pybedtools import Interval
import numpy as np
import pytest

"""Test BedDataset
"""


def write_tmp(string, tmpdir):
    p = tmpdir.mkdir("bed-files").join("file2.txt")
    p.write(string)
    return str(p)


def test_bed3(tmpdir):
    bed_file = write_tmp('chr1\t1\t2\nchr1\t1\t3', tmpdir)

    bt = BedDataset(bed_file)