CGATcore Experiment Module¶
experiment.py - writing reproducible scripts¶
The :mod:experiment
modules contains utility functions for argument
parsing, logging and record keeping within scripts.
This module is imported by most CGAT scripts. It provides convenient and consistent methods for
Record keeping
_Argument parsing
_Input/Output redirection
_Logging
_Running external commands
_Benchmarking
_
See :doc:../scripts/cgat_script_template
on how to use this module.
This module can handle both optparse and argparse. The default is to return an argparse object.
For default argparse: The basic usage of this module within a script is::
"""script_name.py - my script
Mode Documentation
"""
import sys
import optparse
import CGAT.experiment as E
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if not argv: argv = sys.argv
# setup command line parser
parser = E.OptionParser(description=__doc__)
parser.add_arguments("-t", "--test", dest="test", type="string",
help="supply help")
# add common options (-h/--help, ...) and parse
# command line
args = E.Start(parser)
# do something
# ...
E.info("an information message")
E.warn("a warning message)
## write footer and output benchmark information.
E.Stop()
if __name__ == "__main__":
sys.exit(main(sys.argv))
To use optparse: The basic usage of this module within a script is::
def main(argv=None):
"""script main.
parses command line options in sys.argv, unless *argv* is given.
"""
if not argv: argv = sys.argv
# setup command line parser
parser = E.OptionParser(version="%prog version: $Id$",
usage=globals()["__doc__"], optparse=True)
parser.add_option("-t", "--test", dest="test", type="string",
help="supply help")
# add common options (-h/--help, ...) and parse
# command line
(options, args) = E.Start(parser, optparse=True)
# do something
# ...
E.info("an information message")
E.warn("a warning message)
## write footer and output benchmark information.
E.Stop()
if __name__ == "__main__":
sys.exit(main(sys.argv))
Record keeping¶
The central functions in this module are the :py:func:Start
and
:py:func:Stop
methods which are called before or after any work is
done within a script.
The :py:func:Start
is called with an E.OptionParser object.
:py:func:Start
will add additional command line arguments, such as
--help
for command line help or --verbose
to control the
:term:loglevel
. It can also add optional arguments for scripts
needing database access, writing to multiple output files, etc.
:py:func:Start
will write record keeping information to a
logfile. Typically, logging information is output on stdout, prefixed
by a #
, but it can be re-directed to a separate file. Below is a
typical output::
# output generated by /ifs/devel/andreas/cgat/beds2beds.py --force-output --exclusive-overlap --method=unmerged-combinations --output-filename-pattern=030m.intersection.tsv.dir/030m.intersection.tsv-%s.bed.gz --log=030m.intersection.tsv.log Irf5-030m-R1.bed.gz Rela-030m-R1.bed.gz # nopep8
# job started at Thu Mar 29 13:06:33 2012 on cgat150.anat.ox.ac.uk -- e1c16e80-03a1-4023-9417-f3e44e33bdcd
# pid: 16649, system: Linux 2.6.32-220.7.1.el6.x86_64 #1 SMP Fri Feb 10 15:22:22 EST 2012 x86_64
# exclusive : True
# filename_update : None
# ignore_strand : False
# loglevel : 1
# method : unmerged-combinations
# output_filename_pattern : 030m.intersection.tsv.dir/030m.intersection.tsv-%s.bed.gz
# output_force : True
# pattern_id : (.*).bed.gz
# stderr : <open file '<stderr>', mode 'w' at 0x2ba70e0c2270>
# stdin : <open file '<stdin>', mode 'r' at 0x2ba70e0c2150>
# stdlog : <open file '030m.intersection.tsv.log', mode 'a' at 0x1f1a810>
# stdout : <open file '<stdout>', mode 'w' at 0x2ba70e0c21e0>
# timeit_file : None
# timeit_header : None
# timeit_name : all
# tracks : None
The header contains information about:
* the script name (``beds2beds.py``)
* the command line options (``--force-output --exclusive-overlap
--method=unmerged-combinations
--output-filename-pattern=030m.intersection.tsv.dir/030m.intersection.tsv-%s.bed.gz
--log=030m.intersection.tsv.log Irf5-030m-R1.bed.gz
Rela-030m-R1.bed.gz``)
* the time when the job was started (``Thu Mar 29 13:06:33 2012``)
* the location it was executed (``cgat150.anat.ox.ac.uk``)
* a unique job id (``e1c16e80-03a1-4023-9417-f3e44e33bdcd``)
* the pid of the job (``16649``)
* the system specification (``Linux 2.6.32-220.7.1.el6.x86_64 #1
SMP Fri Feb 10 15:22:22 EST 2012 x86_64``)
It is followed by a list of all options that have been set in the script.
Once completed, a script will call the :py:func:Stop
function to
signify the end of the experiment.
:py:func:Stop
will output to the log file that the script has
concluded successfully. Below is typical output::
# job finished in 11 seconds at Thu Mar 29 13:06:44 2012 -- 11.36 0.45 0.00 0.01 -- e1c16e80-03a1-4023-9417-f3e44e33bdcd
The footer contains information about:
- the job has finished (
job finished
) - the time it took to execute (
11 seconds
) - when it completed (
Thu Mar 29 13:06:44 2012
) - some benchmarking information (
11.36 0.45 0.00 0.01
) which isuser time
,system time
,child user time
,child system time
. - the unique job id (
e1c16e80-03a1-4023-9417-f3e44e33bdcd
)
The unique job id can be used to easily retrieve matching information from a concatenation of log files.
Argument parsing¶
The module provides :class:OptionParser
to facilitate option
parsing. :class:OptionParser
is derived from the
:py:class:optparse.OptionParser
class, but has improvements to
provide better formatted output on the command line. It also allows to
provide a comma-separated list to options that accept multiple
arguments. Thus, --method=sort --method=crop
and
--method=sort,crop
are equivalent.
Additionally, there are set of commonly used option groups that are
used in many scripts. The :func:Start
method has options to automatically
add these. For example::
(options, args) = E.Start(parser, add_output_options=True)
will add the option --output-filename-pattern
. Similarly::
(options, args) = E.Start(parser, add_database_options=True)
will add multiple options for scripts accessing databases, such as
--database-host
and --database-username
.
Input/Output redirection¶
:func:Start
adds the options --stdin
, --stderr` and
--stdout`` which allow using files as input/output streams.
To make this work, scripts should not read from sys.stdin or write to
sys.stdout directly, but instead use options.stdin
and
options.stdout
. For example to simply read all lines from stdin
and write to stdout, use::
(options, args) = E.Start(parser)
input_data = options.stdin.readlines() options.stdout.write("".join(input_data))
The script can then be used in many different contexts::
cat in.data | python script.py > out.data python script.py --stdin=in.data > out.data python script.py --stdin=in.data --stdout=out.data
The method handles gzip compressed files transparently. The following are equivalent::
zcat in.data.gz | python script.py | gzip > out.data.gz python script.py --stdin=in.data.gz --stdout=out.data.gz
For scripts producing multiple output files, use the argument
add_output_options=True
to :func:Start
. This provides the option
--output-filename-pattern
on the command line. The user can then
supply a pattern for output files. Any %s
appearing in the pattern
will be substituted by a section
. Inside the script, When opening
an output file, use the method :func:open_output_file
to provide a
file object::
output_histogram = E.open_output_file(section="histogram") output_stats = E.open_output_file(section="stats")
If the user calls the script with::
python script.py --output-filename-pattern=sample1_%s.tsv.gz
the script will create the files sample1_histogram.tsv.gz
and
sample1_stats.tsv.gz
.
This method will also add the option --force-output
to permit
overwriting existing files.
Logging¶
:py:mod:experiment
provides the well known logging methods from
the :py:mod:logging
module such as :py:func:info
,
:py:func:warn
, etc. These are provided so that no additional import
of the :py:mod:logging
module is required, but either functions
can be used.
Running external commands¶
The :func:run
method is a shortcut :py:func:subprocess.call
and
similar methods with some additional sanity checking.
Benchmarking¶
The :func:Start
method records basic benchmarking information when a
script starts and :func:Stop
outputs it as part of its final log
message::
# job finished in 11 seconds at Thu Mar 29 13:06:44 2012 -- 11.36 0.45 0.00 0.01 -- e1c16e80-03a1-4023-9417-f3e44e33bdcd
See Record keeping
_ for an explanations of the fields.
To facilitate collecting benchmark information from running multiple
scripts, these data can be tagged and saved in a separate file. See the
command line options --timeit
, --timeit-name
, --timeit-header
in :func:Start
.
The module contains some decorator functions for benchmarking
(:func:benchmark
) and caching function (:func:cached_function
) or
class method (:func:cached_method
) calls.
API¶
AppendCommaOption
¶
Bases: Option
Option with additional parsing capabilities.
-
"," in arguments to options that have the action 'append' are treated as a list of options. This is what galaxy does, but generally convenient.
-
Option values of "None" and "" are treated as default values.
Source code in cgatcore/experiment.py
ArgumentParser
¶
Bases: ArgumentParser
'CGAT derivative of ArgumentParser. OptionParser is still implimented for backwards compatibility
Source code in cgatcore/experiment.py
BetterFormatter
¶
Bases: IndentedHelpFormatter
A formatter for :class:OptionParser
outputting indented
help text.
Source code in cgatcore/experiment.py
Counter
¶
Bases: object
a counter class.
The counter acts both as a dictionary and a object permitting attribute access.
Counts are automatically initialized to 0.
Instantiate and use like this::
c = Counter() c.input += 1 c.output += 2 c["skipped"] += 1
print str(c)
Source code in cgatcore/experiment.py
1562 1563 1564 1565 1566 1567 1568 1569 1570 1571 1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597 1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 |
|
__init__()
¶
asTable(as_rows=True)
¶
return values as tab-separated table (without header).
Key, value pairs are sorted lexicographically.
Source code in cgatcore/experiment.py
MultiLineFormatter
¶
Bases: Formatter
logfile formatter: add identation for multi-line entries.
Source code in cgatcore/experiment.py
OptionParser
¶
Bases: OptionParser
CGAT derivative of ArgumentParser. OptionParser is still implemented for backwards compatibility
Source code in cgatcore/experiment.py
cached_function
¶
Bases: object
Decorator that caches a function's return value each time it is called. If called later with the same arguments, the cached value is returned, and not re-evaluated.
Taken from http://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Source code in cgatcore/experiment.py
cached_property
¶
Bases: object
Decorator for read-only properties.
Modified from https://wiki.python.org/moin/PythonDecoratorLibrary#Memoize
Source code in cgatcore/experiment.py
benchmark(func)
¶
decorator collecting wall clock time spent in decorated method.
Source code in cgatcore/experiment.py
callbackShortHelp(option, opt, value, parser)
¶
output short help (only command line options).
Source code in cgatcore/experiment.py
get_args()
¶
get_footer()
¶
return a header string with command line options and timestamp.
Source code in cgatcore/experiment.py
get_header()
¶
return a header string with command line options and timestamp
Source code in cgatcore/experiment.py
get_output_file(section, suffix=None)
¶
return filename to write to, replacing any %s
with section in
the output pattern for files (--output-filename-pattern
).
Arguments¶
section : string section will replace any %s in the pattern for output files suffix : string optional suffix to append to the filename. If provided, it will be added before any existing extension, or at the end if no extension exists.
Source code in cgatcore/experiment.py
get_params(options=None)
¶
return a string containing script parameters.
Parameters are all variables that start with param_
.
Source code in cgatcore/experiment.py
open_file(filename, mode='r', create_dir=False, encoding='utf-8')
¶
open file in filename with mode mode.
If create is set, the directory containing filename will be created if it does not exist.
gzip - compressed files are recognized by the
suffix .gz
and opened transparently.
Note that there are differences in the file like objects returned, for example in the ability to seek.
returns a file or file-like object.
Source code in cgatcore/experiment.py
open_output_file(section, mode='w', encoding='utf-8')
¶
open file for writing substituting section in the output_pattern (if defined).
This method will automatically create any parent directories that are missing.
If the filename ends with ".gz", the output is opened as a gzip'ed file.
Arguments¶
section : string section will replace any %s in the pattern for output files
char
file opening mode
Returns¶
File an opened file
Source code in cgatcore/experiment.py
run(statement, return_stdout=False, return_stderr=False, return_popen=False, on_error='raise', encoding='utf-8', **kwargs)
¶
execute a command line statement.
By default this method returns the code returned by the executed command. If return_stdout is True, the contents of stdout are returned as a string, likewise for return_stderr.
If return_popen, the Popen object is returned.
kwargs
are passed on to subprocess.call,
subprocess.check_output or subprocess.Popen.
Arguments¶
string
Action to perform on error. Valid actions are "ignore" and "raise".
Raises¶
OSError If process failed or was terminated.
Source code in cgatcore/experiment.py
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 1406 1407 1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 |
|
start(parser=None, argv=None, quiet=False, no_parsing=False, add_csv_options=False, add_database_options=False, add_pipe_options=True, add_cluster_options=False, add_output_options=False, logger_callback=None, return_parser=False, unknowns=False)
¶
set up an experiment.
The :py:func:Start
method will set up a file logger and add some
default and some optional options to the command line parser. It
will then parse the command line and set up input/output
redirection and start a timer for benchmarking purposes.
The default options added by this method are:
-v/--verbose
the :term:loglevel
timeit
turn on benchmarking information and save to file
timeit-name
name to use for timing information,
timeit-header
output header for timing information.
seed
the random seed. If given, the python random
number generator will be initialized with this
seed.
Optional options added are:
add_csv_options
dialect
csv_dialect. the default is excel-tab
, defaulting to
:term:tsv
formatted files.
add_database_options
-C/--connection
psql connection string
-U/--user
psql user name
add_cluster_options
--use-cluster
use cluster
--cluster-priority
cluster priority to request
--cluster-queue
cluster queue to use
--cluster-num-jobs
number of jobs to submit to the cluster at the same time
--cluster-options
additional options to the cluster for each job.
add_output_options
-P/--output-filename-pattern
Pattern to use for output filenames.
Arguments¶
:py:class:E.OptionParser
instance with command line options.
list
command line options to parse. Defaults to
:py:data:sys.argv
bool
set :term:loglevel
to 0 - no logging
bool
do not parse command line options
bool
return the parser object, no parsing. Useful for inspecting the command line options of a script without running it.
object
callback function to further configure logging system. The callback should accept the options as first parameter and return a logger.
bool
if a set of unknown args are to be returned
bool
specify if parser type is either optparse or argparse
Returns¶
tuple
(:py:class:E.OptionParser
object, list of positional
arguments)
Source code in cgatcore/experiment.py
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 |
|
stop(logger=None)
¶
stop the experiment.
This method performs final book-keeping, closes the output streams and writes the final log messages indicating script completion.
Source code in cgatcore/experiment.py
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 |
|
trace_calls(frame, event, arg)
¶
trace functions calls for debugging purposes.
See https://pymotw.com/2/sys/tracing.html