File: test_qcumber2.py

package info (click to toggle)
qcumber 2.3.0-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm, bullseye, sid
  • size: 2,276 kB
  • sloc: python: 3,097; sh: 153; makefile: 18
file content (1405 lines) | stat: -rwxr-xr-x 58,421 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
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
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
210
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
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
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from contextlib import contextmanager, ExitStack
import argparse
import copy
import glob
import hashlib
import json
import readline
import shutil
import subprocess
import sys
import time
import tempfile
import _thread
import queue
import os.path
import yaml


def main():
    parser = argparse.ArgumentParser(
        prog='qcumber_test_suite',
        description=(
            'Script that runs a suite of tests on QCumber\n'
            'The script relies on a .yaml file that specifies the\n'
            'kinds of tests to run and types of data used during the\n'
            'process.\n  Authors: René Kmiecinski, BI-Support\n'
            '  Email: r.w.kmiecinski@gmail.com\n'),
        formatter_class=argparse.RawTextHelpFormatter,
        add_help=False)
    parser.add_argument('-h', '--help', action=_HelpAction,
                        help='show this help message and exit')
    parser.add_argument('-i', '--run_file',
                        help='config file used to run tests.\n'
                             'defaults to: test_run.yaml')
    parser.add_argument('-g', '--gold_standard_file',
                        help='gold standard file used. It is a json file\n'
                             'containing hashes, and other information used\n'
                             'and generated while testing')
    parser.add_argument('--trigger_overwrite', action="store_true",
                        help='Trigger the set overwrite flags in the test run'
                             ' yaml.\nThe overwrite flag is only useful when'
                             'writing new file rules.\nIt needs this option'
                             'and the set_overwrite yaml line in the\n'
                             'run config to activate')
    parser.add_argument('-s', '--spec', default='low',
                        choices=['low', 'mid', 'high', 'cluster'],
                        help='Specify which default set of runs to load\n'
                             'Low: low tier laptop from 2013 4GB RAM and'
                             ' abysmal IO\nMid: ---\nHigh: ---\nCluster ---')
    parser.add_argument('-v', '--verbosity', choices=[0, 1, 2],
                        help='Verbosity.\n 0 - quiet\n'
                             ' 1 - only status and errors\n'
                             ' 2 - output everything')
    # Hidden option
    parser.add_argument('--active_default_run_file', help=argparse.SUPPRESS)
    subparsers = parser.add_subparsers(
            help='See detailed description bellow',
            title='SUBCOMMANDS', dest='command')

    gen_test_yaml_parser = subparsers.add_parser(
            'gen_test_yaml',
            description='generates default test_run.yaml')

    update_default_yaml_parser = subparsers.add_parser(
            'update_default_yaml',
            description='replace default test_run.yaml file\n'
                        'with the current test.yaml\n'
                        '(Warning: the default file is tracked by git)',
            formatter_class=argparse.RawTextHelpFormatter)

    update_default_goldstandard_parser = subparsers.add_parser(
            'update_default_goldstandard',
            description='replace default goldstandard file\n'
                        'with the current goldstandard\n'
                        '(Warning: the default file is tracked by git)',
            formatter_class=argparse.RawTextHelpFormatter)
    # ### Utility Mode ### #
    util_parser = subparsers.add_parser(
            'util',
            description=('Maintenance of gold standard file.\n'
                         '(e.g.: gold standard for run or set gold standard)\n'
                         'Access information about test runs\n'
                         'and the directories and files they created'),
            formatter_class=argparse.RawTextHelpFormatter)

    util_parser.add_argument(
            '-r', '--test_regex', nargs=2,
            help='<regex(perl)> <file>\n'
                 'Test a regular expression on a file\n'
                 'It will then output the differences')
    util_parser.add_argument(
            '-i', '--run_info',
            help='Info of run that produced the test folder')
    # argcomplete.autocomplete(parser)
    default_test_run_selector = {
            'low': '.default_low_spec_test_run.yaml',
            'mid': '.default_mid_spec_test_run.yaml',
            'high': '.default_high_spec_test_run.yaml',
            'cluster': '.default_cluster_spec_test_run.yaml',
            }
    data_path = 'data'
    default_gold_standard_file = '.default_gold_standard.json'
    gold_standard_file = data_path + '/gold_standard.json'
    test_run_c_file = 'test_run.yaml'

    args = parser.parse_args()
    default_test_run_c_file = default_test_run_selector[args.spec]
    args.active_default_run_file = default_test_run_c_file
    # default_test_run_c_file = '.default_test_run.yaml'
    if not args.run_file:
        args.run_file = test_run_c_file
    if not args.gold_standard_file:
        # If local standard not found
        if not os.path.isfile(gold_standard_file):
            # And default file found
            if os.path.isfile(default_gold_standard_file):
                shutil.copyfile(default_gold_standard_file,
                                gold_standard_file)
            args.gold_standard_file = gold_standard_file
    else:
        gold_standard_file = args.gold_standard_file

    if args.command:
        if args.command in ['util', 'gen_test_yaml',
                            'update_default_yaml',
                            'update_default_goldstandard']:
            command = eval(args.command)
            command(args)
        else:
            eprint('\n[ERROR] - Command not recognized!')
            parser.print_help()
            util_parser.print_help()
            gen_test_yaml_parser.print_help()
            update_default_yaml_parser.print_help()
            update_default_goldstandard_parser.print_help()
    else:
        try:
            with open(test_run_c_file, 'r') as testrun_conf_file:
                user_config_dict = yaml.load(testrun_conf_file)
        except FileNotFoundError:
            try:
                with open(default_test_run_c_file, 'r') as testrun_conf_file:
                    user_config_dict = yaml.load(testrun_conf_file)
            except FileNotFoundError:
                eprint('No config file found!')
        except yaml.YAMLError as exc:
            exit(exc)
        tests = QCumberTests(**user_config_dict)
        tests.run_tests(data_path, gold_standard_file)


def gen_test_yaml(args):
    try:
        shutil.copyfile(args.active_default_run_file,
                        outputFileDialogue('test_run.yaml', False))
    except UserAbortError:
        exit('Goodbye')
    except FileNotFoundError:
        exit('default test_run.yaml not found!\n'
             'There should be a hidden ".default_test_run.yaml" in the\n'
             'current working directory.')


def update_default_yaml(args):
    default_test_run_selector = {
            'low': '.default_low_spec_test_run.yaml',
            'mid': '.default_mid_spec_test_run.yaml',
            'high': '.default_high_spec_test_run.yaml',
            'cluster': '.default_cluster_spec_test_run.yaml',
            }
    try:
        shutil.copyfile(args.run_file,
                        default_test_run_selector[args.spec])
    except FileNotFoundError:
        exit('file does not exist')


def update_default_goldstandard(args):
    try:
        shutil.copyfile(args.gold_standard_file, '.default_goldstandard.json')
    except FileNotFoundError:
        exit('file does not exist')


def util(args):
    if args.run_info:
        if os.path.isdir(args.run_info):
            try:
                with open('%s/%s' % (args.run_info,
                                     '.testrun_info.yaml')) as run_conf_f:
                    while True:
                        line = run_conf_f.readline()
                        if not line:
                            break
                        else:
                            print(line)
            except FileNotFoundError:
                exit('No ".testrun_config.yaml" found in directory!')
    if args.test_regex:
        regex, testfile = args.test_regex
        with open('regex_test_result', 'wb') as regex_r_file:
            with subprocess.Popen(['perl', '-pe', '%s' % regex,
                                   '%s' % testfile],
                                  stdout=regex_r_file) as reg_proc:
                reg_proc.wait()
                if reg_proc.returncode:
                    raise subprocess.CalledProcessError(
                            reg_proc.returncode,
                            "Error while running regular"
                            " expression on file!\n")
        with subprocess.Popen(['diff', '-dU100000',
                               'regex_test_result',
                               '%s' % testfile]) as diff_proc:
            diff_proc.wait()
            if diff_proc.returncode == 2:
                raise subprocess.CalledProcessError(
                        diff_proc.returncode,
                        "Error while running diff on file after applying\n"
                        "regex on file")
    return

# Classes --->

#  # Exception Classes -->


class UserAbortError(Exception):
    pass
#  # Exception Classes <--


class _HelpAction(argparse._HelpAction):
    ''' argparse monolithic help Action

    HelpAction that can be used to overwrite default help action

    helpfully provided by stackoverflow user
    "Adaephon" in conjunction with "grundic"
    https://stackoverflow.com/questions/20094215/\
    argparse-subparser-monolithic-help-output

    '''
    def __call__(self, parser, namespace, values, option_string=None):
        parser.print_help()

        # retrieve subparsers from parser
        subparsers_actions = [
            action for action in parser._actions
            if isinstance(action, argparse._SubParsersAction)]
        # there will probably only be one subparser_action,
        # but better save than sorry
        for subparsers_action in subparsers_actions:
            # get all subparsers and print help
            for choice, subparser in subparsers_action.choices.items():
                print("----------------------------------------------------\n"
                      ">   SUBCOMAND [{}]:\n".format(choice))
                print(subparser.format_help())

        parser.exit()


class RemoteFile():
    def __init__(self, url, descriptive_name):
        self.url = url
        self.descriptive_name = descriptive_name

    def download(self, download_location, resume=False):
        ref_filename = self.url.split('/')[-1]
        if not os.path.isfile(('%s/' % download_location) + ref_filename):
            if not os.path.isdir('../test/data'):
                eprint('Error: Wrong working directory')
            else:
                cmd = ['wget',
                       '-P%s' % download_location,
                       '-c' if resume else '', self.url]
                print(' '.join(cmd))
                with subprocess.Popen(cmd) as dl_man:
                    dl_man.wait()
                    if dl_man.returncode not in [0, 1]:
                        raise subprocess.CalledProcessError(
                                dl_man.returncode,
                                'Error: wget had non-zero returncode')
        return ref_filename


class MultiFileOutput(object):
    ''' Class that allows for writing of multiple files

    https://stackoverflow.com/questions/41283595/
    how-to-redirect-python-subprocess-stderr-and-stdout-to-multiple-files
    https://stackoverflow.com/users/4014959/pm-2ring
    '''
    def __init__(self, *file_handles):
        self.f_handles = file_handles

    def write(self, data):
        for f in self.f_handles:
            f.write(data)

    def flush(self):
        for f in self.f_handles:
            f.flush()

    def close(self):
        pass


class Thread_Subprocess_State(object):
    def __init__(self):
        self.not_finished = True
        self.returncode = 1

# Yaml-Config Parser --->


class Structure(object):
    '''Helper struct that unroles a dictonary into a class

    If a Class inherits from this class it can be instantiated from an
    dictionary containing attributes listed in the self._fields attribute

    http://www.seanjohnsen.com/2016/11/23/pydeserialization.html

    Attributes:
        _fields (:obj:`list`): List of tuples containing attribute name and
                               type
    '''
    _fields = []
    _default_field_values = []

    def _init_arg(self, expected_type, value):
        try:
            if isinstance(value, expected_type):
                return value
            else:
                return expected_type(**value)
        except TypeError:
            return expected_type(value)

    def __init__(self, **kwargs):
        default_values = dict(self._default_field_values)
        field_names, field_types = zip(*self._fields)
        assert([isinstance(name, str) for name in field_names])
        assert([isinstance(type_, type) for type_ in field_types])

        for name, field_type in self._fields:
            try:
                setattr(self, name, self._init_arg(field_type,
                                                   kwargs.pop(name)))
            except KeyError:
                setattr(self, name, default_values[name])
        # Check for any remaining unknown arguments
        if kwargs:
            raise TypeError(
                    'Invalid arguments(s): {}'.format(','.join(kwargs)))


class QCumberTests(Structure):
    '''Global Test Managing Object

    Attributes:
        references (:obj:`dict`): genomic reference sequences
        default_output_files (:obj:`list`): List[:obj:`OutputFile`]
        test_runs (:obj:`list`): List[:obj:`Run`]
    '''
    def __deserialize_references(value):
        return dict((x, GenomicReference(**y)) for x, y in value.items())

    def __deserialize_remote_reads(value):
        return dict((x, RemoteReadData(**y)) for x, y in value.items())

    def __deserialize_output_files(value):
        return [OutputFile(**x) for x in list(value)]

    def __deserialize_runs(value):
        return [Run(**x) for x in list(value)]
    _default_field_values = [('verbosity', 1)]
    _fields = [('references', __deserialize_references), ('seeds', list),
               ('remote_reads', __deserialize_remote_reads),
               ('default_output_files', __deserialize_output_files),
               ('test_runs', __deserialize_runs), ('verbosity', int)]

    def run_tests(self, data_path, gold_standard_file,
                  trigger_overwrite=False):
        # load gold standard
        gold_standard = {}
        try:
            with open(data_path
                      + '/gold_standard.json', 'r') as gold_standard_file:
                gold_standard = json.load(gold_standard_file)
        except FileNotFoundError:
            pass
        with tmpdir() as temp_dir:
            badrun_simulation = {}
            for run, seed in ((r, s) for r in self.test_runs
                              for s in self.seeds[:1]
                              if r.gen_run_id(s, omit_seed=True)
                              not in badrun_simulation):
                abort_run = False
                run_id, run_id_no_seed = (run.gen_run_id(seed),
                                          run.gen_run_id(seed,
                                                         omit_seed=True))
                hash_gen = hashlib.sha1()
                hash_gen.update(run_id.encode())
                hash_run_id = hash_gen.hexdigest()
                q_run_id = ','.join(run.gen_easy_opts())
                data_id = run.gen_sim_run_id(seed)
                map_reference_file = ''
                if run.map_reference:
                    try:
                        map_reference_file = self.references[
                                run.map_reference].download(data_path)
                        map_reference_file = '%s/%s' % (data_path,
                                                        map_reference_file)
                    except KeyError:
                        reason = ('map reference: %s\n was not found in '
                                  'test_run.yaml' % self.map_reference)
                        eprint(reason)
                        continue
                eprint("Running simulators...")
                for sim in run.simulators:
                    try:
                        ref_filename = self.references[
                               sim.reference].download(data_path)
                        if (not run.map_reference and sim.qcumber_input
                                and run.default_to_simref):
                            map_reference_file = ref_filename
                            map_reference_file = '%s/%s' % (data_path,
                                                            map_reference_file)
                    except KeyError:
                        reason = ('%s not found in'
                                  ' test_run.yaml' % sim.reference)
                        eprint(reason)
                        badrun_simulation[run_id_no_seed] = reason
                        abort_run = True
                        break
                    except subprocess.CalledProcessError as exc:
                        eprint(exc)
                        badrun_simulation[run_id_no_seed] = exc
                        abort_run = True
                        break
                    # Simulate data
                    try:
                        subdir_prefix = sim.simulate_data(
                                hash_run_id,
                                seed, ref_filename, data_path,
                                temp_dir)
                    except subprocess.CalledProcessError as exc:
                        eprint(exc)
                        badrun_simulation[run_id_no_seed] = exc
                        abort_run = True
                        break
                if abort_run or not run.simulators:
                    continue
                # Run QCumber analysis
                if not os.path.isdir(subdir_prefix):
                    try:
                        os.mkdir(subdir_prefix)
                    except FileExistsError as e:
                        if not os.path.isdir(subdir_prefix):
                            eprint("mkdir failed: A file (not a directory)"
                                   " with the same name already exists!\n")
                            continue
                with open('%s/%s' % (subdir_prefix,
                                     '.testrun_info.yaml'),
                          'w') as run_conf_f:
                    yaml.dump(run, run_conf_f, default_flow_style=False)
                print('\nRun Qcumber: %s' % subdir_prefix)
                try:
                    run.run_qcumber(subdir_prefix, '%s/%s' % (temp_dir,
                                                              subdir_prefix),
                                                   data_path,
                                    map_reference_file,
                                    verbosity=self.verbosity)
                except subprocess.CalledProcessError as exc:
                    eprint(exc)
                    continue
                except (BrokenPipeError, KeyboardInterrupt):
                    eprint('User Aborted Run!!')
                    continue
                run.compare_with_golden_standard(subdir_prefix, seed,
                                                 gold_standard,
                                                 q_run_id, data_id,
                                                 self.default_output_files)
            # local data
            for run, data in ((r, d) for r in self.test_runs
                              for d in r.local_real_data):
                q_run_id = ','.join(run.gen_easy_opts())
                data_id = data.get_file_trace()
                hash_gen = hashlib.sha1()
                run_id = ('%s_%s' % (q_run_id, data_id)).encode()
                hash_gen.update(run_id)
                hash_run_id = hash_gen.hexdigest()
                subdir_prefix = 'locald_test%s' % hash_run_id
                if not os.path.isdir(subdir_prefix):
                    try:
                        os.mkdir(subdir_prefix)
                    except FileExistsError as e:
                        if not os.path.isdir(subdir_prefix):
                            eprint("mkdir failed: A file (not a directory)"
                                   " with the same name already exists!\n")
                            continue
                input_folder = data.prepare_data(temp_dir, subdir_prefix)
                try:
                    run.run_qcumber(subdir_prefix, input_folder,
                                    data_path,
                                    map_reference_file,
                                    verbosity=self.verbosity)
                except subprocess.CalledProcessError as exc:
                    eprint(exc)
                    continue
                except (BrokenPipeError, KeyboardInterrupt):
                    eprint('User Aborted Run!!')
                    continue
                print(data_id)
                run.compare_with_golden_standard(subdir_prefix, seed,
                                                 gold_standard,
                                                 q_run_id, data_id,
                                                 self.default_output_files)
            # remote data
            for run, rdata in ((r, d) for r in self.test_runs
                               for d in r.remote_real_data):
                q_run_id = ','.join(run.gen_easy_opts())
                key_files = dict(
                        (data.remote_id,
                         self.remote_reads[data.remote_id].download_all(
                            data_path))
                        for data in rdata.remote_data)
                files = sorted('%s%s' % (f.remote_id, ':%i' % f.cutoff)
                               for f in rdata.remote_data)
                data_id = ','.join(files)
                run_id = '%s_%s' % (q_run_id, data_id)
                hash_gen = hashlib.sha1()
                hash_gen.update(run_id.encode())
                hash_run_id = hash_gen.hexdigest()
                subdir_prefix = 'real_test%s' % hash_run_id
                if not os.path.isdir(subdir_prefix):
                    try:
                        os.mkdir(subdir_prefix)
                    except FileExistsError as e:
                        if not os.path.isdir(subdir_prefix):
                            eprint("mkdir failed: A file (not a directory)"
                                   " with the same name already exists!\n")
                            continue
                input_folder = rdata.prepare_data(temp_dir, subdir_prefix,
                                                  key_files, data_path)
                try:
                    run.run_qcumber(subdir_prefix, input_folder,
                                    data_path,
                                    map_reference_file,
                                    verbosity=self.verbosity)
                except subprocess.CalledProcessError as exc:
                    eprint(exc)
                    continue
                except (BrokenPipeError, KeyboardInterrupt):
                    eprint('User Aborted Run!!')
                    continue
                run.compare_with_golden_standard(subdir_prefix, seed,
                                                 gold_standard,
                                                 q_run_id, data_id,
                                                 self.default_output_files)
            with open(data_path
                      + '/gold_standard.json',
                      'w') as gold_standard_file:
                json.dump(gold_standard, gold_standard_file)


class RemoteReadData(Structure):
    def __deserialize_remote_data(value):
        return [RemoteFile(**x) for x in value]

    _default_field_values = [('descriptive_name', '')]
    _fields = [('descriptive_name', str),
               ('files', __deserialize_remote_data)]

    def download_all(self, data_path):
        return [f.download(data_path) for f in self.files]


class OutputFile(Structure):
    _default_field_values = [('regex', ''), ('use_file_size', False),
                             ('expected_num_files', 1),
                             ('file_size_cutoff', .95)]
    _fields = [('file', str), ('regex', str), ('use_file_size', bool),
               ('expected_num_files', int), ('file_size_cutoff', float)]

    def resolve_name(self, prefix, substitute_str='{{Prefix}}', path=''):
        out = []
        name = self.file.replace(substitute_str, prefix)
        if not any((s_char in name for s_char in '*?[]')):
            new_file = copy.deepcopy(self)
            new_file.file = '%s/%s' % (path, name)
            out = [new_file]
        else:
            for file_name in glob.iglob('%s/%s' % (path, name),
                                        recursive=True):
                new_file = copy.deepcopy(self)
                new_file.file = file_name
                new_file.expected_num_files = 1
                out.append(new_file)
        return out


class Run(Structure):
    def __deserialize_output_files(value):
        return [OutputFile(**x) for x in list(value)]

    def __deserialize_local_real_data(value):
        return [LocalRealData(**x) for x in list(value)]

    def __deserialize_remote_real_data(value):
        return [RemoteRealData(**x) for x in list(value)]

    def __deserialize_simulators(value):
        return [Simulator(**x) for x in list(value)]

    def __trimbetter_option(value):
        if value not in ['default', 'mapping', 'assembly']:
            raise TypeError
        else:
            return value

    _default_field_values = [('trimbetter', False),
                             ('trimbetter_mode', 'default'), ('threads', 8),
                             ('kraken', False), ('additional_opts', []),
                             ('special_output_files', []),
                             ('simulators', []),
                             ('local_real_data', []),
                             ('remote_real_data', []),
                             ('overwrite_standard', False),
                             ('map_reference', ''),
                             ('index', ''),
                             ('default_to_simref', True)]
    _fields = [('trimbetter', bool),
               ('trimbetter_mode', __trimbetter_option),
               ('threads', int), ('kraken', bool),
               ('additional_opts', list),
               ('special_output_files', __deserialize_output_files),
               ('simulators', __deserialize_simulators),
               ('local_real_data', __deserialize_local_real_data),
               ('remote_real_data', __deserialize_remote_real_data),
               ('overwrite_standard', bool),
               ('map_reference', str),
               ('index', str),
               ('default_to_simref', bool)]

    def __grep_progress(self, input_file, subprocess_state):
        # with open(input_file, 'rb') as i_file:
        with subprocess.Popen(['grep', '-iE',
                               'step|error', input_file]) as grep_proc:
            grep_proc.wait()
            subprocess_state.not_finished = False
            subprocess_state.returncode = grep_proc.returncode

    def gen_easy_opts(self):
        opts = ['-t%i' % self.threads]
        if not self.kraken:
            opts.append('-K')
        if self.trimbetter:
            opts.extend(['--trimBetter', self.trimbetter_mode])
        opts.extend(self.additional_opts)
        return opts

    def gen_sim_run_id(self, seed):
        return '|'.join(
                [','.join([sim.name, '%i' % seed,
                           sim.reference]+sim.opt)
                 for sim in self.simulators])

    def gen_run_id(self, seed, omit_seed=False):
        sims = '|'.join(
                [','.join([sim.name, '' if omit_seed else ('%i' % seed),
                           sim.reference]+sim.opt)
                 for sim in self.simulators])
        qcall = ','.join(self.gen_easy_opts())
        return '%s_%s' % (sims, qcall)

    def run_qcumber(self, prefix, input_path, data_path,
                    map_reference, verbosity=1):
        '''
        run Qcumber on data

        Args:
            prefix (:obj:`str`): prefix/name used by dwgsim to create output
            tmp_dir (:obj:`str`): path to temporary directory
            data_path (:obj:`str`): path to data_dir
                                    where in the files that need
                renaming and symlinking are located

        Kwargs:
            verbosity (int): Level of verbosity of stdout (does not affect log)
                level 0: no qcumber output
                level 1: only progress and errors
                level 2: everything, rule and job info
        '''
        reference_opt = ''
        if map_reference or self.index:
            reference_opt = ('-r%s' % (map_reference)
                             if not self.index
                             else '-I%s' % self.index)
        options = self.gen_easy_opts()+['-o%s' % prefix]
        if reference_opt:
            options = options + [reference_opt]
        # ev_loop = asyncio.get_event_loop()
        r_code = 1
        with ExitStack() as e_stack:
            qcumber_info_stream = e_stack.enter_context(
                    (fifo() if (verbosity == 1) else pseudo_stderr()))
            qcumber_log = e_stack.enter_context(
                    open(prefix+'/qcumber_run.log', 'wb'))
            # Object that allows error detection
            thread_state = Thread_Subprocess_State()
            if verbosity == 1:
                _thread.start_new_thread(self.__grep_progress,
                                         (qcumber_info_stream, thread_state))
                time.sleep(0.2)
                qcumber_info_write_handle = e_stack.enter_context(
                        open(qcumber_info_stream, 'wb'))
            processing_file = (qcumber_info_write_handle if verbosity == 1
                               else qcumber_info_stream)
            err_mf = MultiFileOutput(*([qcumber_log]
                                       + ([] if not verbosity
                                          else [processing_file])))
            print(' '.join(['../QCumber-2', '-i%s' % (input_path)] + options))
            with subprocess.Popen(['../QCumber-2',
                                   '-i%s' % (input_path)] +
                                  options, stderr=subprocess.PIPE) as qc2_proc:
                while True:
                    line = qc2_proc.stderr.readline()
                    if (not line):
                        break
                    err_mf.write(line)
                    err_mf.flush()
                qc2_proc.wait()
                err_mf.flush()
                r_code = qc2_proc.returncode
        if r_code:
            raise subprocess.CalledProcessError(
                    r_code,
                    'QCumber encountered an error')

    def compare_with_golden_standard(self, subdir_prefix, seed,
                                     gold_standard,
                                     run_id, data_id,
                                     default_output,
                                     trigger_overwrite=False):
        # Gen Run Id for golden standard
        print('\nGold standard checks:')
        force_overwrite = trigger_overwrite & self.overwrite_standard
        # data_id = self.__gen_run_id(seed)
        # run_id = ','.join(self.gen_easy_opts())
        # output dir
        result_folder = '%s/QCResults' % subdir_prefix
        # Prepare gold standard if run is missing
        if run_id not in gold_standard:
            gold_standard[run_id] = {}
            gold_standard[run_id][data_id] = {}
        elif data_id not in gold_standard[run_id]:
            gold_standard[run_id][data_id] = {}
        # shortcut for active run id
        active_standard = gold_standard[run_id][data_id]
        # Replacement string used in File.resolve_name() to expand filenames
        rep_string = '{{Prefix}}'
        # Join default output files with run specific ones
        files = dict((f.file, f) for f in self.special_output_files)
        # Prioritize run specific output in case of conflict
        for d_file in default_output:
            if d_file.file not in files:
                files[d_file.file] = d_file
        # Iterate through unresolved files
        for prelim_file in files.values():
            resolved_files = prelim_file.resolve_name(
                    subdir_prefix,
                    substitute_str=rep_string,
                    path=result_folder)
            # Check of number of files resolved matches expected num
            num_res_files = len(resolved_files)
            if num_res_files != prelim_file.expected_num_files:
                less_files = num_res_files < prelim_file.expected_num_files
                print("%s: File Rule %s\nExpected %i file and found %i " % (
                    prelim_file.file,
                    'ERROR!' if less_files else 'WARNING',
                    prelim_file.expected_num_files, num_res_files))
            for f in resolved_files:
                new_hash = ''
                new_file_size = 0
                standard_hash = ''
                standard_file_size = 0
                try:
                    standard_file_size, standard_hash = active_standard[
                            f.file]
                except KeyError:
                    pass
                try:
                    new_file_size = os.path.getsize(f.file)
                except FileNotFoundError:
                    print("%s: %s" % (f.file,
                                      'ERROR: FILE NOT FOUND'))
                    continue
                if f.use_file_size:
                    if standard_file_size and not force_overwrite:
                        ratio = (min(float(new_file_size),
                                     standard_file_size)
                                 / max(new_file_size,
                                       float(standard_file_size)))
                        # If user wishes to match file size exactly
                        if 1 == f.file_size_cutoff:
                            smalldiff = new_file_size == standard_file_size
                        else:
                            smalldiff = ratio > f.file_size_cutoff
                        print('%s: %s' % (f.file,
                                          'FILESIZE: OK' if smalldiff
                                          else 'FILESIZE: ERROR'))
                    else:
                        print('file:%s Checked Size: %s' % (f.file, new_hash))
                        active_standard[f.file] = (new_file_size, new_hash)
                    continue
                # Hash file
                if f.regex:
                    print('Sanitizing file before generating hash')
                    result = queue.Queue()
                    with fifo() as pipe:
                        _thread.start_new_thread(hash_file, (pipe, result))
                        time.sleep(0.1)
                        cleanup_file_for_hashing(f.regex, f.file, pipe)
                        new_hash = result.get()
                # I case where no file hash was found in gold standard,
                # insert new one.
                else:
                    result = queue.Queue()
                    hash_file(f.file, result)
                    new_hash = result.get()
                if not standard_hash or force_overwrite:
                    print('file:%s generated hash: %s' % (f.file, new_hash))
                    active_standard[f.file] = (new_file_size, new_hash)
                else:
                    print("%s: %s" % (f.file,
                                      'HASH: OK' if new_hash == standard_hash
                                      else 'HASH: ERROR'))


class Simulator(Structure):
    _default_field_values = [('type', 'read'), ('qcumber_input', True)]
    _fields = [('name', str), ('type', str), ('qcumber_input', bool),
               ('reference', str), ("opt", list)]

    def simulate_data(self, hash_run_id, seed,
                      ref_filename, data_path, temp_dir):
        '''simulates read data

        Currently is only able to use dwgsim. If returns a cleaned up
        temporary directory, where in sanitized reads reside.

        Returns:
            subdir:
        '''
        sim_id = ','.join([self.name, '%i' % seed,
                           self.reference]+self.opt)
        sim_hash_gen = hashlib.sha1()
        sim_hash_gen.update(sim_id.encode())
        sim_hash_id = sim_hash_gen.hexdigest()
        subdir_prefix = 'testData%i%s_%s%s' % (seed, self.name,
                                               self.reference, sim_hash_id)
        for suffix in ['.gz', '.fa.gz', '.fa', '.fna.gz', '.fna']:
            subdir_prefix = subdir_prefix.rstrip(suffix)
        subdir_prefix, _ = sanitize_name_for_illumina(
                subdir_prefix)
        subdir_prefix_path = '%s/%s' % (data_path, subdir_prefix)
        if self.name == 'dwgsim':
            self.dwgsim_generate_reads_unzip(
                    ('%s/' % data_path) + ref_filename,
                    subdir_prefix_path, seed, temp_dir)
            # Set up input folder structure if desired
            eprint("Cleanup simulated data...")
            self.dwgsim_out2qcumber_input(subdir_prefix,
                                          temp_dir, data_path,
                                          sim_hash_id, hash_run_id)
        return subdir_prefix.replace(sim_hash_id, hash_run_id)

    def dwgsim_generate_reads_unzip(self, input_ref, out_prefix, seed,
                                    tmp_dir,
                                    log_file='dwgsim_run', sequencer=0):
        '''
        function that calls dwgsim as a subprocess and unzips reference
        if necessary

        Args:
            tmp_dir (:obj:`str`): temporary directory used for random data
            input_ref (:obj:`str`): filename of input reference
            out_prefix (:obj:`str`): prefix for files and folders created
            seed (int): seed used to generate pseudo random data

        Kwargs:
            sequencer (int): type of sequencer used
                              0 - Illumina (default)
                              1 - SOLiD
                              2 - Ion-Torrent
            log_file (:obj:`str`): logfile per default "dwgsim_run.log"

        Returns:
            (bool): True if success and False otherwise.
                    In case of error check log
        '''
        zipped = input_ref[-3:] == '.gz'
        filename = input_ref.split('/')[-1]
        seed_opt = '-z%i' % (seed)
        options = [out_prefix, seed_opt]+self.opt
        unzipped_path = (input_ref
                         if not zipped
                         else tmp_dir + '/' + filename[:-3])
        # Checking if dwgsim files already exist
        dwgsim_status_filename = out_prefix + '.dwgsim_run_state'
        read_gen_string = ','.join([filename] + options[1:])
        # Adding Simulator Object to QCTestManager
        if self.dwgsim_output_missing(out_prefix, dwgsim_status_filename,
                                      read_gen_string):
            if(zipped and not os.path.isfile(unzipped_path)):
                _unzip(unzipped_path, input_ref)
            with open(log_file+'.log', 'w') as dwg_log:
                _generate_reads(unzipped_path, dwg_log, options, log_file)
            # write dwgsim status file
            with open(dwgsim_status_filename, 'w') as genfile:
                genfile.write(read_gen_string)

    def dwgsim_output_missing(self, dwgsim_out_prefix,
                              dwgsim_status_filename, read_gen_string):
        '''
        function checking if output of dwgsim already exists

        Args:
            dwgsim_out_prefix (:obj:`str`): output prefix used by dwgsim
            unzipped_path
        '''
        runs_read_gen = True
        # cmd_option_list = ['dwgsim', unzipped_path] + options
        if os.path.isfile(dwgsim_status_filename):
            with open(dwgsim_status_filename, 'r') as genfile:
                status_line = genfile.readline()
                runs_read_gen = read_gen_string not in status_line
        return runs_read_gen

    def dwgsim_out2qcumber_input(self, prefix, tmp_dir, data_path,
                                 sim_hash_id, hash_run_id):
        '''
        creating a directory in the temporary directory and symlinks to within
        the directory to test data generated by dwgsim

        Args:
            prefix (:obj:`str`): prefix/name used by dwgsim to create output
            tmp_dir (:obj:`str`): path to temporary directory
            data_path (:obj:`str`): path to data_dir where in the files that
                                    need renaming and symlinking are located
        '''
        real_prefix = prefix.replace(sim_hash_id, hash_run_id)
        tmp_qcumber_input_dir = '%s/%s' % (tmp_dir, real_prefix)
        if not os.path.isdir(tmp_qcumber_input_dir):
            try:
                os.mkdir(tmp_qcumber_input_dir)
            except FileExistsError as e:
                if not os.path.isdir(tmp_qcumber_input_dir):
                    eprint("mkdir failed: A file (not a directory)"
                           " with the same name already exists!\n")
        # ToDo: Need to check if file is already present in directory
        # and increment sample counter or sheet
        for i in range(1, 3):
            os.symlink(os.path.abspath(
                           '%s/%s.bwa.read%i.fastq' % (data_path, prefix, i)),
                       os.path.abspath(
                           '%s/%s_S1_L001_R%i_001.fastq' % (
                               tmp_qcumber_input_dir,
                               real_prefix, i)))
        return tmp_qcumber_input_dir


class InputFile(Structure):
    _default_field_values = [('configfile', ''), ('cutoff', 0)]
    _fields = [('file', str), ('configfile', str), ('cutoff', int)]

    def resolve_name(self):
        out = []
        name = self.file
        if not any((s_char in name for s_char in '*?[]')):
            new_file = copy.deepcopy(self)
            out = [new_file]
        else:
            for file_name in glob.iglob(name, recursive=True):
                new_file = copy.deepcopy(self)
                new_file.file = file_name
                out.append(new_file)
        return out


class RemoteInputFile(Structure):
    _default_field_values = [('cutoff', 0)]
    _fields = [('remote_id', str), ('cutoff', int)]


class LocalRealData(Structure):
    def __deserialize_input_files(value):
        return [InputFile(**x) for x in list(value)]
    _default_field_values = [('project_name', '')]
    _fields = [('project_name', str),
               ('input_files', __deserialize_input_files)]

    def get_file_trace(self):
        '''
        Gets string that defines the files that make up the real data
        '''
        return ','.join(('%s%s' % (f.file, ':%i' % f.cutoff
                                           if f.cutoff else '')
                         for f in self.input_files))

    def prepare_data(self, tmp_dir, prefix):
        dirs = {}
        files = {}
        # Deal with folders and Reads with same name
        for file_obj in (f for f_un_res in self.input_files
                         for f in f_un_res.resolve_name()):
            cur_fd_basname = os.path.basename(file_obj.file)
            if os.path.isdir(file_obj.file):
                if file_obj.file not in dirs:
                    dirs[cur_fd_basname] = file_obj
                else:
                    raise NotImplementedError('Input dirs have same name')
            else:
                if file_obj.file not in files:
                    files[cur_fd_basname] = file_obj
                else:
                    raise NotImplementedError('input files have same name')
        if not files and len(dirs) == 1 and not list(dirs.values())[0].cutoff:
            return list(dirs.values())[0].file
        # tmp_dir = '.'
        temp_input_folder = '%s/%s' % (tmp_dir, prefix)
        if not os.path.isdir(temp_input_folder):
            try:
                os.mkdir(temp_input_folder)
            except FileExistsError as e:
                if not os.path.isdir(temp_input_folder):
                    eprint("mkdir failed: A file (not a directory)"
                           " with the same name already exists!\n")
        # Add directory contents
        for dir, file in ((d, f)
                          for d in dirs
                          for f in os.listdir(dirs[d].file)):
            newfile = copy.deepcopy(dirs[dir])
            newfile.file = '%s/%s' % (dirs[dir].file, file)
            files[file] = newfile
        for f in files:
            if not files[f].cutoff or 'fastq' not in f:
                os.symlink(os.path.abspath(files[f].file),
                           '%s/%s' % (temp_input_folder, f))
            else:
                with ExitStack() as e_stack:
                    if f[-2:] == 'gz':
                        gzip_proc = e_stack.enter_context(
                            subprocess.Popen(['gzip', '-dc',
                                              files[f].file],
                                             stdout=subprocess.PIPE))
                        fastq_stream = gzip_proc.stdout
                    else:
                        fastq_stream = e_stack.enter_context(
                            open(files[f].file, 'rb'))
                    write_file = e_stack.enter_context(
                        open('%s/%s' % (temp_input_folder,
                                        f.strip('.gz')), 'wb'))
                    cut_proc = e_stack.enter_context(
                        subprocess.Popen(['head',
                                          '-n%i' % (4*files[f].cutoff)],
                                         stdin=fastq_stream,
                                         stdout=write_file))
                    cut_proc.wait()
                    if cut_proc.returncode:
                        raise subprocess.CalledProcessError(
                            returncode=cut_proc.returncode,
                            output='bash head error: shortening the'
                                   ' input file failed!')
        return temp_input_folder


class RemoteRealData(Structure):
    def __deserialize_remote_data(value):
        return [RemoteInputFile(**x) for x in list(value)]
    _default_field_values = [('project_name', '')]
    _fields = [('project_name', str),
               ('remote_data', __deserialize_remote_data)]

    def get_file_trace(self):
        '''
        Gets string that defines the files that make up the real data
        '''
        return ','.join(('%s%s' % (f.remote_id, ':%i' % f.cutoff
                                   if f.cutoff else '')
                         for f in self.input_files))

    def prepare_data(self, tmp_dir, prefix, file_info, data_path):
        files = {}
        temp_input_folder = '%s/%s' % (tmp_dir, prefix)
        # Deal with remote data
        for r_data in self.remote_data:
            for f in file_info[r_data.remote_id]:
                cur_f_basename = os.path.basename(f)
                files[cur_f_basename] = InputFile(
                        **{'file': "%s/%s" % (data_path, f),
                           'cutoff': r_data.cutoff})
        if not os.path.isdir(temp_input_folder):
            try:
                os.mkdir(temp_input_folder)
            except FileExistsError as e:
                if not os.path.isdir(temp_input_folder):
                    eprint("mkdir failed: A file (not a directory)"
                           " with the same name already exists!\n")
        # Add directory contents
        for f in files:
            if not files[f].cutoff or 'fastq' not in f:
                os.symlink(os.path.abspath(files[f].file),
                           '%s/%s' % (temp_input_folder, f))
            else:
                with ExitStack() as e_stack:
                    if f[-2:] == 'gz':
                        gzip_proc = e_stack.enter_context(
                            subprocess.Popen(['gzip', '-dc',
                                              files[f].file],
                                             stdout=subprocess.PIPE))
                        fastq_stream = gzip_proc.stdout
                    else:
                        fastq_stream = e_stack.enter_context(
                            open(files[f].file, 'rb'))
                    write_file = e_stack.enter_context(
                        open('%s/%s' % (temp_input_folder,
                                        f.strip('.gz')), 'wb'))
                    cut_proc = e_stack.enter_context(
                        subprocess.Popen(['head',
                                          '-n%i' % (4*files[f].cutoff)],
                                         stdin=fastq_stream,
                                         stdout=write_file))
                    cut_proc.wait()
                    if cut_proc.returncode:
                        raise subprocess.CalledProcessError(
                            returncode=cut_proc.returncode,
                            output='bash head error: shortening the'
                                   ' input file failed!')
        return temp_input_folder


class GenomicReference(RemoteFile):
    pass

# Yaml-Config Parser <---


def sanitize_name_for_illumina(sequence_name):
    '''
    Cleanup string for compatability with illumina naming conventions

    Args:
        sequence_name (:obj:`str`): name which will be sanitized
            (problematic chars will be replaced)
    '''
    separators_used = []
    bad_separators = ['_', '$', '.', '"', "'", '%']
    allowed_separators = ['-', '#', '&', '+', ';', ':', '!', ',', '~']
    separators_tried = 0
    for i in range(len(sequence_name)):
        try:
            bad_index = bad_separators.index(sequence_name[i])
            found_replacement = False
            while not found_replacement:
                if allowed_separators[separators_tried] not in sequence_name:
                    sequence_name = sequence_name.replace(
                        bad_separators[bad_index],
                        allowed_separators[separators_tried])
                    found_replacement = True
                    separators_used += [allowed_separators[separators_tried]]
                else:
                    separators_tried = separators_tried + 1
        except ValueError:
            pass
    return sequence_name, separators_used


def eprint(*args, **kwargs):
    '''
    print function that prints to stderr

    :return: returns nothing
    '''
    print(*args, file=sys.stderr, **kwargs)


def outputFileDialogue(outputFile, overwrite, interactive=True):
    '''
    Utility function for output File:
    Checking if it exists and prompting user if it exists,
    asking if the user wants to overwrite the file.

    Args:
        outputFile (str): output file name
        overwrite (bool): force overwrite of file if True
        interactive (:obj:`Bool`,optional): is user interaction wanted.
            default is True
    Returns:
        str: filename
    Raises:
        UserAbortError: if User types exit() into prompt
    '''
    if outputFile is sys.stdout:
        outputFile = outputFile.fileno()
    else:
        if os.path.isfile(outputFile):
            if interactive:
                if not overwrite:
                    eprint(outputFile, 'does already exist \n overwrite Y/n')
                    running = True
                    while running:
                        if input().upper() not in ['Y', 'YES']:
                            while running:
                                eprint(
                                    'Enter new filename or exit() to exit: ')
                                filename = input()
                                if filename == 'exit()':
                                    raise UserAbortError
                                elif not os.path.isfile(filename):
                                    outputFile = filename
                                    running = False
                                else:
                                    eprint(filename, 'already exists')
                        else:
                            running = False
    return outputFile


@contextmanager
def tmpdir():
    '''
    Generator/contextmanager that creats aTemporary directory
    and removes the same directory after context exit
    '''
    dirname = tempfile.mkdtemp()
    try:
        yield dirname
    finally:
        shutil.rmtree(dirname)


@contextmanager
def fifo():
    '''
    Generator/contextmanager that manages creation of a fifo
    '''
    dirname = tempfile.mkdtemp()
    try:
        path = os.path.join(dirname, 'tmp_fifo')
        os.mkfifo(path)
        yield path
    finally:
        shutil.rmtree(dirname)


@contextmanager
def pseudo_stderr():
    '''
    pseudo stdout context
    '''
    try:
        yield sys.stderr.buffer
    finally:
        pass


"""
@asyncio.coroutine
def copy_to_files(stream, outfile):
    ''' reads input stream and writes multiple output files

    asyncio.coroutine and yields from syntax allows the function
    to be used in the context of the async package

    Args:
        stream (:obj:`_io.TextIOWrapper`): input file handle
        outfile (:obj:`MutiFileOutput`): Multi file object that is
                                         used for writing
    '''
    while True:
        line = yield from stream.readline()
        if not line:
            break
        outfile.write(line)


@asyncio.coroutine
def run_cmd_and_redirect_output(cmd, out_files, err_files):
    ''' runs a cmd via bash and writes the output into files

    Args:
        cmd (:obj:`str`): command to run
        out_files (:obj:`MultiFileOutput`): Multi file object, for stdout of
            the program, whoose file handles have already been opened.
        err_files (:obj:`MultiFileOutput`): Multi file object, for stderr of
            the program, whoose file handles have already been opened.
    '''
    print('Does something')
    proc = yield from asyncio.create_subprocess_shell(
            cmd, stdout=asyncio.subprocess.PIPE,
            stderr=asyncio.subprocess.PIPE,
            executable='/bin/bash')
    try:
        yield from asyncio.gather(
                copy_to_files(proc.stdout, out_files),
                copy_to_files(proc.stderr, err_files))
    except Exception as e:
        proc.kill()
        print(e)
        raise
    finally:
        r_code = yield from proc.wait()
    return r_code
"""


def _unzip(output_name, zipped_input):
    '''
    unzipping file and redirecting it by running zcat as a subprocess

    Args:
        zipped_input (:obj:`str`): zipfile input
        output_name (:obj:`str`): file/pipe output

    Raises:
        subprocess.CalledProcessError, if gzip has non zero returnvalue
    '''
    with open(output_name, 'wb') as redirect_file:
        with subprocess.Popen(['zcat', zipped_input],
                              stdout=redirect_file) as gz_proc:
            gz_proc.communicate()
            if gz_proc.returncode:
                raise subprocess.CalledProcessError(
                    'Gzip failed with error code: %i\n' % (
                        gz_proc.returncode))


def hash_file(input_file, result_queue):
    hash = hashlib.sha1()
    with open(input_file, 'rb') as to_hash_file:
        hashing = True
        while hashing:
            data = to_hash_file.read(65536)
            hash.update(data)
            if not data:
                hashing = False
    result_queue.put(hash.hexdigest())


def cleanup_file_for_hashing(regex, file, outfile_name):
    with open(outfile_name, 'wb') as outfile:
        with subprocess.Popen(['perl', '-pe', regex, file],
                              stdout=outfile) as clean_proc:
            clean_proc.wait()
            if clean_proc.returncode:
                raise subprocess.CalledProcessError(
                        clean_proc.returncode,
                        "Perl Regex failed")


def _generate_reads(_redirect, _dwg_log, _options,
                    _log_file):
    '''
    function actually calling dwgsim and running it as a subprocess

    Args:
        _redirect (:obj:`str`): file/pipe reference genome
        _dwg_log (:obj:`_io.TextIOWrapper`): log file as file object
        _options (:obj:`list`): options of cmd as string list
        _log_file (:obj:`str`): log file as string

    Raises:
        subprocess.CalledProcessError, if dwgsim has non zero returnvalue
    '''
    _dwg_log.write('Simulating Reads by calling:\n%s\n' %
                   " ".join(['dwgsim', _redirect]+_options))
    _dwg_log.flush()
    cmd_option_list = ['dwgsim', _redirect] + _options
    with subprocess.Popen(cmd_option_list,
                          stdout=_dwg_log) as d_proc:
        d_proc.wait()
        if d_proc.returncode:
            raise subprocess.CalledProcessError(
                'The read simulation failed with error code: %i\n'
                'Please check logfile: "%s" ' % (d_proc.returncode,
                                                 _log_file))


def dont_fret_because_readline_is_never_used():
    version = readline._READLINE_VERSION
    print('Nothing of the readline module version: %s'
          'is ever directly called.\n'
          'Including it, allows the user to input things'
          'without losing his or hers mind!\n'
          '(Backspace works after the import)' % version)


# read-gen <---
if __name__ == '__main__':
    main()