# Path: encore/base_model.py
# class BaseModel(object):
#     def __init__(self, working_directory=None, app_config=None):
#         self.working_directory = working_directory
#         self.app_config = app_config
# 
#     def get_geno(self, model_spec, geno=None):
#         if geno is None:
#             if "genotype" in model_spec:
#                 geno = Genotype.get(model_spec["genotype"], self.app_config)
#             else:
#                 raise Exception("No genotype information in job")
#         return geno
# 
#     def get_pheno(self, model_spec, pheno=None):
#         if pheno is None:
#             if "phenotype" in model_spec:
#                 pheno = Phenotype.get(model_spec["phenotype"], self.app_config)
#             else:
#                 raise Exception("No phenotype information in job")
#         return pheno
# 
#     def get_ped_writer(self, model_spec, geno, pheno):
#         ped_writer = PedWriter(pheno.get_pheno_reader(), \
#             model_spec["response"], model_spec.get("covariates",[]),
#             set(geno.get_samples()))
#         if "genopheno" in model_spec and len(model_spec["genopheno"])>0:
#             ped_writer.merge_covar(geno.get_pheno_reader(), \
#                 model_spec["genopheno"])
#         return ped_writer
# 
#     def get_response_values(self, model_spec, geno, pheno):
#         return self.get_ped_writer(model_spec, geno, pheno).get_response_values()
# 
#     def relative_path(self, *args):
#         return os.path.expanduser(os.path.join(self.working_directory, *args))
# 
#     def if_exit_success(self, cmds, ifsuccess): 
#         cmds = cmds + [ 
#             "EXIT_STATUS=$?", 
#             "echo $EXIT_STATUS > ./exit_status.txt",
#             "if [ $EXIT_STATUS == 0 ]; then"
#             ] + ifsuccess + ["fi", "exit $EXIT_STATUS"]
#         return cmds
# 
#     def validate_model_spec(self, model_spec):
#         pass
# 
#     def get_filter_desc(self, vfilter):
#         if not hasattr(self, "filters"):
#             return None
#         for x in self.filters:
#             if x[0] == vfilter:
#                 return x[1]
#         return None
# 
#     def get_failure_reason(self):
#         return None
# 
# Path: encore/chunk_progress.py
# def get_chr_chunk_progress(output_file_glob, fileregex):
#     files = glob.glob(output_file_glob)
#     now = time.mktime(time.localtime())
#     if len(files):
#         chunks = []
#         p = re.compile(fileregex)
#         for file in files:
#             m = p.search(file)
#             chunk = dict(m.groupdict())
#             chunk['chrom'] =  chunk['chr']
#             if not chunk['chrom'].startswith("chr"):
#                 chunk['chrom'] = "chr" + chunk['chrom']
#             chunk['start'] = int(chunk['start'])
#             chunk['stop'] = int(chunk['stop'])
#             chunk['modified'] = time.mktime(time.localtime(os.path.getmtime(file)))
#             chunks.append(chunk)
#         
#         result = collapse_chunk_bins(bin_chunks_by_chr_and_age(chunks, now))
#         return {"data": result, "header": {"format": "ideogram"}}
#     else:
#         return {"data": []}
# 
# def get_gene_chunk_progress(output_file_glob, input_file_glob, min_done_age=0):
#     in_files = glob.glob(input_file_glob)
#     out_files = glob.glob(output_file_glob)
#     if min_done_age>0:
#         now = time.mktime(time.localtime())
#         def age_in_minutes(x):
#             return (now - time.mktime(time.localtime(os.path.getmtime(x)))) / 60
#         out_files = [x for x in out_files if age_in_minutes(x)>min_done_age]
#     return {"data": {"total": len(in_files), "complete": len(out_files)}, 
#         "header": {"format": "progress"}}


from .base_model import BaseModel
from .chunk_progress import get_chr_chunk_progress, get_gene_chunk_progress 
import os
            with open(ped_file_path, "w") as pedfile:
                ped_writer.write_to_file(pedfile)
            return {
                "response": ped_writer.get_response_headers(),
                "covars": ped_writer.get_covar_headers(),
                "path": ped_file_path
            }
        except Exception as e:
            raise Exception("Failed to create ped file ({})".format(e))

    def prepare_job(self, model_spec):
        geno = self.get_geno(model_spec)
        pheno = self.get_pheno(model_spec)

        ped = self.write_ped_file(self.relative_path("pheno.ped"), model_spec, geno, pheno)
        cmds =  self.get_analysis_commands(model_spec, geno, pheno, ped)
        cmds += self.get_postprocessing_commands(geno)

        return {"commands": cmds}

    def get_progress(self):
        output_file_glob = self.relative_path("output.*.epacts")
        if os.path.isfile(self.relative_path("output.1.R")):
            resp = get_gene_chunk_progress(output_file_glob,
                self.relative_path("output.*.R"))
        elif os.path.isfile(self.relative_path("output.1.grp")):
            resp = get_gene_chunk_progress(output_file_glob,
                self.relative_path("output.*.grp"), min_done_age=30)
        else:
            fre = r'output.(?P<chr>\w+)\.(?P<start>\d+)\.(?P<stop>\d+)\.epacts$'

# Path: encore/base_model.py
# class BaseModel(object):
#     def __init__(self, working_directory=None, app_config=None):
#         self.working_directory = working_directory
#         self.app_config = app_config
# 
#     def get_geno(self, model_spec, geno=None):
#         if geno is None:
#             if "genotype" in model_spec:
#                 geno = Genotype.get(model_spec["genotype"], self.app_config)
#             else:
#                 raise Exception("No genotype information in job")
#         return geno
# 
#     def get_pheno(self, model_spec, pheno=None):
#         if pheno is None:
#             if "phenotype" in model_spec:
#                 pheno = Phenotype.get(model_spec["phenotype"], self.app_config)
#             else:
#                 raise Exception("No phenotype information in job")
#         return pheno
# 
#     def get_ped_writer(self, model_spec, geno, pheno):
#         ped_writer = PedWriter(pheno.get_pheno_reader(), \
#             model_spec["response"], model_spec.get("covariates",[]),
#             set(geno.get_samples()))
#         if "genopheno" in model_spec and len(model_spec["genopheno"])>0:
#             ped_writer.merge_covar(geno.get_pheno_reader(), \
#                 model_spec["genopheno"])
#         return ped_writer
# 
#     def get_response_values(self, model_spec, geno, pheno):
#         return self.get_ped_writer(model_spec, geno, pheno).get_response_values()
# 
#     def relative_path(self, *args):
#         return os.path.expanduser(os.path.join(self.working_directory, *args))
# 
#     def if_exit_success(self, cmds, ifsuccess): 
#         cmds = cmds + [ 
#             "EXIT_STATUS=$?", 
#             "echo $EXIT_STATUS > ./exit_status.txt",
#             "if [ $EXIT_STATUS == 0 ]; then"
#             ] + ifsuccess + ["fi", "exit $EXIT_STATUS"]
#         return cmds
# 
#     def validate_model_spec(self, model_spec):
#         pass
# 
#     def get_filter_desc(self, vfilter):
#         if not hasattr(self, "filters"):
#             return None
#         for x in self.filters:
#             if x[0] == vfilter:
#                 return x[1]
#         return None
# 
#     def get_failure_reason(self):
#         return None
# 
# Path: encore/chunk_progress.py
# def get_chr_chunk_progress(output_file_glob, fileregex):
#     files = glob.glob(output_file_glob)
#     now = time.mktime(time.localtime())
#     if len(files):
#         chunks = []
#         p = re.compile(fileregex)
#         for file in files:
#             m = p.search(file)
#             chunk = dict(m.groupdict())
#             chunk['chrom'] =  chunk['chr']
#             if not chunk['chrom'].startswith("chr"):
#                 chunk['chrom'] = "chr" + chunk['chrom']
#             chunk['start'] = int(chunk['start'])
#             chunk['stop'] = int(chunk['stop'])
#             chunk['modified'] = time.mktime(time.localtime(os.path.getmtime(file)))
#             chunks.append(chunk)
#         
#         result = collapse_chunk_bins(bin_chunks_by_chr_and_age(chunks, now))
#         return {"data": result, "header": {"format": "ideogram"}}
#     else:
#         return {"data": []}
# 
# def get_gene_chunk_progress(output_file_glob, input_file_glob, min_done_age=0):
#     in_files = glob.glob(input_file_glob)
#     out_files = glob.glob(output_file_glob)
#     if min_done_age>0:
#         now = time.mktime(time.localtime())
#         def age_in_minutes(x):
#             return (now - time.mktime(time.localtime(os.path.getmtime(x)))) / 60
#         out_files = [x for x in out_files if age_in_minutes(x)>min_done_age]
#     return {"data": {"total": len(in_files), "complete": len(out_files)}, 
#         "header": {"format": "progress"}}


# Path: encore/epacts_job_builder.py
from .base_model import BaseModel
from .chunk_progress import get_chr_chunk_progress, get_gene_chunk_progress 
import os

            with open(ped_file_path, "w") as pedfile:
                ped_writer.write_to_file(pedfile)
            return {
                "response": ped_writer.get_response_headers(),
                "covars": ped_writer.get_covar_headers(),
                "path": ped_file_path
            }
        except Exception as e:
            raise Exception("Failed to create ped file ({})".format(e))

    def prepare_job(self, model_spec):
        geno = self.get_geno(model_spec)
        pheno = self.get_pheno(model_spec)

        ped = self.write_ped_file(self.relative_path("pheno.ped"), model_spec, geno, pheno)
        cmds =  self.get_analysis_commands(model_spec, geno, pheno, ped)
        cmds += self.get_postprocessing_commands(geno)

        return {"commands": cmds}

    def get_progress(self):
        output_file_glob = self.relative_path("output.*.epacts")
        if os.path.isfile(self.relative_path("output.1.R")):
            resp = get_gene_chunk_progress(output_file_glob,
                self.relative_path("output.*.R"))
        elif os.path.isfile(self.relative_path("output.1.grp")):
            resp = get_gene_chunk_progress(output_file_glob,
                self.relative_path("output.*.grp"), min_done_age=30)
        else:
            fre = r'output.(?P<chr>\w+)\.(?P<start>\d+)\.(?P<stop>\d+)\.epacts$'

            resp = get_chr_chunk_progress(output_file_glob, fre)