"keyword","repo_name","file_path","file_extension","file_size","line_count","content","language" "CRISPR","ctSkennerton/crass","TODO.md",".md","1440","27","# TODO ## Issues * Flanking sequences are not called correctly * Causes spacers to be called as flankers * Speed degrades rapidly with the number of patterns identified * Probable cause is the singleton finder * In some circumstances closely related groups are not getting split apart * The final output coverage of the spacer does not always correspond to the number of sources * Spacers go missing in the graph from Crass, but they are present if you perform a regular overlap assembly * This is not a sequencing error issue as even when searching with mismatches, there is not sign of the spacers * Spacer strings only get created during the initial pass of the graph building. However, spacer objects can also be made from the p-graph * This means that spacers may exist in the graph, but not in the output sequences. Maybe the cause of the above issue * If a slave DR is a perfect palindrome of the master DR the offset will be undefined ## Wanted Features * Multi-threading the search algorithms * Using paired read information in the search algorithms * Ability to run Crass on genomes or assembled contigs * Output a gff3 formatted file * Screen for known eukaryotic microsatellites for datasets that may be host contaminated ## Improvements * Use read information better when building the graph * Allow for multiple DR types to be in a single sequence. Very important if Crass is to work on genomes ","Markdown" "CRISPR","ctSkennerton/crass","autogen.sh",".sh","49146","1599","#!/bin/sh # a u t o g e n . s h # # Copyright (c) 2005-2011 United States Government as represented by # the U.S. Army Research Laboratory. # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions # are met: # # 1. Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # # 2. Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following # disclaimer in the documentation and/or other materials provided # with the distribution. # # 3. The name of the author may not be used to endorse or promote # products derived from this software without specific prior written # permission. # # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS # OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE # ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY # DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL # DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE # GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS # INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, # WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING # NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS # SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. # ### # # Script for automatically preparing the sources for compilation by # performing the myriad of necessary steps. The script attempts to # detect proper version support, and outputs warnings about particular # systems that have autotool peculiarities. # # Basically, if everything is set up and installed correctly, the # script will validate that minimum versions of the GNU Build System # tools are installed, account for several common configuration # issues, and then simply run autoreconf for you. # # If autoreconf fails, which can happen for many valid configurations, # this script proceeds to run manual preparation steps effectively # providing a POSIX shell script (mostly complete) reimplementation of # autoreconf. # # The AUTORECONF, AUTOCONF, AUTOMAKE, LIBTOOLIZE, ACLOCAL, AUTOHEADER # environment variables and corresponding _OPTIONS variables (e.g. # AUTORECONF_OPTIONS) may be used to override the default automatic # detection behaviors. Similarly the _VERSION variables will override # the minimum required version numbers. # # Examples: # # To obtain help on usage: # ./autogen.sh --help # # To obtain verbose output: # ./autogen.sh --verbose # # To skip autoreconf and prepare manually: # AUTORECONF=false ./autogen.sh # # To verbosely try running with an older (unsupported) autoconf: # AUTOCONF_VERSION=2.50 ./autogen.sh --verbose # # Author: # Christopher Sean Morrison # # Patches: # Sebastian Pipping # Tom Browder # ###################################################################### # set to minimum acceptable version of autoconf if [ ""x$AUTOCONF_VERSION"" = ""x"" ] ; then AUTOCONF_VERSION=2.52 fi # set to minimum acceptable version of automake if [ ""x$AUTOMAKE_VERSION"" = ""x"" ] ; then AUTOMAKE_VERSION=1.6.0 fi # set to minimum acceptable version of libtool if [ ""x$LIBTOOL_VERSION"" = ""x"" ] ; then LIBTOOL_VERSION=1.4.2 fi ################## # ident function # ################## ident ( ) { # extract copyright from header __copyright=""`grep Copyright $AUTOGEN_SH | head -${HEAD_N}1 | awk '{print $4}'`"" if [ ""x$__copyright"" = ""x"" ] ; then __copyright=""`date +%Y`"" fi # extract version from CVS Id string __id=""$Id$"" __version=""`echo $__id | sed 's/.*\([0-9][0-9][0-9][0-9]\)[-\/]\([0-9][0-9]\)[-\/]\([0-9][0-9]\).*/\1\2\3/'`"" if [ ""x$__version"" = ""x"" ] ; then __version="""" fi echo ""autogen.sh build preparation script by Christopher Sean Morrison"" echo "" + config.guess download patch by Sebastian Pipping (2008-12-03)"" echo ""revised 3-clause BSD-style license, copyright (c) $__copyright"" echo ""script version $__version, ISO/IEC 9945 POSIX shell script"" } ################## # USAGE FUNCTION # ################## usage ( ) { echo ""Usage: $AUTOGEN_SH [-h|--help] [-v|--verbose] [-q|--quiet] [-d|--download] [--version]"" echo "" --help Help on $NAME_OF_AUTOGEN usage"" echo "" --verbose Verbose progress output"" echo "" --quiet Quiet suppressed progress output"" echo "" --download Download the latest config.guess from gnulib"" echo "" --version Only perform GNU Build System version checks"" echo echo ""Description: This script will validate that minimum versions of the"" echo ""GNU Build System tools are installed and then run autoreconf for you."" echo ""Should autoreconf fail, manual preparation steps will be run"" echo ""potentially accounting for several common preparation issues. The"" echo ""AUTORECONF, AUTOCONF, AUTOMAKE, LIBTOOLIZE, ACLOCAL, AUTOHEADER,"" echo ""PROJECT, & CONFIGURE environment variables and corresponding _OPTIONS"" echo ""variables (e.g. AUTORECONF_OPTIONS) may be used to override the"" echo ""default automatic detection behavior."" echo ident return 0 } ########################## # VERSION_ERROR FUNCTION # ########################## version_error ( ) { if [ ""x$1"" = ""x"" ] ; then echo ""INTERNAL ERROR: version_error was not provided a version"" exit 1 fi if [ ""x$2"" = ""x"" ] ; then echo ""INTERNAL ERROR: version_error was not provided an application name"" exit 1 fi $ECHO $ECHO ""ERROR: To prepare the ${PROJECT} build system from scratch,"" $ECHO "" at least version $1 of $2 must be installed."" $ECHO $ECHO ""$NAME_OF_AUTOGEN does not need to be run on the same machine that will"" $ECHO ""run configure or make. Either the GNU Autotools will need to be installed"" $ECHO ""or upgraded on this system, or $NAME_OF_AUTOGEN must be run on the source"" $ECHO ""code on another system and then transferred to here. -- Cheers!"" $ECHO } ########################## # VERSION_CHECK FUNCTION # ########################## version_check ( ) { if [ ""x$1"" = ""x"" ] ; then echo ""INTERNAL ERROR: version_check was not provided a minimum version"" exit 1 fi _min=""$1"" if [ ""x$2"" = ""x"" ] ; then echo ""INTERNAL ERROR: version check was not provided a comparison version"" exit 1 fi _cur=""$2"" # needed to handle versions like 1.10 and 1.4-p6 _min=""`echo ${_min}. | sed 's/[^0-9]/./g' | sed 's/\.\././g'`"" _cur=""`echo ${_cur}. | sed 's/[^0-9]/./g' | sed 's/\.\././g'`"" _min_major=""`echo $_min | cut -d. -f1`"" _min_minor=""`echo $_min | cut -d. -f2`"" _min_patch=""`echo $_min | cut -d. -f3`"" _cur_major=""`echo $_cur | cut -d. -f1`"" _cur_minor=""`echo $_cur | cut -d. -f2`"" _cur_patch=""`echo $_cur | cut -d. -f3`"" if [ ""x$_min_major"" = ""x"" ] ; then _min_major=0 fi if [ ""x$_min_minor"" = ""x"" ] ; then _min_minor=0 fi if [ ""x$_min_patch"" = ""x"" ] ; then _min_patch=0 fi if [ ""x$_cur_minor"" = ""x"" ] ; then _cur_major=0 fi if [ ""x$_cur_minor"" = ""x"" ] ; then _cur_minor=0 fi if [ ""x$_cur_patch"" = ""x"" ] ; then _cur_patch=0 fi $VERBOSE_ECHO ""Checking if ${_cur_major}.${_cur_minor}.${_cur_patch} is greater than ${_min_major}.${_min_minor}.${_min_patch}"" if [ $_min_major -lt $_cur_major ] ; then return 0 elif [ $_min_major -eq $_cur_major ] ; then if [ $_min_minor -lt $_cur_minor ] ; then return 0 elif [ $_min_minor -eq $_cur_minor ] ; then if [ $_min_patch -lt $_cur_patch ] ; then return 0 elif [ $_min_patch -eq $_cur_patch ] ; then return 0 fi fi fi return 1 } ###################################### # LOCATE_CONFIGURE_TEMPLATE FUNCTION # ###################################### locate_configure_template ( ) { _pwd=""`pwd`"" if test -f ""./configure.ac"" ; then echo ""./configure.ac"" elif test -f ""./configure.in"" ; then echo ""./configure.in"" elif test -f ""$_pwd/configure.ac"" ; then echo ""$_pwd/configure.ac"" elif test -f ""$_pwd/configure.in"" ; then echo ""$_pwd/configure.in"" elif test -f ""$PATH_TO_AUTOGEN/configure.ac"" ; then echo ""$PATH_TO_AUTOGEN/configure.ac"" elif test -f ""$PATH_TO_AUTOGEN/configure.in"" ; then echo ""$PATH_TO_AUTOGEN/configure.in"" fi } ################## # argument check # ################## ARGS=""$*"" PATH_TO_AUTOGEN=""`dirname $0`"" NAME_OF_AUTOGEN=""`basename $0`"" AUTOGEN_SH=""$PATH_TO_AUTOGEN/$NAME_OF_AUTOGEN"" LIBTOOL_M4=""${PATH_TO_AUTOGEN}/misc/libtool.m4"" if [ ""x$HELP"" = ""x"" ] ; then HELP=no fi if [ ""x$QUIET"" = ""x"" ] ; then QUIET=no fi if [ ""x$VERBOSE"" = ""x"" ] ; then VERBOSE=no fi if [ ""x$VERSION_ONLY"" = ""x"" ] ; then VERSION_ONLY=no fi if [ ""x$DOWNLOAD"" = ""x"" ] ; then DOWNLOAD=no fi if [ ""x$AUTORECONF_OPTIONS"" = ""x"" ] ; then AUTORECONF_OPTIONS=""-i -f"" fi if [ ""x$AUTOCONF_OPTIONS"" = ""x"" ] ; then AUTOCONF_OPTIONS=""-f"" fi if [ ""x$AUTOMAKE_OPTIONS"" = ""x"" ] ; then AUTOMAKE_OPTIONS=""-a -c -f"" fi ALT_AUTOMAKE_OPTIONS=""-a -c"" if [ ""x$LIBTOOLIZE_OPTIONS"" = ""x"" ] ; then LIBTOOLIZE_OPTIONS=""--automake -c -f"" fi ALT_LIBTOOLIZE_OPTIONS=""--automake --copy --force"" if [ ""x$ACLOCAL_OPTIONS"" = ""x"" ] ; then ACLOCAL_OPTIONS="""" fi if [ ""x$AUTOHEADER_OPTIONS"" = ""x"" ] ; then AUTOHEADER_OPTIONS="""" fi if [ ""x$CONFIG_GUESS_URL"" = ""x"" ] ; then CONFIG_GUESS_URL=""http://git.savannah.gnu.org/gitweb/?p=gnulib.git;a=blob_plain;f=build-aux/config.guess;hb=HEAD"" fi for arg in $ARGS ; do case ""x$arg"" in x--help) HELP=yes ;; x-[hH]) HELP=yes ;; x--quiet) QUIET=yes ;; x-[qQ]) QUIET=yes ;; x--verbose) VERBOSE=yes ;; x-[dD]) DOWNLOAD=yes ;; x--download) DOWNLOAD=yes ;; x-[vV]) VERBOSE=yes ;; x--version) VERSION_ONLY=yes ;; *) echo ""Unknown option: $arg"" echo usage exit 1 ;; esac done ##################### # environment check # ##################### # sanity check before recursions potentially begin if [ ! -f ""$AUTOGEN_SH"" ] ; then if test -f ./autogen.sh ; then PATH_TO_AUTOGEN=""."" NAME_OF_AUTOGEN=""autogen.sh"" AUTOGEN_SH=""$PATH_TO_AUTOGEN/$NAME_OF_AUTOGEN"" else echo ""INTERNAL ERROR: $AUTOGEN_SH does not exist"" exit 1 fi fi # force locale setting to C so things like date output as expected LC_ALL=C # commands that this script expects for __cmd in echo head tail pwd ; do echo ""test"" > /dev/null 2>&1 | $__cmd > /dev/null 2>&1 if [ $? != 0 ] ; then echo ""INTERNAL ERROR: '${__cmd}' command is required"" exit 2 fi done echo ""test"" | grep ""test"" > /dev/null 2>&1 if test ! x$? = x0 ; then echo ""INTERNAL ERROR: grep command is required"" exit 1 fi echo ""test"" | sed ""s/test/test/"" > /dev/null 2>&1 if test ! x$? = x0 ; then echo ""INTERNAL ERROR: sed command is required"" exit 1 fi # determine the behavior of echo case `echo ""testing\c""; echo 1,2,3`,`echo -n testing; echo 1,2,3` in *c*,-n*) ECHO_N= ECHO_C=' ' ECHO_T=' ' ;; *c*,* ) ECHO_N=-n ECHO_C= ECHO_T= ;; *) ECHO_N= ECHO_C='\c' ECHO_T= ;; esac # determine the behavior of head case ""x`echo 'head' | head -n 1 2>&1`"" in *xhead*) HEAD_N=""n "" ;; *) HEAD_N="""" ;; esac # determine the behavior of tail case ""x`echo 'tail' | tail -n 1 2>&1`"" in *xtail*) TAIL_N=""n "" ;; *) TAIL_N="""" ;; esac VERBOSE_ECHO=: ECHO=: if [ ""x$QUIET"" = ""xyes"" ] ; then if [ ""x$VERBOSE"" = ""xyes"" ] ; then echo ""Verbose output quelled by quiet option. Further output disabled."" fi else ECHO=echo if [ ""x$VERBOSE"" = ""xyes"" ] ; then echo ""Verbose output enabled"" VERBOSE_ECHO=echo fi fi # allow a recursive run to disable further recursions if [ ""x$RUN_RECURSIVE"" = ""x"" ] ; then RUN_RECURSIVE=yes fi ################################################ # check for help arg and bypass version checks # ################################################ if [ ""x`echo $ARGS | sed 's/.*[hH][eE][lL][pP].*/help/'`"" = ""xhelp"" ] ; then HELP=yes fi if [ ""x$HELP"" = ""xyes"" ] ; then usage $ECHO ""---"" $ECHO ""Help was requested. No preparation or configuration will be performed."" exit 0 fi ####################### # set up signal traps # ####################### untrap_abnormal ( ) { for sig in 1 2 13 15; do trap - $sig done } # do this cleanup whenever we exit. trap ' # start from the root if test -d ""$START_PATH"" ; then cd ""$START_PATH"" fi # restore/delete backup files if test ""x$PFC_INIT"" = ""x1"" ; then recursive_restore fi ' 0 # trap SIGHUP (1), SIGINT (2), SIGPIPE (13), SIGTERM (15) for sig in 1 2 13 15; do trap ' $ECHO """" $ECHO ""Aborting $NAME_OF_AUTOGEN: caught signal '$sig'"" # start from the root if test -d ""$START_PATH"" ; then cd ""$START_PATH"" fi # clean up on abnormal exit $VERBOSE_ECHO ""rm -rf autom4te.cache"" rm -rf autom4te.cache if test -f ""acinclude.m4.$$.backup"" ; then $VERBOSE_ECHO ""cat acinclude.m4.$$.backup > acinclude.m4"" chmod u+w acinclude.m4 cat acinclude.m4.$$.backup > acinclude.m4 $VERBOSE_ECHO ""rm -f acinclude.m4.$$.backup"" rm -f acinclude.m4.$$.backup fi { (exit 1); exit 1; } ' $sig done ############################# # look for a configure file # ############################# if [ ""x$CONFIGURE"" = ""x"" ] ; then CONFIGURE=""`locate_configure_template`"" if [ ! ""x$CONFIGURE"" = ""x"" ] ; then $VERBOSE_ECHO ""Found a configure template: $CONFIGURE"" fi else $ECHO ""Using CONFIGURE environment variable override: $CONFIGURE"" fi if [ ""x$CONFIGURE"" = ""x"" ] ; then if [ ""x$VERSION_ONLY"" = ""xyes"" ] ; then CONFIGURE=/dev/null else $ECHO $ECHO ""A configure.ac or configure.in file could not be located implying"" $ECHO ""that the GNU Build System is at least not used in this directory. In"" $ECHO ""any case, there is nothing to do here without one of those files."" $ECHO $ECHO ""ERROR: No configure.in or configure.ac file found in `pwd`"" exit 1 fi fi #################### # get project name # #################### if [ ""x$PROJECT"" = ""x"" ] ; then PROJECT=""`grep AC_INIT $CONFIGURE | grep -v '.*#.*AC_INIT' | tail -${TAIL_N}1 | sed 's/^[ ]*AC_INIT(\([^,)]*\).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`"" if [ ""x$PROJECT"" = ""xAC_INIT"" ] ; then # projects might be using the older/deprecated arg-less AC_INIT .. look for AM_INIT_AUTOMAKE instead PROJECT=""`grep AM_INIT_AUTOMAKE $CONFIGURE | grep -v '.*#.*AM_INIT_AUTOMAKE' | tail -${TAIL_N}1 | sed 's/^[ ]*AM_INIT_AUTOMAKE(\([^,)]*\).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`"" fi if [ ""x$PROJECT"" = ""xAM_INIT_AUTOMAKE"" ] ; then PROJECT=""project"" fi if [ ""x$PROJECT"" = ""x"" ] ; then PROJECT=""project"" fi else $ECHO ""Using PROJECT environment variable override: $PROJECT"" fi $ECHO ""Preparing the $PROJECT build system...please wait"" $ECHO ######################## # check for autoreconf # ######################## HAVE_AUTORECONF=no if [ ""x$AUTORECONF"" = ""x"" ] ; then for AUTORECONF in autoreconf ; do $VERBOSE_ECHO ""Checking autoreconf version: $AUTORECONF --version"" $AUTORECONF --version > /dev/null 2>&1 if [ $? = 0 ] ; then HAVE_AUTORECONF=yes break fi done else HAVE_AUTORECONF=yes $ECHO ""Using AUTORECONF environment variable override: $AUTORECONF"" fi ########################## # autoconf version check # ########################## _acfound=no if [ ""x$AUTOCONF"" = ""x"" ] ; then for AUTOCONF in autoconf ; do $VERBOSE_ECHO ""Checking autoconf version: $AUTOCONF --version"" $AUTOCONF --version > /dev/null 2>&1 if [ $? = 0 ] ; then _acfound=yes break fi done else _acfound=yes $ECHO ""Using AUTOCONF environment variable override: $AUTOCONF"" fi _report_error=no if [ ! ""x$_acfound"" = ""xyes"" ] ; then $ECHO ""ERROR: Unable to locate GNU Autoconf."" _report_error=yes else _version=""`$AUTOCONF --version | head -${HEAD_N}1 | sed 's/[^0-9]*\([0-9\.][0-9\.]*\)/\1/'`"" if [ ""x$_version"" = ""x"" ] ; then _version=""0.0.0"" fi $ECHO ""Found GNU Autoconf version $_version"" version_check ""$AUTOCONF_VERSION"" ""$_version"" if [ $? -ne 0 ] ; then _report_error=yes fi fi if [ ""x$_report_error"" = ""xyes"" ] ; then version_error ""$AUTOCONF_VERSION"" ""GNU Autoconf"" exit 1 fi ########################## # automake version check # ########################## _amfound=no if [ ""x$AUTOMAKE"" = ""x"" ] ; then for AUTOMAKE in automake ; do $VERBOSE_ECHO ""Checking automake version: $AUTOMAKE --version"" $AUTOMAKE --version > /dev/null 2>&1 if [ $? = 0 ] ; then _amfound=yes break fi done else _amfound=yes $ECHO ""Using AUTOMAKE environment variable override: $AUTOMAKE"" fi _report_error=no if [ ! ""x$_amfound"" = ""xyes"" ] ; then $ECHO $ECHO ""ERROR: Unable to locate GNU Automake."" _report_error=yes else _version=""`$AUTOMAKE --version | head -${HEAD_N}1 | sed 's/[^0-9]*\([0-9\.][0-9\.]*\)/\1/'`"" if [ ""x$_version"" = ""x"" ] ; then _version=""0.0.0"" fi $ECHO ""Found GNU Automake version $_version"" version_check ""$AUTOMAKE_VERSION"" ""$_version"" if [ $? -ne 0 ] ; then _report_error=yes fi fi if [ ""x$_report_error"" = ""xyes"" ] ; then version_error ""$AUTOMAKE_VERSION"" ""GNU Automake"" exit 1 fi ######################## # check for libtoolize # ######################## HAVE_LIBTOOLIZE=yes HAVE_ALT_LIBTOOLIZE=no _ltfound=no if [ ""x$LIBTOOLIZE"" = ""x"" ] ; then LIBTOOLIZE=libtoolize $VERBOSE_ECHO ""Checking libtoolize version: $LIBTOOLIZE --version"" $LIBTOOLIZE --version > /dev/null 2>&1 if [ ! $? = 0 ] ; then HAVE_LIBTOOLIZE=no $ECHO if [ ""x$HAVE_AUTORECONF"" = ""xno"" ] ; then $ECHO ""Warning: libtoolize does not appear to be available."" else $ECHO ""Warning: libtoolize does not appear to be available. This means that"" $ECHO ""the automatic build preparation via autoreconf will probably not work."" $ECHO ""Preparing the build by running each step individually, however, should"" $ECHO ""work and will be done automatically for you if autoreconf fails."" fi # look for some alternates for tool in glibtoolize libtoolize15 libtoolize14 libtoolize13 ; do $VERBOSE_ECHO ""Checking libtoolize alternate: $tool --version"" _glibtoolize=""`$tool --version > /dev/null 2>&1`"" if [ $? = 0 ] ; then $VERBOSE_ECHO ""Found $tool --version"" _glti=""`which $tool`"" if [ ""x$_glti"" = ""x"" ] ; then $VERBOSE_ECHO ""Cannot find $tool with which"" continue; fi if test ! -f ""$_glti"" ; then $VERBOSE_ECHO ""Cannot use $tool, $_glti is not a file"" continue; fi _gltidir=""`dirname $_glti`"" if [ ""x$_gltidir"" = ""x"" ] ; then $VERBOSE_ECHO ""Cannot find $tool path with dirname of $_glti"" continue; fi if test ! -d ""$_gltidir"" ; then $VERBOSE_ECHO ""Cannot use $tool, $_gltidir is not a directory"" continue; fi HAVE_ALT_LIBTOOLIZE=yes LIBTOOLIZE=""$tool"" $ECHO $ECHO ""Fortunately, $tool was found which means that your system may simply"" $ECHO ""have a non-standard or incomplete GNU Autotools install. If you have"" $ECHO ""sufficient system access, it may be possible to quell this warning by"" $ECHO ""running:"" $ECHO sudo -V > /dev/null 2>&1 if [ $? = 0 ] ; then $ECHO "" sudo ln -s $_glti $_gltidir/libtoolize"" $ECHO else $ECHO "" ln -s $_glti $_gltidir/libtoolize"" $ECHO $ECHO ""Run that as root or with proper permissions to the $_gltidir directory"" $ECHO fi _ltfound=yes break fi done else _ltfound=yes fi else _ltfound=yes $ECHO ""Using LIBTOOLIZE environment variable override: $LIBTOOLIZE"" fi ############################ # libtoolize version check # ############################ _report_error=no if [ ! ""x$_ltfound"" = ""xyes"" ] ; then $ECHO $ECHO ""ERROR: Unable to locate GNU Libtool."" _report_error=yes else _version=""`$LIBTOOLIZE --version | head -${HEAD_N}1 | sed 's/[^0-9]*\([0-9\.][0-9\.]*\)/\1/'`"" if [ ""x$_version"" = ""x"" ] ; then _version=""0.0.0"" fi $ECHO ""Found GNU Libtool version $_version"" version_check ""$LIBTOOL_VERSION"" ""$_version"" if [ $? -ne 0 ] ; then _report_error=yes fi fi if [ ""x$_report_error"" = ""xyes"" ] ; then version_error ""$LIBTOOL_VERSION"" ""GNU Libtool"" exit 1 fi ##################### # check for aclocal # ##################### if [ ""x$ACLOCAL"" = ""x"" ] ; then for ACLOCAL in aclocal ; do $VERBOSE_ECHO ""Checking aclocal version: $ACLOCAL --version"" $ACLOCAL --version > /dev/null 2>&1 if [ $? = 0 ] ; then break fi done else $ECHO ""Using ACLOCAL environment variable override: $ACLOCAL"" fi ######################## # check for autoheader # ######################## if [ ""x$AUTOHEADER"" = ""x"" ] ; then for AUTOHEADER in autoheader ; do $VERBOSE_ECHO ""Checking autoheader version: $AUTOHEADER --version"" $AUTOHEADER --version > /dev/null 2>&1 if [ $? = 0 ] ; then break fi done else $ECHO ""Using AUTOHEADER environment variable override: $AUTOHEADER"" fi ######################### # check if version only # ######################### $VERBOSE_ECHO ""Checking whether to only output version information"" if [ ""x$VERSION_ONLY"" = ""xyes"" ] ; then $ECHO ident $ECHO ""---"" $ECHO ""Version requested. No preparation or configuration will be performed."" exit 0 fi ################################# # PROTECT_FROM_CLOBBER FUNCTION # ################################# protect_from_clobber ( ) { PFC_INIT=1 # protect COPYING & INSTALL from overwrite by automake. the # automake force option will (inappropriately) ignore the existing # contents of a COPYING and/or INSTALL files (depending on the # version) instead of just forcing *missing* files like it does # for AUTHORS, NEWS, and README. this is broken but extremely # prevalent behavior, so we protect against it by keeping a backup # of the file that can later be restored. for file in COPYING INSTALL ; do if test -f ${file} ; then if test -f ${file}.$$.protect_from_automake.backup ; then $VERBOSE_ECHO ""Already backed up ${file} in `pwd`"" else $VERBOSE_ECHO ""Backing up ${file} in `pwd`"" $VERBOSE_ECHO ""cp -p ${file} ${file}.$$.protect_from_automake.backup"" cp -p ${file} ${file}.$$.protect_from_automake.backup fi fi done } ############################## # RECURSIVE_PROTECT FUNCTION # ############################## recursive_protect ( ) { # for projects using recursive configure, run the build # preparation steps for the subdirectories. this function assumes # START_PATH was set to pwd before recursion begins so that # relative paths work. # git 'r done, protect COPYING and INSTALL from being clobbered protect_from_clobber if test -d autom4te.cache ; then $VERBOSE_ECHO ""Found an autom4te.cache directory, deleting it"" $VERBOSE_ECHO ""rm -rf autom4te.cache"" rm -rf autom4te.cache fi # find configure template _configure=""`locate_configure_template`"" if [ ""x$_configure"" = ""x"" ] ; then return fi # $VERBOSE_ECHO ""Looking for configure template found `pwd`/$_configure"" # look for subdirs # $VERBOSE_ECHO ""Looking for subdirs in `pwd`"" _det_config_subdirs=""`grep AC_CONFIG_SUBDIRS $_configure | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ ]*AC_CONFIG_SUBDIRS(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`"" CHECK_DIRS="""" for dir in $_det_config_subdirs ; do if test -d ""`pwd`/$dir"" ; then CHECK_DIRS=""$CHECK_DIRS \""`pwd`/$dir\"""" fi done # process subdirs if [ ! ""x$CHECK_DIRS"" = ""x"" ] ; then $VERBOSE_ECHO ""Recursively scanning the following directories:"" $VERBOSE_ECHO "" $CHECK_DIRS"" for dir in $CHECK_DIRS ; do $VERBOSE_ECHO ""Protecting files from automake in $dir"" cd ""$START_PATH"" eval ""cd $dir"" # recursively git 'r done recursive_protect done fi } # end of recursive_protect ############################# # RESTORE_CLOBBERED FUNCION # ############################# restore_clobbered ( ) { # The automake (and autoreconf by extension) -f/--force-missing # option may overwrite COPYING and INSTALL even if they do exist. # Here we restore the files if necessary. spacer=no for file in COPYING INSTALL ; do if test -f ${file}.$$.protect_from_automake.backup ; then if test -f ${file} ; then # compare entire content, restore if needed if test ""x`cat ${file}`"" != ""x`cat ${file}.$$.protect_from_automake.backup`"" ; then if test ""x$spacer"" = ""xno"" ; then $VERBOSE_ECHO spacer=yes fi # restore the backup $VERBOSE_ECHO ""Restoring ${file} from backup (automake -f likely clobbered it)"" $VERBOSE_ECHO ""rm -f ${file}"" rm -f ${file} $VERBOSE_ECHO ""mv ${file}.$$.protect_from_automake.backup ${file}"" mv ${file}.$$.protect_from_automake.backup ${file} fi # check contents elif test -f ${file}.$$.protect_from_automake.backup ; then $VERBOSE_ECHO ""mv ${file}.$$.protect_from_automake.backup ${file}"" mv ${file}.$$.protect_from_automake.backup ${file} fi # -f ${file} # just in case $VERBOSE_ECHO ""rm -f ${file}.$$.protect_from_automake.backup"" rm -f ${file}.$$.protect_from_automake.backup fi # -f ${file}.$$.protect_from_automake.backup done CONFIGURE=""`locate_configure_template`"" if [ ""x$CONFIGURE"" = ""x"" ] ; then return fi _aux_dir=""`grep AC_CONFIG_AUX_DIR $CONFIGURE | grep -v '.*#.*AC_CONFIG_AUX_DIR' | tail -${TAIL_N}1 | sed 's/^[ ]*AC_CONFIG_AUX_DIR(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`"" if test ! -d ""$_aux_dir"" ; then _aux_dir=. fi for file in config.guess config.sub ltmain.sh ; do if test -f ""${_aux_dir}/${file}"" ; then $VERBOSE_ECHO ""rm -f \""${_aux_dir}/${file}.backup\"""" rm -f ""${_aux_dir}/${file}.backup"" fi done } # end of restore_clobbered ############################## # RECURSIVE_RESTORE FUNCTION # ############################## recursive_restore ( ) { # restore COPYING and INSTALL from backup if they were clobbered # for each directory recursively. # git 'r undone restore_clobbered # find configure template _configure=""`locate_configure_template`"" if [ ""x$_configure"" = ""x"" ] ; then return fi # look for subdirs _det_config_subdirs=""`grep AC_CONFIG_SUBDIRS $_configure | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ ]*AC_CONFIG_SUBDIRS(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`"" CHECK_DIRS="""" for dir in $_det_config_subdirs ; do if test -d ""`pwd`/$dir"" ; then CHECK_DIRS=""$CHECK_DIRS \""`pwd`/$dir\"""" fi done # process subdirs if [ ! ""x$CHECK_DIRS"" = ""x"" ] ; then $VERBOSE_ECHO ""Recursively scanning the following directories:"" $VERBOSE_ECHO "" $CHECK_DIRS"" for dir in $CHECK_DIRS ; do $VERBOSE_ECHO ""Checking files for automake damage in $dir"" cd ""$START_PATH"" eval ""cd $dir"" # recursively git 'r undone recursive_restore done fi } # end of recursive_restore ####################### # INITIALIZE FUNCTION # ####################### initialize ( ) { # this routine performs a variety of directory-specific # initializations. some are sanity checks, some are preventive, # and some are necessary setup detection. # # this function sets: # CONFIGURE # SEARCH_DIRS # CONFIG_SUBDIRS ################################## # check for a configure template # ################################## CONFIGURE=""`locate_configure_template`"" if [ ""x$CONFIGURE"" = ""x"" ] ; then $ECHO $ECHO ""A configure.ac or configure.in file could not be located implying"" $ECHO ""that the GNU Build System is at least not used in this directory. In"" $ECHO ""any case, there is nothing to do here without one of those files."" $ECHO $ECHO ""ERROR: No configure.in or configure.ac file found in `pwd`"" exit 1 fi ##################### # detect an aux dir # ##################### _aux_dir=""`grep AC_CONFIG_AUX_DIR $CONFIGURE | grep -v '.*#.*AC_CONFIG_AUX_DIR' | tail -${TAIL_N}1 | sed 's/^[ ]*AC_CONFIG_AUX_DIR(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`"" if test ! -d ""$_aux_dir"" ; then _aux_dir=. else $VERBOSE_ECHO ""Detected auxillary directory: $_aux_dir"" fi ################################ # detect a recursive configure # ################################ CONFIG_SUBDIRS="""" _det_config_subdirs=""`grep AC_CONFIG_SUBDIRS $CONFIGURE | grep -v '.*#.*AC_CONFIG_SUBDIRS' | sed 's/^[ ]*AC_CONFIG_SUBDIRS(\(.*\)).*/\1/' | sed 's/.*\[\(.*\)\].*/\1/'`"" for dir in $_det_config_subdirs ; do if test -d ""`pwd`/$dir"" ; then $VERBOSE_ECHO ""Detected recursive configure directory: `pwd`/$dir"" CONFIG_SUBDIRS=""$CONFIG_SUBDIRS `pwd`/$dir"" fi done ########################################################### # make sure certain required files exist for GNU projects # ########################################################### _marker_found="""" _marker_found_message_intro='Detected non-GNU marker ""' _marker_found_message_mid='"" in ' for marker in foreign cygnus ; do _marker_found_message=${_marker_found_message_intro}${marker}${_marker_found_message_mid} _marker_found=""`grep 'AM_INIT_AUTOMAKE.*'${marker} $CONFIGURE`"" if [ ! ""x$_marker_found"" = ""x"" ] ; then $VERBOSE_ECHO ""${_marker_found_message}`basename \""$CONFIGURE\""`"" break fi __makefile=`dirname \""$CONFIGURE\""/Makefile.am` if test -f ""$__makefile"" ; then _marker_found=""`grep 'AUTOMAKE_OPTIONS.*'${marker} $__makefile`"" if [ ! ""x$_marker_found"" = ""x"" ] ; then $VERBOSE_ECHO ""${_marker_found_message}${__makefile}"" break fi fi done if [ ""x${_marker_found}"" = ""x"" ] ; then _suggest_foreign=no for file in AUTHORS COPYING ChangeLog INSTALL NEWS README ; do if [ ! -f $file ] ; then $VERBOSE_ECHO ""Touching ${file} since it does not exist"" _suggest_foreign=yes touch $file fi done if [ ""x${_suggest_foreign}"" = ""xyes"" ] ; then $ECHO $ECHO ""Warning: Several files expected of projects that conform to the GNU"" $ECHO ""coding standards were not found. The files were automatically added"" $ECHO ""for you since you do not have a 'foreign' declaration specified."" $ECHO $ECHO ""Consider adding 'foreign' to AM_INIT_AUTOMAKE in `basename \""$CONFIGURE\""`"" __makefile=`dirname \""$CONFIGURE\""/Makefile.am` if test -f ""$__makefile"" ; then $ECHO ""or to AUTOMAKE_OPTIONS in your top-level Makefile.am file."" fi $ECHO fi fi ################################################## # make sure certain generated files do not exist # ################################################## for file in config.guess config.sub ltmain.sh ; do if test -f ""${_aux_dir}/${file}"" ; then $VERBOSE_ECHO ""mv -f \""${_aux_dir}/${file}\"" \""${_aux_dir}/${file}.backup\"""" mv -f ""${_aux_dir}/${file}"" ""${_aux_dir}/${file}.backup"" fi done ############################ # search alternate m4 dirs # ############################ SEARCH_DIRS="""" for dir in m4 ; do if [ -d $dir ] ; then $VERBOSE_ECHO ""Found extra aclocal search directory: $dir"" SEARCH_DIRS=""$SEARCH_DIRS -I `pwd`/$dir"" fi done ###################################### # remove any previous build products # ###################################### if test -d autom4te.cache ; then $VERBOSE_ECHO ""Found an autom4te.cache directory, deleting it"" $VERBOSE_ECHO ""rm -rf autom4te.cache"" rm -rf autom4te.cache fi # tcl/tk (and probably others) have a customized aclocal.m4, so can't delete it # if test -f aclocal.m4 ; then # $VERBOSE_ECHO ""Found an aclocal.m4 file, deleting it"" # $VERBOSE_ECHO ""rm -f aclocal.m4"" # rm -f aclocal.m4 # fi } # end of initialize() ############## # initialize # ############## # stash path START_PATH=""`pwd`"" # Before running autoreconf or manual steps, some prep detection work # is necessary or useful. Only needs to occur once per directory, but # does need to traverse the entire subconfigure hierarchy to protect # files from being clobbered even by autoreconf. recursive_protect # start from where we started cd ""$START_PATH"" # get ready to process initialize ######################################### # DOWNLOAD_GNULIB_CONFIG_GUESS FUNCTION # ######################################### # TODO - should make sure wget/curl exist and/or work before trying to # use them. download_gnulib_config_guess () { # abuse gitweb to download gnulib's latest config.guess via HTTP config_guess_temp=""config.guess.$$.download"" ret=1 for __cmd in wget curl fetch ; do $VERBOSE_ECHO ""Checking for command ${__cmd}"" ${__cmd} --version > /dev/null 2>&1 ret=$? if [ ! $ret = 0 ] ; then continue fi __cmd_version=`${__cmd} --version | head -n 1 | sed -e 's/^[^0-9]\+//' -e 's/ .*//'` $VERBOSE_ECHO ""Found ${__cmd} ${__cmd_version}"" opts="""" case ${__cmd} in wget) opts=""-O"" ;; curl) opts=""-o"" ;; fetch) opts=""-t 5 -f"" ;; esac $VERBOSE_ECHO ""Running $__cmd \""${CONFIG_GUESS_URL}\"" $opts \""${config_guess_temp}\"""" eval ""$__cmd \""${CONFIG_GUESS_URL}\"" $opts \""${config_guess_temp}\"""" > /dev/null 2>&1 if [ $? = 0 ] ; then mv -f ""${config_guess_temp}"" ${_aux_dir}/config.guess ret=0 break fi done if [ ! $ret = 0 ] ; then $ECHO ""Warning: config.guess download failed from: $CONFIG_GUESS_URL"" rm -f ""${config_guess_temp}"" fi } ############################## # LIBTOOLIZE_NEEDED FUNCTION # ############################## libtoolize_needed () { ret=1 # means no, don't need libtoolize for feature in AC_PROG_LIBTOOL AM_PROG_LIBTOOL LT_INIT ; do $VERBOSE_ECHO ""Searching for $feature in $CONFIGURE"" found=""`grep \""^$feature.*\"" $CONFIGURE`"" if [ ! ""x$found"" = ""x"" ] ; then ret=0 # means yes, need to run libtoolize break fi done return ${ret} } ############################################ # prepare build via autoreconf or manually # ############################################ reconfigure_manually=no if [ ""x$HAVE_AUTORECONF"" = ""xyes"" ] ; then $ECHO $ECHO $ECHO_N ""Automatically preparing build ... $ECHO_C"" $VERBOSE_ECHO ""$AUTORECONF $SEARCH_DIRS $AUTORECONF_OPTIONS"" autoreconf_output=""`$AUTORECONF $SEARCH_DIRS $AUTORECONF_OPTIONS 2>&1`"" ret=$? $VERBOSE_ECHO ""$autoreconf_output"" if [ ! $ret = 0 ] ; then if [ ""x$HAVE_ALT_LIBTOOLIZE"" = ""xyes"" ] ; then if [ ! ""x`echo \""$autoreconf_output\"" | grep libtoolize | grep \""No such file or directory\""`"" = ""x"" ] ; then $ECHO $ECHO ""Warning: autoreconf failed but due to what is usually a common libtool"" $ECHO ""misconfiguration issue. This problem is encountered on systems that"" $ECHO ""have installed libtoolize under a different name without providing a"" $ECHO ""symbolic link or without setting the LIBTOOLIZE environment variable."" $ECHO $ECHO ""Restarting the preparation steps with LIBTOOLIZE set to $LIBTOOLIZE"" export LIBTOOLIZE RUN_RECURSIVE=no export RUN_RECURSIVE untrap_abnormal $VERBOSE_ECHO sh $AUTOGEN_SH ""$1"" ""$2"" ""$3"" ""$4"" ""$5"" ""$6"" ""$7"" ""$8"" ""$9"" sh ""$AUTOGEN_SH"" ""$1"" ""$2"" ""$3"" ""$4"" ""$5"" ""$6"" ""$7"" ""$8"" ""$9"" exit $? fi fi $ECHO ""Warning: $AUTORECONF failed"" if test -f ltmain.sh ; then $ECHO ""libtoolize being run by autoreconf is not creating ltmain.sh in the auxillary directory like it should"" fi $ECHO ""Attempting to run the preparation steps individually"" reconfigure_manually=yes else if [ ""x$DOWNLOAD"" = ""xyes"" ] ; then if libtoolize_needed ; then download_gnulib_config_guess fi fi fi else reconfigure_manually=yes fi ############################ # LIBTOOL_FAILURE FUNCTION # ############################ libtool_failure ( ) { # libtool is rather error-prone in comparison to the other # autotools and this routine attempts to compensate for some # common failures. the output after a libtoolize failure is # parsed for an error related to AC_PROG_LIBTOOL and if found, we # attempt to inject a project-provided libtool.m4 file. _autoconf_output=""$1"" if [ ""x$RUN_RECURSIVE"" = ""xno"" ] ; then # we already tried the libtool.m4, don't try again return 1 fi if test -f ""$LIBTOOL_M4"" ; then found_libtool=""`$ECHO $_autoconf_output | grep AC_PROG_LIBTOOL`"" if test ! ""x$found_libtool"" = ""x"" ; then if test -f acinclude.m4 ; then rm -f acinclude.m4.$$.backup $VERBOSE_ECHO ""cat acinclude.m4 > acinclude.m4.$$.backup"" cat acinclude.m4 > acinclude.m4.$$.backup fi $VERBOSE_ECHO ""cat \""$LIBTOOL_M4\"" >> acinclude.m4"" chmod u+w acinclude.m4 cat ""$LIBTOOL_M4"" >> acinclude.m4 # don't keep doing this RUN_RECURSIVE=no export RUN_RECURSIVE untrap_abnormal $ECHO $ECHO ""Restarting the preparation steps with libtool macros in acinclude.m4"" $VERBOSE_ECHO sh $AUTOGEN_SH ""$1"" ""$2"" ""$3"" ""$4"" ""$5"" ""$6"" ""$7"" ""$8"" ""$9"" sh ""$AUTOGEN_SH"" ""$1"" ""$2"" ""$3"" ""$4"" ""$5"" ""$6"" ""$7"" ""$8"" ""$9"" exit $? fi fi } ########################### # MANUAL_AUTOGEN FUNCTION # ########################### manual_autogen ( ) { ################################################## # Manual preparation steps taken are as follows: # # aclocal [-I m4] # # libtoolize --automake -c -f # # aclocal [-I m4] # # autoconf -f # # autoheader # # automake -a -c -f # ################################################## ########### # aclocal # ########### $VERBOSE_ECHO ""$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS"" aclocal_output=""`$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS 2>&1`"" ret=$? $VERBOSE_ECHO ""$aclocal_output"" if [ ! $ret = 0 ] ; then $ECHO ""ERROR: $ACLOCAL failed"" && exit 2 ; fi ############## # libtoolize # ############## if libtoolize_needed ; then if [ ""x$HAVE_LIBTOOLIZE"" = ""xyes"" ] ; then $VERBOSE_ECHO ""$LIBTOOLIZE $LIBTOOLIZE_OPTIONS"" libtoolize_output=""`$LIBTOOLIZE $LIBTOOLIZE_OPTIONS 2>&1`"" ret=$? $VERBOSE_ECHO ""$libtoolize_output"" if [ ! $ret = 0 ] ; then $ECHO ""ERROR: $LIBTOOLIZE failed"" && exit 2 ; fi else if [ ""x$HAVE_ALT_LIBTOOLIZE"" = ""xyes"" ] ; then $VERBOSE_ECHO ""$LIBTOOLIZE $ALT_LIBTOOLIZE_OPTIONS"" libtoolize_output=""`$LIBTOOLIZE $ALT_LIBTOOLIZE_OPTIONS 2>&1`"" ret=$? $VERBOSE_ECHO ""$libtoolize_output"" if [ ! $ret = 0 ] ; then $ECHO ""ERROR: $LIBTOOLIZE failed"" && exit 2 ; fi fi fi ########### # aclocal # ########### # re-run again as instructed by libtoolize $VERBOSE_ECHO ""$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS"" aclocal_output=""`$ACLOCAL $SEARCH_DIRS $ACLOCAL_OPTIONS 2>&1`"" ret=$? $VERBOSE_ECHO ""$aclocal_output"" # libtoolize might put ltmain.sh in the wrong place if test -f ltmain.sh ; then if test ! -f ""${_aux_dir}/ltmain.sh"" ; then $ECHO $ECHO ""Warning: $LIBTOOLIZE is creating ltmain.sh in the wrong directory"" $ECHO $ECHO ""Fortunately, the problem can be worked around by simply copying the"" $ECHO ""file to the appropriate location (${_aux_dir}/). This has been done for you."" $ECHO $VERBOSE_ECHO ""cp -p ltmain.sh \""${_aux_dir}/ltmain.sh\"""" cp -p ltmain.sh ""${_aux_dir}/ltmain.sh"" $ECHO $ECHO_N ""Continuing build preparation ... $ECHO_C"" fi fi # ltmain.sh if [ ""x$DOWNLOAD"" = ""xyes"" ] ; then download_gnulib_config_guess fi fi # libtoolize_needed ############ # autoconf # ############ $VERBOSE_ECHO $VERBOSE_ECHO ""$AUTOCONF $AUTOCONF_OPTIONS"" autoconf_output=""`$AUTOCONF $AUTOCONF_OPTIONS 2>&1`"" ret=$? $VERBOSE_ECHO ""$autoconf_output"" if [ ! $ret = 0 ] ; then # retry without the -f and check for usage of macros that are too new ac2_65_macros=""AT_CHECK_EUNIT AC_PROG_OBJCXX AC_PROG_OBJCXXCPP"" ac2_64_macros=""AT_CHECK_UNQUOTED AT_FAIL_IF AT_SKIP_IF AC_ERLANG_SUBST_ERTS_VER"" ac2_62_macros=""AC_AUTOCONF_VERSION AC_OPENMP AC_PATH_PROGS_FEATURE_CHECK"" ac2_60_macros=""AC_C_FLEXIBLE_ARRAY_MEMBER AC_C_VARARRAYS"" ac2_59_macros=""AC_C_RESTRICT AC_INCLUDES_DEFAULT AC_LANG_ASSERT AC_LANG_WERROR AS_SET_CATFILE AC_PROG_SED AC_PROG_GREP AC_REQUIRE_AUX_FILE AC_CHECK_TARGET_TOOL AC_PATH_TARGET_TOOL AC_CHECK_TARGET_TOOLS AC_CHECK_ALIGNOF AC_PROG_OBJC AC_PROG_OBJCPP AC_ERLANG_SUBST_INSTALL_LIB_DIR AC_ERLANG_SUBST_INSTALL_LIB_SUBDIR AC_ERLANG_PATH_ERLC AC_ERLANG_NEED_ERLC AC_ERLANG_PATH_ERL AC_ERLANG_NEED_ERL AC_ERLANG_CHECK_LIB AC_ERLANG_SUBST_ROOT_DIR AC_ERLANG_SUBST_LIB_DIR AT_COPYRIGHT AS_BOURNE_COMPATIBLE AS_SHELL_SANITIZE AS_CASE AH_HEADER AC_USE_SYSTEM_EXTENSIONS AC_TYPE_INT8_T AC_TYPE_INT16_T AC_TYPE_INT32_T AC_TYPE_INT64_T AC_TYPE_INTMAX_T AC_TYPE_INTPTR_T AC_TYPE_LONG_LONG_INT AC_TYPE_SSIZE_T AC_TYPE_UINT8_T AC_TYPE_UINT16_T AC_TYPE_UINT32_T AC_TYPE_UINT64_T AC_TYPE_UINTMAX_T AC_TYPE_UINTPTR_T AC_TYPE_UNSIGNED_LONG_LONG_INT AC_TYPE_LONG_DOUBLE AC_TYPE_LONG_DOUBLE_WIDER AC_STRUCT_DIRENT_D_INO AC_STRUCT_DIRENT_D_TYPE AC_PROG_CC_C89 AC_PROG_CC_C99 AC_PRESERVE_HELP_ORDER AC_HEADER_ASSERT AC_FUNC_STRTOLD AC_C_TYPEOF AC_PROG_MKDIR_P AC_PROG_CXX_C_O"" ac2_55_macros=""AC_COMPILER_IFELSE AC_FUNC_MBRTOWC AC_HEADER_STDBOOL AC_LANG_CONFTEST AC_LANG_SOURCE AC_LANG_PROGRAM AC_LANG_CALL AC_LANG_FUNC_TRY_LINK AC_MSG_FAILURE AC_PREPROC_IFELSE"" ac2_54_macros=""AC_C_BACKSLASH_A AC_CONFIG_LIBOBJ_DIR AC_GNU_SOURCE AC_PROG_EGREP AC_PROG_FGREP AC_REPLACE_FNMATCH AC_FUNC_FNMATCH_GNU AC_FUNC_REALLOC AC_TYPE_MBSTATE_T"" macros_to_search="""" ac_major=""`echo ${AUTOCONF_VERSION}. | cut -d. -f1 | sed 's/[^0-9]//g'`"" ac_minor=""`echo ${AUTOCONF_VERSION}. | cut -d. -f2 | sed 's/[^0-9]//g'`"" if [ $ac_major -lt 2 ] ; then macros_to_search=""$ac2_65 $ac2_64 $ac2_62 $ac2_60 $ac2_59 $ac2_55 $ac2_54"" else if [ $ac_minor -lt 54 ] ; then macros_to_search=""$ac2_65 $ac2_64 $ac2_62 $ac2_60 $ac2_59 $ac2_55 $ac2_54"" elif [ $ac_minor -lt 55 ] ; then macros_to_search=""$ac2_65 $ac2_64 $ac2_62 $ac2_60 $ac2_59 $ac2_55"" elif [ $ac_minor -lt 59 ] ; then macros_to_search=""$ac2_65 $ac2_64 $ac2_62 $ac2_60 $ac2_59"" elif [ $ac_minor -lt 60 ] ; then macros_to_search=""$ac2_65 $ac2_64 $ac2_62 $ac2_60"" elif [ $ac_minor -lt 62 ] ; then macros_to_search=""$ac2_65 $ac2_64 $ac2_62"" elif [ $ac_minor -lt 64 ] ; then macros_to_search=""$ac2_65 $ac2_64"" elif [ $ac_minor -lt 65 ] ; then macros_to_search=""$ac2_65"" fi fi configure_ac_macros=__none__ for feature in $macros_to_search ; do $VERBOSE_ECHO ""Searching for $feature in $CONFIGURE"" found=""`grep \""^$feature.*\"" $CONFIGURE`"" if [ ! ""x$found"" = ""x"" ] ; then if [ ""x$configure_ac_macros"" = ""x__none__"" ] ; then configure_ac_macros=""$feature"" else configure_ac_macros=""$feature $configure_ac_macros"" fi fi done if [ ! ""x$configure_ac_macros"" = ""x__none__"" ] ; then $ECHO $ECHO ""Warning: Unsupported macros were found in $CONFIGURE"" $ECHO $ECHO ""The `basename \""$CONFIGURE\""` file was scanned in order to determine if any"" $ECHO ""unsupported macros are used that exceed the minimum version"" $ECHO ""settings specified within this file. As such, the following macros"" $ECHO ""should be removed from configure.ac or the version numbers in this"" $ECHO ""file should be increased:"" $ECHO $ECHO ""$configure_ac_macros"" $ECHO $ECHO $ECHO_N ""Ignorantly continuing build preparation ... $ECHO_C"" fi ################### # autoconf, retry # ################### $VERBOSE_ECHO $VERBOSE_ECHO ""$AUTOCONF"" autoconf_output=""`$AUTOCONF 2>&1`"" ret=$? $VERBOSE_ECHO ""$autoconf_output"" if [ ! $ret = 0 ] ; then # test if libtool is busted libtool_failure ""$autoconf_output"" # let the user know what went wrong cat <&1`"" ret=$? $VERBOSE_ECHO ""$autoheader_output"" if [ ! $ret = 0 ] ; then $ECHO ""ERROR: $AUTOHEADER failed"" && exit 2 ; fi fi # need_autoheader ############ # automake # ############ need_automake=no for feature in AM_INIT_AUTOMAKE ; do $VERBOSE_ECHO ""Searching for $feature in $CONFIGURE"" found=""`grep \""^$feature.*\"" $CONFIGURE`"" if [ ! ""x$found"" = ""x"" ] ; then need_automake=yes break fi done if [ ""x$need_automake"" = ""xyes"" ] ; then $VERBOSE_ECHO ""$AUTOMAKE $AUTOMAKE_OPTIONS"" automake_output=""`$AUTOMAKE $AUTOMAKE_OPTIONS 2>&1`"" ret=$? $VERBOSE_ECHO ""$automake_output"" if [ ! $ret = 0 ] ; then ################### # automake, retry # ################### $VERBOSE_ECHO $VERBOSE_ECHO ""$AUTOMAKE $ALT_AUTOMAKE_OPTIONS"" # retry without the -f automake_output=""`$AUTOMAKE $ALT_AUTOMAKE_OPTIONS 2>&1`"" ret=$? $VERBOSE_ECHO ""$automake_output"" if [ ! $ret = 0 ] ; then # test if libtool is busted libtool_failure ""$automake_output"" # let the user know what went wrong cat < ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License Version 3 as ** published by the Free Software Foundation. You may not use, modify or ** distribute this program under any other version of the GNU Lesser General ** Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // msutil: generic utility functions not dependent on any engine components. #include ""msutil.h"" #include #include #include // open O_RDONLY #include #include char const *errname[] = { /*_00*/ """", ""EPERM"", ""ENOENT"", ""ESRCH"", ""EINTR"", /*_05*/ ""EIO"", ""ENXIO"", ""E2BIG"", ""ENOEXEC"", ""EBADF"", /*_10*/ ""ECHILD"", ""EAGAIN"", ""ENOMEM"", ""EACCES"", ""EFAULT"", /*_15*/ ""ENOTBLK"", ""EBUSY"", ""EEXIST"", ""EXDEV"", ""ENODEV"", /*_20*/ ""ENOTDIR"", ""EISDIR"", ""EINVAL"", ""ENFILE"", ""EMFILE"", /*_25*/ ""ENOTTY"", ""ETXTBSY"", ""EFBIG"", ""ENOSPC"", ""ESPIPE"", /*_30*/ ""EROFS"", ""EMLINK"", ""EPIPE"", ""EDOM"", ""ERANGE"", #if defined(__FreeBSD__) /*_35*/ ""EDEADLK"", ""EINPROGRESS"", ""EALREADY"", ""ENOTSOCK"", ""EDESTADDRREQ"", /*_40*/ ""EMSGSIZE"", ""EPROTOTYPE"", ""ENOPROTOOPT"", ""EPROTONOSUPPORT"", ""ESOCKTNOSUPPORT"", /*_45*/ ""EOPNOTSUPP"", ""EPFNOSUPPORT"", ""EAFNOSUPPORT"", ""EADDRINUSE"", ""EADDRNOTAVAIL"", /*_50*/ ""ENETDOWN"", ""ENETUNREACH"", ""ENETRESET"", ""ECONNABORTED"", ""ECONNRESET"", /*_55*/ ""ENOBUFS"", ""EISCONN"", ""ENOTCONN"", ""ESHUTDOWN"", ""ETOOMANYREFS"", /*_60*/ ""ETIMEDOUT"", ""ECONNREFUSED"", ""ELOOP"", ""ENAMETOOLONG"", ""EHOSTDOWN"", /*_65*/ ""EHOSTUNREACH"", ""ENOTEMPTY"", ""EPROCLIM"", ""EUSERS"", ""EDQUOT"", /*_70*/ ""ESTALE"", ""EREMOTE"", ""EBADRPC"", ""ERPCMISMATCH"", ""EPROGUNAVAIL"", /*_75*/ ""EPROGMISMATCH"", ""EPROCUNAVAIL"", ""ENOLCK"", ""ENOSYS"", ""EFTYPE"", /*_80*/ ""EAUTH"", ""ENEEDAUTH"", ""EIDRM"", ""ENOMSG"", ""EOVERFLOW"", /*_85*/ ""ECANCELED"", ""EILSEQ"", ""ENOATTR"", ""EDOOFUS"", ""EBADMSG"", /*_90*/ ""EMULTIHOP"", ""ENOLINK"", ""EPROTO"" #elif defined(__linux__) /*_35*/ ""EDEADLK"", ""ENAMETOOLONG"", ""ENOLCK"", ""ENOSYS"", ""ENOTEMPTY"", /*_40*/ ""ELOOP"", ""E041"", ""ENOMSG"", ""EIDRM"", ""ECHRNG"", /*_45*/ ""EL2NSYNC"", ""EL3HLT"", ""EL3RST"", ""ELNRNG"", ""EUNATCH"", /*_50*/ ""ENOCSI"", ""EL2HLT"", ""EBADE"", ""EBADR"", ""EXFULL"", /*_55*/ ""ENOANO"", ""EBADRQC"", ""EBADSLT"", ""E058"", ""EBFONT"", /*_60*/ ""ENOSTR"", ""ENODATA"", ""ETIME"", ""ENOSR"", ""ENONET"", /*_65*/ ""ENOPKG"", ""EREMOTE"", ""ENOLINK"", ""EADV"", ""ESRMNT"", /*_70*/ ""ECOMM"", ""EPROTO"", ""EMULTIHOP"", ""EDOTDOT"", ""EBADMSG"", /*_75*/ ""EOVERFLOW"", ""ENOTUNIQ"", ""EBADFD"", ""EREMCHG"", ""ELIBACC"", /*_80*/ ""ELIBBAD"", ""ELIBSCN"", ""ELIBMAX"", ""ELIBEXEC"", ""EILSEQ"", /*_85*/ ""ERESTART"", ""ESTRPIPE"", ""EUSERS"", ""ENOTSOCK"", ""EDESTADDRREQ"", /*_90*/ ""EMSGSIZE"", ""EPROTOTYPE"", ""ENOPROTOOPT"", ""EPROTONOSUPPORT"", ""ESOCKTNOSUPPORT"", /*_95*/ ""EOPNOTSUPP"", ""EPFNOSUPPORT"", ""EAFNOSUPPORT"", ""EADDRINUSE"", ""EADDRNOTAVAIL"", /*100*/ ""ENETDOWN"", ""ENETUNREACH"", ""ENETRESET"", ""ECONNABORTED"", ""ECONNRESET"", /*105*/ ""ENOBUFS"", ""EISCONN"", ""ENOTCONN"", ""ESHUTDOWN"", ""ETOOMANYREFS"", /*110*/ ""ETIMEDOUT"", ""ECONNREFUSED"", ""EHOSTDOWN"", ""EHOSTUNREACH"", ""EALREADY"", /*115*/ ""EINPROGRESS"", ""ESTALE"", ""EUCLEAN"", ""ENOTNAM"", ""ENAVAIL"", /*120*/ ""EISNAM"", ""EREMOTEIO"", ""EDQUOT"", ""ENOMEDIUM"", ""EMEDIUMTYPE"", /*125*/ ""ECANCELED"", ""ENOKEY"", ""EKEYEXPIRED"", ""EKEYREVOKED"", ""EKEYREJECTED"", /*130*/ ""EOWNERDEAD"", ""ENOTRECOVERABLE"", ""ERFKILL"" #endif }; int const nerrnames = sizeof(errname)/sizeof(*errname); MEMBUF membuf(int size) { return size ? (MEMBUF){calloc(size+1, 1), size} : NILBUF; } void buffree(MEMBUF buf) { free(buf.ptr); } int nilbuf(MEMBUF buf) { return !buf.ptr; } int nilref(MEMREF const ref) { return !ref.len && !ref.ptr; } MEMREF memref(char const *mem, int len) { return mem && len ? (MEMREF){mem,len} : NILREF; } MEMREF bufref(MEMBUF const buf) { return (MEMREF) {buf.ptr, buf.len}; } MEMBUF chomp(MEMBUF buf) { if (buf.ptr) while (buf.len > 0 && isspace(buf.ptr[buf.len - 1])) buf.ptr[--buf.len] = 0; return buf; } void die(char const *fmt, ...) { va_list vargs; va_start(vargs, fmt); if (*fmt == ':') fputs(getprogname(), stderr); vfprintf(stderr, fmt, vargs); va_end(vargs); if (fmt[strlen(fmt)-1] == ':') fprintf(stderr, "" %s %s"", errname[errno], strerror(errno)); putc('\n', stderr); _exit(1); } #if defined(__linux__) char const * getprogname(void) { static char *progname; if (!progname) { char buf[999]; int len; sprintf(buf, ""/proc/%d/exe"", getpid()); len = readlink(buf, buf, sizeof(buf)); if (len < 0 || len == sizeof(buf)) return NULL; buf[len] = 0; char *cp = strrchr(buf, '/'); progname = strdup(cp ? cp + 1 : buf); } return progname; } #endif MEMREF * refsplit(char *text, char sep, int *pcount) { char *cp; int i, nstrs = 0; MEMREF *strv = NULL; if (*text) { for (cp = text, nstrs = 1; (cp = strchr(cp, sep)); ++cp) ++nstrs; strv = malloc(nstrs * sizeof(MEMREF)); for (i = 0, cp = text; (cp = strchr(strv[i].ptr = cp, sep)); ++i, ++cp) { strv[i].len = cp - strv[i].ptr; *cp = 0; } strv[i].len = strlen(strv[i].ptr); } if (pcount) *pcount = nstrs; return strv; } MEMBUF slurp(const char *filename) { MEMBUF ret = NILBUF; int fd = filename && *filename && strcmp(filename, ""-"") ? open(filename, O_RDONLY) : 0; struct stat s; if (fd < 0 || fstat(fd, &s)) goto ERROR; if (S_ISREG(s.st_mode)) { ret = membuf(s.st_size); if (ret.len != (unsigned)read(fd, ret.ptr, ret.len)) goto ERROR; } else { int len, size = 4096; ret.ptr = malloc(size + 1); for (;0 < (len = read(fd, ret.ptr+ret.len, size-ret.len)); ret.len += len) if (len == size - (int)ret.len) ret.ptr = realloc(ret.ptr, (size <<= 1) + 1); if (len < 0) goto ERROR; ret.ptr = realloc(ret.ptr, ret.len + 1); } close(fd); ret.ptr[ret.len] = 0; return ret; ERROR: if (fd >= 0) close(fd); buffree(ret); return NILBUF; } double tick(void) { struct timeval t; gettimeofday(&t, 0); return t.tv_sec + 1E-6 * t.tv_usec; } void usage(char const *str) { fprintf(stderr, ""Usage: %s %s\n"", getprogname(), str); _exit(2); } ","C" "CRISPR","ctSkennerton/crass","src/aho-corasick/acism_file.c",".c","2372","89","/* ** Copyright (C) 2009-2014 Mischa Sandberg ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License Version 3 as ** published by the Free Software Foundation. You may not use, modify or ** distribute this program under any other version of the GNU Lesser General ** Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include ""msutil.h"" #include ""_acism.h"" #include #include #include #include #ifndef MAP_NOCORE # define MAP_NOCORE 0 #endif void acism_save(FILE *fp, ACISM const*psp) { ACISM ps = *psp; // Overwrite pointers with magic signature. assert(8 <= sizeof ps.tranv + sizeof ps.hashv); memcpy(&ps, ""ACMischa"", 8); ps.flags &= ~IS_MMAP; fwrite(&ps, sizeof(ACISM), 1, fp); fwrite(psp->tranv, p_size(psp), 1, fp); } ACISM* acism_load(FILE *fp) { ACISM *psp = calloc(sizeof(ACISM), 1); if (fread(psp, sizeof(ACISM), 1, fp) == 1 && !memcmp(psp, ""ACMischa"", 8) && (set_tranv(psp, malloc(p_size(psp))), 1) && fread(psp->tranv, p_size(psp), 1, fp)) { return psp; } acism_destroy(psp); return NULL; } ACISM* acism_mmap(FILE *fp) { ACISM *mp = mmap(0, lseek(fileno(fp), 0L, 2), PROT_READ, MAP_SHARED|MAP_NOCORE, fileno(fp), 0); if (mp == MAP_FAILED) return NULL; ACISM *psp = malloc(sizeof*psp); *psp = *(ACISM*)mp; psp->flags |= IS_MMAP; if (memcmp(psp, ""ACMischa"", 8)) { acism_destroy(psp); return NULL; } set_tranv(psp, ((char *)mp) + sizeof(ACISM)); return psp; } void acism_destroy(ACISM *psp) { if (!psp) return; if (psp->flags & IS_MMAP) munmap((char*)psp->tranv - sizeof(ACISM), sizeof(ACISM) + p_size(psp)); else free(psp->tranv); free(psp); } //EOF ","C" "CRISPR","ctSkennerton/crass","src/aho-corasick/acism.c",".c","3524","108","/* ** Copyright (C) 2009-2014 Mischa Sandberg ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License Version 3 as ** published by the Free Software Foundation. You may not use, modify or ** distribute this program under any other version of the GNU Lesser General ** Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include ""_acism.h"" #define BACK ((SYMBOL)0) #define ROOT ((STATE) 0) int acism_more(ACISM const *psp, MEMREF const text, ACISM_ACTION *cb, void *context, int *statep) { ACISM const ps = *psp; char const *cp = text.ptr, *endp = cp + text.len; STATE state = *statep; int ret = 0; while (cp < endp) { _SYMBOL sym = ps.symv[(uint8_t)*cp++]; if (!sym) { // Input byte is not in any pattern string. state = ROOT; continue; } // Search for a valid transition from this (state, sym), // following the backref chain. TRAN next; while (!t_valid(&ps, next = p_tran(&ps, state, sym)) && state != ROOT) { TRAN back = p_tran(&ps, state, BACK); state = t_valid(&ps, back) ? t_next(&ps, back) : ROOT; } if (!t_valid(&ps, next)) continue; if (!(next & (IS_MATCH | IS_SUFFIX))) { // No complete match yet; keep going. state = t_next(&ps, next); continue; } // At this point, one or more patterns have matched. // Find all matches by following the backref chain. // A valid node for (sym) with no SUFFIX flag marks the // end of the suffix chain. // In the same backref traversal, find a new (state), // if the original transition is to a leaf. STATE s = state; // Initially state is ROOT. The chain search saves the // first state from which the next char has a transition. state = t_isleaf(&ps, next) ? 0 : t_next(&ps, next); while (1) { if (t_valid(&ps, next)) { if (next & IS_MATCH) { unsigned strno, ss = s + sym, i; if (t_isleaf(&ps, ps.tranv[ss])) { strno = t_strno(&ps, ps.tranv[ss]); } else { for (i = p_hash(&ps, ss); ps.hashv[i].state != ss; ++i); strno = ps.hashv[i].strno; } if ((ret = cb(strno, cp - text.ptr, context))) goto EXIT; } if (!state && !t_isleaf(&ps, next)) state = t_next(&ps, next); if ( state && !(next & IS_SUFFIX)) break; } if (s == ROOT) break; TRAN b = p_tran(&ps, s, BACK); s = t_valid(&ps, b) ? t_next(&ps, b) : ROOT; next = p_tran(&ps, s, sym); } } EXIT: return *statep = state, ret; } //EOF ","C" "CRISPR","ctSkennerton/crass","src/aho-corasick/acism.h",".h","2555","74","/* ** Copyright (C) 2009-2014 Mischa Sandberg ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License as ** published by the Free Software Foundation. You may not use, modify or ** distribute this program under any other version of the GNU Lesser General ** Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef ACISM_H #define ACISM_H // ""acism"" uses MEMREF {ptr,len} bytevec structs for ""string"" args, // rather than NUL-terminated ""C"" strings. #ifndef MSUTIL_H #include typedef struct { char const *ptr; size_t len; } MEMREF; #endif typedef struct acism ACISM; ACISM* acism_create(MEMREF const *strv, int nstrs); void acism_destroy(ACISM*); // For each match, acism_scan calls its ACISM_ACTION fn, // giving it the strv[] index of the matched string, // and the text[] offset of the byte PAST the end of the string. // If ACISM_ACTION returns 0, search continues; otherwise, // acism_more returns that nonzero value immediately. typedef int (ACISM_ACTION)(int strnum, int textpos, void *context); // If sequential blocks of (text) are passed to repeated acism_more calls, // then search continues where the previous acism_more left off -- // string matches can cross block boundaries. // *state should initially be (0). int acism_more(ACISM const*, MEMREF const text, ACISM_ACTION *fn, void *fndata, int *state); static inline int acism_scan(ACISM const*psp, MEMREF const text, ACISM_ACTION *fn, void *fndata) { int state = 0; return acism_more(psp, text, fn, fndata, &state); } void acism_save(FILE*, ACISM const*); ACISM* acism_load(FILE*); ACISM* acism_mmap(FILE*); // diagnostics typedef enum { PS_STATS=1, PS_TRAN=2, PS_HASH=4, PS_TREE=8, PS_ALL=-1 } PS_DUMP_TYPE; // If (pattv) is not NULL, dump output includes strings. void acism_dump(ACISM const*, PS_DUMP_TYPE, FILE*, MEMREF const*pattv); #define ACISM_STATS 1 // Collect perf stats during acism_create (see acism_dump). #endif//ACISM_H ","Unknown" "CRISPR","ctSkennerton/crass","src/aho-corasick/acism_create.c",".c","12260","397","/* ** Copyright (C) 2009-2014 Mischa Sandberg ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License Version 3 as ** published by the Free Software Foundation. You may not use, modify or ** distribute this program under any other version of the GNU Lesser General ** Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include ""_acism.h"" typedef struct tnode { struct tnode *child, *next, *back; union { unsigned nrefs; STATE state; } x; STRNO match; SYMBOL sym, is_suffix; } TNODE; //--------------|--------------------------------------------- // bitwid: 1+floor(log2(u)) static inline int bitwid(unsigned u) { int ret = !!u; if (u & 0xFFFF0000) u >>= 16, ret += 16; if (u & 0x0000FF00) u >>= 8, ret += 8; if (u & 0x000000F0) u >>= 4, ret += 4; if (u & 0x0000000C) u >>= 2, ret += 2; if (u & 0x00000002) ret++; return ret; } static void fill_symv(ACISM*, MEMREF const*, int ns); static int create_tree(TNODE*, SYMBOL const*symv, MEMREF const*strv, int nstrs); static void add_backlinks(TNODE*, TNODE**, TNODE**); static void prune_backlinks(TNODE*); static int interleave(TNODE*, int nnodes, int nsyms, TNODE**, TNODE**); static void fill_tranv(ACISM*, TNODE const*); static void fill_hashv(ACISM*, TNODE const*, int nn); static TNODE* find_child(TNODE*, SYMBOL); // (ns) is either a STATE, or a (STRNO + tran_size) static inline void set_tran(ACISM *psp, STATE s, SYMBOL sym, int match, int suffix, TRAN ns) { psp->tranv[s + sym] = sym | (match ? IS_MATCH : 0) | (suffix ? IS_SUFFIX : 0) | (ns << SYM_BITS); } // Track statistics for construction #ifdef ACISM_STATS typedef struct { long long val; const char *name; } PSSTAT; extern PSSTAT psstat[]; # define NOTE(n) (psstat[__LINE__] = (PSSTAT) {n, #n}) # define HIT(id) (psstat[__LINE__].val++, psstat[__LINE__].name = id) #else # define NOTE(n) (void)0 # define HIT(id) (void)0 #endif //ACISM_STATS //--------------|--------------------------------------------- ACISM* acism_create(MEMREF const* strv, int nstrs) { TNODE *tp, **v1 = NULL, **v2 = NULL; ACISM *psp = calloc(1, sizeof*psp); fill_symv(psp, strv, nstrs); TNODE *troot = calloc(psp->nchars + 1, sizeof*troot); int nnodes = create_tree(troot, psp->symv, strv, nstrs); NOTE(nnodes); // v1, v2: breadth-first work vectors for add_backlink and interleave. int nhash, i = (nstrs + 1) * sizeof*tp; add_backlinks(troot, v1 = malloc(i), v2 = malloc(i)); for (tp = troot + nnodes, nhash = 0; --tp > troot;) { prune_backlinks(tp); nhash += tp->match && tp->child; } // Calculate each node's offset in tranv[]: psp->tran_size = interleave(troot, nnodes, psp->nsyms, v1, v2); if (bitwid(psp->tran_size + nstrs - 1) + SYM_BITS > sizeof(TRAN)*8 - 2) goto FAIL; if (nhash) { // Hash table is for match info of non-leaf nodes (only). // Set hash_size for p_size(psp): psp->hash_mod = nhash * 5 / 4 + 1; // Initially oversize the table for overflows without wraparound. psp->hash_size = psp->hash_mod + nhash; } set_tranv(psp, calloc(p_size(psp), 1)); if (!psp->tranv) goto FAIL; fill_tranv(psp, troot); // The root state (0) must not look like a valid backref. // Any symbol value other than (0) in tranv[0] ensures that. psp->tranv[0] = 1; if (nhash) { fill_hashv(psp, troot, nnodes); // Adjust hash_size to include trailing overflows // but trim trailing empty slots. psp->hash_size = psp->hash_mod; while ( psp->hashv[psp->hash_size].state) ++psp->hash_size; while (!psp->hashv[psp->hash_size - 1].state) --psp->hash_size; set_tranv(psp, realloc(psp->tranv, p_size(psp))); } // Diagnostics/statistics only: psp->nstrs = nstrs; for (i = psp->maxlen = 0; i < nstrs; ++i) if (psp->maxlen < strv[i].len) psp->maxlen = strv[i].len; goto DONE; FAIL: acism_destroy(psp), psp = NULL; DONE: free(troot), free(v1), free(v2); return psp; } typedef struct { int freq, rank; } FRANK; static int frcmp(FRANK*a, FRANK*b) { return a->freq - b->freq; } static void fill_symv(ACISM *psp, MEMREF const *strv, int nstrs) { int i, j; FRANK frv[256]; for (i = 0; i < 256; ++i) frv[i] = (FRANK){0,i}; for (i = 0; i < nstrs; ++i) for (psp->nchars += j = strv[i].len; --j >= 0;) frv[(uint8_t)strv[i].ptr[j]].freq++; qsort(frv, 256, sizeof*frv, (qsort_cmp)frcmp); for (i = 256; --i >= 0 && frv[i].freq;) psp->symv[frv[i].rank] = ++psp->nsyms; ++psp->nsyms; #if ACISM_SIZE < 8 psp->sym_bits = bitwid(psp->nsyms); psp->sym_mask = ~(-1 << psp->sym_bits); #endif } static int create_tree(TNODE *Tree, SYMBOL const *symv, MEMREF const *strv, int nstrs) { int i, j; TNODE *nextp = Tree + 1; for (i = 0; i < nstrs; ++i) { TNODE *tp = Tree; for (j = 0; tp->child && j < (int)strv[i].len; ++j) { SYMBOL sym = symv[(uint8_t)strv[i].ptr[j]]; if (sym < tp->child->sym) { // Prep to insert new node before tp->child nextp->next = tp->child; break; } tp = tp->child; while (tp->next && sym >= tp->next->sym) tp = tp->next; // Insert new sibling after tp if (sym > tp->sym) { nextp->next = tp->next; tp = tp->next = nextp++; tp->sym = sym; tp->back = Tree; } } for (; j < (int) strv[i].len; ++j) { tp = tp->child = nextp++; tp->sym = symv[(uint8_t)strv[i].ptr[j]]; tp->back = Tree; } tp->match = i + 1; // Encode strno as nonzero } return nextp - Tree; } static void add_backlinks(TNODE *troot, TNODE **v1, TNODE **v2) { TNODE *tp, **tmp; for (tp = troot->child, tmp = v1; tp; tp = tp->next) *tmp++ = tp; *tmp = NULL; while (*v1) { TNODE **spp = v1, **dpp = v2, *srcp, *dstp; while ((srcp = *spp++)) { for (dstp = srcp->child; dstp; dstp = dstp->next) { TNODE *bp = NULL; *dpp++ = dstp; for (tp = srcp->back; tp; tp = tp->back) if ((bp = find_child(tp, dstp->sym))) break; if (!bp) bp = troot; dstp->back = dstp->child ? bp : tp ? tp : troot; dstp->back->x.nrefs++; dstp->is_suffix = bp->match || bp->is_suffix; } } *dpp = 0; tmp = v1; v1 = v2; v2 = tmp; } } static void prune_backlinks(TNODE *tp) { if (tp->x.nrefs || !tp->child) return; TNODE *bp; // (bp != bp->back IFF bp != troot) while ((bp = tp->back) && !bp->match && bp != bp->back) { HIT(""backlinks""); TNODE *cp = tp->child, *pp = bp->child; // Search for a child of bp that's not a child of tp for (; cp && pp && pp->sym >= cp->sym; cp = cp->next) { if (pp->sym == cp->sym) { if (pp->match && cp->is_suffix) break; pp = pp->next; } } if (pp) break; // So, target of back link is not a suffix match // of this node, and its children are a subset // of this node's children: prune it. HIT(""pruned""); if ((tp->back = bp->back)) { tp->back->x.nrefs++; if (!--bp->x.nrefs) prune_backlinks(bp); } } } static int interleave(TNODE *troot, int nnodes, int nsyms, TNODE **v1, TNODE **v2) { unsigned usev_size = nnodes + nsyms; char *usev = calloc(usev_size, sizeof*usev); STATE last_trans = 0, startv[nsyms][2]; TNODE *cp, **tmp; memset(startv, 0, nsyms * sizeof*startv); // Iterate through one level of the Tree at a time. // That srsly improves locality (L1-cache use). v1[0] = troot, v1[1] = NULL; for (; *v1; tmp = v1, v1 = v2, v2 = tmp) { TNODE **srcp = v1, **dstp = v2, *tp; while ((tp = *srcp++)) { if (!tp->child) continue; HIT(""nonleaf""); if (tp->back == troot) tp->back = NULL; // simplify tests. cp = tp->child; STATE pos, *startp = &startv[cp->sym][!!tp->back]; while ((cp = cp->next)) { STATE *newp = &startv[cp->sym][!!tp->back]; if (*startp < *newp) startp = newp; } // If (tp) has a backref, we need a slot at offset 0 // that is free as a base AND to be used (filled in). char need = tp->back ? BASE|USED : BASE; for (pos = *startp;; ++pos) { if (usev[pos] & need) { HIT(""inner loop""); continue; } for (cp = tp->child; cp; cp = cp->next) { HIT(""child loop""); if (usev[pos + cp->sym] & USED) break; } // No child needs an in-use slot? We're done. if (!cp) break; } tp->x.state = pos; // Mark node's base and children as used: usev[pos] |= need; STATE last = 0; // Make compiler happy int nkids = 0; for (cp = tp->child; cp; *dstp++ = cp, cp = cp->next, ++nkids) usev[last = pos + cp->sym] |= USED; // This is a HEURISTIC for advancing search for other nodes *startp += (pos - *startp) / nkids; if (last_trans < last) { last_trans = last; if (last + nsyms >= usev_size) { usev = realloc(usev, usev_size << 1); memset(usev + usev_size, 0, usev_size); usev_size <<= 1; } } } *dstp = NULL; } free(usev); return last_trans + 1; } static void fill_hashv(ACISM *psp, TNODE const treev[], int nnodes) { STRASH *sv = malloc(psp->hash_mod * sizeof*sv), *sp = sv; int i; // First pass: insert without resolving collisions. for (i = 0; i < nnodes; ++i) { STATE base = treev[i].x.state; TNODE const *tp; for (tp = treev[i].child; tp; tp = tp->next) { if (tp->match && tp->child) { STATE state = base + tp->sym; STRASH *hp = &psp->hashv[p_hash(psp, state)]; *(hp->state ? sp++ : hp) = (STRASH){state, tp->match - 1}; } } } while (--sp >= sv) { HIT(""hash collisions""); for (i = p_hash(psp, sp->state); psp->hashv[i].state; ++i) HIT(""hash displacements""); psp->hashv[i] = *sp; } free(sv); } static void fill_tranv(ACISM *psp, TNODE const*tp) { TNODE const *cp = tp->child; if (cp && tp->back) set_tran(psp, tp->x.state, 0, 0, 0, tp->back->x.state); for (; cp; cp = cp->next) { //NOTE: cp->match is (strno+1) so that !cp->match means ""no match"". set_tran(psp, tp->x.state, cp->sym, cp->match, cp->is_suffix, cp->child ? cp->x.state : cp->match - 1 + psp->tran_size); if (cp->child) fill_tranv(psp, cp); } } static TNODE * find_child(TNODE *tp, SYMBOL sym) { for (tp = tp->child; tp && tp->sym < sym; tp = tp->next); return tp && tp->sym == sym ? tp : NULL; } #ifdef ACISM_STATS PSSTAT psstat[__LINE__] = {{__LINE__,0}}; #endif//ACISM_STATS //EOF ","C" "CRISPR","ctSkennerton/crass","src/aho-corasick/_acism.h",".h","3558","121","/* ** Copyright (C) 2009-2014 Mischa Sandberg ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License Version 3 as ** published by the Free Software Foundation. You may not use, modify or ** distribute this program under any other version of the GNU Lesser General ** Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #ifndef _ACISM_H #define _ACISM_H #include #include // malloc #include // memcpy typedef int (*qsort_cmp)(const void *, const void *); // ""Width"" specifier for different plats #if __LONG_MAX__ == 9223372036854775807LL # ifdef __APPLE__ # define F64 ""ll"" # else # define F64 ""l"" # endif #elif __LONG_MAX__ == 2147483647L || defined(_LONG_LONG) || defined(__sun) // AIX 6.1 ... # define F64 ""ll"" #else # error need to define F64 #endif #ifndef ACISM_SIZE # define ACISM_SIZE 4 #endif #if ACISM_SIZE == 8 typedef uint64_t TRAN, STATE, STRNO; # define SYM_BITS 9U # define SYM_MASK 511 # define FNO F64 #else typedef uint32_t TRAN, STATE, STRNO; # define SYM_BITS psp->sym_bits # define SYM_MASK psp->sym_mask # define FNO #endif typedef uint16_t SYMBOL; typedef unsigned _SYMBOL; // An efficient stacklocal SYMBOL enum { IS_MATCH = (TRAN)1 << (8*sizeof(TRAN) - 1), IS_SUFFIX = (TRAN)1 << (8*sizeof(TRAN) - 2), T_FLAGS = IS_MATCH | IS_SUFFIX }; typedef struct { STATE state; STRNO strno; } STRASH; typedef enum { BASE=2, USED=1 } USES; struct acism { TRAN* tranv; STRASH* hashv; unsigned flags; # define IS_MMAP 1 #if ACISM_SIZE < 8 TRAN sym_mask; unsigned sym_bits; #endif unsigned hash_mod; // search hashv starting at (state + sym) % hash_mod. unsigned hash_size; // #(hashv): hash_mod plus the overflows past [hash_mod-1] unsigned tran_size; // #(tranv) unsigned nsyms, nchars, nstrs, maxlen; SYMBOL symv[256]; }; #include ""acism.h"" // p_size: size of tranv + hashv static inline unsigned p_size(ACISM const *psp) { return psp->hash_size * sizeof*psp->hashv + psp->tran_size * sizeof*psp->tranv; } static inline unsigned p_hash(ACISM const *psp, STATE s) { return s * 107 % psp->hash_mod; } static inline void set_tranv(ACISM *psp, void *mem) { psp->hashv = (STRASH*)&(psp->tranv = mem)[psp->tran_size]; } // TRAN accessors. For ACISM_SIZE=8, SYM_{BITS,MASK} do not use psp. static inline TRAN p_tran(ACISM const *psp, STATE s, _SYMBOL sym) { return psp->tranv[s + sym] ^ sym; } static inline _SYMBOL t_sym(ACISM const *psp, TRAN t) { (void)psp; return t & SYM_MASK; } static inline STATE t_next(ACISM const *psp, TRAN t) { (void)psp; return (t & ~T_FLAGS) >> SYM_BITS; } static inline int t_isleaf(ACISM const *psp, TRAN t) { return t_next(psp, t) >= psp->tran_size; } static inline int t_strno(ACISM const *psp, TRAN t) { return t_next(psp, t) - psp->tran_size; } static inline _SYMBOL t_valid(ACISM const *psp, TRAN t) { return !t_sym(psp, t); } #endif//_ACISM_H ","Unknown" "CRISPR","ctSkennerton/crass","src/aho-corasick/acism_dump.c",".c","5409","169","/* ** Copyright (C) 2009-2014 Mischa Sandberg ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License Version 3 as ** published by the Free Software Foundation. You may not use, modify or ** distribute this program under any other version of the GNU Lesser General ** Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include #include #include ""_acism.h"" #if ACISM_SIZE == 4 # define FX """" #elif __LONG_MAX__ < 9223372036854775807 # define FX ""ll"" #else # define FX ""l"" #endif static void printrans(ACISM const*,TRAN,const char*,FILE*,MEMREF const*); static void printree(ACISM const* psp, int state, int depth, char* str, const char* charv, FILE* out, MEMREF const* pattv); #define PSTR(_psp,_i,_pattv) _i, \ _pattv ? (int)_pattv[_i].len : 0, \ _pattv ? _pattv[_i].ptr : """" //--------------|--------------------------------------------- void acism_dump(ACISM const* psp, PS_DUMP_TYPE pdt, FILE *out, MEMREF const*pattv) { int i, empty; char charv[256]; int symdist[257] = {}; for (i = 256; --i >=0;) charv[psp->symv[i]] = i; if (pdt & PS_STATS) { for (i = psp->tran_size, empty = 0; --i >= 0;) { if (psp->tranv[i]) { ++symdist[t_sym(psp, psp->tranv[i])]; } else ++empty; } fprintf(out, ""strs:%d syms:%d chars:%d "" ""trans:%d empty:%d mod:%d hash:%d size:%lu\n"", psp->nstrs, psp->nsyms, psp->nchars, psp->tran_size, empty, psp->hash_mod, psp->hash_size, (long)sizeof(ACISM) + p_size(psp)); } if (pdt & PS_TRAN) { fprintf(out, ""==== TRAN:\n%8s %8s Ch MS %8s\n"", ""Cell"", ""State"", ""Next""); for (i = 1; i < (int)psp->tran_size; ++i) { fprintf(out, ""%8d %8d "", i, i - t_sym(psp, psp->tranv[i])); printrans(psp, i, charv, out, pattv); } } if (pdt & PS_HASH) { fprintf(out, ""==== HASH:\n.....: state strno\n""); for (i = 0; i < (int)psp->hash_size; ++i) { STATE state = psp->hashv[i].state; if (state) fprintf(out, ""%5d: %7""FX""u %3d %8""FX""u %.*s\n"", i, state, i - p_hash(psp, state), PSTR(psp, psp->hashv[i].strno, pattv)); else fprintf(out, ""%5d: %7""FX""d --- %8""FX""d\n"", i, state, psp->hashv[i].strno); } } if (pdt & PS_TREE) { fprintf(out, ""==== TREE:\n""); char str[psp->maxlen + 1]; printree(psp, 0, 0, str, charv, out, pattv); } //TODO: calculate stats: backref chain lengths ... } static void printrans(ACISM const*psp, STATE s, char const *charv, FILE *out, MEMREF const *pattv) { (void)pattv; TRAN x = psp->tranv[s]; if (!x) { fprintf(out, ""(empty)\n""); return; } SYMBOL sym = t_sym(psp,x); char c = charv[sym]; if (sym) fprintf(out, ""--""); else fprintf(out, ""%02X "", c); putc(""M-""[!(x & IS_MATCH)], out); putc(""S-""[!(x & IS_SUFFIX)], out); STATE next = t_next(psp, x); if (t_isleaf(psp, x)) { fprintf(out, "" => %d\n"", t_strno(psp, x)); } else { fprintf(out, "" %7""FX""d"", next); if (x & IS_MATCH) { int i; for (i = p_hash(psp, s); psp->hashv[i].state != s; ++i); fprintf(out, "" #> %""FX""d"", psp->hashv[i].strno); } putc('\n', out); } } static void printree(ACISM const*psp, int state, int depth, char *str, char const *charv, FILE*out, MEMREF const*pattv) { SYMBOL sym; TRAN x; if (depth > (int)psp->maxlen) { fputs(""oops\n"", out); return; } x = psp->tranv[state]; fprintf(out, ""%5d:%.*s"", state, depth, str); if (t_valid(psp,x) && t_next(psp,x)) fprintf(out, "" b=%""FX""d%s"", t_next(psp,x), x & T_FLAGS ? "" BAD"" : """"); fprintf(out, ""\n""); for (sym = 1; sym < psp->nsyms; ++sym) { x = p_tran(psp, state, sym); if (t_valid(psp, x)) { str[depth] = charv[sym]; fprintf(out, ""%*s%c %c%c"", depth+6, """", charv[sym], x & IS_MATCH ? 'M' : '-', x & IS_SUFFIX ? 'S' : '-'); if (x & IS_MATCH && pattv && t_isleaf(psp, x)) fprintf(out, "" %.0d -> %.*s"", PSTR(psp, t_strno(psp,x), pattv)); if (x & IS_SUFFIX) fprintf(out, "" ->S %""FX""d"", t_next(psp, psp->tranv[state])); fprintf(out, ""\n""); if (!t_isleaf(psp, x)) printree(psp, t_next(psp, x), depth+1, str, charv, out, pattv); } } } //EOF ","C" "CRISPR","ctSkennerton/crass","src/aho-corasick/msutil.h",".h","3737","91","/* ** Copyright (C) 2009-2014 Mischa Sandberg ** ** This program is free software; you can redistribute it and/or modify ** it under the terms of the GNU Lesser General Public License Version 3 as ** published by the Free Software Foundation. You may not use, modify or ** distribute this program under any other version of the GNU Lesser General ** Public License. ** ** This program is distributed in the hope that it will be useful, ** but WITHOUT ANY WARRANTY; without even the implied warranty of ** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the ** GNU Lesser General Public License for more details. ** ** You should have received a copy of the GNU Lesser General Public License ** along with this program; if not, write to the Free Software ** Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ // msutil: convenience functions. // MEM: manipulating byte-blocks and slices thereaof. // ""MEMBUF"" is a descriptor of a malloc'd block of memory. // The owner of the MEMBUF variable also ""owns"" the memory. // ""MEMREF"" is a descriptor of memory allocated elsewhere. // A MEMREF can describe a substring of a MEMBUF value. // membuf(size) Create membuf; membuf(0) => NILBUF // buffree(buf) // memref(char const*mem, int len) Create memref from (ptr,len) // nilbuf(buf) Test if buf is a NILBUF // nilref(ref) Test if ref is a NILREF // bufref(buf) Create MEMREF from a MEMBUF; NILBUF => NILREF // // chomp(buf) - Remove trailing >>WHITESPACE<< from a MEMBUF. // chomp(NILBUF) = NILBUF. // die(fmt, ...) - Print message to stderr and exit(1). // If fmt begins with "":"", die prepends program name. // If fmt ends in "":"", die appends strerror(errno). // errname[nerrnames] - (string) names for errno values. More succinct than strerror(). // getprogname() - Returns pointer to the program name (basename). // refsplit(s,sep,&cnt) - split text. Replaces every (sep) with \0 in (text). // Returns malloc'd vector of [cnt] MEMREF's. // slurp(fname) - create membuf from a file. fname ""-"" or NULL reads stdin. // tick() - High-precision timer returns secs as a (double). // usage() - generic print program name, usage; then exit(2) //--------------|--------------------------------------------- #ifndef MSUTIL_H #define MSUTIL_H #include // Defeat gcc 4.4 cdefs.h defining __wur i.e. __attribute((unused-result)) // for system calls where you just don't care (e.g. vasprintf...) // This must follow ""#include "" and precede everything else. #undef __wur #define __wur #include #include #include #include #include #include typedef struct { char *ptr; size_t len; } MEMBUF; typedef struct { char const *ptr; size_t len; } MEMREF; #define NILBUF (MEMBUF){NULL,0} #define NILREF (MEMREF){NULL,0} void buffree(MEMBUF buf); MEMREF bufref(MEMBUF const buf); MEMBUF chomp(MEMBUF buf); void die(char const *fmt, ...); MEMBUF membuf(int size); MEMREF memref(char const *mem, int len); int nilbuf(MEMBUF buf); int nilref(MEMREF const ref); MEMREF* refsplit(char *text, char sep, int *pnrefs); MEMBUF slurp(char const *filename); double tick(void); void usage(char const *); #if defined(__linux__) char const *getprogname(void); // BSD-equivalent #endif extern int const nerrnames; extern char const *errname[]; #endif//MSUTIL_H ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/ksw.c",".c","16949","488","/* The MIT License Copyright (c) 2011 by Attractive Chaos Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ #include #include #include #include ""ksw.h"" #ifdef __GNUC__ #define LIKELY(x) __builtin_expect((x),1) #define UNLIKELY(x) __builtin_expect((x),0) #else #define LIKELY(x) (x) #define UNLIKELY(x) (x) #endif const kswr_t g_defr = { 0, -1, -1, -1, -1, -1, -1 }; struct _kswq_t { int qlen, slen; uint8_t shift, mdiff, max, size; __m128i *qp, *H0, *H1, *E, *Hmax; }; /** * Initialize the query data structure * * @param size Number of bytes used to store a score; valid valures are 1 or 2 * @param qlen Length of the query sequence * @param query Query sequence * @param m Size of the alphabet * @param mat Scoring matrix in a one-dimension array * * @return Query data structure */ kswq_t *ksw_qinit(int size, int qlen, const uint8_t *query, int m, const int8_t *mat) { kswq_t *q; int slen, a, tmp, p; size = size > 1? 2 : 1; p = 8 * (3 - size); // # values per __m128i slen = (qlen + p - 1) / p; // segmented length q = (kswq_t*)malloc(sizeof(kswq_t) + 256 + 16 * slen * (m + 4)); // a single block of memory q->qp = (__m128i*)(((size_t)q + sizeof(kswq_t) + 15) >> 4 << 4); // align memory q->H0 = q->qp + slen * m; q->H1 = q->H0 + slen; q->E = q->H1 + slen; q->Hmax = q->E + slen; q->slen = slen; q->qlen = qlen; q->size = size; // compute shift tmp = m * m; for (a = 0, q->shift = 127, q->mdiff = 0; a < tmp; ++a) { // find the minimum and maximum score if (mat[a] < (int8_t)q->shift) q->shift = mat[a]; if (mat[a] > (int8_t)q->mdiff) q->mdiff = mat[a]; } q->max = q->mdiff; q->shift = 256 - q->shift; // NB: q->shift is uint8_t q->mdiff += q->shift; // this is the difference between the min and max scores // An example: p=8, qlen=19, slen=3 and segmentation: // {{0,3,6,9,12,15,18,-1},{1,4,7,10,13,16,-1,-1},{2,5,8,11,14,17,-1,-1}} if (size == 1) { int8_t *t = (int8_t*)q->qp; for (a = 0; a < m; ++a) { int i, k, nlen = slen * p; const int8_t *ma = mat + a * m; for (i = 0; i < slen; ++i) for (k = i; k < nlen; k += slen) // p iterations *t++ = (k >= qlen? 0 : ma[query[k]]) + q->shift; } } else { int16_t *t = (int16_t*)q->qp; for (a = 0; a < m; ++a) { int i, k, nlen = slen * p; const int8_t *ma = mat + a * m; for (i = 0; i < slen; ++i) for (k = i; k < nlen; k += slen) // p iterations *t++ = (k >= qlen? 0 : ma[query[k]]); } } return q; } kswr_t ksw_u8(kswq_t *q, int tlen, const uint8_t *target, int _gapo, int _gape, int xtra) // the first gap costs -(_o+_e) { int slen, i, m_b, n_b, te = -1, gmax = 0, minsc, endsc; uint64_t *b; __m128i zero, gapoe, gape, shift, *H0, *H1, *E, *Hmax; kswr_t r; #define __max_16(ret, xx) do { \ (xx) = _mm_max_epu8((xx), _mm_srli_si128((xx), 8)); \ (xx) = _mm_max_epu8((xx), _mm_srli_si128((xx), 4)); \ (xx) = _mm_max_epu8((xx), _mm_srli_si128((xx), 2)); \ (xx) = _mm_max_epu8((xx), _mm_srli_si128((xx), 1)); \ (ret) = _mm_extract_epi16((xx), 0) & 0x00ff; \ } while (0) // initialization r = g_defr; minsc = (xtra&KSW_XSUBO)? xtra&0xffff : 0x10000; endsc = (xtra&KSW_XSTOP)? xtra&0xffff : 0x10000; m_b = n_b = 0; b = 0; zero = _mm_set1_epi32(0); gapoe = _mm_set1_epi8(_gapo + _gape); gape = _mm_set1_epi8(_gape); shift = _mm_set1_epi8(q->shift); H0 = q->H0; H1 = q->H1; E = q->E; Hmax = q->Hmax; slen = q->slen; for (i = 0; i < slen; ++i) { _mm_store_si128(E + i, zero); _mm_store_si128(H0 + i, zero); _mm_store_si128(Hmax + i, zero); } // the core loop for (i = 0; i < tlen; ++i) { int j, k, cmp, imax; __m128i e, h, f = zero, max = zero, *S = q->qp + target[i] * slen; // s is the 1st score vector h = _mm_load_si128(H0 + slen - 1); // h={2,5,8,11,14,17,-1,-1} in the above example h = _mm_slli_si128(h, 1); // h=H(i-1,-1); << instead of >> because x64 is little-endian for (j = 0; LIKELY(j < slen); ++j) { /* SW cells are computed in the following order: * H(i,j) = max{H(i-1,j-1)+S(i,j), E(i,j), F(i,j)} * E(i+1,j) = max{H(i,j)-q, E(i,j)-r} * F(i,j+1) = max{H(i,j)-q, F(i,j)-r} */ // compute H'(i,j); note that at the beginning, h=H'(i-1,j-1) h = _mm_adds_epu8(h, _mm_load_si128(S + j)); h = _mm_subs_epu8(h, shift); // h=H'(i-1,j-1)+S(i,j) e = _mm_load_si128(E + j); // e=E'(i,j) h = _mm_max_epu8(h, e); h = _mm_max_epu8(h, f); // h=H'(i,j) max = _mm_max_epu8(max, h); // set max _mm_store_si128(H1 + j, h); // save to H'(i,j) // now compute E'(i+1,j) h = _mm_subs_epu8(h, gapoe); // h=H'(i,j)-gapo e = _mm_subs_epu8(e, gape); // e=E'(i,j)-gape e = _mm_max_epu8(e, h); // e=E'(i+1,j) _mm_store_si128(E + j, e); // save to E'(i+1,j) // now compute F'(i,j+1) f = _mm_subs_epu8(f, gape); f = _mm_max_epu8(f, h); // get H'(i-1,j) and prepare for the next j h = _mm_load_si128(H0 + j); // h=H'(i-1,j) } // NB: we do not need to set E(i,j) as we disallow adjecent insertion and then deletion for (k = 0; LIKELY(k < 16); ++k) { // this block mimics SWPS3; NB: H(i,j) updated in the lazy-F loop cannot exceed max f = _mm_slli_si128(f, 1); for (j = 0; LIKELY(j < slen); ++j) { h = _mm_load_si128(H1 + j); h = _mm_max_epu8(h, f); // h=H'(i,j) _mm_store_si128(H1 + j, h); h = _mm_subs_epu8(h, gapoe); f = _mm_subs_epu8(f, gape); cmp = _mm_movemask_epi8(_mm_cmpeq_epi8(_mm_subs_epu8(f, h), zero)); if (UNLIKELY(cmp == 0xffff)) goto end_loop16; } } end_loop16: //int k;for (k=0;k<16;++k)printf(""%d "", ((uint8_t*)&max)[k]);printf(""\n""); __max_16(imax, max); // imax is the maximum number in max if (imax >= minsc) { // write the b array; this condition adds branching unfornately if (n_b == 0 || (int32_t)b[n_b-1] + 1 != i) { // then append if (n_b == m_b) { m_b = m_b? m_b<<1 : 8; b = (uint64_t*)realloc(b, 8 * m_b); } b[n_b++] = (uint64_t)imax<<32 | i; } else if ((int)(b[n_b-1]>>32) < imax) b[n_b-1] = (uint64_t)imax<<32 | i; // modify the last } if (imax > gmax) { gmax = imax; te = i; // te is the end position on the target for (j = 0; LIKELY(j < slen); ++j) // keep the H1 vector _mm_store_si128(Hmax + j, _mm_load_si128(H1 + j)); if (gmax + q->shift >= 255 || gmax >= endsc) break; } S = H1; H1 = H0; H0 = S; // swap H0 and H1 } r.score = gmax + q->shift < 255? gmax : 255; r.te = te; if (r.score != 255) { // get a->qe, the end of query match; find the 2nd best score int max = -1, low, high, qlen = slen * 16; uint8_t *t = (uint8_t*)Hmax; for (i = 0; i < qlen; ++i, ++t) if ((int)*t > max) max = *t, r.qe = i / 16 + i % 16 * slen; //printf(""%d,%d\n"", max, gmax); if (b) { i = (r.score + q->max - 1) / q->max; low = te - i; high = te + i; for (i = 0; i < n_b; ++i) { int e = (int32_t)b[i]; if ((e < low || e > high) && b[i]>>32 > (uint32_t)r.score2) r.score2 = b[i]>>32, r.te2 = e; } } } free(b); return r; } kswr_t ksw_i16(kswq_t *q, int tlen, const uint8_t *target, int _gapo, int _gape, int xtra) // the first gap costs -(_o+_e) { int slen, i, m_b, n_b, te = -1, gmax = 0, minsc, endsc; uint64_t *b; __m128i zero, gapoe, gape, *H0, *H1, *E, *Hmax; kswr_t r; #define __max_8(ret, xx) do { \ (xx) = _mm_max_epi16((xx), _mm_srli_si128((xx), 8)); \ (xx) = _mm_max_epi16((xx), _mm_srli_si128((xx), 4)); \ (xx) = _mm_max_epi16((xx), _mm_srli_si128((xx), 2)); \ (ret) = _mm_extract_epi16((xx), 0); \ } while (0) // initialization r = g_defr; minsc = (xtra&KSW_XSUBO)? xtra&0xffff : 0x10000; endsc = (xtra&KSW_XSTOP)? xtra&0xffff : 0x10000; m_b = n_b = 0; b = 0; zero = _mm_set1_epi32(0); gapoe = _mm_set1_epi16(_gapo + _gape); gape = _mm_set1_epi16(_gape); H0 = q->H0; H1 = q->H1; E = q->E; Hmax = q->Hmax; slen = q->slen; for (i = 0; i < slen; ++i) { _mm_store_si128(E + i, zero); _mm_store_si128(H0 + i, zero); _mm_store_si128(Hmax + i, zero); } // the core loop for (i = 0; i < tlen; ++i) { int j, k, imax; __m128i e, h, f = zero, max = zero, *S = q->qp + target[i] * slen; // s is the 1st score vector h = _mm_load_si128(H0 + slen - 1); // h={2,5,8,11,14,17,-1,-1} in the above example h = _mm_slli_si128(h, 2); for (j = 0; LIKELY(j < slen); ++j) { h = _mm_adds_epi16(h, *S++); e = _mm_load_si128(E + j); h = _mm_max_epi16(h, e); h = _mm_max_epi16(h, f); max = _mm_max_epi16(max, h); _mm_store_si128(H1 + j, h); h = _mm_subs_epu16(h, gapoe); e = _mm_subs_epu16(e, gape); e = _mm_max_epi16(e, h); _mm_store_si128(E + j, e); f = _mm_subs_epu16(f, gape); f = _mm_max_epi16(f, h); h = _mm_load_si128(H0 + j); } for (k = 0; LIKELY(k < 16); ++k) { f = _mm_slli_si128(f, 2); for (j = 0; LIKELY(j < slen); ++j) { h = _mm_load_si128(H1 + j); h = _mm_max_epi16(h, f); _mm_store_si128(H1 + j, h); h = _mm_subs_epu16(h, gapoe); f = _mm_subs_epu16(f, gape); if(UNLIKELY(!_mm_movemask_epi8(_mm_cmpgt_epi16(f, h)))) goto end_loop8; } } end_loop8: __max_8(imax, max); if (imax >= minsc) { if (n_b == 0 || (int32_t)b[n_b-1] + 1 != i) { if (n_b == m_b) { m_b = m_b? m_b<<1 : 8; b = (uint64_t*)realloc(b, 8 * m_b); } b[n_b++] = (uint64_t)imax<<32 | i; } else if ((int)(b[n_b-1]>>32) < imax) b[n_b-1] = (uint64_t)imax<<32 | i; // modify the last } if (imax > gmax) { gmax = imax; te = i; for (j = 0; LIKELY(j < slen); ++j) _mm_store_si128(Hmax + j, _mm_load_si128(H1 + j)); if (gmax >= endsc) break; } S = H1; H1 = H0; H0 = S; } r.score = gmax; r.te = te; { int max = -1, low, high, qlen = slen * 8; uint16_t *t = (uint16_t*)Hmax; for (i = 0, r.qe = -1; i < qlen; ++i, ++t) if ((int)*t > max) max = *t, r.qe = i / 8 + i % 8 * slen; if (b) { i = (r.score + q->max - 1) / q->max; low = te - i; high = te + i; for (i = 0; i < n_b; ++i) { int e = (int32_t)b[i]; if ((e < low || e > high) && b[i]>>32 > (uint32_t)r.score2) r.score2 = b[i]>>32, r.te2 = e; } } } free(b); return r; } static void revseq(int l, uint8_t *s) { int i, t; for (i = 0; i < l>>1; ++i) t = s[i], s[i] = s[l - 1 - i], s[l - 1 - i] = t; } kswr_t ksw_align(int qlen, uint8_t *query, int tlen, uint8_t *target, int m, const int8_t *mat, int gapo, int gape, int xtra, kswq_t **qry) { int size; kswq_t *q; kswr_t r, rr; kswr_t (*func)(kswq_t*, int, const uint8_t*, int, int, int); q = (qry && *qry)? *qry : ksw_qinit((xtra&KSW_XBYTE)? 1 : 2, qlen, query, m, mat); if (qry && *qry == 0) *qry = q; func = q->size == 2? ksw_i16 : ksw_u8; size = q->size; r = func(q, tlen, target, gapo, gape, xtra); if (qry == 0) free(q); if ((xtra&KSW_XSTART) == 0 || ((xtra&KSW_XSUBO) && r.score < (xtra&0xffff))) return r; revseq(r.qe + 1, query); revseq(r.te + 1, target); // +1 because qe/te points to the exact end, not the position after the end q = ksw_qinit(size, r.qe + 1, query, m, mat); rr = func(q, tlen, target, gapo, gape, KSW_XSTOP | r.score); revseq(r.qe + 1, query); revseq(r.te + 1, target); free(q); if (r.score == rr.score) r.tb = r.te - rr.te, r.qb = r.qe - rr.qe; return r; } /******************************************* * Main function (not compiled by default) * *******************************************/ #ifdef _KSW_MAIN #include #include #include #include ""kseq.h"" unsigned char seq_nt4_table[256] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; int main(int argc, char *argv[]) { int c, sa = 1, sb = 3, i, j, k, forward_only = 0, max_rseq = 0; int8_t mat[25]; int gapo = 5, gape = 2, minsc = 5, xtra = KSW_XSTART; uint8_t *rseq = 0; gzFile fpt, fpq; kseq_t *kst, *ksq; // parse command line while ((c = getopt(argc, argv, ""a:b:q:r:ft:1"")) >= 0) { switch (c) { case 'a': sa = atoi(optarg); break; case 'b': sb = atoi(optarg); break; case 'q': gapo = atoi(optarg); break; case 'r': gape = atoi(optarg); break; case 't': minsc = atoi(optarg); break; case 'f': forward_only = 1; break; case '1': xtra |= KSW_XBYTE; break; } } if (optind + 2 > argc) { fprintf(stderr, ""Usage: ksw [-1] [-f] [-a%d] [-b%d] [-q%d] [-r%d] [-t%d] \n"", sa, sb, gapo, gape, minsc); return 1; } if (minsc > 0xffff) minsc = 0xffff; if (minsc > 0) xtra |= KSW_XSUBO | minsc; // initialize scoring matrix for (i = k = 0; i < 4; ++i) { for (j = 0; j < 4; ++j) mat[k++] = i == j? sa : -sb; mat[k++] = 0; // ambiguous base } for (j = 0; j < 5; ++j) mat[k++] = 0; // open file fpt = gzopen(argv[optind], ""r""); kst = kseq_init(fpt); fpq = gzopen(argv[optind+1], ""r""); ksq = kseq_init(fpq); // all-pair alignment printf(""target\ttarget_start\ttarget_end\tquery\tquery_start\tquery_end\tbest_score\t2nd score\tsecond target score\toffset\n""); while (kseq_read(ksq) > 0) { kswq_t *q[2] = {0, 0}; kswr_t r; kswr_t rr; for (i = 0; i < (int)ksq->seq.l; ++i) ksq->seq.s[i] = seq_nt4_table[(int)ksq->seq.s[i]]; if (!forward_only) { // reverse if ((int)ksq->seq.m > max_rseq) { max_rseq = ksq->seq.m; rseq = (uint8_t*)realloc(rseq, max_rseq); } for (i = 0, j = ksq->seq.l - 1; i < (int)ksq->seq.l; ++i, --j) rseq[j] = ksq->seq.s[i] == 4? 4 : 3 - ksq->seq.s[i]; } gzrewind(fpt); kseq_rewind(kst); while (kseq_read(kst) > 0) { for (i = 0; i < (int)kst->seq.l; ++i) kst->seq.s[i] = seq_nt4_table[(int)kst->seq.s[i]]; r = ksw_align( ksq->seq.l, (uint8_t*)ksq->seq.s, kst->seq.l, (uint8_t*)kst->seq.s, 5, mat, gapo, gape, xtra, &q[0]); if (rseq) { rr = ksw_align( ksq->seq.l, rseq, kst->seq.l, (uint8_t*)kst->seq.s, 5, mat, gapo, gape, xtra, &q[1]); if (rr.score == r.score) { printf(""BOTH ALIGNMENTS HAVE IDENTICAL SCORES\n""); } if (rr.score > r.score && rr.score >= minsc) { printf(""R: %s\t%d\t%d\t%s\t%d\t%d\t%d\t%d\t%d\t%d\n"", kst->name.s, rr.tb, r.te+1, ksq->name.s, (int)ksq->seq.l - rr.qb, (int)ksq->seq.l - 1 - rr.qe, rr.score, rr.score2, rr.te2, rr.tb - rr.qb); goto next_iter; } else { goto print_forward; } } print_forward: if (r.score >= minsc) printf(""%s\t%d\t%d\t%s\t%d\t%d\t%d\t%d\t%d\t%d\n"", kst->name.s, r.tb, r.te+1, ksq->name.s, r.qb, r.qe+1, r.score, r.score2, r.te2, r.tb - r.qb); next_iter: ; } free(q[0]); free(q[1]); } free(rseq); kseq_destroy(kst); gzclose(fpt); kseq_destroy(ksq); gzclose(fpq); return 0; } #endif","C" "CRISPR","ctSkennerton/crass","src/crass/parser.cpp",".cpp","1401","40","/* * crass.h is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include ""parser.h"" crispr::xml::parser::parser() : reader(), writer() {} crispr::xml::parser::~parser() {}","C++" "CRISPR","ctSkennerton/crass","src/crass/MergeTool.cpp",".cpp","6411","166","// MergeTool.cpp // // Copyright (C) 2011 - Connor Skennerton // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #include ""MergeTool.h"" #include ""Exception.h"" #include ""writer.h"" #include ""reader.h"" #include ""config.h"" #include #include int MergeTool::processOptions (int argc, char ** argv) { int c; int index; static struct option long_options [] = { {""help"", no_argument, NULL, 'h'}, {""sanitise"", no_argument, NULL, 's'}, {""outfile"", required_argument, NULL, 'o'}, {0,0,0,0} }; while((c = getopt_long(argc, argv, ""hso:"", long_options, &index)) != -1) { switch(c) { case 'h': { mergeUsage (); exit(0); break; } case 's': { MT_Sanitise = true; break; } case 'o': { MT_OutFile = optarg; break; } default: { mergeUsage(); exit(1); break; } } } return optind; } int mergeMain (int argc, char ** argv) { try { MergeTool mt; int opt_index = mt.processOptions(argc, argv); if (opt_index >= argc) { throw crispr::input_exception(""No input files provided"" ); } else if (opt_index == argc - 1) { // less than 2 input files throw crispr::input_exception(""You must provide at least two input files to merge""); } else { // merge!! // create a DOM document crispr::xml::writer master_DOM; int master_DOM_error; xercesc::DOMElement * master_root_elem = master_DOM.createDOMDocument(""crispr"", ""1.1"", master_DOM_error); if (master_root_elem != NULL && master_DOM_error == 0) { xercesc::DOMDocument * master_doc = master_DOM.getDocumentObj(); while (opt_index < argc) { // create a file parser crispr::xml::reader input_file; xercesc::DOMDocument * input_doc = input_file.setFileParser(argv[opt_index]); // Get the top-level element: xercesc::DOMElement* elementRoot = input_doc->getDocumentElement(); if( !elementRoot ) throw(crispr::xml_exception( __FILE__, __LINE__, __PRETTY_FUNCTION__, ""empty XML document"" )); // get the children for (xercesc::DOMElement * currentElement = elementRoot->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if( xercesc::XMLString::equals(currentElement->getTagName(), input_file.tag_Group())) { if (mt.getSanitise()) { // change the name std::stringstream ss; ss <<'G'<< mt.getNextGroupID(); XMLCh * x_group = tc(ss.str().c_str()); currentElement->setAttribute(master_DOM.attr_Gid(), x_group); mt.incrementGroupID(); xr(&x_group); } else { // check if we already seen it if so warn the user char * gid = tc(currentElement->getAttribute(master_DOM.attr_Gid())); if ( mt.find(gid) != mt.end()) { // this group id has been seen before std::cout<<""Group IDs in the two files conflict ""<appendChild(master_doc->importNode(currentElement, true)); } } opt_index++; } master_DOM.printDOMToFile(mt.getFileName()); } else { throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""no root for master DOM""); } } } catch (crispr::input_exception& e) { std::cerr<. // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // system includes #include #include // local includes #include ""StringCheck.h"" #include ""Exception.h"" StringToken StringCheck::addString(std::string newStr) { //----- // add the string and retuen it's token // mNextFreeToken++; mT2S_map[mNextFreeToken] = newStr; mS2T_map[newStr] = mNextFreeToken; return mNextFreeToken; } std::string StringCheck::getString(StringToken token) { //----- // return the string for a given token or spew // if(mT2S_map.find(token) != mT2S_map.end()) { return mT2S_map[token]; } else { throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Token not stored""); } } StringToken StringCheck::getToken(const std::string& queryStr) { //----- // return the token or 0 // if(mS2T_map.end() == mS2T_map.find(queryStr)) return 0; return mS2T_map[queryStr]; } ","C++" "CRISPR","ctSkennerton/crass","src/crass/FilterTool.cpp",".cpp","14435","389","// FilterTool.cpp // // Copyright (C) 2011, 2012 - Connor Skennerton // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #include ""FilterTool.h"" #include ""Exception.h"" #include ""config.h"" #include ""writer.h"" #include ""parser.h"" #include ""StlExt.h"" #include #include #include ""Utils.h"" #define exists(container,searchThing ) container.find(searchThing) != container.end() int FilterTool::processOptions (int argc, char ** argv) { int c; int index; static struct option long_options [] = { {""help"", no_argument, NULL, 'h'}, {""outfile"", required_argument, NULL, 'o'}, {""spacer"",required_argument,NULL,'s'}, {""direct-repeat"", required_argument, NULL, 'd'}, {""flanker"", required_argument, NULL, 'f'}, {""coverage"",required_argument,NULL,'C'}, {0,0,0,0} }; while((c = getopt_long(argc, argv, ""hs:c:f:d:o:C:"", long_options,&index)) != -1) { switch(c) { case 'h': { filterUsage(); exit(0); break; } case 's': { if (! from_string(FT_Spacers, optarg, std::dec)) { crispr::input_exception(""cannot convert arguement of -s to integer""); } break; } case 'o': { FT_OutputFile = optarg; break; } case 'f': { if (! from_string(FT_Flank, optarg, std::dec)) { crispr::input_exception(""cannot convert arguement of -f to integer""); } break; } case 'd': { if(! from_string(FT_Repeats, optarg, std::dec)){ crispr::input_exception(""cannot convert arguement of -d to integer""); } break; } case 'c': { if(! from_string(FT_contigs, optarg, std::dec)){ crispr::input_exception(""cannot convert arguement of -c to integer""); } break; } case 'C': { if(! from_string(FT_Coverage, optarg, std::dec)){ crispr::input_exception(""cannot convert arguement of -C to integer""); } break; } default: { filterUsage(); exit(1); break; } } } return optind; } int FilterTool::processInputFile(const char * inputFile) { try { crispr::xml::writer output_xml; int output_error; xercesc::DOMElement * output_root_elem = output_xml.createDOMDocument(""crispr"", ""1.1"", output_error); if(output_error && NULL == output_root_elem) { throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Cannot create output xml file""); } crispr::xml::parser xml_parser; xercesc::DOMDocument * input_doc_obj = xml_parser.setFileParser(inputFile); xercesc::DOMElement * root_elem = input_doc_obj->getDocumentElement(); if (!root_elem) { throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""problem when parsing xml file""); } if (FT_OutputFile.empty()) { FT_OutputFile = inputFile; } std::vector good_children; for (xercesc::DOMElement * currentElement = root_elem->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { // the user wants to change any of these if (FT_Spacers || FT_Repeats || FT_Flank || FT_Coverage) { if (! parseGroup(currentElement, xml_parser)) { good_children.push_back(currentElement); } } } std::vector::iterator iter = good_children.begin(); xercesc::DOMDocument * output_document = output_xml.getDocumentObj(); while (iter != good_children.end()) { output_root_elem->appendChild(output_document->importNode(*iter, true)); iter++; } output_xml.printDOMToFile(FT_OutputFile, output_document); } catch (crispr::xml_exception& e) { std::cerr<getFirstElementChild(); if (NULL != currentElement) { std::set spacers_to_remove; if( parseData(currentElement, xmlParser, spacers_to_remove) ) return true; // get the assembly node currentElement = parentNode->getLastElementChild(); parseAssembly(currentElement, xmlParser, spacers_to_remove); } else { throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""There is no Data""); } return false; } // return true if group should be removed bool FilterTool::parseData(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::set& spacersToRemove) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Drs())) { if (FT_Repeats) { // change the direct repeats if (FT_Repeats > parseDrs(currentElement)) { return true; } } } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Spacers())) { if (FT_Spacers | FT_Coverage) { // change the spacers if (FT_Spacers > parseSpacers(currentElement, xmlParser, spacersToRemove)) { return true; } } } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Flankers())) { if (FT_Flank) { // change the flankers if ( FT_Flank > parseFlankers(currentElement)) { return true; } } } } return false; } int FilterTool::countElements(xercesc::DOMElement * parentNode) { int count = 0; for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { ++count; } return count; } int FilterTool::parseSpacers(xercesc::DOMElement *parentNode, crispr::xml::reader& xmlParser, std::set& spacersToRemove) { if (FT_Coverage) { std::vector remove_list; for (xercesc::DOMElement * currentSpacer = parentNode->getFirstElementChild(); currentSpacer != NULL; currentSpacer = currentSpacer->getNextElementSibling()) { char * c_spacer_coverage = tc(currentSpacer->getAttribute(xmlParser.attr_Cov())); int cov; from_string(cov, c_spacer_coverage, std::dec); xr(&c_spacer_coverage); if (cov < FT_Coverage) { // remove spacer remove_list.push_back(currentSpacer); char * c_spid = tc(currentSpacer->getAttribute(xmlParser.attr_Spid())); spacersToRemove.insert(c_spid); xr(&c_spid); } } std::vector::iterator iter; for (iter = remove_list.begin(); iter != remove_list.end(); iter++) { parentNode->removeChild(*iter); } } else if(FT_Spacers) { return countElements(parentNode); } return 1; } void FilterTool::parseAssembly(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::set& spacersToRemove) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Contig())) { char * c_contig_id = tc(currentElement->getAttribute(xmlParser.attr_Cid())); std::string contig_id = c_contig_id; xr(&c_contig_id); parseContig(currentElement, xmlParser, contig_id, spacersToRemove); } } } void FilterTool::parseContig(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::string& contigId, std::set& spacersToRemove) { std::vector remove_list; for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Cspacer())) { // get the node char * c_spid = tc(currentElement->getAttribute(xmlParser.attr_Spid())); if(exists(spacersToRemove, c_spid)) { remove_list.push_back(currentElement); continue; } xr(&c_spid); parseCSpacer(currentElement, xmlParser, contigId, spacersToRemove); } } std::vector::iterator iter; for (iter = remove_list.begin(); iter != remove_list.end(); iter++) { parentNode->removeChild(*iter); } } void FilterTool::parseCSpacer(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::string& contigId, std::set& spacersToRemove) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Fspacers())) { parseLinkSpacers(currentElement, xmlParser, contigId, spacersToRemove); } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Bspacers())) { parseLinkSpacers(currentElement, xmlParser, contigId, spacersToRemove); } } } void FilterTool::parseLinkSpacers(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::string& contigId, std::set& spacersToRemove) { std::vector remove_list; for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { char * c_spid = tc(currentElement->getAttribute(xmlParser.attr_Spid())); if(exists(spacersToRemove, c_spid)) { remove_list.push_back(currentElement); continue; } xr(&c_spid); } std::vector::iterator iter; for (iter = remove_list.begin(); iter != remove_list.end(); iter++) { parentNode->removeChild(*iter); } } int filterMain (int argc, char ** argv) { try { FilterTool ft; int opt_index = ft.processOptions (argc, argv); if (opt_index >= argc) { throw crispr::input_exception(""No input file provided"" ); } else { // get cracking and process that file return ft.processInputFile(argv[opt_index]); } } catch(crispr::input_exception& re) { std::cerr<. */ #ifndef STLEXT_H #define STLEXT_H #include #include #include #include #include #include #include #include #include template void addOrIncrement(std::map &inMap, T1 &searchThing) { if (inMap.find(searchThing) != inMap.end()) { inMap[searchThing] += 1; } else { inMap[searchThing] = 1; } } template inline std::string to_string (const T& t) { std::stringstream ss; ss << t; return ss.str(); } template bool from_string(T& t, const std::string& s, std::ios_base& (*f)(std::ios_base&)) { std::istringstream iss(s); return !(iss >> f >> t).fail(); } template void mapToVector(std::map& map, std::vector& vector) { typename std::map::iterator iter = map.begin(); while (iter != map.end()) { vector.push_back(iter->first); iter++; } } // templated function to split a string on delimeters and return it in a container of class T template < class ContainerT > void tokenize(const std::string& str, ContainerT& tokens, const std::string& delimiters = "" "", const bool trimEmpty = false) { std::string::size_type pos, lastPos = 0; while(true) { pos = str.find_first_of(delimiters, lastPos); if(pos == std::string::npos) { pos = str.length(); if(pos != lastPos || !trimEmpty) tokens.push_back( typename ContainerT::value_type(str.data()+lastPos, (typename ContainerT::value_type::size_type)pos - lastPos )); break; } else { if(pos != lastPos || !trimEmpty) tokens.push_back(typename ContainerT::value_type(str.data()+lastPos, (typename ContainerT::value_type::size_type)pos-lastPos )); } lastPos = pos + 1; } } template < class ContainerT > void split(const std::string& str, ContainerT& tokens, const std::string& delimiters = "","", const bool trimEmpty = false) { std::string::size_type pos, lastPos = 0; while(true) { pos = str.find_first_of(delimiters, lastPos); if(pos == std::string::npos) { pos = str.length(); if(pos != lastPos || !trimEmpty) tokens.insert( typename ContainerT::value_type(str.data()+lastPos, (typename ContainerT::value_type::size_type)pos - lastPos )); break; } else { if(pos != lastPos || !trimEmpty) tokens.insert(typename ContainerT::value_type(str.data()+lastPos, (typename ContainerT::value_type::size_type)pos-lastPos )); } lastPos = pos + 1; } } // class T1 is the container that holds the numbers and class T2 is the return type like int or double template typename T::value_type mean(T& container) { return (std::accumulate(container.begin(), container.end(), static_cast(0))/container.size()); } template typename T::value_type median(T& container) { std::nth_element(container.begin(), container.begin()+container.size()/2, container.end()); return *(container.begin()+container.size()/2); } template typename T::value_type percentile(T& container, double percentile) { std::nth_element(container.begin(), container.begin()+container.size()*percentile, container.end()); return *(container.begin()+container.size()*percentile); } template typename T::value_type mode(T& container) { std::vector histogram(container.size(),0); typename T::iterator iter = container.begin(); while (iter != container.end()) { histogram[*iter++]++; } return std::max_element(histogram.begin(), histogram.end()) - histogram.begin(); } template double standardDeviation(T& container) { double average = static_cast( mean(container)); std::vector temp; typename T::iterator iter; for (iter = container.begin(); iter != container.end(); iter++) { double i = static_cast(*iter) - average; temp.push_back(i*i); } return std::sqrt(std::accumulate(temp.begin(), temp.end(), static_cast(0))/temp.size() ); } #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/NodeManager.h",".h","11762","300","// File: NodeManager.h // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Class to handle all the lists of nodes and class instances. // Each cannonical form of direct repeat gets it's ""own"" NodeManager // Thus a cannonical DR is a crispr is a NodeManager // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // #ifndef NodeManager_h #define NodeManager_h // system includes #include #include #include #include #include #include // local includes #include ""NodeManager.h"" #include ""crassDefines.h"" #include ""CrisprNode.h"" #include ""SpacerInstance.h"" #include ""libcrispr.h"" #include ""StringCheck.h"" #include ""ReadHolder.h"" #include ""GraphDrawingDefines.h"" #include ""Rainbow.h"" #include ""writer.h"" #include ""StatsManager.h"" #ifdef SEARCH_SINGLETON #include ""SearchChecker.h"" #endif // typedefs typedef std::map NodeList; typedef std::map::iterator NodeListIterator; typedef std::map SpacerList; typedef std::map::iterator SpacerListIterator; typedef std::vector NodeVector; typedef std::vector::iterator NodeVectorIterator; typedef std::pair CrisprNodePair; typedef std::pair CrisprNodePairIterator; typedef std::vector SpacerVector; typedef std::vector::iterator SpacerVectorIterator; typedef std::mapContigList; typedef std::map::iterator ContigListIterator; //macros #define makeKey(i,j) (i*100000)+j class WalkingManager { SpacerInstancePair WM_WalkingElem; SI_EdgeDirection WM_Wanted_Edge_Type; public: WalkingManager(SpacerInstance * firstNode, SpacerInstance * secondNode, SI_EdgeDirection incommingEdge) { WM_WalkingElem.first = firstNode; WM_WalkingElem.second = secondNode; WM_Wanted_Edge_Type = incommingEdge; } WalkingManager(void){} ~WalkingManager(void){} SpacerInstance * getFirstNode(void) { return WM_WalkingElem.first; } SpacerInstance * getSecondNode(void) { return WM_WalkingElem.second; } SpacerInstance * first(void) { return WM_WalkingElem.first; } SpacerInstance * second(void) { return WM_WalkingElem.second; } SpacerInstancePair getWalkingElem(void) { return WM_WalkingElem; } SI_EdgeDirection getEdgeType(void) { return WM_Wanted_Edge_Type; } void setFirstNode(SpacerInstance * fn) { WM_WalkingElem.first = fn; } void setSecondNode(SpacerInstance * sn) { WM_WalkingElem.second = sn; } void setWalkingElem(SpacerInstancePair np) { WM_WalkingElem = np; } void setWantedEdge(SI_EdgeDirection e) { WM_Wanted_Edge_Type = e; } SpacerInstance * shift(SpacerInstance * newNode); }; class NodeManager { public: NodeManager(std::string drSeq, const options * userOpts); ~NodeManager(void); bool addReadHolder(ReadHolder * RH); NodeListIterator nodeBegin(void) { return NM_Nodes.begin(); } NodeListIterator nodeEnd(void) { return NM_Nodes.end(); } // get / set inline StringCheck * getStringCheck(void) { return &NM_StringCheck; } void findCapNodes(NodeVector * capNodes); // go through all the node and get a list of pointers to the nodes that have only one edge void findAllNodes(NodeVector * allNodes); void findAllNodes(NodeVector * capNodes, NodeVector * otherNodes); int findCapsAt(NodeVector * capNodes, bool searchForward, bool isInner, bool doStrict, CrisprNode * queryNode); EDGE_TYPE getOppositeEdgeType(EDGE_TYPE currentEdgeType); int getSpacerCountAndStats( bool showDetached=false, bool excludeFlankers=true); inline bool haveAnyFlankers(void){return (0 != NM_FlankerNodes.size());} inline void clearStats(void) {NM_SpacerLenStat.clear();} // Walking bool getSpacerEdgeFromCap(WalkingManager * walkElem, SpacerInstance * nextSpacer); bool getSpacerEdgeFromCross(WalkingManager * walkElem, SpacerInstance * nextSpacer); bool stepThroughSpacerPath(WalkingManager * walkElem, SpacerInstance ** previousNode); bool walkFromCross(SpacerInstanceList * crossNodes); // Cleaning int cleanGraph(void); bool clearBubbles(CrisprNode * rootNode, EDGE_TYPE currentEdgeType); // Contigs void getAllSpacerCaps(SpacerInstanceVector * sv); void findSpacerForContig(SpacerInstanceVector * sv, int contigID); int cleanSpacerGraph(void); void removeSpacerBubbles(void); int splitIntoContigs(void); void findAllForwardAttachedNodes(NodeVector * nodes); int buildSpacerGraph(void); void clearContigs(void); void contigiseForwardSpacers(std::queue * walkingQueue, SpacerInstance * SI); bool getForwardSpacer(SpacerInstance ** retSpacer, SpacerInstance * SI); bool getPrevSpacer(SpacerInstance ** retSpacer, SpacerInstance * SI); // Making purdy colours void setDebugColourLimits(void); void setSpacerColourLimits(void); // Printing / IO // Print a graphviz style graph of the DRs and spacers void printDebugGraph(std::ostream &dataOut, std::string title, bool showDetached, bool printBackEdges, bool longDesc); void printDebugNodeAttributes(std::ostream& dataOut, CrisprNode * currCrisprNode, std::string colourCode, bool longDesc); // Print a graphviz style graph of the FULL spacers bool printSpacerGraph(std::string& outFileName, std::string title, bool longDesc, bool showSingles); // Print a graphviz style graph of the FULL spacers bool printSpacerGraph(void); std::string getSpacerGraphLabel(SpacerInstance * spacer, bool longDesc); // make a key for the spacer graph void printSpacerKey(std::ostream &dataOut, int numSteps, std::string groupNumber); void dumpReads(std::string readsFileName, bool showDetached); // XML // print this node managers portion of the XML file void printXML(std::ofstream * XMLFile, int GID, bool showDetached ); void addSpacersToDOM(crispr::xml::writer * xmlDoc, xercesc::DOMElement * parentNode, bool showDetached, std::set& allSourcesForNM ); void addFlankersToDOM(crispr::xml::writer * xmlDoc, xercesc::DOMElement * parentNode, bool showDetached, std::set& allSourcesForNM ); void printAssemblyToDOM(crispr::xml::writer * xmlDoc, xercesc::DOMElement * parentNode, bool showDetached ); void getHeadersForSpacers(SpacerInstance * SI, std::set& nrTokens ); void appendSourcesForSpacer(xercesc::DOMElement * spacerNode, std::set& nrTokens, crispr::xml::writer * xmlDoc ); void generateAllsourceTags(crispr::xml::writer * xmlDoc, std::set& allSourcesForNM, xercesc::DOMElement * parentNode ); // Spacer dictionaries void printAllSpacers(void); // Flankers void generateFlankers(bool showDetached=false); // Stats inline size_t meanSpacerLength(void) { return NM_SpacerLenStat.mean();} inline double stdevSpacerLength(void) { return NM_SpacerLenStat.standardDeviation();} private: // functions bool splitReadHolder(ReadHolder * RH); void addCrisprNodes(CrisprNode ** prevNode, std::string& workingString, StringToken headerSt, ReadHolder * RH); void addSecondCrisprNode(CrisprNode ** prevNode, std::string& workingString, StringToken headerSt, ReadHolder * RH); void addFirstCrisprNode(CrisprNode ** prevNode, std::string& workingString, StringToken headerSt, ReadHolder * RH); void setContigIDForSpacers(SpacerInstanceVector * currentContigNodes); void setUpperAndLowerCoverage(void); // members std::string NM_DirectRepeatSequence; // the sequence of this managers direct repeat NodeList NM_Nodes; // list of CrisprNodes this manager manages SpacerList NM_Spacers; // list of all the spacers ReadList NM_ReadList; // list of readholders StringCheck NM_StringCheck; // string check object for unique strings Rainbow NM_DebugRainbow; // the Rainbow class for making colours Rainbow NM_SpacerRainbow; // the Rainbow class for making colours const options * NM_Opts; // pointer to the user options structure int NM_NextContigID; // next free contig ID (doubles as a counter) ContigList NM_Contigs; // our contigs StatsManager > NM_SpacerLenStat; // Keep a check on all of the spacer lengths for deciding whecher thay are a flanker or not SpacerInstanceVector NM_FlankerNodes; // a list of spacers that are also flankers -- used only in the print functions }; #endif // NodeManager_h ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/SmithWaterman.h",".h","3405","87","// File: SmithWaterman.h // Original Author: Connor Skennerton // -------------------------------------------------------------------- // // OVERVIEW: // // Modified smithwaterman implementation // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // -------------------------------------------------------------------- ////////////////////////////////////////////// // Simple Ends-Free Smith-Waterman Algorithm // // You will be prompted for input sequences // Penalties and match scores are hard-coded // // Program does not perform multiple tracebacks if // it finds several alignments with the same score // // By Nikhil Gopal // Similar implementation here: https://wiki.uni-koeln.de/biologicalphysics/index.php/Implementation_of_the_Smith-Waterman_local_alignment_algorithm ////////////////////////////////////////////// #ifndef __SMITH_WATERMAN_H #define __SMITH_WATERMAN_H // system includes #include #include #define SW_MATCH (1.2) #define SW_MISMATCH (-1) #define SW_GAP (-1) #define SW_SIM_SCORE(_a, _b) ((_a == _b) ? SW_MATCH : SW_MISMATCH ) typedef std::pair stringPair; double findMax(double a, double b, double c, double d, int * index); //----- // The SW you've grown to know and love // stringPair smithWaterman(std::string& seqA, std::string& seqB); //----- // Same as below but ignore similarity // stringPair smithWaterman(std::string& seqA, std::string& seqB, int * aStartAlign, int * aEndAlign, int aStartSearch, int aEndSearch, double similarity); //----- // Trickle-ier verison of the original version of the smith waterman algorithm I found in this file // // This function is seqA centric, it will align ALL of seqB to the parts of seqA which lie INCLUSIVELY // between aStartSearch and aEndSearch. It will return the UNIMPUTED alignment strings for A and B respectively // in the stringPair variable AND it also stores the start and end indexes used to cut the seqA substring in the // two int references aStartAlign, aEndAlign stringPair smithWaterman(std::string& seqA, std::string& seqB, int * aStartAlign, int * aEndAlign, int aStartSearch, int aEndSearch); #endif // __SMITH_WATERMAN_H ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/StatTool.cpp",".cpp","20383","577","// StatTool.cpp // // Copyright (C) 2011 - Connor Skennerton // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #include ""StatTool.h"" #include ""config.h"" #include ""Exception.h"" #include ""reader.h"" #include ""Utils.h"" #include #include #include #include StatTool::~StatTool() { std::vector::iterator iter = begin(); while (iter != end()) { delete *iter; iter++; } } //void StatTool::generateGroupsFromString ( std::string str) //{ // std::set vec; // split ( str, vec, "",""); // ST_Groups = vec; // ST_Subset = true; //} int StatTool::processOptions (int argc, char ** argv) { int c, index; struct option long_opts [] = { {""help"", no_argument, NULL, 'h'}, {""header"", no_argument, NULL, 'H'}, {""coverage"", no_argument, NULL, 0} }; while((c = getopt_long(argc, argv, ""ahHg:pPs:o:"", long_opts, &index)) != -1) { switch(c) { case 'a': { ST_AggregateStats = true; break; } case 'p': { ST_OutputStyle = pretty; break; } case 'P': { ST_OutputStyle = veryPretty; break; } case 'h': { statUsage(); exit(0); break; } case 'o': { ST_OutputFileName = optarg; break; } case 'g': { if(fileOrString(optarg)) { // its a file parseFileForGroups(ST_Groups, optarg); //ST_Subset = true; } else { // its a string generateGroupsFromString(optarg, ST_Groups); } ST_Subset = true; break; } case 's': { ST_Separator = optarg; break; } case 'H': { ST_WithHeader = true; break; } case 0: { if (! strcmp(""coverage"", long_opts[index].name)) { ST_DetailedCoverage = true; ST_OutputStyle = coverage; } break; } default: { statUsage(); exit(1); break; } } } return optind; } int StatTool::processInputFile(const char * inputFile) { try { crispr::xml::reader xml_parser; std::ifstream in_file_stream(inputFile); if (in_file_stream.good()) { in_file_stream.close(); } else { throw crispr::input_exception(""cannot open input file""); } xercesc::DOMDocument * input_doc_obj = xml_parser.setFileParser(inputFile); xercesc::DOMElement * root_elem = input_doc_obj->getDocumentElement(); if (!root_elem) { throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""problem when parsing xml file""); } int num_groups_to_process = static_cast(ST_Groups.size()); //std::cout<getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (ST_Subset && num_groups_to_process == 0) { break; } // is this a group element if (xercesc::XMLString::equals(currentElement->getTagName(), xml_parser.tag_Group())) { char * c_gid = tc(currentElement->getAttribute(xml_parser.attr_Gid())); std::string group_id = c_gid; if (ST_Subset) { // we only want some of the groups look at DT_Groups if (ST_Groups.find(group_id.substr(1)) != ST_Groups.end() ) { parseGroup(currentElement, xml_parser); // decrease the number of groups left // if we are only using a subset if(ST_Subset) num_groups_to_process--; } } else { parseGroup(currentElement, xml_parser); } xr(&c_gid); } } AStats agregate_stats; agregate_stats.total_groups = 0; agregate_stats.total_spacers = 0; agregate_stats.total_dr = 0; agregate_stats.total_flanker = 0; agregate_stats.total_spacer_length = 0; agregate_stats.total_spacer_cov = 0; agregate_stats.total_dr_length = 0; agregate_stats.total_flanker_length = 0; agregate_stats.total_reads = 0; // go through each of the groups and print out a pretty picture std::vector::iterator iter = this->begin(); int longest_consensus = 0; int longest_gid = 0; if (ST_OutputStyle == veryPretty) { while (iter != this->end()) { if(static_cast((*iter)->getConcensus().length()) > longest_consensus) { longest_consensus = static_cast((*iter)->getConcensus().length()); } if (static_cast((*iter)->getGid().length()) > longest_gid) { longest_gid = static_cast((*iter)->getGid().length()); } } iter = this->begin(); } while (iter != this->end()) { switch (ST_OutputStyle) { case tabular: printTabular(*iter); break; case pretty: prettyPrint(*iter); break; case veryPretty: veryPrettyPrint(*iter, longest_consensus, longest_gid); break; case coverage: printCoverage(*iter); break; default: break; } iter++; } if (ST_AggregateStats) { calculateAgregateSTats(&agregate_stats); printAggregate(&agregate_stats); } } catch (xercesc::DOMException& e ) { char * c_msg = tc(e.getMessage()); std::cerr<getAttribute(xmlParser.attr_Drseq())); std::string concensusRepeat =c_cons; sm->setConcensus(concensusRepeat); xr(&c_cons); char * c_gid = tc(parentNode->getAttribute(xmlParser.attr_Gid())); std::string gid = c_gid; xr(&c_gid); sm->setGid(gid); for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Data())) { parseData(currentElement, xmlParser, sm); } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Metadata())) { parseMetadata(currentElement, xmlParser, sm); } } } void StatTool::parseData(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Drs())) { // change the direct repeats parseDrs(currentElement, xmlParser, statManager); } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Spacers())) { // change the spacers parseSpacers(currentElement, xmlParser, statManager); } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Flankers())) { // change the flankers parseFlankers(currentElement, xmlParser, statManager); } } } void StatTool::parseDrs(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { char * c_repeat = tc(currentElement->getAttribute(xmlParser.attr_Seq())); std::string repeat = c_repeat; xr(&c_repeat); statManager->addRepLenVec(static_cast(repeat.length())); statManager->incrementRpeatCount(); } } void StatTool::parseSpacers(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { char * c_spacer = tc(currentElement->getAttribute(xmlParser.attr_Seq())); std::string spacer = c_spacer; xr(&c_spacer); statManager->addSpLenVec(static_cast(spacer.length())); char * c_cov = tc(currentElement->getAttribute(xmlParser.attr_Cov())); std::string cov = c_cov; xr(&c_cov); if (!cov.empty()) { int cov_int; from_string(cov_int, cov, std::dec); statManager->addSpCovVec(cov_int); } statManager->incrementSpacerCount(); } } void StatTool::parseFlankers(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { char * c_flanker = tc(currentElement->getAttribute(xmlParser.attr_Seq())); std::string flanker = c_flanker; xr(&c_flanker); statManager->addFlLenVec(static_cast(flanker.length())); statManager->incrementFlankerCount(); } } void StatTool::parseMetadata(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_File())) { char * c_type_attr = tc(currentElement->getAttribute(xmlParser.attr_Type())); if (! strcmp(c_type_attr, ""sequence"")) { char * c_url = tc(currentElement->getAttribute(xmlParser.attr_Url())); statManager->setReadCount(calculateReads(c_url)); xr(&c_url); } xr(&c_type_attr); } } } int StatTool::calculateReads(const char * fileName) { std::fstream sequence_file; sequence_file.open(fileName); int sequence_counter = 0; if (! sequence_file.good()) { } std::string line; while (sequence_file >> line) { if (line.substr(0,1) == "">"") { sequence_counter++; } } return sequence_counter; } void StatTool::calculateAgregateSTats(AStats * agregateStats) { std::vector::iterator iter; for(iter = begin(); iter != end(); iter++) { agregateStats->total_groups++; agregateStats->total_dr += (*iter)->getRpeatCount(); agregateStats->total_dr_length += (*iter)->meanRepeatL(); agregateStats->total_spacers += (*iter)->getSpacerCount(); agregateStats->total_spacer_length += ((*iter)->getSpLenVec().empty()) ? 0 : (*iter)->meanSpacerL(); agregateStats->total_spacer_cov +=((*iter)->getSpCovVec().empty()) ? 0 : (*iter)->meanSpacerC(); agregateStats->total_flanker += (*iter)->getFlankerCount(); agregateStats->total_flanker_length += ((*iter)->getFlLenVec().empty()) ? 0 : (*iter)->meanFlankerL(); agregateStats->total_reads += (*iter)->getReadCount(); } } void StatTool::prettyPrint(StatManager * sm) { std::cout<getGid()<<"" | ""<getConcensus()<<"" | ""; int i = 0; for ( i = 0; i < sm->getRpeatCount(); ++i) { std::cout<getSpacerCount() ; ++i) { std::cout<getFlankerCount(); ++i) { std::cout<getRpeatCount()<< "" "" <getSpacerCount()<<"" ""<getFlankerCount()<<"" } ""<getSpacerCount() / num_columns; int current_gid_length = static_cast(sm->getGid().length()); int current_consensus_length = static_cast(sm->getConcensus().length()); int consensus_padding = longestConsensus - current_consensus_length; int gid_padding = longestGID - current_gid_length; //int total_length_before_spacers = current_gid_length + current_consensus_length + gid_padding + consensus_padding; std::cout<getGid(); int i = 0; for ( i = 0; i < gid_padding; i++) { std::cout<<' '; } std::cout<<"" | ""<getConcensus(); for ( i = 0; i < consensus_padding; i++) { std::cout<<' '; } std::cout<<"" | ""; for ( i = 0; i < sm->getRpeatCount(); ++i) { std::cout<getSpacerCount() ; ++i) { std::cout<getFlankerCount(); ++i) { std::cout<getRpeatCount()<< "" "" <getSpacerCount()<<"" ""<getFlankerCount()<<"" } ""<getGid()<getConcensus()<getRpeatCount()<< ST_Separator; std::cout<< sm->meanRepeatL()<getSpacerCount()<getSpLenVec().empty()) { std::cout<< sm->meanSpacerL()<getSpCovVec().empty()) { std::cout<<0<meanSpacerC()<getFlankerCount()<getFlLenVec().empty()) { std::cout<<0<meanFlankerL()<getReadCount()<total_groups<total_dr<total_groups != 0) { std::cout<total_dr_length/agregate_stats->total_groups<total_spacers<total_groups != 0) { std::cout<total_spacer_length/agregate_stats->total_groups<total_groups != 0) { std::cout<total_spacer_cov/agregate_stats->total_groups<total_flanker<total_groups != 0) { std::cout<total_flanker_length/agregate_stats->total_groups<total_groups != 0) { std::cout<total_reads/agregate_stats->total_groups<getGid()<getConcensus()< histogram; std::vector coverage = sm->getSpCovVec(); std::vector::iterator iter; for (iter = coverage.begin(); iter != coverage.end(); iter++) { addOrIncrement(histogram, *iter); } std::map::iterator h_iter; for (h_iter = histogram.begin(); h_iter != histogram.end(); h_iter++) { std::cout<first<<"":""<second<<"",""; } std::cout<= argc) { throw crispr::input_exception(""No input file provided"" ); } else { // get cracking and process that file return st.processInputFile(argv[opt_index]); } } catch(crispr::input_exception& re) { std::cerr<. * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef __SEQ_UTILS_H #define __SEQ_UTILS_H #include #include std::string reverseComplement(std::string str); std::string laurenize(std::string seq); //************************************** // system //************************************** gzFile getFileHandle(const char * inputFile); void RecursiveMkdir(std::string dir); #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/ReadHolder.h",".h","12345","457","// File: ReadHolder.h // Original Author: Michael Imelfort 2011 // Hacked and Extended: Connor Skennerton 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Main class for all things read related. Holds information about the // sequence and the direct repeats contained in the read // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // #ifndef ReadHolder_h #define ReadHolder_h // system includes #include #include #include // local includes #include ""crassDefines.h"" // typedefs typedef std::vector StartStopList; typedef std::vector::iterator StartStopListIterator; typedef std::vector::reverse_iterator StartStopListRIterator; class ReadHolder { public: ReadHolder() { RH_LastDREnd = 0; RH_NextSpacerStart = 0; RH_isSqueezed = false; RH_IsFasta = true; } ReadHolder(std::string s, std::string h) { RH_Seq = s; RH_Header = h; RH_LastDREnd = 0; RH_NextSpacerStart = 0; RH_isSqueezed = false; RH_IsFasta = true; } ReadHolder(const char * s, const char * h) { RH_Seq = s; RH_Header = h; RH_LastDREnd = 0; RH_NextSpacerStart = 0; RH_isSqueezed = false; RH_IsFasta = true; } ReadHolder(std::string s, std::string h, std::string c, std::string q) { RH_Seq = s; RH_Header = h; RH_Comment = c; RH_Qual = q; RH_LastDREnd = 0; RH_NextSpacerStart = 0; RH_isSqueezed = false; RH_IsFasta = false; } ReadHolder(const char * s, const char * h, const char * c, const char * q) { RH_Seq = s; RH_Header = h; RH_Comment = c; RH_Qual = q; RH_LastDREnd = 0; RH_NextSpacerStart = 0; RH_isSqueezed = false; RH_IsFasta = false; } ~ReadHolder(void) { clear(); } void clear(void) { RH_Seq.clear(); RH_StartStops.clear(); RH_Header.clear(); RH_Rle.clear(); RH_Comment.clear(); RH_Qual.clear(); RH_NextSpacerStart = 0; RH_isSqueezed = false; RH_IsFasta = false; } //---- // Getters // inline std::string getComment(void) { return this->RH_Comment; } inline std::string getQual(void) { return this->RH_Qual; } inline bool getIsFasta(void) { return this->RH_IsFasta; } inline std::string getSeq(void) { return this->RH_Seq; } inline std::string getHeader(void) { return this->RH_Header; } inline std::string getSeqRle(void) { return this->RH_Rle; } inline bool getLowLexi(void) { return this->RH_WasLowLexi; } inline bool getSqueezed(void) { return this->RH_isSqueezed; } inline StartStopList getStartStopList(void) { return this->RH_StartStops; } inline int getLastDRPos(void) { return this->RH_LastDREnd; } inline int getLastSpacerPos(void) { return this->RH_NextSpacerStart; } inline int start() { return this->front(); } inline int getFirstRepeatStart() { return this->front(); } // return the second last element in the start stop list // which is equal to the start of the last repeat inline int getLastRepeatStart() { StartStopListIterator iter = RH_StartStops.end() - 2; return *iter; } inline unsigned int numRepeats() { return (unsigned int)(RH_StartStops.size()/2); } inline unsigned int numSpacers() { return numRepeats() - 1; } unsigned int front(void) { return RH_StartStops.front(); } unsigned int back(void) { return RH_StartStops.back(); } int getSeqLength(void) { return (int)RH_Seq.length(); } unsigned int getStartStopListSize(void) { return (int)RH_StartStops.size(); } inline unsigned int getRepeatLength() { return RH_RepeatLength; } inline char getSeqCharAt(int i) { return RH_Seq[i]; } unsigned int getRepeatAt(unsigned int i); std::string repeatStringAt(unsigned int i); std::string spacerStringAt(unsigned int i); unsigned int getAverageSpacerLength(void); void getAllSpacerStrings(std::vector& spacers); void getAllRepeatStrings(std::vector& repeats); int averageRepeatLength(void); //---- //setters // inline void setComment(std::string _comment) { RH_Comment = _comment; } inline void setQual(std::string _qual) { RH_Qual = _qual; RH_IsFasta = false; } inline void setSequence(std::string _sequence) { RH_RepeatLength = 0; RH_Seq = _sequence; } inline void setRepeatLength(int length) { RH_RepeatLength = length; } inline void incrementRepeatLength(void) { RH_RepeatLength++; } inline void decrementRepeatLength(void) { RH_RepeatLength--; } inline void setHeader(std::string h) { this->RH_Header = h; } inline void setDRLowLexi(bool b) { this->RH_WasLowLexi = b; } inline void setSqueezed(bool b) { this->RH_isSqueezed = b; } void setLastDRPos(int i) { this->RH_LastDREnd = i; } void setLastSpacerPos(int i) { this->RH_NextSpacerStart = i; } //---- // Element access to the start stop list // int startStopsAt(int i) { return this->RH_StartStops.at(i); } void startStopsAdd(unsigned int, unsigned int); void clearStartStops(void) { RH_StartStops.clear(); } void removeRepeat(unsigned int val); void dropPartials(void); void reverseStartStops(void); // fix start stops what got corrupted during revcomping // update the DR after finding the TRUE DR void updateStartStops(const int frontOffset, std::string * DR, const options * opts); // the positions are the start positions of the direct repeats // inline int repeatSpacing(unsigned int pos1, unsigned int pos2) { return (getRepeatAt(pos2) - getRepeatAt(pos1)); } StartStopListIterator begin(void) { return this->RH_StartStops.begin(); } StartStopListIterator end(void) { return this->RH_StartStops.end(); } unsigned int& operator[]( const unsigned int i) { return this->RH_StartStops[i]; } std::string substr(int i, int j) { return RH_Seq.substr(i, j); } std::string substr(int i) { return RH_Seq.substr(i); } std::string substr(unsigned int i, unsigned int j) { return RH_Seq.substr(i, j ); } std::string substr(unsigned int i) { return RH_Seq.substr(i); } std::string substr(size_t i, size_t j) { return RH_Seq.substr(i, j ); } std::string substr(size_t i) { return RH_Seq.substr(i); } std::string DRLowLexi(void); // Put the sequence in the form that makes the DR in it's laurenized form void reverseComplementSeq(void); // reverse complement the sequence and fix the start stops void encode(void); // transforms a sequence to a run length encoding form void decode (void); // transforms a sequence back to its original state std::string expand(void); // returns a copy of the string with homopolymers std::string expand(bool fixStopStarts); // returns a copy of the string with homopolymers (fixes stop starts) // cut DRs and Specers bool getFirstDR(std::string * retStr); bool getNextDR(std::string * retStr); bool getFirstSpacer(std::string * retStr); bool getNextSpacer(std::string * retStr); std::string toStringInColumns(void); std::string splitApart(void); std::string splitApartSimple(void); void printContents(void); void printContents(std::ostream& out); void logContents(int logLevel); inline std::ostream& print(std::ostream& s); private: // members std::string RH_Rle; // Run length encoded string std::string RH_Header; // Header for the sequence std::string RH_Comment; // The comment attribute of the sequence std::string RH_Qual; // The quality of the sequence bool RH_IsFasta; // boolean to tell us if the read is fastq or fasta std::string RH_Seq; // The DR_lowlexi sequence of this read bool RH_WasLowLexi; // was the sequence DR_low lexi in the file? StartStopList RH_StartStops; // start stops for DRs, (must be even in length!) bool RH_isSqueezed; // Bool to tell whether the read has homopolymers removed int RH_LastDREnd; // the end of the last DR cut (offset of the iterator) int RH_NextSpacerStart; // the end of the last spacer cut (offset of the iterator) int RH_RepeatLength; }; // overloaded operators std::ostream& operator<< (std::ostream& s, ReadHolder& c); #endif //ReadHolder_h ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/SmithWaterman.cpp",".cpp","8863","309","// File: SmithWaterman.cpp // Original Author: Connor Skennerton // -------------------------------------------------------------------- // // OVERVIEW: // // Modified smithwaterman implementation // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // -------------------------------------------------------------------- ////////////////////////////////////////////// // Simple Ends-Free Smith-Waterman Algorithm // // You will be prompted for input sequences // Penalties and match scores are hard-coded // // Program does not perform multiple tracebacks if // it finds several alignments with the same score // // By Nikhil Gopal // Similar implementation here: https://wiki.uni-koeln.de/biologicalphysics/index.php/Implementation_of_the_Smith-Waterman_local_alignment_algorithm ////////////////////////////////////////////// // system includes #include #include #include #include #include #include #include #include // local includes #include ""SmithWaterman.h"" #include ""SeqUtils.h"" #include ""LoggerSimp.h"" #include ""PatternMatcher.h"" #include ""Exception.h"" double findMax(double a, double b, double c, double d, int * index) { //----- // find the biggest out of these guys! // if all are equal it will return a // if(b > a) { if(c > d) { if(c > b) { *index = 2; return c; } else { *index = 1; return b; } } else { if(d > b) { *index = 3; return d; } else { *index = 1; return b; } } } else { if(c > d) { if(c > a) { *index = 2; return c; } else { *index = 0; return a; } } else { if(d > a) { *index = 3; return d; } else { *index = 0; return a; } } } } stringPair smithWaterman(std::string& seqA, std::string& seqB ) { //----- // The SW you've grown to know and love // int waste1, waste2; return smithWaterman(seqA, seqB, &waste1, &waste2, 0, (int)seqA.length(), 0); } stringPair smithWaterman(std::string& seqA, std::string& seqB, int * aStartAlign, int * aEndAlign, int aStartSearch, int aSearchLen) { //----- // Same as below but ignore similarity // return smithWaterman(seqA, seqB, aStartAlign, aEndAlign, aStartSearch, aSearchLen, 0); } stringPair smithWaterman(std::string& seqA, std::string& seqB, int * aStartAlign, int * aEndAlign, int aStartSearch, int aSearchLen, double similarity) { //----- // Trickle-ier verison of the original version of the smith waterman algorithm I found in this file // // This function is seqA centric, it will align ALL of seqB to the parts of seqA which lie INCLUSIVELY // between aStartSearch and aEndSearch. It will return the UNIMPUTED alignment strings for A and B respectively // in the stringPair variable AND it also stores the start and end indexes used to cut the seqA substring in the // two int references aStartAlign, aEndAlign // // Hoi! // // initialize some variables int length_seq_B = (int)seqB.length(); // initialize matrix double ** matrix = new double*[aSearchLen+1]; int ** I_i = new int*[aSearchLen+1]; int ** I_j = new int*[aSearchLen+1]; for(int i=0;i<=aSearchLen;i++) { double * tmp_mat = new double[length_seq_B+1]; int * tmp_i = new int[length_seq_B+1]; int * tmp_j = new int[length_seq_B+1]; matrix[i] = tmp_mat; I_i[i] = tmp_i; I_j[i] = tmp_j; for(int j=0;j<=length_seq_B;j++) { matrix[i][j]=0; } } //start populating matrix double matrix_max = -1; int i_max = 0, j_max = 0; for (int i=1;i<=aSearchLen;i++) { for(int j=1;j<=length_seq_B;j++) { int index = -1; matrix[i][j] = findMax( matrix[i-1][j-1] + SW_SIM_SCORE(seqA[i-1 + aStartSearch],seqB[j-1]), \ matrix[i-1][j] + SW_GAP, \ matrix[i][j-1] + SW_GAP, \ 0, \ &index ); if(matrix[i][j] > matrix_max) { matrix_max = matrix[i][j]; i_max = i; j_max = j; } switch(index) { case 0: I_i[i][j] = i-1; I_j[i][j] = j-1; break; case 1: I_i[i][j] = i-1; I_j[i][j] = j; break; case 2: I_i[i][j] = i; I_j[i][j] = j-1; break; case 3: I_i[i][j] = i; I_j[i][j] = j; break; default: throw crispr::exception( __FILE__, __LINE__, __PRETTY_FUNCTION__,""Index never set in findMax""); } } } int current_i = i_max; int current_j = j_max; int next_i = I_i[current_i][current_j]; int next_j = I_j[current_i][current_j]; while((next_j!=0) && (next_i!=0) && ((current_i!=next_i) || (current_j!=next_j))) { current_i = next_i; current_j = next_j; next_i = I_i[current_i][current_j]; next_j = I_j[current_i][current_j]; } // record the start and end of seqA current_i--; current_j--; if(0 > current_j) { current_j = 0; } if(0 > current_i) { current_i = 0; } *aStartAlign = current_i+ aStartSearch; *aEndAlign = (*aStartAlign) + i_max - current_i - 1; // we don't need these guys anymore for(int i=0;i<=aSearchLen;i++) { delete [] matrix[i]; delete [] I_i[i]; delete [] I_j[i]; } delete [] matrix; delete [] I_i; delete [] I_j; // calculate similarity and return substrings is need be std::string a_ret; std::string b_ret; try { a_ret = seqA.substr(current_i+ aStartSearch, i_max - current_i + aStartSearch); } catch (std::exception& e) { throw (crispr::exception( __FILE__, __LINE__, __PRETTY_FUNCTION__, e.what())); } try { b_ret = seqB.substr(current_j, j_max - current_j); } catch (std::exception& e) { throw (crispr::exception( __FILE__, __LINE__, __PRETTY_FUNCTION__, e.what())); } if(0 != similarity) { double similarity_ld = 1.0 - (PatternMatcher::levenstheinDistance(a_ret, b_ret) /(double)a_ret.length()); if(similarity_ld >= similarity) { return std::pair(a_ret, b_ret); } else { // no go joe *aStartAlign = 0; *aEndAlign = 0; return std::pair("""",""""); } } else { // just return the substrings return std::pair(a_ret, b_ret); } } ","C++" "CRISPR","ctSkennerton/crass","src/crass/DrawTool.cpp",".cpp","21714","545","// DrawTool.cpp // // Copyright (C) 2011 - Connor Skennerton // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #include ""DrawTool.h"" #include ""Exception.h"" #include ""CrisprGraph.h"" #include ""Utils.h"" #include ""config.h"" #include ""StlExt.h"" #include #include #include #include DrawTool::~DrawTool() { graphVector::iterator iter = DT_Graphs.begin(); while (iter != DT_Graphs.end()) { if ((*iter) != NULL) { delete *iter; *iter = NULL; } iter++; } gvFreeContext(DT_Gvc); } int DrawTool::processOptions (int argc, char ** argv) { try { int c; int index; static struct option long_options [] = { {""help"", no_argument, NULL, 'h'}, {""outfile"", required_argument, NULL, 'o'}, {""colour"",required_argument,NULL,'c'}, {""bins"", required_argument, NULL, 'b'}, {""format"", required_argument, NULL, 'f'}, {""algorithm"", required_argument, NULL, 'a'}, {""groups"", required_argument, NULL, 'g'}, {0,0,0,0} }; bool algo = false, outformat = false; while((c = getopt_long(argc, argv, ""hg:c:a:f:o:b:"", long_options, &index)) != -1) { switch(c) { case 'h': { drawUsage (); exit(1); break; } case 'g': { generateGroupsFromString (optarg); break; } case 'o': { DT_OutputFile = optarg; if (DT_OutputFile[DT_OutputFile.length() - 1] != '/') { DT_OutputFile += '/'; } // check if our output folder exists struct stat file_stats; if (0 != stat(DT_OutputFile.c_str(),&file_stats)) { recursiveMkdir(DT_OutputFile); } break; } case 'c': { if (!strcmp(optarg, ""red-blue"") ) { DT_ColourType = RED_BLUE; } else if (!strcmp(optarg, ""red-blue-green"")) { DT_ColourType = RED_BLUE_GREEN; } else if (!strcmp(optarg, ""blue-red"")) { DT_ColourType = BLUE_RED; } else if (!strcmp(optarg, ""green-blue-red"")) { DT_ColourType = GREEN_BLUE_RED; } else { throw crispr::input_exception(""Not a known color type""); } break; } case 'f': { DT_OutputFormat = optarg; outformat = true; break; } case 'a': { if (!strcmp(optarg, ""dot"") || !strcmp(optarg, ""neato"") || !strcmp(optarg, ""fdp"") || !strcmp(optarg, ""sfdp"") || !strcmp(optarg, ""twopi"") || !strcmp(optarg, ""circo"")) { DT_RenderingAlgorithm = optarg; } else { throw crispr::input_exception(""Not a known Graphviz rendering algorithm""); } algo = true; break; } case 'b': { int i; if (from_string(i, optarg, std::dec)) { if (i > 0) { DT_Bins = i; } else { throw crispr::input_exception(""The number of bins of colour must be greater than 0""); } } else { throw crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__,""could not convert string to int""); } break; } default: { drawUsage(); exit(1); break; } } } if (!(algo & outformat) ) { throw crispr::input_exception(""You must specify both -a and -f on the command line""); } } catch (crispr::input_exception& e) { std::cerr< vec; split ( str, vec, "",""); DT_Groups = vec; DT_Subset = true; } int DrawTool::processInputFile(const char * inputFile) { try { crispr::xml::parser xml_parser; xercesc::DOMDocument * input_doc_obj = xml_parser.setFileParser(inputFile); xercesc::DOMElement * root_elem = input_doc_obj->getDocumentElement(); if( !root_elem ) throw(crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""empty XML document"" )); // get the children for (xercesc::DOMElement * currentElement = root_elem->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { // is this a group element if (xercesc::XMLString::equals(currentElement->getTagName(), xml_parser.tag_Group())) { char * c_group_id = tc(currentElement->getAttribute(xml_parser.attr_Gid())); std::string group_id = c_group_id; if (DT_Subset) { // we only want some of the groups look at DT_Groups if (DT_Groups.find(group_id.substr(1)) != DT_Groups.end() ) { parseGroup(currentElement, xml_parser); } } else { parseGroup(currentElement, xml_parser); } xr(&c_group_id); } } } catch (crispr::xml_exception& e) { std::cerr<getAttribute(xmlParser.attr_Gid())); crispr::graph * current_graph = new crispr::graph(c_gid); xr(&c_gid); // change the max and min coverages back to their original values resetInitialLimits(); DT_Graphs.push_back(current_graph); for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Data())) { parseData(currentElement, xmlParser, current_graph); setColours(); } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Assembly())) { parseAssembly(currentElement, xmlParser, current_graph); } } char * c_file_prefix = tc(parentNode->getAttribute(xmlParser.attr_Gid())); std::string file_prefix = c_file_prefix; std::string file_name = file_prefix + ""."" + DT_OutputFormat; xr(&c_file_prefix); char * file_name_c = strdup(file_name.c_str()); layoutGraph(current_graph->getGraph(), DT_RenderingAlgorithm); renderGraphToFile(current_graph->getGraph(), DT_OutputFormat, file_name_c); freeLayout(current_graph->getGraph()); // free the duplicated string try { delete file_name_c; } catch (std::exception& e) { std::cerr<getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { /*if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Drs())) { // change the direct repeats parseDrs(currentElement, xmlParser); } else*/ if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Spacers())) { // change the spacers parseSpacers(currentElement, xmlParser, currentGraph); } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Flankers())) { // change the flankers parseFlankers(currentElement, xmlParser, currentGraph); } } } //void DrawTool::parseDrs(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser) //{ // xercesc::DOMNodeList * children = parentNode->getChildNodes(); // const XMLSize_t nodeCount = children->getLength(); // // // For all nodes, children of ""root"" in the XML tree. // for( XMLSize_t xx = 0; xx < nodeCount; ++xx ) { // xercesc::DOMNode * currentNode = children->item(xx); // if( currentNode->getNodeType() && currentNode->getNodeType() == xercesc::DOMNode::ELEMENT_NODE ) { // // Found node which is an Element. Re-cast node as element // xercesc::DOMElement* currentElement = dynamic_cast< xercesc::DOMElement* >( currentNode ); // if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.getDr())) { // // } // } // } //} void DrawTool::parseSpacers(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Spacer())) { char * node_name = tc(currentElement->getAttribute(xmlParser.attr_Spid())); Agnode_t * current_graphviz_node = currentGraph->addNode(node_name); char * shape = strdup(""shape""); char * circle = strdup(""circle""); currentGraph->setNodeAttribute(current_graphviz_node, shape, circle); delete shape; delete circle; char * c_spid = tc(currentElement->getAttribute(xmlParser.attr_Spid())); std::string spid = c_spid; if (currentElement->hasAttribute(xmlParser.attr_Cov())) { char * c_cov = tc(currentElement->getAttribute(xmlParser.attr_Cov())); double current_cov; if (from_string(current_cov, c_cov, std::dec)) { recalculateLimits(current_cov); DT_SpacerCoverage[spid] = std::pair(true,current_cov); } else { throw crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Unable to convert serialized coverage""); } xr(&c_cov); } else { DT_SpacerCoverage[spid] = std::pair(false,0); } xr(&c_spid); xr(&node_name); } } } void DrawTool::parseFlankers(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Flanker())) { char * c_flid = tc(currentElement->getAttribute(xmlParser.attr_Flid())); Agnode_t * current_graphviz_node = currentGraph->addNode(c_flid); char * shape = strdup(""shape""); char * shape_val = strdup(""diamond""); currentGraph->setNodeAttribute(current_graphviz_node, shape, shape_val); delete shape; delete shape_val; xr(&c_flid); } } } void DrawTool::parseAssembly(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Contig())) { char * c_contig_id = tc(currentElement->getAttribute(xmlParser.attr_Cid())); std::string contig_id = c_contig_id; parseContig(currentElement, xmlParser,currentGraph, contig_id); xr(&c_contig_id); } } } void DrawTool::parseContig(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph, std::string& contigId) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Cspacer())) { // get the node char * c_spid = tc(currentElement->getAttribute(xmlParser.attr_Spid())); Agnode_t * current_graphviz_node = currentGraph->addNode(c_spid); // find the coverage for this guy if it was set std::string cov_spid = c_spid; xr(&c_spid); if (DT_SpacerCoverage[cov_spid].first) { std::string color = DT_Rainbow.getColour(DT_SpacerCoverage[cov_spid].second); // fix things up for Graphviz char * color_for_graphviz = strdup(('#' + color).c_str()); // add in the colour attributes char * style = strdup(""style""); char * filled = strdup(""filled""); char * fillcolour = strdup(""fillcolor""); currentGraph->setNodeAttribute(current_graphviz_node, style, filled); currentGraph->setNodeAttribute(current_graphviz_node, fillcolour, color_for_graphviz ); delete style; delete filled; delete fillcolour; delete color_for_graphviz; } parseCSpacer(currentElement, xmlParser,currentGraph,current_graphviz_node,contigId); } } } void DrawTool::parseCSpacer(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph, Agnode_t * currentGraphvizNode, std::string& contigId) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { /* if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.getBspacers())) { parseLinkSpacers(currentElement, xmlParser,currentGraph,currentGraphvizNode, REVERSE,contigId); } else*/ if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Fspacers())) { parseLinkSpacers(currentElement, xmlParser,currentGraph,currentGraphvizNode, FORWARD,contigId); /*} else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.getBflankers())) { parseLinkFlankers(currentElement, xmlParser,currentGraph,currentGraphvizNode, REVERSE,contigId); */} else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Fflankers())) { parseLinkFlankers(currentElement, xmlParser,currentGraph,currentGraphvizNode, FORWARD,contigId); } } } void DrawTool::parseLinkSpacers(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph, Agnode_t * currentGraphvizNode, EDGE_DIRECTION edgeDirection, std::string& contigId) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { char * c_spid = tc(currentElement->getAttribute(xmlParser.attr_Spid())); Agnode_t * edge_node = currentGraph->addNode(c_spid); xr(&c_spid); if (edgeDirection == FORWARD) { currentGraph->addEdge(currentGraphvizNode, edge_node); } else { currentGraph->addEdge(edge_node, currentGraphvizNode); } } } void DrawTool::parseLinkFlankers(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph, Agnode_t * currentGraphvizNode, EDGE_DIRECTION edgeDirection, std::string& contigId) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { char * c_flid = tc( currentElement->getAttribute(xmlParser.attr_Flid())); Agnode_t * edge_node = currentGraph->addNode(c_flid); xr(&c_flid); if (edgeDirection == FORWARD) { currentGraph->addEdge(currentGraphvizNode, edge_node); } else { currentGraph->addEdge(edge_node, currentGraphvizNode); } } } int drawMain (int argc, char ** argv) { try { DrawTool dt; int opt_index = dt.processOptions (argc, argv); if (opt_index >= argc) { throw crispr::input_exception(""No input file provided"" ); } else { // get cracking and process that file return dt.processInputFile(argv[opt_index]); } } catch(crispr::input_exception& re) { std::cerr<. // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // -------------------------------------------------------------------- #ifndef __CRASSDEFINES_H #define __CRASSDEFINES_H #include #include #include ""Rainbow.h"" #include ""config.h"" // -------------------------------------------------------------------- // General Macros // -------------------------------------------------------------------- #define isNotDecimal(number) (number > 1.0 || number < 0.0) // -------------------------------------------------------------------- // SEARCH ALGORITHM PARAMETERS // -------------------------------------------------------------------- #define CRASS_DEF_MIN_SEARCH_WINDOW_LENGTH (6) #define CRASS_DEF_MAX_SEARCH_WINDOW_LENGTH (9) #define CRASS_DEF_OPTIMAL_SEARCH_WINDOW_LENGTH (8) #define CRASS_DEF_SCAN_LENGTH (30) #define CRASS_DEF_SCAN_CONFIDENCE (0.70) #define CRASS_DEF_TRIM_EXTEND_CONFIDENCE (0.5) // -------------------------------------------------------------------- // STRING LENGTH / MISMATCH / CLUSTER SIZE PARAMETERS // -------------------------------------------------------------------- #define CRASS_DEF_MAX_CLUSTER_SIZE_FOR_SW (30) // Maximum number of cluster reps we will all vs all sw for #define CRASS_DEF_MIN_SW_ALIGNMENT_RATIO (0.85) // SW alignments need to be this percentage of the original query to be considered real #define CRASS_DEF_SW_SEARCH_EXT (8) #define CRASS_DEF_KMER_SIZE (11) // length of the kmers used when clustering DR groups #define CRASS_DEF_K_CLUST_MIN (6) // number of shared kmers needed to group DR variants together #define CRASS_DEF_READ_COUNTER_LOGGER (100000) #define CRASS_DEF_MAX_READS_FOR_DECISION (1000) // HARD CODED PARAMS FOR FINDING TRUE DRs #define CRASS_DEF_MIN_CONS_ARRAY_LEN (1200) // minimum size of the consensus array #define CRASS_DEF_CONS_ARRAY_RL_MULTIPLIER (4) // find the cons array length by multiplying read length by this guy #define CRASS_DEF_CONS_ARRAY_START (0.5) // how far into the cons array to start placing reads #define CRASS_DEF_PERCENT_IN_ZONE_CUT_OFF (0.85) // amount that a DR must agrre with the existsing DR within a zone to be added #define CRASS_DEF_NUM_KMERS_4_MODE (5) // find the top XX occuring in the DR #define CRASS_DEF_NUM_KMERS_4_MODE_HALF (CRASS_DEF_NUM_KMERS_4_MODE - (CRASS_DEF_NUM_KMERS_4_MODE/2)) // Ceil of 50% of CRASS_DEF_NUM_KMERS_4_MODE #define CRASS_DEF_MIN_READ_DEPTH (2) // read depth used for consensus building #define CRASS_DEF_ZONE_EXT_CONS_CUT_OFF (0.55) // minimum identity to extend a DR from the ""zone"" outwards #define CRASS_DEF_COLLAPSED_CONS_CUT_OFF (0.75) // minimum identity to identify a potential collapsed cluster #define CRASS_DEF_COLLAPSED_THRESHOLD (0.30) // in the event that clustering has collapsed two DRs into one, this number is used to plait them apart #define CRASS_DEF_PARTIAL_SIM_CUT_OFF (0.85) // The similarity needed to exted into partial matches #define CRASS_DEF_MIN_PARTIAL_LENGTH (4) // The mininum length allowed for a partial direct repeat at the beginning or end of a read #define CRASS_DEF_MAX_SING_PATTERNS (5000) // the maximum number of patterns we'll search for in a single hit // -------------------------------------------------------------------- // HARD CODED PARAMS FOR DR FILTERING // -------------------------------------------------------------------- #define CRASS_DEF_LOW_COMPLEXITY_THRESHHOLD (0.75) #define CRASS_DEF_SPACER_OR_REPEAT_MAX_SIMILARITY (0.82) #define CRASS_DEF_SPACER_TO_SPACER_LENGTH_DIFF (12) #define CRASS_DEF_SPACER_TO_REPEAT_LENGTH_DIFF (30) #define CRASS_DEF_DEFAULT_MIN_NUM_REPEATS (2) #define CRASS_DEF_KMER_MAX_ABUNDANCE_CUTOFF (0.23) // DRs should NOT have kmers more abundant than this percentage! // -------------------------------------------------------------------- // FILE IO // -------------------------------------------------------------------- #define CRASS_DEF_FASTQ_FILENAME_MAX_LENGTH (1024) #define CRASS_DEF_DEF_KMER_LOOKUP_EXT ""crass_kmers.txt"" #define CRASS_DEF_DEF_PATTERN_LOOKUP_EXT ""crass_direct_repeats.txt"" #define CRASS_DEF_DEF_SPACER_LOOKUP_EXT ""crass_spacers.txt"" #define CRASS_DEF_CRISPR_EXT "".crispr"" // -------------------------------------------------------------------- // XML // -------------------------------------------------------------------- #define CRASS_DEF_CRISPR_HEADER ""\n\n"" #define CRASS_DEF_ROOT_ELEMENT ""crispr"" #define CRASS_DEF_XML_VERSION ""1.1"" #define CRASS_DEF_CRISPR_FOOTER ""\n"" // -------------------------------------------------------------------- // GRAPH BUILDING // -------------------------------------------------------------------- #define CRASS_DEF_NODE_KMER_SIZE (7) // size of the kmer that defines a crispr node #define CRASS_DEF_MAX_CLEANING (2) // the maximum length that a branch can be before it's cleaned #define CRASS_DEF_STDEV_SPACER_LENGTH (6.0) // the maximum standard deviation allowed in the length of spacers // after the true DR is found that is allowable before it is removed // -------------------------------------------------------------------- // USER OPTION STRUCTURE // -------------------------------------------------------------------- #define CRASS_DEF_STATS_REPORT false // should we create a stats report #define CRASS_DEF_STATS_REPORT_DELIM ""\t"" // delimiter string for stats report #define CRASS_DEF_OUTPUT_DIR ""./"" // default output directory #define CRASS_DEF_MIN_DR_SIZE (23) // minimum direct repeat size #define CRASS_DEF_MAX_DR_SIZE (47) // maximum direct repeat size #define CRASS_DEF_MIN_SPACER_SIZE (26) // minimum spacer size #define CRASS_DEF_MAX_SPACER_SIZE (50) // maximum spacer size #define CRASS_DEF_NUM_DR_ERRORS (0) // maxiumum allowable errors in direct repeat #define CRASS_DEF_COVCUTOFF (3) // minimum number of attached spacers that a group needs to have #ifdef DEBUG #define CRASS_DEF_MAX_LOGGING (10) #else #define CRASS_DEF_MAX_LOGGING (4) #endif #define CRASS_DEF_DEFAULT_LOGGING (1) #define CRASS_DEF_LOGTOSCREEN false // should we log to screen or to file #define CRASS_DEF_NUM_OF_BINS (-1) // the number of bins to create #define CRASS_DEF_GRAPH_COLOUR BLUE_RED // default colour scale for the graphs #define CRASS_DEF_SPACER_LONG_DESC false // use a long desc of the spacer in the output graph #define CRASS_DEF_SPACER_SHOW_SINGLES false // do not show singles by default typedef struct { int logLevel; // level of verbosity allowed in the log file bool reportStats; // print a starts report currently not used unsigned int lowDRsize; // the lower size limit for a direct repeat unsigned int highDRsize; // the upper size limit for a direct repeat unsigned int lowSpacerSize; // the lower limit for a spacer unsigned int highSpacerSize; // the upper size limit for a spacer std::string output_fastq; // the output directory for the output files std::string delim; // delimiter used in stats report currently not used int kmer_clust_size; // number of kmers needed to be shared to add to a cluser unsigned int searchWindowLength; // option 'w'used in long read search only unsigned int minNumRepeats; // option 'n'used in long read search only bool logToScreen; // log to std::cout rather than to the log file int coverageBins; // The number of bins of colours RB_TYPE graphColourType; // the colour type of the graph std::string layoutAlgorithm; // the graphviz layout algorithm to use bool longDescription; // print a long description for the final spacer graph bool showSingles; // print singletons when making the spacer graph int cNodeKmerLength; // length of the kmers making up a crisprnode #ifdef DEBUG bool noDebugGraph; // Even if DEBUG preprocessor macro is set do not produce debug graph files #endif #ifdef SEARCH_SINGLETON std::string searchChecker; // A file containing headers to reads that need to be tracked through crass #endif #ifdef RENDERING bool noRendering; // Even if RENDERING preprocessor macro is set do not produce any rendered images #endif int covCutoff; // The lower bounds of acceptable numbers of reads that a group can have } options; // -------------------------------------------------------------------- #endif // __CRASSDEFINES_H ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/Exception.h",".h","5579","192","/* * * Copyright (C) Connor Skennerton 2011 2012 * crisprtools is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * crisprtools is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #ifndef _EXCEPTION_H_ #define _EXCEPTION_H_ #include #include #include #include namespace crispr { class exception { public: // constructor exception(){} exception(const char * file, int line, const char * function ,const char * message) { std::stringstream ss; ss<<""[ERROR]: ""; ss<< message<. * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ // system includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include // local includes #include ""config.h"" #include ""crass.h"" #include ""crassDefines.h"" #include ""LoggerSimp.h"" #include ""WorkHorse.h"" #include ""Rainbow.h"" #include ""StlExt.h"" #include ""Exception.h"" #include ""SeqUtils.h"" //************************************** // user input + system //************************************** void usage(void) { std::cout<<""Compiler Options:""< Output a log file and set a log level [1 - ""< Output directory [default: .]""< Minimim length of the direct repeat""< Maximim length of the direct repeat""< Total number of direct repeats in a CRISPR for""< Minimim length of the spacer to search for [Default: ""< Maximim length of the spacer to search for [Default: ""< The length of the search window. Can only be""< A decimal number that represents the reduction in size of the spacer""< A decimal number that represents the reduction in size of the direct repeat""< Remove groups with less than x spacers [Default: ""< The number of the kmers that need to be""< Length of the kmers used to make crispr nodes [Default: ""< Graphviz layout algorithm to use for printing spacer graphs. The following are available:""< The number of colour bins for the output graph.""< Defines the range of colours to use for the output graph""< A file containing read headers that should be tracked through ""<layoutAlgorithm = optarg; } #else std::cerr<(opts->coverageBins, optarg, std::dec); if (opts->coverageBins < 1) { std::cerr<graphColourType = RED_BLUE; } else if(strcmp(optarg, ""read-blue-green"") == 0) { opts->graphColourType = RED_BLUE_GREEN; } else if(strcmp(optarg, ""blue-red"") == 0) { opts->graphColourType = BLUE_RED; } else if(strcmp(optarg, ""green-blue-red"") == 0) { opts->graphColourType = GREEN_BLUE_RED; } else { std::cerr<graphColourType = RED_BLUE; } break; case 'd': from_string(opts->lowDRsize, optarg, std::dec); if (opts->lowDRsize < 8) { std::cerr<lowDRsize<<"" changing to ""<lowDRsize = CRASS_DEF_MIN_DR_SIZE; } break; case 'D': from_string(opts->highDRsize, optarg, std::dec); break; case 'e': #ifdef DEBUG opts->noDebugGraph = true; #endif break; case 'f': from_string(opts->covCutoff, optarg, std::dec); break; case 'g': opts->logToScreen = true; break; case 'G': opts->showSingles= true; break; case 'h': versionInfo(); usage(); exit(0); break; case 'k': from_string(opts->kmer_clust_size, optarg, std::dec); if (opts->kmer_clust_size < 4) { std::cerr<kmer_clust_size = CRASS_DEF_K_CLUST_MIN; } break; case 'K': from_string(opts->cNodeKmerLength, optarg, std::dec); break; case 'l': from_string(opts->logLevel, optarg, std::dec); if(opts->logLevel > CRASS_DEF_MAX_LOGGING) { std::cerr<logLevel<logLevel = CRASS_DEF_MAX_LOGGING; } break; case 'L': opts->longDescription = true; break; case 'n': from_string(opts->minNumRepeats, optarg, std::dec); if (opts->minNumRepeats < 2) { std::cerr<output_fastq = optarg; // just in case the user put '.' or '..' or '~' as the output directory if (opts->output_fastq[opts->output_fastq.length() - 1] != '/') { opts->output_fastq += '/'; } // check if our output folder exists struct stat file_stats; if (0 != stat(opts->output_fastq.c_str(),&file_stats)) { RecursiveMkdir(opts->output_fastq); } // check that the directory is writable else if(access(optarg, W_OK)) { std::cerr<noRendering = true; #endif break; case 's': from_string(opts->lowSpacerSize, optarg, std::dec); if (opts->lowSpacerSize < 8) { std::cerr<lowSpacerSize<<"" changing to ""<lowSpacerSize = CRASS_DEF_MIN_SPACER_SIZE; } break; case 'S': from_string(opts->highSpacerSize, optarg, std::dec); break; case 'V': versionInfo(); exit(1); break; case 'w': from_string(opts->searchWindowLength, optarg, std::dec); if ((opts->searchWindowLength < CRASS_DEF_MIN_SEARCH_WINDOW_LENGTH) || (opts->searchWindowLength > CRASS_DEF_MAX_SEARCH_WINDOW_LENGTH)) { std::cerr<searchWindowLength<searchWindowLength = CRASS_DEF_OPTIMAL_SEARCH_WINDOW_LENGTH; } break; case 0: #ifdef SEARCH_SINGLETON if (strcmp(""searchChecker"", long_options[index].name) == 0) opts->searchChecker = optarg; #endif break; default: versionInfo(); usage(); exit(1); break; } } // Sanity checks for the high and low dr size if (opts->lowDRsize >= opts->highDRsize) { std::cerr<lowDRsize<<"" >= ""<highDRsize<<"")""<lowSpacerSize >= opts->highSpacerSize) { std::cerr<lowSpacerSize<<"" >= ""<highSpacerSize<<"")""<= argc) { std::cerr< seq_files; while (opt_idx < argc) { // std::string seq_file(argv[opt_idx]); seq_files.push_back(seq_file); opt_idx++; } logTimeStamp(); std::string cmd_line; for (int i = 0; i < argc; ++i) { cmd_line += argv[i]; cmd_line += ' '; } WorkHorse * mHorse = new WorkHorse(&opts, timestamp,cmd_line); try { #if SEARCH_SINGLETON debugger->headerFile(opts.searchChecker); debugger->processHeaderFile(); #endif /* SearchCheckerList::iterator debug_iter; for (debug_iter = debugger->begin(); debug_iter != debugger->end(); debug_iter++) { std::cout<first<doWork(seq_files); #ifdef SEARCH_SINGLETON delete debugger; #endif delete mHorse; return error_code; } catch (crispr::exception& e) { std::cerr<. // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // system includes #include #include #include #include #include #include #include #include #include #include #include #include #include ""StlExt.h"" #include ""Exception.h"" // local includes #include ""WorkHorse.h"" #include ""libcrispr.h"" #include ""LoggerSimp.h"" #include ""crassDefines.h"" #include ""NodeManager.h"" #include ""ReadHolder.h"" #include ""SeqUtils.h"" #include ""SmithWaterman.h"" #include ""StringCheck.h"" #include ""config.h"" #include ""ksw.h"" bool sortLengthDecending( const std::string& a, const std::string& b) { return a.length() > b.length(); } bool sortLengthAssending( const std::string& a, const std::string& b) { return a.length() < b.length(); } // a should be shorter than b if sorted correctly bool includeSubstring(const std::string& a, const std::string& b) { if (std::string::npos != b.find(a)) { return true; } else if(std::string::npos != b.find(reverseComplement(a))) { return true; } return false; } bool isNotEmpty(const std::string& a) { return !a.empty(); } WorkHorse::~WorkHorse() { // //----- // // destructor // // // clean up all the NodeManagers DR_ListIterator dr_iter = mDRs.begin(); while(dr_iter != mDRs.end()) { if(NULL != dr_iter->second) { delete dr_iter->second; dr_iter->second = NULL; } dr_iter++; } mDRs.clear(); // check to see none of these are floating around DR_Cluster_MapIterator drg_iter = mDR2GIDMap.begin(); while(drg_iter != mDR2GIDMap.end()) { if(drg_iter->second != NULL) { delete drg_iter->second; } drg_iter++; } // clear the reads! clearReadMap( &mReads); } void WorkHorse::clearReadList(ReadList * tmp_list) { //----- // clear all the reads from the readlist // ReadListIterator read_iter = tmp_list->begin(); while(read_iter != tmp_list->end()) { if(*read_iter != NULL) { delete *read_iter; *read_iter = NULL; } read_iter++; } tmp_list->clear(); } void WorkHorse::clearReadMap(ReadMap * tmp_map) { //----- // clear all the reads from the readlist // ReadMapIterator read_iter = tmp_map->begin(); while(read_iter != tmp_map->end()) { if (read_iter->second != NULL) { clearReadList(read_iter->second); delete read_iter->second; read_iter->second = NULL; } read_iter++; } tmp_map->clear(); } int WorkHorse::numOfReads(void) { int count = 0; ReadMapIterator read_iter = mReads.begin(); while(read_iter != mReads.end()) { if (read_iter->second != NULL) { count += (int)(read_iter->second)->size(); } read_iter++; } return count; } // do all the work! int WorkHorse::doWork(Vecstr seqFiles) { //----- // wrapper for the various processes needed to assemble crisprs // logInfo(""Parsing reads in "" << (seqFiles.size()) << "" files"", 1); if(parseSeqFiles(seqFiles)) { logError(""FATAL ERROR: parseSeqFiles failed""); return 2; } // build the spacer end graph if(buildGraph()) { logError(""FATAL ERROR: buildGraph failed""); return 3; } #ifdef SEARCH_SINGLETON std::ofstream debug_out; std::stringstream debug_out_file_name; debug_out_file_name <output_fastq<< ""crass.debug.""<begin(); debug_iter != debugger->end(); debug_iter++) { debug_out<first<<""\t""<second.gid()<<""\t""<second.truedr()<<""\t""; std::vector::iterator node_iter = debug_iter->second.begin(); if(node_iter != debug_iter->second.end()) { debug_out <<*node_iter; for ( node_iter++ ; node_iter != debug_iter->second.end(); node_iter++) { debug_out<<"":""<<*node_iter; } } debug_out<<""\t""; Vecstr::iterator sp_iter = debug_iter->second.beginSp(); if(sp_iter != debug_iter->second.endSp()) { debug_out<<*sp_iter; for ( sp_iter++ ; sp_iter != debug_iter->second.endSp(); sp_iter++) { debug_out<<"":""<<*sp_iter; } } debug_out<noDebugGraph) // this option will only exist if DEBUG is set anyway { // print debug graphs if(renderDebugGraphs()) { logError(""FATAL ERROR: renderDebugGraphs failed""); return 4; } } #endif // clean each spacer end graph if(cleanGraph()) { logError(""FATAL ERROR: cleanGraph failed""); return 5; } // make spacer graphs if(makeSpacerGraphs()) { logError(""FATAL ERROR: makeSpacerGraphs failed""); return 50; } // clean spacer graphs if(cleanSpacerGraphs()) { logError(""FATAL ERROR: cleanSpacerGraphs failed""); return 51; } // make contigs if(splitIntoContigs()) { logError(""FATAL ERROR: splitIntoContigs failed""); return 6; } // call flanking regions if (generateFlankers()) { logError(""FATAL ERROR: generateFlankers failed""); return 70; } //remove NodeManagers with low numbers of spacers // and where the standard deviation of the spacer length // is too high if (removeLowConfidenceNodeManagers()) { logError(""FATAL ERROR: removeLowSpacerNodeManagers failed""); return 7; } // print the reads to a file if requested // if(dumpReads(false)) // { // logError(""FATAL ERROR: dumpReads failed""); // return 9; // } #if DEBUG if (!mOpts->noDebugGraph) { // print clean graphs if(renderDebugGraphs(""Clean_"")) { logError(""FATAL ERROR: renderDebugGraphs failed""); return 10; } } #endif // print spacer graphs // if(renderSpacerGraphs()) // { // logError(""FATAL ERROR: renderSpacerGraphs failed""); // return 11; // } outputResults(); logInfo(""all done!"", 1); return 0; } int WorkHorse::parseSeqFiles(Vecstr seqFiles) { //----- // Load data from files and search for DRs // Vecstr::iterator seq_iter = seqFiles.begin(); // direct repeat sequence and unique ID lookupTable patterns_lookup; // the sequence of whole spacers and their unique ID lookupTable reads_found; time_t start_time; time(&start_time); while(seq_iter != seqFiles.end()) { logInfo(""Parsing file: "" << *seq_iter, 1); try { int max_len = searchFile(seq_iter->c_str(), *mOpts, &mReads, &mStringCheck, patterns_lookup, reads_found, start_time); mMaxReadLength = (max_len > mMaxReadLength) ? max_len : mMaxReadLength; logInfo(""Finished file: "" << *seq_iter, 1); } catch (crispr::exception& e) { std::cerr<c_str(), 1); } logInfo(""Finished file: "" << *seq_iter, 1); seq_iter++; } // add in a new line so the looger won't overlap itself std::cout<numOfReads(), 2); if (non_redundant_set->size() > 0) { std::cout<<""[""<size() << "" non-redundant patterns.""<c_str(), *mOpts, non_redundant_set, reads_found, &mReads, &mStringCheck, start_time); } catch (crispr::exception& e) { std::cerr<numOfReads(), 2); try { if (findConsensusDRs(group_kmer_counts_map, next_free_GID)) { logError(""Wierd stuff happend when trying to get the 'true' direct repeat""); return 1; } } catch(crispr::exception& e) { std::cerr< truedr_to_group; std::map::iterator iter = mTrueDRs.begin(); while(iter != mTrueDRs.end()) { std::map::iterator prev_iter = truedr_to_group.find(iter->second); if(prev_iter != truedr_to_group.end()) { // this true DR has already been identified logInfo(""Combining groups ""<first<<"" (""<second<<"") and ""<second << "" (""<first<<"") as they are identical"",4); // combine the DR2GID_map DR_ClusterIterator drc_iter; for(drc_iter = mDR2GIDMap[iter->first]->begin(); drc_iter != mDR2GIDMap[iter->first]->end(); ++drc_iter) { logInfo(*drc_iter, 1); mDR2GIDMap[prev_iter->second]->push_back(*drc_iter); } // delete the references to this group in DR2GID_map delete mDR2GIDMap[iter->first]; mDR2GIDMap.erase(iter->first); // remove the reference in the true DRs mTrueDRs.erase(iter++); } else { truedr_to_group[iter->second] = iter->first; ++iter; } } } int WorkHorse::buildGraph(void) { //----- // Load the spacers into a graph // // go through the DR2GID_map and make all reads in each group into nodes DR_Cluster_MapIterator drg_iter = mDR2GIDMap.begin(); //std::cout<<'['<second) { #ifdef DEBUG logInfo(""Creating NodeManager ""<first, 6); #endif //MI std::cout<<'['<first<<','<first]<first]] = new NodeManager(mTrueDRs[drg_iter->first], mOpts); //MI std::cout<<'.'<second)->begin(); while(drc_iter != (drg_iter->second)->end()) { // go through each read //MI std::cout<<'|'<begin(); while (read_iter != mReads[*drc_iter]->end()) { if(*read_iter == NULL) { logError(""Read is set to null""); } //MI std::cout<<'.'<find((*read_iter)->getHeader()); if (debug_iter != debugger->end()) { //found one of our interesting reads // add in the true DR debug_iter->second.truedr(mTrueDRs[drg_iter->first]); debug_iter->second.gid(drg_iter->first); } #endif mDRs[mTrueDRs[drg_iter->first]]->addReadHolder(*read_iter); read_iter++; } drc_iter++; } //MI std::cout<<""],""<second) { #ifdef DEBUG if (NULL == mDRs[mTrueDRs[drg_iter->first]]) { logWarn(""Before Clean Graph: NodeManager ""<first<<"" is NULL"",6); } else { #endif if((mDRs[mTrueDRs[drg_iter->first]])->cleanGraph()) { return 1; } #ifdef DEBUG } if (NULL == mDRs[mTrueDRs[drg_iter->first]]) { logWarn(""After Clean Graph: NodeManager ""<first<<"" is NULL"",6); } #endif } drg_iter++; } return 0; } int WorkHorse::removeLowConfidenceNodeManagers(void) { logInfo(""Removing CRISPRs with low numbers of spacers"", 1); int counter = 0; DR_Cluster_MapIterator drg_iter = mDR2GIDMap.begin(); while(drg_iter != mDR2GIDMap.end()) { if(NULL != drg_iter->second) { if (NULL != mDRs[mTrueDRs[drg_iter->first]]) { NodeManager * current_manager = mDRs[mTrueDRs[drg_iter->first]]; if( current_manager->getSpacerCountAndStats(false) < mOpts->covCutoff) { logInfo(""Deleting NodeManager ""<first<<"" as it contained less than ""<covCutoff<<"" attached spacers"",5); delete mDRs[mTrueDRs[drg_iter->first]]; mDRs[mTrueDRs[drg_iter->first]] = NULL; } else if (current_manager->stdevSpacerLength() > CRASS_DEF_STDEV_SPACER_LENGTH) { logInfo(""Deleting NodeManager ""<first<<"" as the stdev (""<stdevSpacerLength()<<"") of the spacer lengths was greater than ""<first]]; mDRs[mTrueDRs[drg_iter->first]] = NULL; } counter++; } } drg_iter++; } //std::cout<<'['<first]) { continue; } #ifdef DEBUG logInfo(__FILE__ <<"":""<<__LINE__<<"" checking for null ""<< mDR2GIDMap[group_count_iter->first], 6) #endif parseGroupedDRs(group_count_iter->first, &nextFreeGID); combineGroupsWithIdenticalDRs(); // delete the kmer count lists cause we're finsihed with them now if(NULL != group_count_iter->second) { delete group_count_iter->second; group_count_iter->second = NULL; } } return 0; } void WorkHorse::removeRedundantRepeats(Vecstr& repeatVector) { // given a vector of repeat sequences, will order the vector based on repeat // length and then remove longer repeats if there is a shorter one that is // a perfect substring std::sort(repeatVector.begin(), repeatVector.end(), sortLengthAssending); Vecstr::iterator iter; // go though all of the patterns and determine which are substrings // clear the string if it is for (iter = repeatVector.begin(); iter != repeatVector.end(); iter++) { if (iter->empty()) { continue; } Vecstr::iterator iter2; for (iter2 = iter+1; iter2 != repeatVector.end(); iter2++) { if (iter2->empty()) { continue; } //pass both itererators into the comparison function if (includeSubstring(*iter, *iter2)) { iter2->clear(); } } } // ok so now partition the vector so that all the empties are at one end // will return an iterator postion to the first position where the string // is empty Vecstr::iterator empty_iter = std::partition(repeatVector.begin(), repeatVector.end(), isNotEmpty); // remove all the empties from the list repeatVector.erase(empty_iter, repeatVector.end()); } Vecstr * WorkHorse::createNonRedundantSet(GroupKmerMap& groupKmerCountsMap, int& nextFreeGID) { // cluster the direct repeats then remove the redundant ones // creates a vector in dynamic memory, so don't forget to delete //----- // Cluster potential DRs and work out their true sequences // make the node managers while we're at it! // std::map k2GID_map; logInfo(""Reducing list of potential DRs (1): Initial clustering"", 1); logInfo(""Reticulating splines..."", 1); // go through all of the read holder objects ReadMapIterator read_map_iter = mReads.begin(); while (read_map_iter != mReads.end()) { clusterDRReads(read_map_iter->first, &nextFreeGID, &k2GID_map, &groupKmerCountsMap); ++read_map_iter; } std::cout<<'['<second)->begin(); if (dcg_iter->second != NULL) { logInfo(""-------------"", 4); logInfo(""Group: "" << dcg_iter->first, 4); Vecstr clustered_repeats; while(dc_iter != (dcg_iter->second)->end()) { std::string tmp = mStringCheck.getString(*dc_iter); clustered_repeats.push_back(tmp); logInfo(tmp, 4); dc_iter++; } logInfo(""-------------"", 4); removeRedundantRepeats(clustered_repeats); Vecstr::iterator cr_iter; Vecstr tmp_vec; for (cr_iter = clustered_repeats.begin(); cr_iter != clustered_repeats.end(); ++cr_iter) { tmp_vec.push_back(reverseComplement(*cr_iter)); } non_redundant_repeats->insert(non_redundant_repeats->end(), clustered_repeats.begin(), clustered_repeats.end()); non_redundant_repeats->insert(non_redundant_repeats->end(), tmp_vec.begin(), tmp_vec.end()); } dcg_iter++; } logInfo(""non-redundant patterns:"", 4); Vecstr::iterator nr_iter; for (nr_iter = non_redundant_repeats->begin(); nr_iter != non_redundant_repeats->end(); ++nr_iter) { logInfo(*nr_iter, 4); } logInfo(""-------------"", 4); return non_redundant_repeats; } bool WorkHorse::findMasterDR(int GID, StringToken& masterDRToken) { //----- // Identify a master DR // // Updates the values in masterDRToken and masterDRSequence and returns true // otherwise deletes the memory pointed at by clustered_DRs and returns false // // // this new version of the function needs only to find the longest DR in the list // so that all of the other DRs can be aligned against it. logInfo(""Identifying a master DR"", 1); DR_Cluster * current_dr_cluster = mDR2GIDMap[GID]; size_t current_longest_size = 0; DR_ClusterIterator dr_iter;// = dr_cluster->begin(); for (dr_iter = current_dr_cluster->begin(); dr_iter != current_dr_cluster->end(); ++dr_iter) { std::string tmp_dr_seq = mStringCheck.getString(*dr_iter); if (tmp_dr_seq.size() > current_longest_size) { masterDRToken = *dr_iter; current_longest_size = tmp_dr_seq.size(); } } if(masterDRToken == -1) { logError(""Could not identify a master DR""); } logInfo(""Identified: "" << mStringCheck.getString(masterDRToken) << "" ("" << masterDRToken << "") as a master potential DR"", 4); return true; } bool WorkHorse::populateCoverageArray(int GID, Aligner& drAligner) { //----- // Use the data structures initialised in parseGroupedDRs // Load all the reads into the consensus array // logInfo(""Populating consensus array"", 1); #ifdef DEBUG logInfo(__FILE__ <<"":""<<__LINE__<<"" checking for null ""<< mDR2GIDMap[GID], 6) #endif //++++++++++++++++++++++++++++++++++++++++++++++++ // now go thru all the other DRs in this group and add them into // the consensus array DR_ClusterIterator dr_iter;// = (mDR2GIDMap[GID])->begin(); for (dr_iter = (mDR2GIDMap[GID])->begin(); dr_iter != (mDR2GIDMap[GID])->end(); dr_iter++) { // we've already done the master DR if(drAligner.getMasterDrToken() == *dr_iter) { continue; } drAligner.alignSlave(*dr_iter); } // kill the unfounded ones dr_iter = (mDR2GIDMap[GID])->begin(); while (dr_iter != (mDR2GIDMap[GID])->end()) { if(drAligner.offsetFind(*dr_iter) != drAligner.offsetEnd()) { if(drAligner.offset(*dr_iter) == -1) { #ifdef DEBUG logInfo(""clearing unaligned slave ""<<*dr_iter, 6) #endif if (NULL != mReads[*dr_iter]) { clearReadList(mReads[*dr_iter]); mReads[*dr_iter] = NULL; dr_iter = mDR2GIDMap[GID]->erase(dr_iter); continue; } } } ++dr_iter; } return true; } std::string WorkHorse::calculateDRConsensus(int GID, Aligner& drAligner, int& nextFreeGID, int& collapsedPos, std::map& collapsedOptions, std::map& refinedDREnds ) { drAligner.generateConsensus(); // make the true DR and check for consistency std::string true_dr = """"; for (int i = drAligner.getDRZoneStart(); i <= drAligner.getDRZoneEnd(); i++) { #ifdef DEBUG logInfo(""Pos: "" << i << "" coverage: "" << drAligner.coverageAt(i, drAligner.consensusAt(i)) << "" conserved(%): "" << drAligner.conservationAt(i) << "" consensus: "" << drAligner.consensusAt(i), 1); #endif collapsedPos++; if(drAligner.conservationAt(i) >= CRASS_DEF_COLLAPSED_CONS_CUT_OFF) { refinedDREnds[i] = true; true_dr += drAligner.consensusAt(i); } else { // possible collapsed cluster refinedDREnds[i] = false; #ifdef DEBUG logInfo(""-------------"", 5); logInfo(""Possible collapsed cluster at position: "" << collapsedPos << "" ("" << (drAligner.getDRZoneStart() + collapsedPos) << "" || "" << drAligner.conservationAt(i) << "")"", 5); logInfo(""Base: Count: Cov:"",5); #endif float total_count = drAligner.depthAt(i); char alphabet[4] = {'A', 'C', 'G', 'T'}; for(int k = 0; k < 4; k++) { float nt_proportion = static_cast(drAligner.coverageAt(i, alphabet[k])/total_count); // check to make sure that each base is represented enough times if(nt_proportion >= CRASS_DEF_COLLAPSED_THRESHOLD) { #ifdef DEBUG logInfo("" "" << alphabet[k] << "" "" << drAligner.coverageAt(i, alphabet[k]) << "" "" << nt_proportion <<"" above threshold, added to colapsed options"", 5); #endif // there's enough bases here to warrant further investigation collapsedOptions[alphabet[k]] = (int)(collapsedOptions.size() + nextFreeGID); nextFreeGID++; } #ifdef DEBUG else { logInfo("" "" << alphabet[k] << "" "" << drAligner.coverageAt(i, alphabet[k]) << "" "" << nt_proportion <<"" below threshold"", 5); } #endif } // make sure we've got more than 1 option if(2 > collapsedOptions.size()) { collapsedOptions.clear(); #ifdef DEBUG logInfo("" ...ignoring (FA)"", 5); #endif true_dr += drAligner.consensusAt(i); refinedDREnds[i] = true; } else { // is this seen at the DR level? refinedDREnds[i] = false; std::map collapsed_options2; DR_ClusterIterator dr_iter = (mDR2GIDMap[GID])->begin(); while (dr_iter != (mDR2GIDMap[GID])->end()) { std::string tmp_DR = mStringCheck.getString(*dr_iter); if(-1 != drAligner.offset(*dr_iter)) { // check if the deciding character is within range of this DR // collapsed_pos + dr_zone_start gives the index in the ARRAY of the collapsed char // DR_offset_map[*dr_iter] gives the start of the DR in the array // We need to check that collapsed_pos + dr_zone_start >= DR_offset_map[*dr_iter] AND // that collapsed_pos < dr_zone_start - DR_offset_map[*dr_iter] + tmp_DR.length() //if(DR_offset_map[*dr_iter] <= dr_zone_start && dr_zone_start < (DR_offset_map[*dr_iter] + (int)(tmp_DR.length())) && collapsed_pos < (int)(tmp_DR.length())) if((collapsedPos + drAligner.getDRZoneStart() >= drAligner.offset(*dr_iter)) && (collapsedPos + drAligner.getDRZoneStart() - drAligner.offset(*dr_iter) < ((int)tmp_DR.length()))) { // this is easy, we can compare based on this char only char decision_char = tmp_DR[drAligner.getDRZoneStart() - drAligner.offset(*dr_iter) + collapsedPos]; collapsed_options2[decision_char] = collapsedOptions[decision_char]; } } else { logWarn(""No offset for DR: "" << tmp_DR, 1); } dr_iter++; } if(2 > collapsed_options2.size()) { // in the case that the DR is collapsing at the very end of the zone, // it may be because the spacers ahve a weird distribution of starting // bases. We need to check this out here... #ifdef DEBUG if(collapsedPos == 0) { logInfo("" ...ignoring (RLO SS)"", 5); } else if(collapsedPos + drAligner.getDRZoneStart() == drAligner.getDRZoneEnd()) { logInfo("" ...ignoring (RLO EE)"", 5); } else { logInfo("" ...ignoring (RLO KK)"", 5); } #endif true_dr += drAligner.consensusAt(i); refinedDREnds[i] = true; collapsedOptions.clear(); } else { // If it aint in collapsed_options2 it aint super fantastic! collapsedOptions.clear(); collapsedOptions = collapsed_options2; // make the collapsed pos array specific and exit this loop collapsedPos += drAligner.getDRZoneStart(); i = drAligner.getDRZoneEnd() + 1; } } } } logInfo(""Consensus DR: "" << true_dr, 1); return true_dr; } void WorkHorse::splitGroupedDR(std::map& collapsed_options, Aligner& dr_aligner, int collapsed_pos, int GID, int * nextFreeGID) { // We need to build a bit of new infrastructure. // assume we have K different DR alleles and N putative DRs // we need to build K new DR clusters logInfo(""Attempting to split the collapsed DR"", 5); std::map coll_char_to_GID_map; std::map::iterator co_iter = collapsed_options.begin(); while(co_iter != collapsed_options.end()) { int group = (*nextFreeGID)++; mDR2GIDMap[group] = new DR_Cluster; coll_char_to_GID_map[co_iter->first] = group; logInfo(""Mapping \""""<< co_iter->first << "" : "" << co_iter->second << ""\"" to group: "" << group << "" ""<< &mDR2GIDMap[group], 1); co_iter++; } DR_ClusterIterator dr_iter = (mDR2GIDMap[GID])->begin(); while (dr_iter != (mDR2GIDMap[GID])->end()) { std::string tmp_DR = mStringCheck.getString(*dr_iter); if(-1 != dr_aligner.offset(*dr_iter)) { // check if the deciding character is within range of this DR if(dr_aligner.offset(*dr_iter) <= collapsed_pos && collapsed_pos < (dr_aligner.offset(*dr_iter) + (int)(tmp_DR.length()))) { logInfo(""\tdeciding character within DR ""<< *dr_iter,5); // this is easy, we can compare based on this char only char decision_char = tmp_DR[collapsed_pos - dr_aligner.offset(*dr_iter)]; (mDR2GIDMap[ coll_char_to_GID_map[ decision_char ] ])->push_back(*dr_iter); } else { logInfo(""\tRebuilding cluster from the ground up for DR "" << *dr_iter,5); // this is tricky, we need to completely break the group and re-cluster // from the ground up based on reads // get the offset from the start of the DR to the deciding char // if it is negative, the dec char lies before the DR // otherwise it lies after int dec_diff = collapsed_pos - dr_aligner.offset(*dr_iter); logInfo(""\t\tBuilding form map"",5); // we're not guaranteed to see all forms. So we need to be careful here... // First we go through just to count the forms std::map forms_map; ReadListIterator read_iter = mReads[*dr_iter]->begin(); while (read_iter != mReads[*dr_iter]->end()) { StartStopListIterator ss_iter = (*read_iter)->begin(); while(ss_iter != (*read_iter)->end()) { int within_read_dec_pos = *ss_iter + dec_diff; if(within_read_dec_pos > 0 && within_read_dec_pos < (int)(*read_iter)->getSeqLength()) { char decision_char = (*read_iter)->getSeqCharAt(within_read_dec_pos); // it must be one of the collapsed options! if(collapsed_options.find(decision_char) != collapsed_options.end()) { forms_map[decision_char] = NULL; break; } } ss_iter+=2; } read_iter++; } // the size of forms_map tells us how many different types we actually saw. switch(forms_map.size()) { case 1: { logInfo(""\t\tOne form found"", 5); // we can just reuse the existing ReadList! // find out which group this bozo is in read_iter = mReads[*dr_iter]->begin(); bool break_out = false; while (read_iter != mReads[*dr_iter]->end()) { StartStopListIterator ss_iter = (*read_iter)->begin(); while(ss_iter != (*read_iter)->end()) { int within_read_dec_pos = *ss_iter + dec_diff; if(within_read_dec_pos > 0 && within_read_dec_pos < (int)(*read_iter)->getSeqLength()) { char decision_char = (*read_iter)->getSeqCharAt(within_read_dec_pos); // it must be one of the collapsed options! if(forms_map.find(decision_char) != forms_map.end()) { (mDR2GIDMap[ coll_char_to_GID_map[ decision_char ] ])->push_back(*dr_iter); break_out = true; break; } } ss_iter+=2; } read_iter++; if(break_out) break; } break; } case 0: { // Something is wrong! logWarn(""\t\tNo reads fit the form: "" << tmp_DR, 1); if(NULL != mReads[*dr_iter]) { clearReadList(mReads[*dr_iter]); delete mReads[*dr_iter]; mReads[*dr_iter] = NULL; } break; } default: { // we need to make a couple of new readlists and nuke the old one. // first make the new readlists logInfo(""\t\tMultiple forms, splitting reads"", 5); std::map::iterator fm_iter = forms_map.begin(); while(fm_iter != forms_map.end()) { StringToken st = mStringCheck.addString(tmp_DR); mReads[st] = new ReadList(); // make sure we know which readlist is which forms_map[fm_iter->first] = mReads[st]; // put the new dr_token into the right cluster (mDR2GIDMap[ coll_char_to_GID_map[ fm_iter->first ] ])->push_back(st); // next! fm_iter++; } // put the correct reads on the correct readlist read_iter = mReads[*dr_iter]->begin(); while (read_iter != mReads[*dr_iter]->end()) { StartStopListIterator ss_iter = (*read_iter)->begin(); while(ss_iter != (*read_iter)->end()) { int within_read_dec_pos = *ss_iter + dec_diff; if(within_read_dec_pos > 0 && within_read_dec_pos < (int)(*read_iter)->getSeqLength()) { char decision_char = (*read_iter)->getSeqCharAt(within_read_dec_pos); // needs to be a form we've seen before! if(forms_map.find(decision_char) != forms_map.end()) { // push this readholder onto the correct list (forms_map[decision_char])->push_back(*read_iter); // make the original pointer point to NULL so we don't delete twice *read_iter = NULL; break; } } ss_iter+=2; } read_iter++; } // nuke the old readlist if(NULL != mReads[*dr_iter]) { clearReadList(mReads[*dr_iter]); delete mReads[*dr_iter]; mReads[*dr_iter] = NULL; } break; } } } } dr_iter++; } // time to delete the old clustered DRs and the group from the DR2GID_map logInfo(""\tRemoving original group ""<< GID, 5); cleanGroup(GID); logInfo(""\tCalling the parser recursively"", 4); // call this baby recursively with the new clusters std::map::iterator cc_iter = coll_char_to_GID_map.begin(); while(cc_iter != coll_char_to_GID_map.end()) { parseGroupedDRs(cc_iter->second, nextFreeGID); cc_iter++; } } bool WorkHorse::parseGroupedDRs(int GID, int * nextFreeGID) { //----- // Cluster refinement and possible splitting for a Group ID // logInfo(""Parsing group: "" << GID, 4); // std::stringstream outfile; // outfile <output_fastq<<""debug_gid_""<begin(); drc_iter != mDR2GIDMap[GID]->end(); drc_iter++) { // ReadListIterator read_iter; // for (read_iter = mReads[*drc_iter]->begin(); read_iter != mReads[*drc_iter]->end(); read_iter++) { // outstream << *(*read_iter)< collapsed_options; // holds the chars we need to split on std::map refined_DR_ends; // so we can update DR ends based on consensus std::string true_DR = calculateDRConsensus(GID, dr_aligner, *nextFreeGID, collapsed_pos, collapsed_options, refined_DR_ends); // check to make sure that the DR is not just some random long RE if((unsigned int)(true_DR.length()) > mOpts->highDRsize) { cleanGroup(GID); logInfo(""Killed: {"" << true_DR << ""} cause' it was too long"", 1); return false; } if (collapsed_options.size() == 0) { if((unsigned int)(true_DR.length()) < mOpts->lowDRsize) { cleanGroup(GID); logInfo(""Killed: {"" << true_DR << ""} cause' the consensus was too short... ("" << true_DR.length() << "" ,"" << collapsed_options.size() << "")"", 1); return false; } // QC the DR again for low complexity if (isRepeatLowComplexity(true_DR)) { cleanGroup(GID); logInfo(""Killed: {"" << true_DR << ""} cause' the consensus was low complexity..."", 1); return false; } // test our true DR for highly abundant kmers try { float max_frequency; if (drHasHighlyAbundantKmers(true_DR, max_frequency) ) { cleanGroup(GID); logInfo(""Killed: {"" << true_DR << ""} cause' the consensus contained highly abundant kmers: ""< ""<< CRASS_DEF_KMER_MAX_ABUNDANCE_CUTOFF, 1); return false; } } catch (crispr::exception& e) { std::cerr< 0) { splitGroupedDR(collapsed_options, dr_aligner, collapsed_pos, GID, nextFreeGID); } else { //++++++++++++++++++++++++++++++++++++++++++++++++ // repair all the startstops for each read in this group // // This function is recursive, so we'll only get here when we have found exactly one DR // make sure that the true DR is in its laurenized form std::string laurenized_true_dr = laurenize(true_DR); bool rev_comp = (laurenized_true_dr != true_DR) ? true : false; logInfo(""Found DR: "" << laurenized_true_dr, 2); mTrueDRs[GID] = laurenized_true_dr; logInfo(""group: ""<< GID<< "" associated:"" << &mDR2GIDMap[GID], 5); DR_ClusterIterator drc_iter = (mDR2GIDMap[GID])->begin(); while(drc_iter != (mDR2GIDMap[GID])->end()) { logInfo(""\tRepeat: ""<<*drc_iter, 5); if(dr_aligner.offsetFind(*drc_iter) == dr_aligner.offsetEnd()) { logError(""1: Repeat ""<< *drc_iter<<"" in Group ""<begin(); while (read_iter != mReads[*drc_iter]->end()) { //if ((dr_aligner.offset(*drc_iter) - dr_aligner.getDRZoneStart()) < 0) { // // std::stringstream ss; // std::cerr << ""front offset is a negative number\ndr_aligner.offset=""<updateStartStops((dr_aligner.offset(*drc_iter) - dr_aligner.getDRZoneStart()), &true_DR, mOpts); } catch (crispr::exception &e) { std::cerr <begin(); drc_iter != (mDR2GIDMap[GID])->end(); drc_iter++) { for (read_iter = mReads[*drc_iter]->begin(); read_iter != mReads[*drc_iter]->end(); read_iter++) { logInfoNoPrefix( *(*read_iter), 1); } } throw e; } // reverse complement sequence if the true DR is not in its laurenized form if (rev_comp) { try { (*read_iter)->reverseComplementSeq(); } catch (crispr::exception& e) { std::cerr<begin(); size_t number_of_reads_in_group = 0; while (grouped_drs_iter != currentGroup->end()) { number_of_reads_in_group += mReads[*grouped_drs_iter]->size(); ++grouped_drs_iter; } return (int)number_of_reads_in_group; } bool WorkHorse::clusterDRReads(StringToken DRToken, int * nextFreeGID, std::map * k2GIDMap, GroupKmerMap * groupKmerCountsMap) { //----- // hash a DR! // std::string DR = mStringCheck.getString(DRToken); int str_len = (int)DR.length(); int off = str_len - CRASS_DEF_KMER_SIZE; int num_mers = off + 1; //*************************************** //*************************************** //*************************************** //*************************************** // LOOK AT ME! // // Here we declare the minimum criteria for membership when clustering // this is not cool! int min_clust_membership_count = mOpts->kmer_clust_size; // //*************************************** //*************************************** //*************************************** //*************************************** // STOLED FROM SaSSY!!!! // First we cut kmers from the sequence then we use these to // determine overlaps, finally we make edges // // When we cut kmers from a read it is like this... // // XXXXXXXXXXXXXXXXXXXXXXXXXXXXXX // ------------------------------ // XXXXXXXXXXXXXXXXXXXXXXXXXX // XXXXXXXXXXXXXXXXXXXXXXXXXX // XXXXXXXXXXXXXXXXXXXXXXXXXX // XXXXXXXXXXXXXXXXXXXXXXXXXX // XXXXXXXXXXXXXXXXXXXXXXXXXX // // so we break the job into three parts // // XXXX|XXXXXXXXXXXXXXXXXXXXXX|XXXX // ----|----------------------|---- // XXXX|XXXXXXXXXXXXXXXXXXXXXX| // XXX|XXXXXXXXXXXXXXXXXXXXXX|X // XX|XXXXXXXXXXXXXXXXXXXXXX|XX // X|XXXXXXXXXXXXXXXXXXXXXX|XXX // |XXXXXXXXXXXXXXXXXXXXXX|XXXX // // the first and last part may be a little slow but the middle part can fly through... // // make a 2d array for the kmers! char ** kmers = NULL; int * kmer_offsets = NULL; try { kmers = new char*[num_mers]; } catch(std::exception& e) { std::cerr<<""Attempting to alloc ""<= j) { kmers[j][kmer_offsets[j]] = DR[pos_counter]; } kmer_offsets[j]++; } pos_counter++; } // this is the fast part of the loop while(pos_counter < off) { for(int j = 0; j < num_mers; j++) { if(kmer_offsets[j] >= 0 && kmer_offsets[j] < CRASS_DEF_KMER_SIZE) { kmers[j][kmer_offsets[j]] = DR[pos_counter]; } kmer_offsets[j]++; } pos_counter++; } // an even slower ending while(pos_counter < str_len) { for(int j = 0; j < num_mers; j++) { if(kmer_offsets[j] < CRASS_DEF_KMER_SIZE) { kmers[j][kmer_offsets[j]] = DR[pos_counter]; } kmer_offsets[j]++; } pos_counter++; } // // Now the fun stuff begins: // Vecstr homeless_kmers; std::map group_count; std::map local_kmer_CountMap; int group = 0; for(int i = 0; i < num_mers; ++i) { // make it a string! kmers[i][CRASS_DEF_KMER_SIZE] = '\0'; std::string tmp_str(kmers[i]); tmp_str = laurenize(tmp_str); // see if this guy has been counted LOCALLY // use this list when we go to select N most abundant kmers if(local_kmer_CountMap.find(tmp_str) == local_kmer_CountMap.end()) { // first time this kmer has been seen in this read local_kmer_CountMap[tmp_str] = 1; } else { local_kmer_CountMap[tmp_str]++; } // see if we've seen this kmer before GLOBALLY std::map::iterator k2g_iter = k2GIDMap->find(tmp_str); if(k2g_iter == k2GIDMap->end()) { // first time we seen this one GLOBALLY homeless_kmers.push_back(tmp_str); } else { // we've seen this guy before. // only do this if our guy doesn't belong to a group yet if(0 == group) { // this kmer belongs to a group -> increment the local group count std::map::iterator this_group_iter = group_count.find(k2g_iter->second); if(this_group_iter == group_count.end()) { group_count[k2g_iter->second] = 1; } else { group_count[k2g_iter->second]++; // have we seen this guy enought times? if(min_clust_membership_count <= group_count[k2g_iter->second]) { // we have found a group for this mofo! group = k2g_iter->second; } } } } } if(0 == group) { // we couldn't put our guy into a group group = (*nextFreeGID)++; // we need to make a new entry in the group map mGroupMap[group] = true; mDR2GIDMap[group] = new DR_Cluster; // we need a new kmer counter for this group (*groupKmerCountsMap)[group] = new std::map; } // we need to record the group for this mofo! mDR2GIDMap[group]->push_back(DRToken); // we need to assign all homeless kmers to the group! Vecstr::iterator homeless_iter = homeless_kmers.begin(); while(homeless_iter != homeless_kmers.end()) { (*k2GIDMap)[*homeless_iter] = group; homeless_iter++; } // we need to fix up the group counts std::map::iterator local_count_iter = local_kmer_CountMap.begin(); while(local_count_iter != local_kmer_CountMap.end()) { (*(*groupKmerCountsMap)[group])[local_count_iter->first] += local_count_iter->second; local_count_iter++; } // clean up delete [] kmer_offsets; for(int i = 0; i < num_mers; i++) { delete [] kmers[i]; } delete [] kmers; return true; } //************************************** // spacer graphs //************************************** int WorkHorse::makeSpacerGraphs(void) { //----- // build the spacer graphs // // go through the DR2GID_map and make all reads in each group into nodes DR_ListIterator dr_iter = mDRs.begin(); while(dr_iter != mDRs.end()) { if(NULL != dr_iter->second) { logInfo(""Making spacer graph for DR: "" << dr_iter->first, 1); if((dr_iter->second)->buildSpacerGraph()) return 1; } dr_iter++; } return 0; } int WorkHorse::cleanSpacerGraphs(void) { //----- // clean the spacer graphs // // go through the DR2GID_map and make all reads in each group into nodes #ifdef DEBUG //renderSpacerGraphs(""Spacer_Preclean_""); #endif DR_ListIterator dr_iter = mDRs.begin(); while(dr_iter != mDRs.end()) { if(NULL != dr_iter->second) { logInfo(""Cleaning spacer graph for DR: "" << dr_iter->first, 1); //(dr_iter->second)->printAllSpacers(); if((dr_iter->second)->cleanSpacerGraph()) return 1; } dr_iter++; } return 0; } int WorkHorse::generateFlankers(void) { //----- // Wrapper for graph cleaning // // create a spacer dictionary logInfo(""Detecting Flanker sequences"", 1); DR_Cluster_MapIterator drg_iter = mDR2GIDMap.begin(); while(drg_iter != mDR2GIDMap.end()) { if(NULL != drg_iter->second) { if (NULL != mDRs[mTrueDRs[drg_iter->first]]) { logInfo(""Assigning flankers for NodeManager ""<first, 3); (mDRs[mTrueDRs[drg_iter->first]])->generateFlankers(); } } drg_iter++; } return 0; } //************************************** // contig making //************************************** int WorkHorse::splitIntoContigs(void) { //----- // split all groups into contigs // DR_ListIterator dr_iter = mDRs.begin(); while(dr_iter != mDRs.end()) { if(NULL != dr_iter->second) { logInfo(""Making spacer contigs for DR: "" << dr_iter->first, 1); if((dr_iter->second)->splitIntoContigs()) return 1; } dr_iter++; } return 0; } //************************************** // file IO //************************************** int WorkHorse::renderDebugGraphs(void) { //----- // Print the debug graph // // use the default name return renderDebugGraphs(""Group_""); } int WorkHorse::renderDebugGraphs(std::string namePrefix) { //----- // Print the debug graph // // go through the DR2GID_map and make all reads in each group into nodes #ifdef RENDERING std::cout<<""[""<second) { if (NULL != mDRs[mTrueDRs[drg_iter->first]]) { std::ofstream graph_file; std::string graph_file_prefix = mOpts->output_fastq + namePrefix + to_string(drg_iter->first) + ""_"" + mTrueDRs[drg_iter->first]; std::string graph_file_name = graph_file_prefix + ""_debug.gv""; graph_file.open(graph_file_name.c_str()); if (graph_file.good()) { mDRs[mTrueDRs[drg_iter->first]]->printDebugGraph(graph_file, mTrueDRs[drg_iter->first], false, false, false); #if RENDERING if (!mOpts->noRendering) { // create a command string and call neato to make the image file std::cout<<""[""<first< ""+ graph_file_prefix + "".eps""; if (system(cmd.c_str())) { logError(""Problem running neato when rendering debug graphs""); } } #endif } else { logError(""Unable to create graph output file ""<output_fastq<second) { if(NULL != mDRs[mTrueDRs[drg_iter->first]]) { NodeManager * current_manager = mDRs[mTrueDRs[drg_iter->first]]; std::ofstream graph_file; std::string graph_file_prefix = mOpts->output_fastq + namePrefix + to_string(drg_iter->first) + ""_"" + mTrueDRs[drg_iter->first]; std::string graph_file_name = graph_file_prefix + ""_spacers.gv""; // check to see if there is anything to print if ( current_manager->printSpacerGraph(graph_file_name, mTrueDRs[drg_iter->first], mOpts->longDescription, mOpts->showSingles)) { // add our group to the key current_manager->printSpacerKey(key_file, 10, namePrefix + to_string(drg_iter->first)); // output the reads std::string read_file_name = mOpts->output_fastq + ""Group_"" + to_string(drg_iter->first) + ""_"" + mTrueDRs[drg_iter->first] + "".fa""; this->dumpReads(current_manager, read_file_name); } else { // should delete this guy since there are no spacers // this way the group will not be in the xml either delete mDRs[mTrueDRs[drg_iter->first]]; mDRs[mTrueDRs[drg_iter->first]] = NULL; } #if RENDERING if (!mOpts->noRendering) { // create a command string and call graphviz to make the image file std::cout<<""[""<first<layoutAlgorithm + "" -Teps "" + graph_file_name + "" > ""+ graph_file_prefix + "".eps""; if(system(cmd.c_str())) { logError(""Problem running ""<layoutAlgorithm<<"" when rendering spacer graphs""); return 1; } } #endif } } drg_iter++; } gvGraphFooter(key_file); key_file.close(); return 0; } int WorkHorse::checkFileOrError(const char * fileName) { // Test to see if the file is ok. struct stat inputDirStatus; int xStat = stat(fileName, &inputDirStatus); // stat failed if (xStat == -1) { return errno; } return 0; } bool WorkHorse::outputResults(std::string namePrefix) { //----- // Print the cleaned? spacer graph, reads and the XML // #ifdef RENDERING if(! mOpts->noRendering) { std::cout<<""[""<output_fastq<createDOMDocument(CRASS_DEF_ROOT_ELEMENT, CRASS_DEF_XML_VERSION, error_num); if (!root_element && error_num) { delete xml_doc; throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Unable to create xml document""); } // go through the node managers and print the group info // print all the inside information int final_out_number = 0; DR_Cluster_MapIterator drg_iter = mDR2GIDMap.begin(); for (drg_iter = mDR2GIDMap.begin(); drg_iter != mDR2GIDMap.end(); drg_iter++) { // make sure that our cluster is real if (drg_iter->second == NULL) { continue; } if(NULL == mDRs[mTrueDRs[drg_iter->first]]) { continue; } NodeManager * current_manager = mDRs[mTrueDRs[drg_iter->first]]; std::ofstream graph_file; std::string graph_file_prefix = mOpts->output_fastq + ""Spacers_"" + to_string(drg_iter->first) + ""_"" + mTrueDRs[drg_iter->first]; std::string graph_file_name = graph_file_prefix + ""_spacers.gv""; // check to see if there is anything to print if ( current_manager->printSpacerGraph(graph_file_name, mTrueDRs[drg_iter->first], mOpts->longDescription, mOpts->showSingles)) { #ifdef RENDERING if (!mOpts->noRendering) { // create a command string and call graphviz to make the image file std::cout<<""[""<first<layoutAlgorithm + "" -Teps "" + graph_file_name + "" > ""+ graph_file_prefix + "".eps""; if(system(cmd.c_str())) { logError(""Problem running ""<layoutAlgorithm<<"" when rendering spacer graphs""); return 1; } } #endif // add our group to the key current_manager->printSpacerKey(key_file, 10, namePrefix + to_string(drg_iter->first)); // output the reads std::string read_file_name = mOpts->output_fastq + ""Group_"" + to_string(drg_iter->first) + ""_"" + mTrueDRs[drg_iter->first] + "".fa""; this->dumpReads(current_manager, read_file_name, true); /* * Output the xml data to crass.crispr */ std::string gid_as_string = ""G"" + to_string(drg_iter->first); final_out_number++; xercesc::DOMElement * group_elem = xml_doc->addGroup(gid_as_string, mTrueDRs[drg_iter->first], root_element); /* * section */ this->addDataToDOM(xml_doc, group_elem, drg_iter->first); /* * section */ this->addMetadataToDOM(xml_doc, group_elem, drg_iter->first); /* * section */ xercesc::DOMElement * assem_elem = xml_doc->addAssembly(group_elem); current_manager->printAssemblyToDOM(xml_doc, assem_elem, false); } else { // should delete this guy since there are no spacers delete mDRs[mTrueDRs[drg_iter->first]]; mDRs[mTrueDRs[drg_iter->first]] = NULL; } } std::cout<<""[""<printDOMToFile(namePrefix); delete xml_doc; gvGraphFooter(key_file); key_file.close(); return 0; } bool WorkHorse::addDataToDOM(crispr::xml::writer * xmlDoc, xercesc::DOMElement * groupElement, int groupNumber) { try { xercesc::DOMElement * data_elem = xmlDoc->addData(groupElement); if ((mDRs[mTrueDRs[groupNumber]])->haveAnyFlankers()) { xmlDoc->createFlankers(data_elem); } xercesc::DOMElement * sources_tag = data_elem->getFirstElementChild(); std::set all_sources; for (xercesc::DOMElement * currentElement = data_elem->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if( xercesc::XMLString::equals(currentElement->getTagName(), xmlDoc->tag_Drs())) { // TODO: current implementation in Crass only supports a single DR for a group // in the future this will change, but for now ok to keep as a constant std::string drid = ""DR1""; xmlDoc->addDirectRepeat(drid, mTrueDRs[groupNumber], currentElement); } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlDoc->tag_Spacers())) { // print out all the spacers for this group (mDRs[mTrueDRs[groupNumber]])->addSpacersToDOM(xmlDoc, currentElement, false, all_sources); } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlDoc->tag_Flankers())) { // should only get in here if there are flankers for the group // print out all the flankers for this group (mDRs[mTrueDRs[groupNumber]])->addFlankersToDOM(xmlDoc, currentElement, false, all_sources); } } (mDRs[mTrueDRs[groupNumber]])->generateAllsourceTags(xmlDoc, all_sources, sources_tag); } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::ostringstream errBuf; errBuf << ""Error parsing file: "" << message << std::flush; xercesc::XMLString::release( &message ); return 1; } return 0; } bool WorkHorse::addMetadataToDOM(crispr::xml::writer * xmlDoc, xercesc::DOMElement * groupElement, int groupNumber) { try { std::stringstream notes; notes << ""Run on ""<< mTimeStamp; xercesc::DOMElement * metadata_elem = xmlDoc->addMetaData(groupElement); xercesc::DOMElement * prog_elem = xmlDoc->addProgram(metadata_elem); xmlDoc->addProgName(PACKAGE_NAME, prog_elem); xmlDoc->addProgVersion(PACKAGE_VERSION, prog_elem); xmlDoc->addProgCommand(mCommandLine, prog_elem); xmlDoc->addNotesToMetadata(notes.str(), metadata_elem); std::string file_name; char buf[4096]; if(getcwd(buf, 4096) == NULL) { crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Something went wrong getting the the CWD""); } std::string absolute_dir = buf; absolute_dir += ""/""; // add in files if they exist if (!mOpts->logToScreen) { // we whould have a log file file_name = mOpts->output_fastq + PACKAGE_NAME + ""."" + mTimeStamp + "".log""; if (! checkFileOrError(file_name.c_str())) { xmlDoc->addFileToMetadata(""log"", absolute_dir + file_name, metadata_elem); } else { throw crispr::no_file_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, (absolute_dir + file_name).c_str()); } } #ifdef DEBUG // check for debuging .gv files if (!mOpts->noDebugGraph) { file_name = mOpts->output_fastq + ""Group_""; std::string file_sufix = to_string(groupNumber) + ""_"" + mTrueDRs[groupNumber] + ""_debug.gv""; if (! checkFileOrError((file_name + file_sufix).c_str())) { xmlDoc->addFileToMetadata(""data"", absolute_dir + file_name + file_sufix, metadata_elem); } else { throw crispr::no_file_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, (absolute_dir + file_name + file_sufix).c_str() ); } // and now for the cleaned .gv file_name = mOpts->output_fastq + ""Clean_""; if (! checkFileOrError((file_name + file_sufix).c_str())) { xmlDoc->addFileToMetadata(""data"", absolute_dir + file_name + file_sufix, metadata_elem); } else { throw crispr::no_file_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, (absolute_dir + file_name + file_sufix).c_str() ); } } #endif // DEBUG #ifdef RENDERING // check for image files #ifdef DEBUG if (!mOpts->noDebugGraph) { file_name = mOpts->output_fastq + ""Group_"" + to_string(groupNumber) + ""_"" + mTrueDRs[groupNumber] + "".eps""; if (! checkFileOrError(file_name.c_str())) { xmlDoc->addFileToMetadata(""image"", absolute_dir + file_name, metadata_elem); } else { throw crispr::no_file_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__,(absolute_dir + file_name).c_str()); } file_name = mOpts->output_fastq + ""Clean_"" + to_string(groupNumber) + ""_"" + mTrueDRs[groupNumber] + "".eps""; if (! checkFileOrError(file_name.c_str())) { xmlDoc->addFileToMetadata(""image"", absolute_dir + file_name, metadata_elem); } else { throw crispr::no_file_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__,(absolute_dir + file_name).c_str()); } } #endif // DEBUG if (!mOpts->noRendering) { file_name = mOpts->output_fastq + ""Spacers_"" + to_string(groupNumber) + ""_"" + mTrueDRs[groupNumber] + "".eps""; if (! checkFileOrError(file_name.c_str())) { xmlDoc->addFileToMetadata(""image"", absolute_dir + file_name, metadata_elem); } else { throw crispr::no_file_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__,(absolute_dir + file_name).c_str()); } } #endif // RENDERING // add in the final Spacer graph file_name = mOpts->output_fastq + ""Spacers_""; std::string file_sufix = to_string(groupNumber) + ""_"" + mTrueDRs[groupNumber] + ""_spacers.gv""; if (! checkFileOrError((file_name + file_sufix).c_str())) { xmlDoc->addFileToMetadata(""data"", absolute_dir + file_name + file_sufix, metadata_elem); } else { throw crispr::no_file_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, (absolute_dir + file_name + file_sufix).c_str() ); } // check the sequence file file_name = mOpts->output_fastq + ""Group_"" + to_string(groupNumber) + ""_"" + mTrueDRs[groupNumber] + "".fa""; if (! checkFileOrError(file_name.c_str())) { xmlDoc->addFileToMetadata(""sequence"", absolute_dir + file_name, metadata_elem); } else { throw crispr::no_file_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__,(absolute_dir + file_name).c_str()); } } catch(crispr::no_file_exception& e) { std::cerr<. */ int splitMain(int argc, char ** argv);","Unknown" "CRISPR","ctSkennerton/crass","src/crass/StringCheck.h",".h","2450","74","// File: StringCheck.h // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Give this guy a string, get a token, give this guy a token, get a string // All token are unique, all strings aren't! // // Basically a glorified map // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // #ifndef StringCheck_h #define StringCheck_h // system includes #include #include // typedefs typedef int StringToken; class StringCheck { public: StringCheck(std::string name) { mNextFreeToken = 1; mName = name;} StringCheck(void) { mNextFreeToken = 1; mName = ""unset"";} ~StringCheck(void) {} StringToken addString(std::string newStr); std::string getString(StringToken token); StringToken getToken(const std::string& queryStr); inline void setName(std::string name) { mName = name; } // members StringToken mNextFreeToken; // der std::map mT2S_map; // token to string map std::map mS2T_map; // string to token map std::string mName; }; #endif //StringCheck_h ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/StatsManager.h",".h","4006","127","/* * StatsManager.h is part of the crass project * * Created by Connor Skennerton on 8/01/12. * Copyright 2012 Connor Skennerton. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef crass_StatsManager_h #define crass_StatsManager_h /* This is a simple little class for calculating the mean etc... for any container that accepts a push_back funtion (vector, deque, list, stack, queue) */ #include #include #include template class StatsManager { T container; public: StatsManager (void){} typename T::value_type mean(void); typename T::value_type median(void); typename T::value_type percentile(double percent); typename T::value_type mode(void); double standardDeviation(void); void add(typename T::value_type a); bool remove(typename T::value_type a); void clear(void); }; template typename T::value_type StatsManager::mean() { return (std::accumulate(container.begin(), container.end(), static_cast(0))/container.size()); } template typename T::value_type StatsManager::median(void) { std::nth_element(container.begin(), container.begin()+container.size()/2, container.end()); return *(container.begin()+container.size()/2); } template typename T::value_type StatsManager::percentile( double percentile) { std::nth_element(container.begin(), container.begin()+container.size()*percentile, container.end()); return *(container.begin()+container.size()*percentile); } template typename T::value_type StatsManager::mode(void) { std::vector histogram(container.size(),0); typename T::iterator iter = container.begin(); while (iter != container.end()) { histogram[*iter++]++; } return std::max_element(histogram.begin(), histogram.end()) - histogram.begin(); } template double StatsManager::standardDeviation(void) { double average = static_cast( mean()); std::vector temp; typename T::iterator iter; for (iter = container.begin(); iter != container.end(); iter++) { double i = static_cast(*iter) - average; temp.push_back(i*i); } return std::sqrt(std::accumulate(temp.begin(), temp.end(), static_cast(0))/temp.size() ); } template bool StatsManager::remove(typename T::value_type a) { typename T::iterator iter; bool success = false; for (iter = container.begin(); iter != container.end(); iter++) { if (*iter == a) { container.erase(*iter); success = true; break; } } return success; } template void StatsManager::add(typename T::value_type a) { container.push_back(a); } template void StatsManager::clear(void) { container.clear(); } #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/libcrispr.cpp",".cpp","40578","1164","// File: libcrispr.cpp // Original Author: Michael Imelfort 2011 :) // -------------------------------------------------------------------- // // OVERVIEW: // // This file wraps all the crispr associated functions we'll need. // The ""crispr toolbox"" // // -------------------------------------------------------------------- // Copyright 2011, 2012 Michael Imelfort and Connor Skennerton // Copyright 2016 Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // system includes #include #include #include #include #include #include #include #include #include #include #include #include ""StlExt.h"" #include ""Exception.h"" // local includes #include ""libcrispr.h"" #include ""LoggerSimp.h"" #include ""crassDefines.h"" #include ""PatternMatcher.h"" #include ""SeqUtils.h"" #include ""kseq.h"" #include ""config.h"" extern ""C"" { #include ""../aho-corasick/msutil.h"" #include ""../aho-corasick/acism.h"" } int searchFile(const char *inputFastq, const options& opts, ReadMap * mReads, StringCheck * mStringCheck, lookupTable& patternsHash, lookupTable& readsFound, time_t& time_start ) { //----- // Wrapper used for searching reads for DRs // depending on the length of the read. // this funciton may use the boyer moore algorithm // or the CRT search algorithm // gzFile fp = getFileHandle(inputFastq); kseq_t * seq; // initialize seq seq = kseq_init(fp); int l, log_counter, max_read_length; log_counter = max_read_length = 0; static int read_counter = 0; time_t time_current; // read sequence while ( (l = kseq_read(seq)) >= 0 ) { max_read_length = (l > max_read_length) ? l : max_read_length; if (log_counter == CRASS_DEF_READ_COUNTER_LOGGER) { time(&time_current); double diff = difftime(time_current, time_start); //time_start = time_current; std::cout<<""\r[""<seq.s);tmp_holder.setHeader( seq->name.s); #if SEARCH_SINGLETON SearchCheckerList::iterator debug_iter = debugger->find(seq->name.s); if (debug_iter != debugger->end()) { changeLogLevel(10); std::cout<<""Processing interesting read: ""<first<comment.s) { tmp_holder.setComment(seq->comment.s); } if (seq->qual.s) { tmp_holder.setQual(seq->qual.s); } bool crispr_read = searchCore(tmp_holder, opts ); if(crispr_read) { addReadHolder(mReads, mStringCheck, tmp_holder); patternsHash[tmp_holder.repeatStringAt(0)] = true; readsFound[tmp_holder.getHeader()] = true; } } catch (crispr::exception& e) { std::cerr<size()<<"" direct repeat variants have been found from "" << read_counter << "" reads"", 2); return max_read_length; } // CRT search int scanRight(ReadHolder& tmp_holder, std::string& pattern, unsigned int minSpacerLength, unsigned int scanRange) { #ifdef DEBUG logInfo(""Scanning Right for more repeats:"", 9); #endif unsigned int start_stops_size = tmp_holder.getStartStopListSize(); unsigned int pattern_length = static_cast(pattern.length()); // final start index unsigned int last_repeat_index = tmp_holder.getRepeatAt(start_stops_size - 2); //second to final start index unsigned int second_last_repeat_index = tmp_holder.getRepeatAt(start_stops_size - 4); unsigned int repeat_spacing = last_repeat_index - second_last_repeat_index; #ifdef DEBUG logInfo(start_stops_size<<"" : ""<(tmp_holder.getSeqLength()); bool more_to_search = true; while (more_to_search) { candidate_repeat_index = last_repeat_index + repeat_spacing; begin_search = candidate_repeat_index - scanRange; end_search = candidate_repeat_index + pattern_length + scanRange; #ifdef DEBUG logInfo(candidate_repeat_index<<"" : ""< read_length - 1) { #ifdef DEBUG logInfo(""returning... ""< ""< read_length) { end_search = read_length; } if ( begin_search >= end_search) { #ifdef DEBUG logInfo(""Returning... ""<= ""<= 0) { tmp_holder.startStopsAdd(begin_search + position, begin_search + position + pattern_length - 1); second_last_repeat_index = last_repeat_index; last_repeat_index = begin_search + position; repeat_spacing = last_repeat_index - second_last_repeat_index; if (repeat_spacing < (minSpacerLength + pattern_length)) { more_to_search = false; } } else { more_to_search = false; } } return begin_search + position; } int searchCore(ReadHolder& tmpHolder, const options& opts) { //----- // Code lifted from CRT, ported by Connor and hacked by Mike. // std::string read = tmpHolder.getSeq(); // get the length of this sequence unsigned int seq_length = static_cast(read.length()); //the mumber of bases that can be skipped while we still guarantee that the entire search //window will at some point in its iteration thru the sequence will not miss a any repeat unsigned int skips = opts.lowDRsize - (2 * opts.searchWindowLength - 1); if (skips < 1) { skips = 1; } int searchEnd = seq_length - opts.lowDRsize - opts.lowSpacerSize - opts.searchWindowLength - 1; if (searchEnd < 0) { logWarn(""Read ""<(searchEnd); j = j + skips) { unsigned int beginSearch = j + opts.lowDRsize + opts.lowSpacerSize; unsigned int endSearch = j + opts.highDRsize + opts.highSpacerSize + opts.searchWindowLength; if (endSearch >= seq_length) { endSearch = seq_length - 1; } //should never occur if (endSearch < beginSearch) { endSearch = beginSearch; } std::string text; std::string pattern; try { text = read.substr(beginSearch, (endSearch - beginSearch)); } catch (std::exception& e) { throw crispr::substring_exception(e.what(), text.c_str(), beginSearch, (endSearch - beginSearch), __FILE__, __LINE__, __PRETTY_FUNCTION__); } try { pattern = read.substr(j, opts.searchWindowLength); } catch (std::exception& e) { throw crispr::substring_exception(e.what(), read.c_str(), j, opts.searchWindowLength, __FILE__, __LINE__, __PRETTY_FUNCTION__); } //if pattern is found, add it to candidate list and scan right for additional similarly spaced repeats int pattern_in_text_index = -1; pattern_in_text_index = PatternMatcher::bmpSearch(text, pattern); if (pattern_in_text_index >= 0) { tmpHolder.startStopsAdd(j, j + opts.searchWindowLength - 1); unsigned int found_pattern_start_index = beginSearch + static_cast(pattern_in_text_index); tmpHolder.startStopsAdd(found_pattern_start_index, found_pattern_start_index + opts.searchWindowLength - 1); scanRight(tmpHolder, pattern, opts.lowSpacerSize, 24); } if ( (tmpHolder.numRepeats() >= opts.minNumRepeats) ) //tmp_holder->numRepeats is half the size of the StartStopList { #ifdef DEBUG logInfo(tmpHolder.getHeader(), 8); logInfo(""\tPassed test 1. At least ""<= opts.lowDRsize) && (actual_repeat_length <= opts.highDRsize) ) { #ifdef DEBUG logInfo(""\tPassed test 2. The repeat length is ""<= ""<< actual_repeat_length <<"" <= ""<readsFound->find(payload->read->name.s) == payload->readsFound->end()) { #ifdef DEBUG logInfo(""new read recruited: ""<read->name.s, 9); logInfo(payload->read->seq.s, 10); #endif // The index is one past the end of the match but crass stores // it's position at the end of the match unsigned int DR_end = static_cast(textpos - 1); //static_cast(search_data.iFoundPosition) + static_cast(search_data.sDataFound.length()) - 1; if(DR_end >= static_cast(payload->read->seq.l)) { DR_end = static_cast(payload->read->seq.l) - 1; } ReadHolder tmp_holder; tmp_holder.setSequence(payload->read->seq.s); tmp_holder.setHeader( payload->read->name.s); if (payload->read->comment.s) { tmp_holder.setComment(payload->read->comment.s); } if (payload->read->qual.s) { tmp_holder.setQual(payload->read->qual.s); } //logInfo(""textpos: ""<pattv[strnum].len, 1) tmp_holder.startStopsAdd(DR_end - (payload->pattv[strnum].len - 1), DR_end); addReadHolder(payload->mReads, payload->mStringCheck, tmp_holder); } return 1; } void findSingletons(const char *inputFastq, const options &opts, std::vector * nonRedundantPatterns, lookupTable &readsFound, ReadMap * mReads, StringCheck * mStringCheck, time_t& startTime) { std::string conc; std::vector::iterator iter; for( iter = nonRedundantPatterns->begin(); iter != nonRedundantPatterns->end(); ++iter) { conc += *iter + ""\n""; } // this is a hack as refsplit creates an extra blank record, which stuffs // up the search if the string ends with a new line character. Basically // here I'm replacing the last newline with null to prevent this char * concstr = new char[conc.size() + 1]; std::copy(conc.begin(), conc.end(), concstr); concstr[conc.size()] = '\0'; concstr[conc.size()-1] = '\0'; int npatts; MEMREF *pattv = refsplit(concstr, '\n', &npatts); ACISM *psp = acism_create(pattv, npatts); gzFile fp = getFileHandle(inputFastq); kseq_t *seq; seq = kseq_init(fp); int l; int log_counter = 0; static int read_counter = 0; time_t time_current; MultisearchPayload payload; payload.mReads = mReads; payload.mStringCheck = mStringCheck; payload.pattv = pattv; payload.readsFound = &readsFound; while ( (l = kseq_read(seq)) >= 0 ) { // seq is a read what we love // search it for the patterns until found if (log_counter == CRASS_DEF_READ_COUNTER_LOGGER) { time(&time_current); double diff = difftime(time_current, startTime); std::cout<<""\r[""<seq.s, seq->seq.l}; (void)acism_scan(psp, tmp, (ACISM_ACTION*)on_match, &payload); log_counter++; read_counter++; } gzclose(fp); kseq_destroy(seq); // destroy seq delete[] concstr; time(&time_current); double diff = difftime(time_current, startTime); std::cout<<""\r[""< cut_off) { cut_off = 2; } #ifdef DEBUG logInfo(""cutoff: ""< cut_off) { cut_off = 2; } #ifdef DEBUG logInfo(""minimum number of repeats needed with same nucleotide for extension: ""< 0) { if((last_repeat_start_index + searchWindowLength + right_extension_length) >= static_cast(tmp_holder.getSeqLength())) { DR_index_end -= 2; } for (unsigned int k = 0; k < DR_index_end; k+=2 ) { #ifdef DEBUG logInfo(k<<"" : ""<= static_cast(tmp_holder.getSeqLength())) { k = DR_index_end; } else { switch( tmp_holder.getSeqCharAt(tmp_holder.getRepeatAt(k) + tmp_holder.getRepeatLength())) { case 'A': char_count_A++; break; case 'C': char_count_C++; break; case 'G': char_count_G++; break; case 'T': char_count_T++; break; } } } #ifdef DEBUG logInfo(""R: "" << char_count_A << "" : "" << char_count_C << "" : "" << char_count_G << "" : "" << char_count_T << "" : "" << tmp_holder.getRepeatLength() << "" : "" << max_right_extension_length, 9); #endif if ( (char_count_A >= cut_off) || (char_count_C >= cut_off) || (char_count_G >= cut_off) || (char_count_T >= cut_off) ) { #ifdef DEBUG logInfo(""R: SUCCESS! count above ""<< cut_off, 9); #endif tmp_holder.incrementRepeatLength(); max_right_extension_length--; right_extension_length++; char_count_A = char_count_C = char_count_T = char_count_G = 0; } else { #ifdef DEBUG logInfo(""R: FAILURE! count below ""<< cut_off, 9); #endif break; } } char_count_A = char_count_C = char_count_T = char_count_G = 0; // again, not too far unsigned int left_extension_length = 0; int test_for_negative = shortest_repeat_spacing - tmp_holder.getRepeatLength();// - minSpacerLength; unsigned int max_left_extension_length = (test_for_negative >= 0)? static_cast(test_for_negative) : 0; #ifdef DEBUG logInfo(""max left extension length: ""< first_repeat_start_index) { #ifdef DEBUG logInfo(""removing start partial: ""< ""<(CRASS_DEF_TRIM_EXTEND_CONFIDENCE * (num_repeats - 1)); if (2 > cut_off) { cut_off = 2; } #ifdef DEBUG logInfo(""new cutoff: ""<= cut_off) || (char_count_C >= cut_off) || (char_count_G >= cut_off) || (char_count_T >= cut_off) ) { tmp_holder.incrementRepeatLength(); left_extension_length++; char_count_A = char_count_C = char_count_T = char_count_G = 0; } else { break; } } StartStopListIterator repeat_iter = tmp_holder.begin(); #ifdef DEBUG logInfo(""Repeat positions:"", 9); #endif while (repeat_iter < tmp_holder.end()) { if(*repeat_iter < static_cast(left_extension_length)) { *repeat_iter = 0; } else { *repeat_iter -= left_extension_length; } if(*(repeat_iter+1) + right_extension_length >= tmp_holder.getSeqLength()) { *(repeat_iter + 1) = tmp_holder.getSeqLength() - 1; } else { *(repeat_iter + 1) += right_extension_length; } #ifdef DEBUG logInfo(""\t""<<*repeat_iter<<"",""<<*(repeat_iter+1), 9); #endif repeat_iter += 2; } return static_cast(tmp_holder.getRepeatLength()); } bool testSpacerLength(int minSpacerLength, int maxSpacerLength, int minAllowedSpacerLength, int maxAllowedSpacerLength) { /* * MAX AND MIN SPACER LENGTHS */ if (minSpacerLength < minAllowedSpacerLength) { #ifdef DEBUG logInfo(""\tFailed test 4a. Min spacer length out of range: ""< ""< maxAllowedSpacerLength) { #ifdef DEBUG logInfo(""\tFailed test 4b. Max spacer length out of range: ""< ""< CRASS_DEF_SPACER_OR_REPEAT_MAX_SIMILARITY) { #ifdef DEBUG logInfo(""\tFailed test 5b. Spacers are too similar to the repeat: ""< ""< CRASS_DEF_SPACER_OR_REPEAT_MAX_SIMILARITY) { #ifdef DEBUG logInfo(""\tFailed test 5a. Spacers are too similar: ""< ""< CRASS_DEF_SPACER_TO_SPACER_LENGTH_DIFF) { #ifdef DEBUG logInfo(""\tFailed test 6a. Spacer lengths differ too much: ""< ""< CRASS_DEF_SPACER_TO_REPEAT_LENGTH_DIFF) { #ifdef DEBUG logInfo(""\tFailed test 6b. Repeat to spacer lengths differ too much: ""< ""< tmp_holder.numSpacers()); if(!is_short) { // for holding stats float ave_spacer_to_spacer_len_difference = 0.0; float ave_repeat_to_spacer_len_difference = 0.0; float ave_spacer_to_spacer_difference = 0.0; float ave_repeat_to_spacer_difference = 0.0; int min_spacer_length = 10000000; int max_spacer_length = 0; int num_compared = 0; // now go through the spacers and check for similarities std::vector spacer_vec; //get all the spacer strings tmp_holder.getAllSpacerStrings(spacer_vec); std::vector::iterator spacer_iter = spacer_vec.begin(); std::vector::iterator spacer_last = spacer_vec.end(); spacer_last--; while (spacer_iter != spacer_last) { num_compared++; try { ave_repeat_to_spacer_difference += PatternMatcher::getStringSimilarity(repeat, *spacer_iter); } catch (std::exception& e) { std::cerr<<""Failed to compare similarity between: ""<(spacer_iter->size()) - static_cast((spacer_iter + 1)->size())); ave_repeat_to_spacer_len_difference += (static_cast(repeat.size()) - static_cast(spacer_iter->size())); spacer_iter++; } // now look for max and min lengths! spacer_iter = spacer_vec.begin(); spacer_last = spacer_vec.end(); while (spacer_iter != spacer_last) { if(static_cast(spacer_iter->length()) < min_spacer_length) { min_spacer_length = static_cast(spacer_iter->length()); } if(static_cast(spacer_iter->length()) > max_spacer_length) { max_spacer_length = static_cast(spacer_iter->length()); } spacer_iter++; } // we may not have compared anything... if(num_compared == 0) { // there are only three spacers in this read and the read begins and ends on a spacer // we will still need to do some comparisons is_short = true; single_compare_index = 1; } else { // we can keep going! ave_spacer_to_spacer_difference /= static_cast(num_compared); ave_repeat_to_spacer_difference /= static_cast(num_compared); ave_spacer_to_spacer_len_difference = abs(ave_spacer_to_spacer_len_difference /= static_cast(num_compared)); ave_repeat_to_spacer_len_difference = abs(ave_repeat_to_spacer_len_difference /= static_cast(num_compared)); if(! testSpacerLength(min_spacer_length, max_spacer_length, minSpacerLength, maxSpacerLength)) { return false; } if(! testSpacerSpacerSimilarity(ave_spacer_to_spacer_difference)) { return false; } if(! testSpacerRepeatSimilarity(ave_repeat_to_spacer_difference)) { return false; } if(! testSpacerSpacerLengthDiff(ave_spacer_to_spacer_len_difference)) { return false; } if(! testRepeatSpacerLengthDiff(ave_repeat_to_spacer_len_difference)) { return false; } } } // Are we testing a short read or only one spacer? if(is_short) { std::string spacer = tmp_holder.spacerStringAt(single_compare_index); if(! testSpacerLength(spacer.length(), spacer.length(), minSpacerLength, maxSpacerLength)) { return false; } float similarity = PatternMatcher::getStringSimilarity(repeat, spacer); if(! testSpacerRepeatSimilarity(similarity)) { return false; } int repeat_spacer_len_diff = abs(static_cast(spacer.length()) - static_cast(repeat.length())); if(! testRepeatSpacerLengthDiff(repeat_spacer_len_diff)) { return false; } } return true; } bool isRepeatLowComplexity(std::string& repeat) { int c_count = 0; int g_count = 0; int a_count = 0; int t_count = 0; int n_count = 0; int curr_repeat_length = static_cast(repeat.length()); int cut_off = static_cast(curr_repeat_length * CRASS_DEF_LOW_COMPLEXITY_THRESHHOLD); std::string::iterator dr_iter; for (dr_iter = repeat.begin(); dr_iter != repeat.end();++dr_iter) { switch (*dr_iter) { case 'c': case 'C': c_count++; break; case 't': case 'T': t_count++; break; case 'a': case 'A': a_count++; break; case 'g': case 'G': g_count++; break; default: n_count++; break; } } if (a_count > cut_off) return true; else if (t_count > cut_off) return true; else if (g_count > cut_off) return true; else if (c_count > cut_off) return true; else if (n_count > cut_off) return true; return false; } bool drHasHighlyAbundantKmers(std::string& directRepeat) { float max; return drHasHighlyAbundantKmers(directRepeat, max); } bool drHasHighlyAbundantKmers(std::string& directRepeat, float& maxFrequency) { // cut kmers from the direct repeat to test whether // a particular kmer is vastly over represented std::map kmer_counter; size_t kmer_length = 3; size_t max_index = (directRepeat.length() - kmer_length); std::string kmer; int total_count = 0; try { for (size_t i = 0; i < max_index; i++) { kmer = directRepeat.substr(i, kmer_length); //std::cout << kmer << "", ""; addOrIncrement(kmer_counter, kmer); total_count++; } } catch (std::exception& e) { throw crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, e.what()); } //std::cout << std::endl; std::map::iterator iter; //std::cout << directRepeat << std::endl; int max_count = 0; for (iter = kmer_counter.begin(); iter != kmer_counter.end(); ++iter) { if (iter->second > max_count) { max_count = iter->second; } //std::cout << ""{"" << iter->first << "", "" << iter->second << "", "" << (float(iter->second)/float(total_count)) << ""}, ""; } //std::cout << std::endl; maxFrequency = static_cast(max_count)/static_cast(total_count); if (maxFrequency > CRASS_DEF_KMER_MAX_ABUNDANCE_CUTOFF) { return true; } else { return false; } } void addReadHolder(ReadMap * mReads, StringCheck * mStringCheck, ReadHolder& tmpReadholder) { ReadHolder * candidate = new ReadHolder(tmpReadholder); std::string dr_lowlexi; try { dr_lowlexi = candidate->DRLowLexi(); } catch(crispr::exception& e) { std::cerr<getToken(dr_lowlexi); if(0 == st) { // new guy st = mStringCheck->addString(dr_lowlexi); (*mReads)[st] = new ReadList(); } #ifdef DEBUG logInfo(""Direct repeat: ""<find(tmpReadholder.getHeader()); if (debug_iter != debugger->end()) { // our read got through to this stage std::cout<< tmpReadholder.splitApart(); tmpReadholder.printContents(); debug_iter->second.token(st); std::cout<first<<"" "" <push_back(candidate); } ","C++" "CRISPR","ctSkennerton/crass","src/crass/ExtractTool.cpp",".cpp","17674","484","// ExtractTool.cpp // // Copyright (C) 2011, 2012 - Connor Skennerton // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #include ""ExtractTool.h"" #include ""Utils.h"" #include ""config.h"" #include ""Exception.h"" #include ""StlExt.h"" #include ""reader.h"" #include #include #include #include #include #include ExtractTool::ExtractTool (void) { // set the 'print coverage' bit by defult ET_BitMask.set(6); ET_OutputPrefix = ""./""; ET_OutputNamePrefix = """"; ET_OutputHeaderPrefix = """"; } ExtractTool::~ExtractTool (void) {} //void ExtractTool::generateGroupsFromString ( std::string str) //{ // std::set vec; // split ( str, vec, "",""); // ET_Group = vec; // // set the 'do subset' bit // ET_BitMask.set(0); //} void ExtractTool::setOutputBuffer(std::ofstream& out, const char * file) { if (NULL != file) { // has argument // open output buffer std::string filename = ET_OutputPrefix + ET_OutputHeaderPrefix + file; out.open(filename.c_str()); if (!out) { std::stringstream msg; msg << ""failed to open output file: "" << filename <<""\n""; msg << ""Make sure that the path exists and remember ""; msg << ""to only give the basename when specifying -d, -s and -f and specify the directory ""; msg <<""with the -o option on the command line""<::rdbuf(std::cout.rdbuf()); } } int ExtractTool::processOptions (int argc, char ** argv) { char * dr_file; char * spacer_file; char * flanker_file; dr_file = NULL; spacer_file = NULL; flanker_file = NULL; bool dr, flanker, spacer; dr = flanker = spacer = false; int c; int index; static struct option long_options [] = { {""help"", no_argument, NULL, 'h'}, {""header-prefix"", required_argument, NULL, 'H'}, {""groups"",required_argument, NULL, 'g'}, {""spacer"",optional_argument,NULL,'s'}, {""direct-repeat"", optional_argument, NULL, 'd'}, {""flanker"", optional_argument, NULL, 'f'}, {""split-group"", no_argument, NULL, 'x'}, {""outfile-prefix"",required_argument,NULL, 'o'}, {""outfile-dir"",required_argument,NULL,'O'}, {0,0,0,0} }; while((c = getopt_long(argc, argv, ""hH:g:Cs::d::f::xyo:O:"", long_options, &index)) != -1) { switch(c) { case 'C': { ET_BitMask.reset(6); break; } case 'h': { extractUsage (); exit(0); break; } case 'H': { ET_OutputHeaderPrefix = optarg; break; } case 'g': { if(fileOrString(optarg)) { parseFileForGroups(ET_Group, optarg); //ST_Subset = true; } else { generateGroupsFromString(optarg, ET_Group); } ET_BitMask.set(0); break; } case 's': { spacer = true; spacer_file = optarg; ET_BitMask.set(4); break; } case 'd': { dr = true; dr_file = optarg; ET_BitMask.set(5); break; } case 'f': { flanker = true; flanker_file = optarg; ET_BitMask.set(3); break; } case 'x': { ET_BitMask.set(2); break; } case 'o': { ET_OutputPrefix = optarg; // just in case the user put '.' or '..' or '~' as the output directory if (ET_OutputPrefix[ET_OutputPrefix.length() - 1] != '/') { ET_OutputPrefix += '/'; } // check if our output folder exists struct stat file_stats; if (0 != stat(ET_OutputPrefix.c_str(),&file_stats)) { recursiveMkdir(ET_OutputPrefix); } break; } case 'O': { ET_OutputNamePrefix = optarg; break; } default: { extractUsage(); exit(1); break; } } } if (!(ET_BitMask[3] | ET_BitMask[4] | ET_BitMask[5])) { throw crispr::input_exception(""Please specify at least one of -s -d -f""); } if (! ET_BitMask[2]) { if (dr) { setOutputBuffer(ET_RepeatStream, dr_file); } if (spacer) { setOutputBuffer(ET_SpacerStream, spacer_file); } if (flanker) { setOutputBuffer(ET_FlankerStream, flanker_file); } } return optind; } int ExtractTool::processInputFile(const char * inputFile) { // open the file crispr::xml::reader xml_obj; try { xercesc::DOMDocument * xml_doc = xml_obj.setFileParser(inputFile); xercesc::DOMElement * root_elem = xml_doc->getDocumentElement(); if( !root_elem ) throw(crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""empty XML document"" )); parseWantedGroups(xml_obj, root_elem); } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::ostringstream errBuf; errBuf << ""Error parsing file: "" << message << std::flush; xercesc::XMLString::release( &message ); throw (crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, (errBuf.str()).c_str())); } catch (crispr::xml_exception& xe) { std::cerr<< xe.what()<(ET_Group.size()); for (xercesc::DOMElement * currentElement = rootElement->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { // break if we have processed all of the wanted groups if(ET_BitMask[0] && num_groups_to_process == 0) { break; } // new group char * c_group_id = tc(currentElement->getAttribute(xmlObj.attr_Gid())); std::string group_id = c_group_id; xr(&c_group_id); if (ET_BitMask[0]) { // we only want some of the groups look at ET_Groups if (ET_Group.find(group_id.substr(1)) == ET_Group.end() ) { continue; } if (ET_BitMask[2]) openStream(group_id); extractDataFromGroup(xmlObj, currentElement); if(ET_BitMask[0]) num_groups_to_process--; if(ET_BitMask[2]) closeStream(); } else { if (ET_BitMask[2]) openStream(group_id); extractDataFromGroup(xmlObj, currentElement); if(ET_BitMask[2]) closeStream(); } } } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::stringstream errBuf; errBuf << ""Error parsing file: "" << message << std::flush; throw (crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, (errBuf.str()).c_str())); xercesc::XMLString::release( &message ); } catch (crispr::xml_exception& xe) { std::cerr<< xe.what()<getAttribute(xmlDoc.attr_Gid())); for (xercesc::DOMElement * current_element = currentGroup->getFirstElementChild(); current_element != NULL; current_element = current_element->getNextElementSibling()) { if(xercesc::XMLString::equals(current_element->getTagName(), xmlDoc.tag_Data())) { // go through all the children of data for (xercesc::DOMElement * data_child = current_element->getFirstElementChild(); data_child != NULL; data_child = data_child->getNextElementSibling()) { if (xercesc::XMLString::equals(data_child->getTagName(), xmlDoc.tag_Drs())) { if (ET_BitMask[5]) { // get direct repeats processData(xmlDoc, data_child, REPEAT, c_gid, ET_RepeatStream); } } else if (xercesc::XMLString::equals(data_child->getTagName(), xmlDoc.tag_Spacers())) { if (ET_BitMask[4]) { // get spacers processData(xmlDoc, data_child, SPACER, c_gid, ET_SpacerStream); } } else if (xercesc::XMLString::equals(data_child->getTagName(), xmlDoc.tag_Flankers())) { if (ET_BitMask[3]) { // get flankers processData(xmlDoc, data_child, FLANKER, c_gid, ET_FlankerStream); } } } } } xr(&c_gid); } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::ostringstream errBuf; errBuf << ""Error parsing file: "" << message << std::flush; xercesc::XMLString::release( &message ); } catch (crispr::xml_exception& xe) { std::cerr<< xe.what()<getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { char * c_seq = tc(currentElement->getAttribute(xmlDoc.attr_Seq())); std::string id; switch (wantedType) { case REPEAT: { char * c_id = tc(currentElement->getAttribute(xmlDoc.attr_Drid())); id = c_id; xr(&c_id); break; } case SPACER: { char * c_id = tc(currentElement->getAttribute(xmlDoc.attr_Spid())); id = c_id; if (ET_BitMask[6] && currentElement->hasAttribute(xmlDoc.attr_Cov())) { char * c_cov = tc(currentElement->getAttribute(xmlDoc.attr_Cov())); id += ""_Cov_""; id += c_cov; xr(&c_cov); } xr(&c_id); break; } case FLANKER: { char * c_id = tc(currentElement->getAttribute(xmlDoc.attr_Flid())); id = c_id; xr(&c_id); break; } case CONSENSUS: { break; } default: { throw (crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Input element enum unknown"")); break; } } outStream<<'>'<= argc) { throw crispr::input_exception(""No input file provided"" ); } else { std::ifstream infile(argv[opt_index]); if (! infile.good()) { throw crispr::input_exception(""cannot open input file""); } // get cracking and process that file return et.processInputFile(argv[opt_index]); } } catch(crispr::input_exception& re) { std::cerr< */ /* Last Modified: 12APR2009 */ /* De-macro'd by the ACE-team 18MAY2012 wattup! */ #include #include #include #include #include ""kseq.h"" kstream_t *ks_init(gzFile f) { kstream_t *ks = (kstream_t*)calloc(1, sizeof(kstream_t)); ks->f = f; ks->buf = (char*)malloc(4096); return ks; } void ks_destroy(kstream_t *ks) { if (ks) { free(ks->buf); free(ks); } } int ks_getc(kstream_t *ks) { if (ks->is_eof && ks->begin >= ks->end) return -1; if (ks->begin >= ks->end) { ks->begin = 0; ks->end = gzread(ks->f, ks->buf, 4096); if (ks->end < 4096) ks->is_eof = 1; if (ks->end == 0) return -1; } return (int)ks->buf[ks->begin++]; } int ks_getuntil(kstream_t *ks, int delimiter, kstring_t *str, int *dret) { if (dret) *dret = 0; str->l = 0; if (ks->begin >= ks->end && ks->is_eof) return -1; for (;;) { int i; if (ks->begin >= ks->end) { if (!ks->is_eof) { ks->begin = 0; ks->end = gzread(ks->f, ks->buf, 4096); if (ks->end < 4096) ks->is_eof = 1; if (ks->end == 0) break; } else break; } if (delimiter > 1) { for (i = ks->begin; i < ks->end; ++i) { if (ks->buf[i] == delimiter) break; } } else if (delimiter == 0) { for (i = ks->begin; i < ks->end; ++i) { if (isspace(ks->buf[i])) break; } } else if (delimiter == 1) { for (i = ks->begin; i < ks->end; ++i){ if (isspace(ks->buf[i]) && ks->buf[i] != ' ') break; } } else i = 0; if ((int)(str->m - str->l) < i - ks->begin + 1) { str->m = str->l + (i - ks->begin) + 1; (--(str->m), (str->m)|=(str->m)>>1, (str->m)|=(str->m)>>2, (str->m)|=(str->m)>>4, (str->m)|=(str->m)>>8, (str->m)|=(str->m)>>16, ++(str->m)); str->s = (char*)realloc(str->s, str->m); } memcpy(str->s + str->l, ks->buf + ks->begin, i - ks->begin); str->l = str->l + (i - ks->begin); ks->begin = i + 1; if (i < ks->end) { if (dret) *dret = ks->buf[i]; break; } } if (str->l == 0) { str->m = 1; str->s = (char*)calloc(1, 1); } str->s[str->l] = '\0'; return (int)str->l; } kseq_t *kseq_init(gzFile fd) { kseq_t *s = (kseq_t*)calloc(1, sizeof(kseq_t)); s->f = ks_init(fd); return s; } void kseq_rewind(kseq_t *ks) { ks->last_char = 0; ks->f->is_eof = ks->f->begin = ks->f->end = 0; } void kseq_destroy(kseq_t *ks) { if (!ks) return; free(ks->name.s); free(ks->comment.s); free(ks->seq.s); free(ks->qual.s); ks_destroy(ks->f); free(ks); } int kseq_read(kseq_t *seq) { int c; kstream_t *ks = seq->f; if (seq->last_char == 0) { while ((c = ks_getc(ks)) != -1 && c != '>' && c != '@'); if (c == -1) return -1; seq->last_char = c; } seq->comment.l = seq->seq.l = seq->qual.l = 0; if (ks_getuntil(ks, 0, &seq->name, &c) < 0) return -1; if (c != '\n') ks_getuntil(ks, '\n', &seq->comment, 0); while ((c = ks_getc(ks)) != -1 && c != '>' && c != '+' && c != '@') { if (isgraph(c)) { if (seq->seq.l + 1 >= seq->seq.m) { seq->seq.m = seq->seq.l + 2; (--(seq->seq.m), (seq->seq.m)|=(seq->seq.m)>>1, (seq->seq.m)|=(seq->seq.m)>>2, (seq->seq.m)|=(seq->seq.m)>>4, (seq->seq.m)|=(seq->seq.m)>>8, (seq->seq.m)|=(seq->seq.m)>>16, ++(seq->seq.m)); seq->seq.s = (char*)realloc(seq->seq.s, seq->seq.m); } seq->seq.s[seq->seq.l++] = (char)c; } } if (c == '>' || c == '@') seq->last_char = c; seq->seq.s[seq->seq.l] = 0; if (c != '+') return (int)seq->seq.l; if (seq->qual.m < seq->seq.m) { seq->qual.m = seq->seq.m; seq->qual.s = (char*)realloc(seq->qual.s, seq->qual.m); } while ((c = ks_getc(ks)) != -1 && c != '\n'); if (c == -1) return -2; while ((c = ks_getc(ks)) != -1 && seq->qual.l < seq->seq.l) { if (c >= 33 && c <= 127) seq->qual.s[seq->qual.l++] = (unsigned char)c; } seq->qual.s[seq->qual.l] = 0; seq->last_char = 0; if (seq->seq.l != seq->qual.l) return -2; return (int)seq->seq.l; }","C++" "CRISPR","ctSkennerton/crass","src/crass/AssemblyWrapper.h",".h","7554","190","/* * AssemblyWrapper.h is part of the crass project * * Created by Connor Skennerton on 27/10/11. * Copyright 2011, 2012 Connor Skennerton and Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef crass_AssemblyWrapper_h #define crass_AssemblyWrapper_h #include #include #include #include #include ""kseq.h"" #include #include ""reader.h"" enum ASSEMBLERS { unset, velvet, cap3 }; typedef struct{ std::string xmlFileName; // name of the crass xml file int group; // group id to parse int logLevel; // log level bool pairedEnd; // does the user want a paired end assembly std::string inputDirName; // location of the input directory std::string outputDirName; // location of the output directory std::string segments; // a comma separated list of segments to assemble bool logToScreen; // does the user want logging info printed to screen int insertSize; // the insert size for the paired end assembly ASSEMBLERS assembler; // the assembler that the user wants } assemblyOptions; typedef std::vector IDVector; typedef std::map Spacer2SourceMap; typedef std::map XMLIDMap; typedef std::set StringSet; class CrisprParser : public crispr::xml::reader { public: // // Working functions // void parseXMLFile(std::string XMLFile, std::string& wantedGroup, std::string& directRepeat, StringSet& wantedContigs, StringSet& wantedSpacers ); xercesc::DOMElement * getWantedGroupFromRoot(xercesc::DOMElement * currentElement, std::string& wantedGroup, std::string& directRepeat ); xercesc::DOMElement * parseGroupForAssembly(xercesc::DOMElement* currentElement ); void parseAssemblyForContigIds(xercesc::DOMElement* parentNode, StringSet& wantedReads, Spacer2SourceMap& spacersForAssembly, XMLIDMap& source2acc, StringSet& wantedContigs ); /** Iterate through all spacers for a contig and collecting source accessions * @param parentNode The contig node from the DOM tree * @param wantedReads a container to store the source accessions in * @param spacersForAssembly A container containing a list of all sources for each spacer * @param source2acc A container containing a mapping between source IDs and source accessions */ void getSourceIdForAssembly(xercesc::DOMElement* parentNode, StringSet& wantedReads, Spacer2SourceMap& spacersForAssembly, XMLIDMap& source2acc ); /** Get a list of sources for a group * @param container An associative container to write the sources to. * The container must have both key and value types as XMLCh * * The container must overload reference operator[] * @param parentNode The parent node for the sources for iteration */ template void getSourcesForGroup(C& container, xercesc::DOMElement * parentNode) { if (xercesc::XMLString::equals(tag_Sources(), parentNode->getTagName())) { for (xercesc::DOMElement * currentNode = parentNode->getFirstElementChild(); currentNode != NULL; currentNode = currentNode->getNextElementSibling()) { char * current_source_id = tc(currentNode->getAttribute(attr_Soid())); char * current_source_acc = tc(currentNode->getAttribute(attr_Accession())); container[current_source_id] = current_source_acc; xr(¤t_source_id); xr(¤t_source_acc); } } else { throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Parent not 'sources' tag""); } } /** Get a list of source identifiers for all spacers * @param container An associative container that maps a single * key (the spacer) to a list of sources * @param parentNode The parent node for the spacer tags */ template void mapSacersToSourceID(C& container, xercesc::DOMElement * parentNode) { // each spacer for (xercesc::DOMElement * currentNode = parentNode->getFirstElementChild(); currentNode != NULL; currentNode = currentNode->getNextElementSibling()) { char * spid = tc(currentNode->getAttribute(attr_Spid())); // each source for (xercesc::DOMElement * sp_source = currentNode->getFirstElementChild(); sp_source != NULL; sp_source = sp_source->getNextElementSibling()) { char * soid = tc(sp_source->getAttribute(attr_Soid())); container[spid].push_back(soid); xr(&soid); } xr(&spid); } } }; void assemblyVersionInfo(void); void assemblyUsage(void); int processAssemblyOptions(int argc, char * argv[], assemblyOptions& opts); inline int calculateOverlapLength(int drLength){return drLength + 8;} void parseSegmentString(std::string& segmentString, std::set& segments); void generateTmpAssemblyFile(std::string fileName, std::set& wantedContigs, assemblyOptions& opts, std::string& tmpFileName); int velvetWrapper(int hashLength, assemblyOptions& opts, std::string& tmpFileName); int capWrapper(int overlapLength, assemblyOptions& opts, std::string& tmpFileName); int assemblyMain(int argc, char * argv[]); #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/Aligner.cpp",".cpp","19707","512","/* * Aligner.cpp is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011, 2012 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include #include #include ""Exception.h"" #include ""Aligner.h"" #include ""LoggerSimp.h"" #include ""SeqUtils.h"" const unsigned char Aligner::seq_nt4_table[256] = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 }; // will convert any char to an A if it is not C,G,T const char Aligner::CHAR_TO_INDEX[128] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 1, 1, 1, 3, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 4, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 }; void Aligner::setMasterDR(StringToken master) { AL_masterDRToken = master; std::string master_string = mStringCheck->getString(AL_masterDRToken); if (AL_masterDRToken == 0) { // could not be found, through exception logError(""cannot find the token for DR string ""<< master_string); } AL_Offsets[AL_masterDRToken] = (int)(AL_length * CRASS_DEF_CONS_ARRAY_START); prepareMasterForAlignment(master_string); placeReadsInCoverageArray(AL_masterDRToken); calculateDRZone(); } void Aligner::alignSlave(StringToken& slaveDRToken) { AL_Offsets[slaveDRToken] = -1; std::string slaveDR = mStringCheck->getString(slaveDRToken); #ifdef DEBUG logInfo(""aligning slave"" << slaveDR << "" (""<getString(AL_masterDRToken), 4); logWarn(""******"", 4); flags[failed] = true; } } if (flags[failed]) { if(! flags[score_equal]){ logWarn(""Alignment Warning: Alignment failed"", 4); logWarn(""\tCannot place slave: ""<getString(AL_masterDRToken), 4); logWarn(""******"", 4); } return; } if (flags[reversed] ) { // we need to reverse all the reads and the DR for these reads try { ReadListIterator read_iter = mReads->at(slaveDRToken)->begin(); while (read_iter != mReads->at(slaveDRToken)->end()) { (*read_iter)->reverseComplementSeq(); read_iter++; } } catch(crispr::exception& e) { std::cerr<addString(slaveDR); (*mReads)[st] = (*mReads)[slaveDRToken]; (*mReads)[slaveDRToken] = NULL; slaveDRToken = st; } //std::cerr << AL_Offsets[AL_masterDRToken] + offset < "" << AL_ZoneEnd, 1); #endif // chars we luv! char alphabet[4] = {'A', 'C', 'G', 'T'}; // populate the conservation array int num_GT_zero = 0; for(int j = 0; j < AL_length; j++) { int max_count = 0; float total_count = 0.0; for(int i = 0; i < 4; i++) { total_count += static_cast(AL_coverage[coverageIndex(j,alphabet[i])]); if(AL_coverage[coverageIndex(j,alphabet[i])] > max_count) { max_count = AL_coverage[coverageIndex(j,alphabet[i])]; AL_consensus[j] = alphabet[i]; } } // we need at least CRASS_DEF_MIN_READ_DEPTH reads to call a DR if(total_count > CRASS_DEF_MIN_READ_DEPTH) { AL_conservation[j] = static_cast(max_count)/total_count; num_GT_zero++; } else { AL_conservation[j] = 0; } } // trim these back a bit (if we trim too much we'll get it back right now anywho) // CTS: Not quite true, if it is low coverage then there will be no extension! // check to see that this DR is supported by a bare minimum of reads if(num_GT_zero < CRASS_DEF_MIN_READ_DEPTH) { logWarn(""**WARNING: low confidence DR"", 1); } else { // first work from the left and trim back while(AL_ZoneStart > 0) { if(AL_conservation[AL_ZoneStart - 1] < CRASS_DEF_ZONE_EXT_CONS_CUT_OFF) AL_ZoneStart++; else break; } // next work from the right while(AL_ZoneEnd < AL_length - 1) { if(AL_conservation[AL_ZoneEnd + 1] < CRASS_DEF_ZONE_EXT_CONS_CUT_OFF) AL_ZoneEnd--; else break; } } //same as the loops above but this time extend outward while(AL_ZoneStart > 0) { if(AL_conservation[AL_ZoneStart - 1] >= CRASS_DEF_ZONE_EXT_CONS_CUT_OFF) AL_ZoneStart--; else break; } // next work to the right while(AL_ZoneEnd < AL_length - 1) { if(AL_conservation[AL_ZoneEnd + 1] >= CRASS_DEF_ZONE_EXT_CONS_CUT_OFF) AL_ZoneEnd++; else break; } #ifdef DEBUG logInfo(""DR zone (post fix): "" << AL_ZoneStart << "" -> "" << AL_ZoneEnd, 1); #endif } void Aligner::prepareSequenceForAlignment(std::string& sequence, uint8_t *transformedSequence) { size_t seq_length = sequence.length(); size_t i; for (i = 0; i < seq_length; ++i) transformedSequence[i] = seq_nt4_table[(int)sequence[i]]; // null terminate the sequences transformedSequence[seq_length] = '\0'; } void Aligner::prepareSlaveForAlignment(std::string& slaveDR, uint8_t *slaveTransformedForward, uint8_t *slaveTransformedReverse) { prepareSequenceForAlignment(slaveDR, slaveTransformedForward); std::string revcomp_slave_dr = reverseComplement(slaveDR); prepareSequenceForAlignment(revcomp_slave_dr, slaveTransformedReverse); } int Aligner::getOffsetAgainstMaster(std::string& slaveDR, AlignerFlag_t& flags) { #ifdef DEBUG logInfo(""getting offset of this slave against master DR"", 6) #endif int slave_dr_length = static_cast(slaveDR.length()); uint8_t* slave_dr_forward = new uint8_t[slave_dr_length+1]; uint8_t* slave_dr_reverse = new uint8_t[slave_dr_length+1]; prepareSlaveForAlignment(slaveDR, slave_dr_forward, slave_dr_reverse); // query profile kswq_t *slave_forward_query_profile = 0; kswq_t *slave_reverse_query_profile = 0; // alignment of slave against master kswr_t forward_return = ksw_align(slave_dr_length, slave_dr_forward, AL_masterDRLength, AL_masterDR, 5, AL_scoringMatrix, AL_gapOpening, AL_gapExtension, AL_xtra, &slave_forward_query_profile); kswr_t reverse_return = ksw_align(slave_dr_length, slave_dr_reverse, AL_masterDRLength, AL_masterDR, 5, AL_scoringMatrix, AL_gapOpening, AL_gapExtension, AL_xtra, &slave_reverse_query_profile); // free the query profile free(slave_forward_query_profile); free(slave_reverse_query_profile); delete [] slave_dr_reverse; delete [] slave_dr_forward; // figure out which alignment was better if (reverse_return.score == forward_return.score) { flags[score_equal] = true; return 0; } kswr_t best_alignment_info; if(reverse_return.score > forward_return.score) { best_alignment_info = reverse_return; flags[reversed] = true; } else { best_alignment_info = forward_return; } int min_query_seq_coverage = static_cast(slave_dr_length / 2); if(min_query_seq_coverage > best_alignment_info.score) { logWarn(""Alignment Warning: Slave Alignment Failure"",4); logWarn(""\tfailed query coverage test"", 4); logWarn(""\trequired: ""<getString(AL_masterDRToken) , 4); logWarn(""\ttb: ""<< best_alignment_info.tb, 4); logWarn(""\tte: ""<< best_alignment_info.te+1, 4); logWarn(""\tslave: ""<< slaveDR, 4); logWarn(""\tqb: ""<< best_alignment_info.qb, 4); logWarn(""\tqe: ""<< best_alignment_info.qe+1, 4); logWarn(""\tscore: ""<< best_alignment_info.score, 4); logWarn(""\t2nd-score: ""<< best_alignment_info.score2, 4); logWarn(""\t2nd-te: ""<< best_alignment_info.te2, 4); logWarn(""\toffset: ""<getString(AL_masterDRToken) , 4); logWarn(""\ttb: ""<< best_alignment_info.tb, 4); logWarn(""\tte: ""<< best_alignment_info.te+1, 4); logWarn(""\tslave: ""<< slaveDR, 4); logWarn(""\tqb: ""<< best_alignment_info.qb, 4); logWarn(""\tqe: ""<< best_alignment_info.qe+1, 4); logWarn(""\tscore: ""<< best_alignment_info.score, 4); logWarn(""\t2nd-score: ""<< best_alignment_info.score2, 4); logWarn(""\t2nd-te: ""<< best_alignment_info.te2, 4); logWarn(""\toffset: ""<at(currentDrToken)->begin(); int current_dr_length = static_cast(mStringCheck->getString(currentDrToken).length()); while (read_iter != mReads->at(currentDrToken)->end()) { // don't care about partials int dr_start_index = 0; int dr_end_index = 1; while(((*read_iter)->startStopsAt(dr_end_index) - (*read_iter)->startStopsAt(dr_start_index)) != (current_dr_length - 1)) { dr_start_index += 2; dr_end_index += 2; } // go through every full length DR in the read and place in the array do { if(((*read_iter)->startStopsAt(dr_end_index) - (*read_iter)->startStopsAt(dr_start_index)) == (current_dr_length - 1)) { // we need to find the first kmer which matches the mode. int this_read_start_pos = AL_Offsets[currentDrToken] - (*read_iter)->startStopsAt(dr_start_index); for(int i = 0; i < (int)(*read_iter)->getSeqLength(); i++) { char current_nt = (*read_iter)->getSeqCharAt(i); int index_b = i+this_read_start_pos; if((index_b) >= AL_length) { logError(""***FATAL*** MEMORY CORRUPTION: The consensus/coverage arrays are too short""); } if((index_b) < 0) { logError(""***FATAL*** MEMORY CORRUPTION: index = ""<< index_b<<"" less than array begining""); } if(coverageIndex(index_b,current_nt) >= (int)AL_coverage.size()) { logError(""***FATAL*** MEMORY CORRUPTION: index = ""<= ""<= (int)((*read_iter)->numRepeats()*2)) { break; } } while(((*read_iter)->startStopsAt(dr_end_index) - (*read_iter)->startStopsAt(dr_start_index)) == (current_dr_length - 1)); read_iter++; } } void Aligner::extendSlaveDR(StringToken& token, size_t slaveDRLength, std::string &extendedSlaveDR){ //StringToken token = mStringCheck->getToken(slaveDR); // go into the reads and get the sequence of the DR plus a few bases on either side ReadListIterator read_iter = mReads->at(token)->begin(); while (read_iter != mReads->at(token)->end()) { // don't care about partials int dr_start_index = 0; int dr_end_index = 1; // Find the DR which is the right DR length. // compensates for partial repeats while(((*read_iter)->startStopsAt(dr_end_index) - (*read_iter)->startStopsAt(dr_start_index)) != ((int)(slaveDRLength) - 1)) { dr_start_index += 2; dr_end_index += 2; } // check that the DR does not lie too close to the end of the read so that we can extend if((*read_iter)->startStopsAt(dr_start_index) - 2 < 0 || (*read_iter)->startStopsAt(dr_end_index) + 2 > (*read_iter)->getSeqLength()) { // go to the next read read_iter++; continue; } else { // substring the read to get the new length extendedSlaveDR = (*read_iter)->getSeq().substr((*read_iter)->startStopsAt(dr_start_index) - 2, slaveDRLength + 4); break; } } } void Aligner::calculateDRZone() { ReadListIterator read_iter = mReads->at(AL_masterDRToken)->begin(); while (read_iter != mReads->at(AL_masterDRToken)->end()) { // don't care about partials int dr_start_index = 0; int dr_end_index = 1; // Find the DR which is the master DR length. // compensates for partial repeats while(((*read_iter)->startStopsAt(dr_end_index) - (*read_iter)->startStopsAt(dr_start_index)) != (AL_masterDRLength - 1)) { dr_start_index += 2; dr_end_index += 2; } // This if is to catch some weird-ass scenario, if you get a report that everything is wrong, then you've most likely // corrupted memory somewhere! if(((*read_iter)->startStopsAt(dr_end_index) - (*read_iter)->startStopsAt(dr_start_index)) == (AL_masterDRLength - 1)) { // the start of the read is the position of the master DR - the position of the DR in the read int this_read_start_pos = AL_Offsets.at(AL_masterDRToken) - (*read_iter)->startStopsAt(dr_start_index); AL_ZoneStart = this_read_start_pos + (*read_iter)->startStopsAt(dr_start_index); AL_ZoneEnd = this_read_start_pos + (*read_iter)->startStopsAt(dr_end_index); break; } } } void Aligner::print(std::ostream& out) { std::vector::iterator iter; for (int j = 1; j <= 4;++j) { for (int i = 0; i < AL_length; ++i) { out<getToken(slave)<<"") in array"" <getString(AL_masterDRToken) << ""\ntb: ""<< alignment.tb<< ""\nte: ""<< alignment.te+1<< ""\nq: ""<< slave<< ""\nqb: ""<< alignment.qb<< ""\nqe: ""<< alignment.qe+1<< ""\nscore: ""<< alignment.score<< ""\n2nd-score: ""<< alignment.score2<< ""\n2nd-te: ""<< alignment.te2<< ""\noffset: ""<. * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef __CRASS_H #define __CRASS_H // system includes #include #include #include #include #include // local includes #include ""crassDefines.h"" #include ""kseq.h"" #include ""CrisprNode.h"" #include ""WorkHorse.h"" //************************************** // user input + system //************************************** static struct option long_options [] = { {""layoutAlgorithm"",required_argument,NULL,'a'}, {""numBins"",required_argument,NULL,'b'}, {""graphColour"",required_argument,NULL,'c'}, {""minDR"", required_argument, NULL, 'd'}, {""maxDR"", required_argument, NULL, 'D'}, #ifdef DEBUG {""noDebugGraph"",no_argument,NULL,'e'}, #endif {""covCutoff"",required_argument,NULL,'f'}, {""logToScreen"", no_argument, NULL, 'g'}, {""showSingltons"",no_argument,NULL,'G'}, {""help"", no_argument, NULL, 'h'}, //{""removeHomopolymers"",no_argument,NULL,'H'}, {""kmerCount"", required_argument, NULL, 'k'}, {""graphNodeLen"",required_argument,NULL,'K'}, {""logLevel"", required_argument, NULL, 'l'}, {""longDescription"",no_argument,NULL,'L'}, {""minNumRepeats"", required_argument, NULL, 'n'}, {""outDir"", required_argument, NULL, 'o'}, #ifdef RENDERING {""noRendering"",no_argument,NULL,'r'}, #endif {""minSpacer"", required_argument, NULL, 's'}, {""maxSpacer"", required_argument, NULL, 'S'}, {""version"", no_argument, NULL, 'V'}, {""windowLength"", required_argument, NULL, 'w'}, {""spacerScalling"",required_argument,NULL,'x'}, {""repeatScalling"",required_argument,NULL,'y'}, {""noScalling"",no_argument,NULL,'z'}, #ifdef SEARCH_SINGLETON {""searchChecker"", required_argument, NULL, 0}, #endif {NULL, no_argument, NULL, 0} }; void usage(void); void versionInfo(void); //void recursiveMkdir(std::string dir); int processOptions(int argc, char *argv[], options *opts); #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/writer.h",".h","14642","275","/* * crass.h is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef WRITER_H #define WRITER_H #include ""base.h"" namespace crispr { namespace xml { class writer : virtual public base { //members xercesc::DOMDocument * XW_DocElem; int XW_CurrentSourceId; public: //constructor/destructor writer(); ~writer(); /** Create an in-memory representation of a crispr file * @param rootElement Name for the root element * @param versionNumber version for the crispr file to have * @param errorNumber an integer for saving any error codes produced during document creation * @return The xercesc::DOMElement for the root node or NULL on failure */ xercesc::DOMElement * createDOMDocument(std::string rootElement, std::string versionNumber, int& errorNumber ); xercesc::DOMElement * createDOMDocument(const char * rootElement, const char * versionNumber, int& errorNumber ); /** add a 'metadata' tag to 'group' * @param parentNode the xercesc::DOMElement of the 'group' tag * @return the xercesc::DOMElement of the 'metadata' tag */ xercesc::DOMElement * addMetaData(xercesc::DOMElement * parentNode); /** add a 'metadata' tag to 'group' with notes * @param parentNode the xercesc::DOMElement of the 'group' tag * @param notes freeform notes that the user can add in * @return the xercesc::DOMElement of the 'metadata' tag */ xercesc::DOMElement * addMetaData(std::string notes, xercesc::DOMElement * parentNode); /** add in files referenced by this group * @param type The type of reference file. Must be one of image|sequence|log|data * @param url path to the file * @param parentNode xercesc::DOMElement of the 'metadata' tag */ void addFileToMetadata(std::string type, std::string url, xercesc::DOMElement * parentNode); /** add extra notes to the 'metadata' * @param notes freeform notes added by the user * @param parentNode xercesc::DOMElement of the 'metadata' tag */ void addNotesToMetadata(std::string notes, xercesc::DOMElement * parentNode); /** add a 'group' to the root element * @param gID The unique group identifier * @param drConsensus The direct repeat concensus sequence for this group * @param parentNode xercesc::DOMElement of the root element */ xercesc::DOMElement * addGroup(std::string& gID, std::string& drConsensus, xercesc::DOMElement * parentNode); /** add the 'data' to 'group'. This automatically creates the child nodes for the 'sources' 'drs' and 'spacers' tags * @param parentNode the 'group' xercesc::DOMElement * @return The xercesc::DOMElement of the 'data' tag */ xercesc::DOMElement * addData(xercesc::DOMElement * parentNode); /** add the 'assembly' to 'group' * @param parentNode the 'group' xercesc::DOMElement * @return The xercesc::DOMElement of the 'assembly' tag */ xercesc::DOMElement * addAssembly(xercesc::DOMElement * parentNode); /** add a direct repeat 'dr' tag to the 'drs' tag * @param drid The unique DR id for this group * @param seq The sequence of the direct repeat in its lowest lexicographical form * @param parentNode The xercesc::DOMElement of the 'drs' tag */ void addDirectRepeat(std::string& drid, std::string& seq, xercesc::DOMElement * parentNode); /** add a 'spcaer' tag to the 'spacers' * @param seq sequence of the spacer in the form that would appear if the direct repeat is in its lowest lexicographical form * @param spid the unique spacer identifier for this group * @param parentNode the xercesc::DOMElement of the 'spacers' tag * @param cov The coverage of the spacer. Defaults to zero * @return the xercesc::DOMElement for the 'spacer' tag */ xercesc::DOMElement * addSpacer(std::string& seq, std::string& spid, xercesc::DOMElement * parentNode, std::string cov = ""0"" ); /** create a 'flankers' tag in 'data' * @param parentNode the xercesc::DOMElement of the 'data' tag * @return the xercesc::DOMElement of the 'flankers' tag */ xercesc::DOMElement * createFlankers(xercesc::DOMElement * parentNode); /** add a 'flanker' tag to the 'flankers' tag * @param seq sequence of the flanker in the form that would appear if the direct repeat is in its lowest lexicographical form * @param flid the unique flanker identifier for this group * @param parentNode the xercesc::DOMElement of the 'flankers' tag * @return the xercesc::DOMElement of the 'flanker' tag */ xercesc::DOMElement * addFlanker(std::string& seq, std::string& flid, xercesc::DOMElement * parentNode); /** add a 'contig' to an 'assembly' * @param cid a unique contig id for this group * @param parentNode the xercesc::DOMElement of the 'assembly' tag * @return the xercesc::DOMElement of the 'contig' tag */ xercesc::DOMElement * addContig(std::string& cid, xercesc::DOMElement * parentNode); /** add the concensus sequence to the contig * @param concensus A string of DNA characters representing the joined sequence of all the spacers and direct repeats for this contig * @param parentNode the xercesc::DOMElement of the 'contig' tag */ void createConsensus(std::string& concensus, xercesc::DOMElement * parentNode); /** Add a 'cspacer' to a 'contig' * @param spid Unique identifier for the spacer. should be the same as listed in the 'spacers' tag in 'data' * @param parentNode the xercesc::DOMElement of the 'contig' tag * @return the xercesc::DOMElement of the 'cspacer' tag */ xercesc::DOMElement * addSpacerToContig(std::string& spid, xercesc::DOMElement * parentNode); /** use to create a backward spacers ('bspacers') or forward spacers ('fspacers') child elements of 'cspacer' * @param tag A string of either ""bspacers"" or ""fspacers"" * @return the xercesc::DOMElement of either ""bspacers"" or ""fspacers"" */ xercesc::DOMElement * createSpacers(std::string tag); /** A convienience method that calls createSpacers, Used only for making the code more explicit * @param tag A string of either ""bflankers"" or ""fflankers"" * @return the xercesc::DOMElement of either ""bflankers"" or ""fflankers"" */ xercesc::DOMElement * createFlankers(std::string tag); /** add either a backward spacer (bs) or forward spacer (fs) tags to a cspacer tag * @param tag A string that describes the type of association ('bs' or 'fs') * @param spid The unique spacer id for the link. Should be the same as an spid listed in 'spacers' tag inside 'data' * @param drid The unique direct repeat id for the DR that sits inbetween the two spacers * @param drconf * @param parentNode The xercesc::DOMElement corresponding to one of bspacers, fspacers */ void addSpacer(std::string tag, std::string& spid, std::string& drid, std::string& drconf, xercesc::DOMElement * parentNode); /** add either a backward flanker (bf) or forward flanker (ff) tags to cspacer * @param tag A string that describes the type of association ('bf' or 'ff') * @param flid The unique flanker id for the link. Should be the same as an spid listed in 'fankers' tag inside 'data' * @param drconf * @param directjoin * @param parentNode The xercesc::DOMElement corresponding to one of bflankers, fflankers */ void addFlanker(std::string tag, std::string& flid, std::string& drconf, std::string& directjoin, xercesc::DOMElement * parentNode); /** create the sources tag for a group * @param parentNode The xercesc::DOMElement for the 'group' tag * @return The xercesc::DOMElement for the 'sources' tag */ xercesc::DOMElement * addSources(xercesc::DOMElement * parentNode); /** add a 'source' tag for the sources * @param accession The accession for the source as it would appear in a fasta file * @param soid The unique source identifier for this source. Ideally this should be short, containing sharacters and * numbers for future reference within the cirpsr file. * @param parentNode The xercesc::DOMElement of the 'sources' tag * @return The xercesc::DOMElement of teh 'source' tag */ xercesc::DOMElement * addSource(std::string accession, std::string soid, xercesc::DOMElement * parentNode); /** add a source tag for a spacer * @param soid The unique source identifier for this source. Sould be the same as listed in the 'sources' inside 'data' * @param parentNode The xercesc::DOMElement of the 'spacer' that was fould inside this source * @return The xercesc::DOMElement of the 'source' tag */ xercesc::DOMElement * addSpacerSource(std::string soid, xercesc::DOMElement * parentNode); /** add start and end positions for 'source' in 'spacer' * @param start The start position in the source for the spacer * @param end The end position in the source for the spacer * @param parentNode The 'source' tag to the spacer */ void addStartAndEndPos(std::string start, std::string end, xercesc::DOMElement * parentNode); /** add a 'program' tag to 'metadata' * @param parentNode The xercesc::DOMElement of the 'metadata' tag * @return The xercesc::DOMElement of the 'program' tag */ xercesc::DOMElement * addProgram(xercesc::DOMElement * parentNode); /** add a 'name' tag to 'program' * @param progName The name of the program that called this CRISPR * @param parentNode The xercesc::DOMElement of the 'program' tag */ void addProgName(std::string progName, xercesc::DOMElement * parentNode); /** add a 'version' tag to 'program' * @param progVersion The version of the program that called this CRISPR * @param parentNode The xercesc::DOMElement of the 'program' tag */ void addProgVersion(std::string progVersion, xercesc::DOMElement * parentNode); /** add a 'command' tag to 'program' * @param progCommand The command line options used to call this CRISPR * @param parentNode The xercesc::DOMElement of the 'program' tag */ void addProgCommand(std::string progCommand, xercesc::DOMElement * parentNode); /** print the current document to file * @param outFileName The name of the output file */ bool printDOMToFile(std::string outFileName ); /** print the current document to screen */ bool printDOMToScreen(void); bool printDOMToFile(std::string outFileName, xercesc::DOMDocument * domDoc ); bool printDOMToScreen( xercesc::DOMDocument * domDoc); /** convienience method to return the root element of the current document * @return The xercesc::DOMElement for the root ('crispr') tag */ inline xercesc::DOMElement * getRootElement(void) { return XW_DocElem->getDocumentElement(); } /** convienience method to return the current document * @return The xercesc::DOMDocument for this writer */ inline xercesc::DOMDocument * getDocumentObj(void) { return XW_DocElem; } }; } } #endif","Unknown" "CRISPR","ctSkennerton/crass","src/crass/Aligner.h",".h","8479","245","/* * Aligner.h is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011, 2012 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef crass_Aligner_h #define crass_Aligner_h #include #include #include #include #include ""ksw.h"" #include ""StringCheck.h"" #include ""Types.h"" #include ""crassDefines.h"" #define coverageIndex(i,c) (((CHAR_TO_INDEX[(int)c] - 1) * AL_length) + i) typedef std::bitset<3> AlignerFlag_t; class Aligner { // named accessors for the bitset flags enum Flag_t { reversed, failed, score_equal }; static const unsigned char seq_nt4_table[256];/* = { 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 0, 4, 1, 4, 4, 4, 2, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 3, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4 };*/ // ASCII table that converts characters into the multiplier // used for finding the correct index in the coverage array static const char CHAR_TO_INDEX[128];/* = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 2, 0, 0, 0, 3, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 4, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };*/ public: //int gapo = 5, gape = 2, minsc = 0, xtra = KSW_XSTART; Aligner(int length, ReadMap *wh_reads, StringCheck *wh_st, int gapo=5, int gape=2, int minsc=5, int xtra=KSW_XSTART): AL_length(length), AL_consensus(length,'N'), AL_conservation(length, 0.0f), AL_coverage(length*4, 0), AL_gapOpening(gapo), AL_gapExtension(gape), AL_minAlignmentScore(minsc), AL_xtra(xtra) { // assign workhorse variables mReads = wh_reads; mStringCheck = wh_st; // set up default parameters for ksw alignment int sa = 1, sb = 3, i, j, k; if (AL_minAlignmentScore > 0xffff) AL_minAlignmentScore = 0xffff; if (AL_minAlignmentScore > 0) AL_xtra |= KSW_XSUBO | AL_minAlignmentScore; // initialize scoring matrix for (i = k = 0; i < 4; ++i) { for (j = 0; j < 4; ++j) AL_scoringMatrix[k++] = i == j? sa : -sb; AL_scoringMatrix[k++] = 0; // ambiguous base } for (j = 0; j < 5; ++j) AL_scoringMatrix[k++] = 0; } ~Aligner(){ if (AL_masterDR != NULL) { delete [] AL_masterDR; AL_masterDR = NULL; } } inline StringToken getMasterDrToken(){return AL_masterDRToken;} void setMasterDR(StringToken master); void alignSlave(StringToken& slaveDRToken); // add in all of the reads for this group to the coverage array void generateConsensus(); void print(std::ostream &out = std::cout); inline std::map::iterator offsetBegin(){return AL_Offsets.begin();} inline std::map::iterator offsetEnd(){return AL_Offsets.end();} inline std::map::iterator offsetFind(StringToken& token){return AL_Offsets.find(token);} inline int offset(StringToken& drToken){return AL_Offsets[drToken];} inline int getDRZoneStart(){return AL_ZoneStart;} inline int getDRZoneEnd(){return AL_ZoneEnd;} inline void setDRZoneStart(int i){AL_ZoneStart = i;} inline void setDRZoneEnd(int i){AL_ZoneEnd = i;} inline int coverageAt(int i, char c){return AL_coverage.at(coverageIndex(i,c)); } inline char consensusAt(int i){return AL_consensus.at(i);} inline float conservationAt(int i){return AL_conservation.at(i);} inline int depthAt(int i){return AL_coverage[coverageIndex(i,'A')] + AL_coverage[coverageIndex(i,'C')] + AL_coverage[coverageIndex(i,'G')] + AL_coverage[coverageIndex(i,'T')];} private: // private methods // // call ksw alignment to determine the offset for this slave against the master int getOffsetAgainstMaster(std::string& slaveDR, AlignerFlag_t& flags); // transform any sequence into the right form for ksw void prepareSequenceForAlignment(std::string& sequence, uint8_t *transformedSequence); // transform a slave DR into the right form for ksw in both orientations void prepareSlaveForAlignment(std::string& slaveDR, uint8_t *slaveTransformedForward, uint8_t *slaveTransformedReverse); // transform the master DR into the right form for ksw inline void prepareMasterForAlignment(std::string& masterDR) { AL_masterDRLength = masterDR.length(); //AL_minAlignmentScore = static_cast(AL_masterDRLength * 0.5); AL_masterDR = new uint8_t[AL_masterDRLength+1]; prepareSequenceForAlignment(masterDR, AL_masterDR); }; void placeReadsInCoverageArray(StringToken& currentDRToken); void extendSlaveDR(StringToken& slaveDRToken, size_t slaveDRLength, std::string& extendedSlaveDR); void calculateDRZone(); void printAlignment(const kswr_t& alignment, const std::string& slave, std::ostream& out); //Members // length of the arrays int AL_length; // Vectors to hold the alignment data std::vector AL_consensus; std::vector AL_conservation; std::vector AL_coverage; // Storage of all the offsets against the master std::map AL_Offsets; // smith-waterman default parameters int AL_gapOpening; int AL_gapExtension; int AL_minAlignmentScore; int AL_xtra; int8_t AL_scoringMatrix[25]; // master DR uint8_t *AL_masterDR; int AL_masterDRLength; StringToken AL_masterDRToken; // ""Glue"" between WorkHorse ReadMap * mReads; StringCheck * mStringCheck; int AL_ZoneStart; int AL_ZoneEnd; }; #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/base.h",".h","14606","412","/* * crass.h is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef BASE_H #define BASE_H // system includes #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #if defined(XERCES_NEW_IOSTREAMS) #include #else #include #endif #include ""Exception.h"" #define tc(buf) xercesc::XMLString::transcode(buf) // same as above but more verbose #define transcode_xmlch(buf) xercesc::XMLString::transcode(buf) #define xr(buf) xercesc::XMLString::release(buf) // same as above but more verbose #define free_xmlch(buf) xercesc::XMLString::release(buf) // Error codes enum { ERROR_ARGS = 1, ERROR_XERCES_INIT, ERROR_PARSE, ERROR_EMPTY_DOCUMENT }; namespace crispr { namespace xml { class base { public: //constructor / destructor base(void); ~base(void); // funtions used to keep constructor and destructor clean // and so the inherated classes can use them void init(void); void alloc(void); void dealloc(void); void release(void); // // Generic get // // grep ATTLIST crispr-1.1.dtd | perl -ne 's/[^ ]* [^ ]* ([^ ]*) .*/\1/ ;chomp; my $original = $_; s/\b(\w)/\U$1/g; print ""inline XMLCh * attr_$_(void) { return ATTR_$original; }\n"";' | sort | uniq // grep ELEMENT crispr-1.1.dtd | perl -ne 's/[^ ]* ([^ ]*) .*/\1/ ;chomp; my $original = $_; s/\b(\w)/\U$1/g; print ""inline XMLCh * tag_$_(void) { return TAG_$original; }\n"";' |sort | uniq /** Accessor to the 'accession' attribute * @return XMLCh * of 'accession' */ inline XMLCh * attr_Accession(void) { return ATTR_accession; } /** Accessor to the 'cid' attribute * @return XMLCh * of 'cid' */ inline XMLCh * attr_Cid(void) { return ATTR_cid; } /** Accessor to the 'confcnt' attribute * @return XMLCh * of 'confcnt' */ inline XMLCh * attr_Confcnt(void) { return ATTR_confcnt; } /** Accessor to the 'cov' attribute * @return XMLCh * of 'cov' */ inline XMLCh * attr_Cov(void) { return ATTR_cov; } /** Accessor to the 'directjoin' attribute * @return XMLCh * of 'directjoin' */ inline XMLCh * attr_Directjoin(void) { return ATTR_directjoin; } /** Accessor to the drconf attribute * @return XMLCh * of drconf */ inline XMLCh * attr_Drconf(void) { return ATTR_drconf; } /** Accessor to the drid attribute * @return XMLCh * of drid */ inline XMLCh * attr_Drid(void) { return ATTR_drid; } /** Accessor to the drseq attribute * @return XMLCh * of drseq */ inline XMLCh * attr_Drseq(void) { return ATTR_drseq; } /** Accessor to the flid attribute * @return XMLCh * of flid */ inline XMLCh * attr_Flid(void) { return ATTR_flid; } /** Accessor to the gid attribute * @return XMLCh * of gid */ inline XMLCh * attr_Gid(void) { return ATTR_gid; } /** Accessor to the seq attribute * @return XMLCh * of seq */ inline XMLCh * attr_Seq(void) { return ATTR_seq; } /** Accessor to the soid attribute * @return XMLCh * of soid */ inline XMLCh * attr_Soid(void) { return ATTR_soid; } /** Accessor to the spid attribute * @return XMLCh * of spid */ inline XMLCh * attr_Spid(void) { return ATTR_spid; } /** Accessor to the totcnt attribute * @return XMLCh * of totcnt */ inline XMLCh * attr_Totcnt(void) { return ATTR_totcnt; } /** Accessor to the type attribute * @return XMLCh * of type */ inline XMLCh * attr_Type(void) { return ATTR_type; } /** Accessor to the url attribute * @return XMLCh * of url */ inline XMLCh * attr_Url(void) { return ATTR_url; } /** Accessor to the version attribute * @return XMLCh * of version */ inline XMLCh * attr_Version(void) { return ATTR_version; } /** Accessor to the assembly element * @return XMLCh * of assembly */ inline XMLCh * tag_Assembly(void) { return TAG_assembly; } /** Accessor to the bf element * @return XMLCh * of bf */ inline XMLCh * tag_Bf(void) { return TAG_bf; } /** Accessor to the bflankers element * @return XMLCh * of bflankers */ inline XMLCh * tag_Bflankers(void) { return TAG_bflankers; } /** Accessor to the bs element * @return XMLCh * of bs */ inline XMLCh * tag_Bs(void) { return TAG_bs; } /** Accessor to the bspacers element * @return XMLCh * of bspacers */ inline XMLCh * tag_Bspacers(void) { return TAG_bspacers; } /** Accessor to the command element * @return XMLCh * of command */ inline XMLCh * tag_Command(void) { return TAG_command; } /** Accessor to the consensus element * @return XMLCh * of consensus */ inline XMLCh * tag_Consensus(void) { return TAG_consensus; } /** Accessor to the contig element * @return XMLCh * of contig */ inline XMLCh * tag_Contig(void) { return TAG_contig; } /** Accessor to the crispr element * @return XMLCh * of crispr */ inline XMLCh * tag_Crispr(void) { return TAG_crispr; } /** Accessor to the cspacer element * @return XMLCh * of cspacer */ inline XMLCh * tag_Cspacer(void) { return TAG_cspacer; } /** Accessor to the data element * @return XMLCh * of data */ inline XMLCh * tag_Data(void) { return TAG_data; } /** Accessor to the dr element * @return XMLCh * of dr */ inline XMLCh * tag_Dr(void) { return TAG_dr; } /** Accessor to the drs element * @return XMLCh * of drs */ inline XMLCh * tag_Drs(void) { return TAG_drs; } /** Accessor to the epos element * @return XMLCh * of epos */ inline XMLCh * tag_Epos(void) { return TAG_epos; } /** Accessor to the ff element * @return XMLCh * of ff */ inline XMLCh * tag_Ff(void) { return TAG_ff; } /** Accessor to the fflankers element * @return XMLCh * of fflankers */ inline XMLCh * tag_Fflankers(void) { return TAG_fflankers; } /** Accessor to the file element * @return XMLCh * of file */ inline XMLCh * tag_File(void) { return TAG_file; } /** Accessor to the flanker element * @return XMLCh * of flanker */ inline XMLCh * tag_Flanker(void) { return TAG_flanker; } /** Accessor to the flankers element * @return XMLCh * of flankers */ inline XMLCh * tag_Flankers(void) { return TAG_flankers; } /** Accessor to the fs element * @return XMLCh * of fs */ inline XMLCh * tag_Fs(void) { return TAG_fs; } /** Accessor to the fspacers element * @return XMLCh * of fspacers */ inline XMLCh * tag_Fspacers(void) { return TAG_fspacers; } /** Accessor to the group element * @return XMLCh * of group */ inline XMLCh * tag_Group(void) { return TAG_group; } /** Accessor to the metadata element * @return XMLCh * of metadata */ inline XMLCh * tag_Metadata(void) { return TAG_metadata; } /** Accessor to the name element * @return XMLCh * of name */ inline XMLCh * tag_Name(void) { return TAG_name; } /** Accessor to the notes element * @return XMLCh * of notes */ inline XMLCh * tag_Notes(void) { return TAG_notes; } /** Accessor to the program element * @return XMLCh * of program */ inline XMLCh * tag_Program(void) { return TAG_program; } /** Accessor to the source element * @return XMLCh * of source */ inline XMLCh * tag_Source(void) { return TAG_source; } /** Accessor to the sources element * @return XMLCh * of sources */ inline XMLCh * tag_Sources(void) { return TAG_sources; } /** Accessor to the spos element * @return XMLCh * of spos */ inline XMLCh * tag_Spos(void) { return TAG_spos; } /** Accessor to the spacer element * @return XMLCh * of spacer */ inline XMLCh * tag_Spacer(void) { return TAG_spacer; } /** Accessor to the spacers element * @return XMLCh * of spacers */ inline XMLCh * tag_Spacers(void) { return TAG_spacers; } /** Accessor to the version element * @return XMLCh * of version */ inline XMLCh * tag_Version(void) { return TAG_version; } private: // grep ATTLIST crispr-1.1.dtd | sed -e ""s%[^ ]* [^ ]* \([^ ]*\) .*%XMLCh\* ATTR_\1;%"" | sort | uniq // grep ELEMENT crass-1.1.dtd | sed -e ""s%[^ ]* \([^ ]*\) .*%XMLCh\* TAG_\1;%"" | sort | uniq XMLCh * ATTR_accession; XMLCh * ATTR_cid; XMLCh * ATTR_confcnt; XMLCh * ATTR_cov; XMLCh * ATTR_directjoin; XMLCh * ATTR_drconf; XMLCh * ATTR_drid; XMLCh * ATTR_drseq; XMLCh * ATTR_flid; XMLCh * ATTR_gid; XMLCh * ATTR_seq; XMLCh * ATTR_soid; XMLCh * ATTR_spid; XMLCh * ATTR_totcnt; XMLCh * ATTR_type; XMLCh * ATTR_url; XMLCh * ATTR_version; XMLCh * TAG_assembly; XMLCh * TAG_bf; XMLCh * TAG_bflankers; XMLCh * TAG_bs; XMLCh * TAG_bspacers; XMLCh * TAG_command; XMLCh * TAG_consensus; XMLCh * TAG_contig; XMLCh * TAG_crispr; XMLCh * TAG_cspacer; XMLCh * TAG_data; XMLCh * TAG_dr; XMLCh * TAG_drs; XMLCh * TAG_epos; XMLCh * TAG_ff; XMLCh * TAG_fflankers; XMLCh * TAG_file; XMLCh * TAG_flanker; XMLCh * TAG_flankers; XMLCh * TAG_fs; XMLCh * TAG_fspacers; XMLCh * TAG_group; XMLCh * TAG_metadata; XMLCh * TAG_name; XMLCh * TAG_notes; XMLCh * TAG_program; XMLCh * TAG_source; XMLCh * TAG_sources; XMLCh * TAG_spacer; XMLCh * TAG_spacers; XMLCh * TAG_spos; XMLCh * TAG_version; }; } } #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/Utils.h",".h","1611","45","/* * Utils.h is part of the crisprtools project * * Created by Connor Skennerton on 3/12/11. * Copyright 2011 Connor Skennerton. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef crisprtools_Utils_h #define crisprtools_Utils_h #include #include void recursiveMkdir(std::string dir); bool fileOrString(const char * str); void parseFileForGroups(std::set& groups, const char * filePath); void generateGroupsFromString(std::string str, std::set& groups); #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/Utils.cpp",".cpp","2965","100","/* * Utils.cpp is part of the crisprtools project * * Created by Connor Skennerton on 3/12/11. * Copyright 2011 Connor Skennerton. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include #include #include #include #include #include #include ""Utils.h"" #include ""StlExt.h"" #include ""Exception.h"" void recursiveMkdir(std::string dir) { std::string tmp; size_t pos = 0; while ( std::string::npos != (pos = dir.find('/',pos+1)) ) { tmp = dir.substr(0,pos); mkdir(tmp.c_str(), (S_IRWXU | S_IRWXG)); } mkdir(dir.c_str(), (S_IRWXU | S_IRWXG)); } bool fileOrString(const char * str) { struct stat file_stats; if (-1 == stat(str, &file_stats)) { // some sort of error occured but // it might still be a file as input // with just a weird error switch (errno) { case ENOENT: // no such file or directory // it's a string return false; break; default: // it was a file but there is some other error throw crispr::input_exception(strerror(errno)); break; } } else { return true; } } void parseFileForGroups(std::set& groups, const char * filePath) { // read through a file of group numbers std::string line; std::fstream in_file; in_file.open(filePath); if ( in_file.good()) { while (in_file >> line) { groups.insert(line); } } else { // error std::string s = ""cannot read file ""; throw crispr::input_exception( (s + filePath).c_str()); } } void generateGroupsFromString(std::string str, std::set& groups) { split(str, groups, "",""); }","C++" "CRISPR","ctSkennerton/crass","src/crass/WorkHorse.h",".h","7523","200","// File: WorkHorse.h // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // This class is responsible for ""running"" the algorithm // // -------------------------------------------------------------------- // Copyright 2011, 2012 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // #ifndef WorkHorse_h #define WorkHorse_h // system includes #include #include #include #include // local includes #include ""crassDefines.h"" #include ""libcrispr.h"" #include ""NodeManager.h"" #include ""ReadHolder.h"" #include ""StringCheck.h"" #include ""writer.h"" #if SEARCH_SINGLETON #include ""SearchChecker.h"" #endif #include ""Types.h"" #include ""Aligner.h"" // typedefs typedef std::map DR_List; typedef std::map::iterator DR_ListIterator; bool sortLengthAssending( const std::string &a, const std::string &b); bool sortLengthDecending( const std::string &a, const std::string &b); bool includeSubstring(const std::string& a, const std::string& b); bool isNotEmpty(const std::string& a); class WorkHorse { public: WorkHorse (options * opts, std::string timestamp, std::string commandLine) { mOpts = opts; mMaxReadLength = 0; mStringCheck.setName(""WH""); mTimeStamp = timestamp; mCommandLine = commandLine; } ~WorkHorse(); // do all the work! int doWork(Vecstr seqFiles); //************************************** // file IO //************************************** int numOfReads(void); private: void clearReadList(ReadList * tmp_list); void clearReadMap(ReadMap * tmp_map); //************************************** // functions used to cluster DRs into groups and identify the ""true"" DR //************************************** int parseSeqFiles(Vecstr seqFiles); // parse the raw read files int buildGraph(void); // build the basic graph structue int cleanGraph(void); // clean the graph structue void removeRedundantRepeats(Vecstr& repeatVector); Vecstr * createNonRedundantSet(GroupKmerMap& groupKmerCountsMap, int& nextFreeGID); int removeLowConfidenceNodeManagers(void); int findConsensusDRs(GroupKmerMap& groupKmerCountsMap, int& nextFreeGID); bool clusterDRReads(StringToken DRToken, int * nextFreeGID, std::map * k2GIDMap, GroupKmerMap * groupKmerCountsMap); // cut kmers and hash bool findMasterDR(int GID, StringToken& masterDRToken); bool populateCoverageArray( int GID, Aligner& drAligner ); std::string calculateDRConsensus(int GID, Aligner& drAligner, int& nextFreeGID, int& collapsedPos, std::map& collapsedOptions, std::map& refinedDREnds ); void splitGroupedDR( std::map& collaped_options, Aligner& dr_aligner, int collapsed_pos, int GID, int * nextFreeGID); bool parseGroupedDRs( int GID, int * nextFreeGID); void combineGroupsWithIdenticalDRs(); int numberOfReadsInGroup(DR_Cluster * currentGroup); void cleanGroup(int GID); //************************************** // spacer graphs //************************************** int makeSpacerGraphs(void); int cleanSpacerGraphs(void); int generateFlankers(void); //************************************** // contig making //************************************** int splitIntoContigs(void); //************************************** // file IO //************************************** inline void dumpReads( NodeManager * manager, std::string& fileName, bool showDetached=false) { manager->dumpReads(fileName, showDetached); } //int dumpSpacers(void); // Dump the spacers for this group to file int renderDebugGraphs(void); // render debug graphs int renderDebugGraphs(std::string namePrefix); int renderSpacerGraphs(void); // render debug graphs int renderSpacerGraphs(std::string namePrefix); int checkFileOrError(const char * fileName); bool outputResults(void) { return outputResults(mOpts->output_fastq + ""crass""); } // print all the assembly gossip to XML bool outputResults(std::string namePrefix); bool addDataToDOM(crispr::xml::writer * xmlDoc, xercesc::DOMElement * groupElement, int groupNumber); bool addMetadataToDOM(crispr::xml::writer * xmlDoc, xercesc::DOMElement * groupElement, int groupNumber); // members DR_List mDRs; // list of nodemanagers, cannonical DRs, one nodemanager per direct repeat ReadMap mReads; // reads containing possible double DRs options * mOpts; // search options std::string mOutFileDir; // where to spew text to int mMaxReadLength; // the average seen read length StringCheck mStringCheck; // Place to swap strings for tokens std::string mTimeStamp; // hold the timestmp so we can make filenames std::string mCommandLine; // holds the exact command line string for logging purposes // global variables used to cluster and munge DRs std::map mGroupMap; // list of valid group IDs DR_Cluster_Map mDR2GIDMap; // map a DR (StringToken) to a GID std::map mTrueDRs; // map GId to true DR strings }; #endif //WorkHorse_h ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/CrisprNode.cpp",".cpp","11896","390","// File: CrisprNode.cpp // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Individual nodes for each kmer! // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // system includes #include #include #include #include // local includes #include ""CrisprNode.h"" #include ""LoggerSimp.h"" #include ""crassDefines.h"" #include ""GraphDrawingDefines.h"" #include ""Rainbow.h"" #include ""StringCheck.h"" #include ""libcrispr.h"" #include ""ReadHolder.h"" #include ""Exception.h"" // // Edge level functions // bool CrisprNode::addEdge(CrisprNode * parterNode, EDGE_TYPE type) { //----- // Add a new edge return success if the partner has been added // // get the right edge list edgeList * add_list = getEdges(type); // now see we haven't added it before if(add_list->find(parterNode) == add_list->end()) { // new guy (*add_list)[parterNode] = true; switch(type) { case CN_EDGE_FORWARD: mInnerRank_F++; break; case CN_EDGE_BACKWARD: mInnerRank_B++; break; case CN_EDGE_JUMPING_F: mJumpingRank_F++; break; case CN_EDGE_JUMPING_B: mJumpingRank_B++; break; default: throw crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Unknown edge type""); } return true; } return false; } edgeList * CrisprNode::getEdges(EDGE_TYPE type) { //----- // get edges of a particular type // switch(type) { case CN_EDGE_FORWARD: return &mForwardEdges; case CN_EDGE_BACKWARD: return &mBackwardEdges; case CN_EDGE_JUMPING_F: return &mJumpingForwardEdges; case CN_EDGE_JUMPING_B: return &mJumpingBackwardEdges; default: throw crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Unknown edge type""); } } void CrisprNode::calculateReadCoverage(edgeList * currentList, std::map& countingMap) { edgeListIterator eli; for (eli = currentList->begin(); eli != currentList->end(); eli++) { // check if he's attached if(! eli->second) { continue; } #ifdef DEBUG logInfo(""Edge: ""<<(eli->first)->getID(), 10); #endif // get the headers std::vector * inner_headers = (eli->first)->getReadHeaders(); std::vector::iterator inner_rh_iter = inner_headers->begin(); std::vector::iterator inner_rh_last = inner_headers->end(); while(inner_rh_iter != inner_rh_last) { if(countingMap.find(*inner_rh_iter) != countingMap.end()) { countingMap[*inner_rh_iter]++; #ifdef DEBUG logInfo(""\t\tIncrementing: ""<<*inner_rh_iter<<"" : ""< counting_map; // initialise the counting map to inlcude all the reads we care about std::vector::iterator rh_iter = mReadHeaders.begin(); for (rh_iter = mReadHeaders.begin(); rh_iter != mReadHeaders.end(); ++rh_iter) { counting_map[*rh_iter] = 0; #ifdef DEBUG logInfo(""Node :""< perhaps one of these lists is empty? if(mIsForward) { // first forward calculateReadCoverage(&mForwardEdges, counting_map); // then backward calculateReadCoverage(&mJumpingBackwardEdges, counting_map); } else { // first forward calculateReadCoverage(&mJumpingForwardEdges, counting_map); // then backward calculateReadCoverage(&mBackwardEdges, counting_map); } int ret_val = 0; std::map::iterator cm_iter = counting_map.begin(); std::map::iterator cm_last = counting_map.end(); while(cm_iter != cm_last) { if(cm_iter->second > 1) ret_val++; cm_iter++; } return ret_val; } // // Node level functions // void CrisprNode::setEdgeAttachState(edgeList * currentList, bool attachState, EDGE_TYPE currentType) { edgeListIterator eli; for (eli = currentList->begin(); eli != currentList->end(); eli++) { // go through each edge, check if it's not the right state if((eli->second ^ attachState) && (eli->first)->isAttached()) { // this edge is not the right state and the corresponding node is actually attached edgeList * other_eli = (eli->first)->getEdges(currentType); (*other_eli)[this] = attachState; eli->second = attachState; (eli->first)->updateRank(attachState, currentType); if((eli->first)->getTotalRank() == 0) (eli->first)->setAsDetached(); } } } void CrisprNode::setAttach(bool attachState) { //----- // detach or re-attach this node // // find and attached nodes and set the edges to attachState setEdgeAttachState(&mForwardEdges, attachState, CN_EDGE_FORWARD); setEdgeAttachState(&mBackwardEdges, attachState, CN_EDGE_BACKWARD); setEdgeAttachState(&mJumpingForwardEdges, attachState, CN_EDGE_JUMPING_F); setEdgeAttachState(&mJumpingBackwardEdges, attachState, CN_EDGE_JUMPING_B); // set our state mAttached = attachState; } int CrisprNode::getRank(EDGE_TYPE type) { //----- // return the rank of the node // switch(type) { case CN_EDGE_FORWARD: return mInnerRank_F; case CN_EDGE_BACKWARD: return mInnerRank_B; case CN_EDGE_JUMPING_F: return mJumpingRank_F; case CN_EDGE_JUMPING_B: return mJumpingRank_B; default: throw crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Unknown edge type""); } } void CrisprNode::updateRank(bool attachState, EDGE_TYPE type) { //----- // increment or decrement the rank of this type // int increment = -1; if(attachState) increment = 1; switch(type) { case CN_EDGE_FORWARD: mInnerRank_F += increment; break; case CN_EDGE_BACKWARD: mInnerRank_B += increment; break; case CN_EDGE_JUMPING_F: mJumpingRank_F += increment; break; case CN_EDGE_JUMPING_B: mJumpingRank_B += increment; break; default: throw crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Unknown edge type""); } } // // File IO / printing // void CrisprNode::printEdgesForList(edgeList * currentList, std::ostream &dataOut, StringCheck * ST, std::string label, bool showDetached, bool longDesc) { edgeListIterator eli; for (eli = currentList->begin(); eli != currentList->end(); eli++) { // check if the edge is active if((eli->second) || showDetached) { std::stringstream ss; if(longDesc) ss << (eli->first)->getID() << ""_"" << ST->getString((eli->first)->getID()); else ss << (eli->first)->getID(); gvEdge(dataOut,label,ss.str()); } } } void CrisprNode::printEdges(std::ostream &dataOut, StringCheck * ST, std::string label, bool showDetached, bool printBackEdges, bool longDesc) { //----- // print the edges so that the first member of the pair is first // // now print the edges printEdgesForList(&mForwardEdges, dataOut, ST, label, showDetached, longDesc); printEdgesForList(&mJumpingForwardEdges, dataOut, ST, label, showDetached, longDesc); if(printBackEdges) { printEdgesForList(&mBackwardEdges, dataOut, ST, label, showDetached, longDesc); printEdgesForList(&mJumpingBackwardEdges, dataOut, ST, label, showDetached, longDesc); } } std::vector CrisprNode::getReadHeaders(StringCheck * ST) { //----- // Given a StringCheck return the read headers for this node // std::vector ret_vector; if(ST != NULL) { std::vector::iterator rh_iter = mReadHeaders.begin(); while(rh_iter != mReadHeaders.end()) { ret_vector.push_back(ST->getString(*rh_iter)); rh_iter++; } } return ret_vector; } std::string CrisprNode::sayEdgeTypeLikeAHuman(EDGE_TYPE type) { //----- // get edges of a particular type // switch(type) { case CN_EDGE_FORWARD: return ""Forward""; case CN_EDGE_BACKWARD: return ""Backward""; case CN_EDGE_JUMPING_F: return ""JumpingForward""; case CN_EDGE_JUMPING_B: return ""JumpingBackward""; default: throw crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Unknown edge type""); } } ","C++" "CRISPR","ctSkennerton/crass","src/crass/SpacerInstance.h",".h","6093","180","// File: SpacerInstance.h // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Spacers! Lots of them! // Each found spacer *could* be different. Each unique instance should be saved // so that graph cleaning can be doned. // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // #ifndef SpacerInstance_h #define SpacerInstance_h // system includes #include #include // local includes #include ""crassDefines.h"" #include ""CrisprNode.h"" #include ""StringCheck.h"" class SpacerInstance; // we hash together string tokens to make a unique key for each spacer typedef unsigned int SpacerKey; enum SI_EdgeDirection { REVERSE = 0, FORWARD = 1 }; typedef struct{ SpacerInstance * edge; SI_EdgeDirection d; } spacerEdgeStruct; inline std::string saySpacerEdgeDirectionLikeAHuman(SI_EdgeDirection d) { if(d == REVERSE) { return ""REVERSE""; } return ""FORWARD""; } typedef std::vector SpacerInstanceVector; typedef std::vector::iterator SpacerInstanceVector_Iterator; typedef std::list SpacerInstanceList; typedef std::list::iterator SpacerInstanceList_Iterator; typedef std::pair SpacerInstancePair; typedef std::vector SpacerEdgeVector; typedef std::vector::iterator SpacerEdgeVector_Iterator; inline SpacerKey makeSpacerKey(StringToken backST, StringToken frontST) { //----- // make a spacer key from two string tokens // if(backST < frontST) { return (backST * 10000000) + frontST; } return (frontST * 10000000) + backST; } class SpacerInstance { public: SpacerInstance (void) { SI_SpacerSeqID = 0; SI_LeadingNode = NULL; SI_LastNode = NULL; SI_InstanceCount = 0; SI_ContigID = 0; SI_Attached = false; SI_isFlanker = false; } SpacerInstance (StringToken spacerID); SpacerInstance (StringToken spacerID, CrisprNode * leadingNode, CrisprNode * lastNode); ~SpacerInstance () {clearEdge();} // // get / set // inline void incrementCount(void) { SI_InstanceCount++; } inline unsigned int getCount(void) { return SI_InstanceCount; } inline StringToken getID(void) { return SI_SpacerSeqID; } inline CrisprNode * getLeader(void) { return SI_LeadingNode; } inline CrisprNode * getLast(void) { return SI_LastNode; } inline bool isAttached(void) { if ((SI_LeadingNode->isAttached() && SI_LastNode->isAttached() ^ SI_Attached)) { std::cout<<""Spacer ""<. // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // #ifndef LoggerSimp_h #define LoggerSimp_h #include #include #include ""crassDefines.h"" #include #include using namespace std; // for making the main logger #define intialiseGlobalLogger(lOGfILE, lOGlEVEL) logger->init(lOGfILE, lOGlEVEL) // for determining if logging is possible at a given level #define willLog(lOGlEVEL) (logger->getLogLevel() >= lOGlEVEL) class LoggerSimp { public: // Constructor/Destructor static LoggerSimp* Inst(void); // get the singleton logger ~LoggerSimp(); // kill it! [call this at the end of main()] // Get methods int getLogLevel(void); // get the log level std::string getLogFile(void); // the file we're logging to bool isFileOpen(void); // is the log file open? std::ofstream * getFhandle(void); // get the fileHandle std::streambuf * getBuff(void); // get the rbuff // Set Methods void init(std::string logFile, int logLevel); // don't call this directly, use the macro instead void setStartTime(void); // what time was the logger instantiated? void setLogLevel(int ll); // set the log level void setLogFile(std::string lf); // set the file name for the log file void setFileOpen(bool isOpen); // set if the file is open // Operations std::string int2Str(int input); // convert an into to a string std::string timeToString(bool elapsed); // write out the current time, prettylike void closeLogFile(void); // close the log file down void openLogFile(void); // open the log file void clearLogFile(void); // clear the logFile at the start std::iostream * mGlobalHandle; // what we realy write to protected: LoggerSimp(); private: static LoggerSimp * mInstance; // the internal instance for the singleton std::ofstream * mFileHandle; // for writing to files std::streambuf *mBuff; // for holding rbuffs std::ofstream * mTmpFH; // semi-tmp fh std::string mLogFile; // this is the file we'll be writing out to int mLogLevel; // which logging level are we at? time_t mStartTime; // the time when the logger was created time_t mCurrentTime; // now, .. no ... NOW! NOW! bool mFileOpen; // is the log file open? }; static LoggerSimp* logger = LoggerSimp::Inst(); // this makes the singleton available to all classes // which include LoggerSimp.h // get the log level #define isLogging(ll) (logger->getLogLevel() >= ll) // set the log level #define changeLogLevel(ll) (logger->setLogLevel(ll)) // for logging info #define logInfo(cOUTsTRING, ll) { \ if(logger->getLogLevel() >= ll) { \ (*(logger->mGlobalHandle)) << logger->timeToString(true) << ""\tI "" << cOUTsTRING << std::endl; \ } \ } // for dumping large amounts of info to the logfile after a msg #define logInfoNoPrefix(cOUTsTRING, ll) { \ if(logger->getLogLevel() >= ll) { \ (*(logger->mGlobalHandle)) << cOUTsTRING <mGlobalHandle)) << logger->timeToString(true) << ""\tERR "" << __FILE__ << "" : "" << __PRETTY_FUNCTION__ << "" : "" << __LINE__ << "": "" << cOUTsTRING << std::endl; \ throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__,s.str().c_str());\ } // for warnings #define logWarn(cOUTsTRING, ll) { \ if(logger->getLogLevel() >= ll) { \ (*(logger->mGlobalHandle)) << logger->timeToString(true) << ""\tW "" << cOUTsTRING << std::endl; \ } \ } // time stamp #define logTimeStamp() { \ (*(logger->mGlobalHandle)) << ""----------------------------------------------------------------------\n----------------------------------------------------------------------\n-- "" << logger->timeToString(false) << "" -- "" << PACKAGE_FULL_NAME<<"" (""<getLogLevel() >= ll) { \ (*(logger->mGlobalHandle)) << logger->timeToString(true) << ""\tI "" << __FILE__ << "" : "" << __PRETTY_FUNCTION__ << "" : "" << __LINE__ << "": "" << cOUTsTRING << std::endl; \ } \ } // for errors #define logError(cOUTsTRING) { \ (*(logger->mGlobalHandle)) << logger->timeToString(true) << ""\tERR "" << __FILE__ << "" : "" << __PRETTY_FUNCTION__ << "" : "" << __LINE__ << "": "" << cOUTsTRING << std::endl; \ } // for warnings #define logWarn(cOUTsTRING, ll) { \ if(logger->getLogLevel() >= ll) { \ (*(logger->mGlobalHandle)) << logger->timeToString(true) << ""\tW "" << __FILE__ << "" : "" << __PRETTY_FUNCTION__ << "" : "" << __LINE__ << "": "" << cOUTsTRING << std::endl; \ } \ } #endif // __SUPER_LOGGING #endif //LoggerSimp_h ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/PatternMatcher.cpp",".cpp","5634","206","/* * PatternMatcher.cpp is part of the CRisprASSembler project * Levensthein code was downloaded from http://www.merriampark.com/ldcpp.htm * Copyright (c) Merriam Park Software 2009 * * Boyer-Moore code was downloaded from http://dev-faqs.blogspot.com/2010/05/boyer-moore-algorithm.html * Copyright (c) 2010 dev-faqs.blogspot.com * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include ""PatternMatcher.h"" #include int PatternMatcher::bmpSearch(const std::string &text, const std::string &pattern){ size_t textSize = text.size(); size_t patternSize = pattern.size(); if(textSize == 0 || patternSize == 0){ return -1; } if(patternSize > textSize){ return -1; } std::vector bmpLast = computeBmpLast(pattern); size_t tIdx = patternSize - 1; size_t pIdx = patternSize - 1; while(tIdx < textSize) { if(pattern[pIdx] == text[tIdx]) { if(pIdx == 0) { //found a match return (int)tIdx; } tIdx--; pIdx--; } else { //Character Jump Heuristics int lastOccur = bmpLast[text[tIdx]]; tIdx = tIdx + patternSize - std::min((int)pIdx, 1 + lastOccur); pIdx = patternSize - 1; } } return - 1; } // slight variation of the code above so that when a match is found it is pushed to // a vector of starting positions void PatternMatcher::bmpMultiSearch(const std::string &text, const std::string &pattern, std::vector &startOffsetVec ) { size_t textSize = text.size(); size_t patternSize = pattern.size(); if(textSize == 0 || patternSize == 0){ return; } if(patternSize > textSize){ return; } std::vector bmpLast = computeBmpLast(pattern); size_t tIdx = patternSize - 1; size_t pIdx = patternSize - 1; while(tIdx < textSize) { if(pattern[pIdx] == text[tIdx]) { if(pIdx == 0) { //found a match startOffsetVec.push_back((int)tIdx) ; } tIdx--; pIdx--; } else { //Character Jump Heuristics int lastOccur = bmpLast[text[tIdx]]; tIdx = tIdx + patternSize - std::min((int)pIdx, 1 + lastOccur); pIdx = patternSize - 1; } } } std::vector PatternMatcher::computeBmpLast(const std::string &pattern){ const size_t NUM_ASCII_CHARS = 128; std::vector bmpLast(NUM_ASCII_CHARS); for(size_t i = 0; i < NUM_ASCII_CHARS; i++){ bmpLast[i] = -1; } for(size_t i = 0; i < pattern.size(); i++){ bmpLast[pattern[i]] = (int)i; } return bmpLast; } int PatternMatcher::levenstheinDistance( std::string& source, std::string& target) { // Step 1 int n = (int)source.length(); int m = (int)target.length(); if (n == 0) { return m; } if (m == 0) { return n; } // Good form to declare a TYPEDEF Tmatrix matrix(n+1); // Size the vectors in the 2.nd dimension. Unfortunately C++ doesn't // allow for allocation on declaration of 2.nd dimension of vec of vec for (int i = 0; i <= n; i++) { matrix[i].resize(m+1); } // Step 2 for (int i = 0; i <= n; i++) { matrix[i][0]=i; } for (int j = 0; j <= m; j++) { matrix[0][j]=j; } // Step 3 for (int i = 1; i <= n; i++) { char s_i = source[i-1]; // Step 4 for (int j = 1; j <= m; j++) { char t_j = target[j-1]; // Step 5 int cost; if (s_i == t_j) { cost = 0; } else { cost = 1; } // Step 6 int above = matrix[i-1][j]; int left = matrix[i][j-1]; int diag = matrix[i-1][j-1]; int cell = std::min( above + 1, std::min(left + 1, diag + cost)); // Step 6A: Cover transposition, in addition to deletion, // insertion and substitution. This step is taken from: // Berghel, Hal ; Roach, David : ""An Extension of Ukkonen's // Enhanced Dynamic Programming ASM Algorithm"" // (http://www.acm.org/~hlb/publications/asm/asm.html) if (i>2 && j>2) { int trans=matrix[i-2][j-2]+1; if (source[i-2]!=t_j) trans++; if (s_i!=target[j-2]) trans++; if (cell>trans) cell=trans; } matrix[i][j]=cell; } } // Step 7 return matrix[n][m]; } float PatternMatcher::getStringSimilarity(std::string& s1, std::string& s2) { float max_length = std::max(s1.length(), s2.length()); if(/*max_length > 10 ||*/ s1.length() < 3 || s2.length() < 3) return 0; float edit_distance = levenstheinDistance(s1 , s2); return 1.0 - (edit_distance/max_length); } ","C++" "CRISPR","ctSkennerton/crass","src/crass/Rainbow.h",".h","4048","123","// File: Rainbow.h // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Simple heat map generator. Returns hex-RGB colours based on limits set by user // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // #ifndef Rainbow_h #define Rainbow_h // system includes #include #include // local includes // defaults #define RB_ERROR_COLOUR ""000000"" // error colour. return this whenever you want to panic #define RB_DEFAULT_TYPE BLUE_RED // default type of heatmap #define RB_LB 0 // default upper bound #define RB_UB 1 // default lowe bound #define RB_TICKS 10 // default ticks // some math constants we need (I know!) #define PI (3.1415927) // we can have anumber of different types of heatmaps enum RB_TYPE { RED_BLUE, BLUE_RED, RED_BLUE_GREEN, GREEN_BLUE_RED }; class Rainbow { public: Rainbow() { setDefaults(); } ~Rainbow() {} void setDefaults(void); // set the limits we need! void setLimits(double lb, double ub, int res); void setLimits(double lb, double ub) { setLimits(lb, ub, (int)(ub-lb)+1); } void setType(RB_TYPE type); void setUpperBound(double ub){setLimits(mLowerBound, ub, (int)(ub - mLowerBound)+1); } void setLowerBound(double lb){setLimits(lb, mUpperBound, (int)(mUpperBound - lb)+1); } // get a colour! std::string getColour(double value); std::string int2RGB(int rgb); // get the limits double getUpperLimit(void) { return mUpperBound; } double getLowerLimit(void) { return mLowerBound; } private: // members double mLowerBound; // lowest number we'll colour` double mUpperBound; // highest int mResolution; // number of steps between low and high (inclusive) RB_TYPE mType; // type of the heatmap // We need offsets for the start of each cos graph double mRedOffset; double mGreenOffset; double mBlueOffset; // should we ignore any colour bool mIgnoreRed; bool mIgnoreGreen; bool mIgnoreBlue; // horizontal scaling double mLowerScale; double mUpperScale; // shortcut // // Given value X between mLowerBound and mUpperBound we need to find a value // Z between mLowerScale and mUpperScale. This involves a constant multiplicaation // by (mUpperScale - mLowerScale)/(mUpperBound - mLowerBound). So we work this out once. // double mScaleMultiplier; double mTickSize; // size of a tick }; #endif //Rainbow_h ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/SplitTool.cpp",".cpp","789","24","// SplitTool.cpp // // Copyright (C) 2011 - Connor Skennerton // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 2 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #include ""SplitTool.h"" int splitMain (int argc, char ** argv) { return 0; } ","C++" "CRISPR","ctSkennerton/crass","src/crass/CrisprNode.h",".h","8351","202","// File: CrisprNode.h // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Header file for the NodeManager // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // #ifndef CrisprNode_h #define CrisprNode_h // system includes #include #include #include // local includes #include ""crassDefines.h"" #include ""StringCheck.h"" #include ""Rainbow.h"" #include ""libcrispr.h"" #include ""ReadHolder.h"" class CrisprNode; // Enum to let us know if the node is a ""first"" node in a spacer pair enum EDGE_TYPE { CN_EDGE_BACKWARD, CN_EDGE_FORWARD, CN_EDGE_JUMPING_F, CN_EDGE_JUMPING_B, CN_EDGE_ERROR }; // a list of edges ( we use a map to make lookups faster ) // The bool teels us if the edge is active (ie, if the joining node is still attached / in use) typedef std::map edgeList; typedef std::map::iterator edgeListIterator; class CrisprNode { public: //constructor CrisprNode(void) { mid = 0; mAttached = true; mInnerRank_F = 0; mInnerRank_B = 0; mJumpingRank_F = 0; mJumpingRank_B = 0; mCoverage = 0; mIsForward = true; } CrisprNode(StringToken id) { mid = id; mAttached = true; // by default, a node is attached unless actually detached by the user mInnerRank_F = 0; mInnerRank_B = 0; mJumpingRank_F = 0; mJumpingRank_B = 0; mCoverage = 1; mIsForward = true; } //destructor ~CrisprNode(){} // // Generic get and set // inline StringToken getID(void) { return mid; } inline bool isForward(void) { return mIsForward; } inline void setForward(bool forward) { mIsForward = forward; } inline int getCoverage() {return mCoverage;} int getDiscountedCoverage(void); inline void addReadHeader(StringToken readHeader) { mReadHeaders.push_back(readHeader); } inline void addReadHolder(ReadHolder * RH) { mReadHolders.push_back(RH); } inline std::vector * getReadHeaders(void) { return &mReadHeaders; } inline ReadList * getReadHolders(void) { return &mReadHolders; } // // Edge level functions // bool addEdge(CrisprNode * parterNode, EDGE_TYPE type); // return success if the partner has been added edgeList * getEdges(EDGE_TYPE type); // get edges of a particular type // // Node level functions // inline void detachNode(void) { setAttach(false); } // detach this node inline void reattachNode(void) { setAttach(true); } // re-attach this node inline bool isAttached(void) { return mAttached; } // der... void setAsDetached(void) { mAttached = false; } // DO NOT CALL THIS OUTSIDE OF THE ATTACH FUNCTION! int getRank(EDGE_TYPE type); // return the rank of the node void updateRank(bool attachState, EDGE_TYPE type); // increment or decrement the rank of this type inline void incrementCount(void) { mCoverage++; } // Increment the coverage int getTotalRank(void) { return getRank(CN_EDGE_BACKWARD) + getRank(CN_EDGE_FORWARD) + getRank(CN_EDGE_JUMPING_F) + getRank(CN_EDGE_JUMPING_B); } int getJumpingRank(void) { return getRank(CN_EDGE_JUMPING_F) + getRank(CN_EDGE_JUMPING_B); } int getInnerRank(void) { return getRank(CN_EDGE_BACKWARD) + getRank(CN_EDGE_FORWARD); } // // File IO / printing // void printEdges(std::ostream &dataOut, StringCheck * ST, std::string label, bool showDetached, bool printBackEdges, bool longDesc); std::vector getReadHeaders(StringCheck * ST); std::string sayEdgeTypeLikeAHuman(EDGE_TYPE type); std::vector::iterator beginHeaders(void) {return mReadHeaders.begin();} std::vector::iterator endHeaders(void) {return mReadHeaders.end();} private: void setAttach(bool attachState); // set the attach state of the node void setEdgeAttachState(edgeList * currentList, bool attachState, EDGE_TYPE currentType); void calculateReadCoverage(edgeList * currentList, std::map& countingMap); void printEdgesForList(edgeList * currentList, std::ostream &dataOut, StringCheck * ST, std::string label, bool showDetached, bool longDesc); // id of the kmer of the cripsr node StringToken mid; // // We need different edge lists to store the variety of edges we may encounter, observe... // // NODE 1 NODE 2 NODE 3 NODE 4 NODE 5 NODE 6 // ... DRDRDRDRDR | SP_start ---- SP_end | DRDRDRDRDR | SP_start ---- SP_end | DRDRDRDRDR | SP_start ---- SP_end | DRDRDRDRDR ... // // Gives edge types: (B = CN_EDGE_BACKWARD, F = CN_EDGE_FORWARD, JF = JUMPING CN_EDGE_FORWARD, JB = JUMPING CN_EDGE_BACKWARD, X = no egde) // // --------------------------------------------------------------- // | NODE 1 | NODE 2 | NODE 3 | NODE 4 | NODE 5 | NODE 6 | // --------------------------------------------------------------- // NODE 1 | X | F | X | X | X | X | // NODE 2 | B | X | JF | X | X | X | // NODE 3 | X | JB | X | F | X | X | // NODE 4 | X | X | B | X | JF | X | // NODE 5 | X | X | X | JB | X | F | // NODE 6 | X | X | X | X | B | X | // --------------------------------------------------------------- // edgeList mForwardEdges; edgeList mBackwardEdges; edgeList mJumpingForwardEdges; edgeList mJumpingBackwardEdges; // We need multiple classes of RANK int mInnerRank_F; int mInnerRank_B; int mJumpingRank_F; int mJumpingRank_B; // We need to mark whether nodes are atached or detached bool mAttached; // how many times have we seen this guy? int mCoverage; // is this a forward facing node? bool mIsForward; // we need to know which reads produced these nodes std::vector mReadHeaders; // headers of all reads which contain these spacers ReadList mReadHolders; // waste of the last var, shut up. }; #endif //CrisprNode_h ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/parser.h",".h","1586","50","/* * crass.h is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef PARSER_H #define PARSER_H #include ""reader.h"" #include ""writer.h"" namespace crispr { namespace xml { class parser : public reader, public writer { public: // constructor parser(); ~parser(); }; } } #endif","Unknown" "CRISPR","ctSkennerton/crass","src/crass/SearchChecker.cpp",".cpp","2084","65","/* * SearchChecker.cpp is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011, 2012 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include #include #include ""SearchChecker.h"" #include ""Exception.h"" SearchChecker * SearchChecker::SC_instance = NULL; SearchChecker * SearchChecker::instance() { if (!SC_instance) SC_instance = new SearchChecker; return SC_instance; } void SearchChecker::processHeaderFile() { std::fstream in; in.open(SC_FileName.c_str()); if (in.good()) { std::string line; while (in >> line) { SearchData s; SC_Data[line] = s; } } else { throw crispr::runtime_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""could not open header file""); } }","C++" "CRISPR","ctSkennerton/crass","src/crass/base.cpp",".cpp","8257","191","/* * crass.h is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include ""base.h"" using namespace crispr::xml; base::base() { try { // Initialize Xerces infrastructure init(); // transcode all the member variables alloc(); } catch( xercesc::XMLException& e ) { char * message = xercesc::XMLString::transcode( e.getMessage() ); std::cerr << ""XML toolkit initialization error: "" << message << std::endl; xercesc::XMLString::release( &message ); // throw exception here to return ERROR_XERCES_INIT } } base::~base(void) { // Free memory dealloc(); // Terminate Xerces release(); } void base::init(void) { xercesc::XMLPlatformUtils::Initialize(); } void base::alloc(void) { // USE sed // grep ELEMENT crass.dtd | sed -e ""s%[^ ]* \([^ ]*\) .*%TAG_\1 = XMLString::transcode(\""\1\"");%"" | sort | uniq // grep ATTLIST crass.dtd | sed -e ""s%[^ ]* [^ ]* \([^ ]*\) .*%ATTR_\1 = XMLString::transcode(\""\1\"");%"" | sort | uniq TAG_assembly = xercesc::XMLString::transcode(""assembly""); TAG_bf = xercesc::XMLString::transcode(""bf""); TAG_bflankers = xercesc::XMLString::transcode(""bflankers""); TAG_bs = xercesc::XMLString::transcode(""bs""); TAG_bspacers = xercesc::XMLString::transcode(""bspacers""); TAG_command = xercesc::XMLString::transcode(""command""); TAG_consensus = xercesc::XMLString::transcode(""consensus""); TAG_contig = xercesc::XMLString::transcode(""contig""); TAG_crispr = xercesc::XMLString::transcode(""crispr""); TAG_cspacer = xercesc::XMLString::transcode(""cspacer""); TAG_data = xercesc::XMLString::transcode(""data""); TAG_dr = xercesc::XMLString::transcode(""dr""); TAG_drs = xercesc::XMLString::transcode(""drs""); TAG_epos = xercesc::XMLString::transcode(""epos""); TAG_ff = xercesc::XMLString::transcode(""ff""); TAG_fflankers = xercesc::XMLString::transcode(""fflankers""); TAG_file = xercesc::XMLString::transcode(""file""); TAG_flanker = xercesc::XMLString::transcode(""flanker""); TAG_flankers = xercesc::XMLString::transcode(""flankers""); TAG_fs = xercesc::XMLString::transcode(""fs""); TAG_fspacers = xercesc::XMLString::transcode(""fspacers""); TAG_group = xercesc::XMLString::transcode(""group""); TAG_metadata = xercesc::XMLString::transcode(""metadata""); TAG_name = xercesc::XMLString::transcode(""name""); TAG_notes = xercesc::XMLString::transcode(""notes""); TAG_program = xercesc::XMLString::transcode(""program""); TAG_source = xercesc::XMLString::transcode(""source""); TAG_sources = xercesc::XMLString::transcode(""sources""); TAG_spacer = xercesc::XMLString::transcode(""spacer""); TAG_spacers = xercesc::XMLString::transcode(""spacers""); TAG_spos = xercesc::XMLString::transcode(""spos""); TAG_version = xercesc::XMLString::transcode(""version""); ATTR_accession = xercesc::XMLString::transcode(""accession""); ATTR_cid = xercesc::XMLString::transcode(""cid""); ATTR_confcnt = xercesc::XMLString::transcode(""confcnt""); ATTR_cov = xercesc::XMLString::transcode(""cov""); ATTR_directjoin = xercesc::XMLString::transcode(""directjoin""); ATTR_drconf = xercesc::XMLString::transcode(""drconf""); ATTR_drid = xercesc::XMLString::transcode(""drid""); ATTR_drseq = xercesc::XMLString::transcode(""drseq""); ATTR_flid = xercesc::XMLString::transcode(""flid""); ATTR_gid = xercesc::XMLString::transcode(""gid""); ATTR_seq = xercesc::XMLString::transcode(""seq""); ATTR_soid = xercesc::XMLString::transcode(""soid""); ATTR_spid = xercesc::XMLString::transcode(""spid""); ATTR_totcnt = xercesc::XMLString::transcode(""totcnt""); ATTR_type = xercesc::XMLString::transcode(""type""); ATTR_url = xercesc::XMLString::transcode(""url""); ATTR_version = xercesc::XMLString::transcode(""version""); } void base::dealloc(void) { // grep ELEMENT crass.dtd | sed -e ""s%[^ ]* \([^ ]*\) .*%XMLString::release( \&TAG_\1 );%"" | sort | uniq // grep ATTLIST crass.dtd | sed -e ""s%[^ ]* [^ ]* \([^ ]*\) .*%XMLString::release( \&ATTR_\1 );%"" | sort | uniq try { xercesc::XMLString::release( &TAG_assembly ); xercesc::XMLString::release( &TAG_bf ); xercesc::XMLString::release( &TAG_bflankers ); xercesc::XMLString::release( &TAG_bs ); xercesc::XMLString::release( &TAG_bspacers ); xercesc::XMLString::release( &TAG_command ); xercesc::XMLString::release( &TAG_consensus ); xercesc::XMLString::release( &TAG_contig ); xercesc::XMLString::release( &TAG_crispr ); xercesc::XMLString::release( &TAG_cspacer ); xercesc::XMLString::release( &TAG_data ); xercesc::XMLString::release( &TAG_dr ); xercesc::XMLString::release( &TAG_drs ); xercesc::XMLString::release( &TAG_epos ); xercesc::XMLString::release( &TAG_ff ); xercesc::XMLString::release( &TAG_fflankers ); xercesc::XMLString::release( &TAG_file ); xercesc::XMLString::release( &TAG_flanker ); xercesc::XMLString::release( &TAG_flankers ); xercesc::XMLString::release( &TAG_fs ); xercesc::XMLString::release( &TAG_fspacers ); xercesc::XMLString::release( &TAG_group ); xercesc::XMLString::release( &TAG_metadata ); xercesc::XMLString::release( &TAG_name ); xercesc::XMLString::release( &TAG_notes ); xercesc::XMLString::release( &TAG_program ); xercesc::XMLString::release( &TAG_source ); xercesc::XMLString::release( &TAG_sources ); xercesc::XMLString::release( &TAG_spacer ); xercesc::XMLString::release( &TAG_spacers ); xercesc::XMLString::release( &TAG_spos ); xercesc::XMLString::release( &TAG_version ); xercesc::XMLString::release( &ATTR_accession ); xercesc::XMLString::release( &ATTR_cid ); xercesc::XMLString::release( &ATTR_confcnt ); xercesc::XMLString::release( &ATTR_cov ); xercesc::XMLString::release( &ATTR_directjoin ); xercesc::XMLString::release( &ATTR_drconf ); xercesc::XMLString::release( &ATTR_drid ); xercesc::XMLString::release( &ATTR_drseq ); xercesc::XMLString::release( &ATTR_flid ); xercesc::XMLString::release( &ATTR_gid ); xercesc::XMLString::release( &ATTR_seq ); xercesc::XMLString::release( &ATTR_soid ); xercesc::XMLString::release( &ATTR_spid ); xercesc::XMLString::release( &ATTR_totcnt ); xercesc::XMLString::release( &ATTR_type ); xercesc::XMLString::release( &ATTR_url ); xercesc::XMLString::release( &ATTR_version ); } catch(...) { throw crispr::xml_exception (__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Unknown error occurred""); } } void base::release (void) { xercesc::XMLPlatformUtils::Terminate(); // Terminate after release of memory } ","C++" "CRISPR","ctSkennerton/crass","src/crass/SanitiseTool.cpp",".cpp","15165","407","// SanitiseTool.cpp // // Copyright (C) 2011 - Connor Skennerton // // This program is free software; you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation; either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . #include #include ""SanitiseTool.h"" #include ""Exception.h"" #include ""parser.h"" #include ""config.h"" #include int SanitiseTool::processOptions (int argc, char ** argv) { int c; int index; static struct option long_options [] = { {""help"", no_argument, NULL, 'h'}, {""all"", no_argument, NULL, 'a'}, //{""groups"",required_argument, NULL, 'g'}, {""spacer"",no_argument,NULL,'s'}, {""direct-repeat"", no_argument, NULL, 'd'}, {""flanker"", no_argument, NULL, 'f'}, {""contig"", no_argument, NULL, 'c'}, {""outfile"",required_argument,NULL, 'o'}, //{""outfile-dir"",required_argument,NULL,'O'}, {0,0,0,0} }; while((c = getopt_long(argc, argv, ""ahscfdo:"", long_options, &index)) != -1) { switch(c) { case 'a': { ST_contigs = ST_Repeats = ST_Flank = ST_Spacers = true; break; } case 'h': { sanitiseUsage(); exit(0); break; } case 's': { ST_Spacers = true; break; } case 'o': { ST_OutputFile = optarg; break; } case 'f': { ST_Flank = true; break; } case 'd': { ST_Repeats = true; break; } case 'c': { ST_contigs = true; break; } default: { sanitiseUsage(); exit(1); break; } } } if (!(ST_contigs | ST_Spacers | ST_Repeats | ST_Flank)) { throw crispr::input_exception(""Please specify one of -s -f -d -c""); } return optind; } int SanitiseTool::processInputFile(const char * inputFile) { try { crispr::xml::parser xml_parser; xercesc::DOMDocument * input_doc_obj = xml_parser.setFileParser(inputFile); xercesc::DOMElement * root_elem = input_doc_obj->getDocumentElement(); if (!root_elem) { throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""problem when parsing xml file""); } if (ST_OutputFile.empty()) { ST_OutputFile = inputFile; } for (xercesc::DOMElement * currentElement = root_elem->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { // is this a group element if (xercesc::XMLString::equals(currentElement->getTagName(), xml_parser.tag_Group())) { XMLCh * x_next_group_num = tc( getNextGroupS().c_str()); currentElement->setAttribute(xml_parser.attr_Gid(), x_next_group_num); incrementGroup(); xr(&x_next_group_num); // the user wants to change any of these if (ST_Spacers || ST_Repeats || ST_Flank || ST_contigs) { parseGroup(currentElement, xml_parser); } } setNextRepeat(1); setNextContig(1); setNextRepeat(1); setNextSpacer(1); } xml_parser.printDOMToFile(ST_OutputFile, input_doc_obj); } catch (crispr::xml_exception& e) { std::cerr<getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Data())) { if (ST_Spacers || ST_Repeats || ST_Flank) { parseData(currentElement, xmlParser); } } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Assembly())) { if (ST_contigs || ST_Spacers || ST_Repeats || ST_Flank) { parseAssembly(currentElement, xmlParser); } } } } void SanitiseTool::parseData(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Drs())) { if (ST_Repeats) { // change the direct repeats parseDrs(currentElement, xmlParser); } } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Spacers())) { if (ST_Spacers) { // change the spacers parseSpacers(currentElement, xmlParser); } } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Flankers())) { if (ST_Flank) { // change the flankers parseFlankers(currentElement, xmlParser); } } } } void SanitiseTool::parseDrs(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Dr())) { char * c_drid = tc(currentElement->getAttribute(xmlParser.attr_Drid())); std::string drid = c_drid; ST_RepeatMap[drid] = getNextRepeatS(); xr(&c_drid); XMLCh * x_next_repeat_num = tc(getNextRepeatS().c_str()); currentElement->setAttribute(xmlParser.attr_Drid(), x_next_repeat_num); xr(&x_next_repeat_num); incrementRepeat(); } } } void SanitiseTool::parseSpacers(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Spacer())) { char * c_spid = tc(currentElement->getAttribute(xmlParser.attr_Spid())); std::string spid = c_spid; ST_SpacerMap[spid] = getNextSpacerS(); xr(&c_spid); XMLCh * x_next_spacer_num = tc(getNextSpacerS().c_str()); currentElement->setAttribute(xmlParser.attr_Spid(), x_next_spacer_num); xr(&x_next_spacer_num); incrementSpacer(); } } } void SanitiseTool::parseFlankers(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Flanker())) { char * c_flid = tc(currentElement->getAttribute(xmlParser.attr_Flid())); std::string flid = c_flid; ST_FlankMap[flid] = getNextFlankerS(); xr(&c_flid); XMLCh * x_next_flanker_num = tc(getNextFlankerS().c_str()); currentElement->setAttribute(xmlParser.attr_Flid(), x_next_flanker_num); xr(&x_next_flanker_num); incrementFlanker(); } } } void SanitiseTool::parseAssembly(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Contig())) { XMLCh * x_next_contig = tc(getNextContigS().c_str()); currentElement->setAttribute(xmlParser.attr_Cid(), x_next_contig); incrementContig(); xr(&x_next_contig); parseContig(currentElement, xmlParser); } } } void SanitiseTool::parseContig(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Cspacer())) { if (ST_Spacers) { char * c_spid = tc( currentElement->getAttribute(xmlParser.attr_Spid())); std::string spid = c_spid; XMLCh * x_new_spid = tc(ST_SpacerMap[spid].c_str()); currentElement->setAttribute(xmlParser.attr_Spid(), x_new_spid); xr(&c_spid); xr(&x_new_spid); } if (ST_Spacers || ST_Repeats || ST_Flank) { parseCSpacer(currentElement, xmlParser); } } } } void SanitiseTool::parseCSpacer(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Bspacers())) { if (ST_Spacers || ST_Repeats) { parseLinkSpacers(currentElement, xmlParser); } } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Fspacers())) { if (ST_Spacers || ST_Repeats) { parseLinkSpacers(currentElement, xmlParser); } } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Bflankers())) { if (ST_Flank || ST_Repeats) { parseLinkFlankers(currentElement, xmlParser); } } else if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Fflankers())) { if (ST_Flank || ST_Repeats) { parseLinkFlankers(currentElement, xmlParser); } } } } void SanitiseTool::parseLinkSpacers(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (ST_Spacers) { char * c_spid = tc(currentElement->getAttribute(xmlParser.attr_Spid())); std::string spid = c_spid; XMLCh * x_new_spid = tc( ST_SpacerMap[spid].c_str()); currentElement->setAttribute(xmlParser.attr_Spid(), x_new_spid); xr(&c_spid); xr(&x_new_spid); } if (ST_Repeats) { char * c_drid = tc( currentElement->getAttribute(xmlParser.attr_Drid())); std::string drid = c_drid; XMLCh * x_new_drid = tc(ST_RepeatMap[drid].c_str()); currentElement->setAttribute(xmlParser.attr_Drid(), x_new_drid); xr(&c_drid); xr(&x_new_drid); } } } void SanitiseTool::parseLinkFlankers(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (ST_Flank) { char * c_flid = tc( currentElement->getAttribute(xmlParser.attr_Flid())); std::string flid = c_flid; XMLCh * x_new_flid = tc( ST_FlankMap[flid].c_str()); currentElement->setAttribute(xmlParser.attr_Flid(), x_new_flid); xr(&c_flid); xr(&x_new_flid); } if (ST_Repeats) { char * c_drid = tc( currentElement->getAttribute(xmlParser.attr_Drid())); std::string drid = c_drid; XMLCh * x_new_drid = tc(ST_RepeatMap[drid].c_str()); currentElement->setAttribute(xmlParser.attr_Drid(), x_new_drid); xr(&c_drid); xr(&x_new_drid); } } } int sanitiseMain (int argc, char ** argv) { try { SanitiseTool st; int opt_index = st.processOptions (argc, argv); if (opt_index >= argc) { throw crispr::input_exception(""No input file provided"" ); } else { // get cracking and process that file return st.processInputFile(argv[opt_index]); } } catch(crispr::input_exception& re) { std::cerr<. * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef crass_SearchChecker_h #define crass_SearchChecker_h #include #include #include #include #include ""ReadHolder.h"" #include ""StringCheck.h"" //#include ""libcrispr.h"" //#include ""NodeManager.h"" typedef std::vector SearchDataNodes; class SearchData { ReadHolder * SD_holder; StringToken SD_drtoken; StringToken SD_nmHeaderToken; //NodeManager * SD_nodeManager; SearchDataNodes SD_nodes; std::string SD_truedr; int SD_groupNumber; std::vector SD_spacerStringList; public: SearchData() { SD_holder = NULL; //SD_nodeManager = NULL; SD_drtoken = 0; SD_nmHeaderToken = 0; SD_groupNumber = 0; } ~SearchData(){ if (SD_holder != NULL) { delete SD_holder; } } inline StringToken token(){ return SD_drtoken;} inline void token(StringToken i) {SD_drtoken = i;} inline StringToken nmtoken() {return SD_nmHeaderToken;} inline void nmtoken(StringToken s) {SD_nmHeaderToken = s;} inline ReadHolder * read() {return SD_holder;} inline void read(ReadHolder * r) {SD_holder = r;} inline std::string truedr() {return SD_truedr;} inline void truedr(std::string s) {SD_truedr = s;} inline void addSpacer(std::string s) {SD_spacerStringList.push_back(s);} inline std::vector::iterator beginSp() {return SD_spacerStringList.begin();} inline std::vector::iterator endSp() {return SD_spacerStringList.end();} inline int gid() {return SD_groupNumber;} inline void gid(int i) {SD_groupNumber = i;} inline void addNode(StringToken t) {SD_nodes.push_back(t);} inline SearchDataNodes::iterator begin() {return SD_nodes.begin();} inline SearchDataNodes::iterator end() {return SD_nodes.end();} }; typedef std::map SearchCheckerList; class SearchChecker { static SearchChecker *SC_instance; SearchChecker(){}; std::string SC_FileName; //a file containing a list of headers for interesting reads SearchCheckerList SC_Data; // data about individual reads public: // get/set inline bool hasHeader(std::string s) {return (find(s) != end());} inline void headerFile(std::string s ) {SC_FileName = s;} inline void add(std::string a, SearchData& s) {SC_Data[a] = s;} inline SearchCheckerList::iterator find(std::string s) {return SC_Data.find(s);} inline SearchCheckerList::iterator begin() {return SC_Data.begin();} inline SearchCheckerList::iterator end() {return SC_Data.end();} void processHeaderFile(void); static SearchChecker * instance(); }; static SearchChecker * debugger = SearchChecker::instance(); #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/writer.cpp",".cpp","28322","766","/* * crass.h is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include ""writer.h"" crispr::xml::writer::writer() { XW_DocElem = NULL; } crispr::xml::writer::~writer() { delete XW_DocElem; } xercesc::DOMElement * crispr::xml::writer::createDOMDocument(std::string rootElement, std::string versionNumber, int& errorNumber ) { XMLCh * core = tc(""Core""); xercesc::DOMImplementation* impl = xercesc::DOMImplementationRegistry::getDOMImplementation(core); xr(&core); if (impl != NULL) { try { XMLCh * x_root_elem = tc(rootElement.c_str()); XW_DocElem = impl->createDocument( 0, x_root_elem, 0); xr(&x_root_elem); if (XW_DocElem != NULL) { xercesc::DOMElement* rootElem = XW_DocElem->getDocumentElement(); XMLCh * x_version_num = tc(versionNumber.c_str()); rootElem->setAttribute(attr_Version(), x_version_num); xr(&x_version_num); errorNumber = 0; return rootElem; } } catch (const xercesc::OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << ""OutOfMemoryException"" << XERCES_STD_QUALIFIER endl; errorNumber = 5; } catch (const xercesc::DOMException& e) { XERCES_STD_QUALIFIER cerr << ""DOMException code is: "" << e.code << XERCES_STD_QUALIFIER endl; errorNumber = 2; } catch (...) { XERCES_STD_QUALIFIER cerr << ""An error occurred creating the document"" << XERCES_STD_QUALIFIER endl; errorNumber = 3; } } // (inpl != NULL) else { XERCES_STD_QUALIFIER cerr << ""Requested implementation is not supported"" << XERCES_STD_QUALIFIER endl; errorNumber = 4; } return NULL; } xercesc::DOMElement * crispr::xml::writer::createDOMDocument(const char * rootElement, const char * versionNumber, int& errorNumber ) { XMLCh * core = tc(""Core""); xercesc::DOMImplementation* impl = xercesc::DOMImplementationRegistry::getDOMImplementation(core); xr(&core); if (impl != NULL) { try { XMLCh * x_root_elem = tc(rootElement); XW_DocElem = impl->createDocument(0, x_root_elem, 0); xr(&x_root_elem); if (XW_DocElem != NULL) { xercesc::DOMElement* rootElem = XW_DocElem->getDocumentElement(); XMLCh * x_version_num = tc(versionNumber); rootElem->setAttribute(attr_Version(), x_version_num ); xr(&x_version_num); errorNumber = 0; return rootElem; } } catch (const xercesc::OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << ""OutOfMemoryException"" << XERCES_STD_QUALIFIER endl; errorNumber = 5; } catch (const xercesc::DOMException& e) { XERCES_STD_QUALIFIER cerr << ""DOMException code is: "" << e.code << XERCES_STD_QUALIFIER endl; errorNumber = 2; } catch (...) { XERCES_STD_QUALIFIER cerr << ""An error occurred creating the document"" << XERCES_STD_QUALIFIER endl; errorNumber = 3; } } // (inpl != NULL) else { XERCES_STD_QUALIFIER cerr << ""Requested implementation is not supported"" << XERCES_STD_QUALIFIER endl; errorNumber = 4; } return NULL; } xercesc::DOMElement * crispr::xml::writer::addMetaData(xercesc::DOMElement * parentNode) { xercesc::DOMElement * meta_data_elem = XW_DocElem->createElement(tag_Metadata()); parentNode->appendChild(meta_data_elem); return meta_data_elem; } xercesc::DOMElement * crispr::xml::writer::addMetaData(std::string notes, xercesc::DOMElement * parentNode) { xercesc::DOMElement * meta_data_elem = XW_DocElem->createElement(tag_Metadata()); xercesc::DOMElement * notes_elem = XW_DocElem->createElement(tag_Notes()); XMLCh * x_notes = tc(notes.c_str()); xercesc::DOMText * meta_data_notes = XW_DocElem->createTextNode(x_notes); xr(&x_notes); notes_elem->appendChild(meta_data_notes); meta_data_elem->appendChild(notes_elem); parentNode->appendChild(meta_data_elem); return meta_data_elem; } void crispr::xml::writer::addFileToMetadata(std::string type, std::string url, xercesc::DOMElement * parentNode) { xercesc::DOMElement * file = XW_DocElem->createElement(tag_File()); XMLCh * x_type = tc(type.c_str()); XMLCh * x_url = tc(url.c_str()); file->setAttribute(attr_Type(), x_type); file->setAttribute(attr_Url(), x_url); xr(&x_type); xr(&x_url); parentNode->appendChild(file); } void crispr::xml::writer::addNotesToMetadata(std::string notes, xercesc::DOMElement *parentNode) { xercesc::DOMElement * notes_elem = XW_DocElem->createElement(tag_Notes()); XMLCh * x_notes = tc(notes.c_str()); xercesc::DOMText * meta_data_notes = XW_DocElem->createTextNode(x_notes); xr(&x_notes); notes_elem->appendChild(meta_data_notes); parentNode->appendChild(notes_elem); } xercesc::DOMElement * crispr::xml::writer::addGroup(std::string& gID, std::string& drConsensus, xercesc::DOMElement * parentNode) { xercesc::DOMElement * group = XW_DocElem->createElement(tag_Group()); // Set the attributes of the group XMLCh * x_gID = tc(gID.c_str()); XMLCh * x_drConsensus = tc(drConsensus.c_str()); group->setAttribute(attr_Gid(), x_gID); group->setAttribute(attr_Drseq(), x_drConsensus); xr(&x_gID); xr(&x_drConsensus); // add the group to the parent (root element) parentNode->appendChild(group); return group; } xercesc::DOMElement * crispr::xml::writer::addData(xercesc::DOMElement * parentNode) { // create the data node with spacer and drs as child elements xercesc::DOMElement * data = XW_DocElem->createElement(tag_Data()); xercesc::DOMElement * sources = XW_DocElem->createElement(tag_Sources()); xercesc::DOMElement * drs = XW_DocElem->createElement(tag_Drs()); xercesc::DOMElement * spacers = XW_DocElem->createElement(tag_Spacers()); data->appendChild(sources); data->appendChild(drs); data->appendChild(spacers); parentNode->appendChild(data); return data; } xercesc::DOMElement * crispr::xml::writer::addAssembly(xercesc::DOMElement * parentNode) { xercesc::DOMElement * assembly = XW_DocElem->createElement(tag_Assembly()); parentNode->appendChild(assembly); return assembly; } void crispr::xml::writer::addDirectRepeat(std::string& drid, std::string& seq, xercesc::DOMElement * parentNode) { xercesc::DOMElement * dr = XW_DocElem->createElement(tag_Dr()); XMLCh * x_seq = tc(seq.c_str()); XMLCh * x_drid = tc(drid.c_str()); dr->setAttribute(attr_Seq(), x_seq); dr->setAttribute(attr_Drid(), x_drid); xr(&x_seq); xr(&x_drid); parentNode->appendChild(dr); } xercesc::DOMElement * crispr::xml::writer::addSpacer(std::string& seq, std::string& spid, xercesc::DOMElement * parentNode, std::string cov) { xercesc::DOMElement * sp = XW_DocElem->createElement(tag_Spacer()); XMLCh * x_seq = tc(seq.c_str()); XMLCh * x_cov = tc(cov.c_str()); XMLCh * x_spid = tc(spid.c_str()); sp->setAttribute(attr_Seq(), x_seq); sp->setAttribute(attr_Spid(), x_spid); sp->setAttribute(attr_Cov(), x_cov); xr(&x_seq); xr(&x_cov); xr(&x_spid); parentNode->appendChild(sp); return sp; } xercesc::DOMElement * crispr::xml::writer::createFlankers(xercesc::DOMElement * parentNode) { xercesc::DOMElement * flankers = XW_DocElem->createElement(tag_Flankers()); parentNode->appendChild(flankers); return flankers; } xercesc::DOMElement * crispr::xml::writer::addFlanker(std::string& seq, std::string& flid, xercesc::DOMElement * parentNode) { XMLCh * x_seq = tc(seq.c_str()); XMLCh * x_flid = tc(flid.c_str()); xercesc::DOMElement * flanker = XW_DocElem->createElement(tag_Flanker()); flanker->setAttribute(attr_Seq(), x_seq); flanker->setAttribute(attr_Flid(), x_flid); xr(&x_seq); xr(&x_flid); parentNode->appendChild(flanker); return flanker; } xercesc::DOMElement * crispr::xml::writer::addContig(std::string& cid, xercesc::DOMElement * parentNode) { xercesc::DOMElement * contig = XW_DocElem->createElement(tag_Contig()); XMLCh * x_cid = tc(cid.c_str()); contig->setAttribute(attr_Cid(), x_cid); xr(&x_cid); parentNode->appendChild(contig); return contig; } void crispr::xml::writer::createConsensus(std::string& concensus, xercesc::DOMElement * parentNode) { xercesc::DOMElement * concensus_elem = XW_DocElem->createElement(tag_Consensus()); XMLCh * x_consensus = tc(concensus.c_str()); xercesc::DOMText * concensus_text = XW_DocElem->createTextNode(x_consensus); xr(&x_consensus); concensus_elem->appendChild(concensus_text); parentNode->appendChild(concensus_elem); } xercesc::DOMElement * crispr::xml::writer::addSpacerToContig(std::string& spid, xercesc::DOMElement * parentNode) { xercesc::DOMElement * cspacer = XW_DocElem->createElement(tag_Cspacer()); XMLCh * x_spid = tc(spid.c_str()); cspacer->setAttribute(attr_Spid(), x_spid); xr(&x_spid); parentNode->appendChild(cspacer); return cspacer; } xercesc::DOMElement * crispr::xml::writer::createSpacers(std::string tag) { XMLCh * x_tag = tc(tag.c_str()); xercesc::DOMElement * spacers = XW_DocElem->createElement(x_tag); xr(&x_tag); return spacers; } xercesc::DOMElement * crispr::xml::writer::createFlankers(std::string tag) { return createSpacers(tag); } void crispr::xml::writer::addSpacer(std::string tag, std::string& spid, std::string& drid, std::string& drconf, xercesc::DOMElement * parentNode) { XMLCh * x_tag = tc(tag.c_str()); XMLCh * x_drid = tc(drid.c_str()); XMLCh * x_drconf = tc(drconf.c_str()); XMLCh * x_spid = tc(spid.c_str()); xercesc::DOMElement * fs = XW_DocElem->createElement(x_tag); fs->setAttribute(attr_Drid(), x_drid); fs->setAttribute(attr_Drconf(), x_drconf); fs->setAttribute(attr_Spid(), x_spid); xr(&x_tag); xr(&x_drid); xr(&x_drconf); xr(&x_spid); parentNode->appendChild(fs); } void crispr::xml::writer::addFlanker(std::string tag, std::string& flid, std::string& drconf, std::string& directjoin, xercesc::DOMElement * parentNode) { XMLCh * x_tag = tc(tag.c_str()); XMLCh * x_flid = tc(flid.c_str()); XMLCh * x_drconf = tc(drconf.c_str()); XMLCh * x_directjoin = tc(directjoin.c_str()); xercesc::DOMElement * bf = XW_DocElem->createElement(x_tag); bf->setAttribute(attr_Flid(), x_flid); bf->setAttribute(attr_Drconf(), x_drconf); bf->setAttribute(attr_Directjoin(), x_directjoin); xr(&x_tag); xr(&x_flid); xr(&x_drconf); xr(&x_directjoin); parentNode->appendChild(bf); } //create the sources tag for a group xercesc::DOMElement * crispr::xml::writer::addSources(xercesc::DOMElement * parentNode) { xercesc::DOMElement * sources = XW_DocElem->createElement(tag_Sources()); parentNode->appendChild(sources); return sources; } // create a source tag for either the sources in xercesc::DOMElement * crispr::xml::writer::addSource(std::string accession, std::string soid, xercesc::DOMElement * parentNode) { xercesc::DOMElement * source = XW_DocElem->createElement(tag_Source()); XMLCh * x_acc = tc(accession.c_str()); source->setAttribute(attr_Accession(), x_acc); XMLCh * x_soid = tc(soid.c_str()); source->setAttribute(attr_Soid(), x_soid); parentNode->appendChild(source); xr(&x_acc); xr(&x_soid); return source; } xercesc::DOMElement * crispr::xml::writer::addSpacerSource(std::string soid, xercesc::DOMElement * parentNode) { xercesc::DOMElement * source = XW_DocElem->createElement(tag_Source()); XMLCh * x_soid = tc(soid.c_str()); source->setAttribute(attr_Soid(), x_soid); parentNode->appendChild(source); xr(&x_soid); return source; } // add start and end positions for in void crispr::xml::writer::addStartAndEndPos(std::string start, std::string end, xercesc::DOMElement * parentNode) { xercesc::DOMElement * start_tag = XW_DocElem->createElement(tag_Spos()); xercesc::DOMElement * end_tag = XW_DocElem->createElement(tag_Epos()); XMLCh * x_start_site = tc(start.c_str()); XMLCh * x_end_site = tc(end.c_str()); xercesc::DOMText * start_text = XW_DocElem->createTextNode(x_start_site); xercesc::DOMText * end_text = XW_DocElem->createTextNode(x_end_site); start_tag->appendChild(start_text); end_tag->appendChild(end_text); parentNode->appendChild(start_tag); parentNode->appendChild(end_tag); xr(&x_start_site); xr(&x_end_site); } // add a tag to xercesc::DOMElement * crispr::xml::writer::addProgram(xercesc::DOMElement * parentNode) { xercesc::DOMElement * program = XW_DocElem->createElement(tag_Program()); parentNode->appendChild(program); return program; } //add a tag to void crispr::xml::writer::addProgName(std::string progName, xercesc::DOMElement * parentNode) { xercesc::DOMElement * name_tag = XW_DocElem->createElement(tag_Name()); XMLCh * x_prog_name = tc(progName.c_str()); xercesc::DOMText * name_text = XW_DocElem->createTextNode(x_prog_name); name_tag->appendChild(name_text); parentNode->appendChild(name_tag); xr(&x_prog_name); } // add a tag to void crispr::xml::writer::addProgVersion(std::string progVersion, xercesc::DOMElement * parentNode) { xercesc::DOMElement * version_tag = XW_DocElem->createElement(tag_Version()); XMLCh * x_prog_version = tc(progVersion.c_str()); xercesc::DOMText * version_text = XW_DocElem->createTextNode(x_prog_version); version_tag->appendChild(version_text); parentNode->appendChild(version_tag); xr(&x_prog_version); } //add a tag to void crispr::xml::writer::addProgCommand(std::string progCommand, xercesc::DOMElement * parentNode) { xercesc::DOMElement * command_tag = XW_DocElem->createElement(tag_Command()); XMLCh * x_prog_version = tc(progCommand.c_str()); xercesc::DOMText * command_text = XW_DocElem->createTextNode(x_prog_version); command_tag->appendChild(command_text); parentNode->appendChild(command_tag); xr(&x_prog_version); } // // File IO / Printing // bool crispr::xml::writer::printDOMToFile(std::string outFileName ) { bool retval; try { // get a serializer, an instance of DOMLSSerializer XMLCh tempStr[3] = {xercesc::chLatin_L, xercesc::chLatin_S, xercesc::chNull}; xercesc::DOMImplementation *impl = xercesc::DOMImplementationRegistry::getDOMImplementation(tempStr); xercesc::DOMLSSerializer *theSerializer = ((xercesc::DOMImplementationLS*)impl)->createLSSerializer(); xercesc::DOMLSOutput *theOutputDesc = ((xercesc::DOMImplementationLS*)impl)->createLSOutput(); // set user specified output encoding XMLCh * x_encoding = tc(""ISO8859-1""); theOutputDesc->setEncoding(x_encoding); xr(&x_encoding); xercesc::DOMConfiguration* serializerConfig=theSerializer->getDomConfig(); // set feature if the serializer supports the feature/mode if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTSplitCdataSections, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTSplitCdataSections, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTDiscardDefaultContent, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTDiscardDefaultContent, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTFormatPrettyPrint, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTFormatPrettyPrint, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTBOM, false)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTBOM, false); // // Plug in a format target to receive the resultant // XML stream from the serializer. // // StdOutFormatTarget prints the resultant XML stream // to stdout once it receives any thing from the serializer. // xercesc::XMLFormatTarget *myFormTarget; myFormTarget = new xercesc::LocalFileFormatTarget(outFileName.c_str()); //myFormTarget=new StdOutFormatTarget(); theOutputDesc->setByteStream(myFormTarget); theSerializer->write(XW_DocElem, theOutputDesc); theOutputDesc->release(); theSerializer->release(); // // Filter, formatTarget and error handler // are NOT owned by the serializer. // delete myFormTarget; retval = true; } catch (const xercesc::OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << ""OutOfMemoryException"" << XERCES_STD_QUALIFIER endl; retval = false; } catch (xercesc::XMLException& e) { char * c_exept = tc(e.getMessage()); XERCES_STD_QUALIFIER cerr << ""An error occurred during creation of output transcoder. Msg is:"" << XERCES_STD_QUALIFIER endl << c_exept << XERCES_STD_QUALIFIER endl; retval = false; xr(&c_exept); } return retval; } bool crispr::xml::writer::printDOMToScreen(void ) { bool retval; try { // get a serializer, an instance of DOMLSSerializer XMLCh tempStr[3] = {xercesc::chLatin_L, xercesc::chLatin_S, xercesc::chNull}; xercesc::DOMImplementation *impl = xercesc::DOMImplementationRegistry::getDOMImplementation(tempStr); xercesc::DOMLSSerializer *theSerializer = ((xercesc::DOMImplementationLS*)impl)->createLSSerializer(); xercesc::DOMLSOutput *theOutputDesc = ((xercesc::DOMImplementationLS*)impl)->createLSOutput(); // set user specified output encoding XMLCh * x_encoding = tc(""ISO8859-1""); theOutputDesc->setEncoding(x_encoding); xr(&x_encoding); xercesc::DOMConfiguration* serializerConfig=theSerializer->getDomConfig(); // set feature if the serializer supports the feature/mode if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTSplitCdataSections, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTSplitCdataSections, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTDiscardDefaultContent, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTDiscardDefaultContent, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTFormatPrettyPrint, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTFormatPrettyPrint, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTBOM, false)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTBOM, false); // // Plug in a format target to receive the resultant // XML stream from the serializer. // // StdOutFormatTarget prints the resultant XML stream // to stdout once it receives any thing from the serializer. // xercesc::XMLFormatTarget *myFormTarget; myFormTarget=new xercesc::StdOutFormatTarget(); theOutputDesc->setByteStream(myFormTarget); theSerializer->write(XW_DocElem, theOutputDesc); theOutputDesc->release(); theSerializer->release(); // // Filter, formatTarget and error handler // are NOT owned by the serializer. // delete myFormTarget; retval = true; } catch (const xercesc::OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << ""OutOfMemoryException"" << XERCES_STD_QUALIFIER endl; retval = false; } catch (xercesc::XMLException& e) { char * c_exept = tc(e.getMessage()); XERCES_STD_QUALIFIER cerr << ""An error occurred during creation of output transcoder. Msg is:"" << XERCES_STD_QUALIFIER endl << c_exept << XERCES_STD_QUALIFIER endl; retval = false; xr(&c_exept); } return retval; } bool crispr::xml::writer::printDOMToFile(std::string outFileName, xercesc::DOMDocument * docDOM ) { bool retval; try { // get a serializer, an instance of DOMLSSerializer XMLCh tempStr[3] = {xercesc::chLatin_L, xercesc::chLatin_S, xercesc::chNull}; xercesc::DOMImplementation *impl = xercesc::DOMImplementationRegistry::getDOMImplementation(tempStr); xercesc::DOMLSSerializer *theSerializer = ((xercesc::DOMImplementationLS*)impl)->createLSSerializer(); xercesc::DOMLSOutput *theOutputDesc = ((xercesc::DOMImplementationLS*)impl)->createLSOutput(); // set user specified output encoding XMLCh * x_encoding = tc(""ISO8859-1""); theOutputDesc->setEncoding(x_encoding); xr(&x_encoding); xercesc::DOMConfiguration* serializerConfig = theSerializer->getDomConfig(); // set feature if the serializer supports the feature/mode if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTSplitCdataSections, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTSplitCdataSections, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTDiscardDefaultContent, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTDiscardDefaultContent, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTFormatPrettyPrint, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTFormatPrettyPrint, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTBOM, false)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTBOM, false); // // Plug in a format target to receive the resultant // XML stream from the serializer. // // StdOutFormatTarget prints the resultant XML stream // to stdout once it receives any thing from the serializer. // xercesc::XMLFormatTarget *myFormTarget; myFormTarget = new xercesc::LocalFileFormatTarget(outFileName.c_str()); //myFormTarget=new StdOutFormatTarget(); theOutputDesc->setByteStream(myFormTarget); theSerializer->write(docDOM, theOutputDesc); theOutputDesc->release(); theSerializer->release(); // // Filter, formatTarget and error handler // are NOT owned by the serializer. // delete myFormTarget; retval = true; } catch (const xercesc::OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << ""OutOfMemoryException"" << XERCES_STD_QUALIFIER endl; retval = false; } catch (xercesc::XMLException& e) { char * c_msg = tc(e.getMessage()); XERCES_STD_QUALIFIER cerr << ""An error occurred during creation of output transcoder. Msg is:"" << XERCES_STD_QUALIFIER endl << c_msg << XERCES_STD_QUALIFIER endl; retval = false; xr(&c_msg); } return retval; } bool crispr::xml::writer::printDOMToScreen(xercesc::DOMDocument * domDoc ) { bool retval; try { // get a serializer, an instance of DOMLSSerializer XMLCh tempStr[3] = {xercesc::chLatin_L, xercesc::chLatin_S, xercesc::chNull}; xercesc::DOMImplementation *impl = xercesc::DOMImplementationRegistry::getDOMImplementation(tempStr); xercesc::DOMLSSerializer *theSerializer = ((xercesc::DOMImplementationLS*)impl)->createLSSerializer(); xercesc::DOMLSOutput *theOutputDesc = ((xercesc::DOMImplementationLS*)impl)->createLSOutput(); // set user specified output encoding XMLCh * x_encoding = tc(""ISO8859-1""); theOutputDesc->setEncoding(x_encoding); xr(&x_encoding); xercesc::DOMConfiguration* serializerConfig=theSerializer->getDomConfig(); // set feature if the serializer supports the feature/mode if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTSplitCdataSections, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTSplitCdataSections, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTDiscardDefaultContent, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTDiscardDefaultContent, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTFormatPrettyPrint, true)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTFormatPrettyPrint, true); if (serializerConfig->canSetParameter(xercesc::XMLUni::fgDOMWRTBOM, false)) serializerConfig->setParameter(xercesc::XMLUni::fgDOMWRTBOM, false); // // Plug in a format target to receive the resultant // XML stream from the serializer. // // StdOutFormatTarget prints the resultant XML stream // to stdout once it receives any thing from the serializer. // xercesc::XMLFormatTarget *myFormTarget; myFormTarget=new xercesc::StdOutFormatTarget(); theOutputDesc->setByteStream(myFormTarget); theSerializer->write(domDoc, theOutputDesc); theOutputDesc->release(); theSerializer->release(); // // Filter, formatTarget and error handler // are NOT owned by the serializer. // delete myFormTarget; retval = true; } catch (const xercesc::OutOfMemoryException&) { XERCES_STD_QUALIFIER cerr << ""OutOfMemoryException"" << XERCES_STD_QUALIFIER endl; retval = false; } catch (xercesc::XMLException& e) { char * c_msg = tc(e.getMessage()); XERCES_STD_QUALIFIER cerr << ""An error occurred during creation of output transcoder. Msg is:"" << XERCES_STD_QUALIFIER endl << c_msg << XERCES_STD_QUALIFIER endl; retval = false; xr(&c_msg); } return retval; } ","C++" "CRISPR","ctSkennerton/crass","src/crass/Rainbow.cpp",".cpp","5539","209","// File: Rainbow.cpp // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Implementation of Rainbow functions // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // system includes #include #include #include #include // local includes #include ""Rainbow.h"" // vertical scalers #define RB_lower_offset (0.5) #define RB_divisor (0.6666666666) #define getValue(vAL) ((cos(vAL) + RB_lower_offset) * RB_divisor) // crude rounding function // setting initial limits void Rainbow::setLimits(double lb, double ub, int res) { //----- // set the limits // mLowerBound = lb; mUpperBound = ub; mResolution = res; // set the shortcut constants mScaleMultiplier = (mUpperScale - mLowerScale)/(mUpperBound - mLowerBound); mTickSize = (mUpperBound - mLowerBound)/(mResolution - 1); } void Rainbow::setType(RB_TYPE type) { //----- // set the offsets based on type // mType = type; switch(type) { case RED_BLUE: { mRedOffset = 0; mGreenOffset = RB_divisor * PI * 2; mBlueOffset = RB_divisor * PI; mIgnoreRed = false; mIgnoreGreen = true; mIgnoreBlue = false; mLowerScale = 0; mUpperScale = (RB_divisor * PI); break; } case RED_BLUE_GREEN: { mRedOffset = 0; mGreenOffset = RB_divisor * PI * 2; mBlueOffset = RB_divisor * PI; mIgnoreRed = false; mIgnoreGreen = false; mIgnoreBlue = false; mLowerScale = 0; mUpperScale = (RB_divisor * PI * 2); break; } case GREEN_BLUE_RED: { mRedOffset = RB_divisor * PI * 2; mGreenOffset = 0; mBlueOffset = RB_divisor * PI; mIgnoreRed = false; mIgnoreGreen = false; mIgnoreBlue = false; mLowerScale = 0; mUpperScale = (RB_divisor * PI * 2); break; } case BLUE_RED: default: { // BLUE_RED, mRedOffset = RB_divisor * PI; mGreenOffset = RB_divisor * PI * 2; mBlueOffset = 0; mIgnoreRed = false; mIgnoreGreen = true; mIgnoreBlue = false; mLowerScale = 0; mUpperScale = (RB_divisor * PI); } } // reset this mScaleMultiplier = (mUpperScale - mLowerScale)/(mUpperBound - mLowerBound); } void Rainbow::setDefaults(void) { //----- // Just waht it says // setType(RB_DEFAULT_TYPE); setLimits(RB_LB, RB_UB, RB_TICKS); } // get a colour!; std::string Rainbow::getColour(double value) { //----- // Return a colour for the given value. // If nothing makes sense. return black // // check to see that everything makes sense if(-1 == mResolution) return RB_ERROR_COLOUR; if(value > mUpperBound || value < mLowerBound) return RB_ERROR_COLOUR; // normalise the value to suit the ticks double normalised_value = round(value/mTickSize) * mTickSize; // map the normalised value onto the horizontal scale double scaled_value = (normalised_value - mLowerBound) * mScaleMultiplier + mLowerScale; // now construct the colour std::stringstream ss; if(mIgnoreRed) ss << ""00""; else ss << int2RGB(round(getValue(scaled_value - mRedOffset) * 255)); if(mIgnoreGreen) ss << ""00""; else ss << int2RGB(round(getValue(scaled_value - mGreenOffset) * 255)); if(mIgnoreBlue) ss << ""00""; else ss << int2RGB(round(getValue(scaled_value - mBlueOffset) * 255)); return ss.str(); } std::string Rainbow::int2RGB(int rgb) { //---- // convert an int between 0 and 255 to a hex RGB value // if(0 >= rgb) { return ""00""; } else { std::stringstream ss; if (16 > rgb) ss << ""0"" << std::hex << rgb; else ss << std::hex << rgb; return ss.str(); } } ","C++" "CRISPR","ctSkennerton/crass","src/crass/CrisprGraph.h",".h","2972","104","/* * CrisprGraph.h is part of the crisprtools project * * Created by Connor Skennerton on 7/12/11. * Copyright 2011 Connor Skennerton. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef crisprtools_CrisprGraph_h #define crisprtools_CrisprGraph_h #include #include namespace crispr { // basic wrapper around the graphviz library class graph { Agraph_t * G_graph; public: graph(char * name ) { G_graph = agopen(name, AGDIGRAPH ); } ~graph() { agclose(G_graph); } inline Agraph_t * getGraph(void){return G_graph;} inline Agnode_t * addNode(char * name) { Agnode_t * n = agnode(G_graph, name); return n; } inline Agedge_t * addEdge(Agnode_t * tail, Agnode_t * head) { return agedge(G_graph, tail, head); } inline Agnode_t * nodeWithName(char * name) { return agfindnode(G_graph, name); } inline Agedge_t * findEdge(Agnode_t * tail, Agnode_t * head) { return agfindedge(G_graph, tail, head); } int setNodeAttribute(Agnode_t * node ,char * attrName, char * attrValue); int setGraphAttribute(char * attrName, char * attrValue); int setEdgeAttribute(Agedge_t * edge ,char * attrName, char * attrValue); inline int setNodeAttribute(char * nodeName ,char * attrName, char * attrValue) { Agnode_t * node = agfindnode(G_graph, nodeName); if (node != NULL) { return setNodeAttribute(node, attrName, attrValue); } else { return 1; } } }; } #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/reader.cpp",".cpp","2642","75","/* * crass.h is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include ""reader.h"" crispr::xml::reader::reader() { XR_FileParser = new xercesc::XercesDOMParser; } crispr::xml::reader::~reader() { delete XR_FileParser; } xercesc::DOMDocument * crispr::xml::reader::setFileParser(const char * XMLFile) { // Configure DOM parser. XR_FileParser->setValidationScheme( xercesc::XercesDOMParser::Val_Never ); XR_FileParser->setDoNamespaces( false ); XR_FileParser->setDoSchema( false ); XR_FileParser->setLoadExternalDTD( false ); try { XR_FileParser->parse( XMLFile ); return XR_FileParser->getDocument(); } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::stringstream errBuf; errBuf << ""Error parsing file: "" << message << std::flush; xercesc::XMLString::release( &message ); throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__,(errBuf.str()).c_str()); } catch (xercesc::DOMException& e) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::stringstream errBuf; errBuf << ""Error parsing file: "" << message << std::flush; xercesc::XMLString::release( &message ); throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__,(errBuf.str()).c_str()); } } ","C++" "CRISPR","ctSkennerton/crass","src/crass/GraphDrawingDefines.h",".h","6271","131","/* * GraphDrawingDefines.h is part of the crass project * * Created by Connor Skennerton on 6/09/11. * Copyright 2011 Connor Skennerton. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef crass_GraphDrawingDefines_h #define crass_GraphDrawingDefines_h // -------------------------------------------------------------------- // GRAPH DRAWING DEFAULTS // -------------------------------------------------------------------- #define CRASS_DEF_GV_DEFULT_COLOUR ""grey"" // colour when no coverage is available #define CRASS_DEF_GV_EDGE_LENGTH 2 // length of arrows for edges in images #define CRASS_DEF_GV_NODE_SHAPE ""circle"" // shape of nodes #define CRASS_DEF_GV_FLANKER_SHAPE ""diamond"" // shape for the flankers #define CRASS_DEF_GV_NODE_PREFIX ""node_"" // prefix used when naming nodes for the image #define CRASS_DEF_GV_NODE_FILL ""filled"" // should our nodes be filled with colour #define CRASS_DEF_DEFAULT_GRAPH_TYPE ""digraph"" // the default type of graphviz graph to generate #define CRASS_DEF_DEFAULT_SUB_GRAPH_TYPE ""subgraph"" // the default type of graphviz graph to generate #define CRASS_DEF_GV_SPA_EDGE_LENGTH 2 // length of arrows for edges in images #define CRASS_DEF_GV_SPA_SHAPE ""circle"" // shape of nodes #define CRASS_DEF_GV_SPA_PREFIX ""sp_"" // prefix used when naming spacers for the image #define CRASS_DEF_GV_FL_PREFIX ""fl_"" // prefix used when naming flankers for the image // -------------------------------------------------------------------- // GRAPH DRAWING MACROS // -------------------------------------------------------------------- #define gvEdge(stream,id1,id2){\ stream< ""< ""< ""< ""<KEY"";\ } #define gvKeyGroupHeader(stream, cLUSTERnUMBER, gROUPnAME){ \ stream<<""\t""<""<"";\ } #define gvKeyEntry(stream, lABEL, cOLOUR){ \ stream<<""""<< lABEL <<"""";\ } #define gvKeyFooter(stream){ \ stream<<""> ];\n\t}""<. */ #include ""parser.h"" #include ""CrisprGraph.h"" #include ""Rainbow.h"" #include #include #include #include #ifndef DRAWTOOL_H #define DRAWTOOLS_H typedef std::vector graphVector; class DrawTool { enum EDGE_DIRECTION { FORWARD = 0, REVERSE = 1 }; GVC_t * DT_Gvc; std::string DT_OutputFile; char * DT_RenderingAlgorithm; char * DT_OutputFormat; std::set DT_Groups; std::map > DT_SpacerCoverage; bool DT_Subset; graphVector DT_Graphs; Rainbow DT_Rainbow; RB_TYPE DT_ColourType; int DT_Bins; double DT_UpperLimit; double DT_LowerLimit; void resetInitialLimits(void) { DT_LowerLimit = 10000000; DT_UpperLimit = 0; } void recalculateLimits(double d) { if (d > DT_UpperLimit) { DT_UpperLimit = d; } if(d < DT_LowerLimit) { DT_LowerLimit = d; } } void setColours(void) { DT_Rainbow.setType(DT_ColourType); if (DT_Bins > 0) { DT_Rainbow.setLimits(DT_LowerLimit, DT_UpperLimit, DT_Bins); } else { DT_Rainbow.setLimits(DT_LowerLimit, DT_UpperLimit); } } public: DrawTool() { DT_Gvc = gvContext(); DT_Subset = false; DT_LowerLimit = 10000000; DT_UpperLimit = 0; DT_ColourType = BLUE_RED; DT_Bins = -1; } ~DrawTool(); inline GVC_t * getContext(void){return DT_Gvc;} void layoutGraph(Agraph_t * g, char * a){gvLayout(DT_Gvc, g, a);} void renderGraphToFile(Agraph_t * g, char * t, char * f){gvRenderFilename(DT_Gvc, g, t, f);} void freeLayout(Agraph_t * g){gvFreeLayout(DT_Gvc, g);} int processOptions(int argc, char ** argv); void generateGroupsFromString ( std::string str); int processInputFile(const char * inputFile); void parseGroup(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser); void parseData(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * current_graph); void parseDrs(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * current_graph); void parseSpacers(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * current_graph); void parseFlankers(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * current_graph); void parseAssembly(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph); void parseContig(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph, std::string& contigId); void parseCSpacer(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph, Agnode_t * currentGraphvizNode, std::string& contigId); void parseLinkSpacers(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph, Agnode_t * currentGraphvizNode, EDGE_DIRECTION edgeDirection, std::string& contigId); void parseLinkFlankers(xercesc::DOMElement * parentNode, crispr::xml::parser& xmlParser, crispr::graph * currentGraph, Agnode_t * currentGraphvizNode, EDGE_DIRECTION edgeDirection, std::string& contigId); }; int drawMain(int argc, char ** argv); void drawUsage(void); #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/ExtractTool.h",".h","2888","93","/* * ExtractTool.h * * Copyright (C) 2011 2012 - Connor Skennerton * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef EXTRACTTOOL_H #define EXTRACTTOOL_H #include #include #include #include #include #include ""base.h"" class ExtractTool { public: enum ELEMENT_TYPE{REPEAT,SPACER,CONSENSUS,FLANKER}; // constructor ExtractTool(); // destructor ~ExtractTool(); // option processing //void generateGroupsFromString( std::string groupString); int processOptions(int argc, char ** argv); void setOutputBuffer(std::ofstream& out, const char * file); // process the input int processInputFile(const char * inputFile); void parseWantedGroups(crispr::xml::base& xmlObj, xercesc::DOMElement * rootElement); void extractDataFromGroup(crispr::xml::base& xmlDoc, xercesc::DOMElement * currentGroup); void processData(crispr::xml::base& xmlDoc, xercesc::DOMElement * currentType, ELEMENT_TYPE wantedType, std::string gid, std::ostream& outStream); private: void closeStream(); void openStream(std::string& groupId); std::set ET_Group; // holds a comma separated list of groups that need to be extracted std::ofstream ET_RepeatStream; std::ofstream ET_FlankerStream; std::ofstream ET_SpacerStream; std::ofstream ET_OneStream; std::ofstream ET_GroupStream; std::string ET_OutputPrefix; std::string ET_OutputHeaderPrefix; std::string ET_OutputNamePrefix; std::bitset<7> ET_BitMask; /* each bit is for a different option: bit pos: 6543210 0000000 ||||||| ||||||------- a subset of the groups is wanted |||||-------- print different types of data (spacers, dr, flanker) into separate files ||||--------- print results from a different group into separate files |||---------- extract flanking sequences ||----------- extract spacer sequences |------------ extract direct repeat sequences ------------- print coverage information if extracting spacers */ }; /* Global functions */ int extractMain(int argc, char ** argv); void extractUsage(void); #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/NodeManager.cpp",".cpp","73121","2069","// File: NodeManager.cpp // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Implementation of NodeManager functions // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // system includes #include #include #include #include #include #include #include // local includes #include #include ""NodeManager.h"" #include ""LoggerSimp.h"" #include ""crassDefines.h"" #include ""CrisprNode.h"" #include ""SpacerInstance.h"" #include ""libcrispr.h"" #include ""StringCheck.h"" #include ""ReadHolder.h"" #include ""StringCheck.h"" #include ""GraphDrawingDefines.h"" #include ""Rainbow.h"" #include ""StlExt.h"" #include ""Exception.h"" SpacerInstance * WalkingManager::shift(SpacerInstance * newNode) { SpacerInstance * old_node = WM_WalkingElem.first; WM_WalkingElem.first = WM_WalkingElem.second; WM_WalkingElem.second = newNode; return old_node; } NodeManager::NodeManager(std::string drSeq, const options * userOpts) { //----- // constructor // NM_DirectRepeatSequence = drSeq; NM_Opts = userOpts; NM_StringCheck.setName(""NM_"" + drSeq); NM_NextContigID = 0; } NodeManager::~NodeManager(void) { //----- // destructor // // clean up all the cripsr nodes NodeListIterator node_iter = NM_Nodes.begin(); while(node_iter != NM_Nodes.end()) { if(NULL != node_iter->second) { delete node_iter->second; node_iter->second = NULL; } node_iter++; } NM_Nodes.clear(); SpacerListIterator spacer_iter = NM_Spacers.begin(); while(spacer_iter != NM_Spacers.end()) { if(NULL != spacer_iter->second) { delete spacer_iter->second; spacer_iter->second = NULL; } spacer_iter++; } NM_Spacers.clear(); // delete contigs; clearContigs(); } bool NodeManager::addReadHolder(ReadHolder * RH) { //----- // add a readholder to this mofo // if (splitReadHolder(RH)) { NM_ReadList.push_back(RH); return true; } else { logError(""Unable to split ReadHolder""); return false; } } //---- // private function called from addReadHolder to split the read into spacers and pass it through to others // bool NodeManager::splitReadHolder(ReadHolder * RH) { //----- // Split down a read holder and make some nodes // std::string working_str; CrisprNode * prev_node = NULL; // add the header of this read to our stringcheck StringToken header_st = NM_StringCheck.addString(RH->getHeader()); #ifdef SEARCH_SINGLETON SearchCheckerList::iterator debug_iter = debugger->find(RH->getHeader()); if ( debug_iter != debugger->end()) { // an interesting read debug_iter->second.nmtoken(header_st); } #endif //MI std::cout << std::endl << ""----------------------------------\n"" << RH->getHeader() << std::endl; //MI std::cout << RH->splitApartSimple() << std::endl; if(RH->getFirstSpacer(&working_str)) { //MI std::cout << ""first SP: "" << working_str << std::endl; try { // do we have a direct repeat from the very beginning if (RH->startStopsAt(0) == 0) { //MI std::cout << ""both"" << std::endl; addCrisprNodes(&prev_node, working_str, header_st, RH); } else { //MI std::cout << ""sec"" << std::endl; // we only want to add the second kmer, since it is anchored by the direct repeat addSecondCrisprNode(&prev_node, working_str, header_st, RH); } // get all the spacers in the middle //check to see if we end with a direct repeat or a spacer if (RH->getSeqLength() == (int)RH->back() + 1) { // direct repeat goes right to the end of the read take both //MI std::cout << ""DR until end"" << std::endl; while (RH->getNextSpacer(&working_str)) { //MI std::cout << ""SP: "" << working_str << std::endl; addCrisprNodes(&prev_node, working_str, header_st, RH); } } else { //MI std::cout << ""SP at end"" << std::endl; // we end with an overhanging spacer so we want to break from the loop early // so that on the final time we only cut the first kmer while (RH->getLastSpacerPos() < (int)RH->getStartStopListSize() - 1) { //std::cout<getLastSpacerPos()<<"" : ""<<(int)RH->getStartStopListSize() - 1<<"" : ""<getNextSpacer(&working_str); //MI std::cout << ""SP: "" << working_str << std::endl; addCrisprNodes(&prev_node, working_str, header_st, RH); } // get our last spacer if (RH->getNextSpacer(&working_str)) { //std::cout<cNodeKmerLength) return; std::string first_kmer = workingString.substr(0, NM_Opts->cNodeKmerLength); std::string second_kmer = workingString.substr(workingString.length() - NM_Opts->cNodeKmerLength, NM_Opts->cNodeKmerLength ); CrisprNode * first_kmer_node; CrisprNode * second_kmer_node; SpacerKey this_sp_key; // check to see if these kmers are already stored StringToken st1 = NM_StringCheck.getToken(first_kmer); // if they have been added previously then token != 0 if(0 == st1) { // first time we've seen this guy. Make some new objects st1 = NM_StringCheck.addString(first_kmer); first_kmer_node = new CrisprNode(st1); // add them to the pile NM_Nodes[st1] = first_kmer_node; #ifdef DEBUG logInfo(""creating node ""<incrementCount(); } StringToken st2 = NM_StringCheck.getToken(second_kmer); if(0 == st2) { st2 = NM_StringCheck.addString(second_kmer); second_kmer_node = new CrisprNode(st2); second_kmer_node->setForward(false); NM_Nodes[st2] = second_kmer_node; #ifdef DEBUG logInfo(""creating node ""<incrementCount(); } // add in the read headers for the two CrisprNodes first_kmer_node->addReadHeader(headerSt); second_kmer_node->addReadHeader(headerSt); first_kmer_node->addReadHolder(RH); second_kmer_node->addReadHolder(RH); // the first kmers pair is the previous node which lay before it therefore bool is true // make sure prevNode is not NULL if (NULL != *prevNode) { this_sp_key = makeSpacerKey(st1, (*prevNode)->getID()); if(NM_Spacers.find(this_sp_key) == NM_Spacers.end()) { (*prevNode)->addEdge(first_kmer_node, CN_EDGE_JUMPING_F); first_kmer_node->addEdge(*prevNode, CN_EDGE_JUMPING_B); } } #ifdef SEARCH_SINGLETON SearchCheckerList::iterator debug_iter = debugger->find(NM_StringCheck.getString(headerSt)); if (debug_iter != debugger->end()) { // interesting read debug_iter->second.addNode(st1); debug_iter->second.addNode(st2); } #endif // now it's time to add the spacer SpacerInstance * curr_spacer; // check to see if we already have it here this_sp_key = makeSpacerKey(st1, st2); if(NM_Spacers.find(this_sp_key) == NM_Spacers.end()) { // new instance StringToken sp_str_token = NM_StringCheck.getToken(workingString); if(0 == sp_str_token) { sp_str_token = NM_StringCheck.addString(workingString); } curr_spacer = new SpacerInstance(sp_str_token, first_kmer_node, second_kmer_node); NM_Spacers[this_sp_key] = curr_spacer; #ifdef SEARCH_SINGLETON if (debug_iter != debugger->end()) { debug_iter->second.addSpacer(workingString); } #endif #ifdef DEBUG logInfo(""Creating spacer: ""<addEdge(second_kmer_node, CN_EDGE_FORWARD); second_kmer_node->addEdge(first_kmer_node, CN_EDGE_BACKWARD); } else { // increment the number of times we've seen this guy (NM_Spacers[this_sp_key])->incrementCount(); } *prevNode = second_kmer_node; } void NodeManager::addSecondCrisprNode(CrisprNode ** prevNode, std::string& workingString, StringToken headerSt, ReadHolder * RH) { if ((int)workingString.length() < NM_Opts->cNodeKmerLength) return; std::string second_kmer = workingString.substr(workingString.length() - NM_Opts->cNodeKmerLength, NM_Opts->cNodeKmerLength ); CrisprNode * second_kmer_node; // check to see if these kmers are already stored StringToken st2 = NM_StringCheck.getToken(second_kmer); // if they have been added previously then token != 0 if(0 == st2) { // first time we've seen this guy. Make some new objects st2 = NM_StringCheck.addString(second_kmer); second_kmer_node = new CrisprNode(st2); second_kmer_node->setForward(false); // add them to the pile NM_Nodes[st2] = second_kmer_node; } else { // we already have a node for this guy second_kmer_node = NM_Nodes[st2]; (NM_Nodes[st2])->incrementCount(); } #ifdef SEARCH_SINGLETON SearchCheckerList::iterator debug_iter = debugger->find(NM_StringCheck.getString(headerSt)); if (debug_iter != debugger->end()) { // interesting read debug_iter->second.addNode(st2); } #endif // add in the read headers for the this CrisprNode second_kmer_node->addReadHeader(headerSt); second_kmer_node->addReadHolder(RH); // add this guy in as the previous node for the next iteration *prevNode = second_kmer_node; // there is no one yet to make an edge } void NodeManager::addFirstCrisprNode(CrisprNode ** prevNode, std::string& workingString, StringToken headerSt, ReadHolder * RH) { if ((int)workingString.length() < NM_Opts->cNodeKmerLength) return; std::string first_kmer = workingString.substr(0, NM_Opts->cNodeKmerLength); CrisprNode * first_kmer_node; // check to see if these kmers are already stored StringToken st1 = NM_StringCheck.getToken(first_kmer); // if they have been added previously then token != 0 if(0 == st1) { // first time we've seen this guy. Make some new objects st1 = NM_StringCheck.addString(first_kmer); first_kmer_node = new CrisprNode(st1); // add them to the pile NM_Nodes[st1] = first_kmer_node; } else { // we already have a node for this guy first_kmer_node = NM_Nodes[st1]; (NM_Nodes[st1])->incrementCount(); } #ifdef SEARCH_SINGLETON SearchCheckerList::iterator debug_iter = debugger->find(NM_StringCheck.getString(headerSt)); if (debug_iter != debugger->end()) { // interesting read debug_iter->second.addNode(st1); } #endif // add in the read headers for the this CrisprNode first_kmer_node->addReadHeader(headerSt); first_kmer_node->addReadHolder(RH); // check to see if we already have it here if(NULL != *prevNode) { SpacerKey this_sp_key = makeSpacerKey(st1, (*prevNode)->getID()); if(NM_Spacers.find(this_sp_key) == NM_Spacers.end()) { (*prevNode)->addEdge(first_kmer_node, CN_EDGE_JUMPING_F); first_kmer_node->addEdge(*prevNode, CN_EDGE_JUMPING_B); } } } // Walking void NodeManager::findCapNodes(NodeVector * capNodes) { //----- // find cap nodes! // capNodes->clear(); NodeListIterator all_node_iter = NM_Nodes.begin(); while (all_node_iter != NM_Nodes.end()) { if((all_node_iter->second)->isAttached()) { if ((all_node_iter->second)->getTotalRank() == 1) { capNodes->push_back(all_node_iter->second); } } all_node_iter++; } } void NodeManager::findAllNodes(NodeVector * allNodes) { //----- // make a nodevector of all of the nodes! // allNodes->clear(); NodeListIterator all_node_iter = NM_Nodes.begin(); while (all_node_iter != NM_Nodes.end()) { if((all_node_iter->second)->isAttached()) { allNodes->push_back(all_node_iter->second); all_node_iter++; } } } void NodeManager::findAllNodes(NodeVector * capNodes, NodeVector * otherNodes) { //----- // make nodevectors of all of the nodes, split between cap and other // capNodes->clear(); otherNodes->clear(); NodeListIterator all_node_iter = NM_Nodes.begin(); while (all_node_iter != NM_Nodes.end()) { if((all_node_iter->second)->isAttached()) { int rank = (all_node_iter->second)->getTotalRank(); if (rank == 1) { capNodes->push_back(all_node_iter->second); } else { otherNodes->push_back(all_node_iter->second); } } all_node_iter++; } } int NodeManager::findCapsAt(NodeVector * capNodes, bool searchForward, bool isInner, bool doStrict, CrisprNode * queryNode) { //----- // Populate the passed nodevector with the capnodes at queryNode // and return the size of the vector // // if doStrict is true then the function will only return a non-zero result // when the the query node is joined ONLY to cap nodes (of the given edge type) // capNodes->clear(); if(queryNode->isAttached()) { // first, find what type of edge we are searching for. edgeListIterator el_iter; edgeList * el; if(searchForward) { if(isInner) el = queryNode->getEdges(CN_EDGE_FORWARD); else el = queryNode->getEdges(CN_EDGE_JUMPING_F); } else { if(isInner) el = queryNode->getEdges(CN_EDGE_BACKWARD); else el = queryNode->getEdges(CN_EDGE_JUMPING_B); } el_iter = el->begin(); while(el_iter != el->end()) { // make sure we only look at attached edges if(el_iter->second) { CrisprNode * attached_node = el_iter->first; if(1 == attached_node->getTotalRank()) { // this guy is a cap! capNodes->push_back(attached_node); } else { // non-cap of the same edge type if(doStrict) { capNodes->clear(); return 0; } } } el_iter++; } } return (int)capNodes->size(); } bool NodeManager::getSpacerEdgeFromCap(WalkingManager * walkElem, SpacerInstance * currentSpacer) { if (currentSpacer->getSpacerRank() == 1) { SpacerEdgeVector_Iterator iter = currentSpacer->begin(); while (iter != currentSpacer->end()) { if (((*iter)->edge)->isAttached()) { if (0 == ((*iter)->edge)->getContigID()) { walkElem->setSecondNode((*iter)->edge); walkElem->setFirstNode(currentSpacer); walkElem->setWantedEdge((*iter)->d); } else { currentSpacer->setContigID(((*iter)->edge)->getContigID()); return false; } } else { return false; } iter++; } } else { return false; } if (walkElem->first() == NULL || walkElem->second() == NULL) { return false; } else { return true; } } bool NodeManager::getSpacerEdgeFromCross(WalkingManager * walkElem, SpacerInstance * currentSpacer ) { // check that the edge is a path node if (currentSpacer->getSpacerRank() == 2) { SpacerEdgeVector_Iterator iter = currentSpacer->begin(); while (iter != currentSpacer->end()) { if (((*iter)->edge)->isAttached()) { if (0 == ((*iter)->edge)->getContigID()) { walkElem->setSecondNode((*iter)->edge); walkElem->setFirstNode(currentSpacer); walkElem->setWantedEdge((*iter)->d); return true; } } else { return false; } iter++; } } else { return false; } if (walkElem->first() == NULL || walkElem->second() == NULL) { return false; } else { return true; } } bool NodeManager::stepThroughSpacerPath(WalkingManager * walkElem, SpacerInstance ** previousNode) { switch ((walkElem->second())->getSpacerRank()) { case 2: { // path node? // check to see if the other edge is going in the same direction as wantedDirection SpacerEdgeVector_Iterator iter = (walkElem->second())->begin(); while (iter != (walkElem->second())->end()) { // make sure the edge is attached, in the right direction, not the incomming edge and not assigned to a contig already if ((*iter)->edge->isAttached() && ((*iter)->d == walkElem->getEdgeType()) && ((*iter)->edge->getID() != walkElem->first()->getID()) && ((*iter)->edge->getContigID() == 0)) { *previousNode = walkElem->shift((*iter)->edge); return true; } iter++; } break; } case 1: // default: { return false; // cross node break; } } return false; } // Cleaning int NodeManager::cleanGraph(void) { //----- // Clean all the bits off the graph mofo! // // keep going while we're detaching stuff bool some_detached = true; while(some_detached) { std::multimap fork_choice_map; NodeVector nv_cap, nv_other, detach_list; NodeVectorIterator nv_iter; some_detached = false; // get all the nodes findAllNodes(&nv_cap, &nv_other); // First do caps nv_iter = nv_cap.begin(); while(nv_iter != nv_cap.end()) { // we can just lop off caps joined by jumpers (perhaps) if ((*nv_iter)->getInnerRank() == 0) { // make sure that this guy is linked to a cross node edgeList * el; if(0 != (*nv_iter)->getRank(CN_EDGE_JUMPING_F)) el = (*nv_iter)->getEdges(CN_EDGE_JUMPING_F); else el = (*nv_iter)->getEdges(CN_EDGE_JUMPING_B); // there is only one guy in this list! int other_rank = ((el->begin())->first)->getTotalRank(); if(other_rank != 2) detach_list.push_back(*nv_iter); } else { // make sure that this guy is linked to a cross node edgeList * el; bool is_forward; if(0 != (*nv_iter)->getRank(CN_EDGE_FORWARD)) { el = (*nv_iter)->getEdges(CN_EDGE_FORWARD); is_forward = false; } else { el = (*nv_iter)->getEdges(CN_EDGE_BACKWARD); is_forward = true; } // there is only one guy in this list! CrisprNode * joining_node = ((el->begin())->first); int other_rank = joining_node->getTotalRank(); if(other_rank != 2) { // this guy joins onto a crossnode // check to see if he is the only cap here! NodeVector caps_at_join; if(findCapsAt(&caps_at_join, is_forward, true, true, joining_node) > 1) { // this is a fork at the end of an arm fork_choice_map.insert(std::pair(joining_node, *nv_iter)) ; } else { // the only cap at a cross. NUKE! detach_list.push_back(*nv_iter); } } } nv_iter++; } // make coverage decisions for end forks std::map best_coverage_map_cov; std::map best_coverage_map_node; std::multimap::iterator fcm_iter = fork_choice_map.begin(); while(fcm_iter != fork_choice_map.end()) { if(best_coverage_map_cov.find(fcm_iter->first) == best_coverage_map_cov.end()) { // first one! best_coverage_map_cov.insert(std::pair(fcm_iter->first, ((*fcm_iter).second)->getCoverage())); best_coverage_map_node.insert(std::pair(fcm_iter->first, (*fcm_iter).second)); } else { // one is already here! int new_cov = ((*fcm_iter).second)->getCoverage(); if(best_coverage_map_cov[fcm_iter->first] < new_cov) { // the new one is better! best_coverage_map_cov[fcm_iter->first] = ((*fcm_iter).second)->getCoverage(); best_coverage_map_node[fcm_iter->first] = (*fcm_iter).second; } } fcm_iter++; } fcm_iter = fork_choice_map.begin(); while(fcm_iter != fork_choice_map.end()) { if(best_coverage_map_node[fcm_iter->first] != (*fcm_iter).second) { // not the best one! detach_list.push_back((*fcm_iter).second); } fcm_iter++; } // check to see if we'll need to do this again if(detach_list.size() > 0) some_detached = true; // finally, detach! nv_iter = detach_list.begin(); while(nv_iter != detach_list.end()) { (*nv_iter)->detachNode(); nv_iter++; } // refresh the node lists findAllNodes(&nv_cap, &nv_other); // then do bubbles nv_iter = nv_other.begin(); while(nv_iter != nv_other.end()) { switch ((*nv_iter)->getTotalRank()) { case 2: { // check that there is one inner and one jumping edge if (!((*nv_iter)->getInnerRank() && (*nv_iter)->getJumpingRank())) { #ifdef DEBUG logInfo(""node ""<<(*nv_iter)->getID()<<"" has only two edges of the same type -- cannot be linear -- detaching"", 8); #endif (*nv_iter)->detachNode(); some_detached = true; } break; } case 1: case 0: break; default: { // get the rank for the the inner and jumping edges. if((*nv_iter)->getInnerRank() != 1) { // there are multiple inner edges for this guy if(clearBubbles(*nv_iter, CN_EDGE_FORWARD)) some_detached = true; } if((*nv_iter)->getJumpingRank() != 1) { // there are multiple jumping edges for this guy if(clearBubbles(*nv_iter, CN_EDGE_JUMPING_F)) some_detached = true; } break; } } nv_iter++; } } return 0; } bool NodeManager::clearBubbles(CrisprNode * rootNode, EDGE_TYPE currentEdgeType) { //----- // Return true if something got detached // bool some_detached = false; // get a list of edges edgeList * curr_edges = rootNode->getEdges(currentEdgeType); // the key is the hashed values of both the root node and the edge // the value is the node id of the edge std::map bubble_map; // now go through each of the edges and make a hashed key for the edge edgeListIterator curr_edges_iter; //= curr_edges->begin(); for (curr_edges_iter = curr_edges->begin(); curr_edges_iter != curr_edges->end(); ++curr_edges_iter) { if ( !(curr_edges_iter->first)->isAttached()) { continue; } // we want to go through all the edges of the nodes above (2nd degree separation) // and since we used the forward edges to get here we now want the opposite (Jummping_F) edgeList * edges_of_curr_edge = (curr_edges_iter->first)->getEdges(getOppositeEdgeType(currentEdgeType)); edgeListIterator edges_of_curr_edge_iter; //= edges_of_curr_edge->begin(); for (edges_of_curr_edge_iter = edges_of_curr_edge->begin(); edges_of_curr_edge_iter != edges_of_curr_edge->end(); ++edges_of_curr_edge_iter) { // make sue that this guy is attached if (! (edges_of_curr_edge_iter->first)->isAttached()) { continue; } // so now we're at the second degree of separation for our edges // again make a key but check to see if the key exists in the hash int new_key = makeKey(rootNode->getID(), (edges_of_curr_edge_iter->first)->getID()); if (bubble_map.find(new_key) == bubble_map.end()) { // first time we've seen him bubble_map[new_key] = (curr_edges_iter->first)->getID(); } else { // aha! he is pointing back onto the same guy as someone else. We have a bubble! //get the CrisprNode of the first guy CrisprNode * first_node = NM_Nodes[bubble_map[new_key]]; #ifdef DEBUG logInfo(""Bubble found conecting ""<getID()<<"" : ""<getID()<<"" : ""<<(edges_of_curr_edge_iter->first)->getID()<< "" : ""<<(curr_edges_iter->first)->getID(), 8); #endif //perform a coverage test on the nodes that end up here and kill the one with the least coverage // TODO: this is a pretty dumb test, since the coverage between the two nodes could be very similar // for example one has a coverage of 20 and the other a coverage of 18. The node with 18 will get // removed but should it have been? The way to fix this would be to create some infastructure in // NodeManager to calculate the average and stdev of the coverage and then remove a node only if // it is below 1 stdev of the average, else it could be a biological thing that this bubble exists. if (first_node->getDiscountedCoverage() > (curr_edges_iter->first)->getDiscountedCoverage()) { #ifdef DEBUG logInfo(""Node ""<getID()<<"" has higher discounted coverage (""<getDiscountedCoverage()<<"") than Node ""<<(curr_edges_iter->first)->getID()<<"" (""<<(curr_edges_iter->first)->getDiscountedCoverage()<<"")"", 8); #endif // the first guy has greater coverage so detach our current node (curr_edges_iter->first)->detachNode(); some_detached = true; #ifdef DEBUG logInfo(""Detaching ""<<(curr_edges_iter->first)->getID()<<"" as it has lower coverage"", 8); #endif } else { #ifdef DEBUG logInfo(""Node ""<getID()<<"" has lower discounted coverage (""<getDiscountedCoverage()<<"") than Node ""<<(curr_edges_iter->first)->getID()<<"" (""<<(curr_edges_iter->first)->getDiscountedCoverage()<<"")"", 8); #endif // the first guy was lower so kill him first_node->detachNode(); some_detached = true; #ifdef DEBUG logInfo(""Detaching ""<getID()<<"" as it has lower coverage"", 8); #endif // replace the existing key (to check for triple bubbles) bubble_map[new_key] = (curr_edges_iter->first)->getID(); } } } } return some_detached; } EDGE_TYPE NodeManager::getOppositeEdgeType(EDGE_TYPE currentEdgeType) { switch (currentEdgeType) { case CN_EDGE_BACKWARD: return CN_EDGE_JUMPING_B; break; case CN_EDGE_FORWARD: return CN_EDGE_JUMPING_F; break; case CN_EDGE_JUMPING_B: return CN_EDGE_BACKWARD; break; case CN_EDGE_JUMPING_F: return CN_EDGE_FORWARD; break; default: logError(""Cannot find the opposite edge type for input""); return CN_EDGE_ERROR; break; } } int NodeManager::getSpacerCountAndStats(bool showDetached, bool excludeFlankers) { int number_of_spacers = 0; SpacerListIterator sp_iter; NM_Spacers.begin(); for (sp_iter = NM_Spacers.begin(); sp_iter != NM_Spacers.end(); ++sp_iter) { SpacerInstance * current_spacer = sp_iter->second; if (showDetached || current_spacer->isAttached()) { if (excludeFlankers & current_spacer->isFlanker()) { continue; } // add in some stats for the spacers std::string spacer = NM_StringCheck.getString((sp_iter->second)->getID()); NM_SpacerLenStat.add(spacer.length()); number_of_spacers++; } } return number_of_spacers; } // Contigs void NodeManager::clearContigs(void) { //----- // Clear all contig information // ContigListIterator cl_iter = NM_Contigs.begin(); while(cl_iter != NM_Contigs.end()) { if(NULL != cl_iter->second) { SpacerVectorIterator sp_iter = (cl_iter->second)->begin(); while(sp_iter != (cl_iter->second)->end()) { (NM_Spacers[*sp_iter])->setContigID(0); sp_iter++; } delete cl_iter->second; } cl_iter++; } NM_NextContigID = 0; } void NodeManager::findAllForwardAttachedNodes(NodeVector * nodes) { //----- // make nodevectors of all of the nodes, split between cap, cross, path and other // nodes->clear(); NodeListIterator all_node_iter = NM_Nodes.begin(); while (all_node_iter != NM_Nodes.end()) { if((all_node_iter->second)->isAttached()&& (all_node_iter->second)->isForward()) { nodes->push_back(all_node_iter->second); } all_node_iter++; } } int NodeManager::buildSpacerGraph(void) { //----- // For all forward nodes, count the number of ongoing spacers // make spacer edges if told to do so // SpacerListIterator spacers_iter = NM_Spacers.begin(); while(spacers_iter != NM_Spacers.end()) { // get the last node of this spacer CrisprNode * rq_leader_node = (spacers_iter->second)->getLeader(); CrisprNode * rq_last_node = (spacers_iter->second)->getLast(); if(rq_last_node->isAttached() && rq_leader_node->isAttached()) { // mark this guy as attached (spacers_iter->second)->setAttached(true); #ifdef DEBUG SpacerInstance * debug_spacer = (spacers_iter->second); logInfo(""Spacer ""<getID()<<"" composed of nodes ""<<(debug_spacer->getLeader())->getID()<<"" ""<<(debug_spacer->getLast())->getID(), 8); #endif // now get all the jumping forward edges from this node edgeList * qel = rq_last_node->getEdges(CN_EDGE_JUMPING_F); edgeListIterator qel_iter = qel->begin(); while(qel_iter != qel->end()) { if((qel_iter->first)->isAttached() && (qel_iter->first)->isForward()) { // a forward attached node. Now check for inner edges. edgeList * el = (qel_iter->first)->getEdges(CN_EDGE_FORWARD); edgeListIterator el_iter = el->begin(); while(el_iter != el->end()) { if((el_iter->first)->isAttached()) { // bingo! SpacerInstance * next_spacer = NM_Spacers[makeSpacerKey((el_iter->first)->getID(), (qel_iter->first)->getID())]; if (next_spacer == spacers_iter->second) { //logError(""Spacer ""<second << "" with id ""<< (spacers_iter->second)->getID()<< "" has an edge to itself... aborting edge ""<second); } else { // we can add an edge for these two spacers // add the forward edge to the next spacer spacerEdgeStruct * new_edge = new spacerEdgeStruct(); new_edge->edge = next_spacer; new_edge->d = FORWARD; (spacers_iter->second)->addEdge(new_edge); // add the corresponding reverse edge to the current spacer spacerEdgeStruct * new_edge2 = new spacerEdgeStruct(); new_edge2->edge = spacers_iter->second; new_edge2->d = REVERSE; next_spacer->addEdge(new_edge2); } } el_iter++; } } qel_iter++; } } else { (spacers_iter->second)->setAttached(false); } spacers_iter++; } return 0; } void NodeManager::getAllSpacerCaps(SpacerInstanceVector * sv) { SpacerListIterator sp_iter = NM_Spacers.begin(); while (sp_iter != NM_Spacers.end()) { if((sp_iter->second)->isAttached() ) { if ((sp_iter->second)->getSpacerRank() == 1) { sv->push_back(sp_iter->second); } } sp_iter++; } } void NodeManager::findSpacerForContig(SpacerInstanceVector * sv, int contigID) { SpacerListIterator sp_iter = NM_Spacers.begin(); // first we build up the contents of the walking queue while(sp_iter != NM_Spacers.end()) { if((sp_iter->second)->isAttached() ) { if ((sp_iter->second)->getContigID() == contigID) { sv->push_back(sp_iter->second); } } sp_iter++; } } int NodeManager::cleanSpacerGraph(void) { //----- // Clean up the spacer graph // int round = 0; bool cleaned_some = true; while(cleaned_some) { round++; logInfo(""Cleaning round: "" << round, 2); cleaned_some = false; // remove fur SpacerListIterator sp_iter = NM_Spacers.begin(); while(sp_iter != NM_Spacers.end()) { if((sp_iter->second)->isAttached()) { if(sp_iter->second->isFur()) { //std::cout << ""a: "" << (sp_iter->second) <<"" round: ""<second)->printContents(); sp_iter->second->detachFromSpacerGraph(); cleaned_some = true; } } sp_iter++; } // remove non-viable nodes sp_iter = NM_Spacers.begin(); while(sp_iter != NM_Spacers.end()) { //std::cout<<""Testing Attached: ""<<(*sp_iter->second).getID()<second)->isAttached()) { if(!sp_iter->second->isViable()) { //std::cout << ""b: "" << sp_iter->second <<"" round: ""<second)->printContents(); sp_iter->second->detachFromSpacerGraph(); cleaned_some = true; } } sp_iter++; } // remove bubbles //std::cout << ""rembubs"" << std::endl; removeSpacerBubbles(); //std::cout << ""rembubs-over"" << std::endl; } return 0; } void NodeManager::removeSpacerBubbles(void) { //----- // remove bubbles from the spacer graph // std::map bubble_map; SpacerInstanceVector detach_list; SpacerListIterator sp_iter; for(sp_iter = NM_Spacers.begin(); sp_iter != NM_Spacers.end(); sp_iter++) { SpacerInstance * current_spacer = (sp_iter->second); if( !current_spacer->isAttached()) { continue; } // we only car about rank 2 or over nodes if(2 > current_spacer->getSpacerRank()) { continue; } // first make a list of the forward and backward spacers SpacerEdgeVector_Iterator edge_iter = current_spacer->begin(); SpacerInstanceVector f_spacers, r_spacers; while(edge_iter != current_spacer->end()) { if((*edge_iter)->d == REVERSE) r_spacers.push_back((*edge_iter)->edge); else f_spacers.push_back((*edge_iter)->edge); edge_iter++; } // now make a list of spacer keys SpacerInstanceVector_Iterator r_edge_iter; // = r_spacers.begin(); for(r_edge_iter = r_spacers.begin(); r_edge_iter != r_spacers.end(); r_edge_iter++) { SpacerInstance * curent_reverse_spacer = *r_edge_iter; SpacerInstanceVector_Iterator f_edge_iter; //= f_spacers.begin(); for(f_edge_iter = f_spacers.begin(); f_edge_iter != f_spacers.end(); f_edge_iter++) { SpacerInstance * curent_forward_spacer = *f_edge_iter; // make a key SpacerKey tmp_key = makeSpacerKey(curent_reverse_spacer->getID(), curent_forward_spacer->getID()); // check if we've seen this key before std::map::iterator bm_iter = bubble_map.find(tmp_key); if(bm_iter == bubble_map.end()) { // first time bubble_map[tmp_key] = sp_iter->second; } else { // bubble! -- perhaps, settle down son. We need to R-E-S-P-E-C-T directionality. if (curent_reverse_spacer->find(current_spacer) != curent_reverse_spacer->end()) { if (curent_reverse_spacer->find(bubble_map[tmp_key]) != curent_reverse_spacer->end()) { continue; } } std::cout<<""Coverage test: ""<getID()<<"" : ""<getID()<getCount() < current_spacer->getCount()) { // stored guy has lower coverage! detach_list.push_back(bubble_map[tmp_key]); bubble_map[tmp_key] = sp_iter->second; } else if(current_spacer->getCount() < bubble_map[tmp_key]->getCount()) { // new guy has lower coverage! detach_list.push_back(sp_iter->second); } else { // coverages are equal, kill the one with the lower rank if(bubble_map[tmp_key]->getSpacerRank() < current_spacer->getSpacerRank()) { // stored guy has lower coverage! detach_list.push_back(bubble_map[tmp_key]); bubble_map[tmp_key] = sp_iter->second; } else { // new guy has lower or equal coverage! detach_list.push_back(sp_iter->second); } } } } } } // detach all on the detach list! SpacerInstanceVector_Iterator dl_iter = detach_list.begin(); while(dl_iter != detach_list.end()) { (*dl_iter)->detachFromSpacerGraph(); dl_iter++; } } int NodeManager::splitIntoContigs(void) { //----- // split the group into contigs // // get all of the cap nodes SpacerInstanceVector start_walk_nodes; getAllSpacerCaps(&start_walk_nodes); SpacerInstanceList cross_nodes; WalkingManager * walk_elem = new WalkingManager(); // walk from the cap nodes to a cross node SpacerInstanceVector_Iterator cap_node_iter = start_walk_nodes.begin(); while (cap_node_iter != start_walk_nodes.end()) { SpacerInstanceVector current_contig_spacers; NM_NextContigID++; if (getSpacerEdgeFromCap(walk_elem,*cap_node_iter)) { SpacerInstance * previous_spacer = NULL; //current_contig_spacers.push_back(*cap_node_iter); do { if (NULL != previous_spacer) { current_contig_spacers.push_back(previous_spacer); } } while (stepThroughSpacerPath(walk_elem, &previous_spacer)); // if we get to this point then it means that we reached a cross node or the end of a path // the first node in the walking elem would be in the current contig current_contig_spacers.push_back(walk_elem->first()); if ((walk_elem->second())->getSpacerRank() == 1) { // end of path current_contig_spacers.push_back(walk_elem->second()); } else { // push the cross node onto a list cross_nodes.push_back(walk_elem->second()); } // assign the nodes the same contig id as the cap -- but not the cross node setContigIDForSpacers(¤t_contig_spacers); } cap_node_iter++; } NM_NextContigID++; walkFromCross(&cross_nodes); delete walk_elem; logInfo(""Made: "" << NM_NextContigID << "" spacer contig(s)"", 1); return 0; } bool NodeManager::walkFromCross(SpacerInstanceList * crossNodes) { WalkingManager * walk_elem = new WalkingManager(); SpacerInstanceList_Iterator cross_node_iter = crossNodes->begin(); while (cross_node_iter != crossNodes->end()) { (*cross_node_iter)->setContigID(NM_NextContigID++); // walk along those edges as long as possible making sure that the first edge is not a // cross node and that the nodes don't already have a contig id SpacerEdgeVector_Iterator edge_iter = (*cross_node_iter)->begin(); while (edge_iter != (*cross_node_iter)->end()) { // go through all the edges of the cross node that do not have a contig id if (((*edge_iter)->edge->isAttached()) && (0 == (*edge_iter)->edge->getContigID())) { if( getSpacerEdgeFromCross(walk_elem, (*edge_iter)->edge)) { SpacerInstanceVector current_contig_nodes; SpacerInstance * previous_node = NULL; // edge is a path node so walk do { if (NULL != previous_node) { current_contig_nodes.push_back(previous_node); } } while (stepThroughSpacerPath(walk_elem, &previous_node)); if ((walk_elem->second())->getSpacerRank() == 1 && (walk_elem->second())->isAttached()) { // end of path current_contig_nodes.push_back(walk_elem->second()); } else if ((walk_elem->second())->getContigID() == 0 && (walk_elem->second())->isAttached()) { // add the first node into the list of current contig current_contig_nodes.push_back(walk_elem->first()); // push the cross node onto a vector crossNodes->push_back(walk_elem->second()); } //current_contig_nodes.push_back(walk_elem->first()); setContigIDForSpacers(¤t_contig_nodes); NM_NextContigID++; } else { // means that the edge is a cross node so push it back on to the list crossNodes->push_back((*edge_iter)->edge); } } ++edge_iter; } cross_node_iter++; } delete walk_elem; return true; } void NodeManager::setContigIDForSpacers(SpacerInstanceVector * currentContigNodes) { SpacerInstanceVector_Iterator iter = currentContigNodes->begin(); while (iter != currentContigNodes->end()) { (*iter)->setContigID(NM_NextContigID); iter++; } } // Printing / IO void NodeManager::dumpReads(std::string readsFileName, bool showDetached) { //----- // dump reads to this file // std::set reads_set; std::ofstream reads_file; reads_file.open(readsFileName.c_str()); if (reads_file.good()) { SpacerListIterator spacer_iter = NM_Spacers.begin(); while(spacer_iter != NM_Spacers.end()) { SpacerInstance * SI = spacer_iter->second; // get the crisprnodes for these guys CrisprNode * Cleader = SI->getLeader(); CrisprNode * Clast = SI->getLast(); if(showDetached || ((SI->getLeader())->isAttached() && (SI->getLast())->isAttached())) { std::vector headers = Cleader->getReadHeaders(&NM_StringCheck); std::vector::iterator h_iter = headers.begin(); while(h_iter != headers.end()) { reads_set.insert(*h_iter); h_iter++; } headers = Clast->getReadHeaders(&NM_StringCheck); h_iter = headers.begin(); while(h_iter != headers.end()) { reads_set.insert(*h_iter); h_iter++; } } spacer_iter++; } // now we can print all the reads to file ReadListIterator read_iter = NM_ReadList.begin(); while (read_iter != NM_ReadList.end()) { std::string header = (*read_iter)->getHeader(); if(reads_set.find(header) != reads_set.end()) { reads_file <<*(*read_iter)<& allSources) { SpacerListIterator spacer_iter = NM_Spacers.begin(); while(spacer_iter != NM_Spacers.end()) { SpacerInstance * SI = spacer_iter->second; if((showDetached || ((SI->getLeader())->isAttached() && (SI->getLast())->isAttached())) && !(SI->isFlanker())) { std::set nr_tokens; getHeadersForSpacers(SI, nr_tokens); // generate the spacer tag std::string spacer = NM_StringCheck.getString(SI->getID()); std::string spid = ""SP"" + to_string(SI->getID()); std::string cov = to_string(SI->getCount()); xercesc::DOMElement * spacer_node = xmlDoc->addSpacer(spacer, spid, parentNode, cov); appendSourcesForSpacer(spacer_node, nr_tokens, xmlDoc); allSources.insert(nr_tokens.begin(), nr_tokens.end()); } spacer_iter++; } } void NodeManager::addFlankersToDOM(crispr::xml::writer * xmlDoc, xercesc::DOMElement * parentNode, bool showDetached, std::set& allSources) { SpacerInstanceVector_Iterator iter; for (iter = NM_FlankerNodes.begin(); iter != NM_FlankerNodes.end(); iter++) { SpacerInstance * SI = *iter; if(showDetached || ((SI->getLeader())->isAttached() && (SI->getLast())->isAttached())) { std::set nr_tokens; getHeadersForSpacers(SI, nr_tokens); std::string spacer = NM_StringCheck.getString(SI->getID()); std::string flid = ""FL"" + to_string(SI->getID()); xercesc::DOMElement * spacer_node = xmlDoc->addFlanker(spacer, flid, parentNode); // add in all the source tags for this spacer appendSourcesForSpacer(spacer_node, nr_tokens, xmlDoc); allSources.insert(nr_tokens.begin(), nr_tokens.end()); } } } void NodeManager::printAssemblyToDOM(crispr::xml::writer * xmlDoc, xercesc::DOMElement * parentNode, bool showDetached) { int current_contig_num = 0; while (current_contig_num < NM_NextContigID) { current_contig_num++; std::string cid = ""C"" + to_string(current_contig_num); xercesc::DOMElement * contig_elem = xmlDoc->addContig(cid, parentNode); SpacerListIterator spacer_iter = NM_Spacers.begin(); while(spacer_iter != NM_Spacers.end()) { SpacerInstance * SI = spacer_iter->second; if (SI->getContigID() == current_contig_num) { if( showDetached || SI->isAttached()) { std::string spacer = NM_StringCheck.getString(SI->getID()); std::string id = (SI->isFlanker()) ? ""FL"" + to_string(SI->getID()) : ""SP"" + to_string(SI->getID()); xercesc::DOMElement * cspacer = xmlDoc->addSpacerToContig(id, contig_elem); bool ff = false; bool bf = false; bool fs = false; bool bs = false; xercesc::DOMElement * fspacers = NULL; xercesc::DOMElement * bspacers = NULL; xercesc::DOMElement * fflankers = NULL; xercesc::DOMElement * bflankers = NULL; SpacerEdgeVector_Iterator sp_iter = SI->begin(); while (sp_iter != SI->end()) { if ((*sp_iter)->edge->isAttached()) { std::string edge_id = (SI->isFlanker()) ? ""FL"" + to_string((*sp_iter)->edge->getID()) : ""SP"" + to_string((*sp_iter)->edge->getID()); std::string drid = ""DR1""; std::string drconf = ""0""; std::string directjoin = ""0""; switch ((*sp_iter)->d) { case FORWARD: { if ((*sp_iter)->edge->isFlanker()) { if (ff) { // we've already created // add spacer xmlDoc->addFlanker(""ff"", edge_id, drconf, directjoin, fflankers);//(""fs"", edge_spid, drid, drconf, fspacers); } else { // create fflankers = xmlDoc->createFlankers(""fflankers""); xmlDoc->addFlanker(""ff"", edge_id, drconf, directjoin, fflankers);//(""fs"", edge_spid, drid, drconf, fspacers); ff = true; } } else { if (fs) { // we've already created // add spacer xmlDoc->addSpacer(""fs"", edge_id, drid, drconf, fspacers); } else { // create fspacers = xmlDoc->createSpacers(""fspacers""); xmlDoc->addSpacer(""fs"", edge_id, drid, drconf, fspacers); fs = true; } } break; } case REVERSE: { if ((*sp_iter)->edge->isFlanker()) { if (bf) { // we've already created // add spacer xmlDoc->addFlanker(""bf"", edge_id, drconf, directjoin, bflankers);//(""bs"", edge_id, drid, drconf, bspacers); } else { // create bflankers = xmlDoc->createFlankers(""bflankers""); xmlDoc->addFlanker(""bf"", edge_id, drconf, directjoin, bflankers);//(""bs"", edge_id, drid, drconf, bspacers); bf = true; } } else { if (bs) { // we've already created // add spacer xmlDoc->addSpacer(""bs"", edge_id, drid, drconf, bspacers); } else { // create bspacers = xmlDoc->createSpacers(""bspacers""); xmlDoc->addSpacer(""bs"", edge_id, drid, drconf, bspacers); bs = true; } } break; } default: { break; } } } ++sp_iter; } if (bspacers != NULL) { cspacer->appendChild(bspacers); } if (fspacers != NULL) { cspacer->appendChild(fspacers); } if (bflankers != NULL) { cspacer->appendChild(bflankers); } if (fflankers != NULL) { cspacer->appendChild(fflankers); } } } spacer_iter++; } } } void NodeManager::getHeadersForSpacers(SpacerInstance * SI, std::set& nrTokens) { // go through all the string tokens for both the leader and last nodes // for all the CrisprNodes in the Spacers CrisprNode * first_node = SI->getLeader(); CrisprNode * second_node = SI->getLast(); std::vector::iterator header_iter; for (header_iter = first_node->beginHeaders(); header_iter != first_node->endHeaders(); header_iter++) { nrTokens.insert(*header_iter); } for (header_iter = second_node->beginHeaders(); header_iter != second_node->endHeaders(); header_iter++) { nrTokens.insert(*header_iter); } } void NodeManager::appendSourcesForSpacer(xercesc::DOMElement * spacerNode, std::set& nrTokens, crispr::xml::writer * xmlDoc) { // add in all the source tags for this spacer std::set::iterator nr_iter; for (nr_iter = nrTokens.begin(); nr_iter != nrTokens.end(); nr_iter++) { std::string s = NM_StringCheck.getString(*nr_iter); std::string sid = ""SO""; sid += to_string(*nr_iter); // add the source to both the current spacer // and to the total sources list //xmlDoc->addSource(s, sid, allSources); xmlDoc->addSpacerSource(sid, spacerNode); } } void NodeManager::generateAllsourceTags(crispr::xml::writer * xmlDoc, std::set& allSourcesForNM, xercesc::DOMElement * parentNode ) { // add in all the source tags for this spacer std::set::iterator nr_iter; for (nr_iter = allSourcesForNM.begin(); nr_iter != allSourcesForNM.end(); nr_iter++) { std::string s = NM_StringCheck.getString(*nr_iter); std::string sid = ""SO""; sid += to_string(*nr_iter); xmlDoc->addSource(s, sid, parentNode); } } // Making purdy colours void NodeManager::setDebugColourLimits(void) { //----- // Make the colurs needed for printing the graphviz stuff // double max_coverage = 0; double min_coverage = 10000000; NodeListIterator nl_iter = nodeBegin(); while (nl_iter != nodeEnd()) { int coverage = (nl_iter->second)->getCoverage(); if (coverage > max_coverage) { max_coverage = coverage; } else if(coverage < min_coverage) { min_coverage = coverage; } nl_iter++; } NM_DebugRainbow.setType(NM_Opts->graphColourType); if (NM_Opts->coverageBins != -1) { NM_DebugRainbow.setLimits(min_coverage, max_coverage, NM_Opts->coverageBins); } else { NM_DebugRainbow.setLimits(min_coverage,max_coverage); } } void NodeManager::setSpacerColourLimits(void) { //----- // Make the colurs needed for printing the graphviz stuff // double max_coverage = 0; double min_coverage = 10000000; SpacerListIterator sp_iter = NM_Spacers.begin(); while (sp_iter != NM_Spacers.end()) { int coverage = (sp_iter->second)->getCount(); if (coverage > max_coverage) { max_coverage = coverage; } else if(coverage < min_coverage) { min_coverage = coverage; } sp_iter++; } NM_SpacerRainbow.setType(NM_Opts->graphColourType); if (NM_Opts->coverageBins != -1) { NM_SpacerRainbow.setLimits(min_coverage, max_coverage, NM_Opts->coverageBins); } else { NM_SpacerRainbow.setLimits(min_coverage,max_coverage); } } void NodeManager::printDebugGraph(std::ostream &dataOut, std::string title, bool showDetached, bool printBackEdges, bool longDesc) { //----- // Print a graphviz style graph of the DRs and spacers // setDebugColourLimits(); gvGraphHeader(dataOut, title); NodeListIterator nl_iter = nodeBegin(); // first loop to print out the nodes while (nl_iter != nodeEnd()) { // check whether we should print if((nl_iter->second)->isAttached() | showDetached) { printDebugNodeAttributes(dataOut, nl_iter->second ,NM_DebugRainbow.getColour((nl_iter->second)->getCoverage()), longDesc); } nl_iter++; } // and go through again to print the edges nl_iter = nodeBegin(); while (nl_iter != nodeEnd()) { // check whether we should print if((nl_iter->second)->isAttached() | showDetached) { std::stringstream ss; if(longDesc) ss << (nl_iter->second)->getID() << ""_"" << NM_StringCheck.getString((nl_iter->second)->getID()); else ss << (nl_iter->second)->getID(); (nl_iter->second)->printEdges(dataOut, &NM_StringCheck, ss.str(), showDetached, printBackEdges, longDesc); } nl_iter++; } gvGraphFooter(dataOut) } void NodeManager::printDebugNodeAttributes(std::ostream& dataOut, CrisprNode * currCrisprNode, std::string colourCode, bool longDesc) { //----- // print the node declaration // std::stringstream ss; if(longDesc) ss << currCrisprNode->getID() << ""_"" << NM_StringCheck.getString(currCrisprNode->getID()); else ss << currCrisprNode->getID(); std::string label = ss.str(); if(currCrisprNode->isForward()) { gvNodeF(dataOut,label,colourCode); } else { gvNodeB(dataOut,label,colourCode); } } bool NodeManager::printSpacerGraph(std::string& outFileName, std::string title, bool longDesc, bool showSingles) { //----- // Print a graphviz style graph of the DRs and spacers // std::stringstream tmp_out; setSpacerColourLimits(); gvGraphHeader(tmp_out, title); bool at_least_one_spacer=false; SpacerListIterator spi_iter = NM_Spacers.begin(); while (spi_iter != NM_Spacers.end()) { if ((spi_iter->second)->isAttached() && (showSingles || (0 != (spi_iter->second)->getSpacerRank()))) { at_least_one_spacer = true; // print the graphviz nodes std::string label = getSpacerGraphLabel(spi_iter->second, longDesc); // print the node attribute if ((spi_iter->second)->isFlanker()) { gvFlanker(tmp_out, label, NM_SpacerRainbow.getColour((spi_iter->second)->getCount())); } else { gvSpacer(tmp_out,label,NM_SpacerRainbow.getColour((spi_iter->second)->getCount())); } } spi_iter++; } if (!at_least_one_spacer) { return false; } std::ofstream data_out; data_out.open(outFileName.c_str()); if (data_out.good()) { data_out<second)->isAttached() && (showSingles || (0 != (spi_iter->second)->getSpacerRank()))) { // print the graphviz nodes std::string label = getSpacerGraphLabel(spi_iter->second, longDesc); // print the node attribute // now print the edges SpacerEdgeVector_Iterator edge_iter = (spi_iter->second)->begin(); while (edge_iter != (spi_iter->second)->end()) { if (((*edge_iter)->edge)->isAttached() && (*edge_iter)->d == FORWARD && (showSingles || (0 != ((*edge_iter)->edge)->getSpacerRank()))) { // get the label for our edge // print the graphviz nodes gvSpEdge(data_out, label, getSpacerGraphLabel((*edge_iter)->edge, longDesc)); } edge_iter++; } } spi_iter++; } gvGraphFooter(data_out); data_out.close(); return true; } else { logError(""Cannot open output file ""<isFlanker()) { se<< CRASS_DEF_GV_FL_PREFIX; } else { se << CRASS_DEF_GV_SPA_PREFIX; } se << spacer->getID() << ""_"" << NM_StringCheck.getString(spacer->getID()) << ""_"" << spacer->getCount(); } else { if (spacer->isFlanker()) { se<< CRASS_DEF_GV_FL_PREFIX; } else { se << CRASS_DEF_GV_SPA_PREFIX; } se << spacer->getID() << ""_"" << spacer->getCount(); } se << ""_C"" << spacer->getContigID(); return se.str(); } void NodeManager::printAllSpacers(void) { SpacerListIterator sp_iter = NM_Spacers.begin(); // first we build up the contents of the walking queue while(sp_iter != NM_Spacers.end()) { (sp_iter->second)->printContents(); sp_iter++; } } void NodeManager::printSpacerKey(std::ostream &dataOut, int numSteps, std::string groupNumber) { //----- // Print a graphviz style graph of the DRs and spacers // static int cluster_number = 0; gvKeyGroupHeader(dataOut, cluster_number, groupNumber); double ul = NM_SpacerRainbow.getUpperLimit(); double ll = NM_SpacerRainbow.getLowerLimit(); double step_size = (ul - ll) / (numSteps - 1); if(step_size < 1) { step_size = 1; } for(double i = ll; i <= ul; i+= step_size) { int this_step = int(i); std::stringstream ss; ss << this_step; gvKeyEntry(dataOut, ss.str(), NM_SpacerRainbow.getColour(this_step)); } gvKeyFooter(dataOut); cluster_number++; } // Flankers void NodeManager::generateFlankers(bool showDetached) { // generate statistics about length of spacers int spacer_count = getSpacerCountAndStats(); logInfo(""Number of spacers when testing for flankers: "" << spacer_count, 3); if (spacer_count >= 3) { // do some maths double stdev = NM_SpacerLenStat.standardDeviation(); int mean = (int)NM_SpacerLenStat.mean(); int lower_bound = mean - (stdev*1.5); int upper_bound = mean + (stdev*1.5); // if there is no variation then there is no flankers if (stdev > 1 ) { logInfo(""Ave SP Length: ""<second; if(showDetached || ((SI->getLeader())->isAttached() && (SI->getLast())->isAttached())) { /*if(SI->isCap()) {*/ int spacer_length = (int)(NM_StringCheck.getString(SI->getID())).length(); if (spacer_length > upper_bound || spacer_length < lower_bound) { SI->setFlanker(true); NM_FlankerNodes.push_back(SI); } /* }*/ } spacer_iter++; } } else { logInfo(""not enough length variation to detect flankers"", 3); } } else { logInfo(""not enough spacers to determine flankers"", 3); } // do this here so that any subsuquent calls don't include the flanking sequences clearStats(); } ","C++" "CRISPR","ctSkennerton/crass","src/crass/ReadHolder.cpp",".cpp","37720","1276","// File: ReadHolder.cpp // Original Author: Michael Imelfort 2011 // Hacked and Extended: Connor Skennerton 2011, 2012 // -------------------------------------------------------------------- // // OVERVIEW: // // Implementation of ReadHolder functions // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // system includes #include #include #include #include // local includes #include ""ReadHolder.h"" #include ""SeqUtils.h"" #include ""SmithWaterman.h"" #include ""LoggerSimp.h"" #include ""Exception.h"" // the input must be an even number which will be the start of the repeat unsigned int ReadHolder::getRepeatAt(unsigned int i) { if (i % 2 != 0) { std::stringstream ss; ss<<""Attempting to get a repeat start index from a odd numbered index in RH_StartStops: ""<printContents(ss); throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ss); } if (i > RH_StartStops.size()) { std::stringstream ss; ss<<""Index is greater than the length of the Vector: ""<printContents(ss); throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ss); } return RH_StartStops[i]; } std::string ReadHolder::repeatStringAt(unsigned int i) { if (i % 2 != 0) { std::stringstream ss; ss<<""Attempting to cut a repeat sequence from a odd numbered index in RH_StartStops: ""<printContents(ss); throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ss); } if (i > RH_StartStops.size()) { std::stringstream ss; ss<<""Index is greater than the length of the Vector: ""<printContents(ss); throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ss); } return RH_Seq.substr(RH_StartStops[i], RH_StartStops[i + 1] - RH_StartStops[i] + 1); } std::string ReadHolder::spacerStringAt(unsigned int i) { if (i % 2 != 0) { std::stringstream ss; ss<<""Attempting to cut a spacer sequence from a odd numbered index in RH_StartStops: ""<printContents(ss); throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ss); } if (i > RH_StartStops.size()) { std::stringstream ss; ss<<""Index is greater than the length of the Vector: ""<= ""<printContents(ss); throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ss); } std::string tmp_seq; unsigned int curr_spacer_start_index = 0; unsigned int curr_spacer_end_index = 0; try { curr_spacer_start_index = RH_StartStops.at(i + 1) + 1; curr_spacer_end_index = RH_StartStops.at(i + 2) - 1; tmp_seq = RH_Seq.substr(curr_spacer_start_index, (curr_spacer_end_index - curr_spacer_start_index)); } catch (std::out_of_range& e) { throw crispr::substring_exception(e.what(), RH_Seq.c_str(), curr_spacer_start_index, (curr_spacer_end_index - curr_spacer_start_index), __FILE__, __LINE__, __PRETTY_FUNCTION__); } catch (std::exception& e) { throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, e.what()); } return tmp_seq; } unsigned int ReadHolder::getAverageSpacerLength() { //----- // Used to determine if the string seaching functions are doing a good job // eats poo and dies when the read starts / ends with a spacer. So we need to watch that // unsigned int sum = 0; int stored_len = 0; unsigned int num_spacers = 0; // get the first spacer, but only include it if a DR lies before it std::string tmp_string; if(getFirstSpacer(&tmp_string)) { // check to make sure that the read doesn't start on a spacer if(*(RH_StartStops.begin()) == 0) { // starts on a DR stored_len = (int)tmp_string.length(); } // else stored_len == 0 // get all the middle spacers while(getNextSpacer(&tmp_string)) { num_spacers++; sum += stored_len; stored_len = (int)tmp_string.length(); } // check to make sure that the read doesn't end on a spacer if(RH_StartStops.back() == (RH_Seq.length() - 1)) { // ends on a DR num_spacers++; sum += stored_len; } if(0 != num_spacers) return sum/numSpacers(); } else { throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""No Spacers!""); } return 0; } void ReadHolder::getAllSpacerStrings(std::vector& spacers) { // get the first spacer, but only include it if a DR lies before it std::string tmp_string; try { if(getFirstSpacer(&tmp_string)) { // check to make sure that the read doesn't start on a spacer if(*(RH_StartStops.begin()) == 0) { // starts on a DR spacers.push_back(tmp_string); } // get all the middle spacers while(getNextSpacer(&tmp_string)) { spacers.push_back(tmp_string); } // check to make sure that the read doesn't end on a spacer if(RH_StartStops.back() != (RH_Seq.length() - 1)) { // ends on a Spacer spacers.pop_back(); } } else { throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""No Spacers!""); } } catch (crispr::exception& e) { std::cerr <& repeats) { unsigned int final_index = getStartStopListSize() - 2; for (unsigned int i = 0; i < final_index; i+=2) { repeats.push_back(repeatStringAt(i)); } } int ReadHolder::averageRepeatLength() { int sum = 0; unsigned int final_index = getStartStopListSize() - 2; for (unsigned int i = 0; i < final_index; i+=2) { sum += (int)repeatStringAt(i).length(); } return sum/numRepeats(); } void ReadHolder::startStopsAdd(unsigned int i, unsigned int j) { #ifdef DEBUG if(((int)i < 0) || ((int)j < 0)) { std::stringstream ss; ss<<""Adding negative to SS list! "" << i << "" : "" << j; throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ss); } if(i > j) { std::stringstream ss; ss <<""SS list corrupted! "" << i << "" : "" << j; throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ss); } if((i > RH_Seq.length()) || (j > RH_Seq.length())) { std::stringstream ss; ss<<""Too long! "" << i << "" : "" << j; throw crispr::exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ss); } #endif this->RH_StartStops.push_back(i); if(j >= (unsigned int)getSeqLength()) { j = (unsigned int)getSeqLength() - 1; } this->RH_StartStops.push_back(j); } void ReadHolder::dropPartials(void) { //----- // Drop any partial DRs // StartStopListIterator r_iter = RH_StartStops.begin(); if(*r_iter == 0) { logInfo(""\tDropping front partial repeat ""<<*r_iter << "" == 0"", 8); // this is a partial RH_StartStops.erase(r_iter, r_iter+2); } r_iter = RH_StartStops.end() - 1; if(*r_iter >= (unsigned int)RH_Seq.length() - 1) { logInfo(""\tDropping end partial repeat ""<<*r_iter<<""; seq_len - rep_len = ""<< (unsigned int)RH_Seq.length() - RH_RepeatLength<< ""; seq_len = ""<printContents(); std::stringstream ss; ss<<""The first direct repeat position is a negative number: "" <printContents(); } #endif tmp_ss.push_back(prev_pos_fixed); prev_pos_orig = *ss_iter; ss_iter++; } RH_StartStops.clear(); RH_StartStops.insert(RH_StartStops.begin(), tmp_ss.begin(), tmp_ss.end()); } void ReadHolder::updateStartStops(const int frontOffset, std::string * DR, const options * opts) { //----- // Update the start and stops to capture the largest part // of the DR // // Take this opportunity to look for partials at either end of the read // int DR_length = static_cast(DR->length()); StartStopListIterator ss_iter = RH_StartStops.begin(); while(ss_iter != RH_StartStops.end()) { int usable_length = DR_length - 1; // the first guy is the start of the DR if(frontOffset >= static_cast((*ss_iter))) { // this will be less than 0 int amount_below_zero = frontOffset - static_cast((*ss_iter)); usable_length = DR_length - amount_below_zero - 1; *ss_iter = 0; } else { *ss_iter -= frontOffset; } if(*ss_iter > static_cast(RH_Seq.length())) { std::stringstream ss; ss<<""Something wrong with front offset!\n"" <<""ss iter: ""<<*ss_iter << ""\n"" <<""front offset: "" << frontOffset<<""\n""; this->printContents(ss); logError(ss.str()); //throw crispr::exception(__FILE__, // __LINE__, // __PRETTY_FUNCTION__, // (ss.str()).c_str()); } // the second guy is the end of the DR ss_iter++; *ss_iter = *(ss_iter - 1) + usable_length; // correct if we have gone beyond the end of the read if(*ss_iter >= RH_Seq.length()) { *ss_iter = static_cast(RH_Seq.length()) - 1; } ss_iter++; } // now we check to see if we can find one more DRs on the front or back of this mofo // front first ss_iter = RH_StartStops.begin(); if((*ss_iter) > opts->lowSpacerSize) { // we should look for a DR here int part_s, part_e; part_s = part_e = 0; stringPair sp = smithWaterman(RH_Seq, *DR, &part_s, &part_e, 0, (static_cast((*ss_iter)) - opts->lowSpacerSize), CRASS_DEF_PARTIAL_SIM_CUT_OFF); if(0 != part_e) { if (part_e - part_s >= CRASS_DEF_MIN_PARTIAL_LENGTH) { if(((DR->rfind(sp.second) + (sp.second).length()) == DR->length()) && (0 == part_s)) { logInfo(""adding direct repeat to start"",10); logInfo(sp.first << "" : "" << sp.second << "" : "" << part_s << "" : "" << part_e,10); if(part_e < 0) { std::stringstream ss; ss<<""Adding negative to SS list! "" << part_e; logError(ss.str()); //throw crispr::exception(__FILE__, // __LINE__, // __PRETTY_FUNCTION__, // (ss.str()).c_str()); } if(part_e > (int)RH_Seq.length()) { std::stringstream ss; ss <<""SS longer than read: "" << part_e; logError(ss.str()); //throw crispr::exception(__FILE__, // __LINE__, // __PRETTY_FUNCTION__, // (ss.str()).c_str()); } std::reverse(RH_StartStops.begin(), RH_StartStops.end()); RH_StartStops.push_back(part_e); RH_StartStops.push_back(0); std::reverse(RH_StartStops.begin(), RH_StartStops.end()); } } } } // then the back unsigned int end_dist = static_cast(RH_Seq.length()) - RH_StartStops.back(); if(end_dist > (unsigned int)(opts->lowSpacerSize)) { // we should look for a DR here int part_s, part_e; part_s = part_e = 0; stringPair sp = smithWaterman(RH_Seq, *DR, &part_s, &part_e, (RH_StartStops.back() + opts->lowSpacerSize), (end_dist - opts->lowSpacerSize), CRASS_DEF_PARTIAL_SIM_CUT_OFF); if(0 != part_e) { if (part_e - part_s >= CRASS_DEF_MIN_PARTIAL_LENGTH) { if((((int)(RH_Seq.length()) - 1 ) == part_e) && (0 == DR->find(sp.second))) { logInfo(""adding partial direct repeat to end"",10); logInfo(sp.first << "" : "" << sp.second << "" : "" << part_s << "" : "" << part_e,10); logInfo((int)sp.first.length() - (int)sp.second.length(),10); // in most cases the right index is returned however // if the length of the smith waterman alignment differ the index needs to be corrected startStopsAdd(part_s + abs((int)sp.first.length() - (int)sp.second.length()), part_e); } } } } } std::string ReadHolder::DRLowLexi(void) { //----- // Orientate a READ based on low lexi of the interalised DR // std::string tmp_dr; std::string rev_comp; int num_repeats = numRepeats(); // make sure that tere is 4 elements in the array, if not you can only cut one if (num_repeats == 1) { tmp_dr = repeatStringAt(0); rev_comp = reverseComplement(tmp_dr); } else if (2 == num_repeats) { // choose the dr that is not a partial ( no start at 0 or end at length) // take the second if (RH_StartStops.front() == 0) { tmp_dr = repeatStringAt(2); rev_comp = reverseComplement(tmp_dr); } // take the first else if (RH_StartStops.back() == static_cast(RH_Seq.length())) { tmp_dr = repeatStringAt(0); rev_comp = reverseComplement(tmp_dr); } // if they both are then just take whichever is longer else { int lenA = RH_StartStops.at(1) - RH_StartStops.at(0); int lenB = RH_StartStops.at(3) - RH_StartStops.at(2); if (lenA > lenB) { tmp_dr = repeatStringAt(0); rev_comp = reverseComplement(tmp_dr); } else { tmp_dr = repeatStringAt(2); rev_comp = reverseComplement(tmp_dr); } } } // long read more than two repeats else { // take the second tmp_dr = repeatStringAt(2); rev_comp = reverseComplement(tmp_dr); } if (tmp_dr < rev_comp) { // the direct repeat is in it lowest lexicographical form RH_WasLowLexi = true; #ifdef DEBUG logInfo(""DR in low lexi""<RH_isSqueezed) { return; } else { std::stringstream rle, seq; rle<RH_Seq[0]; seq<RH_Seq[0]; //std::cout<<""seq length: ""<(this->RH_Seq.length()); for (int i = 1; i < length; i++) { if (this->RH_Seq[i] == this->RH_Seq[i - 1]) { int count = 0; do { count++; i++; } while ((i < length) && (this->RH_Seq[i] == this->RH_Seq[i - 1])); if(i < length) { rle << count << this->RH_Seq[i]; seq<RH_Seq[i]; //std::cout<<""b-index: ""<RH_Seq[i]<RH_Seq[i]; seq << this->RH_Seq[i]; //std::cout<<""e-index: ""<RH_Seq[i]<RH_Seq = seq.str(); this->RH_Rle = rle.str(); this->RH_isSqueezed = true; } } void ReadHolder::decode(void) { //----- // Go from RLE to normal // Call it anytime. Fixes start stops // std::string tmp = this->expand(true); this->RH_isSqueezed = false; this->RH_Seq = tmp; } std::string ReadHolder::expand(void) { //---- // Expand the string from RLE but don't fix stop starts. // return expand(false); } std::string ReadHolder::expand(bool fixStopStarts) { //---- // Expand the string from RLE and fix stope starts as needed // if (!this->RH_isSqueezed) { return this->RH_Seq; } else { std::stringstream tmp; int main_index = 0; int new_index = 0; int old_index = 0; int stop_index = static_cast(RH_Rle.length()); int next_ss_index = -1; StartStopListIterator ss_iter = RH_StartStops.begin(); // no point in fixing starts and stops if there are none if(RH_StartStops.size() == 0) { fixStopStarts = false; } if(fixStopStarts) { next_ss_index = *ss_iter; } while (main_index < stop_index) { if (isdigit(RH_Rle[main_index])) { int count = RH_Rle[main_index] - '0'; new_index += count; while (count != 0) { tmp << RH_Rle[main_index -1]; count--; } } else { if(next_ss_index == old_index) { *ss_iter = new_index; ss_iter++; if(ss_iter != RH_StartStops.end()) { next_ss_index = *ss_iter; } else { next_ss_index = -1; } } tmp << RH_Rle[main_index]; old_index++; new_index++; } main_index++; } return tmp.str(); } } // cut DRs and Specers bool ReadHolder::getFirstDR(std::string * retStr) { //----- // cut the first DR or return false if it all stuffs up // RH_LastDREnd = 0; return getNextDR(retStr); } bool ReadHolder::getNextDR(std::string * retStr) { //----- // cut the next DR or return false if it all stuffs up // // make the iterator point to the start of the next DR StartStopListIterator ss_iter = RH_StartStops.begin() + RH_LastDREnd; // find out where to start and stop the cuts int start_cut = -1; int end_cut = -1; if(ss_iter < RH_StartStops.end()) { start_cut = *ss_iter; } else return false; ss_iter++; if(ss_iter < RH_StartStops.end()) { end_cut = *ss_iter; } else { return false; } // check to see if we made any good of start and end cut int dist = end_cut - start_cut; if(0 != dist) { *retStr = RH_Seq.substr(start_cut, dist + 1); RH_LastDREnd+=2; return true; } else { return false; } } bool ReadHolder::getFirstSpacer(std::string * retStr) { //----- // cut the first Spacer or return false if it all stuffs up // RH_NextSpacerStart = 0; try { return getNextSpacer(retStr); } catch (crispr::substring_exception& e) { std::cerr< ((int)(RH_StartStops.size()) - 1)) { //std::stringstream ss; //ss << ""Next spacer start is greater than length ""< ""< (RH_Seq.length() - 1)) { std::stringstream error_stream; this->printContents(error_stream); error_stream <<""ss list out of range; ""<<*ss_iter<< "" > ""<'< 0) { s<<' '< 0) { s<. */ #ifndef STATTOOL_H #define STATTOOL_H #include #include #include #include ""base.h"" #include ""StlExt.h"" #define SPACER_CHAR '+' #define FLANKER_CHAR '~' #define REPEAT_CHAR '-' typedef struct __AStats { int total_groups; int total_spacers; int total_dr; int total_flanker; int total_spacer_length; int total_spacer_cov; int total_dr_length; int total_flanker_length; int total_reads; } AStats; class StatManager { std::vector SM_SpacerLength; std::vector SM_SpacerCoverage; std::vector SM_RepeatLength; std::vector SM_FlankerLength; int SM_SpacerCount; int SM_RepeatCount; int SM_FlankerCount; int SM_ReadCount; std::string SM_ConsensusRepeat; std::string SM_Gid; public: StatManager() { SM_FlankerCount = 0; SM_RepeatCount = 0; SM_SpacerCount = 0; SM_ReadCount = 0; } inline std::string getConcensus(void){return SM_ConsensusRepeat;} inline std::string getGid(void){return SM_Gid;} inline int getSpacerCount(void) {return SM_SpacerCount;} inline int getRpeatCount(void) {return SM_RepeatCount;} inline int getFlankerCount(void) {return SM_FlankerCount;} inline int getReadCount(void) {return SM_ReadCount;} inline void incrementSpacerCount(void) {++SM_SpacerCount;} inline void incrementRpeatCount(void) {++SM_RepeatCount;} inline void incrementFlankerCount(void) {++SM_FlankerCount;} inline std::vector getSpLenVec(void){return SM_SpacerLength;} inline std::vector getSpCovVec(void){return SM_SpacerCoverage;} inline std::vector getRepLenVec(void){return SM_RepeatLength;} inline std::vector getFlLenVec(void){return SM_FlankerLength;} inline void setConcensus(std::string s){ SM_ConsensusRepeat = s;} inline void setGid(std::string g){ SM_Gid = g;} inline void setSpacerCount(int i) { SM_SpacerCount = i;} inline void setRepeatCount(int i) { SM_RepeatCount = i;} inline void setFlankerCount(int i) { SM_FlankerCount = i;} inline void setReadCount(int i) {SM_ReadCount = i;} // mode inline int modeSpacerL(void){return mode(SM_SpacerLength);} inline int modeSpacerC(void){return mode(SM_SpacerCoverage);} inline int modeRepeatL(void){return mode(SM_RepeatLength);} inline int modeFlankerL(void){return mode(SM_FlankerLength);} // median; inline int medianSpacerL(void){return median(SM_SpacerLength);} inline int medianSpacerC(void){return median(SM_SpacerCoverage);} inline int medianRepeatL(void){return median(SM_RepeatLength);} inline int medianFlankerL(void){return median(SM_FlankerLength);} // mean inline int meanSpacerL(void) {return mean(SM_SpacerLength);} inline int meanSpacerC(void) {return mean(SM_SpacerCoverage);} inline int meanRepeatL(void) {return mean(SM_RepeatLength);} inline int meanFlankerL(void) {return mean(SM_FlankerLength);} inline void addSpLenVec(int i ){return SM_SpacerLength.push_back(i);} inline void addSpCovVec(int i ){return SM_SpacerCoverage.push_back(i);} inline void addRepLenVec(int i ){return SM_RepeatLength.push_back(i);} inline void addFlLenVec(int i ){return SM_FlankerLength.push_back(i);} }; class StatTool { enum OUTPUT_STYLE {tabular, pretty, veryPretty, coverage}; std::set ST_Groups; std::vector ST_StatsVec; //bool ST_Pretty; bool ST_AssemblyStats; bool ST_Subset; std::string ST_OutputFileName; bool ST_WithHeader; bool ST_AggregateStats; bool ST_DetailedCoverage; //bool ST_Tabular; std::string ST_Separator; OUTPUT_STYLE ST_OutputStyle; public: StatTool() { //ST_Pretty = false; ST_Subset = false; ST_AssemblyStats = false; ST_WithHeader = false; ST_AggregateStats = false; ST_DetailedCoverage = false; //ST_Tabular = true; ST_Separator = ""\t""; ST_OutputStyle = tabular; } ~StatTool(); //void generateGroupsFromString(std::string str); int processOptions(int argc, char ** argv); int processInputFile(const char * inputFile); void parseGroup(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser); void parseData(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager); void parseDrs(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager); void parseSpacers(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager); void parseFlankers(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager); void parseMetadata(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser, StatManager * statManager); int calculateReads(const char * fileName); // void parseAssembly(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser); // void parseContig(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser); // void parseCSpacer(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser); // void parseLinkSpacers(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser); // void parseLinkFlankers(xercesc::DOMElement * parentNode, crispr::xml::base& xmlParser); void calculateAgregateSTats(AStats * agregateStats); void prettyPrint(StatManager * sm); void veryPrettyPrint(StatManager * sm, int longestConsensus, int longestGID); void printHeader(void); void printTabular(StatManager * sm); void printCoverage(StatManager * sm); void printAggregate(AStats * agregateStats); std::vector::iterator begin(){return ST_StatsVec.begin();} std::vector::iterator end(){return ST_StatsVec.end();} }; int statMain(int argc, char ** argv); void statUsage(void); #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/PatternMatcher.h",".h","1552","47","/* * PatternMatcher.h is part of the CRisprASSembler project * Levensthein code was downloaded from http://www.merriampark.com/ldcpp.htm * Copyright (c) Merriam Park Software 2009 * * Boyer-Moore code was downloaded from http://dev-faqs.blogspot.com/2010/05/boyer-moore-algorithm.html * Copyright (c) 2010 dev-faqs.blogspot.com * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef _BM_H_ #define _BM_H_ #include #include #include typedef std::vector< std::vector > Tmatrix; class PatternMatcher{ public: static int bmpSearch(const std::string& text, const std::string& pattern); static void bmpMultiSearch(const std::string &text, const std::string &pattern, std::vector &startOffsetVec); static int levenstheinDistance( std::string& source, std::string& target); static float getStringSimilarity(std::string& s1, std::string& s2); private: static std::vector computeBmpLast(const std::string& pattern); PatternMatcher(); PatternMatcher(const PatternMatcher&); const PatternMatcher& operator=(const PatternMatcher&); }; #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/MergeTool.h",".h","1830","56","/* * MergeTool.h * * Copyright (C) 2011 - Connor Skennerton * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #ifndef MERGETOOL_H #define MERGETOOL_H #include #include class MergeTool { std::set MT_GroupIds; bool MT_Sanitise; int MT_NextGroupID; std::string MT_OutFile; public: MergeTool(void){ MT_OutFile = ""crisprtools_merged.crispr""; MT_NextGroupID = 1; MT_Sanitise = false; } ~MergeTool(){} inline bool getSanitise(void){return MT_Sanitise;}; inline int getNextGroupID(void){return MT_NextGroupID;}; inline void incrementGroupID(void){MT_NextGroupID++;}; inline std::string getFileName(void){return MT_OutFile;}; int processInputFile(const char * inputFile); int processOptions(int argc, char ** argv); inline std::set::iterator find(std::string s) {return MT_GroupIds.find(s);}; inline std::set::iterator begin(){return MT_GroupIds.begin();}; inline std::set::iterator end(){return MT_GroupIds.end();}; inline void insert(std::string s){MT_GroupIds.insert(s);}; }; int mergeMain(int argc, char ** argv); void mergeUsage(void); #endif","Unknown" "CRISPR","ctSkennerton/crass","src/crass/SpacerInstance.cpp",".cpp","5976","240","// File: SpacerInstance.cpp // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // Implementation of SpacerInstance functions // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // system includes #include #include #include ""Exception.h"" // local includes #include ""SpacerInstance.h"" #include ""CrisprNode.h"" #include ""StringCheck.h"" #include ""LoggerSimp.h"" SpacerInstance::SpacerInstance(StringToken spacerID) { //----- // constructor // SI_SpacerSeqID = spacerID; SI_LeadingNode = NULL; SI_LastNode = NULL; SI_InstanceCount = 0; SI_ContigID = 0; SI_Attached = false; SI_isFlanker = false; } SpacerInstance::SpacerInstance(StringToken spacerID, CrisprNode * leadingNode, CrisprNode * lastNode) { SI_SpacerSeqID = spacerID; SI_LeadingNode = leadingNode; SI_LastNode = lastNode; SI_InstanceCount = 1; SI_ContigID = 0; SI_Attached = false; SI_isFlanker = false; } void SpacerInstance::clearEdge(void) { //----- // Clear all edges // SpacerEdgeVector_Iterator iter = SI_SpacerEdges.begin(); while (iter != SI_SpacerEdges.end()) { if (*iter != NULL) { delete *iter; *iter = NULL; } iter++; } } bool SpacerInstance::isFur(void) { //----- // Check to see if the spacer is a cap joined onto a non-cap // SpacerEdgeVector_Iterator edge_iter = SI_SpacerEdges.begin(); // zero rank spacers are viable by default if(1 != getSpacerRank()) return false; while(edge_iter != SI_SpacerEdges.end()) { if((*edge_iter)->edge->getSpacerRank() > 2) { return true; } edge_iter++; } return false; } bool SpacerInstance::isViable(void) { //----- // Check to see if the spacer has forward AND reverse edges // return true or false accordingly // SpacerEdgeVector_Iterator edge_iter = SI_SpacerEdges.begin(); // zero rank spacers are viable by default if(getSpacerRank() < 2) { return true; } bool has_forward = false; bool has_reverse = false; while(edge_iter != SI_SpacerEdges.end()) { if((*edge_iter)->d == REVERSE) has_reverse = true; else has_forward = true; if(has_reverse && has_forward) return true; edge_iter++; } return false; } SpacerEdgeVector_Iterator SpacerInstance::find(SpacerInstance * si) { // check to see if the spacer instance in in the edges SpacerEdgeVector_Iterator iter; for (iter = SI_SpacerEdges.begin(); iter != SI_SpacerEdges.end(); ++iter) { if ((*iter)->edge == si) { return iter; } } return SI_SpacerEdges.end(); } void SpacerInstance::detachFromSpacerGraph(void) { //----- // remove this spacer from the graph // if(0 == getSpacerRank()) return; SpacerEdgeVector_Iterator edge_iter = SI_SpacerEdges.begin(); while(edge_iter != SI_SpacerEdges.end()) { // delete the return edge //std::cout << ""c: "" << this << "" : "" << (*edge_iter)->edge << std::endl; if(!(*edge_iter)->edge->detachSpecificSpacer(this)) { return; } // free the memory! if (*edge_iter != NULL) { delete *edge_iter; *edge_iter = NULL; } edge_iter++; } // no edges left here SI_SpacerEdges.clear(); } bool SpacerInstance::detachSpecificSpacer(SpacerInstance * target) { //----- // remove this spacer from the graph // if(0 == getSpacerRank()) { logError(""Trying to remove edge from zero rank spacer""); return false; } SpacerEdgeVector_Iterator edge_iter = SI_SpacerEdges.begin(); while(edge_iter != SI_SpacerEdges.end()) { // we need to find the target edge if((*edge_iter)->edge == target) { //std::cout << ""rev: "" << target << "" : "" << this << std::endl; // free the memory if (*edge_iter != NULL) { delete *edge_iter; *edge_iter = NULL; } // remove from the vector SI_SpacerEdges.erase(edge_iter); return true; } edge_iter++; } logError(""Could not find target: "" << target); return false; } void SpacerInstance::printContents(void) { //----- // print the contents of all the contents // std::cout << ""-------------------------------\n"" << this << std::endl; std::cout << ""ST: "" << SI_SpacerSeqID << "" LEADER: "" << SI_LeadingNode->getID() << "" LAST: "" << SI_LastNode->getID() << std::endl; std::cout << ""IC: "" << SI_InstanceCount << "" ATT? "" << SI_Attached << "" CID: "" << SI_ContigID << std::endl; SpacerEdgeVector_Iterator edge_iter = SI_SpacerEdges.begin(); while(edge_iter != SI_SpacerEdges.end()) { std::cout << "" --> "" << (*edge_iter)->edge << "" : "" << (*edge_iter)->d << std::endl; edge_iter++; } } ","C++" "CRISPR","ctSkennerton/crass","src/crass/reader.h",".h","1927","63","/* * crass.h is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef READER_H #define READER_H #include ""base.h"" namespace crispr { namespace xml { class reader : virtual public base { public: // default constructor reader(); ~reader(); // the reader should have virtual functions for overloading // Parsing functions xercesc::DOMDocument * setFileParser(const char * xmlFile); private: xercesc::XercesDOMParser * XR_FileParser; // parsing object }; } } #endif","Unknown" "CRISPR","ctSkennerton/crass","src/crass/kseq.h",".h","1961","76","/* The MIT License Copyright (c) 2008 Genome Research Ltd (GRL). Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the ""Software""), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ /* Contact: Heng Li */ /* Last Modified: 12APR2009 */ /* De-macro'd by the ACE-team 18MAY2012 wattup! */ #ifndef AC_KSEQ_H #define AC_KSEQ_H #include #include #include #include typedef struct //__kstream_t { char *buf; int begin, end, is_eof; gzFile f; } kstream_t; typedef struct //__kstring_t { size_t l, m; char *s; } kstring_t; typedef struct { kstring_t name, comment, seq, qual; int last_char; kstream_t *f; } kseq_t; kstream_t *ks_init(gzFile f); void ks_destroy(kstream_t *ks); int ks_getc(kstream_t *ks); int ks_getuntil(kstream_t *ks, int delimiter, kstring_t *str, int *dret); kseq_t *kseq_init(gzFile fd); void kseq_rewind(kseq_t *ks); void kseq_destroy(kseq_t *ks); int kseq_read(kseq_t *seq); #endif","Unknown" "CRISPR","ctSkennerton/crass","src/crass/FilterTool.h",".h","2611","63","/* * FilterTool.h * * Copyright (C) 2011, 2012 - Connor Skennerton * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include ""reader.h"" #include #include #include class FilterTool { int FT_Spacers; int FT_Repeats; int FT_Flank; int FT_contigs; int FT_Coverage; std::string FT_OutputFile; int countElements(xercesc::DOMElement * parentNode); public: FilterTool() { FT_Spacers = 0; FT_Repeats = 0; FT_Flank = 0; FT_contigs = 0; FT_Coverage = 0; } int processOptions(int argc, char ** argv); int processInputFile(const char * inputFile); bool parseGroup(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser); bool parseData(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::set& spacersToRemove); inline int parseDrs(xercesc::DOMElement * parentNode){return countElements(parentNode);} int parseSpacers(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::set& spacersToRemove); inline int parseFlankers(xercesc::DOMElement * parentNode){return countElements(parentNode);} void parseAssembly(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::set& spacersToRemove); void parseContig(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::string& contigId, std::set& spacersToRemove); void parseCSpacer(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::string& contigId, std::set& spacersToRemove); void parseLinkSpacers(xercesc::DOMElement * parentNode, crispr::xml::reader& xmlParser, std::string& contigId, std::set& spacersToRemove); }; int filterMain(int argc, char ** argv); void filterUsage(void);","Unknown" "CRISPR","ctSkennerton/crass","src/crass/ksw.h",".h","2681","72","#ifndef __AC_KSW_H #define __AC_KSW_H #include #define KSW_XBYTE 0x10000 #define KSW_XSTOP 0x20000 #define KSW_XSUBO 0x40000 #define KSW_XSTART 0x80000 struct _kswq_t; typedef struct _kswq_t kswq_t; typedef struct { int score; // best score int te, qe; // target end and query end int score2, te2; // second best score and ending position on the target int tb, qb; // target start and query start } kswr_t; #ifdef __cplusplus extern ""C"" { #endif /** * Aligning two sequences * * @param qlen length of the query sequence (typically * * crisprtools is free software: you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * crisprtools is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program. If not, see . */ #include #include #include #include ""config.h"" #include ""Utils.h"" #include ""MergeTool.h"" #include ""SplitTool.h"" #include ""ExtractTool.h"" #include ""FilterTool.h"" #include ""SanitiseTool.h"" #if RENDERING && HAVE_LIBCDT && HAVE_LIBGRAPH && HAVE_LIBGVC #include ""DrawTool.h"" #endif #include ""StatTool.h"" #include ""RemoveTool.h"" void usage (void) { std::cout< -h for help on each utility""< [options]""<. * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef crisprtools_RemoveTool_h #define crisprtools_RemoveTool_h #include #include #include ""writer.h"" int removeMain(int argc, char ** argv); void removeUsage(void); int processRemoveOptions(int argc, char ** argv, std::set& groups, std::string& outputFile, bool& remove ); void removeAssociatedData(xercesc::DOMElement * groupElement, crispr::xml::writer& xmlParser); void parseMetadata(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser); #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/AssemblyWrapper.cpp",".cpp","29489","753","/* * AssemblyWrapper.cpp is part of the crass project * * Created by Connor Skennerton on 27/10/11. * Copyright 2011, 2012 Connor Skennerton and Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ // System Includes #include #include #include #include #include #include #include #include #include #include #include #include // Local Includes #include ""AssemblyWrapper.h"" #include ""config.h"" #include ""crassDefines.h"" #include ""StlExt.h"" #include ""kseq.h"" #include ""SeqUtils.h"" void CrisprParser::parseXMLFile(std::string XMLFile, std::string& wantedGroup, std::string& directRepeat, std::set& wantedContigs, std::set& wantedReads ) { try { // no need to free this pointer - owned by the parent parser object xercesc::DOMDocument * xmlDoc = setFileParser(XMLFile.c_str()); //xercesc::DOMDocument * xmlDoc = XR_FileParser->getDocument(); // Get the top-level element: xercesc::DOMElement * elementRoot = xmlDoc->getDocumentElement(); if( !elementRoot ) throw crispr::xml_exception( __FILE__, __LINE__, __PRETTY_FUNCTION__, ""empty XML document"" ); // find our wanted group xercesc::DOMElement * wanted_group_element = getWantedGroupFromRoot(elementRoot, wantedGroup, directRepeat); if (!wanted_group_element) { throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""Could not find the input group."" ); } // get the sources // they should be the first child element of the data XMLIDMap all_sources; xercesc::DOMElement * sources_elem = wanted_group_element->getFirstElementChild()->getFirstElementChild(); getSourcesForGroup(all_sources, sources_elem); // a map of spacers to their corresponding list of sources Spacer2SourceMap spacer_2_sources; // the spacers come after the DRs mapSacersToSourceID(spacer_2_sources, (sources_elem->getNextElementSibling())->getNextElementSibling()); // get the assembly node xercesc::DOMElement * assembly_element = parseGroupForAssembly(wanted_group_element); if (assembly_element == NULL) { throw crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""no assembly tag for group."" ); } // get the contigs and spacers parseAssemblyForContigIds(assembly_element, wantedReads, spacer_2_sources, all_sources, wantedContigs); } catch( xercesc::XMLException& e ) { char* message = xercesc::XMLString::transcode( e.getMessage() ); std::ostringstream errBuf; errBuf << ""Error parsing file: "" << message << std::flush; xercesc::XMLString::release( &message ); } } xercesc::DOMElement * CrisprParser::getWantedGroupFromRoot(xercesc::DOMElement * parentNode, std::string& wantedGroup, std::string& directRepeat) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), tag_Group())) { // new group // test if it's one that we want char * c_group_name = tc(currentElement->getAttribute(attr_Gid())); std::string current_group_name = c_group_name; xr(&c_group_name); if (current_group_name == wantedGroup) { // get the length of the direct repeat char * c_dr = tc(currentElement->getAttribute(attr_Drseq())); directRepeat = c_dr; return currentElement; } } } // we should theoretically never get here but if the xml is bad then it might just happen // or if the user has put in a group that doesn't exist by mistake return NULL; } xercesc::DOMElement * CrisprParser::parseGroupForAssembly(xercesc::DOMElement* parentNode) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if( xercesc::XMLString::equals(currentElement->getTagName(), tag_Assembly())) { // assembly section // the child nodes will be the contigs return currentElement; } } // if there is no assembly for this group return NULL; } void CrisprParser::parseAssemblyForContigIds(xercesc::DOMElement* parentNode, std::set& wantedReads, Spacer2SourceMap& spacersForAssembly, XMLIDMap& source2acc, std::set& wantedContigs) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if( xercesc::XMLString::equals(currentElement->getTagName(), tag_Contig())) { // check to see if the current contig is one that we want char * c_current_contig = tc(currentElement->getAttribute(attr_Cid())); std::string current_contig = c_current_contig; std::set::iterator contig_iter = wantedContigs.find(current_contig); if( contig_iter != wantedContigs.end()) { // get the spacers from the assembly getSourceIdForAssembly(currentElement, wantedReads, spacersForAssembly, source2acc); } xr(&c_current_contig); } } } void CrisprParser::getSourceIdForAssembly(xercesc::DOMElement* parentNode, std::set& wantedReads, Spacer2SourceMap& spacersForAssembly, XMLIDMap& source2acc) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if( xercesc::XMLString::equals(currentElement->getTagName(), tag_Cspacer())) { char * spid = tc(currentElement->getAttribute(attr_Spid())); if (spacersForAssembly.find(spid) != spacersForAssembly.end()) { IDVector::iterator iter; for(iter = spacersForAssembly[spid].begin(); iter != spacersForAssembly[spid].end(); iter++) { wantedReads.insert(source2acc[*iter]); } } } } } void assemblyVersionInfo(void) { std::cout< Output a log file and set a log level [1 - ""< ID of the group that you want to assemble. Give only the group number; For example""< A comma separated list of numbered segments to assemble from the specified group""< xml output file created by crass. should be called crass.crispr in the crass output directory""< input directory for the assembly. This will be the output directory from Crass [default: .]""< size of the insert for paired end assembly""< name of the directory for the assembly output files""<(opts.group, optarg, std::dec); break; } case 'h': { assemblyUsage(); exit(0); break; } case 'i': { // Test to see if the file is ok. struct stat inputDirStatus; int iStat = stat(optarg, &inputDirStatus); // stat failed switch (iStat) { case -1: { switch (errno) { case ENOENT: { throw ( std::runtime_error(""Input directory path does not exist, or path is an empty string."") ); break; } case ELOOP: { throw ( std::runtime_error(""Too many symbolic links encountered while traversing the input directory path."")); break; } case EACCES: { throw ( std::runtime_error(""You do not have permission to access the input directory."")); break; } case ENOTDIR: { throw ( std::runtime_error(""Input is not a directory\n"")); break; } default: { throw (std::runtime_error(""An error occured when reading the input directory"")); break; } } break; } default: { opts.inputDirName = optarg; break; } } break; } case 'I': { from_string(opts.insertSize, optarg, std::dec); break; } case 'l': { from_string(opts.logLevel, optarg, std::dec); if(opts.logLevel > CRASS_DEF_MAX_LOGGING) { std::cerr<& segments) { // split the segment id string into the individual pieces std::vector tmp; tokenize(segmentString, tmp, "",""); std::vector::iterator tmp_iter = tmp.begin(); while (tmp_iter != tmp.end()) { // prepend on a 'C' cause that is the format of the xml file segments.insert(""C"" + *tmp_iter); tmp_iter++; } } void generateTmpAssemblyFile(std::string fileName, std::set& wantedContigs, assemblyOptions& opts, std::string& tmpFileName) { gzFile fp = getFileHandle((opts.inputDirName + fileName).c_str()); kseq_t *seq; int l; // initialize an output file handle std::ofstream out_file; out_file.open((opts.inputDirName + tmpFileName).c_str()); if (out_file.good()) { // initialize seq seq = kseq_init(fp); // read sequence while ( (l = kseq_read(seq)) >= 0 ) { if (wantedContigs.find(seq->name.s) != wantedContigs.end()) { // this read comes from a segment that we want // check to see if it is fasta or fastq if (seq->qual.s) { // it's fastq out_file<<'@'<name.s<seq.s<comment.s) { out_file<comment.s; } out_file<qual.s<'<name.s; if (seq->comment.s) { out_file<<' '<comment.s; } out_file<seq.s< "" + opts.outputDirName + '/' + tmpFileName + "".crass.cap3""; std::cout << cap3cmd << std::endl; int cap_exit = system(cap3cmd.c_str()); if (cap_exit) { throw (std::runtime_error(""cap3 did not exit normally"")); } } catch (crispr::exception& e) { std::cerr< segments; parseSegmentString(opts.segments, segments); std::set spacers_for_assembly; //parse xml file CrisprParser xml_parser; std::string direct_repeat; std::string group_as_string = ""G"" + to_string(opts.group); try { xml_parser.parseXMLFile(opts.xmlFileName, group_as_string, direct_repeat, segments, spacers_for_assembly ); } catch (crispr::xml_exception& e) { std::cerr<. * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #ifndef crass_Types_h #define crass_Types_h #include #include #include #include ""ReadHolder.h"" #include ""StringCheck.h"" // forward declaration of readholder class //class ReadHolder; // Types cut from libcrispr.h typedef std::map lookupTable; typedef std::vector ReadList; typedef std::vector::iterator ReadListIterator; // direct repeat as a string and a list of the read objects that contain that direct repeat typedef std::map ReadMap; typedef std::map::iterator ReadMapIterator; // Types from WorkHorse.h // for storing clusters of DRs // indexed using StringCheck type tokens typedef std::vector DR_Cluster; typedef std::vector::iterator DR_ClusterIterator; typedef std::map::iterator DR_Cluster_MapIterator; typedef std::map DR_Cluster_Map; typedef std::map * > GroupKmerMap; typedef std::vector Vecstr; #endif ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/RemoveTool.cpp",".cpp","8455","232","/* * RemoveTool.cpp is part of the crisprtools project * * Created by Connor Skennerton on 22/12/11. * Copyright 2011 Connor Skennerton. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include #include #include #include ""RemoveTool.h"" #include ""Exception.h"" #include ""StlExt.h"" #include ""parser.h"" #include ""config.h"" #include ""Utils.h"" int removeMain(int argc, char ** argv) { try { std::set groups; std::string output_file; bool remove_files = false; int opt_index = processRemoveOptions(argc, argv, groups, output_file, remove_files); if(argc <= opt_index) { throw crispr::input_exception(""Please specify an input file""); } crispr::xml::parser xml_obj; xercesc::DOMDocument * xml_doc = xml_obj.setFileParser(argv[opt_index]); xercesc::DOMElement * root_elem = xml_doc->getDocumentElement(); if( !root_elem ) throw(crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, ""empty XML document"" )); // get the children std::vector bad_children; for (xercesc::DOMElement * currentElement = root_elem->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xml_obj.tag_Group())) { // new group char * c_group_id = tc(currentElement->getAttribute(xml_obj.attr_Gid())); std::string group_id = c_group_id; if (groups.find(group_id.substr(1)) != groups.end() ) { bad_children.push_back(currentElement); if (remove_files) { removeAssociatedData(currentElement, xml_obj); } } xr(&c_group_id); } } std::vector::iterator iter = bad_children.begin(); while (iter != bad_children.end()) { root_elem->removeChild(*iter); iter++; } if (output_file.empty()) { xml_obj.printDOMToFile(argv[opt_index],xml_doc); } else { xml_obj.printDOMToFile(output_file); } } catch( xercesc::XMLException& e ) { char * message = xercesc::XMLString::transcode( e.getMessage() ); std::ostringstream errBuf; errBuf << ""Error parsing file: "" << message << std::flush; throw (crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, (errBuf.str()).c_str())); xercesc::XMLString::release( &message ); } catch (xercesc::DOMException& e) { char * message = xercesc::XMLString::transcode( e.getMessage() ); std::ostringstream errBuf; errBuf << ""Error parsing file: "" << message << std::flush; throw (crispr::xml_exception(__FILE__, __LINE__, __PRETTY_FUNCTION__, (errBuf.str()).c_str())); xercesc::XMLString::release( &message ); } catch (crispr::xml_exception& xe) { std::cerr<< xe.what()<getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_Metadata())) { parseMetadata(currentElement, xmlParser); } } } void parseMetadata(xercesc::DOMElement * parentNode, crispr::xml::writer& xmlParser) { for (xercesc::DOMElement * currentElement = parentNode->getFirstElementChild(); currentElement != NULL; currentElement = currentElement->getNextElementSibling()) { if (xercesc::XMLString::equals(currentElement->getTagName(), xmlParser.tag_File())) { char * c_url = tc(currentElement->getAttribute(xmlParser.attr_Url())); if (remove(c_url)) { perror(""Cannot remove file""); } xr(&c_url); } } } void removeUsage(void) { std::cout< file.crispr""<& groups, std::string& outputFile, bool& rem ) { try { int c; int index; static struct option long_options [] = { {""help"", no_argument, NULL, 'h'}, {""groups"",required_argument, NULL, 'g'}, {""remove-file"", no_argument, NULL, 'r'}, {""outfile"",required_argument,NULL, 'o'}, {0,0,0,0} }; while((c = getopt_long(argc, argv, ""hg:o:r"", long_options, &index)) != -1) { switch(c) { case 'h': { removeUsage (); exit(0); break; } case 'g': { if(fileOrString(optarg)) { // its a file parseFileForGroups(groups, optarg); //ST_Subset = true; } else { // its a string generateGroupsFromString(optarg, groups); } break; } case 'o': { outputFile = optarg; break; } case 'r': { rem = true; } default: { removeUsage(); exit(1); break; } } } if (groups.empty()) { throw crispr::input_exception(""Please specify the groups to remove with -g""); } } catch (crispr::input_exception& e) { std::cerr<. * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include #include ""CrisprGraph.h"" namespace crispr { int graph::setNodeAttribute(Agnode_t * node ,char * attrName, char * attrValue) { char * dummy = strdup(""""); int ret = agsafeset(node, attrName, attrValue, dummy); delete dummy; return ret; } int graph::setGraphAttribute(char * attrName, char * attrValue) { char * dummy = strdup(""""); int ret = agsafeset(G_graph, attrName, attrValue, dummy); delete dummy; return ret; } int graph::setEdgeAttribute(Agedge_t * edge ,char * attrName, char * attrValue) { char * dummy = strdup(""""); int ret = agsafeset(edge, attrName, attrValue, dummy); delete dummy; return ret; } } ","C++" "CRISPR","ctSkennerton/crass","src/crass/SanitiseTool.h",".h","4270","137","/* * SanitiseTool.h * * Copyright (C) 2011 - Connor Skennerton * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . */ #include #include #include #include ""writer.h"" typedef std::map conversionMap; class SanitiseTool { bool ST_Repeats; bool ST_Spacers; bool ST_contigs; bool ST_Flank; std::string ST_OutputFile; conversionMap ST_RepeatMap; conversionMap ST_SpacerMap; conversionMap ST_FlankMap; conversionMap ST_ContigMap; int ST_NextGroup; int ST_NextSpacer; int ST_NextRepeat; int ST_NextFlanker; int ST_NextContig; public: // constructor SanitiseTool() { ST_NextGroup = 1; ST_NextSpacer = 1; ST_NextRepeat = 1; ST_NextFlanker = 1; ST_NextContig = 1; ST_Repeats = false; ST_Spacers = false; ST_contigs = false; ST_Flank = false; } // get and set inline int getNextGroup(void){return ST_NextGroup;} inline int getNextSpacer(void){return ST_NextSpacer;} inline int getNextRepeat(void){return ST_NextRepeat;} inline int getNextFlanker(void){return ST_NextFlanker;} inline int getNextContig(void){return ST_NextContig;} inline std::string getNextGroupS(void) { std::stringstream ss; ss<<'G'<. // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // // system includes #include #include #include #include // local includes #include ""LoggerSimp.h"" LoggerSimp* LoggerSimp::mInstance = NULL; LoggerSimp* LoggerSimp::Inst(void) { if(mInstance == NULL){ mInstance = new LoggerSimp(); } mInstance->setFileOpen(false); std::ofstream * fh = mInstance->getFhandle(); if (fh != NULL) { fh = NULL; } std::streambuf * buff = mInstance->getBuff(); if (buff != NULL) { buff = NULL; } return mInstance; } LoggerSimp::LoggerSimp() {} LoggerSimp::~LoggerSimp(){ if(mFileOpen) mInstance->closeLogFile(); if(mTmpFH != NULL) { delete mTmpFH; } if(mGlobalHandle != NULL) { delete mGlobalHandle; } if(mInstance != NULL) { delete mInstance; } } void LoggerSimp::init(std::string logFile, int logLevel) { mInstance->setLogLevel(logLevel); mInstance->setStartTime(); if(logFile == """") { // set the logger to cout std::streambuf * buff = mInstance->getBuff(); buff = std::cout.rdbuf(); mGlobalHandle = new std::iostream(buff); } else { mInstance->setLogFile(logFile); mInstance->clearLogFile(); mInstance->openLogFile(); } } // Get methods int LoggerSimp::getLogLevel(void) { //----- // get the log level // return mLogLevel; } std::string LoggerSimp::getLogFile(void) { //----- // the file we're logging to // return mLogFile; } bool LoggerSimp::isFileOpen(void) { //----- // is the log file open? // return mFileOpen; } std::ofstream * LoggerSimp::getFhandle(void) { //----- // get the fileHandle // return mFileHandle; } std::streambuf * LoggerSimp::getBuff(void) { //----- // get the rbuff // return mBuff; } // Set Methods void LoggerSimp::setFileOpen(bool isOpen) { //---- // set the file open flag // mFileOpen = isOpen; } void LoggerSimp::setStartTime(void) { //---- // set the start time // time ( &mStartTime ); } void LoggerSimp::setLogLevel(int ll) { //----- // set the log level // mLogLevel = ll; } void LoggerSimp::setLogFile(std::string lf) { //----- // set the file name for the log file // mLogFile = lf; } // Operations std::string LoggerSimp::int2Str(int input) { //----- // curse c++ and their non toString() // std::stringstream ss; std::string s; ss << input; ss >> s; return s; } std::string LoggerSimp::timeToString(bool elapsed) { //----- // get the time in a pretty form. Also can get time elapsed // struct tm * timeinfo; char buffer [80]; time ( &mCurrentTime ); if(elapsed) { std::string tmp = """"; int tot_secs = (int)(difftime(mCurrentTime, mStartTime)); int tot_days = tot_secs / 86400; if(tot_days) { tmp += int2Str(tot_days)+""d ""; tot_secs = tot_secs - (tot_days * 86400); } int tot_hours = tot_secs / 3600; if(tot_hours) { tmp += int2Str(tot_hours)+""h ""; tot_secs = tot_secs - (tot_hours * 3600); } int tot_mins = tot_secs / 60; if(tot_mins) { tmp += int2Str(tot_mins)+""m ""; tot_secs = tot_secs - (tot_mins * 60); } tmp += int2Str(tot_secs)+""s""; return tmp; } else { timeinfo = localtime ( &mCurrentTime ); strftime (buffer,80,""%d/%m/%Y_%I:%M"",timeinfo); std::string tmp(buffer); return tmp; } } void LoggerSimp::openLogFile(void) { //----- // opens the log file // mTmpFH = mInstance->getFhandle(); mTmpFH = new std::ofstream(getLogFile().c_str(), std::ios::app); mInstance->setFileOpen(true); std::streambuf * buff = mInstance->getBuff(); buff = mTmpFH->rdbuf(); mGlobalHandle = new std::iostream(buff); } void LoggerSimp::closeLogFile(void) { //----- // closes the log file // std::ofstream * fh = mInstance->getFhandle(); if(fh != NULL) { fh->close(); delete fh; } } void LoggerSimp::clearLogFile(void) { //----- // clears the log file // std::ofstream tmp_file(mLogFile.c_str(), std::ios::out); tmp_file.close(); } ","C++" "CRISPR","ctSkennerton/crass","src/crass/libcrispr.h",".h","3971","133","// File: libcrispr.h // Original Author: Michael Imelfort 2011 // -------------------------------------------------------------------- // // OVERVIEW: // // Header file for the ""crispr toolbox"" // // -------------------------------------------------------------------- // Copyright 2011 Michael Imelfort and Connor Skennerton // This program is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program. If not, see . // -------------------------------------------------------------------- // // A // A B // A B R // A B R A // A B R A C // A B R A C A // A B R A C A D // A B R A C A D A // A B R A C A D A B // A B R A C A D A B R // A B R A C A D A B R A // #ifndef libcrispr_h #define libcrispr_h // system includes #include #include #include #include #include #include // local includes #include ""crassDefines.h"" #include ""PatternMatcher.h"" #include ""kseq.h"" #include ""ReadHolder.h"" #include ""SeqUtils.h"" #include ""StringCheck.h"" #include ""Types.h"" #if SEARCH_SINGLETON #include ""SearchChecker.h"" #endif enum READ_TYPE { LONG_READ, SHORT_READ }; enum side{rightSide, leftSide}; //************************************** // search functions //************************************** int searchFile(const char *inputFile, const options &opts, ReadMap * mReads, StringCheck * mStringCheck, lookupTable& patternsHash, lookupTable& readsFound, time_t& startTime); int searchCore(ReadHolder& seq, const options &opts ); void findSingletons(const char *inputFastq, const options &opts, std::vector * nonRedundantPatterns, lookupTable &readsFound, ReadMap * mReads, StringCheck * mStringCheck, time_t& startTime); int scanRight(ReadHolder& tmp_holder, std::string& pattern, unsigned int minSpacerLength, unsigned int scanRange); unsigned int extendPreRepeat(ReadHolder& tmp_holder, int searchWindowLength, int minSpacerLength); bool testSpacerLength(int minSpacerLength, int maxSpacerLength, int minAllowedSpacerLength, int maxAllowedSpacerLength); bool testSpacerRepeatSimilarity(float similarity); bool testSpacerSpacerSimilarity(float similarity); bool testSpacerSpacerLengthDiff(int difference); bool testRepeatSpacerLengthDiff(int differnce); bool qcFoundRepeats(ReadHolder& tmp_holder, int minSpacerLength, int maxSpacerLength); bool isRepeatLowComplexity(std::string& repeat); bool drHasHighlyAbundantKmers(std::string& directRepeat, float& max_count); bool drHasHighlyAbundantKmers(std::string& directRepeat); void addReadHolder(ReadMap * mReads, StringCheck * mStringCheck, ReadHolder& tmp_holder); // // // //void map2Vector(lookupTable &patterns_hash, std::vector &patterns); #endif //libcrispr_h ","Unknown" "CRISPR","ctSkennerton/crass","src/crass/SeqUtils.cpp",".cpp","3927","140","/* * SeqUtils.cpp is part of the CRisprASSembler project * * Created by Connor Skennerton. * Copyright 2011, 2012 Connor Skennerton & Michael Imelfort. All rights reserved. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see . * * * * A B R A K A D A B R A * A B R A K A D A B R * A B R A K A D A B * A B R A K A D A * A B R A K A D * A B R A K A * A B R A K * A B R A * A B R * A B * A */ #include #include #include #include #include #include #include #include #include #include #include #include ""SeqUtils.h"" char comp_tab[] = { 0, 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, 'T', 'V', 'G', 'H', 'E', 'F', 'C', 'D', 'I', 'J', 'M', 'L', 'K', 'N', 'O', 'P', 'Q', 'Y', 'S', 'A', 'A', 'B', 'W', 'X', 'R', 'Z', 91, 92, 93, 94, 95, 64, 't', 'v', 'g', 'h', 'e', 'f', 'c', 'd', 'i', 'j', 'm', 'l', 'k', 'n', 'o', 'p', 'q', 'y', 's', 'a', 'a', 'b', 'w', 'x', 'r', 'z', 123, 124, 125, 126, 127 }; std::string reverseComplement(std::string str) { int l = static_cast(str.length()); char * revcomp_str = new char[l+1]; for (int i = 0; i <=l; i++) { revcomp_str[i]='\0'; } int i, c0, c1; for (i = 0; i < l>>1; ++i) { c0 = comp_tab[(int)str[i]]; c1 = comp_tab[(int)str[l - 1 - i]]; revcomp_str[i] = c1; revcomp_str[l - 1 - i] = c0; } if (l&1) { revcomp_str[l>>1] = comp_tab[(int)str[l>>1]]; } std::string ret = revcomp_str; delete [] revcomp_str; return ret; } std::string laurenize (std::string seq1) { std::string seq2 = reverseComplement(seq1); if (seq1 < seq2) { return seq1; } return seq2; } gzFile getFileHandle(const char * inputFile) { gzFile fp; if ( strcmp(inputFile, ""-"") == 0 ) { fp = gzdopen(fileno(stdin), ""r""); } else { fp = gzopen(inputFile, ""r""); } if ( (fp == NULL) && (strcmp(inputFile, ""-"") != 0) ) { std::cerr<< PACKAGE_NAME<<"" : [ERROR] Could not open FASTQ ""< #include #include // #included from: catch_compiler_capabilities.h #define TWOBLUECUBES_CATCH_COMPILER_CAPABILITIES_HPP_INCLUDED // Detect a number of compiler features - mostly C++11/14 conformance - by compiler // The following features are defined: // // CATCH_CONFIG_CPP11_NULLPTR : is nullptr supported? // CATCH_CONFIG_CPP11_NOEXCEPT : is noexcept supported? // CATCH_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods // CATCH_CONFIG_CPP11_IS_ENUM : std::is_enum is supported? // CATCH_CONFIG_CPP11_TUPLE : std::tuple is supported // CATCH_CONFIG_CPP11_LONG_LONG : is long long supported? // CATCH_CONFIG_CPP11_OVERRIDE : is override supported? // CATCH_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) // CATCH_CONFIG_CPP11_OR_GREATER : Is C++11 supported? // CATCH_CONFIG_VARIADIC_MACROS : are variadic macros supported? // CATCH_CONFIG_COUNTER : is the __COUNTER__ macro supported? // **************** // Note to maintainers: if new toggles are added please document them // in configuration.md, too // **************** // In general each macro has a _NO_ form // (e.g. CATCH_CONFIG_CPP11_NO_NULLPTR) which disables the feature. // Many features, at point of detection, define an _INTERNAL_ macro, so they // can be combined, en-mass, with the _NO_ forms later. // All the C++11 features can be disabled with CATCH_CONFIG_NO_CPP11 #if defined(__cplusplus) && __cplusplus >= 201103L # define CATCH_CPP11_OR_GREATER #endif #ifdef __clang__ # if __has_feature(cxx_nullptr) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # endif # if __has_feature(cxx_noexcept) # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT # endif # if defined(CATCH_CPP11_OR_GREATER) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma( ""clang diagnostic ignored \""-Wparentheses\"""" ) # endif #endif // __clang__ //////////////////////////////////////////////////////////////////////////////// // Borland #ifdef __BORLANDC__ #endif // __BORLANDC__ //////////////////////////////////////////////////////////////////////////////// // EDG #ifdef __EDG_VERSION__ #endif // __EDG_VERSION__ //////////////////////////////////////////////////////////////////////////////// // Digital Mars #ifdef __DMC__ #endif // __DMC__ //////////////////////////////////////////////////////////////////////////////// // GCC #ifdef __GNUC__ # if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # endif # if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) && defined(CATCH_CPP11_OR_GREATER) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS _Pragma( ""GCC diagnostic ignored \""-Wparentheses\"""" ) # endif // - otherwise more recent versions define __cplusplus >= 201103L // and will get picked up below #endif // __GNUC__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #ifdef _MSC_VER #if (_MSC_VER >= 1600) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR #endif #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) #define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT #define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #endif #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // Use variadic macros if the compiler supports them #if ( defined _MSC_VER && _MSC_VER > 1400 && !defined __EDGE__) || \ ( defined __WAVE__ && __WAVE_HAS_VARIADICS ) || \ ( defined __GNUC__ && __GNUC__ >= 3 ) || \ ( !defined __cplusplus && __STDC_VERSION__ >= 199901L || __cplusplus >= 201103L ) #define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS #endif // Use __COUNTER__ if the compiler supports it #if ( defined _MSC_VER && _MSC_VER >= 1300 ) || \ ( defined __GNUC__ && __GNUC__ >= 4 && __GNUC_MINOR__ >= 3 ) || \ ( defined __clang__ && __clang_major__ >= 3 ) #define CATCH_INTERNAL_CONFIG_COUNTER #endif //////////////////////////////////////////////////////////////////////////////// // C++ language feature support // catch all support for C++11 #if defined(CATCH_CPP11_OR_GREATER) # if !defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) # define CATCH_INTERNAL_CONFIG_CPP11_NULLPTR # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT # define CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS # define CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM # define CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM # endif # ifndef CATCH_INTERNAL_CONFIG_CPP11_TUPLE # define CATCH_INTERNAL_CONFIG_CPP11_TUPLE # endif # ifndef CATCH_INTERNAL_CONFIG_VARIADIC_MACROS # define CATCH_INTERNAL_CONFIG_VARIADIC_MACROS # endif # if !defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) # define CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG # endif # if !defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) # define CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE # endif # if !defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) # define CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR # endif #endif // __cplusplus >= 201103L // Now set the actual defines based on the above + anything the user has configured #if defined(CATCH_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NO_NULLPTR) && !defined(CATCH_CONFIG_CPP11_NULLPTR) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_NULLPTR #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_NOEXCEPT #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CATCH_CONFIG_CPP11_GENERATED_METHODS) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_GENERATED_METHODS #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_NO_IS_ENUM) && !defined(CATCH_CONFIG_CPP11_IS_ENUM) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_IS_ENUM #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_CPP11_NO_TUPLE) && !defined(CATCH_CONFIG_CPP11_TUPLE) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_TUPLE #endif #if defined(CATCH_INTERNAL_CONFIG_VARIADIC_MACROS) && !defined(CATCH_CONFIG_NO_VARIADIC_MACROS) && !defined(CATCH_CONFIG_VARIADIC_MACROS) # define CATCH_CONFIG_VARIADIC_MACROS #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_LONG_LONG) && !defined(CATCH_CONFIG_CPP11_LONG_LONG) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_LONG_LONG #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_OVERRIDE) && !defined(CATCH_CONFIG_CPP11_OVERRIDE) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_OVERRIDE #endif #if defined(CATCH_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_UNIQUE_PTR) && !defined(CATCH_CONFIG_CPP11_UNIQUE_PTR) && !defined(CATCH_CONFIG_NO_CPP11) # define CATCH_CONFIG_CPP11_UNIQUE_PTR #endif #if defined(CATCH_INTERNAL_CONFIG_COUNTER) && !defined(CATCH_CONFIG_NO_COUNTER) && !defined(CATCH_CONFIG_COUNTER) # define CATCH_CONFIG_COUNTER #endif #if !defined(CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS) # define CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS #endif // noexcept support: #if defined(CATCH_CONFIG_CPP11_NOEXCEPT) && !defined(CATCH_NOEXCEPT) # define CATCH_NOEXCEPT noexcept # define CATCH_NOEXCEPT_IS(x) noexcept(x) #else # define CATCH_NOEXCEPT throw() # define CATCH_NOEXCEPT_IS(x) #endif // nullptr support #ifdef CATCH_CONFIG_CPP11_NULLPTR # define CATCH_NULL nullptr #else # define CATCH_NULL NULL #endif // override support #ifdef CATCH_CONFIG_CPP11_OVERRIDE # define CATCH_OVERRIDE override #else # define CATCH_OVERRIDE #endif // unique_ptr support #ifdef CATCH_CONFIG_CPP11_UNIQUE_PTR # define CATCH_AUTO_PTR( T ) std::unique_ptr #else # define CATCH_AUTO_PTR( T ) std::auto_ptr #endif namespace Catch { struct IConfig; struct CaseSensitive { enum Choice { Yes, No }; }; class NonCopyable { #ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS NonCopyable( NonCopyable const& ) = delete; NonCopyable( NonCopyable && ) = delete; NonCopyable& operator = ( NonCopyable const& ) = delete; NonCopyable& operator = ( NonCopyable && ) = delete; #else NonCopyable( NonCopyable const& info ); NonCopyable& operator = ( NonCopyable const& ); #endif protected: NonCopyable() {} virtual ~NonCopyable(); }; class SafeBool { public: typedef void (SafeBool::*type)() const; static type makeSafe( bool value ) { return value ? &SafeBool::trueValue : 0; } private: void trueValue() const {} }; template inline void deleteAll( ContainerT& container ) { typename ContainerT::const_iterator it = container.begin(); typename ContainerT::const_iterator itEnd = container.end(); for(; it != itEnd; ++it ) delete *it; } template inline void deleteAllValues( AssociativeContainerT& container ) { typename AssociativeContainerT::const_iterator it = container.begin(); typename AssociativeContainerT::const_iterator itEnd = container.end(); for(; it != itEnd; ++it ) delete it->second; } bool startsWith( std::string const& s, std::string const& prefix ); bool endsWith( std::string const& s, std::string const& suffix ); bool contains( std::string const& s, std::string const& infix ); void toLowerInPlace( std::string& s ); std::string toLower( std::string const& s ); std::string trim( std::string const& str ); bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ); struct pluralise { pluralise( std::size_t count, std::string const& label ); friend std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ); std::size_t m_count; std::string m_label; }; struct SourceLineInfo { SourceLineInfo(); SourceLineInfo( char const* _file, std::size_t _line ); SourceLineInfo( SourceLineInfo const& other ); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS SourceLineInfo( SourceLineInfo && ) = default; SourceLineInfo& operator = ( SourceLineInfo const& ) = default; SourceLineInfo& operator = ( SourceLineInfo && ) = default; # endif bool empty() const; bool operator == ( SourceLineInfo const& other ) const; bool operator < ( SourceLineInfo const& other ) const; std::string file; std::size_t line; }; std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ); // This is just here to avoid compiler warnings with macro constants and boolean literals inline bool isTrue( bool value ){ return value; } inline bool alwaysTrue() { return true; } inline bool alwaysFalse() { return false; } void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ); void seedRng( IConfig const& config ); unsigned int rngSeed(); // Use this in variadic streaming macros to allow // >> +StreamEndStop // as well as // >> stuff +StreamEndStop struct StreamEndStop { std::string operator+() { return std::string(); } }; template T const& operator + ( T const& value, StreamEndStop ) { return value; } } #define CATCH_INTERNAL_LINEINFO ::Catch::SourceLineInfo( __FILE__, static_cast( __LINE__ ) ) #define CATCH_INTERNAL_ERROR( msg ) ::Catch::throwLogicError( msg, CATCH_INTERNAL_LINEINFO ); #include namespace Catch { class NotImplementedException : public std::exception { public: NotImplementedException( SourceLineInfo const& lineInfo ); NotImplementedException( NotImplementedException const& ) {} virtual ~NotImplementedException() CATCH_NOEXCEPT {} virtual const char* what() const CATCH_NOEXCEPT; private: std::string m_what; SourceLineInfo m_lineInfo; }; } // end namespace Catch /////////////////////////////////////////////////////////////////////////////// #define CATCH_NOT_IMPLEMENTED throw Catch::NotImplementedException( CATCH_INTERNAL_LINEINFO ) // #included from: internal/catch_context.h #define TWOBLUECUBES_CATCH_CONTEXT_H_INCLUDED // #included from: catch_interfaces_generators.h #define TWOBLUECUBES_CATCH_INTERFACES_GENERATORS_H_INCLUDED #include namespace Catch { struct IGeneratorInfo { virtual ~IGeneratorInfo(); virtual bool moveNext() = 0; virtual std::size_t getCurrentIndex() const = 0; }; struct IGeneratorsForTest { virtual ~IGeneratorsForTest(); virtual IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) = 0; virtual bool moveNext() = 0; }; IGeneratorsForTest* createGeneratorsForTest(); } // end namespace Catch // #included from: catch_ptr.hpp #define TWOBLUECUBES_CATCH_PTR_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Wpadded"" #endif namespace Catch { // An intrusive reference counting smart pointer. // T must implement addRef() and release() methods // typically implementing the IShared interface template class Ptr { public: Ptr() : m_p( CATCH_NULL ){} Ptr( T* p ) : m_p( p ){ if( m_p ) m_p->addRef(); } Ptr( Ptr const& other ) : m_p( other.m_p ){ if( m_p ) m_p->addRef(); } ~Ptr(){ if( m_p ) m_p->release(); } void reset() { if( m_p ) m_p->release(); m_p = CATCH_NULL; } Ptr& operator = ( T* p ){ Ptr temp( p ); swap( temp ); return *this; } Ptr& operator = ( Ptr const& other ){ Ptr temp( other ); swap( temp ); return *this; } void swap( Ptr& other ) { std::swap( m_p, other.m_p ); } T* get() const{ return m_p; } T& operator*() const { return *m_p; } T* operator->() const { return m_p; } bool operator !() const { return m_p == CATCH_NULL; } operator SafeBool::type() const { return SafeBool::makeSafe( m_p != CATCH_NULL ); } private: T* m_p; }; struct IShared : NonCopyable { virtual ~IShared(); virtual void addRef() const = 0; virtual void release() const = 0; }; template struct SharedImpl : T { SharedImpl() : m_rc( 0 ){} virtual void addRef() const { ++m_rc; } virtual void release() const { if( --m_rc == 0 ) delete this; } mutable unsigned int m_rc; }; } // end namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif #include #include #include namespace Catch { class TestCase; class Stream; struct IResultCapture; struct IRunner; struct IGeneratorsForTest; struct IConfig; struct IContext { virtual ~IContext(); virtual IResultCapture* getResultCapture() = 0; virtual IRunner* getRunner() = 0; virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) = 0; virtual bool advanceGeneratorsForCurrentTest() = 0; virtual Ptr getConfig() const = 0; }; struct IMutableContext : IContext { virtual ~IMutableContext(); virtual void setResultCapture( IResultCapture* resultCapture ) = 0; virtual void setRunner( IRunner* runner ) = 0; virtual void setConfig( Ptr const& config ) = 0; }; IContext& getCurrentContext(); IMutableContext& getCurrentMutableContext(); void cleanUpContext(); Stream createStream( std::string const& streamName ); } // #included from: internal/catch_test_registry.hpp #define TWOBLUECUBES_CATCH_TEST_REGISTRY_HPP_INCLUDED // #included from: catch_interfaces_testcase.h #define TWOBLUECUBES_CATCH_INTERFACES_TESTCASE_H_INCLUDED #include namespace Catch { class TestSpec; struct ITestCase : IShared { virtual void invoke () const = 0; protected: virtual ~ITestCase(); }; class TestCase; struct IConfig; struct ITestCaseRegistry { virtual ~ITestCaseRegistry(); virtual std::vector const& getAllTests() const = 0; virtual std::vector const& getAllTestsSorted( IConfig const& config ) const = 0; }; bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ); std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ); std::vector const& getAllTestCasesSorted( IConfig const& config ); } namespace Catch { template class MethodTestCase : public SharedImpl { public: MethodTestCase( void (C::*method)() ) : m_method( method ) {} virtual void invoke() const { C obj; (obj.*m_method)(); } private: virtual ~MethodTestCase() {} void (C::*m_method)(); }; typedef void(*TestFunction)(); struct NameAndDesc { NameAndDesc( const char* _name = """", const char* _description= """" ) : name( _name ), description( _description ) {} const char* name; const char* description; }; void registerTestCase ( ITestCase* testCase, char const* className, NameAndDesc const& nameAndDesc, SourceLineInfo const& lineInfo ); struct AutoReg { AutoReg ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ); template AutoReg ( void (C::*method)(), char const* className, NameAndDesc const& nameAndDesc, SourceLineInfo const& lineInfo ) { registerTestCase ( new MethodTestCase( method ), className, nameAndDesc, lineInfo ); } ~AutoReg(); private: AutoReg( AutoReg const& ); void operator= ( AutoReg const& ); }; void registerTestCaseFunction ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ); } // end namespace Catch #ifdef CATCH_CONFIG_VARIADIC_MACROS /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE2( TestName, ... ) \ static void TestName(); \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); }\ static void TestName() #define INTERNAL_CATCH_TESTCASE( ... ) \ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, ... ) \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, ""&"" #QualifiedMethod, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestName, ClassName, ... )\ namespace{ \ struct TestName : ClassName{ \ void test(); \ }; \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestName::test, #ClassName, Catch::NameAndDesc( __VA_ARGS__ ), CATCH_INTERNAL_LINEINFO ); \ } \ void TestName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, ... ) \ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, __VA_ARGS__ ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, ... ) \ Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( __VA_ARGS__ ) ); #else /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TESTCASE2( TestName, Name, Desc ) \ static void TestName(); \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &TestName, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); }\ static void TestName() #define INTERNAL_CATCH_TESTCASE( Name, Desc ) \ INTERNAL_CATCH_TESTCASE2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), Name, Desc ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_METHOD_AS_TEST_CASE( QualifiedMethod, Name, Desc ) \ namespace{ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar )( &QualifiedMethod, ""&"" #QualifiedMethod, Catch::NameAndDesc( Name, Desc ), CATCH_INTERNAL_LINEINFO ); } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST_CASE_METHOD2( TestCaseName, ClassName, TestName, Desc )\ namespace{ \ struct TestCaseName : ClassName{ \ void test(); \ }; \ Catch::AutoReg INTERNAL_CATCH_UNIQUE_NAME( autoRegistrar ) ( &TestCaseName::test, #ClassName, Catch::NameAndDesc( TestName, Desc ), CATCH_INTERNAL_LINEINFO ); \ } \ void TestCaseName::test() #define INTERNAL_CATCH_TEST_CASE_METHOD( ClassName, TestName, Desc )\ INTERNAL_CATCH_TEST_CASE_METHOD2( INTERNAL_CATCH_UNIQUE_NAME( ____C_A_T_C_H____T_E_S_T____ ), ClassName, TestName, Desc ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_REGISTER_TESTCASE( Function, Name, Desc ) \ Catch::AutoReg( Function, CATCH_INTERNAL_LINEINFO, Catch::NameAndDesc( Name, Desc ) ); #endif // #included from: internal/catch_capture.hpp #define TWOBLUECUBES_CATCH_CAPTURE_HPP_INCLUDED // #included from: catch_result_builder.h #define TWOBLUECUBES_CATCH_RESULT_BUILDER_H_INCLUDED // #included from: catch_result_type.h #define TWOBLUECUBES_CATCH_RESULT_TYPE_H_INCLUDED namespace Catch { // ResultWas::OfType enum struct ResultWas { enum OfType { Unknown = -1, Ok = 0, Info = 1, Warning = 2, FailureBit = 0x10, ExpressionFailed = FailureBit | 1, ExplicitFailure = FailureBit | 2, Exception = 0x100 | FailureBit, ThrewException = Exception | 1, DidntThrowException = Exception | 2, FatalErrorCondition = 0x200 | FailureBit }; }; inline bool isOk( ResultWas::OfType resultType ) { return ( resultType & ResultWas::FailureBit ) == 0; } inline bool isJustInfo( int flags ) { return flags == ResultWas::Info; } // ResultDisposition::Flags enum struct ResultDisposition { enum Flags { Normal = 0x01, ContinueOnFailure = 0x02, // Failures fail test, but execution continues FalseTest = 0x04, // Prefix expression with ! SuppressFail = 0x08 // Failures are reported but do not fail the test }; }; inline ResultDisposition::Flags operator | ( ResultDisposition::Flags lhs, ResultDisposition::Flags rhs ) { return static_cast( static_cast( lhs ) | static_cast( rhs ) ); } inline bool shouldContinueOnFailure( int flags ) { return ( flags & ResultDisposition::ContinueOnFailure ) != 0; } inline bool isFalseTest( int flags ) { return ( flags & ResultDisposition::FalseTest ) != 0; } inline bool shouldSuppressFailure( int flags ) { return ( flags & ResultDisposition::SuppressFail ) != 0; } } // end namespace Catch // #included from: catch_assertionresult.h #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_H_INCLUDED #include namespace Catch { struct AssertionInfo { AssertionInfo() {} AssertionInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, std::string const& _capturedExpression, ResultDisposition::Flags _resultDisposition ); std::string macroName; SourceLineInfo lineInfo; std::string capturedExpression; ResultDisposition::Flags resultDisposition; }; struct AssertionResultData { AssertionResultData() : resultType( ResultWas::Unknown ) {} std::string reconstructedExpression; std::string message; ResultWas::OfType resultType; }; class AssertionResult { public: AssertionResult(); AssertionResult( AssertionInfo const& info, AssertionResultData const& data ); ~AssertionResult(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS AssertionResult( AssertionResult const& ) = default; AssertionResult( AssertionResult && ) = default; AssertionResult& operator = ( AssertionResult const& ) = default; AssertionResult& operator = ( AssertionResult && ) = default; # endif bool isOk() const; bool succeeded() const; ResultWas::OfType getResultType() const; bool hasExpression() const; bool hasMessage() const; std::string getExpression() const; std::string getExpressionInMacro() const; bool hasExpandedExpression() const; std::string getExpandedExpression() const; std::string getMessage() const; SourceLineInfo getSourceInfo() const; std::string getTestMacroName() const; protected: AssertionInfo m_info; AssertionResultData m_resultData; }; } // end namespace Catch // #included from: catch_matchers.hpp #define TWOBLUECUBES_CATCH_MATCHERS_HPP_INCLUDED namespace Catch { namespace Matchers { namespace Impl { namespace Generic { template class AllOf; template class AnyOf; template class Not; } template struct Matcher : SharedImpl { typedef ExpressionT ExpressionType; virtual ~Matcher() {} virtual Ptr clone() const = 0; virtual bool match( ExpressionT const& expr ) const = 0; virtual std::string toString() const = 0; Generic::AllOf operator && ( Matcher const& other ) const; Generic::AnyOf operator || ( Matcher const& other ) const; Generic::Not operator ! () const; }; template struct MatcherImpl : Matcher { virtual Ptr > clone() const { return Ptr >( new DerivedT( static_cast( *this ) ) ); } }; namespace Generic { template class Not : public MatcherImpl, ExpressionT> { public: explicit Not( Matcher const& matcher ) : m_matcher(matcher.clone()) {} Not( Not const& other ) : m_matcher( other.m_matcher ) {} virtual bool match( ExpressionT const& expr ) const CATCH_OVERRIDE { return !m_matcher->match( expr ); } virtual std::string toString() const CATCH_OVERRIDE { return ""not "" + m_matcher->toString(); } private: Ptr< Matcher > m_matcher; }; template class AllOf : public MatcherImpl, ExpressionT> { public: AllOf() {} AllOf( AllOf const& other ) : m_matchers( other.m_matchers ) {} AllOf& add( Matcher const& matcher ) { m_matchers.push_back( matcher.clone() ); return *this; } virtual bool match( ExpressionT const& expr ) const { for( std::size_t i = 0; i < m_matchers.size(); ++i ) if( !m_matchers[i]->match( expr ) ) return false; return true; } virtual std::string toString() const { std::ostringstream oss; oss << ""( ""; for( std::size_t i = 0; i < m_matchers.size(); ++i ) { if( i != 0 ) oss << "" and ""; oss << m_matchers[i]->toString(); } oss << "" )""; return oss.str(); } AllOf operator && ( Matcher const& other ) const { AllOf allOfExpr( *this ); allOfExpr.add( other ); return allOfExpr; } private: std::vector > > m_matchers; }; template class AnyOf : public MatcherImpl, ExpressionT> { public: AnyOf() {} AnyOf( AnyOf const& other ) : m_matchers( other.m_matchers ) {} AnyOf& add( Matcher const& matcher ) { m_matchers.push_back( matcher.clone() ); return *this; } virtual bool match( ExpressionT const& expr ) const { for( std::size_t i = 0; i < m_matchers.size(); ++i ) if( m_matchers[i]->match( expr ) ) return true; return false; } virtual std::string toString() const { std::ostringstream oss; oss << ""( ""; for( std::size_t i = 0; i < m_matchers.size(); ++i ) { if( i != 0 ) oss << "" or ""; oss << m_matchers[i]->toString(); } oss << "" )""; return oss.str(); } AnyOf operator || ( Matcher const& other ) const { AnyOf anyOfExpr( *this ); anyOfExpr.add( other ); return anyOfExpr; } private: std::vector > > m_matchers; }; } // namespace Generic template Generic::AllOf Matcher::operator && ( Matcher const& other ) const { Generic::AllOf allOfExpr; allOfExpr.add( *this ); allOfExpr.add( other ); return allOfExpr; } template Generic::AnyOf Matcher::operator || ( Matcher const& other ) const { Generic::AnyOf anyOfExpr; anyOfExpr.add( *this ); anyOfExpr.add( other ); return anyOfExpr; } template Generic::Not Matcher::operator ! () const { return Generic::Not( *this ); } namespace StdString { inline std::string makeString( std::string const& str ) { return str; } inline std::string makeString( const char* str ) { return str ? std::string( str ) : std::string(); } struct CasedString { CasedString( std::string const& str, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ), m_str( adjustString( str ) ) {} std::string adjustString( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } std::string toStringSuffix() const { return m_caseSensitivity == CaseSensitive::No ? "" (case insensitive)"" : """"; } CaseSensitive::Choice m_caseSensitivity; std::string m_str; }; struct Equals : MatcherImpl { Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( str, caseSensitivity ) {} Equals( Equals const& other ) : m_data( other.m_data ){} virtual ~Equals(); virtual bool match( std::string const& expr ) const { return m_data.m_str == m_data.adjustString( expr );; } virtual std::string toString() const { return ""equals: \"""" + m_data.m_str + ""\"""" + m_data.toStringSuffix(); } CasedString m_data; }; struct Contains : MatcherImpl { Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( substr, caseSensitivity ){} Contains( Contains const& other ) : m_data( other.m_data ){} virtual ~Contains(); virtual bool match( std::string const& expr ) const { return m_data.adjustString( expr ).find( m_data.m_str ) != std::string::npos; } virtual std::string toString() const { return ""contains: \"""" + m_data.m_str + ""\"""" + m_data.toStringSuffix(); } CasedString m_data; }; struct StartsWith : MatcherImpl { StartsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( substr, caseSensitivity ){} StartsWith( StartsWith const& other ) : m_data( other.m_data ){} virtual ~StartsWith(); virtual bool match( std::string const& expr ) const { return startsWith( m_data.adjustString( expr ), m_data.m_str ); } virtual std::string toString() const { return ""starts with: \"""" + m_data.m_str + ""\"""" + m_data.toStringSuffix(); } CasedString m_data; }; struct EndsWith : MatcherImpl { EndsWith( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) : m_data( substr, caseSensitivity ){} EndsWith( EndsWith const& other ) : m_data( other.m_data ){} virtual ~EndsWith(); virtual bool match( std::string const& expr ) const { return endsWith( m_data.adjustString( expr ), m_data.m_str ); } virtual std::string toString() const { return ""ends with: \"""" + m_data.m_str + ""\"""" + m_data.toStringSuffix(); } CasedString m_data; }; } // namespace StdString } // namespace Impl // The following functions create the actual matcher objects. // This allows the types to be inferred template inline Impl::Generic::Not Not( Impl::Matcher const& m ) { return Impl::Generic::Not( m ); } template inline Impl::Generic::AllOf AllOf( Impl::Matcher const& m1, Impl::Matcher const& m2 ) { return Impl::Generic::AllOf().add( m1 ).add( m2 ); } template inline Impl::Generic::AllOf AllOf( Impl::Matcher const& m1, Impl::Matcher const& m2, Impl::Matcher const& m3 ) { return Impl::Generic::AllOf().add( m1 ).add( m2 ).add( m3 ); } template inline Impl::Generic::AnyOf AnyOf( Impl::Matcher const& m1, Impl::Matcher const& m2 ) { return Impl::Generic::AnyOf().add( m1 ).add( m2 ); } template inline Impl::Generic::AnyOf AnyOf( Impl::Matcher const& m1, Impl::Matcher const& m2, Impl::Matcher const& m3 ) { return Impl::Generic::AnyOf().add( m1 ).add( m2 ).add( m3 ); } inline Impl::StdString::Equals Equals( std::string const& str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Equals( str, caseSensitivity ); } inline Impl::StdString::Equals Equals( const char* str, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Equals( Impl::StdString::makeString( str ), caseSensitivity ); } inline Impl::StdString::Contains Contains( std::string const& substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Contains( substr, caseSensitivity ); } inline Impl::StdString::Contains Contains( const char* substr, CaseSensitive::Choice caseSensitivity = CaseSensitive::Yes ) { return Impl::StdString::Contains( Impl::StdString::makeString( substr ), caseSensitivity ); } inline Impl::StdString::StartsWith StartsWith( std::string const& substr ) { return Impl::StdString::StartsWith( substr ); } inline Impl::StdString::StartsWith StartsWith( const char* substr ) { return Impl::StdString::StartsWith( Impl::StdString::makeString( substr ) ); } inline Impl::StdString::EndsWith EndsWith( std::string const& substr ) { return Impl::StdString::EndsWith( substr ); } inline Impl::StdString::EndsWith EndsWith( const char* substr ) { return Impl::StdString::EndsWith( Impl::StdString::makeString( substr ) ); } } // namespace Matchers using namespace Matchers; } // namespace Catch namespace Catch { struct TestFailureException{}; template class ExpressionLhs; struct STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison; struct CopyableStream { CopyableStream() {} CopyableStream( CopyableStream const& other ) { oss << other.oss.str(); } CopyableStream& operator=( CopyableStream const& other ) { oss.str(""""); oss << other.oss.str(); return *this; } std::ostringstream oss; }; class ResultBuilder { public: ResultBuilder( char const* macroName, SourceLineInfo const& lineInfo, char const* capturedExpression, ResultDisposition::Flags resultDisposition, char const* secondArg = """" ); template ExpressionLhs operator <= ( T const& operand ); ExpressionLhs operator <= ( bool value ); template ResultBuilder& operator << ( T const& value ) { m_stream.oss << value; return *this; } template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); ResultBuilder& setResultType( ResultWas::OfType result ); ResultBuilder& setResultType( bool result ); ResultBuilder& setLhs( std::string const& lhs ); ResultBuilder& setRhs( std::string const& rhs ); ResultBuilder& setOp( std::string const& op ); void endExpression(); std::string reconstructExpression() const; AssertionResult build() const; void useActiveException( ResultDisposition::Flags resultDisposition = ResultDisposition::Normal ); void captureResult( ResultWas::OfType resultType ); void captureExpression(); void captureExpectedException( std::string const& expectedMessage ); void captureExpectedException( Matchers::Impl::Matcher const& matcher ); void handleResult( AssertionResult const& result ); void react(); bool shouldDebugBreak() const; bool allowThrows() const; private: AssertionInfo m_assertionInfo; AssertionResultData m_data; struct ExprComponents { ExprComponents() : testFalse( false ) {} bool testFalse; std::string lhs, rhs, op; } m_exprComponents; CopyableStream m_stream; bool m_shouldDebugBreak; bool m_shouldThrow; }; } // namespace Catch // Include after due to circular dependency: // #included from: catch_expression_lhs.hpp #define TWOBLUECUBES_CATCH_EXPRESSION_LHS_HPP_INCLUDED // #included from: catch_evaluate.hpp #define TWOBLUECUBES_CATCH_EVALUATE_HPP_INCLUDED #ifdef _MSC_VER #pragma warning(push) #pragma warning(disable:4389) // '==' : signed/unsigned mismatch #endif #include namespace Catch { namespace Internal { enum Operator { IsEqualTo, IsNotEqualTo, IsLessThan, IsGreaterThan, IsLessThanOrEqualTo, IsGreaterThanOrEqualTo }; template struct OperatorTraits { static const char* getName(){ return ""*error*""; } }; template<> struct OperatorTraits { static const char* getName(){ return ""==""; } }; template<> struct OperatorTraits { static const char* getName(){ return ""!=""; } }; template<> struct OperatorTraits { static const char* getName(){ return ""<""; } }; template<> struct OperatorTraits { static const char* getName(){ return "">""; } }; template<> struct OperatorTraits { static const char* getName(){ return ""<=""; } }; template<> struct OperatorTraits{ static const char* getName(){ return "">=""; } }; template inline T& opCast(T const& t) { return const_cast(t); } // nullptr_t support based on pull request #154 from Konstantin Baumann #ifdef CATCH_CONFIG_CPP11_NULLPTR inline std::nullptr_t opCast(std::nullptr_t) { return nullptr; } #endif // CATCH_CONFIG_CPP11_NULLPTR // So the compare overloads can be operator agnostic we convey the operator as a template // enum, which is used to specialise an Evaluator for doing the comparison. template class Evaluator{}; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs) { return bool( opCast( lhs ) == opCast( rhs ) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) != opCast( rhs ) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) < opCast( rhs ) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) > opCast( rhs ) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) >= opCast( rhs ) ); } }; template struct Evaluator { static bool evaluate( T1 const& lhs, T2 const& rhs ) { return bool( opCast( lhs ) <= opCast( rhs ) ); } }; template bool applyEvaluator( T1 const& lhs, T2 const& rhs ) { return Evaluator::evaluate( lhs, rhs ); } // This level of indirection allows us to specialise for integer types // to avoid signed/ unsigned warnings // ""base"" overload template bool compare( T1 const& lhs, T2 const& rhs ) { return Evaluator::evaluate( lhs, rhs ); } // unsigned X to int template bool compare( unsigned int lhs, int rhs ) { return applyEvaluator( lhs, static_cast( rhs ) ); } template bool compare( unsigned long lhs, int rhs ) { return applyEvaluator( lhs, static_cast( rhs ) ); } template bool compare( unsigned char lhs, int rhs ) { return applyEvaluator( lhs, static_cast( rhs ) ); } // unsigned X to long template bool compare( unsigned int lhs, long rhs ) { return applyEvaluator( lhs, static_cast( rhs ) ); } template bool compare( unsigned long lhs, long rhs ) { return applyEvaluator( lhs, static_cast( rhs ) ); } template bool compare( unsigned char lhs, long rhs ) { return applyEvaluator( lhs, static_cast( rhs ) ); } // int to unsigned X template bool compare( int lhs, unsigned int rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( int lhs, unsigned long rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( int lhs, unsigned char rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } // long to unsigned X template bool compare( long lhs, unsigned int rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( long lhs, unsigned long rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( long lhs, unsigned char rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } // pointer to long (when comparing against NULL) template bool compare( long lhs, T* rhs ) { return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); } template bool compare( T* lhs, long rhs ) { return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); } // pointer to int (when comparing against NULL) template bool compare( int lhs, T* rhs ) { return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); } template bool compare( T* lhs, int rhs ) { return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); } #ifdef CATCH_CONFIG_CPP11_LONG_LONG // long long to unsigned X template bool compare( long long lhs, unsigned int rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( long long lhs, unsigned long rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( long long lhs, unsigned long long rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( long long lhs, unsigned char rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } // unsigned long long to X template bool compare( unsigned long long lhs, int rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( unsigned long long lhs, long rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( unsigned long long lhs, long long rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } template bool compare( unsigned long long lhs, char rhs ) { return applyEvaluator( static_cast( lhs ), rhs ); } // pointer to long long (when comparing against NULL) template bool compare( long long lhs, T* rhs ) { return Evaluator::evaluate( reinterpret_cast( lhs ), rhs ); } template bool compare( T* lhs, long long rhs ) { return Evaluator::evaluate( lhs, reinterpret_cast( rhs ) ); } #endif // CATCH_CONFIG_CPP11_LONG_LONG #ifdef CATCH_CONFIG_CPP11_NULLPTR // pointer to nullptr_t (when comparing against nullptr) template bool compare( std::nullptr_t, T* rhs ) { return Evaluator::evaluate( nullptr, rhs ); } template bool compare( T* lhs, std::nullptr_t ) { return Evaluator::evaluate( lhs, nullptr ); } #endif // CATCH_CONFIG_CPP11_NULLPTR } // end of namespace Internal } // end of namespace Catch #ifdef _MSC_VER #pragma warning(pop) #endif // #included from: catch_tostring.h #define TWOBLUECUBES_CATCH_TOSTRING_H_INCLUDED #include #include #include #include #include #ifdef __OBJC__ // #included from: catch_objc_arc.hpp #define TWOBLUECUBES_CATCH_OBJC_ARC_HPP_INCLUDED #import #ifdef __has_feature #define CATCH_ARC_ENABLED __has_feature(objc_arc) #else #define CATCH_ARC_ENABLED 0 #endif void arcSafeRelease( NSObject* obj ); id performOptionalSelector( id obj, SEL sel ); #if !CATCH_ARC_ENABLED inline void arcSafeRelease( NSObject* obj ) { [obj release]; } inline id performOptionalSelector( id obj, SEL sel ) { if( [obj respondsToSelector: sel] ) return [obj performSelector: sel]; return nil; } #define CATCH_UNSAFE_UNRETAINED #define CATCH_ARC_STRONG #else inline void arcSafeRelease( NSObject* ){} inline id performOptionalSelector( id obj, SEL sel ) { #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Warc-performSelector-leaks"" #endif if( [obj respondsToSelector: sel] ) return [obj performSelector: sel]; #ifdef __clang__ #pragma clang diagnostic pop #endif return nil; } #define CATCH_UNSAFE_UNRETAINED __unsafe_unretained #define CATCH_ARC_STRONG __strong #endif #endif #ifdef CATCH_CONFIG_CPP11_TUPLE #include #endif #ifdef CATCH_CONFIG_CPP11_IS_ENUM #include #endif namespace Catch { // Why we're here. template std::string toString( T const& value ); // Built in overloads std::string toString( std::string const& value ); std::string toString( std::wstring const& value ); std::string toString( const char* const value ); std::string toString( char* const value ); std::string toString( const wchar_t* const value ); std::string toString( wchar_t* const value ); std::string toString( int value ); std::string toString( unsigned long value ); std::string toString( unsigned int value ); std::string toString( const double value ); std::string toString( const float value ); std::string toString( bool value ); std::string toString( char value ); std::string toString( signed char value ); std::string toString( unsigned char value ); #ifdef CATCH_CONFIG_CPP11_LONG_LONG std::string toString( long long value ); std::string toString( unsigned long long value ); #endif #ifdef CATCH_CONFIG_CPP11_NULLPTR std::string toString( std::nullptr_t ); #endif #ifdef __OBJC__ std::string toString( NSString const * const& nsstring ); std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ); std::string toString( NSObject* const& nsObject ); #endif namespace Detail { extern const std::string unprintableString; struct BorgType { template BorgType( T const& ); }; struct TrueType { char sizer[1]; }; struct FalseType { char sizer[2]; }; TrueType& testStreamable( std::ostream& ); FalseType testStreamable( FalseType ); FalseType operator<<( std::ostream const&, BorgType const& ); template struct IsStreamInsertable { static std::ostream &s; static T const&t; enum { value = sizeof( testStreamable(s << t) ) == sizeof( TrueType ) }; }; #if defined(CATCH_CONFIG_CPP11_IS_ENUM) template::value > struct EnumStringMaker { static std::string convert( T const& ) { return unprintableString; } }; template struct EnumStringMaker { static std::string convert( T const& v ) { return ::Catch::toString( static_cast::type>(v) ); } }; #endif template struct StringMakerBase { #if defined(CATCH_CONFIG_CPP11_IS_ENUM) template static std::string convert( T const& v ) { return EnumStringMaker::convert( v ); } #else template static std::string convert( T const& ) { return unprintableString; } #endif }; template<> struct StringMakerBase { template static std::string convert( T const& _value ) { std::ostringstream oss; oss << _value; return oss.str(); } }; std::string rawMemoryToString( const void *object, std::size_t size ); template inline std::string rawMemoryToString( const T& object ) { return rawMemoryToString( &object, sizeof(object) ); } } // end namespace Detail template struct StringMaker : Detail::StringMakerBase::value> {}; template struct StringMaker { template static std::string convert( U* p ) { if( !p ) return ""NULL""; else return Detail::rawMemoryToString( p ); } }; template struct StringMaker { static std::string convert( R C::* p ) { if( !p ) return ""NULL""; else return Detail::rawMemoryToString( p ); } }; namespace Detail { template std::string rangeToString( InputIterator first, InputIterator last ); } //template //struct StringMaker > { // static std::string convert( std::vector const& v ) { // return Detail::rangeToString( v.begin(), v.end() ); // } //}; template std::string toString( std::vector const& v ) { return Detail::rangeToString( v.begin(), v.end() ); } #ifdef CATCH_CONFIG_CPP11_TUPLE // toString for tuples namespace TupleDetail { template< typename Tuple, std::size_t N = 0, bool = (N < std::tuple_size::value) > struct ElementPrinter { static void print( const Tuple& tuple, std::ostream& os ) { os << ( N ? "", "" : "" "" ) << Catch::toString(std::get(tuple)); ElementPrinter::print(tuple,os); } }; template< typename Tuple, std::size_t N > struct ElementPrinter { static void print( const Tuple&, std::ostream& ) {} }; } template struct StringMaker> { static std::string convert( const std::tuple& tuple ) { std::ostringstream os; os << '{'; TupleDetail::ElementPrinter>::print( tuple, os ); os << "" }""; return os.str(); } }; #endif // CATCH_CONFIG_CPP11_TUPLE namespace Detail { template std::string makeString( T const& value ) { return StringMaker::convert( value ); } } // end namespace Detail /// \brief converts any type to a string /// /// The default template forwards on to ostringstream - except when an /// ostringstream overload does not exist - in which case it attempts to detect /// that and writes {?}. /// Overload (not specialise) this template for custom typs that you don't want /// to provide an ostream overload for. template std::string toString( T const& value ) { return StringMaker::convert( value ); } namespace Detail { template std::string rangeToString( InputIterator first, InputIterator last ) { std::ostringstream oss; oss << ""{ ""; if( first != last ) { oss << Catch::toString( *first ); for( ++first ; first != last ; ++first ) oss << "", "" << Catch::toString( *first ); } oss << "" }""; return oss.str(); } } } // end namespace Catch namespace Catch { // Wraps the LHS of an expression and captures the operator and RHS (if any) - // wrapping them all in a ResultBuilder object template class ExpressionLhs { ExpressionLhs& operator = ( ExpressionLhs const& ); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS ExpressionLhs& operator = ( ExpressionLhs && ) = delete; # endif public: ExpressionLhs( ResultBuilder& rb, T lhs ) : m_rb( rb ), m_lhs( lhs ) {} # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS ExpressionLhs( ExpressionLhs const& ) = default; ExpressionLhs( ExpressionLhs && ) = default; # endif template ResultBuilder& operator == ( RhsT const& rhs ) { return captureExpression( rhs ); } template ResultBuilder& operator != ( RhsT const& rhs ) { return captureExpression( rhs ); } template ResultBuilder& operator < ( RhsT const& rhs ) { return captureExpression( rhs ); } template ResultBuilder& operator > ( RhsT const& rhs ) { return captureExpression( rhs ); } template ResultBuilder& operator <= ( RhsT const& rhs ) { return captureExpression( rhs ); } template ResultBuilder& operator >= ( RhsT const& rhs ) { return captureExpression( rhs ); } ResultBuilder& operator == ( bool rhs ) { return captureExpression( rhs ); } ResultBuilder& operator != ( bool rhs ) { return captureExpression( rhs ); } void endExpression() { bool value = m_lhs ? true : false; m_rb .setLhs( Catch::toString( value ) ) .setResultType( value ) .endExpression(); } // Only simple binary expressions are allowed on the LHS. // If more complex compositions are required then place the sub expression in parentheses template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator + ( RhsT const& ); template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator - ( RhsT const& ); template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator / ( RhsT const& ); template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator * ( RhsT const& ); template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator && ( RhsT const& ); template STATIC_ASSERT_Expression_Too_Complex_Please_Rewrite_As_Binary_Comparison& operator || ( RhsT const& ); private: template ResultBuilder& captureExpression( RhsT const& rhs ) { return m_rb .setResultType( Internal::compare( m_lhs, rhs ) ) .setLhs( Catch::toString( m_lhs ) ) .setRhs( Catch::toString( rhs ) ) .setOp( Internal::OperatorTraits::getName() ); } private: ResultBuilder& m_rb; T m_lhs; }; } // end namespace Catch namespace Catch { template inline ExpressionLhs ResultBuilder::operator <= ( T const& operand ) { return ExpressionLhs( *this, operand ); } inline ExpressionLhs ResultBuilder::operator <= ( bool value ) { return ExpressionLhs( *this, value ); } } // namespace Catch // #included from: catch_message.h #define TWOBLUECUBES_CATCH_MESSAGE_H_INCLUDED #include namespace Catch { struct MessageInfo { MessageInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ); std::string macroName; SourceLineInfo lineInfo; ResultWas::OfType type; std::string message; unsigned int sequence; bool operator == ( MessageInfo const& other ) const { return sequence == other.sequence; } bool operator < ( MessageInfo const& other ) const { return sequence < other.sequence; } private: static unsigned int globalCount; }; struct MessageBuilder { MessageBuilder( std::string const& macroName, SourceLineInfo const& lineInfo, ResultWas::OfType type ) : m_info( macroName, lineInfo, type ) {} template MessageBuilder& operator << ( T const& value ) { m_stream << value; return *this; } MessageInfo m_info; std::ostringstream m_stream; }; class ScopedMessage { public: ScopedMessage( MessageBuilder const& builder ); ScopedMessage( ScopedMessage const& other ); ~ScopedMessage(); MessageInfo m_info; }; } // end namespace Catch // #included from: catch_interfaces_capture.h #define TWOBLUECUBES_CATCH_INTERFACES_CAPTURE_H_INCLUDED #include namespace Catch { class TestCase; class AssertionResult; struct AssertionInfo; struct SectionInfo; struct SectionEndInfo; struct MessageInfo; class ScopedMessageBuilder; struct Counts; struct IResultCapture { virtual ~IResultCapture(); virtual void assertionEnded( AssertionResult const& result ) = 0; virtual bool sectionStarted( SectionInfo const& sectionInfo, Counts& assertions ) = 0; virtual void sectionEnded( SectionEndInfo const& endInfo ) = 0; virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) = 0; virtual void pushScopedMessage( MessageInfo const& message ) = 0; virtual void popScopedMessage( MessageInfo const& message ) = 0; virtual std::string getCurrentTestName() const = 0; virtual const AssertionResult* getLastResult() const = 0; virtual void handleFatalErrorCondition( std::string const& message ) = 0; }; IResultCapture& getResultCapture(); } // #included from: catch_debugger.h #define TWOBLUECUBES_CATCH_DEBUGGER_H_INCLUDED // #included from: catch_platform.h #define TWOBLUECUBES_CATCH_PLATFORM_H_INCLUDED #if defined(__MAC_OS_X_VERSION_MIN_REQUIRED) #define CATCH_PLATFORM_MAC #elif defined(__IPHONE_OS_VERSION_MIN_REQUIRED) #define CATCH_PLATFORM_IPHONE #elif defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) #define CATCH_PLATFORM_WINDOWS #endif #include namespace Catch{ bool isDebuggerActive(); void writeToDebugConsole( std::string const& text ); } #ifdef CATCH_PLATFORM_MAC // The following code snippet based on: // http://cocoawithlove.com/2008/03/break-into-debugger.html #ifdef DEBUG #if defined(__ppc64__) || defined(__ppc__) #define CATCH_BREAK_INTO_DEBUGGER() \ if( Catch::isDebuggerActive() ) { \ __asm__(""li r0, 20\nsc\nnop\nli r0, 37\nli r4, 2\nsc\nnop\n"" \ : : : ""memory"",""r0"",""r3"",""r4"" ); \ } #else #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) {__asm__(""int $3\n"" : : );} #endif #endif #elif defined(_MSC_VER) #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { __debugbreak(); } #elif defined(__MINGW32__) extern ""C"" __declspec(dllimport) void __stdcall DebugBreak(); #define CATCH_BREAK_INTO_DEBUGGER() if( Catch::isDebuggerActive() ) { DebugBreak(); } #endif #ifndef CATCH_BREAK_INTO_DEBUGGER #define CATCH_BREAK_INTO_DEBUGGER() Catch::alwaysTrue(); #endif // #included from: catch_interfaces_runner.h #define TWOBLUECUBES_CATCH_INTERFACES_RUNNER_H_INCLUDED namespace Catch { class TestCase; struct IRunner { virtual ~IRunner(); virtual bool aborting() const = 0; }; } /////////////////////////////////////////////////////////////////////////////// // In the event of a failure works out if the debugger needs to be invoked // and/or an exception thrown and takes appropriate action. // This needs to be done as a macro so the debugger will stop in the user // source code rather than in Catch library code #define INTERNAL_CATCH_REACT( resultBuilder ) \ if( resultBuilder.shouldDebugBreak() ) CATCH_BREAK_INTO_DEBUGGER(); \ resultBuilder.react(); /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ try { \ CATCH_INTERNAL_SUPPRESS_PARENTHESES_WARNINGS \ ( __catchResult <= expr ).endExpression(); \ } \ catch( ... ) { \ __catchResult.useActiveException( Catch::ResultDisposition::Normal ); \ } \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::isTrue( false && !!(expr) ) ) // expr here is never evaluated at runtime but it forces the compiler to give it a look /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_IF( expr, resultDisposition, macroName ) \ INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ if( Catch::getResultCapture().getLastResult()->succeeded() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_ELSE( expr, resultDisposition, macroName ) \ INTERNAL_CATCH_TEST( expr, resultDisposition, macroName ); \ if( !Catch::getResultCapture().getLastResult()->succeeded() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_NO_THROW( expr, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ try { \ expr; \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ } \ catch( ... ) { \ __catchResult.useActiveException( resultDisposition ); \ } \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS( expr, resultDisposition, matcher, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition, #matcher ); \ if( __catchResult.allowThrows() ) \ try { \ expr; \ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ } \ catch( ... ) { \ __catchResult.captureExpectedException( matcher ); \ } \ else \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_THROWS_AS( expr, exceptionType, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #expr, resultDisposition ); \ if( __catchResult.allowThrows() ) \ try { \ expr; \ __catchResult.captureResult( Catch::ResultWas::DidntThrowException ); \ } \ catch( exceptionType ) { \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ } \ catch( ... ) { \ __catchResult.useActiveException( resultDisposition ); \ } \ else \ __catchResult.captureResult( Catch::ResultWas::Ok ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) /////////////////////////////////////////////////////////////////////////////// #ifdef CATCH_CONFIG_VARIADIC_MACROS #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, ... ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, """", resultDisposition ); \ __catchResult << __VA_ARGS__ + ::Catch::StreamEndStop(); \ __catchResult.captureResult( messageType ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) #else #define INTERNAL_CATCH_MSG( messageType, resultDisposition, macroName, log ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, """", resultDisposition ); \ __catchResult << log + ::Catch::StreamEndStop(); \ __catchResult.captureResult( messageType ); \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) #endif /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_INFO( log, macroName ) \ Catch::ScopedMessage INTERNAL_CATCH_UNIQUE_NAME( scopedMessage ) = Catch::MessageBuilder( macroName, CATCH_INTERNAL_LINEINFO, Catch::ResultWas::Info ) << log; /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CHECK_THAT( arg, matcher, resultDisposition, macroName ) \ do { \ Catch::ResultBuilder __catchResult( macroName, CATCH_INTERNAL_LINEINFO, #arg "", "" #matcher, resultDisposition ); \ try { \ std::string matcherAsString = (matcher).toString(); \ __catchResult \ .setLhs( Catch::toString( arg ) ) \ .setRhs( matcherAsString == Catch::Detail::unprintableString ? #matcher : matcherAsString ) \ .setOp( ""matches"" ) \ .setResultType( (matcher).match( arg ) ); \ __catchResult.captureExpression(); \ } catch( ... ) { \ __catchResult.useActiveException( resultDisposition | Catch::ResultDisposition::ContinueOnFailure ); \ } \ INTERNAL_CATCH_REACT( __catchResult ) \ } while( Catch::alwaysFalse() ) // #included from: internal/catch_section.h #define TWOBLUECUBES_CATCH_SECTION_H_INCLUDED // #included from: catch_section_info.h #define TWOBLUECUBES_CATCH_SECTION_INFO_H_INCLUDED // #included from: catch_totals.hpp #define TWOBLUECUBES_CATCH_TOTALS_HPP_INCLUDED #include namespace Catch { struct Counts { Counts() : passed( 0 ), failed( 0 ), failedButOk( 0 ) {} Counts operator - ( Counts const& other ) const { Counts diff; diff.passed = passed - other.passed; diff.failed = failed - other.failed; diff.failedButOk = failedButOk - other.failedButOk; return diff; } Counts& operator += ( Counts const& other ) { passed += other.passed; failed += other.failed; failedButOk += other.failedButOk; return *this; } std::size_t total() const { return passed + failed + failedButOk; } bool allPassed() const { return failed == 0 && failedButOk == 0; } bool allOk() const { return failed == 0; } std::size_t passed; std::size_t failed; std::size_t failedButOk; }; struct Totals { Totals operator - ( Totals const& other ) const { Totals diff; diff.assertions = assertions - other.assertions; diff.testCases = testCases - other.testCases; return diff; } Totals delta( Totals const& prevTotals ) const { Totals diff = *this - prevTotals; if( diff.assertions.failed > 0 ) ++diff.testCases.failed; else if( diff.assertions.failedButOk > 0 ) ++diff.testCases.failedButOk; else ++diff.testCases.passed; return diff; } Totals& operator += ( Totals const& other ) { assertions += other.assertions; testCases += other.testCases; return *this; } Counts assertions; Counts testCases; }; } namespace Catch { struct SectionInfo { SectionInfo ( SourceLineInfo const& _lineInfo, std::string const& _name, std::string const& _description = std::string() ); std::string name; std::string description; SourceLineInfo lineInfo; }; struct SectionEndInfo { SectionEndInfo( SectionInfo const& _sectionInfo, Counts const& _prevAssertions, double _durationInSeconds ) : sectionInfo( _sectionInfo ), prevAssertions( _prevAssertions ), durationInSeconds( _durationInSeconds ) {} SectionInfo sectionInfo; Counts prevAssertions; double durationInSeconds; }; } // end namespace Catch // #included from: catch_timer.h #define TWOBLUECUBES_CATCH_TIMER_H_INCLUDED #ifdef CATCH_PLATFORM_WINDOWS typedef unsigned long long uint64_t; #else #include #endif namespace Catch { class Timer { public: Timer() : m_ticks( 0 ) {} void start(); unsigned int getElapsedMicroseconds() const; unsigned int getElapsedMilliseconds() const; double getElapsedSeconds() const; private: uint64_t m_ticks; }; } // namespace Catch #include namespace Catch { class Section : NonCopyable { public: Section( SectionInfo const& info ); ~Section(); // This indicates whether the section should be executed or not operator bool() const; private: SectionInfo m_info; std::string m_name; Counts m_assertions; bool m_sectionIncluded; Timer m_timer; }; } // end namespace Catch #ifdef CATCH_CONFIG_VARIADIC_MACROS #define INTERNAL_CATCH_SECTION( ... ) \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, __VA_ARGS__ ) ) #else #define INTERNAL_CATCH_SECTION( name, desc ) \ if( Catch::Section const& INTERNAL_CATCH_UNIQUE_NAME( catch_internal_Section ) = Catch::SectionInfo( CATCH_INTERNAL_LINEINFO, name, desc ) ) #endif // #included from: internal/catch_generators.hpp #define TWOBLUECUBES_CATCH_GENERATORS_HPP_INCLUDED #include #include #include #include namespace Catch { template struct IGenerator { virtual ~IGenerator() {} virtual T getValue( std::size_t index ) const = 0; virtual std::size_t size () const = 0; }; template class BetweenGenerator : public IGenerator { public: BetweenGenerator( T from, T to ) : m_from( from ), m_to( to ){} virtual T getValue( std::size_t index ) const { return m_from+static_cast( index ); } virtual std::size_t size() const { return static_cast( 1+m_to-m_from ); } private: T m_from; T m_to; }; template class ValuesGenerator : public IGenerator { public: ValuesGenerator(){} void add( T value ) { m_values.push_back( value ); } virtual T getValue( std::size_t index ) const { return m_values[index]; } virtual std::size_t size() const { return m_values.size(); } private: std::vector m_values; }; template class CompositeGenerator { public: CompositeGenerator() : m_totalSize( 0 ) {} // *** Move semantics, similar to auto_ptr *** CompositeGenerator( CompositeGenerator& other ) : m_fileInfo( other.m_fileInfo ), m_totalSize( 0 ) { move( other ); } CompositeGenerator& setFileInfo( const char* fileInfo ) { m_fileInfo = fileInfo; return *this; } ~CompositeGenerator() { deleteAll( m_composed ); } operator T () const { size_t overallIndex = getCurrentContext().getGeneratorIndex( m_fileInfo, m_totalSize ); typename std::vector*>::const_iterator it = m_composed.begin(); typename std::vector*>::const_iterator itEnd = m_composed.end(); for( size_t index = 0; it != itEnd; ++it ) { const IGenerator* generator = *it; if( overallIndex >= index && overallIndex < index + generator->size() ) { return generator->getValue( overallIndex-index ); } index += generator->size(); } CATCH_INTERNAL_ERROR( ""Indexed past end of generated range"" ); return T(); // Suppress spurious ""not all control paths return a value"" warning in Visual Studio - if you know how to fix this please do so } void add( const IGenerator* generator ) { m_totalSize += generator->size(); m_composed.push_back( generator ); } CompositeGenerator& then( CompositeGenerator& other ) { move( other ); return *this; } CompositeGenerator& then( T value ) { ValuesGenerator* valuesGen = new ValuesGenerator(); valuesGen->add( value ); add( valuesGen ); return *this; } private: void move( CompositeGenerator& other ) { std::copy( other.m_composed.begin(), other.m_composed.end(), std::back_inserter( m_composed ) ); m_totalSize += other.m_totalSize; other.m_composed.clear(); } std::vector*> m_composed; std::string m_fileInfo; size_t m_totalSize; }; namespace Generators { template CompositeGenerator between( T from, T to ) { CompositeGenerator generators; generators.add( new BetweenGenerator( from, to ) ); return generators; } template CompositeGenerator values( T val1, T val2 ) { CompositeGenerator generators; ValuesGenerator* valuesGen = new ValuesGenerator(); valuesGen->add( val1 ); valuesGen->add( val2 ); generators.add( valuesGen ); return generators; } template CompositeGenerator values( T val1, T val2, T val3 ){ CompositeGenerator generators; ValuesGenerator* valuesGen = new ValuesGenerator(); valuesGen->add( val1 ); valuesGen->add( val2 ); valuesGen->add( val3 ); generators.add( valuesGen ); return generators; } template CompositeGenerator values( T val1, T val2, T val3, T val4 ) { CompositeGenerator generators; ValuesGenerator* valuesGen = new ValuesGenerator(); valuesGen->add( val1 ); valuesGen->add( val2 ); valuesGen->add( val3 ); valuesGen->add( val4 ); generators.add( valuesGen ); return generators; } } // end namespace Generators using namespace Generators; } // end namespace Catch #define INTERNAL_CATCH_LINESTR2( line ) #line #define INTERNAL_CATCH_LINESTR( line ) INTERNAL_CATCH_LINESTR2( line ) #define INTERNAL_CATCH_GENERATE( expr ) expr.setFileInfo( __FILE__ ""("" INTERNAL_CATCH_LINESTR( __LINE__ ) "")"" ) // #included from: internal/catch_interfaces_exception.h #define TWOBLUECUBES_CATCH_INTERFACES_EXCEPTION_H_INCLUDED #include #include // #included from: catch_interfaces_registry_hub.h #define TWOBLUECUBES_CATCH_INTERFACES_REGISTRY_HUB_H_INCLUDED #include namespace Catch { class TestCase; struct ITestCaseRegistry; struct IExceptionTranslatorRegistry; struct IExceptionTranslator; struct IReporterRegistry; struct IReporterFactory; struct IRegistryHub { virtual ~IRegistryHub(); virtual IReporterRegistry const& getReporterRegistry() const = 0; virtual ITestCaseRegistry const& getTestCaseRegistry() const = 0; virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() = 0; }; struct IMutableRegistryHub { virtual ~IMutableRegistryHub(); virtual void registerReporter( std::string const& name, Ptr const& factory ) = 0; virtual void registerListener( Ptr const& factory ) = 0; virtual void registerTest( TestCase const& testInfo ) = 0; virtual void registerTranslator( const IExceptionTranslator* translator ) = 0; }; IRegistryHub& getRegistryHub(); IMutableRegistryHub& getMutableRegistryHub(); void cleanUp(); std::string translateActiveException(); } namespace Catch { typedef std::string(*exceptionTranslateFunction)(); struct IExceptionTranslator; typedef std::vector ExceptionTranslators; struct IExceptionTranslator { virtual ~IExceptionTranslator(); virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const = 0; }; struct IExceptionTranslatorRegistry { virtual ~IExceptionTranslatorRegistry(); virtual std::string translateActiveException() const = 0; }; class ExceptionTranslatorRegistrar { template class ExceptionTranslator : public IExceptionTranslator { public: ExceptionTranslator( std::string(*translateFunction)( T& ) ) : m_translateFunction( translateFunction ) {} virtual std::string translate( ExceptionTranslators::const_iterator it, ExceptionTranslators::const_iterator itEnd ) const CATCH_OVERRIDE { try { if( it == itEnd ) throw; else return (*it)->translate( it+1, itEnd ); } catch( T& ex ) { return m_translateFunction( ex ); } } protected: std::string(*m_translateFunction)( T& ); }; public: template ExceptionTranslatorRegistrar( std::string(*translateFunction)( T& ) ) { getMutableRegistryHub().registerTranslator ( new ExceptionTranslator( translateFunction ) ); } }; } /////////////////////////////////////////////////////////////////////////////// #define INTERNAL_CATCH_TRANSLATE_EXCEPTION2( translatorName, signature ) \ static std::string translatorName( signature ); \ namespace{ Catch::ExceptionTranslatorRegistrar INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionRegistrar )( &translatorName ); }\ static std::string translatorName( signature ) #define INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION2( INTERNAL_CATCH_UNIQUE_NAME( catch_internal_ExceptionTranslator ), signature ) // #included from: internal/catch_approx.hpp #define TWOBLUECUBES_CATCH_APPROX_HPP_INCLUDED #include #include namespace Catch { namespace Detail { class Approx { public: explicit Approx ( double value ) : m_epsilon( std::numeric_limits::epsilon()*100 ), m_scale( 1.0 ), m_value( value ) {} Approx( Approx const& other ) : m_epsilon( other.m_epsilon ), m_scale( other.m_scale ), m_value( other.m_value ) {} static Approx custom() { return Approx( 0 ); } Approx operator()( double value ) { Approx approx( value ); approx.epsilon( m_epsilon ); approx.scale( m_scale ); return approx; } friend bool operator == ( double lhs, Approx const& rhs ) { // Thanks to Richard Harris for his help refining this formula return fabs( lhs - rhs.m_value ) < rhs.m_epsilon * (rhs.m_scale + (std::max)( fabs(lhs), fabs(rhs.m_value) ) ); } friend bool operator == ( Approx const& lhs, double rhs ) { return operator==( rhs, lhs ); } friend bool operator != ( double lhs, Approx const& rhs ) { return !operator==( lhs, rhs ); } friend bool operator != ( Approx const& lhs, double rhs ) { return !operator==( rhs, lhs ); } Approx& epsilon( double newEpsilon ) { m_epsilon = newEpsilon; return *this; } Approx& scale( double newScale ) { m_scale = newScale; return *this; } std::string toString() const { std::ostringstream oss; oss << ""Approx( "" << Catch::toString( m_value ) << "" )""; return oss.str(); } private: double m_epsilon; double m_scale; double m_value; }; } template<> inline std::string toString( Detail::Approx const& value ) { return value.toString(); } } // end namespace Catch // #included from: internal/catch_interfaces_tag_alias_registry.h #define TWOBLUECUBES_CATCH_INTERFACES_TAG_ALIAS_REGISTRY_H_INCLUDED // #included from: catch_tag_alias.h #define TWOBLUECUBES_CATCH_TAG_ALIAS_H_INCLUDED #include namespace Catch { struct TagAlias { TagAlias( std::string _tag, SourceLineInfo _lineInfo ) : tag( _tag ), lineInfo( _lineInfo ) {} std::string tag; SourceLineInfo lineInfo; }; struct RegistrarForTagAliases { RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); }; } // end namespace Catch #define CATCH_REGISTER_TAG_ALIAS( alias, spec ) namespace{ Catch::RegistrarForTagAliases INTERNAL_CATCH_UNIQUE_NAME( AutoRegisterTagAlias )( alias, spec, CATCH_INTERNAL_LINEINFO ); } // #included from: catch_option.hpp #define TWOBLUECUBES_CATCH_OPTION_HPP_INCLUDED namespace Catch { // An optional type template class Option { public: Option() : nullableValue( CATCH_NULL ) {} Option( T const& _value ) : nullableValue( new( storage ) T( _value ) ) {} Option( Option const& _other ) : nullableValue( _other ? new( storage ) T( *_other ) : CATCH_NULL ) {} ~Option() { reset(); } Option& operator= ( Option const& _other ) { if( &_other != this ) { reset(); if( _other ) nullableValue = new( storage ) T( *_other ); } return *this; } Option& operator = ( T const& _value ) { reset(); nullableValue = new( storage ) T( _value ); return *this; } void reset() { if( nullableValue ) nullableValue->~T(); nullableValue = CATCH_NULL; } T& operator*() { return *nullableValue; } T const& operator*() const { return *nullableValue; } T* operator->() { return nullableValue; } const T* operator->() const { return nullableValue; } T valueOr( T const& defaultValue ) const { return nullableValue ? *nullableValue : defaultValue; } bool some() const { return nullableValue != CATCH_NULL; } bool none() const { return nullableValue == CATCH_NULL; } bool operator !() const { return nullableValue == CATCH_NULL; } operator SafeBool::type() const { return SafeBool::makeSafe( some() ); } private: T* nullableValue; char storage[sizeof(T)]; }; } // end namespace Catch namespace Catch { struct ITagAliasRegistry { virtual ~ITagAliasRegistry(); virtual Option find( std::string const& alias ) const = 0; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const = 0; static ITagAliasRegistry const& get(); }; } // end namespace Catch // These files are included here so the single_include script doesn't put them // in the conditionally compiled sections // #included from: internal/catch_test_case_info.h #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_H_INCLUDED #include #include #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Wpadded"" #endif namespace Catch { struct ITestCase; struct TestCaseInfo { enum SpecialProperties{ None = 0, IsHidden = 1 << 1, ShouldFail = 1 << 2, MayFail = 1 << 3, Throws = 1 << 4 }; TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::set const& _tags, SourceLineInfo const& _lineInfo ); TestCaseInfo( TestCaseInfo const& other ); friend void setTags( TestCaseInfo& testCaseInfo, std::set const& tags ); bool isHidden() const; bool throws() const; bool okToFail() const; bool expectedToFail() const; std::string name; std::string className; std::string description; std::set tags; std::set lcaseTags; std::string tagsAsString; SourceLineInfo lineInfo; SpecialProperties properties; }; class TestCase : public TestCaseInfo { public: TestCase( ITestCase* testCase, TestCaseInfo const& info ); TestCase( TestCase const& other ); TestCase withName( std::string const& _newName ) const; void invoke() const; TestCaseInfo const& getTestCaseInfo() const; void swap( TestCase& other ); bool operator == ( TestCase const& other ) const; bool operator < ( TestCase const& other ) const; TestCase& operator = ( TestCase const& other ); private: Ptr test; }; TestCase makeTestCase( ITestCase* testCase, std::string const& className, std::string const& name, std::string const& description, SourceLineInfo const& lineInfo ); } #ifdef __clang__ #pragma clang diagnostic pop #endif #ifdef __OBJC__ // #included from: internal/catch_objc.hpp #define TWOBLUECUBES_CATCH_OBJC_HPP_INCLUDED #import #include // NB. Any general catch headers included here must be included // in catch.hpp first to make sure they are included by the single // header for non obj-usage /////////////////////////////////////////////////////////////////////////////// // This protocol is really only here for (self) documenting purposes, since // all its methods are optional. @protocol OcFixture @optional -(void) setUp; -(void) tearDown; @end namespace Catch { class OcMethod : public SharedImpl { public: OcMethod( Class cls, SEL sel ) : m_cls( cls ), m_sel( sel ) {} virtual void invoke() const { id obj = [[m_cls alloc] init]; performOptionalSelector( obj, @selector(setUp) ); performOptionalSelector( obj, m_sel ); performOptionalSelector( obj, @selector(tearDown) ); arcSafeRelease( obj ); } private: virtual ~OcMethod() {} Class m_cls; SEL m_sel; }; namespace Detail{ inline std::string getAnnotation( Class cls, std::string const& annotationName, std::string const& testCaseName ) { NSString* selStr = [[NSString alloc] initWithFormat:@""Catch_%s_%s"", annotationName.c_str(), testCaseName.c_str()]; SEL sel = NSSelectorFromString( selStr ); arcSafeRelease( selStr ); id value = performOptionalSelector( cls, sel ); if( value ) return [(NSString*)value UTF8String]; return """"; } } inline size_t registerTestMethods() { size_t noTestMethods = 0; int noClasses = objc_getClassList( CATCH_NULL, 0 ); Class* classes = (CATCH_UNSAFE_UNRETAINED Class *)malloc( sizeof(Class) * noClasses); objc_getClassList( classes, noClasses ); for( int c = 0; c < noClasses; c++ ) { Class cls = classes[c]; { u_int count; Method* methods = class_copyMethodList( cls, &count ); for( u_int m = 0; m < count ; m++ ) { SEL selector = method_getName(methods[m]); std::string methodName = sel_getName(selector); if( startsWith( methodName, ""Catch_TestCase_"" ) ) { std::string testCaseName = methodName.substr( 15 ); std::string name = Detail::getAnnotation( cls, ""Name"", testCaseName ); std::string desc = Detail::getAnnotation( cls, ""Description"", testCaseName ); const char* className = class_getName( cls ); getMutableRegistryHub().registerTest( makeTestCase( new OcMethod( cls, selector ), className, name.c_str(), desc.c_str(), SourceLineInfo() ) ); noTestMethods++; } } free(methods); } } return noTestMethods; } namespace Matchers { namespace Impl { namespace NSStringMatchers { template struct StringHolder : MatcherImpl{ StringHolder( NSString* substr ) : m_substr( [substr copy] ){} StringHolder( StringHolder const& other ) : m_substr( [other.m_substr copy] ){} StringHolder() { arcSafeRelease( m_substr ); } NSString* m_substr; }; struct Equals : StringHolder { Equals( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str isEqualToString:m_substr]; } virtual std::string toString() const { return ""equals string: "" + Catch::toString( m_substr ); } }; struct Contains : StringHolder { Contains( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location != NSNotFound; } virtual std::string toString() const { return ""contains string: "" + Catch::toString( m_substr ); } }; struct StartsWith : StringHolder { StartsWith( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == 0; } virtual std::string toString() const { return ""starts with: "" + Catch::toString( m_substr ); } }; struct EndsWith : StringHolder { EndsWith( NSString* substr ) : StringHolder( substr ){} virtual bool match( ExpressionType const& str ) const { return (str != nil || m_substr == nil ) && [str rangeOfString:m_substr].location == [str length] - [m_substr length]; } virtual std::string toString() const { return ""ends with: "" + Catch::toString( m_substr ); } }; } // namespace NSStringMatchers } // namespace Impl inline Impl::NSStringMatchers::Equals Equals( NSString* substr ){ return Impl::NSStringMatchers::Equals( substr ); } inline Impl::NSStringMatchers::Contains Contains( NSString* substr ){ return Impl::NSStringMatchers::Contains( substr ); } inline Impl::NSStringMatchers::StartsWith StartsWith( NSString* substr ){ return Impl::NSStringMatchers::StartsWith( substr ); } inline Impl::NSStringMatchers::EndsWith EndsWith( NSString* substr ){ return Impl::NSStringMatchers::EndsWith( substr ); } } // namespace Matchers using namespace Matchers; } // namespace Catch /////////////////////////////////////////////////////////////////////////////// #define OC_TEST_CASE( name, desc )\ +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Name_test ) \ {\ return @ name; \ }\ +(NSString*) INTERNAL_CATCH_UNIQUE_NAME( Catch_Description_test ) \ { \ return @ desc; \ } \ -(void) INTERNAL_CATCH_UNIQUE_NAME( Catch_TestCase_test ) #endif #ifdef CATCH_IMPL // #included from: internal/catch_impl.hpp #define TWOBLUECUBES_CATCH_IMPL_HPP_INCLUDED // Collect all the implementation files together here // These are the equivalent of what would usually be cpp files #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Wweak-vtables"" #endif // #included from: ../catch_session.hpp #define TWOBLUECUBES_CATCH_RUNNER_HPP_INCLUDED // #included from: internal/catch_commandline.hpp #define TWOBLUECUBES_CATCH_COMMANDLINE_HPP_INCLUDED // #included from: catch_config.hpp #define TWOBLUECUBES_CATCH_CONFIG_HPP_INCLUDED // #included from: catch_test_spec_parser.hpp #define TWOBLUECUBES_CATCH_TEST_SPEC_PARSER_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Wpadded"" #endif // #included from: catch_test_spec.hpp #define TWOBLUECUBES_CATCH_TEST_SPEC_HPP_INCLUDED #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Wpadded"" #endif // #included from: catch_wildcard_pattern.hpp #define TWOBLUECUBES_CATCH_WILDCARD_PATTERN_HPP_INCLUDED namespace Catch { class WildcardPattern { enum WildcardPosition { NoWildcard = 0, WildcardAtStart = 1, WildcardAtEnd = 2, WildcardAtBothEnds = WildcardAtStart | WildcardAtEnd }; public: WildcardPattern( std::string const& pattern, CaseSensitive::Choice caseSensitivity ) : m_caseSensitivity( caseSensitivity ), m_wildcard( NoWildcard ), m_pattern( adjustCase( pattern ) ) { if( startsWith( m_pattern, ""*"" ) ) { m_pattern = m_pattern.substr( 1 ); m_wildcard = WildcardAtStart; } if( endsWith( m_pattern, ""*"" ) ) { m_pattern = m_pattern.substr( 0, m_pattern.size()-1 ); m_wildcard = static_cast( m_wildcard | WildcardAtEnd ); } } virtual ~WildcardPattern(); virtual bool matches( std::string const& str ) const { switch( m_wildcard ) { case NoWildcard: return m_pattern == adjustCase( str ); case WildcardAtStart: return endsWith( adjustCase( str ), m_pattern ); case WildcardAtEnd: return startsWith( adjustCase( str ), m_pattern ); case WildcardAtBothEnds: return contains( adjustCase( str ), m_pattern ); } #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Wunreachable-code"" #endif throw std::logic_error( ""Unknown enum"" ); #ifdef __clang__ #pragma clang diagnostic pop #endif } private: std::string adjustCase( std::string const& str ) const { return m_caseSensitivity == CaseSensitive::No ? toLower( str ) : str; } CaseSensitive::Choice m_caseSensitivity; WildcardPosition m_wildcard; std::string m_pattern; }; } #include #include namespace Catch { class TestSpec { struct Pattern : SharedImpl<> { virtual ~Pattern(); virtual bool matches( TestCaseInfo const& testCase ) const = 0; }; class NamePattern : public Pattern { public: NamePattern( std::string const& name ) : m_wildcardPattern( toLower( name ), CaseSensitive::No ) {} virtual ~NamePattern(); virtual bool matches( TestCaseInfo const& testCase ) const { return m_wildcardPattern.matches( toLower( testCase.name ) ); } private: WildcardPattern m_wildcardPattern; }; class TagPattern : public Pattern { public: TagPattern( std::string const& tag ) : m_tag( toLower( tag ) ) {} virtual ~TagPattern(); virtual bool matches( TestCaseInfo const& testCase ) const { return testCase.lcaseTags.find( m_tag ) != testCase.lcaseTags.end(); } private: std::string m_tag; }; class ExcludedPattern : public Pattern { public: ExcludedPattern( Ptr const& underlyingPattern ) : m_underlyingPattern( underlyingPattern ) {} virtual ~ExcludedPattern(); virtual bool matches( TestCaseInfo const& testCase ) const { return !m_underlyingPattern->matches( testCase ); } private: Ptr m_underlyingPattern; }; struct Filter { std::vector > m_patterns; bool matches( TestCaseInfo const& testCase ) const { // All patterns in a filter must match for the filter to be a match for( std::vector >::const_iterator it = m_patterns.begin(), itEnd = m_patterns.end(); it != itEnd; ++it ) if( !(*it)->matches( testCase ) ) return false; return true; } }; public: bool hasFilters() const { return !m_filters.empty(); } bool matches( TestCaseInfo const& testCase ) const { // A TestSpec matches if any filter matches for( std::vector::const_iterator it = m_filters.begin(), itEnd = m_filters.end(); it != itEnd; ++it ) if( it->matches( testCase ) ) return true; return false; } private: std::vector m_filters; friend class TestSpecParser; }; } #ifdef __clang__ #pragma clang diagnostic pop #endif namespace Catch { class TestSpecParser { enum Mode{ None, Name, QuotedName, Tag }; Mode m_mode; bool m_exclusion; std::size_t m_start, m_pos; std::string m_arg; TestSpec::Filter m_currentFilter; TestSpec m_testSpec; ITagAliasRegistry const* m_tagAliases; public: TestSpecParser( ITagAliasRegistry const& tagAliases ) : m_tagAliases( &tagAliases ) {} TestSpecParser& parse( std::string const& arg ) { m_mode = None; m_exclusion = false; m_start = std::string::npos; m_arg = m_tagAliases->expandAliases( arg ); for( m_pos = 0; m_pos < m_arg.size(); ++m_pos ) visitChar( m_arg[m_pos] ); if( m_mode == Name ) addPattern(); return *this; } TestSpec testSpec() { addFilter(); return m_testSpec; } private: void visitChar( char c ) { if( m_mode == None ) { switch( c ) { case ' ': return; case '~': m_exclusion = true; return; case '[': return startNewMode( Tag, ++m_pos ); case '""': return startNewMode( QuotedName, ++m_pos ); default: startNewMode( Name, m_pos ); break; } } if( m_mode == Name ) { if( c == ',' ) { addPattern(); addFilter(); } else if( c == '[' ) { if( subString() == ""exclude:"" ) m_exclusion = true; else addPattern(); startNewMode( Tag, ++m_pos ); } } else if( m_mode == QuotedName && c == '""' ) addPattern(); else if( m_mode == Tag && c == ']' ) addPattern(); } void startNewMode( Mode mode, std::size_t start ) { m_mode = mode; m_start = start; } std::string subString() const { return m_arg.substr( m_start, m_pos - m_start ); } template void addPattern() { std::string token = subString(); if( startsWith( token, ""exclude:"" ) ) { m_exclusion = true; token = token.substr( 8 ); } if( !token.empty() ) { Ptr pattern = new T( token ); if( m_exclusion ) pattern = new TestSpec::ExcludedPattern( pattern ); m_currentFilter.m_patterns.push_back( pattern ); } m_exclusion = false; m_mode = None; } void addFilter() { if( !m_currentFilter.m_patterns.empty() ) { m_testSpec.m_filters.push_back( m_currentFilter ); m_currentFilter = TestSpec::Filter(); } } }; inline TestSpec parseTestSpec( std::string const& arg ) { return TestSpecParser( ITagAliasRegistry::get() ).parse( arg ).testSpec(); } } // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif // #included from: catch_interfaces_config.h #define TWOBLUECUBES_CATCH_INTERFACES_CONFIG_H_INCLUDED #include #include #include namespace Catch { struct Verbosity { enum Level { NoOutput = 0, Quiet, Normal }; }; struct WarnAbout { enum What { Nothing = 0x00, NoAssertions = 0x01 }; }; struct ShowDurations { enum OrNot { DefaultForReporter, Always, Never }; }; struct RunTests { enum InWhatOrder { InDeclarationOrder, InLexicographicalOrder, InRandomOrder }; }; struct UseColour { enum YesOrNo { Auto, Yes, No }; }; class TestSpec; struct IConfig : IShared { virtual ~IConfig(); virtual bool allowThrows() const = 0; virtual std::ostream& stream() const = 0; virtual std::string name() const = 0; virtual bool includeSuccessfulResults() const = 0; virtual bool shouldDebugBreak() const = 0; virtual bool warnAboutMissingAssertions() const = 0; virtual int abortAfter() const = 0; virtual bool showInvisibles() const = 0; virtual ShowDurations::OrNot showDurations() const = 0; virtual TestSpec const& testSpec() const = 0; virtual RunTests::InWhatOrder runOrder() const = 0; virtual unsigned int rngSeed() const = 0; virtual UseColour::YesOrNo useColour() const = 0; }; } // #included from: catch_stream.h #define TWOBLUECUBES_CATCH_STREAM_H_INCLUDED // #included from: catch_streambuf.h #define TWOBLUECUBES_CATCH_STREAMBUF_H_INCLUDED #include namespace Catch { class StreamBufBase : public std::streambuf { public: virtual ~StreamBufBase() CATCH_NOEXCEPT; }; } #include #include #include namespace Catch { std::ostream& cout(); std::ostream& cerr(); struct IStream { virtual ~IStream() CATCH_NOEXCEPT; virtual std::ostream& stream() const = 0; }; class FileStream : public IStream { mutable std::ofstream m_ofs; public: FileStream( std::string const& filename ); virtual ~FileStream() CATCH_NOEXCEPT; public: // IStream virtual std::ostream& stream() const CATCH_OVERRIDE; }; class CoutStream : public IStream { mutable std::ostream m_os; public: CoutStream(); virtual ~CoutStream() CATCH_NOEXCEPT; public: // IStream virtual std::ostream& stream() const CATCH_OVERRIDE; }; class DebugOutStream : public IStream { std::auto_ptr m_streamBuf; mutable std::ostream m_os; public: DebugOutStream(); virtual ~DebugOutStream() CATCH_NOEXCEPT; public: // IStream virtual std::ostream& stream() const CATCH_OVERRIDE; }; } #include #include #include #include #include #ifndef CATCH_CONFIG_CONSOLE_WIDTH #define CATCH_CONFIG_CONSOLE_WIDTH 80 #endif namespace Catch { struct ConfigData { ConfigData() : listTests( false ), listTags( false ), listReporters( false ), listTestNamesOnly( false ), showSuccessfulTests( false ), shouldDebugBreak( false ), noThrow( false ), showHelp( false ), showInvisibles( false ), filenamesAsTags( false ), abortAfter( -1 ), rngSeed( 0 ), verbosity( Verbosity::Normal ), warnings( WarnAbout::Nothing ), showDurations( ShowDurations::DefaultForReporter ), runOrder( RunTests::InDeclarationOrder ), useColour( UseColour::Auto ) {} bool listTests; bool listTags; bool listReporters; bool listTestNamesOnly; bool showSuccessfulTests; bool shouldDebugBreak; bool noThrow; bool showHelp; bool showInvisibles; bool filenamesAsTags; int abortAfter; unsigned int rngSeed; Verbosity::Level verbosity; WarnAbout::What warnings; ShowDurations::OrNot showDurations; RunTests::InWhatOrder runOrder; UseColour::YesOrNo useColour; std::string outputFilename; std::string name; std::string processName; std::vector reporterNames; std::vector testsOrTags; }; class Config : public SharedImpl { private: Config( Config const& other ); Config& operator = ( Config const& other ); virtual void dummy(); public: Config() {} Config( ConfigData const& data ) : m_data( data ), m_stream( openStream() ) { if( !data.testsOrTags.empty() ) { TestSpecParser parser( ITagAliasRegistry::get() ); for( std::size_t i = 0; i < data.testsOrTags.size(); ++i ) parser.parse( data.testsOrTags[i] ); m_testSpec = parser.testSpec(); } } virtual ~Config() { } std::string const& getFilename() const { return m_data.outputFilename ; } bool listTests() const { return m_data.listTests; } bool listTestNamesOnly() const { return m_data.listTestNamesOnly; } bool listTags() const { return m_data.listTags; } bool listReporters() const { return m_data.listReporters; } std::string getProcessName() const { return m_data.processName; } bool shouldDebugBreak() const { return m_data.shouldDebugBreak; } std::vector getReporterNames() const { return m_data.reporterNames; } int abortAfter() const { return m_data.abortAfter; } TestSpec const& testSpec() const { return m_testSpec; } bool showHelp() const { return m_data.showHelp; } bool showInvisibles() const { return m_data.showInvisibles; } // IConfig interface virtual bool allowThrows() const { return !m_data.noThrow; } virtual std::ostream& stream() const { return m_stream->stream(); } virtual std::string name() const { return m_data.name.empty() ? m_data.processName : m_data.name; } virtual bool includeSuccessfulResults() const { return m_data.showSuccessfulTests; } virtual bool warnAboutMissingAssertions() const { return m_data.warnings & WarnAbout::NoAssertions; } virtual ShowDurations::OrNot showDurations() const { return m_data.showDurations; } virtual RunTests::InWhatOrder runOrder() const { return m_data.runOrder; } virtual unsigned int rngSeed() const { return m_data.rngSeed; } virtual UseColour::YesOrNo useColour() const { return m_data.useColour; } private: IStream const* openStream() { if( m_data.outputFilename.empty() ) return new CoutStream(); else if( m_data.outputFilename[0] == '%' ) { if( m_data.outputFilename == ""%debug"" ) return new DebugOutStream(); else throw std::domain_error( ""Unrecognised stream: "" + m_data.outputFilename ); } else return new FileStream( m_data.outputFilename ); } ConfigData m_data; std::auto_ptr m_stream; TestSpec m_testSpec; }; } // end namespace Catch // #included from: catch_clara.h #define TWOBLUECUBES_CATCH_CLARA_H_INCLUDED // Use Catch's value for console width (store Clara's off to the side, if present) #ifdef CLARA_CONFIG_CONSOLE_WIDTH #define CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH CLARA_CONFIG_CONSOLE_WIDTH #undef CLARA_CONFIG_CONSOLE_WIDTH #endif #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH // Declare Clara inside the Catch namespace #define STITCH_CLARA_OPEN_NAMESPACE namespace Catch { // #included from: ../external/clara.h // Version 0.0.2.4 // Only use header guard if we are not using an outer namespace #if !defined(TWOBLUECUBES_CLARA_H_INCLUDED) || defined(STITCH_CLARA_OPEN_NAMESPACE) #ifndef STITCH_CLARA_OPEN_NAMESPACE #define TWOBLUECUBES_CLARA_H_INCLUDED #define STITCH_CLARA_OPEN_NAMESPACE #define STITCH_CLARA_CLOSE_NAMESPACE #else #define STITCH_CLARA_CLOSE_NAMESPACE } #endif #define STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE // ----------- #included from tbc_text_format.h ----------- // Only use header guard if we are not using an outer namespace #if !defined(TBC_TEXT_FORMAT_H_INCLUDED) || defined(STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE) #ifndef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE #define TBC_TEXT_FORMAT_H_INCLUDED #endif #include #include #include #include // Use optional outer namespace #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE namespace STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE { #endif namespace Tbc { #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; #else const unsigned int consoleWidth = 80; #endif struct TextAttributes { TextAttributes() : initialIndent( std::string::npos ), indent( 0 ), width( consoleWidth-1 ), tabChar( '\t' ) {} TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } std::size_t initialIndent; // indent of first line, or npos std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos std::size_t width; // maximum width of text, including indent. Longer text will wrap char tabChar; // If this char is seen the indent is changed to current pos }; class Text { public: Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) : attr( _attr ) { std::string wrappableChars = "" [({.,/|\\-""; std::size_t indent = _attr.initialIndent != std::string::npos ? _attr.initialIndent : _attr.indent; std::string remainder = _str; while( !remainder.empty() ) { if( lines.size() >= 1000 ) { lines.push_back( ""... message truncated due to excessive size"" ); return; } std::size_t tabPos = std::string::npos; std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); std::size_t pos = remainder.find_first_of( '\n' ); if( pos <= width ) { width = pos; } pos = remainder.find_last_of( _attr.tabChar, width ); if( pos != std::string::npos ) { tabPos = pos; if( remainder[width] == '\n' ) width--; remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); } if( width == remainder.size() ) { spliceLine( indent, remainder, width ); } else if( remainder[width] == '\n' ) { spliceLine( indent, remainder, width ); if( width <= 1 || remainder.size() != 1 ) remainder = remainder.substr( 1 ); indent = _attr.indent; } else { pos = remainder.find_last_of( wrappableChars, width ); if( pos != std::string::npos && pos > 0 ) { spliceLine( indent, remainder, pos ); if( remainder[0] == ' ' ) remainder = remainder.substr( 1 ); } else { spliceLine( indent, remainder, width-1 ); lines.back() += ""-""; } if( lines.size() == 1 ) indent = _attr.indent; if( tabPos != std::string::npos ) indent += tabPos; } } } void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); _remainder = _remainder.substr( _pos ); } typedef std::vector::const_iterator const_iterator; const_iterator begin() const { return lines.begin(); } const_iterator end() const { return lines.end(); } std::string const& last() const { return lines.back(); } std::size_t size() const { return lines.size(); } std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } std::string toString() const { std::ostringstream oss; oss << *this; return oss.str(); } inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); it != itEnd; ++it ) { if( it != _text.begin() ) _stream << ""\n""; _stream << *it; } return _stream; } private: std::string str; TextAttributes attr; std::vector lines; }; } // end namespace Tbc #ifdef STITCH_TBC_TEXT_FORMAT_OUTER_NAMESPACE } // end outer namespace #endif #endif // TBC_TEXT_FORMAT_H_INCLUDED // ----------- end of #include from tbc_text_format.h ----------- // ........... back in clara.h #undef STITCH_TBC_TEXT_FORMAT_OPEN_NAMESPACE // ----------- #included from clara_compilers.h ----------- #ifndef TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED #define TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED // Detect a number of compiler features - mostly C++11/14 conformance - by compiler // The following features are defined: // // CLARA_CONFIG_CPP11_NULLPTR : is nullptr supported? // CLARA_CONFIG_CPP11_NOEXCEPT : is noexcept supported? // CLARA_CONFIG_CPP11_GENERATED_METHODS : The delete and default keywords for compiler generated methods // CLARA_CONFIG_CPP11_OVERRIDE : is override supported? // CLARA_CONFIG_CPP11_UNIQUE_PTR : is unique_ptr supported (otherwise use auto_ptr) // CLARA_CONFIG_CPP11_OR_GREATER : Is C++11 supported? // CLARA_CONFIG_VARIADIC_MACROS : are variadic macros supported? // In general each macro has a _NO_ form // (e.g. CLARA_CONFIG_CPP11_NO_NULLPTR) which disables the feature. // Many features, at point of detection, define an _INTERNAL_ macro, so they // can be combined, en-mass, with the _NO_ forms later. // All the C++11 features can be disabled with CLARA_CONFIG_NO_CPP11 #ifdef __clang__ #if __has_feature(cxx_nullptr) #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR #endif #if __has_feature(cxx_noexcept) #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT #endif #endif // __clang__ //////////////////////////////////////////////////////////////////////////////// // GCC #ifdef __GNUC__ #if __GNUC__ == 4 && __GNUC_MINOR__ >= 6 && defined(__GXX_EXPERIMENTAL_CXX0X__) #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR #endif // - otherwise more recent versions define __cplusplus >= 201103L // and will get picked up below #endif // __GNUC__ //////////////////////////////////////////////////////////////////////////////// // Visual C++ #ifdef _MSC_VER #if (_MSC_VER >= 1600) #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR #define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR #endif #if (_MSC_VER >= 1900 ) // (VC++ 13 (VS2015)) #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT #define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #endif #endif // _MSC_VER //////////////////////////////////////////////////////////////////////////////// // C++ language feature support // catch all support for C++11 #if defined(__cplusplus) && __cplusplus >= 201103L #define CLARA_CPP11_OR_GREATER #if !defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) #define CLARA_INTERNAL_CONFIG_CPP11_NULLPTR #endif #ifndef CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT #define CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT #endif #ifndef CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #define CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS #endif #if !defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) #define CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE #endif #if !defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) #define CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR #endif #endif // __cplusplus >= 201103L // Now set the actual defines based on the above + anything the user has configured #if defined(CLARA_INTERNAL_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NO_NULLPTR) && !defined(CLARA_CONFIG_CPP11_NULLPTR) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_NULLPTR #endif #if defined(CLARA_INTERNAL_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NO_NOEXCEPT) && !defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_NOEXCEPT #endif #if defined(CLARA_INTERNAL_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_NO_GENERATED_METHODS) && !defined(CLARA_CONFIG_CPP11_GENERATED_METHODS) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_GENERATED_METHODS #endif #if defined(CLARA_INTERNAL_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_OVERRIDE) && !defined(CLARA_CONFIG_CPP11_OVERRIDE) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_OVERRIDE #endif #if defined(CLARA_INTERNAL_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_UNIQUE_PTR) && !defined(CLARA_CONFIG_CPP11_UNIQUE_PTR) && !defined(CLARA_CONFIG_NO_CPP11) #define CLARA_CONFIG_CPP11_UNIQUE_PTR #endif // noexcept support: #if defined(CLARA_CONFIG_CPP11_NOEXCEPT) && !defined(CLARA_NOEXCEPT) #define CLARA_NOEXCEPT noexcept # define CLARA_NOEXCEPT_IS(x) noexcept(x) #else #define CLARA_NOEXCEPT throw() # define CLARA_NOEXCEPT_IS(x) #endif // nullptr support #ifdef CLARA_CONFIG_CPP11_NULLPTR #define CLARA_NULL nullptr #else #define CLARA_NULL NULL #endif // override support #ifdef CLARA_CONFIG_CPP11_OVERRIDE #define CLARA_OVERRIDE override #else #define CLARA_OVERRIDE #endif // unique_ptr support #ifdef CLARA_CONFIG_CPP11_UNIQUE_PTR # define CLARA_AUTO_PTR( T ) std::unique_ptr #else # define CLARA_AUTO_PTR( T ) std::auto_ptr #endif #endif // TWOBLUECUBES_CLARA_COMPILERS_H_INCLUDED // ----------- end of #include from clara_compilers.h ----------- // ........... back in clara.h #include #include #include #if defined(WIN32) || defined(__WIN32__) || defined(_WIN32) || defined(_MSC_VER) #define CLARA_PLATFORM_WINDOWS #endif // Use optional outer namespace #ifdef STITCH_CLARA_OPEN_NAMESPACE STITCH_CLARA_OPEN_NAMESPACE #endif namespace Clara { struct UnpositionalTag {}; extern UnpositionalTag _; #ifdef CLARA_CONFIG_MAIN UnpositionalTag _; #endif namespace Detail { #ifdef CLARA_CONSOLE_WIDTH const unsigned int consoleWidth = CLARA_CONFIG_CONSOLE_WIDTH; #else const unsigned int consoleWidth = 80; #endif using namespace Tbc; inline bool startsWith( std::string const& str, std::string const& prefix ) { return str.size() >= prefix.size() && str.substr( 0, prefix.size() ) == prefix; } template struct RemoveConstRef{ typedef T type; }; template struct RemoveConstRef{ typedef T type; }; template struct RemoveConstRef{ typedef T type; }; template struct RemoveConstRef{ typedef T type; }; template struct IsBool { static const bool value = false; }; template<> struct IsBool { static const bool value = true; }; template void convertInto( std::string const& _source, T& _dest ) { std::stringstream ss; ss << _source; ss >> _dest; if( ss.fail() ) throw std::runtime_error( ""Unable to convert "" + _source + "" to destination type"" ); } inline void convertInto( std::string const& _source, std::string& _dest ) { _dest = _source; } inline void convertInto( std::string const& _source, bool& _dest ) { std::string sourceLC = _source; std::transform( sourceLC.begin(), sourceLC.end(), sourceLC.begin(), ::tolower ); if( sourceLC == ""y"" || sourceLC == ""1"" || sourceLC == ""true"" || sourceLC == ""yes"" || sourceLC == ""on"" ) _dest = true; else if( sourceLC == ""n"" || sourceLC == ""0"" || sourceLC == ""false"" || sourceLC == ""no"" || sourceLC == ""off"" ) _dest = false; else throw std::runtime_error( ""Expected a boolean value but did not recognise:\n '"" + _source + ""'"" ); } template struct IArgFunction { virtual ~IArgFunction() {} #ifdef CLARA_CONFIG_CPP11_GENERATED_METHODS IArgFunction() = default; IArgFunction( IArgFunction const& ) = default; #endif virtual void set( ConfigT& config, std::string const& value ) const = 0; virtual bool takesArg() const = 0; virtual IArgFunction* clone() const = 0; }; template class BoundArgFunction { public: BoundArgFunction() : functionObj( CLARA_NULL ) {} BoundArgFunction( IArgFunction* _functionObj ) : functionObj( _functionObj ) {} BoundArgFunction( BoundArgFunction const& other ) : functionObj( other.functionObj ? other.functionObj->clone() : CLARA_NULL ) {} BoundArgFunction& operator = ( BoundArgFunction const& other ) { IArgFunction* newFunctionObj = other.functionObj ? other.functionObj->clone() : CLARA_NULL; delete functionObj; functionObj = newFunctionObj; return *this; } ~BoundArgFunction() { delete functionObj; } void set( ConfigT& config, std::string const& value ) const { functionObj->set( config, value ); } bool takesArg() const { return functionObj->takesArg(); } bool isSet() const { return functionObj != CLARA_NULL; } private: IArgFunction* functionObj; }; template struct NullBinder : IArgFunction{ virtual void set( C&, std::string const& ) const {} virtual bool takesArg() const { return true; } virtual IArgFunction* clone() const { return new NullBinder( *this ); } }; template struct BoundDataMember : IArgFunction{ BoundDataMember( M C::* _member ) : member( _member ) {} virtual void set( C& p, std::string const& stringValue ) const { convertInto( stringValue, p.*member ); } virtual bool takesArg() const { return !IsBool::value; } virtual IArgFunction* clone() const { return new BoundDataMember( *this ); } M C::* member; }; template struct BoundUnaryMethod : IArgFunction{ BoundUnaryMethod( void (C::*_member)( M ) ) : member( _member ) {} virtual void set( C& p, std::string const& stringValue ) const { typename RemoveConstRef::type value; convertInto( stringValue, value ); (p.*member)( value ); } virtual bool takesArg() const { return !IsBool::value; } virtual IArgFunction* clone() const { return new BoundUnaryMethod( *this ); } void (C::*member)( M ); }; template struct BoundNullaryMethod : IArgFunction{ BoundNullaryMethod( void (C::*_member)() ) : member( _member ) {} virtual void set( C& p, std::string const& stringValue ) const { bool value; convertInto( stringValue, value ); if( value ) (p.*member)(); } virtual bool takesArg() const { return false; } virtual IArgFunction* clone() const { return new BoundNullaryMethod( *this ); } void (C::*member)(); }; template struct BoundUnaryFunction : IArgFunction{ BoundUnaryFunction( void (*_function)( C& ) ) : function( _function ) {} virtual void set( C& obj, std::string const& stringValue ) const { bool value; convertInto( stringValue, value ); if( value ) function( obj ); } virtual bool takesArg() const { return false; } virtual IArgFunction* clone() const { return new BoundUnaryFunction( *this ); } void (*function)( C& ); }; template struct BoundBinaryFunction : IArgFunction{ BoundBinaryFunction( void (*_function)( C&, T ) ) : function( _function ) {} virtual void set( C& obj, std::string const& stringValue ) const { typename RemoveConstRef::type value; convertInto( stringValue, value ); function( obj, value ); } virtual bool takesArg() const { return !IsBool::value; } virtual IArgFunction* clone() const { return new BoundBinaryFunction( *this ); } void (*function)( C&, T ); }; } // namespace Detail inline std::vector argsToVector( int argc, char const* const* const argv ) { std::vector args( static_cast( argc ) ); for( std::size_t i = 0; i < static_cast( argc ); ++i ) args[i] = argv[i]; return args; } class Parser { enum Mode { None, MaybeShortOpt, SlashOpt, ShortOpt, LongOpt, Positional }; Mode mode; std::size_t from; bool inQuotes; public: struct Token { enum Type { Positional, ShortOpt, LongOpt }; Token( Type _type, std::string const& _data ) : type( _type ), data( _data ) {} Type type; std::string data; }; Parser() : mode( None ), from( 0 ), inQuotes( false ){} void parseIntoTokens( std::vector const& args, std::vector& tokens ) { const std::string doubleDash = ""--""; for( std::size_t i = 1; i < args.size() && args[i] != doubleDash; ++i ) parseIntoTokens( args[i], tokens); } void parseIntoTokens( std::string const& arg, std::vector& tokens ) { for( std::size_t i = 0; i <= arg.size(); ++i ) { char c = arg[i]; if( c == '""' ) inQuotes = !inQuotes; mode = handleMode( i, c, arg, tokens ); } } Mode handleMode( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { switch( mode ) { case None: return handleNone( i, c ); case MaybeShortOpt: return handleMaybeShortOpt( i, c ); case ShortOpt: case LongOpt: case SlashOpt: return handleOpt( i, c, arg, tokens ); case Positional: return handlePositional( i, c, arg, tokens ); default: throw std::logic_error( ""Unknown mode"" ); } } Mode handleNone( std::size_t i, char c ) { if( inQuotes ) { from = i; return Positional; } switch( c ) { case '-': return MaybeShortOpt; #ifdef CLARA_PLATFORM_WINDOWS case '/': from = i+1; return SlashOpt; #endif default: from = i; return Positional; } } Mode handleMaybeShortOpt( std::size_t i, char c ) { switch( c ) { case '-': from = i+1; return LongOpt; default: from = i; return ShortOpt; } } Mode handleOpt( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { if( std::string( "":=\0"", 5 ).find( c ) == std::string::npos ) return mode; std::string optName = arg.substr( from, i-from ); if( mode == ShortOpt ) for( std::size_t j = 0; j < optName.size(); ++j ) tokens.push_back( Token( Token::ShortOpt, optName.substr( j, 1 ) ) ); else if( mode == SlashOpt && optName.size() == 1 ) tokens.push_back( Token( Token::ShortOpt, optName ) ); else tokens.push_back( Token( Token::LongOpt, optName ) ); return None; } Mode handlePositional( std::size_t i, char c, std::string const& arg, std::vector& tokens ) { if( inQuotes || std::string( ""\0"", 3 ).find( c ) == std::string::npos ) return mode; std::string data = arg.substr( from, i-from ); tokens.push_back( Token( Token::Positional, data ) ); return None; } }; template struct CommonArgProperties { CommonArgProperties() {} CommonArgProperties( Detail::BoundArgFunction const& _boundField ) : boundField( _boundField ) {} Detail::BoundArgFunction boundField; std::string description; std::string detail; std::string placeholder; // Only value if boundField takes an arg bool takesArg() const { return !placeholder.empty(); } void validate() const { if( !boundField.isSet() ) throw std::logic_error( ""option not bound"" ); } }; struct OptionArgProperties { std::vector shortNames; std::string longName; bool hasShortName( std::string const& shortName ) const { return std::find( shortNames.begin(), shortNames.end(), shortName ) != shortNames.end(); } bool hasLongName( std::string const& _longName ) const { return _longName == longName; } }; struct PositionalArgProperties { PositionalArgProperties() : position( -1 ) {} int position; // -1 means non-positional (floating) bool isFixedPositional() const { return position != -1; } }; template class CommandLine { struct Arg : CommonArgProperties, OptionArgProperties, PositionalArgProperties { Arg() {} Arg( Detail::BoundArgFunction const& _boundField ) : CommonArgProperties( _boundField ) {} using CommonArgProperties::placeholder; // !TBD std::string dbgName() const { if( !longName.empty() ) return ""--"" + longName; if( !shortNames.empty() ) return ""-"" + shortNames[0]; return ""positional args""; } std::string commands() const { std::ostringstream oss; bool first = true; std::vector::const_iterator it = shortNames.begin(), itEnd = shortNames.end(); for(; it != itEnd; ++it ) { if( first ) first = false; else oss << "", ""; oss << ""-"" << *it; } if( !longName.empty() ) { if( !first ) oss << "", ""; oss << ""--"" << longName; } if( !placeholder.empty() ) oss << "" <"" << placeholder << "">""; return oss.str(); } }; typedef CLARA_AUTO_PTR( Arg ) ArgAutoPtr; friend void addOptName( Arg& arg, std::string const& optName ) { if( optName.empty() ) return; if( Detail::startsWith( optName, ""--"" ) ) { if( !arg.longName.empty() ) throw std::logic_error( ""Only one long opt may be specified. '"" + arg.longName + ""' already specified, now attempting to add '"" + optName + ""'"" ); arg.longName = optName.substr( 2 ); } else if( Detail::startsWith( optName, ""-"" ) ) arg.shortNames.push_back( optName.substr( 1 ) ); else throw std::logic_error( ""option must begin with - or --. Option was: '"" + optName + ""'"" ); } friend void setPositionalArg( Arg& arg, int position ) { arg.position = position; } class ArgBuilder { public: ArgBuilder( Arg* arg ) : m_arg( arg ) {} // Bind a non-boolean data member (requires placeholder string) template void bind( M C::* field, std::string const& placeholder ) { m_arg->boundField = new Detail::BoundDataMember( field ); m_arg->placeholder = placeholder; } // Bind a boolean data member (no placeholder required) template void bind( bool C::* field ) { m_arg->boundField = new Detail::BoundDataMember( field ); } // Bind a method taking a single, non-boolean argument (requires a placeholder string) template void bind( void (C::* unaryMethod)( M ), std::string const& placeholder ) { m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); m_arg->placeholder = placeholder; } // Bind a method taking a single, boolean argument (no placeholder string required) template void bind( void (C::* unaryMethod)( bool ) ) { m_arg->boundField = new Detail::BoundUnaryMethod( unaryMethod ); } // Bind a method that takes no arguments (will be called if opt is present) template void bind( void (C::* nullaryMethod)() ) { m_arg->boundField = new Detail::BoundNullaryMethod( nullaryMethod ); } // Bind a free function taking a single argument - the object to operate on (no placeholder string required) template void bind( void (* unaryFunction)( C& ) ) { m_arg->boundField = new Detail::BoundUnaryFunction( unaryFunction ); } // Bind a free function taking a single argument - the object to operate on (requires a placeholder string) template void bind( void (* binaryFunction)( C&, T ), std::string const& placeholder ) { m_arg->boundField = new Detail::BoundBinaryFunction( binaryFunction ); m_arg->placeholder = placeholder; } ArgBuilder& describe( std::string const& description ) { m_arg->description = description; return *this; } ArgBuilder& detail( std::string const& detail ) { m_arg->detail = detail; return *this; } protected: Arg* m_arg; }; class OptBuilder : public ArgBuilder { public: OptBuilder( Arg* arg ) : ArgBuilder( arg ) {} OptBuilder( OptBuilder& other ) : ArgBuilder( other ) {} OptBuilder& operator[]( std::string const& optName ) { addOptName( *ArgBuilder::m_arg, optName ); return *this; } }; public: CommandLine() : m_boundProcessName( new Detail::NullBinder() ), m_highestSpecifiedArgPosition( 0 ), m_throwOnUnrecognisedTokens( false ) {} CommandLine( CommandLine const& other ) : m_boundProcessName( other.m_boundProcessName ), m_options ( other.m_options ), m_positionalArgs( other.m_positionalArgs ), m_highestSpecifiedArgPosition( other.m_highestSpecifiedArgPosition ), m_throwOnUnrecognisedTokens( other.m_throwOnUnrecognisedTokens ) { if( other.m_floatingArg.get() ) m_floatingArg.reset( new Arg( *other.m_floatingArg ) ); } CommandLine& setThrowOnUnrecognisedTokens( bool shouldThrow = true ) { m_throwOnUnrecognisedTokens = shouldThrow; return *this; } OptBuilder operator[]( std::string const& optName ) { m_options.push_back( Arg() ); addOptName( m_options.back(), optName ); OptBuilder builder( &m_options.back() ); return builder; } ArgBuilder operator[]( int position ) { m_positionalArgs.insert( std::make_pair( position, Arg() ) ); if( position > m_highestSpecifiedArgPosition ) m_highestSpecifiedArgPosition = position; setPositionalArg( m_positionalArgs[position], position ); ArgBuilder builder( &m_positionalArgs[position] ); return builder; } // Invoke this with the _ instance ArgBuilder operator[]( UnpositionalTag ) { if( m_floatingArg.get() ) throw std::logic_error( ""Only one unpositional argument can be added"" ); m_floatingArg.reset( new Arg() ); ArgBuilder builder( m_floatingArg.get() ); return builder; } template void bindProcessName( M C::* field ) { m_boundProcessName = new Detail::BoundDataMember( field ); } template void bindProcessName( void (C::*_unaryMethod)( M ) ) { m_boundProcessName = new Detail::BoundUnaryMethod( _unaryMethod ); } void optUsage( std::ostream& os, std::size_t indent = 0, std::size_t width = Detail::consoleWidth ) const { typename std::vector::const_iterator itBegin = m_options.begin(), itEnd = m_options.end(), it; std::size_t maxWidth = 0; for( it = itBegin; it != itEnd; ++it ) maxWidth = (std::max)( maxWidth, it->commands().size() ); for( it = itBegin; it != itEnd; ++it ) { Detail::Text usage( it->commands(), Detail::TextAttributes() .setWidth( maxWidth+indent ) .setIndent( indent ) ); Detail::Text desc( it->description, Detail::TextAttributes() .setWidth( width - maxWidth - 3 ) ); for( std::size_t i = 0; i < (std::max)( usage.size(), desc.size() ); ++i ) { std::string usageCol = i < usage.size() ? usage[i] : """"; os << usageCol; if( i < desc.size() && !desc[i].empty() ) os << std::string( indent + 2 + maxWidth - usageCol.size(), ' ' ) << desc[i]; os << ""\n""; } } } std::string optUsage() const { std::ostringstream oss; optUsage( oss ); return oss.str(); } void argSynopsis( std::ostream& os ) const { for( int i = 1; i <= m_highestSpecifiedArgPosition; ++i ) { if( i > 1 ) os << "" ""; typename std::map::const_iterator it = m_positionalArgs.find( i ); if( it != m_positionalArgs.end() ) os << ""<"" << it->second.placeholder << "">""; else if( m_floatingArg.get() ) os << ""<"" << m_floatingArg->placeholder << "">""; else throw std::logic_error( ""non consecutive positional arguments with no floating args"" ); } // !TBD No indication of mandatory args if( m_floatingArg.get() ) { if( m_highestSpecifiedArgPosition > 1 ) os << "" ""; os << ""[<"" << m_floatingArg->placeholder << ""> ...]""; } } std::string argSynopsis() const { std::ostringstream oss; argSynopsis( oss ); return oss.str(); } void usage( std::ostream& os, std::string const& procName ) const { validate(); os << ""usage:\n "" << procName << "" ""; argSynopsis( os ); if( !m_options.empty() ) { os << "" [options]\n\nwhere options are: \n""; optUsage( os, 2 ); } os << ""\n""; } std::string usage( std::string const& procName ) const { std::ostringstream oss; usage( oss, procName ); return oss.str(); } ConfigT parse( std::vector const& args ) const { ConfigT config; parseInto( args, config ); return config; } std::vector parseInto( std::vector const& args, ConfigT& config ) const { std::string processName = args[0]; std::size_t lastSlash = processName.find_last_of( ""/\\"" ); if( lastSlash != std::string::npos ) processName = processName.substr( lastSlash+1 ); m_boundProcessName.set( config, processName ); std::vector tokens; Parser parser; parser.parseIntoTokens( args, tokens ); return populate( tokens, config ); } std::vector populate( std::vector const& tokens, ConfigT& config ) const { validate(); std::vector unusedTokens = populateOptions( tokens, config ); unusedTokens = populateFixedArgs( unusedTokens, config ); unusedTokens = populateFloatingArgs( unusedTokens, config ); return unusedTokens; } std::vector populateOptions( std::vector const& tokens, ConfigT& config ) const { std::vector unusedTokens; std::vector errors; for( std::size_t i = 0; i < tokens.size(); ++i ) { Parser::Token const& token = tokens[i]; typename std::vector::const_iterator it = m_options.begin(), itEnd = m_options.end(); for(; it != itEnd; ++it ) { Arg const& arg = *it; try { if( ( token.type == Parser::Token::ShortOpt && arg.hasShortName( token.data ) ) || ( token.type == Parser::Token::LongOpt && arg.hasLongName( token.data ) ) ) { if( arg.takesArg() ) { if( i == tokens.size()-1 || tokens[i+1].type != Parser::Token::Positional ) errors.push_back( ""Expected argument to option: "" + token.data ); else arg.boundField.set( config, tokens[++i].data ); } else { arg.boundField.set( config, ""true"" ); } break; } } catch( std::exception& ex ) { errors.push_back( std::string( ex.what() ) + ""\n- while parsing: ("" + arg.commands() + "")"" ); } } if( it == itEnd ) { if( token.type == Parser::Token::Positional || !m_throwOnUnrecognisedTokens ) unusedTokens.push_back( token ); else if( errors.empty() && m_throwOnUnrecognisedTokens ) errors.push_back( ""unrecognised option: "" + token.data ); } } if( !errors.empty() ) { std::ostringstream oss; for( std::vector::const_iterator it = errors.begin(), itEnd = errors.end(); it != itEnd; ++it ) { if( it != errors.begin() ) oss << ""\n""; oss << *it; } throw std::runtime_error( oss.str() ); } return unusedTokens; } std::vector populateFixedArgs( std::vector const& tokens, ConfigT& config ) const { std::vector unusedTokens; int position = 1; for( std::size_t i = 0; i < tokens.size(); ++i ) { Parser::Token const& token = tokens[i]; typename std::map::const_iterator it = m_positionalArgs.find( position ); if( it != m_positionalArgs.end() ) it->second.boundField.set( config, token.data ); else unusedTokens.push_back( token ); if( token.type == Parser::Token::Positional ) position++; } return unusedTokens; } std::vector populateFloatingArgs( std::vector const& tokens, ConfigT& config ) const { if( !m_floatingArg.get() ) return tokens; std::vector unusedTokens; for( std::size_t i = 0; i < tokens.size(); ++i ) { Parser::Token const& token = tokens[i]; if( token.type == Parser::Token::Positional ) m_floatingArg->boundField.set( config, token.data ); else unusedTokens.push_back( token ); } return unusedTokens; } void validate() const { if( m_options.empty() && m_positionalArgs.empty() && !m_floatingArg.get() ) throw std::logic_error( ""No options or arguments specified"" ); for( typename std::vector::const_iterator it = m_options.begin(), itEnd = m_options.end(); it != itEnd; ++it ) it->validate(); } private: Detail::BoundArgFunction m_boundProcessName; std::vector m_options; std::map m_positionalArgs; ArgAutoPtr m_floatingArg; int m_highestSpecifiedArgPosition; bool m_throwOnUnrecognisedTokens; }; } // end namespace Clara STITCH_CLARA_CLOSE_NAMESPACE #undef STITCH_CLARA_OPEN_NAMESPACE #undef STITCH_CLARA_CLOSE_NAMESPACE #endif // TWOBLUECUBES_CLARA_H_INCLUDED #undef STITCH_CLARA_OPEN_NAMESPACE // Restore Clara's value for console width, if present #ifdef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #define CLARA_CONFIG_CONSOLE_WIDTH CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #undef CATCH_TEMP_CLARA_CONFIG_CONSOLE_WIDTH #endif #include namespace Catch { inline void abortAfterFirst( ConfigData& config ) { config.abortAfter = 1; } inline void abortAfterX( ConfigData& config, int x ) { if( x < 1 ) throw std::runtime_error( ""Value after -x or --abortAfter must be greater than zero"" ); config.abortAfter = x; } inline void addTestOrTags( ConfigData& config, std::string const& _testSpec ) { config.testsOrTags.push_back( _testSpec ); } inline void addReporterName( ConfigData& config, std::string const& _reporterName ) { config.reporterNames.push_back( _reporterName ); } inline void addWarning( ConfigData& config, std::string const& _warning ) { if( _warning == ""NoAssertions"" ) config.warnings = static_cast( config.warnings | WarnAbout::NoAssertions ); else throw std::runtime_error( ""Unrecognised warning: '"" + _warning + ""'"" ); } inline void setOrder( ConfigData& config, std::string const& order ) { if( startsWith( ""declared"", order ) ) config.runOrder = RunTests::InDeclarationOrder; else if( startsWith( ""lexical"", order ) ) config.runOrder = RunTests::InLexicographicalOrder; else if( startsWith( ""random"", order ) ) config.runOrder = RunTests::InRandomOrder; else throw std::runtime_error( ""Unrecognised ordering: '"" + order + ""'"" ); } inline void setRngSeed( ConfigData& config, std::string const& seed ) { if( seed == ""time"" ) { config.rngSeed = static_cast( std::time(0) ); } else { std::stringstream ss; ss << seed; ss >> config.rngSeed; if( ss.fail() ) throw std::runtime_error( ""Argment to --rng-seed should be the word 'time' or a number"" ); } } inline void setVerbosity( ConfigData& config, int level ) { // !TBD: accept strings? config.verbosity = static_cast( level ); } inline void setShowDurations( ConfigData& config, bool _showDurations ) { config.showDurations = _showDurations ? ShowDurations::Always : ShowDurations::Never; } inline void setUseColour( ConfigData& config, std::string const& value ) { std::string mode = toLower( value ); if( mode == ""yes"" ) config.useColour = UseColour::Yes; else if( mode == ""no"" ) config.useColour = UseColour::No; else if( mode == ""auto"" ) config.useColour = UseColour::Auto; else throw std::runtime_error( ""colour mode must be one of: auto, yes or no"" ); } inline void forceColour( ConfigData& config ) { config.useColour = UseColour::Yes; } inline void loadTestNamesFromFile( ConfigData& config, std::string const& _filename ) { std::ifstream f( _filename.c_str() ); if( !f.is_open() ) throw std::domain_error( ""Unable to load input file: "" + _filename ); std::string line; while( std::getline( f, line ) ) { line = trim(line); if( !line.empty() && !startsWith( line, ""#"" ) ) addTestOrTags( config, ""\"""" + line + ""\"","" ); } } inline Clara::CommandLine makeCommandLineParser() { using namespace Clara; CommandLine cli; cli.bindProcessName( &ConfigData::processName ); cli[""-?""][""-h""][""--help""] .describe( ""display usage information"" ) .bind( &ConfigData::showHelp ); cli[""-l""][""--list-tests""] .describe( ""list all/matching test cases"" ) .bind( &ConfigData::listTests ); cli[""-t""][""--list-tags""] .describe( ""list all/matching tags"" ) .bind( &ConfigData::listTags ); cli[""-s""][""--success""] .describe( ""include successful tests in output"" ) .bind( &ConfigData::showSuccessfulTests ); cli[""-b""][""--break""] .describe( ""break into debugger on failure"" ) .bind( &ConfigData::shouldDebugBreak ); cli[""-e""][""--nothrow""] .describe( ""skip exception tests"" ) .bind( &ConfigData::noThrow ); cli[""-i""][""--invisibles""] .describe( ""show invisibles (tabs, newlines)"" ) .bind( &ConfigData::showInvisibles ); cli[""-o""][""--out""] .describe( ""output filename"" ) .bind( &ConfigData::outputFilename, ""filename"" ); cli[""-r""][""--reporter""] // .placeholder( ""name[:filename]"" ) .describe( ""reporter to use (defaults to console)"" ) .bind( &addReporterName, ""name"" ); cli[""-n""][""--name""] .describe( ""suite name"" ) .bind( &ConfigData::name, ""name"" ); cli[""-a""][""--abort""] .describe( ""abort at first failure"" ) .bind( &abortAfterFirst ); cli[""-x""][""--abortx""] .describe( ""abort after x failures"" ) .bind( &abortAfterX, ""no. failures"" ); cli[""-w""][""--warn""] .describe( ""enable warnings"" ) .bind( &addWarning, ""warning name"" ); // - needs updating if reinstated // cli.into( &setVerbosity ) // .describe( ""level of verbosity (0=no output)"" ) // .shortOpt( ""v"") // .longOpt( ""verbosity"" ) // .placeholder( ""level"" ); cli[_] .describe( ""which test or tests to use"" ) .bind( &addTestOrTags, ""test name, pattern or tags"" ); cli[""-d""][""--durations""] .describe( ""show test durations"" ) .bind( &setShowDurations, ""yes|no"" ); cli[""-f""][""--input-file""] .describe( ""load test names to run from a file"" ) .bind( &loadTestNamesFromFile, ""filename"" ); cli[""-#""][""--filenames-as-tags""] .describe( ""adds a tag for the filename"" ) .bind( &ConfigData::filenamesAsTags ); // Less common commands which don't have a short form cli[""--list-test-names-only""] .describe( ""list all/matching test cases names only"" ) .bind( &ConfigData::listTestNamesOnly ); cli[""--list-reporters""] .describe( ""list all reporters"" ) .bind( &ConfigData::listReporters ); cli[""--order""] .describe( ""test case order (defaults to decl)"" ) .bind( &setOrder, ""decl|lex|rand"" ); cli[""--rng-seed""] .describe( ""set a specific seed for random numbers"" ) .bind( &setRngSeed, ""'time'|number"" ); cli[""--force-colour""] .describe( ""force colourised output (deprecated)"" ) .bind( &forceColour ); cli[""--use-colour""] .describe( ""should output be colourised"" ) .bind( &setUseColour, ""yes|no"" ); return cli; } } // end namespace Catch // #included from: internal/catch_list.hpp #define TWOBLUECUBES_CATCH_LIST_HPP_INCLUDED // #included from: catch_text.h #define TWOBLUECUBES_CATCH_TEXT_H_INCLUDED #define TBC_TEXT_FORMAT_CONSOLE_WIDTH CATCH_CONFIG_CONSOLE_WIDTH #define CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE Catch // #included from: ../external/tbc_text_format.h // Only use header guard if we are not using an outer namespace #ifndef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE # ifdef TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED # ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED # define TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED # endif # else # define TWOBLUECUBES_TEXT_FORMAT_H_INCLUDED # endif #endif #ifndef TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED #include #include #include // Use optional outer namespace #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE namespace CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE { #endif namespace Tbc { #ifdef TBC_TEXT_FORMAT_CONSOLE_WIDTH const unsigned int consoleWidth = TBC_TEXT_FORMAT_CONSOLE_WIDTH; #else const unsigned int consoleWidth = 80; #endif struct TextAttributes { TextAttributes() : initialIndent( std::string::npos ), indent( 0 ), width( consoleWidth-1 ), tabChar( '\t' ) {} TextAttributes& setInitialIndent( std::size_t _value ) { initialIndent = _value; return *this; } TextAttributes& setIndent( std::size_t _value ) { indent = _value; return *this; } TextAttributes& setWidth( std::size_t _value ) { width = _value; return *this; } TextAttributes& setTabChar( char _value ) { tabChar = _value; return *this; } std::size_t initialIndent; // indent of first line, or npos std::size_t indent; // indent of subsequent lines, or all if initialIndent is npos std::size_t width; // maximum width of text, including indent. Longer text will wrap char tabChar; // If this char is seen the indent is changed to current pos }; class Text { public: Text( std::string const& _str, TextAttributes const& _attr = TextAttributes() ) : attr( _attr ) { std::string wrappableChars = "" [({.,/|\\-""; std::size_t indent = _attr.initialIndent != std::string::npos ? _attr.initialIndent : _attr.indent; std::string remainder = _str; while( !remainder.empty() ) { if( lines.size() >= 1000 ) { lines.push_back( ""... message truncated due to excessive size"" ); return; } std::size_t tabPos = std::string::npos; std::size_t width = (std::min)( remainder.size(), _attr.width - indent ); std::size_t pos = remainder.find_first_of( '\n' ); if( pos <= width ) { width = pos; } pos = remainder.find_last_of( _attr.tabChar, width ); if( pos != std::string::npos ) { tabPos = pos; if( remainder[width] == '\n' ) width--; remainder = remainder.substr( 0, tabPos ) + remainder.substr( tabPos+1 ); } if( width == remainder.size() ) { spliceLine( indent, remainder, width ); } else if( remainder[width] == '\n' ) { spliceLine( indent, remainder, width ); if( width <= 1 || remainder.size() != 1 ) remainder = remainder.substr( 1 ); indent = _attr.indent; } else { pos = remainder.find_last_of( wrappableChars, width ); if( pos != std::string::npos && pos > 0 ) { spliceLine( indent, remainder, pos ); if( remainder[0] == ' ' ) remainder = remainder.substr( 1 ); } else { spliceLine( indent, remainder, width-1 ); lines.back() += ""-""; } if( lines.size() == 1 ) indent = _attr.indent; if( tabPos != std::string::npos ) indent += tabPos; } } } void spliceLine( std::size_t _indent, std::string& _remainder, std::size_t _pos ) { lines.push_back( std::string( _indent, ' ' ) + _remainder.substr( 0, _pos ) ); _remainder = _remainder.substr( _pos ); } typedef std::vector::const_iterator const_iterator; const_iterator begin() const { return lines.begin(); } const_iterator end() const { return lines.end(); } std::string const& last() const { return lines.back(); } std::size_t size() const { return lines.size(); } std::string const& operator[]( std::size_t _index ) const { return lines[_index]; } std::string toString() const { std::ostringstream oss; oss << *this; return oss.str(); } inline friend std::ostream& operator << ( std::ostream& _stream, Text const& _text ) { for( Text::const_iterator it = _text.begin(), itEnd = _text.end(); it != itEnd; ++it ) { if( it != _text.begin() ) _stream << ""\n""; _stream << *it; } return _stream; } private: std::string str; TextAttributes attr; std::vector lines; }; } // end namespace Tbc #ifdef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE } // end outer namespace #endif #endif // TWOBLUECUBES_TEXT_FORMAT_H_ALREADY_INCLUDED #undef CLICHE_TBC_TEXT_FORMAT_OUTER_NAMESPACE namespace Catch { using Tbc::Text; using Tbc::TextAttributes; } // #included from: catch_console_colour.hpp #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_HPP_INCLUDED namespace Catch { struct Colour { enum Code { None = 0, White, Red, Green, Blue, Cyan, Yellow, Grey, Bright = 0x10, BrightRed = Bright | Red, BrightGreen = Bright | Green, LightGrey = Bright | Grey, BrightWhite = Bright | White, // By intention FileName = LightGrey, Warning = Yellow, ResultError = BrightRed, ResultSuccess = BrightGreen, ResultExpectedFailure = Warning, Error = BrightRed, Success = Green, OriginalExpression = Cyan, ReconstructedExpression = Yellow, SecondaryText = LightGrey, Headers = White }; // Use constructed object for RAII guard Colour( Code _colourCode ); Colour( Colour const& other ); ~Colour(); // Use static method for one-shot changes static void use( Code _colourCode ); private: bool m_moved; }; inline std::ostream& operator << ( std::ostream& os, Colour const& ) { return os; } } // end namespace Catch // #included from: catch_interfaces_reporter.h #define TWOBLUECUBES_CATCH_INTERFACES_REPORTER_H_INCLUDED #include #include #include #include namespace Catch { struct ReporterConfig { explicit ReporterConfig( Ptr const& _fullConfig ) : m_stream( &_fullConfig->stream() ), m_fullConfig( _fullConfig ) {} ReporterConfig( Ptr const& _fullConfig, std::ostream& _stream ) : m_stream( &_stream ), m_fullConfig( _fullConfig ) {} std::ostream& stream() const { return *m_stream; } Ptr fullConfig() const { return m_fullConfig; } private: std::ostream* m_stream; Ptr m_fullConfig; }; struct ReporterPreferences { ReporterPreferences() : shouldRedirectStdOut( false ) {} bool shouldRedirectStdOut; }; template struct LazyStat : Option { LazyStat() : used( false ) {} LazyStat& operator=( T const& _value ) { Option::operator=( _value ); used = false; return *this; } void reset() { Option::reset(); used = false; } bool used; }; struct TestRunInfo { TestRunInfo( std::string const& _name ) : name( _name ) {} std::string name; }; struct GroupInfo { GroupInfo( std::string const& _name, std::size_t _groupIndex, std::size_t _groupsCount ) : name( _name ), groupIndex( _groupIndex ), groupsCounts( _groupsCount ) {} std::string name; std::size_t groupIndex; std::size_t groupsCounts; }; struct AssertionStats { AssertionStats( AssertionResult const& _assertionResult, std::vector const& _infoMessages, Totals const& _totals ) : assertionResult( _assertionResult ), infoMessages( _infoMessages ), totals( _totals ) { if( assertionResult.hasMessage() ) { // Copy message into messages list. // !TBD This should have been done earlier, somewhere MessageBuilder builder( assertionResult.getTestMacroName(), assertionResult.getSourceInfo(), assertionResult.getResultType() ); builder << assertionResult.getMessage(); builder.m_info.message = builder.m_stream.str(); infoMessages.push_back( builder.m_info ); } } virtual ~AssertionStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS AssertionStats( AssertionStats const& ) = default; AssertionStats( AssertionStats && ) = default; AssertionStats& operator = ( AssertionStats const& ) = default; AssertionStats& operator = ( AssertionStats && ) = default; # endif AssertionResult assertionResult; std::vector infoMessages; Totals totals; }; struct SectionStats { SectionStats( SectionInfo const& _sectionInfo, Counts const& _assertions, double _durationInSeconds, bool _missingAssertions ) : sectionInfo( _sectionInfo ), assertions( _assertions ), durationInSeconds( _durationInSeconds ), missingAssertions( _missingAssertions ) {} virtual ~SectionStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS SectionStats( SectionStats const& ) = default; SectionStats( SectionStats && ) = default; SectionStats& operator = ( SectionStats const& ) = default; SectionStats& operator = ( SectionStats && ) = default; # endif SectionInfo sectionInfo; Counts assertions; double durationInSeconds; bool missingAssertions; }; struct TestCaseStats { TestCaseStats( TestCaseInfo const& _testInfo, Totals const& _totals, std::string const& _stdOut, std::string const& _stdErr, bool _aborting ) : testInfo( _testInfo ), totals( _totals ), stdOut( _stdOut ), stdErr( _stdErr ), aborting( _aborting ) {} virtual ~TestCaseStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS TestCaseStats( TestCaseStats const& ) = default; TestCaseStats( TestCaseStats && ) = default; TestCaseStats& operator = ( TestCaseStats const& ) = default; TestCaseStats& operator = ( TestCaseStats && ) = default; # endif TestCaseInfo testInfo; Totals totals; std::string stdOut; std::string stdErr; bool aborting; }; struct TestGroupStats { TestGroupStats( GroupInfo const& _groupInfo, Totals const& _totals, bool _aborting ) : groupInfo( _groupInfo ), totals( _totals ), aborting( _aborting ) {} TestGroupStats( GroupInfo const& _groupInfo ) : groupInfo( _groupInfo ), aborting( false ) {} virtual ~TestGroupStats(); # ifdef CATCH_CONFIG_CPP11_GENERATED_METHODS TestGroupStats( TestGroupStats const& ) = default; TestGroupStats( TestGroupStats && ) = default; TestGroupStats& operator = ( TestGroupStats const& ) = default; TestGroupStats& operator = ( TestGroupStats && ) = default; # endif GroupInfo groupInfo; Totals totals; bool aborting; }; struct TestRunStats { TestRunStats( TestRunInfo const& _runInfo, Totals const& _totals, bool _aborting ) : runInfo( _runInfo ), totals( _totals ), aborting( _aborting ) {} virtual ~TestRunStats(); # ifndef CATCH_CONFIG_CPP11_GENERATED_METHODS TestRunStats( TestRunStats const& _other ) : runInfo( _other.runInfo ), totals( _other.totals ), aborting( _other.aborting ) {} # else TestRunStats( TestRunStats const& ) = default; TestRunStats( TestRunStats && ) = default; TestRunStats& operator = ( TestRunStats const& ) = default; TestRunStats& operator = ( TestRunStats && ) = default; # endif TestRunInfo runInfo; Totals totals; bool aborting; }; class MultipleReporters; struct IStreamingReporter : IShared { virtual ~IStreamingReporter(); // Implementing class must also provide the following static method: // static std::string getDescription(); virtual ReporterPreferences getPreferences() const = 0; virtual void noMatchingTestCases( std::string const& spec ) = 0; virtual void testRunStarting( TestRunInfo const& testRunInfo ) = 0; virtual void testGroupStarting( GroupInfo const& groupInfo ) = 0; virtual void testCaseStarting( TestCaseInfo const& testInfo ) = 0; virtual void sectionStarting( SectionInfo const& sectionInfo ) = 0; virtual void assertionStarting( AssertionInfo const& assertionInfo ) = 0; // The return value indicates if the messages buffer should be cleared: virtual bool assertionEnded( AssertionStats const& assertionStats ) = 0; virtual void sectionEnded( SectionStats const& sectionStats ) = 0; virtual void testCaseEnded( TestCaseStats const& testCaseStats ) = 0; virtual void testGroupEnded( TestGroupStats const& testGroupStats ) = 0; virtual void testRunEnded( TestRunStats const& testRunStats ) = 0; virtual void skipTest( TestCaseInfo const& testInfo ) = 0; virtual MultipleReporters* tryAsMulti() { return CATCH_NULL; } }; struct IReporterFactory : IShared { virtual ~IReporterFactory(); virtual IStreamingReporter* create( ReporterConfig const& config ) const = 0; virtual std::string getDescription() const = 0; }; struct IReporterRegistry { typedef std::map > FactoryMap; typedef std::vector > Listeners; virtual ~IReporterRegistry(); virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const = 0; virtual FactoryMap const& getFactories() const = 0; virtual Listeners const& getListeners() const = 0; }; Ptr addReporter( Ptr const& existingReporter, Ptr const& additionalReporter ); } #include #include namespace Catch { inline std::size_t listTests( Config const& config ) { TestSpec testSpec = config.testSpec(); if( config.testSpec().hasFilters() ) Catch::cout() << ""Matching test cases:\n""; else { Catch::cout() << ""All available test cases:\n""; testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( ""*"" ).testSpec(); } std::size_t matchedTests = 0; TextAttributes nameAttr, tagsAttr; nameAttr.setInitialIndent( 2 ).setIndent( 4 ); tagsAttr.setIndent( 6 ); std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); it != itEnd; ++it ) { matchedTests++; TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); Colour::Code colour = testCaseInfo.isHidden() ? Colour::SecondaryText : Colour::None; Colour colourGuard( colour ); Catch::cout() << Text( testCaseInfo.name, nameAttr ) << std::endl; if( !testCaseInfo.tags.empty() ) Catch::cout() << Text( testCaseInfo.tagsAsString, tagsAttr ) << std::endl; } if( !config.testSpec().hasFilters() ) Catch::cout() << pluralise( matchedTests, ""test case"" ) << ""\n"" << std::endl; else Catch::cout() << pluralise( matchedTests, ""matching test case"" ) << ""\n"" << std::endl; return matchedTests; } inline std::size_t listTestsNamesOnly( Config const& config ) { TestSpec testSpec = config.testSpec(); if( !config.testSpec().hasFilters() ) testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( ""*"" ).testSpec(); std::size_t matchedTests = 0; std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); it != itEnd; ++it ) { matchedTests++; TestCaseInfo const& testCaseInfo = it->getTestCaseInfo(); Catch::cout() << testCaseInfo.name << std::endl; } return matchedTests; } struct TagInfo { TagInfo() : count ( 0 ) {} void add( std::string const& spelling ) { ++count; spellings.insert( spelling ); } std::string all() const { std::string out; for( std::set::const_iterator it = spellings.begin(), itEnd = spellings.end(); it != itEnd; ++it ) out += ""["" + *it + ""]""; return out; } std::set spellings; std::size_t count; }; inline std::size_t listTags( Config const& config ) { TestSpec testSpec = config.testSpec(); if( config.testSpec().hasFilters() ) Catch::cout() << ""Tags for matching test cases:\n""; else { Catch::cout() << ""All available tags:\n""; testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( ""*"" ).testSpec(); } std::map tagCounts; std::vector matchedTestCases = filterTests( getAllTestCasesSorted( config ), testSpec, config ); for( std::vector::const_iterator it = matchedTestCases.begin(), itEnd = matchedTestCases.end(); it != itEnd; ++it ) { for( std::set::const_iterator tagIt = it->getTestCaseInfo().tags.begin(), tagItEnd = it->getTestCaseInfo().tags.end(); tagIt != tagItEnd; ++tagIt ) { std::string tagName = *tagIt; std::string lcaseTagName = toLower( tagName ); std::map::iterator countIt = tagCounts.find( lcaseTagName ); if( countIt == tagCounts.end() ) countIt = tagCounts.insert( std::make_pair( lcaseTagName, TagInfo() ) ).first; countIt->second.add( tagName ); } } for( std::map::const_iterator countIt = tagCounts.begin(), countItEnd = tagCounts.end(); countIt != countItEnd; ++countIt ) { std::ostringstream oss; oss << "" "" << std::setw(2) << countIt->second.count << "" ""; Text wrapper( countIt->second.all(), TextAttributes() .setInitialIndent( 0 ) .setIndent( oss.str().size() ) .setWidth( CATCH_CONFIG_CONSOLE_WIDTH-10 ) ); Catch::cout() << oss.str() << wrapper << ""\n""; } Catch::cout() << pluralise( tagCounts.size(), ""tag"" ) << ""\n"" << std::endl; return tagCounts.size(); } inline std::size_t listReporters( Config const& /*config*/ ) { Catch::cout() << ""Available reporters:\n""; IReporterRegistry::FactoryMap const& factories = getRegistryHub().getReporterRegistry().getFactories(); IReporterRegistry::FactoryMap::const_iterator itBegin = factories.begin(), itEnd = factories.end(), it; std::size_t maxNameLen = 0; for(it = itBegin; it != itEnd; ++it ) maxNameLen = (std::max)( maxNameLen, it->first.size() ); for(it = itBegin; it != itEnd; ++it ) { Text wrapper( it->second->getDescription(), TextAttributes() .setInitialIndent( 0 ) .setIndent( 7+maxNameLen ) .setWidth( CATCH_CONFIG_CONSOLE_WIDTH - maxNameLen-8 ) ); Catch::cout() << "" "" << it->first << "":"" << std::string( maxNameLen - it->first.size() + 2, ' ' ) << wrapper << ""\n""; } Catch::cout() << std::endl; return factories.size(); } inline Option list( Config const& config ) { Option listedCount; if( config.listTests() ) listedCount = listedCount.valueOr(0) + listTests( config ); if( config.listTestNamesOnly() ) listedCount = listedCount.valueOr(0) + listTestsNamesOnly( config ); if( config.listTags() ) listedCount = listedCount.valueOr(0) + listTags( config ); if( config.listReporters() ) listedCount = listedCount.valueOr(0) + listReporters( config ); return listedCount; } } // end namespace Catch // #included from: internal/catch_run_context.hpp #define TWOBLUECUBES_CATCH_RUNNER_IMPL_HPP_INCLUDED // #included from: catch_test_case_tracker.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_TRACKER_HPP_INCLUDED #include #include #include #include namespace Catch { namespace TestCaseTracking { struct ITracker : SharedImpl<> { virtual ~ITracker(); // static queries virtual std::string name() const = 0; // dynamic queries virtual bool isComplete() const = 0; // Successfully completed or failed virtual bool isSuccessfullyCompleted() const = 0; virtual bool isOpen() const = 0; // Started but not complete virtual bool hasChildren() const = 0; virtual ITracker& parent() = 0; // actions virtual void close() = 0; // Successfully complete virtual void fail() = 0; virtual void markAsNeedingAnotherRun() = 0; virtual void addChild( Ptr const& child ) = 0; virtual ITracker* findChild( std::string const& name ) = 0; virtual void openChild() = 0; // Debug/ checking virtual bool isSectionTracker() const = 0; virtual bool isIndexTracker() const = 0; }; class TrackerContext { enum RunState { NotStarted, Executing, CompletedCycle }; Ptr m_rootTracker; ITracker* m_currentTracker; RunState m_runState; public: static TrackerContext& instance() { static TrackerContext s_instance; return s_instance; } TrackerContext() : m_currentTracker( CATCH_NULL ), m_runState( NotStarted ) {} ITracker& startRun(); void endRun() { m_rootTracker.reset(); m_currentTracker = CATCH_NULL; m_runState = NotStarted; } void startCycle() { m_currentTracker = m_rootTracker.get(); m_runState = Executing; } void completeCycle() { m_runState = CompletedCycle; } bool completedCycle() const { return m_runState == CompletedCycle; } ITracker& currentTracker() { return *m_currentTracker; } void setCurrentTracker( ITracker* tracker ) { m_currentTracker = tracker; } }; class TrackerBase : public ITracker { protected: enum CycleState { NotStarted, Executing, ExecutingChildren, NeedsAnotherRun, CompletedSuccessfully, Failed }; class TrackerHasName { std::string m_name; public: TrackerHasName( std::string const& name ) : m_name( name ) {} bool operator ()( Ptr const& tracker ) { return tracker->name() == m_name; } }; typedef std::vector > Children; std::string m_name; TrackerContext& m_ctx; ITracker* m_parent; Children m_children; CycleState m_runState; public: TrackerBase( std::string const& name, TrackerContext& ctx, ITracker* parent ) : m_name( name ), m_ctx( ctx ), m_parent( parent ), m_runState( NotStarted ) {} virtual ~TrackerBase(); virtual std::string name() const CATCH_OVERRIDE { return m_name; } virtual bool isComplete() const CATCH_OVERRIDE { return m_runState == CompletedSuccessfully || m_runState == Failed; } virtual bool isSuccessfullyCompleted() const CATCH_OVERRIDE { return m_runState == CompletedSuccessfully; } virtual bool isOpen() const CATCH_OVERRIDE { return m_runState != NotStarted && !isComplete(); } virtual bool hasChildren() const CATCH_OVERRIDE { return !m_children.empty(); } virtual void addChild( Ptr const& child ) CATCH_OVERRIDE { m_children.push_back( child ); } virtual ITracker* findChild( std::string const& name ) CATCH_OVERRIDE { Children::const_iterator it = std::find_if( m_children.begin(), m_children.end(), TrackerHasName( name ) ); return( it != m_children.end() ) ? it->get() : CATCH_NULL; } virtual ITracker& parent() CATCH_OVERRIDE { assert( m_parent ); // Should always be non-null except for root return *m_parent; } virtual void openChild() CATCH_OVERRIDE { if( m_runState != ExecutingChildren ) { m_runState = ExecutingChildren; if( m_parent ) m_parent->openChild(); } } virtual bool isSectionTracker() const CATCH_OVERRIDE { return false; } virtual bool isIndexTracker() const CATCH_OVERRIDE { return false; } void open() { m_runState = Executing; moveToThis(); if( m_parent ) m_parent->openChild(); } virtual void close() CATCH_OVERRIDE { // Close any still open children (e.g. generators) while( &m_ctx.currentTracker() != this ) m_ctx.currentTracker().close(); switch( m_runState ) { case NotStarted: case CompletedSuccessfully: case Failed: throw std::logic_error( ""Illogical state"" ); case NeedsAnotherRun: break;; case Executing: m_runState = CompletedSuccessfully; break; case ExecutingChildren: if( m_children.empty() || m_children.back()->isComplete() ) m_runState = CompletedSuccessfully; break; default: throw std::logic_error( ""Unexpected state"" ); } moveToParent(); m_ctx.completeCycle(); } virtual void fail() CATCH_OVERRIDE { m_runState = Failed; if( m_parent ) m_parent->markAsNeedingAnotherRun(); moveToParent(); m_ctx.completeCycle(); } virtual void markAsNeedingAnotherRun() CATCH_OVERRIDE { m_runState = NeedsAnotherRun; } private: void moveToParent() { assert( m_parent ); m_ctx.setCurrentTracker( m_parent ); } void moveToThis() { m_ctx.setCurrentTracker( this ); } }; class SectionTracker : public TrackerBase { public: SectionTracker( std::string const& name, TrackerContext& ctx, ITracker* parent ) : TrackerBase( name, ctx, parent ) {} virtual ~SectionTracker(); virtual bool isSectionTracker() const CATCH_OVERRIDE { return true; } static SectionTracker& acquire( TrackerContext& ctx, std::string const& name ) { SectionTracker* section = CATCH_NULL; ITracker& currentTracker = ctx.currentTracker(); if( ITracker* childTracker = currentTracker.findChild( name ) ) { assert( childTracker ); assert( childTracker->isSectionTracker() ); section = static_cast( childTracker ); } else { section = new SectionTracker( name, ctx, ¤tTracker ); currentTracker.addChild( section ); } if( !ctx.completedCycle() && !section->isComplete() ) { section->open(); } return *section; } }; class IndexTracker : public TrackerBase { int m_size; int m_index; public: IndexTracker( std::string const& name, TrackerContext& ctx, ITracker* parent, int size ) : TrackerBase( name, ctx, parent ), m_size( size ), m_index( -1 ) {} virtual ~IndexTracker(); virtual bool isIndexTracker() const CATCH_OVERRIDE { return true; } static IndexTracker& acquire( TrackerContext& ctx, std::string const& name, int size ) { IndexTracker* tracker = CATCH_NULL; ITracker& currentTracker = ctx.currentTracker(); if( ITracker* childTracker = currentTracker.findChild( name ) ) { assert( childTracker ); assert( childTracker->isIndexTracker() ); tracker = static_cast( childTracker ); } else { tracker = new IndexTracker( name, ctx, ¤tTracker, size ); currentTracker.addChild( tracker ); } if( !ctx.completedCycle() && !tracker->isComplete() ) { if( tracker->m_runState != ExecutingChildren && tracker->m_runState != NeedsAnotherRun ) tracker->moveNext(); tracker->open(); } return *tracker; } int index() const { return m_index; } void moveNext() { m_index++; m_children.clear(); } virtual void close() CATCH_OVERRIDE { TrackerBase::close(); if( m_runState == CompletedSuccessfully && m_index < m_size-1 ) m_runState = Executing; } }; inline ITracker& TrackerContext::startRun() { m_rootTracker = new SectionTracker( ""{root}"", *this, CATCH_NULL ); m_currentTracker = CATCH_NULL; m_runState = Executing; return *m_rootTracker; } } // namespace TestCaseTracking using TestCaseTracking::ITracker; using TestCaseTracking::TrackerContext; using TestCaseTracking::SectionTracker; using TestCaseTracking::IndexTracker; } // namespace Catch // #included from: catch_fatal_condition.hpp #define TWOBLUECUBES_CATCH_FATAL_CONDITION_H_INCLUDED namespace Catch { // Report the error condition then exit the process inline void fatal( std::string const& message, int exitCode ) { IContext& context = Catch::getCurrentContext(); IResultCapture* resultCapture = context.getResultCapture(); resultCapture->handleFatalErrorCondition( message ); if( Catch::alwaysTrue() ) // avoids ""no return"" warnings exit( exitCode ); } } // namespace Catch #if defined ( CATCH_PLATFORM_WINDOWS ) ///////////////////////////////////////// namespace Catch { struct FatalConditionHandler { void reset() {} }; } // namespace Catch #else // Not Windows - assumed to be POSIX compatible ////////////////////////// #include namespace Catch { struct SignalDefs { int id; const char* name; }; extern SignalDefs signalDefs[]; SignalDefs signalDefs[] = { { SIGINT, ""SIGINT - Terminal interrupt signal"" }, { SIGILL, ""SIGILL - Illegal instruction signal"" }, { SIGFPE, ""SIGFPE - Floating point error signal"" }, { SIGSEGV, ""SIGSEGV - Segmentation violation signal"" }, { SIGTERM, ""SIGTERM - Termination request signal"" }, { SIGABRT, ""SIGABRT - Abort (abnormal termination) signal"" } }; struct FatalConditionHandler { static void handleSignal( int sig ) { for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) if( sig == signalDefs[i].id ) fatal( signalDefs[i].name, -sig ); fatal( """", -sig ); } FatalConditionHandler() : m_isSet( true ) { for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) signal( signalDefs[i].id, handleSignal ); } ~FatalConditionHandler() { reset(); } void reset() { if( m_isSet ) { for( std::size_t i = 0; i < sizeof(signalDefs)/sizeof(SignalDefs); ++i ) signal( signalDefs[i].id, SIG_DFL ); m_isSet = false; } } bool m_isSet; }; } // namespace Catch #endif // not Windows #include #include namespace Catch { class StreamRedirect { public: StreamRedirect( std::ostream& stream, std::string& targetString ) : m_stream( stream ), m_prevBuf( stream.rdbuf() ), m_targetString( targetString ) { stream.rdbuf( m_oss.rdbuf() ); } ~StreamRedirect() { m_targetString += m_oss.str(); m_stream.rdbuf( m_prevBuf ); } private: std::ostream& m_stream; std::streambuf* m_prevBuf; std::ostringstream m_oss; std::string& m_targetString; }; /////////////////////////////////////////////////////////////////////////// class RunContext : public IResultCapture, public IRunner { RunContext( RunContext const& ); void operator =( RunContext const& ); public: explicit RunContext( Ptr const& _config, Ptr const& reporter ) : m_runInfo( _config->name() ), m_context( getCurrentMutableContext() ), m_activeTestCase( CATCH_NULL ), m_config( _config ), m_reporter( reporter ) { m_context.setRunner( this ); m_context.setConfig( m_config ); m_context.setResultCapture( this ); m_reporter->testRunStarting( m_runInfo ); } virtual ~RunContext() { m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, aborting() ) ); } void testGroupStarting( std::string const& testSpec, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupStarting( GroupInfo( testSpec, groupIndex, groupsCount ) ); } void testGroupEnded( std::string const& testSpec, Totals const& totals, std::size_t groupIndex, std::size_t groupsCount ) { m_reporter->testGroupEnded( TestGroupStats( GroupInfo( testSpec, groupIndex, groupsCount ), totals, aborting() ) ); } Totals runTest( TestCase const& testCase ) { Totals prevTotals = m_totals; std::string redirectedCout; std::string redirectedCerr; TestCaseInfo testInfo = testCase.getTestCaseInfo(); m_reporter->testCaseStarting( testInfo ); m_activeTestCase = &testCase; do { m_trackerContext.startRun(); do { m_trackerContext.startCycle(); m_testCaseTracker = &SectionTracker::acquire( m_trackerContext, testInfo.name ); runCurrentTest( redirectedCout, redirectedCerr ); } while( !m_testCaseTracker->isSuccessfullyCompleted() && !aborting() ); } // !TBD: deprecated - this will be replaced by indexed trackers while( getCurrentContext().advanceGeneratorsForCurrentTest() && !aborting() ); Totals deltaTotals = m_totals.delta( prevTotals ); if( testInfo.expectedToFail() && deltaTotals.testCases.passed > 0 ) { deltaTotals.assertions.failed++; deltaTotals.testCases.passed--; deltaTotals.testCases.failed++; } m_totals.testCases += deltaTotals.testCases; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, redirectedCout, redirectedCerr, aborting() ) ); m_activeTestCase = CATCH_NULL; m_testCaseTracker = CATCH_NULL; return deltaTotals; } Ptr config() const { return m_config; } private: // IResultCapture virtual void assertionEnded( AssertionResult const& result ) { if( result.getResultType() == ResultWas::Ok ) { m_totals.assertions.passed++; } else if( !result.isOk() ) { m_totals.assertions.failed++; } if( m_reporter->assertionEnded( AssertionStats( result, m_messages, m_totals ) ) ) m_messages.clear(); // Reset working state m_lastAssertionInfo = AssertionInfo( """", m_lastAssertionInfo.lineInfo, ""{Unknown expression after the reported line}"" , m_lastAssertionInfo.resultDisposition ); m_lastResult = result; } virtual bool sectionStarted ( SectionInfo const& sectionInfo, Counts& assertions ) { std::ostringstream oss; oss << sectionInfo.name << ""@"" << sectionInfo.lineInfo; ITracker& sectionTracker = SectionTracker::acquire( m_trackerContext, oss.str() ); if( !sectionTracker.isOpen() ) return false; m_activeSections.push_back( §ionTracker ); m_lastAssertionInfo.lineInfo = sectionInfo.lineInfo; m_reporter->sectionStarting( sectionInfo ); assertions = m_totals.assertions; return true; } bool testForMissingAssertions( Counts& assertions ) { if( assertions.total() != 0 ) return false; if( !m_config->warnAboutMissingAssertions() ) return false; if( m_trackerContext.currentTracker().hasChildren() ) return false; m_totals.assertions.failed++; assertions.failed++; return true; } virtual void sectionEnded( SectionEndInfo const& endInfo ) { Counts assertions = m_totals.assertions - endInfo.prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); if( !m_activeSections.empty() ) { m_activeSections.back()->close(); m_activeSections.pop_back(); } m_reporter->sectionEnded( SectionStats( endInfo.sectionInfo, assertions, endInfo.durationInSeconds, missingAssertions ) ); m_messages.clear(); } virtual void sectionEndedEarly( SectionEndInfo const& endInfo ) { if( m_unfinishedSections.empty() ) m_activeSections.back()->fail(); else m_activeSections.back()->close(); m_activeSections.pop_back(); m_unfinishedSections.push_back( endInfo ); } virtual void pushScopedMessage( MessageInfo const& message ) { m_messages.push_back( message ); } virtual void popScopedMessage( MessageInfo const& message ) { m_messages.erase( std::remove( m_messages.begin(), m_messages.end(), message ), m_messages.end() ); } virtual std::string getCurrentTestName() const { return m_activeTestCase ? m_activeTestCase->getTestCaseInfo().name : """"; } virtual const AssertionResult* getLastResult() const { return &m_lastResult; } virtual void handleFatalErrorCondition( std::string const& message ) { ResultBuilder resultBuilder = makeUnexpectedResultBuilder(); resultBuilder.setResultType( ResultWas::FatalErrorCondition ); resultBuilder << message; resultBuilder.captureExpression(); handleUnfinishedSections(); // Recreate section for test case (as we will lose the one that was in scope) TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); Counts assertions; assertions.failed = 1; SectionStats testCaseSectionStats( testCaseSection, assertions, 0, false ); m_reporter->sectionEnded( testCaseSectionStats ); TestCaseInfo testInfo = m_activeTestCase->getTestCaseInfo(); Totals deltaTotals; deltaTotals.testCases.failed = 1; m_reporter->testCaseEnded( TestCaseStats( testInfo, deltaTotals, """", """", false ) ); m_totals.testCases.failed++; testGroupEnded( """", m_totals, 1, 1 ); m_reporter->testRunEnded( TestRunStats( m_runInfo, m_totals, false ) ); } public: // !TBD We need to do this another way! bool aborting() const { return m_totals.assertions.failed == static_cast( m_config->abortAfter() ); } private: void runCurrentTest( std::string& redirectedCout, std::string& redirectedCerr ) { TestCaseInfo const& testCaseInfo = m_activeTestCase->getTestCaseInfo(); SectionInfo testCaseSection( testCaseInfo.lineInfo, testCaseInfo.name, testCaseInfo.description ); m_reporter->sectionStarting( testCaseSection ); Counts prevAssertions = m_totals.assertions; double duration = 0; try { m_lastAssertionInfo = AssertionInfo( ""TEST_CASE"", testCaseInfo.lineInfo, """", ResultDisposition::Normal ); seedRng( *m_config ); Timer timer; timer.start(); if( m_reporter->getPreferences().shouldRedirectStdOut ) { StreamRedirect coutRedir( Catch::cout(), redirectedCout ); StreamRedirect cerrRedir( Catch::cerr(), redirectedCerr ); invokeActiveTestCase(); } else { invokeActiveTestCase(); } duration = timer.getElapsedSeconds(); } catch( TestFailureException& ) { // This just means the test was aborted due to failure } catch(...) { makeUnexpectedResultBuilder().useActiveException(); } m_testCaseTracker->close(); handleUnfinishedSections(); m_messages.clear(); Counts assertions = m_totals.assertions - prevAssertions; bool missingAssertions = testForMissingAssertions( assertions ); if( testCaseInfo.okToFail() ) { std::swap( assertions.failedButOk, assertions.failed ); m_totals.assertions.failed -= assertions.failedButOk; m_totals.assertions.failedButOk += assertions.failedButOk; } SectionStats testCaseSectionStats( testCaseSection, assertions, duration, missingAssertions ); m_reporter->sectionEnded( testCaseSectionStats ); } void invokeActiveTestCase() { FatalConditionHandler fatalConditionHandler; // Handle signals m_activeTestCase->invoke(); fatalConditionHandler.reset(); } private: ResultBuilder makeUnexpectedResultBuilder() const { return ResultBuilder( m_lastAssertionInfo.macroName.c_str(), m_lastAssertionInfo.lineInfo, m_lastAssertionInfo.capturedExpression.c_str(), m_lastAssertionInfo.resultDisposition ); } void handleUnfinishedSections() { // If sections ended prematurely due to an exception we stored their // infos here so we can tear them down outside the unwind process. for( std::vector::const_reverse_iterator it = m_unfinishedSections.rbegin(), itEnd = m_unfinishedSections.rend(); it != itEnd; ++it ) sectionEnded( *it ); m_unfinishedSections.clear(); } TestRunInfo m_runInfo; IMutableContext& m_context; TestCase const* m_activeTestCase; ITracker* m_testCaseTracker; ITracker* m_currentSectionTracker; AssertionResult m_lastResult; Ptr m_config; Totals m_totals; Ptr m_reporter; std::vector m_messages; AssertionInfo m_lastAssertionInfo; std::vector m_unfinishedSections; std::vector m_activeSections; TrackerContext m_trackerContext; }; IResultCapture& getResultCapture() { if( IResultCapture* capture = getCurrentContext().getResultCapture() ) return *capture; else throw std::logic_error( ""No result capture instance"" ); } } // end namespace Catch // #included from: internal/catch_version.h #define TWOBLUECUBES_CATCH_VERSION_H_INCLUDED namespace Catch { // Versioning information struct Version { Version( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, std::string const& _branchName, unsigned int _buildNumber ); unsigned int const majorVersion; unsigned int const minorVersion; unsigned int const patchNumber; // buildNumber is only used if branchName is not null std::string const branchName; unsigned int const buildNumber; friend std::ostream& operator << ( std::ostream& os, Version const& version ); private: void operator=( Version const& ); }; extern Version libraryVersion; } #include #include #include namespace Catch { Ptr createReporter( std::string const& reporterName, Ptr const& config ) { Ptr reporter = getRegistryHub().getReporterRegistry().create( reporterName, config.get() ); if( !reporter ) { std::ostringstream oss; oss << ""No reporter registered with name: '"" << reporterName << ""'""; throw std::domain_error( oss.str() ); } return reporter; } Ptr makeReporter( Ptr const& config ) { std::vector reporters = config->getReporterNames(); if( reporters.empty() ) reporters.push_back( ""console"" ); Ptr reporter; for( std::vector::const_iterator it = reporters.begin(), itEnd = reporters.end(); it != itEnd; ++it ) reporter = addReporter( reporter, createReporter( *it, config ) ); return reporter; } Ptr addListeners( Ptr const& config, Ptr reporters ) { IReporterRegistry::Listeners listeners = getRegistryHub().getReporterRegistry().getListeners(); for( IReporterRegistry::Listeners::const_iterator it = listeners.begin(), itEnd = listeners.end(); it != itEnd; ++it ) reporters = addReporter(reporters, (*it)->create( ReporterConfig( config ) ) ); return reporters; } Totals runTests( Ptr const& config ) { Ptr iconfig = config.get(); Ptr reporter = makeReporter( config ); reporter = addListeners( iconfig, reporter ); RunContext context( iconfig, reporter ); Totals totals; context.testGroupStarting( config->name(), 1, 1 ); TestSpec testSpec = config->testSpec(); if( !testSpec.hasFilters() ) testSpec = TestSpecParser( ITagAliasRegistry::get() ).parse( ""~[.]"" ).testSpec(); // All not hidden tests std::vector const& allTestCases = getAllTestCasesSorted( *iconfig ); for( std::vector::const_iterator it = allTestCases.begin(), itEnd = allTestCases.end(); it != itEnd; ++it ) { if( !context.aborting() && matchTest( *it, testSpec, *iconfig ) ) totals += context.runTest( *it ); else reporter->skipTest( *it ); } context.testGroupEnded( iconfig->name(), totals, 1, 1 ); return totals; } void applyFilenamesAsTags( IConfig const& config ) { std::vector const& tests = getAllTestCasesSorted( config ); for(std::size_t i = 0; i < tests.size(); ++i ) { TestCase& test = const_cast( tests[i] ); std::set tags = test.tags; std::string filename = test.lineInfo.file; std::string::size_type lastSlash = filename.find_last_of( ""\\/"" ); if( lastSlash != std::string::npos ) filename = filename.substr( lastSlash+1 ); std::string::size_type lastDot = filename.find_last_of( ""."" ); if( lastDot != std::string::npos ) filename = filename.substr( 0, lastDot ); tags.insert( ""#"" + filename ); setTags( test, tags ); } } class Session : NonCopyable { static bool alreadyInstantiated; public: struct OnUnusedOptions { enum DoWhat { Ignore, Fail }; }; Session() : m_cli( makeCommandLineParser() ) { if( alreadyInstantiated ) { std::string msg = ""Only one instance of Catch::Session can ever be used""; Catch::cerr() << msg << std::endl; throw std::logic_error( msg ); } alreadyInstantiated = true; } ~Session() { Catch::cleanUp(); } void showHelp( std::string const& processName ) { Catch::cout() << ""\nCatch v"" << libraryVersion << ""\n""; m_cli.usage( Catch::cout(), processName ); Catch::cout() << ""For more detail usage please see the project docs\n"" << std::endl; } int applyCommandLine( int argc, char const* const* const argv, OnUnusedOptions::DoWhat unusedOptionBehaviour = OnUnusedOptions::Fail ) { try { m_cli.setThrowOnUnrecognisedTokens( unusedOptionBehaviour == OnUnusedOptions::Fail ); m_unusedTokens = m_cli.parseInto( Clara::argsToVector( argc, argv ), m_configData ); if( m_configData.showHelp ) showHelp( m_configData.processName ); m_config.reset(); } catch( std::exception& ex ) { { Colour colourGuard( Colour::Red ); Catch::cerr() << ""\nError(s) in input:\n"" << Text( ex.what(), TextAttributes().setIndent(2) ) << ""\n\n""; } m_cli.usage( Catch::cout(), m_configData.processName ); return (std::numeric_limits::max)(); } return 0; } void useConfigData( ConfigData const& _configData ) { m_configData = _configData; m_config.reset(); } int run( int argc, char const* const* const argv ) { int returnCode = applyCommandLine( argc, argv ); if( returnCode == 0 ) returnCode = run(); return returnCode; } int run() { if( m_configData.showHelp ) return 0; try { config(); // Force config to be constructed seedRng( *m_config ); if( m_configData.filenamesAsTags ) applyFilenamesAsTags( *m_config ); // Handle list request if( Option listed = list( config() ) ) return static_cast( *listed ); return static_cast( runTests( m_config ).assertions.failed ); } catch( std::exception& ex ) { Catch::cerr() << ex.what() << std::endl; return (std::numeric_limits::max)(); } } Clara::CommandLine const& cli() const { return m_cli; } std::vector const& unusedTokens() const { return m_unusedTokens; } ConfigData& configData() { return m_configData; } Config& config() { if( !m_config ) m_config = new Config( m_configData ); return *m_config; } private: Clara::CommandLine m_cli; std::vector m_unusedTokens; ConfigData m_configData; Ptr m_config; }; bool Session::alreadyInstantiated = false; } // end namespace Catch // #included from: catch_registry_hub.hpp #define TWOBLUECUBES_CATCH_REGISTRY_HUB_HPP_INCLUDED // #included from: catch_test_case_registry_impl.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_REGISTRY_IMPL_HPP_INCLUDED #include #include #include #include #include namespace Catch { struct LexSort { bool operator() (TestCase i,TestCase j) const { return (i sortTests( IConfig const& config, std::vector const& unsortedTestCases ) { std::vector sorted = unsortedTestCases; switch( config.runOrder() ) { case RunTests::InLexicographicalOrder: std::sort( sorted.begin(), sorted.end(), LexSort() ); break; case RunTests::InRandomOrder: { seedRng( config ); RandomNumberGenerator rng; std::random_shuffle( sorted.begin(), sorted.end(), rng ); } break; case RunTests::InDeclarationOrder: // already in declaration order break; } return sorted; } bool matchTest( TestCase const& testCase, TestSpec const& testSpec, IConfig const& config ) { return testSpec.matches( testCase ) && ( config.allowThrows() || !testCase.throws() ); } void enforceNoDuplicateTestCases( std::vector const& functions ) { std::set seenFunctions; for( std::vector::const_iterator it = functions.begin(), itEnd = functions.end(); it != itEnd; ++it ) { std::pair::const_iterator, bool> prev = seenFunctions.insert( *it ); if( !prev.second ) { std::ostringstream ss; ss << Colour( Colour::Red ) << ""error: TEST_CASE( \"""" << it->name << ""\"" ) already defined.\n"" << ""\tFirst seen at "" << prev.first->getTestCaseInfo().lineInfo << ""\n"" << ""\tRedefined at "" << it->getTestCaseInfo().lineInfo << std::endl; throw std::runtime_error(ss.str()); } } } std::vector filterTests( std::vector const& testCases, TestSpec const& testSpec, IConfig const& config ) { std::vector filtered; filtered.reserve( testCases.size() ); for( std::vector::const_iterator it = testCases.begin(), itEnd = testCases.end(); it != itEnd; ++it ) if( matchTest( *it, testSpec, config ) ) filtered.push_back( *it ); return filtered; } std::vector const& getAllTestCasesSorted( IConfig const& config ) { return getRegistryHub().getTestCaseRegistry().getAllTestsSorted( config ); } class TestRegistry : public ITestCaseRegistry { public: TestRegistry() : m_currentSortOrder( RunTests::InDeclarationOrder ), m_unnamedCount( 0 ) {} virtual ~TestRegistry(); virtual void registerTest( TestCase const& testCase ) { std::string name = testCase.getTestCaseInfo().name; if( name == """" ) { std::ostringstream oss; oss << ""Anonymous test case "" << ++m_unnamedCount; return registerTest( testCase.withName( oss.str() ) ); } m_functions.push_back( testCase ); } virtual std::vector const& getAllTests() const { return m_functions; } virtual std::vector const& getAllTestsSorted( IConfig const& config ) const { if( m_sortedFunctions.empty() ) enforceNoDuplicateTestCases( m_functions ); if( m_currentSortOrder != config.runOrder() || m_sortedFunctions.empty() ) { m_sortedFunctions = sortTests( config, m_functions ); m_currentSortOrder = config.runOrder(); } return m_sortedFunctions; } private: std::vector m_functions; mutable RunTests::InWhatOrder m_currentSortOrder; mutable std::vector m_sortedFunctions; size_t m_unnamedCount; std::ios_base::Init m_ostreamInit; // Forces cout/ cerr to be initialised }; /////////////////////////////////////////////////////////////////////////// class FreeFunctionTestCase : public SharedImpl { public: FreeFunctionTestCase( TestFunction fun ) : m_fun( fun ) {} virtual void invoke() const { m_fun(); } private: virtual ~FreeFunctionTestCase(); TestFunction m_fun; }; inline std::string extractClassName( std::string const& classOrQualifiedMethodName ) { std::string className = classOrQualifiedMethodName; if( startsWith( className, ""&"" ) ) { std::size_t lastColons = className.rfind( ""::"" ); std::size_t penultimateColons = className.rfind( ""::"", lastColons-1 ); if( penultimateColons == std::string::npos ) penultimateColons = 1; className = className.substr( penultimateColons, lastColons-penultimateColons ); } return className; } void registerTestCase ( ITestCase* testCase, char const* classOrQualifiedMethodName, NameAndDesc const& nameAndDesc, SourceLineInfo const& lineInfo ) { getMutableRegistryHub().registerTest ( makeTestCase ( testCase, extractClassName( classOrQualifiedMethodName ), nameAndDesc.name, nameAndDesc.description, lineInfo ) ); } void registerTestCaseFunction ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ) { registerTestCase( new FreeFunctionTestCase( function ), """", nameAndDesc, lineInfo ); } /////////////////////////////////////////////////////////////////////////// AutoReg::AutoReg ( TestFunction function, SourceLineInfo const& lineInfo, NameAndDesc const& nameAndDesc ) { registerTestCaseFunction( function, lineInfo, nameAndDesc ); } AutoReg::~AutoReg() {} } // end namespace Catch // #included from: catch_reporter_registry.hpp #define TWOBLUECUBES_CATCH_REPORTER_REGISTRY_HPP_INCLUDED #include namespace Catch { class ReporterRegistry : public IReporterRegistry { public: virtual ~ReporterRegistry() CATCH_OVERRIDE {} virtual IStreamingReporter* create( std::string const& name, Ptr const& config ) const CATCH_OVERRIDE { FactoryMap::const_iterator it = m_factories.find( name ); if( it == m_factories.end() ) return CATCH_NULL; return it->second->create( ReporterConfig( config ) ); } void registerReporter( std::string const& name, Ptr const& factory ) { m_factories.insert( std::make_pair( name, factory ) ); } void registerListener( Ptr const& factory ) { m_listeners.push_back( factory ); } virtual FactoryMap const& getFactories() const CATCH_OVERRIDE { return m_factories; } virtual Listeners const& getListeners() const CATCH_OVERRIDE { return m_listeners; } private: FactoryMap m_factories; Listeners m_listeners; }; } // #included from: catch_exception_translator_registry.hpp #define TWOBLUECUBES_CATCH_EXCEPTION_TRANSLATOR_REGISTRY_HPP_INCLUDED #ifdef __OBJC__ #import ""Foundation/Foundation.h"" #endif namespace Catch { class ExceptionTranslatorRegistry : public IExceptionTranslatorRegistry { public: ~ExceptionTranslatorRegistry() { deleteAll( m_translators ); } virtual void registerTranslator( const IExceptionTranslator* translator ) { m_translators.push_back( translator ); } virtual std::string translateActiveException() const { try { #ifdef __OBJC__ // In Objective-C try objective-c exceptions first @try { return tryTranslators(); } @catch (NSException *exception) { return Catch::toString( [exception description] ); } #else return tryTranslators(); #endif } catch( TestFailureException& ) { throw; } catch( std::exception& ex ) { return ex.what(); } catch( std::string& msg ) { return msg; } catch( const char* msg ) { return msg; } catch(...) { return ""Unknown exception""; } } std::string tryTranslators() const { if( m_translators.empty() ) throw; else return m_translators[0]->translate( m_translators.begin()+1, m_translators.end() ); } private: std::vector m_translators; }; } namespace Catch { namespace { class RegistryHub : public IRegistryHub, public IMutableRegistryHub { RegistryHub( RegistryHub const& ); void operator=( RegistryHub const& ); public: // IRegistryHub RegistryHub() { } virtual IReporterRegistry const& getReporterRegistry() const CATCH_OVERRIDE { return m_reporterRegistry; } virtual ITestCaseRegistry const& getTestCaseRegistry() const CATCH_OVERRIDE { return m_testCaseRegistry; } virtual IExceptionTranslatorRegistry& getExceptionTranslatorRegistry() CATCH_OVERRIDE { return m_exceptionTranslatorRegistry; } public: // IMutableRegistryHub virtual void registerReporter( std::string const& name, Ptr const& factory ) CATCH_OVERRIDE { m_reporterRegistry.registerReporter( name, factory ); } virtual void registerListener( Ptr const& factory ) CATCH_OVERRIDE { m_reporterRegistry.registerListener( factory ); } virtual void registerTest( TestCase const& testInfo ) CATCH_OVERRIDE { m_testCaseRegistry.registerTest( testInfo ); } virtual void registerTranslator( const IExceptionTranslator* translator ) CATCH_OVERRIDE { m_exceptionTranslatorRegistry.registerTranslator( translator ); } private: TestRegistry m_testCaseRegistry; ReporterRegistry m_reporterRegistry; ExceptionTranslatorRegistry m_exceptionTranslatorRegistry; }; // Single, global, instance inline RegistryHub*& getTheRegistryHub() { static RegistryHub* theRegistryHub = CATCH_NULL; if( !theRegistryHub ) theRegistryHub = new RegistryHub(); return theRegistryHub; } } IRegistryHub& getRegistryHub() { return *getTheRegistryHub(); } IMutableRegistryHub& getMutableRegistryHub() { return *getTheRegistryHub(); } void cleanUp() { delete getTheRegistryHub(); getTheRegistryHub() = CATCH_NULL; cleanUpContext(); } std::string translateActiveException() { return getRegistryHub().getExceptionTranslatorRegistry().translateActiveException(); } } // end namespace Catch // #included from: catch_notimplemented_exception.hpp #define TWOBLUECUBES_CATCH_NOTIMPLEMENTED_EXCEPTION_HPP_INCLUDED #include namespace Catch { NotImplementedException::NotImplementedException( SourceLineInfo const& lineInfo ) : m_lineInfo( lineInfo ) { std::ostringstream oss; oss << lineInfo << "": function ""; oss << ""not implemented""; m_what = oss.str(); } const char* NotImplementedException::what() const CATCH_NOEXCEPT { return m_what.c_str(); } } // end namespace Catch // #included from: catch_context_impl.hpp #define TWOBLUECUBES_CATCH_CONTEXT_IMPL_HPP_INCLUDED // #included from: catch_stream.hpp #define TWOBLUECUBES_CATCH_STREAM_HPP_INCLUDED #include #include #include namespace Catch { template class StreamBufImpl : public StreamBufBase { char data[bufferSize]; WriterF m_writer; public: StreamBufImpl() { setp( data, data + sizeof(data) ); } ~StreamBufImpl() CATCH_NOEXCEPT { sync(); } private: int overflow( int c ) { sync(); if( c != EOF ) { if( pbase() == epptr() ) m_writer( std::string( 1, static_cast( c ) ) ); else sputc( static_cast( c ) ); } return 0; } int sync() { if( pbase() != pptr() ) { m_writer( std::string( pbase(), static_cast( pptr() - pbase() ) ) ); setp( pbase(), epptr() ); } return 0; } }; /////////////////////////////////////////////////////////////////////////// FileStream::FileStream( std::string const& filename ) { m_ofs.open( filename.c_str() ); if( m_ofs.fail() ) { std::ostringstream oss; oss << ""Unable to open file: '"" << filename << ""'""; throw std::domain_error( oss.str() ); } } std::ostream& FileStream::stream() const { return m_ofs; } struct OutputDebugWriter { void operator()( std::string const&str ) { writeToDebugConsole( str ); } }; DebugOutStream::DebugOutStream() : m_streamBuf( new StreamBufImpl() ), m_os( m_streamBuf.get() ) {} std::ostream& DebugOutStream::stream() const { return m_os; } // Store the streambuf from cout up-front because // cout may get redirected when running tests CoutStream::CoutStream() : m_os( Catch::cout().rdbuf() ) {} std::ostream& CoutStream::stream() const { return m_os; } #ifndef CATCH_CONFIG_NOSTDOUT // If you #define this you must implement these functions std::ostream& cout() { return std::cout; } std::ostream& cerr() { return std::cerr; } #endif } namespace Catch { class Context : public IMutableContext { Context() : m_config( CATCH_NULL ), m_runner( CATCH_NULL ), m_resultCapture( CATCH_NULL ) {} Context( Context const& ); void operator=( Context const& ); public: // IContext virtual IResultCapture* getResultCapture() { return m_resultCapture; } virtual IRunner* getRunner() { return m_runner; } virtual size_t getGeneratorIndex( std::string const& fileInfo, size_t totalSize ) { return getGeneratorsForCurrentTest() .getGeneratorInfo( fileInfo, totalSize ) .getCurrentIndex(); } virtual bool advanceGeneratorsForCurrentTest() { IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); return generators && generators->moveNext(); } virtual Ptr getConfig() const { return m_config; } public: // IMutableContext virtual void setResultCapture( IResultCapture* resultCapture ) { m_resultCapture = resultCapture; } virtual void setRunner( IRunner* runner ) { m_runner = runner; } virtual void setConfig( Ptr const& config ) { m_config = config; } friend IMutableContext& getCurrentMutableContext(); private: IGeneratorsForTest* findGeneratorsForCurrentTest() { std::string testName = getResultCapture()->getCurrentTestName(); std::map::const_iterator it = m_generatorsByTestName.find( testName ); return it != m_generatorsByTestName.end() ? it->second : CATCH_NULL; } IGeneratorsForTest& getGeneratorsForCurrentTest() { IGeneratorsForTest* generators = findGeneratorsForCurrentTest(); if( !generators ) { std::string testName = getResultCapture()->getCurrentTestName(); generators = createGeneratorsForTest(); m_generatorsByTestName.insert( std::make_pair( testName, generators ) ); } return *generators; } private: Ptr m_config; IRunner* m_runner; IResultCapture* m_resultCapture; std::map m_generatorsByTestName; }; namespace { Context* currentContext = CATCH_NULL; } IMutableContext& getCurrentMutableContext() { if( !currentContext ) currentContext = new Context(); return *currentContext; } IContext& getCurrentContext() { return getCurrentMutableContext(); } void cleanUpContext() { delete currentContext; currentContext = CATCH_NULL; } } // #included from: catch_console_colour_impl.hpp #define TWOBLUECUBES_CATCH_CONSOLE_COLOUR_IMPL_HPP_INCLUDED namespace Catch { namespace { struct IColourImpl { virtual ~IColourImpl() {} virtual void use( Colour::Code _colourCode ) = 0; }; struct NoColourImpl : IColourImpl { void use( Colour::Code ) {} static IColourImpl* instance() { static NoColourImpl s_instance; return &s_instance; } }; } // anon namespace } // namespace Catch #if !defined( CATCH_CONFIG_COLOUR_NONE ) && !defined( CATCH_CONFIG_COLOUR_WINDOWS ) && !defined( CATCH_CONFIG_COLOUR_ANSI ) # ifdef CATCH_PLATFORM_WINDOWS # define CATCH_CONFIG_COLOUR_WINDOWS # else # define CATCH_CONFIG_COLOUR_ANSI # endif #endif #if defined ( CATCH_CONFIG_COLOUR_WINDOWS ) ///////////////////////////////////////// #ifndef NOMINMAX #define NOMINMAX #endif #ifdef __AFXDLL #include #else #include #endif namespace Catch { namespace { class Win32ColourImpl : public IColourImpl { public: Win32ColourImpl() : stdoutHandle( GetStdHandle(STD_OUTPUT_HANDLE) ) { CONSOLE_SCREEN_BUFFER_INFO csbiInfo; GetConsoleScreenBufferInfo( stdoutHandle, &csbiInfo ); originalForegroundAttributes = csbiInfo.wAttributes & ~( BACKGROUND_GREEN | BACKGROUND_RED | BACKGROUND_BLUE | BACKGROUND_INTENSITY ); originalBackgroundAttributes = csbiInfo.wAttributes & ~( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE | FOREGROUND_INTENSITY ); } virtual void use( Colour::Code _colourCode ) { switch( _colourCode ) { case Colour::None: return setTextAttribute( originalForegroundAttributes ); case Colour::White: return setTextAttribute( FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::Red: return setTextAttribute( FOREGROUND_RED ); case Colour::Green: return setTextAttribute( FOREGROUND_GREEN ); case Colour::Blue: return setTextAttribute( FOREGROUND_BLUE ); case Colour::Cyan: return setTextAttribute( FOREGROUND_BLUE | FOREGROUND_GREEN ); case Colour::Yellow: return setTextAttribute( FOREGROUND_RED | FOREGROUND_GREEN ); case Colour::Grey: return setTextAttribute( 0 ); case Colour::LightGrey: return setTextAttribute( FOREGROUND_INTENSITY ); case Colour::BrightRed: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_RED ); case Colour::BrightGreen: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN ); case Colour::BrightWhite: return setTextAttribute( FOREGROUND_INTENSITY | FOREGROUND_GREEN | FOREGROUND_RED | FOREGROUND_BLUE ); case Colour::Bright: throw std::logic_error( ""not a colour"" ); } } private: void setTextAttribute( WORD _textAttribute ) { SetConsoleTextAttribute( stdoutHandle, _textAttribute | originalBackgroundAttributes ); } HANDLE stdoutHandle; WORD originalForegroundAttributes; WORD originalBackgroundAttributes; }; IColourImpl* platformColourInstance() { static Win32ColourImpl s_instance; Ptr config = getCurrentContext().getConfig(); UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto; if( colourMode == UseColour::Auto ) colourMode = !isDebuggerActive() ? UseColour::Yes : UseColour::No; return colourMode == UseColour::Yes ? &s_instance : NoColourImpl::instance(); } } // end anon namespace } // end namespace Catch #elif defined( CATCH_CONFIG_COLOUR_ANSI ) ////////////////////////////////////// #include namespace Catch { namespace { // use POSIX/ ANSI console terminal codes // Thanks to Adam Strzelecki for original contribution // (http://github.com/nanoant) // https://github.com/philsquared/Catch/pull/131 class PosixColourImpl : public IColourImpl { public: virtual void use( Colour::Code _colourCode ) { switch( _colourCode ) { case Colour::None: case Colour::White: return setColour( ""[0m"" ); case Colour::Red: return setColour( ""[0;31m"" ); case Colour::Green: return setColour( ""[0;32m"" ); case Colour::Blue: return setColour( ""[0:34m"" ); case Colour::Cyan: return setColour( ""[0;36m"" ); case Colour::Yellow: return setColour( ""[0;33m"" ); case Colour::Grey: return setColour( ""[1;30m"" ); case Colour::LightGrey: return setColour( ""[0;37m"" ); case Colour::BrightRed: return setColour( ""[1;31m"" ); case Colour::BrightGreen: return setColour( ""[1;32m"" ); case Colour::BrightWhite: return setColour( ""[1;37m"" ); case Colour::Bright: throw std::logic_error( ""not a colour"" ); } } static IColourImpl* instance() { static PosixColourImpl s_instance; return &s_instance; } private: void setColour( const char* _escapeCode ) { Catch::cout() << '\033' << _escapeCode; } }; IColourImpl* platformColourInstance() { Ptr config = getCurrentContext().getConfig(); UseColour::YesOrNo colourMode = config ? config->useColour() : UseColour::Auto; if( colourMode == UseColour::Auto ) colourMode = (!isDebuggerActive() && isatty(STDOUT_FILENO) ) ? UseColour::Yes : UseColour::No; return colourMode == UseColour::Yes ? PosixColourImpl::instance() : NoColourImpl::instance(); } } // end anon namespace } // end namespace Catch #else // not Windows or ANSI /////////////////////////////////////////////// namespace Catch { static IColourImpl* platformColourInstance() { return NoColourImpl::instance(); } } // end namespace Catch #endif // Windows/ ANSI/ None namespace Catch { Colour::Colour( Code _colourCode ) : m_moved( false ) { use( _colourCode ); } Colour::Colour( Colour const& _other ) : m_moved( false ) { const_cast( _other ).m_moved = true; } Colour::~Colour(){ if( !m_moved ) use( None ); } void Colour::use( Code _colourCode ) { static IColourImpl* impl = platformColourInstance(); impl->use( _colourCode ); } } // end namespace Catch // #included from: catch_generators_impl.hpp #define TWOBLUECUBES_CATCH_GENERATORS_IMPL_HPP_INCLUDED #include #include #include namespace Catch { struct GeneratorInfo : IGeneratorInfo { GeneratorInfo( std::size_t size ) : m_size( size ), m_currentIndex( 0 ) {} bool moveNext() { if( ++m_currentIndex == m_size ) { m_currentIndex = 0; return false; } return true; } std::size_t getCurrentIndex() const { return m_currentIndex; } std::size_t m_size; std::size_t m_currentIndex; }; /////////////////////////////////////////////////////////////////////////// class GeneratorsForTest : public IGeneratorsForTest { public: ~GeneratorsForTest() { deleteAll( m_generatorsInOrder ); } IGeneratorInfo& getGeneratorInfo( std::string const& fileInfo, std::size_t size ) { std::map::const_iterator it = m_generatorsByName.find( fileInfo ); if( it == m_generatorsByName.end() ) { IGeneratorInfo* info = new GeneratorInfo( size ); m_generatorsByName.insert( std::make_pair( fileInfo, info ) ); m_generatorsInOrder.push_back( info ); return *info; } return *it->second; } bool moveNext() { std::vector::const_iterator it = m_generatorsInOrder.begin(); std::vector::const_iterator itEnd = m_generatorsInOrder.end(); for(; it != itEnd; ++it ) { if( (*it)->moveNext() ) return true; } return false; } private: std::map m_generatorsByName; std::vector m_generatorsInOrder; }; IGeneratorsForTest* createGeneratorsForTest() { return new GeneratorsForTest(); } } // end namespace Catch // #included from: catch_assertionresult.hpp #define TWOBLUECUBES_CATCH_ASSERTIONRESULT_HPP_INCLUDED namespace Catch { AssertionInfo::AssertionInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, std::string const& _capturedExpression, ResultDisposition::Flags _resultDisposition ) : macroName( _macroName ), lineInfo( _lineInfo ), capturedExpression( _capturedExpression ), resultDisposition( _resultDisposition ) {} AssertionResult::AssertionResult() {} AssertionResult::AssertionResult( AssertionInfo const& info, AssertionResultData const& data ) : m_info( info ), m_resultData( data ) {} AssertionResult::~AssertionResult() {} // Result was a success bool AssertionResult::succeeded() const { return Catch::isOk( m_resultData.resultType ); } // Result was a success, or failure is suppressed bool AssertionResult::isOk() const { return Catch::isOk( m_resultData.resultType ) || shouldSuppressFailure( m_info.resultDisposition ); } ResultWas::OfType AssertionResult::getResultType() const { return m_resultData.resultType; } bool AssertionResult::hasExpression() const { return !m_info.capturedExpression.empty(); } bool AssertionResult::hasMessage() const { return !m_resultData.message.empty(); } std::string AssertionResult::getExpression() const { if( isFalseTest( m_info.resultDisposition ) ) return ""!"" + m_info.capturedExpression; else return m_info.capturedExpression; } std::string AssertionResult::getExpressionInMacro() const { if( m_info.macroName.empty() ) return m_info.capturedExpression; else return m_info.macroName + ""( "" + m_info.capturedExpression + "" )""; } bool AssertionResult::hasExpandedExpression() const { return hasExpression() && getExpandedExpression() != getExpression(); } std::string AssertionResult::getExpandedExpression() const { return m_resultData.reconstructedExpression; } std::string AssertionResult::getMessage() const { return m_resultData.message; } SourceLineInfo AssertionResult::getSourceInfo() const { return m_info.lineInfo; } std::string AssertionResult::getTestMacroName() const { return m_info.macroName; } } // end namespace Catch // #included from: catch_test_case_info.hpp #define TWOBLUECUBES_CATCH_TEST_CASE_INFO_HPP_INCLUDED namespace Catch { inline TestCaseInfo::SpecialProperties parseSpecialTag( std::string const& tag ) { if( startsWith( tag, ""."" ) || tag == ""hide"" || tag == ""!hide"" ) return TestCaseInfo::IsHidden; else if( tag == ""!throws"" ) return TestCaseInfo::Throws; else if( tag == ""!shouldfail"" ) return TestCaseInfo::ShouldFail; else if( tag == ""!mayfail"" ) return TestCaseInfo::MayFail; else return TestCaseInfo::None; } inline bool isReservedTag( std::string const& tag ) { return parseSpecialTag( tag ) == TestCaseInfo::None && tag.size() > 0 && !isalnum( tag[0] ); } inline void enforceNotReservedTag( std::string const& tag, SourceLineInfo const& _lineInfo ) { if( isReservedTag( tag ) ) { { Colour colourGuard( Colour::Red ); Catch::cerr() << ""Tag name ["" << tag << ""] not allowed.\n"" << ""Tag names starting with non alpha-numeric characters are reserved\n""; } { Colour colourGuard( Colour::FileName ); Catch::cerr() << _lineInfo << std::endl; } exit(1); } } TestCase makeTestCase( ITestCase* _testCase, std::string const& _className, std::string const& _name, std::string const& _descOrTags, SourceLineInfo const& _lineInfo ) { bool isHidden( startsWith( _name, ""./"" ) ); // Legacy support // Parse out tags std::set tags; std::string desc, tag; bool inTag = false; for( std::size_t i = 0; i < _descOrTags.size(); ++i ) { char c = _descOrTags[i]; if( !inTag ) { if( c == '[' ) inTag = true; else desc += c; } else { if( c == ']' ) { TestCaseInfo::SpecialProperties prop = parseSpecialTag( tag ); if( prop == TestCaseInfo::IsHidden ) isHidden = true; else if( prop == TestCaseInfo::None ) enforceNotReservedTag( tag, _lineInfo ); tags.insert( tag ); tag.clear(); inTag = false; } else tag += c; } } if( isHidden ) { tags.insert( ""hide"" ); tags.insert( ""."" ); } TestCaseInfo info( _name, _className, desc, tags, _lineInfo ); return TestCase( _testCase, info ); } void setTags( TestCaseInfo& testCaseInfo, std::set const& tags ) { testCaseInfo.tags = tags; testCaseInfo.lcaseTags.clear(); std::ostringstream oss; for( std::set::const_iterator it = tags.begin(), itEnd = tags.end(); it != itEnd; ++it ) { oss << ""["" << *it << ""]""; std::string lcaseTag = toLower( *it ); testCaseInfo.properties = static_cast( testCaseInfo.properties | parseSpecialTag( lcaseTag ) ); testCaseInfo.lcaseTags.insert( lcaseTag ); } testCaseInfo.tagsAsString = oss.str(); } TestCaseInfo::TestCaseInfo( std::string const& _name, std::string const& _className, std::string const& _description, std::set const& _tags, SourceLineInfo const& _lineInfo ) : name( _name ), className( _className ), description( _description ), lineInfo( _lineInfo ), properties( None ) { setTags( *this, _tags ); } TestCaseInfo::TestCaseInfo( TestCaseInfo const& other ) : name( other.name ), className( other.className ), description( other.description ), tags( other.tags ), lcaseTags( other.lcaseTags ), tagsAsString( other.tagsAsString ), lineInfo( other.lineInfo ), properties( other.properties ) {} bool TestCaseInfo::isHidden() const { return ( properties & IsHidden ) != 0; } bool TestCaseInfo::throws() const { return ( properties & Throws ) != 0; } bool TestCaseInfo::okToFail() const { return ( properties & (ShouldFail | MayFail ) ) != 0; } bool TestCaseInfo::expectedToFail() const { return ( properties & (ShouldFail ) ) != 0; } TestCase::TestCase( ITestCase* testCase, TestCaseInfo const& info ) : TestCaseInfo( info ), test( testCase ) {} TestCase::TestCase( TestCase const& other ) : TestCaseInfo( other ), test( other.test ) {} TestCase TestCase::withName( std::string const& _newName ) const { TestCase other( *this ); other.name = _newName; return other; } void TestCase::swap( TestCase& other ) { test.swap( other.test ); name.swap( other.name ); className.swap( other.className ); description.swap( other.description ); tags.swap( other.tags ); lcaseTags.swap( other.lcaseTags ); tagsAsString.swap( other.tagsAsString ); std::swap( TestCaseInfo::properties, static_cast( other ).properties ); std::swap( lineInfo, other.lineInfo ); } void TestCase::invoke() const { test->invoke(); } bool TestCase::operator == ( TestCase const& other ) const { return test.get() == other.test.get() && name == other.name && className == other.className; } bool TestCase::operator < ( TestCase const& other ) const { return name < other.name; } TestCase& TestCase::operator = ( TestCase const& other ) { TestCase temp( other ); swap( temp ); return *this; } TestCaseInfo const& TestCase::getTestCaseInfo() const { return *this; } } // end namespace Catch // #included from: catch_version.hpp #define TWOBLUECUBES_CATCH_VERSION_HPP_INCLUDED namespace Catch { Version::Version ( unsigned int _majorVersion, unsigned int _minorVersion, unsigned int _patchNumber, std::string const& _branchName, unsigned int _buildNumber ) : majorVersion( _majorVersion ), minorVersion( _minorVersion ), patchNumber( _patchNumber ), branchName( _branchName ), buildNumber( _buildNumber ) {} std::ostream& operator << ( std::ostream& os, Version const& version ) { os << version.majorVersion << ""."" << version.minorVersion << ""."" << version.patchNumber; if( !version.branchName.empty() ) { os << ""-"" << version.branchName << ""."" << version.buildNumber; } return os; } Version libraryVersion( 1, 5, 4, """", 0 ); } // #included from: catch_message.hpp #define TWOBLUECUBES_CATCH_MESSAGE_HPP_INCLUDED namespace Catch { MessageInfo::MessageInfo( std::string const& _macroName, SourceLineInfo const& _lineInfo, ResultWas::OfType _type ) : macroName( _macroName ), lineInfo( _lineInfo ), type( _type ), sequence( ++globalCount ) {} // This may need protecting if threading support is added unsigned int MessageInfo::globalCount = 0; //////////////////////////////////////////////////////////////////////////// ScopedMessage::ScopedMessage( MessageBuilder const& builder ) : m_info( builder.m_info ) { m_info.message = builder.m_stream.str(); getResultCapture().pushScopedMessage( m_info ); } ScopedMessage::ScopedMessage( ScopedMessage const& other ) : m_info( other.m_info ) {} ScopedMessage::~ScopedMessage() { getResultCapture().popScopedMessage( m_info ); } } // end namespace Catch // #included from: catch_legacy_reporter_adapter.hpp #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_HPP_INCLUDED // #included from: catch_legacy_reporter_adapter.h #define TWOBLUECUBES_CATCH_LEGACY_REPORTER_ADAPTER_H_INCLUDED namespace Catch { // Deprecated struct IReporter : IShared { virtual ~IReporter(); virtual bool shouldRedirectStdout() const = 0; virtual void StartTesting() = 0; virtual void EndTesting( Totals const& totals ) = 0; virtual void StartGroup( std::string const& groupName ) = 0; virtual void EndGroup( std::string const& groupName, Totals const& totals ) = 0; virtual void StartTestCase( TestCaseInfo const& testInfo ) = 0; virtual void EndTestCase( TestCaseInfo const& testInfo, Totals const& totals, std::string const& stdOut, std::string const& stdErr ) = 0; virtual void StartSection( std::string const& sectionName, std::string const& description ) = 0; virtual void EndSection( std::string const& sectionName, Counts const& assertions ) = 0; virtual void NoAssertionsInSection( std::string const& sectionName ) = 0; virtual void NoAssertionsInTestCase( std::string const& testName ) = 0; virtual void Aborted() = 0; virtual void Result( AssertionResult const& result ) = 0; }; class LegacyReporterAdapter : public SharedImpl { public: LegacyReporterAdapter( Ptr const& legacyReporter ); virtual ~LegacyReporterAdapter(); virtual ReporterPreferences getPreferences() const; virtual void noMatchingTestCases( std::string const& ); virtual void testRunStarting( TestRunInfo const& ); virtual void testGroupStarting( GroupInfo const& groupInfo ); virtual void testCaseStarting( TestCaseInfo const& testInfo ); virtual void sectionStarting( SectionInfo const& sectionInfo ); virtual void assertionStarting( AssertionInfo const& ); virtual bool assertionEnded( AssertionStats const& assertionStats ); virtual void sectionEnded( SectionStats const& sectionStats ); virtual void testCaseEnded( TestCaseStats const& testCaseStats ); virtual void testGroupEnded( TestGroupStats const& testGroupStats ); virtual void testRunEnded( TestRunStats const& testRunStats ); virtual void skipTest( TestCaseInfo const& ); private: Ptr m_legacyReporter; }; } namespace Catch { LegacyReporterAdapter::LegacyReporterAdapter( Ptr const& legacyReporter ) : m_legacyReporter( legacyReporter ) {} LegacyReporterAdapter::~LegacyReporterAdapter() {} ReporterPreferences LegacyReporterAdapter::getPreferences() const { ReporterPreferences prefs; prefs.shouldRedirectStdOut = m_legacyReporter->shouldRedirectStdout(); return prefs; } void LegacyReporterAdapter::noMatchingTestCases( std::string const& ) {} void LegacyReporterAdapter::testRunStarting( TestRunInfo const& ) { m_legacyReporter->StartTesting(); } void LegacyReporterAdapter::testGroupStarting( GroupInfo const& groupInfo ) { m_legacyReporter->StartGroup( groupInfo.name ); } void LegacyReporterAdapter::testCaseStarting( TestCaseInfo const& testInfo ) { m_legacyReporter->StartTestCase( testInfo ); } void LegacyReporterAdapter::sectionStarting( SectionInfo const& sectionInfo ) { m_legacyReporter->StartSection( sectionInfo.name, sectionInfo.description ); } void LegacyReporterAdapter::assertionStarting( AssertionInfo const& ) { // Not on legacy interface } bool LegacyReporterAdapter::assertionEnded( AssertionStats const& assertionStats ) { if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); it != itEnd; ++it ) { if( it->type == ResultWas::Info ) { ResultBuilder rb( it->macroName.c_str(), it->lineInfo, """", ResultDisposition::Normal ); rb << it->message; rb.setResultType( ResultWas::Info ); AssertionResult result = rb.build(); m_legacyReporter->Result( result ); } } } m_legacyReporter->Result( assertionStats.assertionResult ); return true; } void LegacyReporterAdapter::sectionEnded( SectionStats const& sectionStats ) { if( sectionStats.missingAssertions ) m_legacyReporter->NoAssertionsInSection( sectionStats.sectionInfo.name ); m_legacyReporter->EndSection( sectionStats.sectionInfo.name, sectionStats.assertions ); } void LegacyReporterAdapter::testCaseEnded( TestCaseStats const& testCaseStats ) { m_legacyReporter->EndTestCase ( testCaseStats.testInfo, testCaseStats.totals, testCaseStats.stdOut, testCaseStats.stdErr ); } void LegacyReporterAdapter::testGroupEnded( TestGroupStats const& testGroupStats ) { if( testGroupStats.aborting ) m_legacyReporter->Aborted(); m_legacyReporter->EndGroup( testGroupStats.groupInfo.name, testGroupStats.totals ); } void LegacyReporterAdapter::testRunEnded( TestRunStats const& testRunStats ) { m_legacyReporter->EndTesting( testRunStats.totals ); } void LegacyReporterAdapter::skipTest( TestCaseInfo const& ) { } } // #included from: catch_timer.hpp #ifdef __clang__ #pragma clang diagnostic push #pragma clang diagnostic ignored ""-Wc++11-long-long"" #endif #ifdef CATCH_PLATFORM_WINDOWS #include #else #include #endif namespace Catch { namespace { #ifdef CATCH_PLATFORM_WINDOWS uint64_t getCurrentTicks() { static uint64_t hz=0, hzo=0; if (!hz) { QueryPerformanceFrequency( reinterpret_cast( &hz ) ); QueryPerformanceCounter( reinterpret_cast( &hzo ) ); } uint64_t t; QueryPerformanceCounter( reinterpret_cast( &t ) ); return ((t-hzo)*1000000)/hz; } #else uint64_t getCurrentTicks() { timeval t; gettimeofday(&t,CATCH_NULL); return static_cast( t.tv_sec ) * 1000000ull + static_cast( t.tv_usec ); } #endif } void Timer::start() { m_ticks = getCurrentTicks(); } unsigned int Timer::getElapsedMicroseconds() const { return static_cast(getCurrentTicks() - m_ticks); } unsigned int Timer::getElapsedMilliseconds() const { return static_cast(getElapsedMicroseconds()/1000); } double Timer::getElapsedSeconds() const { return getElapsedMicroseconds()/1000000.0; } } // namespace Catch #ifdef __clang__ #pragma clang diagnostic pop #endif // #included from: catch_common.hpp #define TWOBLUECUBES_CATCH_COMMON_HPP_INCLUDED namespace Catch { bool startsWith( std::string const& s, std::string const& prefix ) { return s.size() >= prefix.size() && s.substr( 0, prefix.size() ) == prefix; } bool endsWith( std::string const& s, std::string const& suffix ) { return s.size() >= suffix.size() && s.substr( s.size()-suffix.size(), suffix.size() ) == suffix; } bool contains( std::string const& s, std::string const& infix ) { return s.find( infix ) != std::string::npos; } void toLowerInPlace( std::string& s ) { std::transform( s.begin(), s.end(), s.begin(), ::tolower ); } std::string toLower( std::string const& s ) { std::string lc = s; toLowerInPlace( lc ); return lc; } std::string trim( std::string const& str ) { static char const* whitespaceChars = ""\n\r\t ""; std::string::size_type start = str.find_first_not_of( whitespaceChars ); std::string::size_type end = str.find_last_not_of( whitespaceChars ); return start != std::string::npos ? str.substr( start, 1+end-start ) : """"; } bool replaceInPlace( std::string& str, std::string const& replaceThis, std::string const& withThis ) { bool replaced = false; std::size_t i = str.find( replaceThis ); while( i != std::string::npos ) { replaced = true; str = str.substr( 0, i ) + withThis + str.substr( i+replaceThis.size() ); if( i < str.size()-withThis.size() ) i = str.find( replaceThis, i+withThis.size() ); else i = std::string::npos; } return replaced; } pluralise::pluralise( std::size_t count, std::string const& label ) : m_count( count ), m_label( label ) {} std::ostream& operator << ( std::ostream& os, pluralise const& pluraliser ) { os << pluraliser.m_count << "" "" << pluraliser.m_label; if( pluraliser.m_count != 1 ) os << ""s""; return os; } SourceLineInfo::SourceLineInfo() : line( 0 ){} SourceLineInfo::SourceLineInfo( char const* _file, std::size_t _line ) : file( _file ), line( _line ) {} SourceLineInfo::SourceLineInfo( SourceLineInfo const& other ) : file( other.file ), line( other.line ) {} bool SourceLineInfo::empty() const { return file.empty(); } bool SourceLineInfo::operator == ( SourceLineInfo const& other ) const { return line == other.line && file == other.file; } bool SourceLineInfo::operator < ( SourceLineInfo const& other ) const { return line < other.line || ( line == other.line && file < other.file ); } void seedRng( IConfig const& config ) { if( config.rngSeed() != 0 ) std::srand( config.rngSeed() ); } unsigned int rngSeed() { return getCurrentContext().getConfig()->rngSeed(); } std::ostream& operator << ( std::ostream& os, SourceLineInfo const& info ) { #ifndef __GNUG__ os << info.file << ""("" << info.line << "")""; #else os << info.file << "":"" << info.line; #endif return os; } void throwLogicError( std::string const& message, SourceLineInfo const& locationInfo ) { std::ostringstream oss; oss << locationInfo << "": Internal Catch error: '"" << message << ""'""; if( alwaysTrue() ) throw std::logic_error( oss.str() ); } } // #included from: catch_section.hpp #define TWOBLUECUBES_CATCH_SECTION_HPP_INCLUDED namespace Catch { SectionInfo::SectionInfo ( SourceLineInfo const& _lineInfo, std::string const& _name, std::string const& _description ) : name( _name ), description( _description ), lineInfo( _lineInfo ) {} Section::Section( SectionInfo const& info ) : m_info( info ), m_sectionIncluded( getResultCapture().sectionStarted( m_info, m_assertions ) ) { m_timer.start(); } Section::~Section() { if( m_sectionIncluded ) { SectionEndInfo endInfo( m_info, m_assertions, m_timer.getElapsedSeconds() ); if( std::uncaught_exception() ) getResultCapture().sectionEndedEarly( endInfo ); else getResultCapture().sectionEnded( endInfo ); } } // This indicates whether the section should be executed or not Section::operator bool() const { return m_sectionIncluded; } } // end namespace Catch // #included from: catch_debugger.hpp #define TWOBLUECUBES_CATCH_DEBUGGER_HPP_INCLUDED #include #ifdef CATCH_PLATFORM_MAC #include #include #include #include #include namespace Catch{ // The following function is taken directly from the following technical note: // http://developer.apple.com/library/mac/#qa/qa2004/qa1361.html // Returns true if the current process is being debugged (either // running under the debugger or has a debugger attached post facto). bool isDebuggerActive(){ int mib[4]; struct kinfo_proc info; size_t size; // Initialize the flags so that, if sysctl fails for some bizarre // reason, we get a predictable result. info.kp_proc.p_flag = 0; // Initialize mib, which tells sysctl the info we want, in this case // we're looking for information about a specific process ID. mib[0] = CTL_KERN; mib[1] = KERN_PROC; mib[2] = KERN_PROC_PID; mib[3] = getpid(); // Call sysctl. size = sizeof(info); if( sysctl(mib, sizeof(mib) / sizeof(*mib), &info, &size, CATCH_NULL, 0) != 0 ) { Catch::cerr() << ""\n** Call to sysctl failed - unable to determine if debugger is active **\n"" << std::endl; return false; } // We're being debugged if the P_TRACED flag is set. return ( (info.kp_proc.p_flag & P_TRACED) != 0 ); } } // namespace Catch #elif defined(_MSC_VER) extern ""C"" __declspec(dllimport) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #elif defined(__MINGW32__) extern ""C"" __declspec(dllimport) int __stdcall IsDebuggerPresent(); namespace Catch { bool isDebuggerActive() { return IsDebuggerPresent() != 0; } } #else namespace Catch { inline bool isDebuggerActive() { return false; } } #endif // Platform #ifdef CATCH_PLATFORM_WINDOWS extern ""C"" __declspec(dllimport) void __stdcall OutputDebugStringA( const char* ); namespace Catch { void writeToDebugConsole( std::string const& text ) { ::OutputDebugStringA( text.c_str() ); } } #else namespace Catch { void writeToDebugConsole( std::string const& text ) { // !TBD: Need a version for Mac/ XCode and other IDEs Catch::cout() << text; } } #endif // Platform // #included from: catch_tostring.hpp #define TWOBLUECUBES_CATCH_TOSTRING_HPP_INCLUDED namespace Catch { namespace Detail { const std::string unprintableString = ""{?}""; namespace { const int hexThreshold = 255; struct Endianness { enum Arch { Big, Little }; static Arch which() { union _{ int asInt; char asChar[sizeof (int)]; } u; u.asInt = 1; return ( u.asChar[sizeof(int)-1] == 1 ) ? Big : Little; } }; } std::string rawMemoryToString( const void *object, std::size_t size ) { // Reverse order for little endian architectures int i = 0, end = static_cast( size ), inc = 1; if( Endianness::which() == Endianness::Little ) { i = end-1; end = inc = -1; } unsigned char const *bytes = static_cast(object); std::ostringstream os; os << ""0x"" << std::setfill('0') << std::hex; for( ; i != end; i += inc ) os << std::setw(2) << static_cast(bytes[i]); return os.str(); } } std::string toString( std::string const& value ) { std::string s = value; if( getCurrentContext().getConfig()->showInvisibles() ) { for(size_t i = 0; i < s.size(); ++i ) { std::string subs; switch( s[i] ) { case '\n': subs = ""\\n""; break; case '\t': subs = ""\\t""; break; default: break; } if( !subs.empty() ) { s = s.substr( 0, i ) + subs + s.substr( i+1 ); ++i; } } } return ""\"""" + s + ""\""""; } std::string toString( std::wstring const& value ) { std::string s; s.reserve( value.size() ); for(size_t i = 0; i < value.size(); ++i ) s += value[i] <= 0xff ? static_cast( value[i] ) : '?'; return Catch::toString( s ); } std::string toString( const char* const value ) { return value ? Catch::toString( std::string( value ) ) : std::string( ""{null string}"" ); } std::string toString( char* const value ) { return Catch::toString( static_cast( value ) ); } std::string toString( const wchar_t* const value ) { return value ? Catch::toString( std::wstring(value) ) : std::string( ""{null string}"" ); } std::string toString( wchar_t* const value ) { return Catch::toString( static_cast( value ) ); } std::string toString( int value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << "" (0x"" << std::hex << value << "")""; return oss.str(); } std::string toString( unsigned long value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << "" (0x"" << std::hex << value << "")""; return oss.str(); } std::string toString( unsigned int value ) { return Catch::toString( static_cast( value ) ); } template std::string fpToString( T value, int precision ) { std::ostringstream oss; oss << std::setprecision( precision ) << std::fixed << value; std::string d = oss.str(); std::size_t i = d.find_last_not_of( '0' ); if( i != std::string::npos && i != d.size()-1 ) { if( d[i] == '.' ) i++; d = d.substr( 0, i+1 ); } return d; } std::string toString( const double value ) { return fpToString( value, 10 ); } std::string toString( const float value ) { return fpToString( value, 5 ) + ""f""; } std::string toString( bool value ) { return value ? ""true"" : ""false""; } std::string toString( char value ) { return value < ' ' ? toString( static_cast( value ) ) : Detail::makeString( value ); } std::string toString( signed char value ) { return toString( static_cast( value ) ); } std::string toString( unsigned char value ) { return toString( static_cast( value ) ); } #ifdef CATCH_CONFIG_CPP11_LONG_LONG std::string toString( long long value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << "" (0x"" << std::hex << value << "")""; return oss.str(); } std::string toString( unsigned long long value ) { std::ostringstream oss; oss << value; if( value > Detail::hexThreshold ) oss << "" (0x"" << std::hex << value << "")""; return oss.str(); } #endif #ifdef CATCH_CONFIG_CPP11_NULLPTR std::string toString( std::nullptr_t ) { return ""nullptr""; } #endif #ifdef __OBJC__ std::string toString( NSString const * const& nsstring ) { if( !nsstring ) return ""nil""; return ""@"" + toString([nsstring UTF8String]); } std::string toString( NSString * CATCH_ARC_STRONG const& nsstring ) { if( !nsstring ) return ""nil""; return ""@"" + toString([nsstring UTF8String]); } std::string toString( NSObject* const& nsObject ) { return toString( [nsObject description] ); } #endif } // end namespace Catch // #included from: catch_result_builder.hpp #define TWOBLUECUBES_CATCH_RESULT_BUILDER_HPP_INCLUDED namespace Catch { std::string capturedExpressionWithSecondArgument( std::string const& capturedExpression, std::string const& secondArg ) { return secondArg.empty() || secondArg == ""\""\"""" ? capturedExpression : capturedExpression + "", "" + secondArg; } ResultBuilder::ResultBuilder( char const* macroName, SourceLineInfo const& lineInfo, char const* capturedExpression, ResultDisposition::Flags resultDisposition, char const* secondArg ) : m_assertionInfo( macroName, lineInfo, capturedExpressionWithSecondArgument( capturedExpression, secondArg ), resultDisposition ), m_shouldDebugBreak( false ), m_shouldThrow( false ) {} ResultBuilder& ResultBuilder::setResultType( ResultWas::OfType result ) { m_data.resultType = result; return *this; } ResultBuilder& ResultBuilder::setResultType( bool result ) { m_data.resultType = result ? ResultWas::Ok : ResultWas::ExpressionFailed; return *this; } ResultBuilder& ResultBuilder::setLhs( std::string const& lhs ) { m_exprComponents.lhs = lhs; return *this; } ResultBuilder& ResultBuilder::setRhs( std::string const& rhs ) { m_exprComponents.rhs = rhs; return *this; } ResultBuilder& ResultBuilder::setOp( std::string const& op ) { m_exprComponents.op = op; return *this; } void ResultBuilder::endExpression() { m_exprComponents.testFalse = isFalseTest( m_assertionInfo.resultDisposition ); captureExpression(); } void ResultBuilder::useActiveException( ResultDisposition::Flags resultDisposition ) { m_assertionInfo.resultDisposition = resultDisposition; m_stream.oss << Catch::translateActiveException(); captureResult( ResultWas::ThrewException ); } void ResultBuilder::captureResult( ResultWas::OfType resultType ) { setResultType( resultType ); captureExpression(); } void ResultBuilder::captureExpectedException( std::string const& expectedMessage ) { if( expectedMessage.empty() ) captureExpectedException( Matchers::Impl::Generic::AllOf() ); else captureExpectedException( Matchers::Equals( expectedMessage ) ); } void ResultBuilder::captureExpectedException( Matchers::Impl::Matcher const& matcher ) { assert( m_exprComponents.testFalse == false ); AssertionResultData data = m_data; data.resultType = ResultWas::Ok; data.reconstructedExpression = m_assertionInfo.capturedExpression; std::string actualMessage = Catch::translateActiveException(); if( !matcher.match( actualMessage ) ) { data.resultType = ResultWas::ExpressionFailed; data.reconstructedExpression = actualMessage; } AssertionResult result( m_assertionInfo, data ); handleResult( result ); } void ResultBuilder::captureExpression() { AssertionResult result = build(); handleResult( result ); } void ResultBuilder::handleResult( AssertionResult const& result ) { getResultCapture().assertionEnded( result ); if( !result.isOk() ) { if( getCurrentContext().getConfig()->shouldDebugBreak() ) m_shouldDebugBreak = true; if( getCurrentContext().getRunner()->aborting() || (m_assertionInfo.resultDisposition & ResultDisposition::Normal) ) m_shouldThrow = true; } } void ResultBuilder::react() { if( m_shouldThrow ) throw Catch::TestFailureException(); } bool ResultBuilder::shouldDebugBreak() const { return m_shouldDebugBreak; } bool ResultBuilder::allowThrows() const { return getCurrentContext().getConfig()->allowThrows(); } AssertionResult ResultBuilder::build() const { assert( m_data.resultType != ResultWas::Unknown ); AssertionResultData data = m_data; // Flip bool results if testFalse is set if( m_exprComponents.testFalse ) { if( data.resultType == ResultWas::Ok ) data.resultType = ResultWas::ExpressionFailed; else if( data.resultType == ResultWas::ExpressionFailed ) data.resultType = ResultWas::Ok; } data.message = m_stream.oss.str(); data.reconstructedExpression = reconstructExpression(); if( m_exprComponents.testFalse ) { if( m_exprComponents.op == """" ) data.reconstructedExpression = ""!"" + data.reconstructedExpression; else data.reconstructedExpression = ""!("" + data.reconstructedExpression + "")""; } return AssertionResult( m_assertionInfo, data ); } std::string ResultBuilder::reconstructExpression() const { if( m_exprComponents.op == """" ) return m_exprComponents.lhs.empty() ? m_assertionInfo.capturedExpression : m_exprComponents.op + m_exprComponents.lhs; else if( m_exprComponents.op == ""matches"" ) return m_exprComponents.lhs + "" "" + m_exprComponents.rhs; else if( m_exprComponents.op != ""!"" ) { if( m_exprComponents.lhs.size() + m_exprComponents.rhs.size() < 40 && m_exprComponents.lhs.find(""\n"") == std::string::npos && m_exprComponents.rhs.find(""\n"") == std::string::npos ) return m_exprComponents.lhs + "" "" + m_exprComponents.op + "" "" + m_exprComponents.rhs; else return m_exprComponents.lhs + ""\n"" + m_exprComponents.op + ""\n"" + m_exprComponents.rhs; } else return ""{can't expand - use "" + m_assertionInfo.macroName + ""_FALSE( "" + m_assertionInfo.capturedExpression.substr(1) + "" ) instead of "" + m_assertionInfo.macroName + ""( "" + m_assertionInfo.capturedExpression + "" ) for better diagnostics}""; } } // end namespace Catch // #included from: catch_tag_alias_registry.hpp #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_HPP_INCLUDED // #included from: catch_tag_alias_registry.h #define TWOBLUECUBES_CATCH_TAG_ALIAS_REGISTRY_H_INCLUDED #include namespace Catch { class TagAliasRegistry : public ITagAliasRegistry { public: virtual ~TagAliasRegistry(); virtual Option find( std::string const& alias ) const; virtual std::string expandAliases( std::string const& unexpandedTestSpec ) const; void add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ); static TagAliasRegistry& get(); private: std::map m_registry; }; } // end namespace Catch #include #include namespace Catch { TagAliasRegistry::~TagAliasRegistry() {} Option TagAliasRegistry::find( std::string const& alias ) const { std::map::const_iterator it = m_registry.find( alias ); if( it != m_registry.end() ) return it->second; else return Option(); } std::string TagAliasRegistry::expandAliases( std::string const& unexpandedTestSpec ) const { std::string expandedTestSpec = unexpandedTestSpec; for( std::map::const_iterator it = m_registry.begin(), itEnd = m_registry.end(); it != itEnd; ++it ) { std::size_t pos = expandedTestSpec.find( it->first ); if( pos != std::string::npos ) { expandedTestSpec = expandedTestSpec.substr( 0, pos ) + it->second.tag + expandedTestSpec.substr( pos + it->first.size() ); } } return expandedTestSpec; } void TagAliasRegistry::add( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { if( !startsWith( alias, ""[@"" ) || !endsWith( alias, ""]"" ) ) { std::ostringstream oss; oss << ""error: tag alias, \"""" << alias << ""\"" is not of the form [@alias name].\n"" << lineInfo; throw std::domain_error( oss.str().c_str() ); } if( !m_registry.insert( std::make_pair( alias, TagAlias( tag, lineInfo ) ) ).second ) { std::ostringstream oss; oss << ""error: tag alias, \"""" << alias << ""\"" already registered.\n"" << ""\tFirst seen at "" << find(alias)->lineInfo << ""\n"" << ""\tRedefined at "" << lineInfo; throw std::domain_error( oss.str().c_str() ); } } TagAliasRegistry& TagAliasRegistry::get() { static TagAliasRegistry instance; return instance; } ITagAliasRegistry::~ITagAliasRegistry() {} ITagAliasRegistry const& ITagAliasRegistry::get() { return TagAliasRegistry::get(); } RegistrarForTagAliases::RegistrarForTagAliases( char const* alias, char const* tag, SourceLineInfo const& lineInfo ) { try { TagAliasRegistry::get().add( alias, tag, lineInfo ); } catch( std::exception& ex ) { Colour colourGuard( Colour::Red ); Catch::cerr() << ex.what() << std::endl; exit(1); } } } // end namespace Catch // #included from: ../reporters/catch_reporter_multi.hpp #define TWOBLUECUBES_CATCH_REPORTER_MULTI_HPP_INCLUDED namespace Catch { class MultipleReporters : public SharedImpl { typedef std::vector > Reporters; Reporters m_reporters; public: void add( Ptr const& reporter ) { m_reporters.push_back( reporter ); } public: // IStreamingReporter virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { return m_reporters[0]->getPreferences(); } virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->noMatchingTestCases( spec ); } virtual void testRunStarting( TestRunInfo const& testRunInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testRunStarting( testRunInfo ); } virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testGroupStarting( groupInfo ); } virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testCaseStarting( testInfo ); } virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->sectionStarting( sectionInfo ); } virtual void assertionStarting( AssertionInfo const& assertionInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->assertionStarting( assertionInfo ); } // The return value indicates if the messages buffer should be cleared: virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { bool clearBuffer = false; for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) clearBuffer |= (*it)->assertionEnded( assertionStats ); return clearBuffer; } virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->sectionEnded( sectionStats ); } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testCaseEnded( testCaseStats ); } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testGroupEnded( testGroupStats ); } virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->testRunEnded( testRunStats ); } virtual void skipTest( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { for( Reporters::const_iterator it = m_reporters.begin(), itEnd = m_reporters.end(); it != itEnd; ++it ) (*it)->skipTest( testInfo ); } virtual MultipleReporters* tryAsMulti() CATCH_OVERRIDE { return this; } }; Ptr addReporter( Ptr const& existingReporter, Ptr const& additionalReporter ) { Ptr resultingReporter; if( existingReporter ) { MultipleReporters* multi = existingReporter->tryAsMulti(); if( !multi ) { multi = new MultipleReporters; resultingReporter = Ptr( multi ); if( existingReporter ) multi->add( existingReporter ); } else resultingReporter = existingReporter; multi->add( additionalReporter ); } else resultingReporter = additionalReporter; return resultingReporter; } } // end namespace Catch // #included from: ../reporters/catch_reporter_xml.hpp #define TWOBLUECUBES_CATCH_REPORTER_XML_HPP_INCLUDED // #included from: catch_reporter_bases.hpp #define TWOBLUECUBES_CATCH_REPORTER_BASES_HPP_INCLUDED #include namespace Catch { struct StreamingReporterBase : SharedImpl { StreamingReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ), stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; } virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { return m_reporterPrefs; } virtual ~StreamingReporterBase() CATCH_OVERRIDE; virtual void noMatchingTestCases( std::string const& ) CATCH_OVERRIDE {} virtual void testRunStarting( TestRunInfo const& _testRunInfo ) CATCH_OVERRIDE { currentTestRunInfo = _testRunInfo; } virtual void testGroupStarting( GroupInfo const& _groupInfo ) CATCH_OVERRIDE { currentGroupInfo = _groupInfo; } virtual void testCaseStarting( TestCaseInfo const& _testInfo ) CATCH_OVERRIDE { currentTestCaseInfo = _testInfo; } virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { m_sectionStack.push_back( _sectionInfo ); } virtual void sectionEnded( SectionStats const& /* _sectionStats */ ) CATCH_OVERRIDE { m_sectionStack.pop_back(); } virtual void testCaseEnded( TestCaseStats const& /* _testCaseStats */ ) CATCH_OVERRIDE { currentTestCaseInfo.reset(); } virtual void testGroupEnded( TestGroupStats const& /* _testGroupStats */ ) CATCH_OVERRIDE { currentGroupInfo.reset(); } virtual void testRunEnded( TestRunStats const& /* _testRunStats */ ) CATCH_OVERRIDE { currentTestCaseInfo.reset(); currentGroupInfo.reset(); currentTestRunInfo.reset(); } virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE { // Don't do anything with this by default. // It can optionally be overridden in the derived class. } Ptr m_config; std::ostream& stream; LazyStat currentTestRunInfo; LazyStat currentGroupInfo; LazyStat currentTestCaseInfo; std::vector m_sectionStack; ReporterPreferences m_reporterPrefs; }; struct CumulativeReporterBase : SharedImpl { template struct Node : SharedImpl<> { explicit Node( T const& _value ) : value( _value ) {} virtual ~Node() {} typedef std::vector > ChildNodes; T value; ChildNodes children; }; struct SectionNode : SharedImpl<> { explicit SectionNode( SectionStats const& _stats ) : stats( _stats ) {} virtual ~SectionNode(); bool operator == ( SectionNode const& other ) const { return stats.sectionInfo.lineInfo == other.stats.sectionInfo.lineInfo; } bool operator == ( Ptr const& other ) const { return operator==( *other ); } SectionStats stats; typedef std::vector > ChildSections; typedef std::vector Assertions; ChildSections childSections; Assertions assertions; std::string stdOut; std::string stdErr; }; struct BySectionInfo { BySectionInfo( SectionInfo const& other ) : m_other( other ) {} BySectionInfo( BySectionInfo const& other ) : m_other( other.m_other ) {} bool operator() ( Ptr const& node ) const { return node->stats.sectionInfo.lineInfo == m_other.lineInfo; } private: void operator=( BySectionInfo const& ); SectionInfo const& m_other; }; typedef Node TestCaseNode; typedef Node TestGroupNode; typedef Node TestRunNode; CumulativeReporterBase( ReporterConfig const& _config ) : m_config( _config.fullConfig() ), stream( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = false; } ~CumulativeReporterBase(); virtual ReporterPreferences getPreferences() const CATCH_OVERRIDE { return m_reporterPrefs; } virtual void testRunStarting( TestRunInfo const& ) CATCH_OVERRIDE {} virtual void testGroupStarting( GroupInfo const& ) CATCH_OVERRIDE {} virtual void testCaseStarting( TestCaseInfo const& ) CATCH_OVERRIDE {} virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { SectionStats incompleteStats( sectionInfo, Counts(), 0, false ); Ptr node; if( m_sectionStack.empty() ) { if( !m_rootSection ) m_rootSection = new SectionNode( incompleteStats ); node = m_rootSection; } else { SectionNode& parentNode = *m_sectionStack.back(); SectionNode::ChildSections::const_iterator it = std::find_if( parentNode.childSections.begin(), parentNode.childSections.end(), BySectionInfo( sectionInfo ) ); if( it == parentNode.childSections.end() ) { node = new SectionNode( incompleteStats ); parentNode.childSections.push_back( node ); } else node = *it; } m_sectionStack.push_back( node ); m_deepestSection = node; } virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { assert( !m_sectionStack.empty() ); SectionNode& sectionNode = *m_sectionStack.back(); sectionNode.assertions.push_back( assertionStats ); return true; } virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { assert( !m_sectionStack.empty() ); SectionNode& node = *m_sectionStack.back(); node.stats = sectionStats; m_sectionStack.pop_back(); } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { Ptr node = new TestCaseNode( testCaseStats ); assert( m_sectionStack.size() == 0 ); node->children.push_back( m_rootSection ); m_testCases.push_back( node ); m_rootSection.reset(); assert( m_deepestSection ); m_deepestSection->stdOut = testCaseStats.stdOut; m_deepestSection->stdErr = testCaseStats.stdErr; } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { Ptr node = new TestGroupNode( testGroupStats ); node->children.swap( m_testCases ); m_testGroups.push_back( node ); } virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { Ptr node = new TestRunNode( testRunStats ); node->children.swap( m_testGroups ); m_testRuns.push_back( node ); testRunEndedCumulative(); } virtual void testRunEndedCumulative() = 0; virtual void skipTest( TestCaseInfo const& ) CATCH_OVERRIDE {} Ptr m_config; std::ostream& stream; std::vector m_assertions; std::vector > > m_sections; std::vector > m_testCases; std::vector > m_testGroups; std::vector > m_testRuns; Ptr m_rootSection; Ptr m_deepestSection; std::vector > m_sectionStack; ReporterPreferences m_reporterPrefs; }; template char const* getLineOfChars() { static char line[CATCH_CONFIG_CONSOLE_WIDTH] = {0}; if( !*line ) { memset( line, C, CATCH_CONFIG_CONSOLE_WIDTH-1 ); line[CATCH_CONFIG_CONSOLE_WIDTH-1] = 0; } return line; } struct TestEventListenerBase : StreamingReporterBase { TestEventListenerBase( ReporterConfig const& _config ) : StreamingReporterBase( _config ) {} virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE {} virtual bool assertionEnded( AssertionStats const& ) CATCH_OVERRIDE { return false; } }; } // end namespace Catch // #included from: ../internal/catch_reporter_registrars.hpp #define TWOBLUECUBES_CATCH_REPORTER_REGISTRARS_HPP_INCLUDED namespace Catch { template class LegacyReporterRegistrar { class ReporterFactory : public IReporterFactory { virtual IStreamingReporter* create( ReporterConfig const& config ) const { return new LegacyReporterAdapter( new T( config ) ); } virtual std::string getDescription() const { return T::getDescription(); } }; public: LegacyReporterRegistrar( std::string const& name ) { getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); } }; template class ReporterRegistrar { class ReporterFactory : public SharedImpl { // *** Please Note ***: // - If you end up here looking at a compiler error because it's trying to register // your custom reporter class be aware that the native reporter interface has changed // to IStreamingReporter. The ""legacy"" interface, IReporter, is still supported via // an adapter. Just use REGISTER_LEGACY_REPORTER to take advantage of the adapter. // However please consider updating to the new interface as the old one is now // deprecated and will probably be removed quite soon! // Please contact me via github if you have any questions at all about this. // In fact, ideally, please contact me anyway to let me know you've hit this - as I have // no idea who is actually using custom reporters at all (possibly no-one!). // The new interface is designed to minimise exposure to interface changes in the future. virtual IStreamingReporter* create( ReporterConfig const& config ) const { return new T( config ); } virtual std::string getDescription() const { return T::getDescription(); } }; public: ReporterRegistrar( std::string const& name ) { getMutableRegistryHub().registerReporter( name, new ReporterFactory() ); } }; template class ListenerRegistrar { class ListenerFactory : public SharedImpl { virtual IStreamingReporter* create( ReporterConfig const& config ) const { return new T( config ); } virtual std::string getDescription() const { return """"; } }; public: ListenerRegistrar() { getMutableRegistryHub().registerListener( new ListenerFactory() ); } }; } #define INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) \ namespace{ Catch::LegacyReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } #define INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) \ namespace{ Catch::ReporterRegistrar catch_internal_RegistrarFor##reporterType( name ); } #define INTERNAL_CATCH_REGISTER_LISTENER( listenerType ) \ namespace{ Catch::ListenerRegistrar catch_internal_RegistrarFor##listenerType; } // #included from: ../internal/catch_xmlwriter.hpp #define TWOBLUECUBES_CATCH_XMLWRITER_HPP_INCLUDED #include #include #include #include namespace Catch { class XmlEncode { public: enum ForWhat { ForTextNodes, ForAttributes }; XmlEncode( std::string const& str, ForWhat forWhat = ForTextNodes ) : m_str( str ), m_forWhat( forWhat ) {} void encodeTo( std::ostream& os ) const { // Apostrophe escaping not necessary if we always use "" to write attributes // (see: http://www.w3.org/TR/xml/#syntax) for( std::size_t i = 0; i < m_str.size(); ++ i ) { char c = m_str[i]; switch( c ) { case '<': os << ""<""; break; case '&': os << ""&""; break; case '>': // See: http://www.w3.org/TR/xml/#syntax if( i > 2 && m_str[i-1] == ']' && m_str[i-2] == ']' ) os << "">""; else os << c; break; case '\""': if( m_forWhat == ForAttributes ) os << """""; else os << c; break; default: // Escape control chars - based on contribution by @espenalb in PR #465 if ( ( c < '\x09' ) || ( c > '\x0D' && c < '\x20') || c=='\x7F' ) os << ""&#x"" << std::uppercase << std::hex << static_cast( c ); else os << c; } } } friend std::ostream& operator << ( std::ostream& os, XmlEncode const& xmlEncode ) { xmlEncode.encodeTo( os ); return os; } private: std::string m_str; ForWhat m_forWhat; }; class XmlWriter { public: class ScopedElement { public: ScopedElement( XmlWriter* writer ) : m_writer( writer ) {} ScopedElement( ScopedElement const& other ) : m_writer( other.m_writer ){ other.m_writer = CATCH_NULL; } ~ScopedElement() { if( m_writer ) m_writer->endElement(); } ScopedElement& writeText( std::string const& text, bool indent = true ) { m_writer->writeText( text, indent ); return *this; } template ScopedElement& writeAttribute( std::string const& name, T const& attribute ) { m_writer->writeAttribute( name, attribute ); return *this; } private: mutable XmlWriter* m_writer; }; XmlWriter() : m_tagIsOpen( false ), m_needsNewline( false ), m_os( &Catch::cout() ) {} XmlWriter( std::ostream& os ) : m_tagIsOpen( false ), m_needsNewline( false ), m_os( &os ) {} ~XmlWriter() { while( !m_tags.empty() ) endElement(); } XmlWriter& startElement( std::string const& name ) { ensureTagClosed(); newlineIfNecessary(); stream() << m_indent << ""<"" << name; m_tags.push_back( name ); m_indent += "" ""; m_tagIsOpen = true; return *this; } ScopedElement scopedElement( std::string const& name ) { ScopedElement scoped( this ); startElement( name ); return scoped; } XmlWriter& endElement() { newlineIfNecessary(); m_indent = m_indent.substr( 0, m_indent.size()-2 ); if( m_tagIsOpen ) { stream() << ""/>\n""; m_tagIsOpen = false; } else { stream() << m_indent << ""\n""; } m_tags.pop_back(); return *this; } XmlWriter& writeAttribute( std::string const& name, std::string const& attribute ) { if( !name.empty() && !attribute.empty() ) stream() << "" "" << name << ""=\"""" << XmlEncode( attribute, XmlEncode::ForAttributes ) << ""\""""; return *this; } XmlWriter& writeAttribute( std::string const& name, bool attribute ) { stream() << "" "" << name << ""=\"""" << ( attribute ? ""true"" : ""false"" ) << ""\""""; return *this; } template XmlWriter& writeAttribute( std::string const& name, T const& attribute ) { std::ostringstream oss; oss << attribute; return writeAttribute( name, oss.str() ); } XmlWriter& writeText( std::string const& text, bool indent = true ) { if( !text.empty() ){ bool tagWasOpen = m_tagIsOpen; ensureTagClosed(); if( tagWasOpen && indent ) stream() << m_indent; stream() << XmlEncode( text ); m_needsNewline = true; } return *this; } XmlWriter& writeComment( std::string const& text ) { ensureTagClosed(); stream() << m_indent << """"; m_needsNewline = true; return *this; } XmlWriter& writeBlankLine() { ensureTagClosed(); stream() << ""\n""; return *this; } void setStream( std::ostream& os ) { m_os = &os; } private: XmlWriter( XmlWriter const& ); void operator=( XmlWriter const& ); std::ostream& stream() { return *m_os; } void ensureTagClosed() { if( m_tagIsOpen ) { stream() << "">\n""; m_tagIsOpen = false; } } void newlineIfNecessary() { if( m_needsNewline ) { stream() << ""\n""; m_needsNewline = false; } } bool m_tagIsOpen; bool m_needsNewline; std::vector m_tags; std::string m_indent; std::ostream* m_os; }; } // #included from: catch_reenable_warnings.h #define TWOBLUECUBES_CATCH_REENABLE_WARNINGS_H_INCLUDED #ifdef __clang__ # ifdef __ICC // icpc defines the __clang__ macro # pragma warning(pop) # else # pragma clang diagnostic pop # endif #elif defined __GNUC__ # pragma GCC diagnostic pop #endif namespace Catch { class XmlReporter : public StreamingReporterBase { public: XmlReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ), m_sectionDepth( 0 ) { m_reporterPrefs.shouldRedirectStdOut = true; } virtual ~XmlReporter() CATCH_OVERRIDE; static std::string getDescription() { return ""Reports test results as an XML document""; } public: // StreamingReporterBase virtual void noMatchingTestCases( std::string const& s ) CATCH_OVERRIDE { StreamingReporterBase::noMatchingTestCases( s ); } virtual void testRunStarting( TestRunInfo const& testInfo ) CATCH_OVERRIDE { StreamingReporterBase::testRunStarting( testInfo ); m_xml.setStream( stream ); m_xml.startElement( ""Catch"" ); if( !m_config->name().empty() ) m_xml.writeAttribute( ""name"", m_config->name() ); } virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { StreamingReporterBase::testGroupStarting( groupInfo ); m_xml.startElement( ""Group"" ) .writeAttribute( ""name"", groupInfo.name ); } virtual void testCaseStarting( TestCaseInfo const& testInfo ) CATCH_OVERRIDE { StreamingReporterBase::testCaseStarting(testInfo); m_xml.startElement( ""TestCase"" ).writeAttribute( ""name"", trim( testInfo.name ) ); if ( m_config->showDurations() == ShowDurations::Always ) m_testCaseTimer.start(); } virtual void sectionStarting( SectionInfo const& sectionInfo ) CATCH_OVERRIDE { StreamingReporterBase::sectionStarting( sectionInfo ); if( m_sectionDepth++ > 0 ) { m_xml.startElement( ""Section"" ) .writeAttribute( ""name"", trim( sectionInfo.name ) ) .writeAttribute( ""description"", sectionInfo.description ); } } virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { } virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { const AssertionResult& assertionResult = assertionStats.assertionResult; // Print any info messages in tags. if( assertionStats.assertionResult.getResultType() != ResultWas::Ok ) { for( std::vector::const_iterator it = assertionStats.infoMessages.begin(), itEnd = assertionStats.infoMessages.end(); it != itEnd; ++it ) { if( it->type == ResultWas::Info ) { m_xml.scopedElement( ""Info"" ) .writeText( it->message ); } else if ( it->type == ResultWas::Warning ) { m_xml.scopedElement( ""Warning"" ) .writeText( it->message ); } } } // Drop out if result was successful but we're not printing them. if( !m_config->includeSuccessfulResults() && isOk(assertionResult.getResultType()) ) return true; // Print the expression if there is one. if( assertionResult.hasExpression() ) { m_xml.startElement( ""Expression"" ) .writeAttribute( ""success"", assertionResult.succeeded() ) .writeAttribute( ""type"", assertionResult.getTestMacroName() ) .writeAttribute( ""filename"", assertionResult.getSourceInfo().file ) .writeAttribute( ""line"", assertionResult.getSourceInfo().line ); m_xml.scopedElement( ""Original"" ) .writeText( assertionResult.getExpression() ); m_xml.scopedElement( ""Expanded"" ) .writeText( assertionResult.getExpandedExpression() ); } // And... Print a result applicable to each result type. switch( assertionResult.getResultType() ) { case ResultWas::ThrewException: m_xml.scopedElement( ""Exception"" ) .writeAttribute( ""filename"", assertionResult.getSourceInfo().file ) .writeAttribute( ""line"", assertionResult.getSourceInfo().line ) .writeText( assertionResult.getMessage() ); break; case ResultWas::FatalErrorCondition: m_xml.scopedElement( ""Fatal Error Condition"" ) .writeAttribute( ""filename"", assertionResult.getSourceInfo().file ) .writeAttribute( ""line"", assertionResult.getSourceInfo().line ) .writeText( assertionResult.getMessage() ); break; case ResultWas::Info: m_xml.scopedElement( ""Info"" ) .writeText( assertionResult.getMessage() ); break; case ResultWas::Warning: // Warning will already have been written break; case ResultWas::ExplicitFailure: m_xml.scopedElement( ""Failure"" ) .writeText( assertionResult.getMessage() ); break; default: break; } if( assertionResult.hasExpression() ) m_xml.endElement(); return true; } virtual void sectionEnded( SectionStats const& sectionStats ) CATCH_OVERRIDE { StreamingReporterBase::sectionEnded( sectionStats ); if( --m_sectionDepth > 0 ) { XmlWriter::ScopedElement e = m_xml.scopedElement( ""OverallResults"" ); e.writeAttribute( ""successes"", sectionStats.assertions.passed ); e.writeAttribute( ""failures"", sectionStats.assertions.failed ); e.writeAttribute( ""expectedFailures"", sectionStats.assertions.failedButOk ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( ""durationInSeconds"", sectionStats.durationInSeconds ); m_xml.endElement(); } } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { StreamingReporterBase::testCaseEnded( testCaseStats ); XmlWriter::ScopedElement e = m_xml.scopedElement( ""OverallResult"" ); e.writeAttribute( ""success"", testCaseStats.totals.assertions.allOk() ); if ( m_config->showDurations() == ShowDurations::Always ) e.writeAttribute( ""durationInSeconds"", m_testCaseTimer.getElapsedSeconds() ); m_xml.endElement(); } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { StreamingReporterBase::testGroupEnded( testGroupStats ); // TODO: Check testGroupStats.aborting and act accordingly. m_xml.scopedElement( ""OverallResults"" ) .writeAttribute( ""successes"", testGroupStats.totals.assertions.passed ) .writeAttribute( ""failures"", testGroupStats.totals.assertions.failed ) .writeAttribute( ""expectedFailures"", testGroupStats.totals.assertions.failedButOk ); m_xml.endElement(); } virtual void testRunEnded( TestRunStats const& testRunStats ) CATCH_OVERRIDE { StreamingReporterBase::testRunEnded( testRunStats ); m_xml.scopedElement( ""OverallResults"" ) .writeAttribute( ""successes"", testRunStats.totals.assertions.passed ) .writeAttribute( ""failures"", testRunStats.totals.assertions.failed ) .writeAttribute( ""expectedFailures"", testRunStats.totals.assertions.failedButOk ); m_xml.endElement(); } private: Timer m_testCaseTimer; XmlWriter m_xml; int m_sectionDepth; }; INTERNAL_CATCH_REGISTER_REPORTER( ""xml"", XmlReporter ) } // end namespace Catch // #included from: ../reporters/catch_reporter_junit.hpp #define TWOBLUECUBES_CATCH_REPORTER_JUNIT_HPP_INCLUDED #include namespace Catch { class JunitReporter : public CumulativeReporterBase { public: JunitReporter( ReporterConfig const& _config ) : CumulativeReporterBase( _config ), xml( _config.stream() ) { m_reporterPrefs.shouldRedirectStdOut = true; } virtual ~JunitReporter() CATCH_OVERRIDE; static std::string getDescription() { return ""Reports test results in an XML format that looks like Ant's junitreport target""; } virtual void noMatchingTestCases( std::string const& /*spec*/ ) CATCH_OVERRIDE {} virtual void testRunStarting( TestRunInfo const& runInfo ) CATCH_OVERRIDE { CumulativeReporterBase::testRunStarting( runInfo ); xml.startElement( ""testsuites"" ); } virtual void testGroupStarting( GroupInfo const& groupInfo ) CATCH_OVERRIDE { suiteTimer.start(); stdOutForSuite.str(""""); stdErrForSuite.str(""""); unexpectedExceptions = 0; CumulativeReporterBase::testGroupStarting( groupInfo ); } virtual bool assertionEnded( AssertionStats const& assertionStats ) CATCH_OVERRIDE { if( assertionStats.assertionResult.getResultType() == ResultWas::ThrewException ) unexpectedExceptions++; return CumulativeReporterBase::assertionEnded( assertionStats ); } virtual void testCaseEnded( TestCaseStats const& testCaseStats ) CATCH_OVERRIDE { stdOutForSuite << testCaseStats.stdOut; stdErrForSuite << testCaseStats.stdErr; CumulativeReporterBase::testCaseEnded( testCaseStats ); } virtual void testGroupEnded( TestGroupStats const& testGroupStats ) CATCH_OVERRIDE { double suiteTime = suiteTimer.getElapsedSeconds(); CumulativeReporterBase::testGroupEnded( testGroupStats ); writeGroup( *m_testGroups.back(), suiteTime ); } virtual void testRunEndedCumulative() CATCH_OVERRIDE { xml.endElement(); } void writeGroup( TestGroupNode const& groupNode, double suiteTime ) { XmlWriter::ScopedElement e = xml.scopedElement( ""testsuite"" ); TestGroupStats const& stats = groupNode.value; xml.writeAttribute( ""name"", stats.groupInfo.name ); xml.writeAttribute( ""errors"", unexpectedExceptions ); xml.writeAttribute( ""failures"", stats.totals.assertions.failed-unexpectedExceptions ); xml.writeAttribute( ""tests"", stats.totals.assertions.total() ); xml.writeAttribute( ""hostname"", ""tbd"" ); // !TBD if( m_config->showDurations() == ShowDurations::Never ) xml.writeAttribute( ""time"", """" ); else xml.writeAttribute( ""time"", suiteTime ); xml.writeAttribute( ""timestamp"", ""tbd"" ); // !TBD // Write test cases for( TestGroupNode::ChildNodes::const_iterator it = groupNode.children.begin(), itEnd = groupNode.children.end(); it != itEnd; ++it ) writeTestCase( **it ); xml.scopedElement( ""system-out"" ).writeText( trim( stdOutForSuite.str() ), false ); xml.scopedElement( ""system-err"" ).writeText( trim( stdErrForSuite.str() ), false ); } void writeTestCase( TestCaseNode const& testCaseNode ) { TestCaseStats const& stats = testCaseNode.value; // All test cases have exactly one section - which represents the // test case itself. That section may have 0-n nested sections assert( testCaseNode.children.size() == 1 ); SectionNode const& rootSection = *testCaseNode.children.front(); std::string className = stats.testInfo.className; if( className.empty() ) { if( rootSection.childSections.empty() ) className = ""global""; } writeSection( className, """", rootSection ); } void writeSection( std::string const& className, std::string const& rootName, SectionNode const& sectionNode ) { std::string name = trim( sectionNode.stats.sectionInfo.name ); if( !rootName.empty() ) name = rootName + ""/"" + name; if( !sectionNode.assertions.empty() || !sectionNode.stdOut.empty() || !sectionNode.stdErr.empty() ) { XmlWriter::ScopedElement e = xml.scopedElement( ""testcase"" ); if( className.empty() ) { xml.writeAttribute( ""classname"", name ); xml.writeAttribute( ""name"", ""root"" ); } else { xml.writeAttribute( ""classname"", className ); xml.writeAttribute( ""name"", name ); } xml.writeAttribute( ""time"", Catch::toString( sectionNode.stats.durationInSeconds ) ); writeAssertions( sectionNode ); if( !sectionNode.stdOut.empty() ) xml.scopedElement( ""system-out"" ).writeText( trim( sectionNode.stdOut ), false ); if( !sectionNode.stdErr.empty() ) xml.scopedElement( ""system-err"" ).writeText( trim( sectionNode.stdErr ), false ); } for( SectionNode::ChildSections::const_iterator it = sectionNode.childSections.begin(), itEnd = sectionNode.childSections.end(); it != itEnd; ++it ) if( className.empty() ) writeSection( name, """", **it ); else writeSection( className, name, **it ); } void writeAssertions( SectionNode const& sectionNode ) { for( SectionNode::Assertions::const_iterator it = sectionNode.assertions.begin(), itEnd = sectionNode.assertions.end(); it != itEnd; ++it ) writeAssertion( *it ); } void writeAssertion( AssertionStats const& stats ) { AssertionResult const& result = stats.assertionResult; if( !result.isOk() ) { std::string elementName; switch( result.getResultType() ) { case ResultWas::ThrewException: case ResultWas::FatalErrorCondition: elementName = ""error""; break; case ResultWas::ExplicitFailure: elementName = ""failure""; break; case ResultWas::ExpressionFailed: elementName = ""failure""; break; case ResultWas::DidntThrowException: elementName = ""failure""; break; // We should never see these here: case ResultWas::Info: case ResultWas::Warning: case ResultWas::Ok: case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: elementName = ""internalError""; break; } XmlWriter::ScopedElement e = xml.scopedElement( elementName ); xml.writeAttribute( ""message"", result.getExpandedExpression() ); xml.writeAttribute( ""type"", result.getTestMacroName() ); std::ostringstream oss; if( !result.getMessage().empty() ) oss << result.getMessage() << ""\n""; for( std::vector::const_iterator it = stats.infoMessages.begin(), itEnd = stats.infoMessages.end(); it != itEnd; ++it ) if( it->type == ResultWas::Info ) oss << it->message << ""\n""; oss << ""at "" << result.getSourceInfo(); xml.writeText( oss.str(), false ); } } XmlWriter xml; Timer suiteTimer; std::ostringstream stdOutForSuite; std::ostringstream stdErrForSuite; unsigned int unexpectedExceptions; }; INTERNAL_CATCH_REGISTER_REPORTER( ""junit"", JunitReporter ) } // end namespace Catch // #included from: ../reporters/catch_reporter_console.hpp #define TWOBLUECUBES_CATCH_REPORTER_CONSOLE_HPP_INCLUDED namespace Catch { struct ConsoleReporter : StreamingReporterBase { ConsoleReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ), m_headerPrinted( false ) {} virtual ~ConsoleReporter() CATCH_OVERRIDE; static std::string getDescription() { return ""Reports test results as plain lines of text""; } virtual void noMatchingTestCases( std::string const& spec ) CATCH_OVERRIDE { stream << ""No test cases matched '"" << spec << ""'"" << std::endl; } virtual void assertionStarting( AssertionInfo const& ) CATCH_OVERRIDE { } virtual bool assertionEnded( AssertionStats const& _assertionStats ) CATCH_OVERRIDE { AssertionResult const& result = _assertionStats.assertionResult; bool printInfoMessages = true; // Drop out if result was successful and we're not printing those if( !m_config->includeSuccessfulResults() && result.isOk() ) { if( result.getResultType() != ResultWas::Warning ) return false; printInfoMessages = false; } lazyPrint(); AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); printer.print(); stream << std::endl; return true; } virtual void sectionStarting( SectionInfo const& _sectionInfo ) CATCH_OVERRIDE { m_headerPrinted = false; StreamingReporterBase::sectionStarting( _sectionInfo ); } virtual void sectionEnded( SectionStats const& _sectionStats ) CATCH_OVERRIDE { if( _sectionStats.missingAssertions ) { lazyPrint(); Colour colour( Colour::ResultError ); if( m_sectionStack.size() > 1 ) stream << ""\nNo assertions in section""; else stream << ""\nNo assertions in test case""; stream << "" '"" << _sectionStats.sectionInfo.name << ""'\n"" << std::endl; } if( m_headerPrinted ) { if( m_config->showDurations() == ShowDurations::Always ) stream << ""Completed in "" << _sectionStats.durationInSeconds << ""s"" << std::endl; m_headerPrinted = false; } else { if( m_config->showDurations() == ShowDurations::Always ) stream << _sectionStats.sectionInfo.name << "" completed in "" << _sectionStats.durationInSeconds << ""s"" << std::endl; } StreamingReporterBase::sectionEnded( _sectionStats ); } virtual void testCaseEnded( TestCaseStats const& _testCaseStats ) CATCH_OVERRIDE { StreamingReporterBase::testCaseEnded( _testCaseStats ); m_headerPrinted = false; } virtual void testGroupEnded( TestGroupStats const& _testGroupStats ) CATCH_OVERRIDE { if( currentGroupInfo.used ) { printSummaryDivider(); stream << ""Summary for group '"" << _testGroupStats.groupInfo.name << ""':\n""; printTotals( _testGroupStats.totals ); stream << ""\n"" << std::endl; } StreamingReporterBase::testGroupEnded( _testGroupStats ); } virtual void testRunEnded( TestRunStats const& _testRunStats ) CATCH_OVERRIDE { printTotalsDivider( _testRunStats.totals ); printTotals( _testRunStats.totals ); stream << std::endl; StreamingReporterBase::testRunEnded( _testRunStats ); } private: class AssertionPrinter { void operator= ( AssertionPrinter const& ); public: AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) : stream( _stream ), stats( _stats ), result( _stats.assertionResult ), colour( Colour::None ), message( result.getMessage() ), messages( _stats.infoMessages ), printInfoMessages( _printInfoMessages ) { switch( result.getResultType() ) { case ResultWas::Ok: colour = Colour::Success; passOrFail = ""PASSED""; //if( result.hasMessage() ) if( _stats.infoMessages.size() == 1 ) messageLabel = ""with message""; if( _stats.infoMessages.size() > 1 ) messageLabel = ""with messages""; break; case ResultWas::ExpressionFailed: if( result.isOk() ) { colour = Colour::Success; passOrFail = ""FAILED - but was ok""; } else { colour = Colour::Error; passOrFail = ""FAILED""; } if( _stats.infoMessages.size() == 1 ) messageLabel = ""with message""; if( _stats.infoMessages.size() > 1 ) messageLabel = ""with messages""; break; case ResultWas::ThrewException: colour = Colour::Error; passOrFail = ""FAILED""; messageLabel = ""due to unexpected exception with message""; break; case ResultWas::FatalErrorCondition: colour = Colour::Error; passOrFail = ""FAILED""; messageLabel = ""due to a fatal error condition""; break; case ResultWas::DidntThrowException: colour = Colour::Error; passOrFail = ""FAILED""; messageLabel = ""because no exception was thrown where one was expected""; break; case ResultWas::Info: messageLabel = ""info""; break; case ResultWas::Warning: messageLabel = ""warning""; break; case ResultWas::ExplicitFailure: passOrFail = ""FAILED""; colour = Colour::Error; if( _stats.infoMessages.size() == 1 ) messageLabel = ""explicitly with message""; if( _stats.infoMessages.size() > 1 ) messageLabel = ""explicitly with messages""; break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: passOrFail = ""** internal error **""; colour = Colour::Error; break; } } void print() const { printSourceInfo(); if( stats.totals.assertions.total() > 0 ) { if( result.isOk() ) stream << ""\n""; printResultType(); printOriginalExpression(); printReconstructedExpression(); } else { stream << ""\n""; } printMessage(); } private: void printResultType() const { if( !passOrFail.empty() ) { Colour colourGuard( colour ); stream << passOrFail << "":\n""; } } void printOriginalExpression() const { if( result.hasExpression() ) { Colour colourGuard( Colour::OriginalExpression ); stream << "" ""; stream << result.getExpressionInMacro(); stream << ""\n""; } } void printReconstructedExpression() const { if( result.hasExpandedExpression() ) { stream << ""with expansion:\n""; Colour colourGuard( Colour::ReconstructedExpression ); stream << Text( result.getExpandedExpression(), TextAttributes().setIndent(2) ) << ""\n""; } } void printMessage() const { if( !messageLabel.empty() ) stream << messageLabel << "":"" << ""\n""; for( std::vector::const_iterator it = messages.begin(), itEnd = messages.end(); it != itEnd; ++it ) { // If this assertion is a warning ignore any INFO messages if( printInfoMessages || it->type != ResultWas::Info ) stream << Text( it->message, TextAttributes().setIndent(2) ) << ""\n""; } } void printSourceInfo() const { Colour colourGuard( Colour::FileName ); stream << result.getSourceInfo() << "": ""; } std::ostream& stream; AssertionStats const& stats; AssertionResult const& result; Colour::Code colour; std::string passOrFail; std::string messageLabel; std::string message; std::vector messages; bool printInfoMessages; }; void lazyPrint() { if( !currentTestRunInfo.used ) lazyPrintRunInfo(); if( !currentGroupInfo.used ) lazyPrintGroupInfo(); if( !m_headerPrinted ) { printTestCaseAndSectionHeader(); m_headerPrinted = true; } } void lazyPrintRunInfo() { stream << ""\n"" << getLineOfChars<'~'>() << ""\n""; Colour colour( Colour::SecondaryText ); stream << currentTestRunInfo->name << "" is a Catch v"" << libraryVersion << "" host application.\n"" << ""Run with -? for options\n\n""; if( m_config->rngSeed() != 0 ) stream << ""Randomness seeded to: "" << m_config->rngSeed() << ""\n\n""; currentTestRunInfo.used = true; } void lazyPrintGroupInfo() { if( !currentGroupInfo->name.empty() && currentGroupInfo->groupsCounts > 1 ) { printClosedHeader( ""Group: "" + currentGroupInfo->name ); currentGroupInfo.used = true; } } void printTestCaseAndSectionHeader() { assert( !m_sectionStack.empty() ); printOpenHeader( currentTestCaseInfo->name ); if( m_sectionStack.size() > 1 ) { Colour colourGuard( Colour::Headers ); std::vector::const_iterator it = m_sectionStack.begin()+1, // Skip first section (test case) itEnd = m_sectionStack.end(); for( ; it != itEnd; ++it ) printHeaderString( it->name, 2 ); } SourceLineInfo lineInfo = m_sectionStack.front().lineInfo; if( !lineInfo.empty() ){ stream << getLineOfChars<'-'>() << ""\n""; Colour colourGuard( Colour::FileName ); stream << lineInfo << ""\n""; } stream << getLineOfChars<'.'>() << ""\n"" << std::endl; } void printClosedHeader( std::string const& _name ) { printOpenHeader( _name ); stream << getLineOfChars<'.'>() << ""\n""; } void printOpenHeader( std::string const& _name ) { stream << getLineOfChars<'-'>() << ""\n""; { Colour colourGuard( Colour::Headers ); printHeaderString( _name ); } } // if string has a : in first line will set indent to follow it on // subsequent lines void printHeaderString( std::string const& _string, std::size_t indent = 0 ) { std::size_t i = _string.find( "": "" ); if( i != std::string::npos ) i+=2; else i = 0; stream << Text( _string, TextAttributes() .setIndent( indent+i) .setInitialIndent( indent ) ) << ""\n""; } struct SummaryColumn { SummaryColumn( std::string const& _label, Colour::Code _colour ) : label( _label ), colour( _colour ) {} SummaryColumn addRow( std::size_t count ) { std::ostringstream oss; oss << count; std::string row = oss.str(); for( std::vector::iterator it = rows.begin(); it != rows.end(); ++it ) { while( it->size() < row.size() ) *it = "" "" + *it; while( it->size() > row.size() ) row = "" "" + row; } rows.push_back( row ); return *this; } std::string label; Colour::Code colour; std::vector rows; }; void printTotals( Totals const& totals ) { if( totals.testCases.total() == 0 ) { stream << Colour( Colour::Warning ) << ""No tests ran\n""; } else if( totals.assertions.total() > 0 && totals.testCases.allPassed() ) { stream << Colour( Colour::ResultSuccess ) << ""All tests passed""; stream << "" ("" << pluralise( totals.assertions.passed, ""assertion"" ) << "" in "" << pluralise( totals.testCases.passed, ""test case"" ) << "")"" << ""\n""; } else { std::vector columns; columns.push_back( SummaryColumn( """", Colour::None ) .addRow( totals.testCases.total() ) .addRow( totals.assertions.total() ) ); columns.push_back( SummaryColumn( ""passed"", Colour::Success ) .addRow( totals.testCases.passed ) .addRow( totals.assertions.passed ) ); columns.push_back( SummaryColumn( ""failed"", Colour::ResultError ) .addRow( totals.testCases.failed ) .addRow( totals.assertions.failed ) ); columns.push_back( SummaryColumn( ""failed as expected"", Colour::ResultExpectedFailure ) .addRow( totals.testCases.failedButOk ) .addRow( totals.assertions.failedButOk ) ); printSummaryRow( ""test cases"", columns, 0 ); printSummaryRow( ""assertions"", columns, 1 ); } } void printSummaryRow( std::string const& label, std::vector const& cols, std::size_t row ) { for( std::vector::const_iterator it = cols.begin(); it != cols.end(); ++it ) { std::string value = it->rows[row]; if( it->label.empty() ) { stream << label << "": ""; if( value != ""0"" ) stream << value; else stream << Colour( Colour::Warning ) << ""- none -""; } else if( value != ""0"" ) { stream << Colour( Colour::LightGrey ) << "" | ""; stream << Colour( it->colour ) << value << "" "" << it->label; } } stream << ""\n""; } static std::size_t makeRatio( std::size_t number, std::size_t total ) { std::size_t ratio = total > 0 ? CATCH_CONFIG_CONSOLE_WIDTH * number/ total : 0; return ( ratio == 0 && number > 0 ) ? 1 : ratio; } static std::size_t& findMax( std::size_t& i, std::size_t& j, std::size_t& k ) { if( i > j && i > k ) return i; else if( j > k ) return j; else return k; } void printTotalsDivider( Totals const& totals ) { if( totals.testCases.total() > 0 ) { std::size_t failedRatio = makeRatio( totals.testCases.failed, totals.testCases.total() ); std::size_t failedButOkRatio = makeRatio( totals.testCases.failedButOk, totals.testCases.total() ); std::size_t passedRatio = makeRatio( totals.testCases.passed, totals.testCases.total() ); while( failedRatio + failedButOkRatio + passedRatio < CATCH_CONFIG_CONSOLE_WIDTH-1 ) findMax( failedRatio, failedButOkRatio, passedRatio )++; while( failedRatio + failedButOkRatio + passedRatio > CATCH_CONFIG_CONSOLE_WIDTH-1 ) findMax( failedRatio, failedButOkRatio, passedRatio )--; stream << Colour( Colour::Error ) << std::string( failedRatio, '=' ); stream << Colour( Colour::ResultExpectedFailure ) << std::string( failedButOkRatio, '=' ); if( totals.testCases.allPassed() ) stream << Colour( Colour::ResultSuccess ) << std::string( passedRatio, '=' ); else stream << Colour( Colour::Success ) << std::string( passedRatio, '=' ); } else { stream << Colour( Colour::Warning ) << std::string( CATCH_CONFIG_CONSOLE_WIDTH-1, '=' ); } stream << ""\n""; } void printSummaryDivider() { stream << getLineOfChars<'-'>() << ""\n""; } private: bool m_headerPrinted; }; INTERNAL_CATCH_REGISTER_REPORTER( ""console"", ConsoleReporter ) } // end namespace Catch // #included from: ../reporters/catch_reporter_compact.hpp #define TWOBLUECUBES_CATCH_REPORTER_COMPACT_HPP_INCLUDED namespace Catch { struct CompactReporter : StreamingReporterBase { CompactReporter( ReporterConfig const& _config ) : StreamingReporterBase( _config ) {} virtual ~CompactReporter(); static std::string getDescription() { return ""Reports test results on a single line, suitable for IDEs""; } virtual ReporterPreferences getPreferences() const { ReporterPreferences prefs; prefs.shouldRedirectStdOut = false; return prefs; } virtual void noMatchingTestCases( std::string const& spec ) { stream << ""No test cases matched '"" << spec << ""'"" << std::endl; } virtual void assertionStarting( AssertionInfo const& ) { } virtual bool assertionEnded( AssertionStats const& _assertionStats ) { AssertionResult const& result = _assertionStats.assertionResult; bool printInfoMessages = true; // Drop out if result was successful and we're not printing those if( !m_config->includeSuccessfulResults() && result.isOk() ) { if( result.getResultType() != ResultWas::Warning ) return false; printInfoMessages = false; } AssertionPrinter printer( stream, _assertionStats, printInfoMessages ); printer.print(); stream << std::endl; return true; } virtual void testRunEnded( TestRunStats const& _testRunStats ) { printTotals( _testRunStats.totals ); stream << ""\n"" << std::endl; StreamingReporterBase::testRunEnded( _testRunStats ); } private: class AssertionPrinter { void operator= ( AssertionPrinter const& ); public: AssertionPrinter( std::ostream& _stream, AssertionStats const& _stats, bool _printInfoMessages ) : stream( _stream ) , stats( _stats ) , result( _stats.assertionResult ) , messages( _stats.infoMessages ) , itMessage( _stats.infoMessages.begin() ) , printInfoMessages( _printInfoMessages ) {} void print() { printSourceInfo(); itMessage = messages.begin(); switch( result.getResultType() ) { case ResultWas::Ok: printResultType( Colour::ResultSuccess, passedString() ); printOriginalExpression(); printReconstructedExpression(); if ( ! result.hasExpression() ) printRemainingMessages( Colour::None ); else printRemainingMessages(); break; case ResultWas::ExpressionFailed: if( result.isOk() ) printResultType( Colour::ResultSuccess, failedString() + std::string( "" - but was ok"" ) ); else printResultType( Colour::Error, failedString() ); printOriginalExpression(); printReconstructedExpression(); printRemainingMessages(); break; case ResultWas::ThrewException: printResultType( Colour::Error, failedString() ); printIssue( ""unexpected exception with message:"" ); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::FatalErrorCondition: printResultType( Colour::Error, failedString() ); printIssue( ""fatal error condition with message:"" ); printMessage(); printExpressionWas(); printRemainingMessages(); break; case ResultWas::DidntThrowException: printResultType( Colour::Error, failedString() ); printIssue( ""expected exception, got none"" ); printExpressionWas(); printRemainingMessages(); break; case ResultWas::Info: printResultType( Colour::None, ""info"" ); printMessage(); printRemainingMessages(); break; case ResultWas::Warning: printResultType( Colour::None, ""warning"" ); printMessage(); printRemainingMessages(); break; case ResultWas::ExplicitFailure: printResultType( Colour::Error, failedString() ); printIssue( ""explicitly"" ); printRemainingMessages( Colour::None ); break; // These cases are here to prevent compiler warnings case ResultWas::Unknown: case ResultWas::FailureBit: case ResultWas::Exception: printResultType( Colour::Error, ""** internal error **"" ); break; } } private: // Colour::LightGrey static Colour::Code dimColour() { return Colour::FileName; } #ifdef CATCH_PLATFORM_MAC static const char* failedString() { return ""FAILED""; } static const char* passedString() { return ""PASSED""; } #else static const char* failedString() { return ""failed""; } static const char* passedString() { return ""passed""; } #endif void printSourceInfo() const { Colour colourGuard( Colour::FileName ); stream << result.getSourceInfo() << "":""; } void printResultType( Colour::Code colour, std::string passOrFail ) const { if( !passOrFail.empty() ) { { Colour colourGuard( colour ); stream << "" "" << passOrFail; } stream << "":""; } } void printIssue( std::string issue ) const { stream << "" "" << issue; } void printExpressionWas() { if( result.hasExpression() ) { stream << "";""; { Colour colour( dimColour() ); stream << "" expression was:""; } printOriginalExpression(); } } void printOriginalExpression() const { if( result.hasExpression() ) { stream << "" "" << result.getExpression(); } } void printReconstructedExpression() const { if( result.hasExpandedExpression() ) { { Colour colour( dimColour() ); stream << "" for: ""; } stream << result.getExpandedExpression(); } } void printMessage() { if ( itMessage != messages.end() ) { stream << "" '"" << itMessage->message << ""'""; ++itMessage; } } void printRemainingMessages( Colour::Code colour = dimColour() ) { if ( itMessage == messages.end() ) return; // using messages.end() directly yields compilation error: std::vector::const_iterator itEnd = messages.end(); const std::size_t N = static_cast( std::distance( itMessage, itEnd ) ); { Colour colourGuard( colour ); stream << "" with "" << pluralise( N, ""message"" ) << "":""; } for(; itMessage != itEnd; ) { // If this assertion is a warning ignore any INFO messages if( printInfoMessages || itMessage->type != ResultWas::Info ) { stream << "" '"" << itMessage->message << ""'""; if ( ++itMessage != itEnd ) { Colour colourGuard( dimColour() ); stream << "" and""; } } } } private: std::ostream& stream; AssertionStats const& stats; AssertionResult const& result; std::vector messages; std::vector::const_iterator itMessage; bool printInfoMessages; }; // Colour, message variants: // - white: No tests ran. // - red: Failed [both/all] N test cases, failed [both/all] M assertions. // - white: Passed [both/all] N test cases (no assertions). // - red: Failed N tests cases, failed M assertions. // - green: Passed [both/all] N tests cases with M assertions. std::string bothOrAll( std::size_t count ) const { return count == 1 ? """" : count == 2 ? ""both "" : ""all "" ; } void printTotals( const Totals& totals ) const { if( totals.testCases.total() == 0 ) { stream << ""No tests ran.""; } else if( totals.testCases.failed == totals.testCases.total() ) { Colour colour( Colour::ResultError ); const std::string qualify_assertions_failed = totals.assertions.failed == totals.assertions.total() ? bothOrAll( totals.assertions.failed ) : """"; stream << ""Failed "" << bothOrAll( totals.testCases.failed ) << pluralise( totals.testCases.failed, ""test case"" ) << "", "" ""failed "" << qualify_assertions_failed << pluralise( totals.assertions.failed, ""assertion"" ) << "".""; } else if( totals.assertions.total() == 0 ) { stream << ""Passed "" << bothOrAll( totals.testCases.total() ) << pluralise( totals.testCases.total(), ""test case"" ) << "" (no assertions).""; } else if( totals.assertions.failed ) { Colour colour( Colour::ResultError ); stream << ""Failed "" << pluralise( totals.testCases.failed, ""test case"" ) << "", "" ""failed "" << pluralise( totals.assertions.failed, ""assertion"" ) << "".""; } else { Colour colour( Colour::ResultSuccess ); stream << ""Passed "" << bothOrAll( totals.testCases.passed ) << pluralise( totals.testCases.passed, ""test case"" ) << "" with "" << pluralise( totals.assertions.passed, ""assertion"" ) << "".""; } } }; INTERNAL_CATCH_REGISTER_REPORTER( ""compact"", CompactReporter ) } // end namespace Catch namespace Catch { // These are all here to avoid warnings about not having any out of line // virtual methods NonCopyable::~NonCopyable() {} IShared::~IShared() {} IStream::~IStream() CATCH_NOEXCEPT {} FileStream::~FileStream() CATCH_NOEXCEPT {} CoutStream::~CoutStream() CATCH_NOEXCEPT {} DebugOutStream::~DebugOutStream() CATCH_NOEXCEPT {} StreamBufBase::~StreamBufBase() CATCH_NOEXCEPT {} IContext::~IContext() {} IResultCapture::~IResultCapture() {} ITestCase::~ITestCase() {} ITestCaseRegistry::~ITestCaseRegistry() {} IRegistryHub::~IRegistryHub() {} IMutableRegistryHub::~IMutableRegistryHub() {} IExceptionTranslator::~IExceptionTranslator() {} IExceptionTranslatorRegistry::~IExceptionTranslatorRegistry() {} IReporter::~IReporter() {} IReporterFactory::~IReporterFactory() {} IReporterRegistry::~IReporterRegistry() {} IStreamingReporter::~IStreamingReporter() {} AssertionStats::~AssertionStats() {} SectionStats::~SectionStats() {} TestCaseStats::~TestCaseStats() {} TestGroupStats::~TestGroupStats() {} TestRunStats::~TestRunStats() {} CumulativeReporterBase::SectionNode::~SectionNode() {} CumulativeReporterBase::~CumulativeReporterBase() {} StreamingReporterBase::~StreamingReporterBase() {} ConsoleReporter::~ConsoleReporter() {} CompactReporter::~CompactReporter() {} IRunner::~IRunner() {} IMutableContext::~IMutableContext() {} IConfig::~IConfig() {} XmlReporter::~XmlReporter() {} JunitReporter::~JunitReporter() {} TestRegistry::~TestRegistry() {} FreeFunctionTestCase::~FreeFunctionTestCase() {} IGeneratorInfo::~IGeneratorInfo() {} IGeneratorsForTest::~IGeneratorsForTest() {} WildcardPattern::~WildcardPattern() {} TestSpec::Pattern::~Pattern() {} TestSpec::NamePattern::~NamePattern() {} TestSpec::TagPattern::~TagPattern() {} TestSpec::ExcludedPattern::~ExcludedPattern() {} Matchers::Impl::StdString::Equals::~Equals() {} Matchers::Impl::StdString::Contains::~Contains() {} Matchers::Impl::StdString::StartsWith::~StartsWith() {} Matchers::Impl::StdString::EndsWith::~EndsWith() {} void Config::dummy() {} namespace TestCaseTracking { ITracker::~ITracker() {} TrackerBase::~TrackerBase() {} SectionTracker::~SectionTracker() {} IndexTracker::~IndexTracker() {} } } #ifdef __clang__ #pragma clang diagnostic pop #endif #endif #ifdef CATCH_CONFIG_MAIN // #included from: internal/catch_default_main.hpp #define TWOBLUECUBES_CATCH_DEFAULT_MAIN_HPP_INCLUDED #ifndef __OBJC__ // Standard C/C++ main entry point int main (int argc, char * argv[]) { return Catch::Session().run( argc, argv ); } #else // __OBJC__ // Objective-C entry point int main (int argc, char * const argv[]) { #if !CATCH_ARC_ENABLED NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init]; #endif Catch::registerTestMethods(); int result = Catch::Session().run( argc, (char* const*)argv ); #if !CATCH_ARC_ENABLED [pool drain]; #endif return result; } #endif // __OBJC__ #endif #ifdef CLARA_CONFIG_MAIN_NOT_DEFINED # undef CLARA_CONFIG_MAIN #endif ////// // If this config identifier is defined then all CATCH macros are prefixed with CATCH_ #ifdef CATCH_CONFIG_PREFIX_ALL #define CATCH_REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, ""CATCH_REQUIRE"" ) #define CATCH_REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, ""CATCH_REQUIRE_FALSE"" ) #define CATCH_REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, """", ""CATCH_REQUIRE_THROWS"" ) #define CATCH_REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, ""CATCH_REQUIRE_THROWS_AS"" ) #define CATCH_REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, ""CATCH_REQUIRE_THROWS_WITH"" ) #define CATCH_REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, ""CATCH_REQUIRE_NOTHROW"" ) #define CATCH_CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_CHECK"" ) #define CATCH_CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, ""CATCH_CHECK_FALSE"" ) #define CATCH_CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_CHECKED_IF"" ) #define CATCH_CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_CHECKED_ELSE"" ) #define CATCH_CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, ""CATCH_CHECK_NOFAIL"" ) #define CATCH_CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_CHECK_THROWS"" ) #define CATCH_CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_CHECK_THROWS_AS"" ) #define CATCH_CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, ""CATCH_CHECK_THROWS_WITH"" ) #define CATCH_CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_CHECK_NOTHROW"" ) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_CHECK_THAT"" ) #define CATCH_REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, ""CATCH_REQUIRE_THAT"" ) #define CATCH_INFO( msg ) INTERNAL_CATCH_INFO( msg, ""CATCH_INFO"" ) #define CATCH_WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_WARN"", msg ) #define CATCH_SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, ""CATCH_INFO"" ) #define CATCH_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg "" := "" << msg, ""CATCH_CAPTURE"" ) #define CATCH_SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg "" := "" << msg, ""CATCH_CAPTURE"" ) #ifdef CATCH_CONFIG_VARIADIC_MACROS #define CATCH_TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define CATCH_TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define CATCH_METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define CATCH_REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define CATCH_SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define CATCH_FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, ""CATCH_FAIL"", __VA_ARGS__ ) #define CATCH_SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_SUCCEED"", __VA_ARGS__ ) #else #define CATCH_TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define CATCH_TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define CATCH_METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define CATCH_REGISTER_TEST_CASE( function, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( function, name, description ) #define CATCH_SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) #define CATCH_FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, ""CATCH_FAIL"", msg ) #define CATCH_SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, ""CATCH_SUCCEED"", msg ) #endif #define CATCH_ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( """", """" ) #define CATCH_REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) #define CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) #define CATCH_GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) // ""BDD-style"" convenience wrappers #ifdef CATCH_CONFIG_VARIADIC_MACROS #define CATCH_SCENARIO( ... ) CATCH_TEST_CASE( ""Scenario: "" __VA_ARGS__ ) #define CATCH_SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, ""Scenario: "" __VA_ARGS__ ) #else #define CATCH_SCENARIO( name, tags ) CATCH_TEST_CASE( ""Scenario: "" name, tags ) #define CATCH_SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, ""Scenario: "" name, tags ) #endif #define CATCH_GIVEN( desc ) CATCH_SECTION( std::string( ""Given: "") + desc, """" ) #define CATCH_WHEN( desc ) CATCH_SECTION( std::string( "" When: "") + desc, """" ) #define CATCH_AND_WHEN( desc ) CATCH_SECTION( std::string( "" And: "") + desc, """" ) #define CATCH_THEN( desc ) CATCH_SECTION( std::string( "" Then: "") + desc, """" ) #define CATCH_AND_THEN( desc ) CATCH_SECTION( std::string( "" And: "") + desc, """" ) // If CATCH_CONFIG_PREFIX_ALL is not defined then the CATCH_ prefix is not required #else #define REQUIRE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal, ""REQUIRE"" ) #define REQUIRE_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::Normal | Catch::ResultDisposition::FalseTest, ""REQUIRE_FALSE"" ) #define REQUIRE_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, """", ""REQUIRE_THROWS"" ) #define REQUIRE_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::Normal, ""REQUIRE_THROWS_AS"" ) #define REQUIRE_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::Normal, matcher, ""REQUIRE_THROWS_WITH"" ) #define REQUIRE_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::Normal, ""REQUIRE_NOTHROW"" ) #define CHECK( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure, ""CHECK"" ) #define CHECK_FALSE( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::FalseTest, ""CHECK_FALSE"" ) #define CHECKED_IF( expr ) INTERNAL_CATCH_IF( expr, Catch::ResultDisposition::ContinueOnFailure, ""CHECKED_IF"" ) #define CHECKED_ELSE( expr ) INTERNAL_CATCH_ELSE( expr, Catch::ResultDisposition::ContinueOnFailure, ""CHECKED_ELSE"" ) #define CHECK_NOFAIL( expr ) INTERNAL_CATCH_TEST( expr, Catch::ResultDisposition::ContinueOnFailure | Catch::ResultDisposition::SuppressFail, ""CHECK_NOFAIL"" ) #define CHECK_THROWS( expr ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, """", ""CHECK_THROWS"" ) #define CHECK_THROWS_AS( expr, exceptionType ) INTERNAL_CATCH_THROWS_AS( expr, exceptionType, Catch::ResultDisposition::ContinueOnFailure, ""CHECK_THROWS_AS"" ) #define CHECK_THROWS_WITH( expr, matcher ) INTERNAL_CATCH_THROWS( expr, Catch::ResultDisposition::ContinueOnFailure, matcher, ""CHECK_THROWS_WITH"" ) #define CHECK_NOTHROW( expr ) INTERNAL_CATCH_NO_THROW( expr, Catch::ResultDisposition::ContinueOnFailure, ""CHECK_NOTHROW"" ) #define CHECK_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::ContinueOnFailure, ""CHECK_THAT"" ) #define REQUIRE_THAT( arg, matcher ) INTERNAL_CHECK_THAT( arg, matcher, Catch::ResultDisposition::Normal, ""REQUIRE_THAT"" ) #define INFO( msg ) INTERNAL_CATCH_INFO( msg, ""INFO"" ) #define WARN( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Warning, Catch::ResultDisposition::ContinueOnFailure, ""WARN"", msg ) #define SCOPED_INFO( msg ) INTERNAL_CATCH_INFO( msg, ""INFO"" ) #define CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg "" := "" << msg, ""CAPTURE"" ) #define SCOPED_CAPTURE( msg ) INTERNAL_CATCH_INFO( #msg "" := "" << msg, ""CAPTURE"" ) #ifdef CATCH_CONFIG_VARIADIC_MACROS #define TEST_CASE( ... ) INTERNAL_CATCH_TESTCASE( __VA_ARGS__ ) #define TEST_CASE_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, __VA_ARGS__ ) #define METHOD_AS_TEST_CASE( method, ... ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, __VA_ARGS__ ) #define REGISTER_TEST_CASE( Function, ... ) INTERNAL_CATCH_REGISTER_TESTCASE( Function, __VA_ARGS__ ) #define SECTION( ... ) INTERNAL_CATCH_SECTION( __VA_ARGS__ ) #define FAIL( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, ""FAIL"", __VA_ARGS__ ) #define SUCCEED( ... ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, ""SUCCEED"", __VA_ARGS__ ) #else #define TEST_CASE( name, description ) INTERNAL_CATCH_TESTCASE( name, description ) #define TEST_CASE_METHOD( className, name, description ) INTERNAL_CATCH_TEST_CASE_METHOD( className, name, description ) #define METHOD_AS_TEST_CASE( method, name, description ) INTERNAL_CATCH_METHOD_AS_TEST_CASE( method, name, description ) #define REGISTER_TEST_CASE( method, name, description ) INTERNAL_CATCH_REGISTER_TESTCASE( method, name, description ) #define SECTION( name, description ) INTERNAL_CATCH_SECTION( name, description ) #define FAIL( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::ExplicitFailure, Catch::ResultDisposition::Normal, ""FAIL"", msg ) #define SUCCEED( msg ) INTERNAL_CATCH_MSG( Catch::ResultWas::Ok, Catch::ResultDisposition::ContinueOnFailure, ""SUCCEED"", msg ) #endif #define ANON_TEST_CASE() INTERNAL_CATCH_TESTCASE( """", """" ) #define REGISTER_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_REPORTER( name, reporterType ) #define REGISTER_LEGACY_REPORTER( name, reporterType ) INTERNAL_CATCH_REGISTER_LEGACY_REPORTER( name, reporterType ) #define GENERATE( expr) INTERNAL_CATCH_GENERATE( expr ) #endif #define CATCH_TRANSLATE_EXCEPTION( signature ) INTERNAL_CATCH_TRANSLATE_EXCEPTION( signature ) // ""BDD-style"" convenience wrappers #ifdef CATCH_CONFIG_VARIADIC_MACROS #define SCENARIO( ... ) TEST_CASE( ""Scenario: "" __VA_ARGS__ ) #define SCENARIO_METHOD( className, ... ) INTERNAL_CATCH_TEST_CASE_METHOD( className, ""Scenario: "" __VA_ARGS__ ) #else #define SCENARIO( name, tags ) TEST_CASE( ""Scenario: "" name, tags ) #define SCENARIO_METHOD( className, name, tags ) INTERNAL_CATCH_TEST_CASE_METHOD( className, ""Scenario: "" name, tags ) #endif #define GIVEN( desc ) SECTION( std::string("" Given: "") + desc, """" ) #define WHEN( desc ) SECTION( std::string("" When: "") + desc, """" ) #define AND_WHEN( desc ) SECTION( std::string(""And when: "") + desc, """" ) #define THEN( desc ) SECTION( std::string("" Then: "") + desc, """" ) #define AND_THEN( desc ) SECTION( std::string("" And: "") + desc, """" ) using Catch::Detail::Approx; #endif // TWOBLUECUBES_SINGLE_INCLUDE_CATCH_HPP_INCLUDED ","Unknown" "CRISPR","ctSkennerton/crass","src/test/test_libcrispr.cpp",".cpp","18045","374","#include #include ""catch.hpp"" #include ""libcrispr.h"" #include ""ReadHolder.h"" // 0 1 // 0 1 2 3 4 5 6 7 8 9 0 1 2 // 012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345 // CACCATGGAAGACCTTCCTAACACCATGGTAGACATTCCTTACACCATGGTAGACCTTCCTAACACCATGGTAGACCTTCCTAACACCATGGTAGACCTTCCTAACACCATGGTAGACCTTTCTAA // rrrrrrrr rrrrrrrr rrrrrrrr TEST_CASE(""searching for additional repeated kmer in a 126bp read"", ""[libcrispr]"") { ReadHolder read(""CACCATGGAAGACCTTCCTAACACCATGGTAGACATTCCTTACACCATGGTAGACCTTCCTAACACCATGGTAGACCTTCCTAACACCATGGTAGACCTTCCTAACACCATGGTAGACCTTTCTAA"",""HWI-D00456:77:C70WLANXX:1:1101:10963:2182""); SECTION(""where there should be one additional match with a minimum spacer length of 26""){ read.startStopsAdd(0, 7); read.startStopsAdd(63,70); std::string pattern = ""CACCATGG""; scanRight(read, pattern, 26, 24); StartStopList reppos = read.getStartStopList(); REQUIRE(reppos.size() == 6); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 7); REQUIRE(reppos[2] == 63); REQUIRE(reppos[3] == 70); REQUIRE(reppos[4] == 105); REQUIRE(reppos[5] == 112); } } TEST_CASE(""check extending repeat with 126bp read"", ""[libcrispr]"") { ReadHolder read(""CACCATGGAAGACCTTCCTAACACCATGGTAGACATTCCTTACACCATGGTAGACCTTCCTAACACCATGGTAGACCTTCCTAACACCATGGTAGACCTTCCTAACACCATGGTAGACCTTTCTAA"",""HWI-D00456:77:C70WLANXX:1:1101:10963:2182""); SECTION(""The search window length is 8 and the min spacer length is 26"") { read.startStopsAdd(0, 7); read.startStopsAdd(63,70); read.startStopsAdd(105,112); int repeat_length = extendPreRepeat(read, 8, 26); REQUIRE(repeat_length == 23); StartStopList reppos = read.getStartStopList(); REQUIRE(reppos.size() == 6); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 21); REQUIRE(reppos[2] == 62); REQUIRE(reppos[3] == 84); REQUIRE(reppos[4] == 104); REQUIRE(reppos[5] == 125); } } TEST_CASE(""searching for additional repeated kmers in 100bp read"", ""[libcrispr]""){ // read // 0 1 // 0 1 2 3 4 5 6 7 8 9 0 // 01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 // CCCCGCAGGCGCGGGGATGAACCGAGCGAGACATCACCGGCGAGTCGGAGCGCGTTGCGTTCCCCGCAGGCGCGGGGATGAACCGAAGATAAACGCCGGCG // rrrrrrrrRRRRRRRRRRRRRRRRR rrrrrrrrRRRRRRRRRRRRRRRRR // ReadHolder read(""CCCCGCAGGCGCGGGGATGAACCGAGCGAGACATCACCGGCGAGTCGGAGCGCGTTGCGTTCCCCGCAGGCGCGGGGATGAACCGAAGATAAACGCCGGCG"", ""HWI-EAS165_0052:2:58:8891:11288#CGATGT/1_C233_C23""); SECTION(""where there should be no additional matches with a minimum spacer length of 21""){ read.startStopsAdd(0, 7); read.startStopsAdd(61,68); std::string pattern = ""CCCCGCAG""; scanRight(read, pattern, 21, 24); StartStopList reppos = read.getStartStopList(); REQUIRE(reppos.size() == 4); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 7); REQUIRE(reppos[2] == 61); REQUIRE(reppos[3] == 68); } SECTION(""where there should be no additional matches with a minimum spacer length of 10""){ read.startStopsAdd(0, 7); read.startStopsAdd(61,68); std::string pattern = ""CCCCGCAG""; scanRight(read, pattern, 10, 24); StartStopList reppos = read.getStartStopList(); REQUIRE(reppos.size() == 4); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 7); REQUIRE(reppos[2] == 61); REQUIRE(reppos[3] == 68); } // read2 // 0 1 // 0 1 2 3 4 5 6 7 8 9 0 // 01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 // TTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTT // rrrrrrrrRRRRRRRRR RrrrrrrrrRRRRRRRRR RrrrrrrrrRRRRRRRRR Spacer Length: 21 // rrrrrrrrRRRRRRR RrrrrrrrrRRRRRRR RrrrrrrrrRRRRRR Spacer Length: 24 ReadHolder read2(""TTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTT"", ""SRR438795.13216""); SECTION(""where there should be one additional match with a minimum spacer length of 21""){ read2.startStopsAdd(0, 7); read2.startStopsAdd(45,52); std::string pattern = ""TTGTTGTT""; scanRight(read2, pattern, 21, 24); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos.size() == 6); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 7); REQUIRE(reppos[2] == 45); REQUIRE(reppos[3] == 52); REQUIRE(reppos[4] == 75); REQUIRE(reppos[5] == 82); } SECTION(""where there should be one additional match with a minimum spacer length of 24""){ //0,7,48,55,81,88, read2.startStopsAdd(0, 7); read2.startStopsAdd(48,55); std::string pattern = ""TTGTTGTT""; scanRight(read2, pattern, 24, 24); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos.size() == 6); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 7); REQUIRE(reppos[2] == 48); REQUIRE(reppos[3] == 55); REQUIRE(reppos[4] == 81); REQUIRE(reppos[5] == 88); } SECTION(""where there should be three additional matches with a minimum spacer length of 10""){ //0,7, //33,40, //51,58, //69,76, //87,94, read2.startStopsAdd(0, 7); read2.startStopsAdd(33,40); std::string pattern = ""TTGTTGTT""; scanRight(read2, pattern, 10, 24); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos.size() == 10); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 7); REQUIRE(reppos[2] == 33); REQUIRE(reppos[3] == 40); REQUIRE(reppos[4] == 51); REQUIRE(reppos[5] == 58); REQUIRE(reppos[6] == 69); REQUIRE(reppos[7] == 76); REQUIRE(reppos[8] == 87); REQUIRE(reppos[9] == 94); } } TEST_CASE(""check extending repeat with 100bp read"", ""[libcrispr]"") { ReadHolder read(""CCCCGCAGGCGCGGGGATGAACCGAGCGAGACATCACCGGCGAGTCGGAGCGCGTTGCGTTCCCCGCAGGCGCGGGGATGAACCGAAGATAAACGCCGGCG"", ""HWI-EAS165_0052:2:58:8891:11288#CGATGT/1_C233_C23""); SECTION(""The search window length is 8 and the min spacer length is 21"") { read.startStopsAdd(0, 7); read.startStopsAdd(61,68); int repeat_length = extendPreRepeat(read, 8, 21); REQUIRE(repeat_length == 25); StartStopList reppos = read.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 24); REQUIRE(reppos[2] == 61); REQUIRE(reppos[3] == 85); } SECTION(""The search window length is 6 and the min spacer length is 21"") { read.startStopsAdd(0, 5); read.startStopsAdd(61,66); int repeat_length = extendPreRepeat(read, 6, 21); REQUIRE(repeat_length == 25); StartStopList reppos = read.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 24); REQUIRE(reppos[2] == 61); REQUIRE(reppos[3] == 85); } SECTION(""The search window length is 11 and the min spacer length is 21"") { read.startStopsAdd(0, 10); read.startStopsAdd(61,71); int repeat_length = extendPreRepeat(read, 11, 21); REQUIRE(repeat_length == 25); StartStopList reppos = read.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 24); REQUIRE(reppos[2] == 61); REQUIRE(reppos[3] == 85); } ReadHolder read2(""TTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTTGTT"", ""SRR438795.13216""); SECTION(""The search window length is 8 and the min spacer length is 21"") { read2.startStopsAdd(0, 7); read2.startStopsAdd(45,52); read2.startStopsAdd(75,82); int repeat_length = extendPreRepeat(read2, 8, 21); REQUIRE(repeat_length == 18); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 16); REQUIRE(reppos[2] == 44); REQUIRE(reppos[3] == 61); REQUIRE(reppos[4] == 74); REQUIRE(reppos[5] == 91); } SECTION(""The search window length is 8 and the min spacer length is 24"") { //0,7,48,55,81,88, read2.startStopsAdd(0, 7); read2.startStopsAdd(48,55); read2.startStopsAdd(81,88); int repeat_length = extendPreRepeat(read2, 8, 24); REQUIRE(repeat_length == 18); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 16); REQUIRE(reppos[2] == 47); REQUIRE(reppos[3] == 64); REQUIRE(reppos[4] == 80); REQUIRE(reppos[5] == 97); } } // read2 // 0 1 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 // 01234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 // CTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACATTTTTTATCCAGATTTTTCCCCAAATTTGCAATAATTGCTACTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACTTCTGTAGAGTTATTGTATAAGAACCCCACGTAGAAACGAGCTTCCACTAACCATTTCCCCGTAAGGGGACGGAAAC // rrrrrrrrRRRRRRRRRRRRRRRRRRRRRRRRRRRR rrrrrrrrRRRRRRRRRRRRRRRRRRRRRRRRRRRR rrrrrrrrRRRRRRRRRRRRRRRRRRRRRRRRRRRR TEST_CASE(""searching for additional repeated kmers in 190bp read"", ""[libcrispr]""){ ReadHolder read2(""CTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACATTTTTTATCCAGATTTTTCCCCAAATTTGCAATAATTGCTACTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACTTCTGTAGAGTTATTGTATAAGAACCCCACGTAGAAACGAGCTTCCACTAACCATTTCCCCGTAAGGGGACGGAAAC"", ""NC_019753_1""); SECTION(""where there should be one additional match with a minimum spacer length of 21""){ read2.startStopsAdd(0, 7); read2.startStopsAdd(78,85); std::string pattern = ""CTTCCACT""; scanRight(read2, pattern, 21, 24); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 7); REQUIRE(reppos[2] == 78); REQUIRE(reppos[3] == 85); REQUIRE(reppos[4] == 155); REQUIRE(reppos[5] == 162); } SECTION(""where there should be one additional match with a minimum spacer length of 10""){ read2.startStopsAdd(0, 7); read2.startStopsAdd(78,85); std::string pattern = ""CTTCCACT""; scanRight(read2, pattern, 10, 24); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 7); REQUIRE(reppos[2] == 78); REQUIRE(reppos[3] == 85); REQUIRE(reppos[4] == 155); REQUIRE(reppos[5] == 162); } } TEST_CASE(""check extending repeat with 190bp read"", ""[libcrispr]"") { ReadHolder read2(""CTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACATTTTTTATCCAGATTTTTCCCCAAATTTGCAATAATTGCTACTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACTTCTGTAGAGTTATTGTATAAGAACCCCACGTAGAAACGAGCTTCCACTAACCATTTCCCCGTAAGGGGACGGAAAC"", ""NC_019753_1""); SECTION(""The search window length is 8 and the min spacer length is 21"") { read2.startStopsAdd(0,7); read2.startStopsAdd(78,85); read2.startStopsAdd(155,162); int repeat_length = extendPreRepeat(read2, 8, 21); REQUIRE(repeat_length == 36); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 35); REQUIRE(reppos[2] == 78); REQUIRE(reppos[3] == 113); REQUIRE(reppos[4] == 155); REQUIRE(reppos[5] == 190); } SECTION(""The search window length is 6 and the min spacer length is 21"") { read2.startStopsAdd(0,5); read2.startStopsAdd(78,83); read2.startStopsAdd(155,160); int repeat_length = extendPreRepeat(read2, 6, 21); REQUIRE(repeat_length == 36); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 35); REQUIRE(reppos[2] == 78); REQUIRE(reppos[3] == 113); REQUIRE(reppos[4] == 155); REQUIRE(reppos[5] == 190); } SECTION(""The search window length is 11 and the min spacer length is 21"") { read2.startStopsAdd(0,10); read2.startStopsAdd(78,88); read2.startStopsAdd(155,165); int repeat_length = extendPreRepeat(read2, 11, 21); REQUIRE(repeat_length == 36); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 35); REQUIRE(reppos[2] == 78); REQUIRE(reppos[3] == 113); REQUIRE(reppos[4] == 155); REQUIRE(reppos[5] == 190); } } // read3 // 0 1 2 3 // 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 // 0123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 // CTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACATTTTTTATCCAGATTTTTCCCCAAATTTGCAATAATTGCTACTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACTTCTGTAGAGTTATTGTATAAGAACCCCACGTAGAAACGAGCTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACCAGAAATTACGACAGACGCGCAAGCAGGATCAGCCACTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACAGCCAGATAATGATGATAATGCTAGAGGCTGTCCGTT // RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR RRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRRR TEST_CASE(""check extending repeat with 300bp read"", ""[libcrispr]"") { ReadHolder read2(""CTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACATTTTTTATCCAGATTTTTCCCCAAATTTGCAATAATTGCTACTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACTTCTGTAGAGTTATTGTATAAGAACCCCACGTAGAAACGAGCTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACCAGAAATTACGACAGACGCGCAAGCAGGATCAGCCACTTCCACTAACCATTTCCCCGTAAGGGGACGGAAACAGCCAGATAATGATGATAATGCTAGAGGCTGTCCGTT"", ""NC_019753_1""); SECTION(""The search window length is 8 and the min spacer length is 21"") { read2.startStopsAdd(0,7); read2.startStopsAdd(78,85); read2.startStopsAdd(155,162); read2.startStopsAdd(227,234); int repeat_length = extendPreRepeat(read2, 8, 21); REQUIRE(repeat_length == 36); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 35); REQUIRE(reppos[2] == 78); REQUIRE(reppos[3] == 113); REQUIRE(reppos[4] == 155); REQUIRE(reppos[5] == 190); REQUIRE(reppos[6] == 227); REQUIRE(reppos[7] == 262); } SECTION(""The search window length is 6 and the min spacer length is 21"") { read2.startStopsAdd(0,5); read2.startStopsAdd(78,83); read2.startStopsAdd(155,160); read2.startStopsAdd(227,232); int repeat_length = extendPreRepeat(read2, 6, 21); REQUIRE(repeat_length == 36); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 35); REQUIRE(reppos[2] == 78); REQUIRE(reppos[3] == 113); REQUIRE(reppos[4] == 155); REQUIRE(reppos[5] == 190); REQUIRE(reppos[6] == 227); REQUIRE(reppos[7] == 262); } SECTION(""The search window length is 11 and the min spacer length is 21"") { read2.startStopsAdd(0,10); read2.startStopsAdd(78,88); read2.startStopsAdd(155,165); read2.startStopsAdd(227,237); int repeat_length = extendPreRepeat(read2, 11, 21); REQUIRE(repeat_length == 36); StartStopList reppos = read2.getStartStopList(); REQUIRE(reppos[0] == 0); REQUIRE(reppos[1] == 35); REQUIRE(reppos[2] == 78); REQUIRE(reppos[3] == 113); REQUIRE(reppos[4] == 155); REQUIRE(reppos[5] == 190); REQUIRE(reppos[6] == 227); REQUIRE(reppos[7] == 262); } } ","C++" "CRISPR","ctSkennerton/crass","scripts/batch_crass.sh",".sh","882","44","#!/bin/bash EXTENSION='fa' KMERSIZE=9 KMERCLUSTER=10 NUMSPACERS=3 EXTRAOPTIONS= LOGLEVEL=4 while getopts "":E:K:k:l:f:X:"" opt; do case $opt in E) EXTENSION=$OPTARG ;; K) KMERSIZE=$OPTARG ;; k) KMERCLUSTER=$OPTARG ;; l) LOGLEVEL=$OPTARG ;; X) EXTRAOPTIONS=$OPTARG ;; f) NUMSPACERS=$OPTARG ;; \?) echo ""Invalid option: -$OPTARG"" >&2 exit 1 ;; :) echo ""Option -$OPTARG requires an argument."" >&2 exit 1 ;; esac done for f in *.${EXTENSION}; do echo ""processing file $f"" crass -o crass_out_${f%.${EXTENSION}} -k $KMERCLUSTER -K $KMERSIZE -l $LOGLEVEL -f $NUMSPACERS $EXTRAOPTIONS $f done ","Shell" "CRISPR","sellerslab/gemini","NEWS.md",".md","552","12","# gemini 0.3.0 * 6-01-19: Introducing GEMINI, a variational Bayesian approach to analyze pairwise CRISPR screens. * Note: This is a pre-release version of GEMINI. * Added a `NEWS.md` file to track changes to the package. * Minor modifications were made to prepare for repository submission. * 6-13-19: Incremented version number from 0.2.0 to 0.99.0 for pre-release. * 6-24-19: Bioconductor revision in progress. Version 0.99.9 * Note: This is a pre-release version of GEMINI. * Modified documentation for all functions and added a workable vignette","Markdown" "CRISPR","sellerslab/gemini","R/gemini_plot_mae.R",".R","800","29","#' MAE plot #' @name gemini_plot_mae #' #' @description Plots the average MAE of gemini model at each iteration step. #' #' @param Model a gemini.model object #' #' @return a ggplot2 object #' @import ggplot2 #' @importFrom scales pretty_breaks #' @export #' #' @examples #' data(""Model"", package = ""gemini"") #' gemini_plot_mae(Model) #' gemini_plot_mae <- function(Model){ stopifnot(""gemini.model"" %in% class(Model)) stopifnot(""mae"" %in% names(Model)) g = ggplot(data = data.frame(iter = seq_len(length(Model$mae))-1, mae = Model$mae), aes_string(x = 'iter', y = 'mae')) + geom_point() + geom_line() + labs(x = ""Iterations"", y = ""Mean Absolute Error"") + scale_x_continuous(breaks = pretty_breaks(n = length(Model$mae))) return(g) } ","R" "CRISPR","sellerslab/gemini","R/bigpapi-data.R",".R","2169","57","#' Big Papi counts matrix #' @name counts #' @description Counts matrix from the Big Papi SynLet dataset. #' The Big Papi dataset was published in Najm et al. 2018 (doi: 10.1038/nbt.4048). #' The counts were acquired from Supplementary Table 3. #' @docType data #' @seealso https://www.nature.com/articles/nbt.4048 #' @keywords data ""counts"" #' Big Papi guide annotations #' #' @name guide.annotation #' #' @description Guide and gene annotations for the Big Papi SynLet dataset. #' The Big Papi dataset was published in Najm et al. 2018 (doi: 10.1038/nbt.4048). #' The guide and gene annotations were acquired from Supplementary Table 2. #' @docType data #' @seealso https://www.nature.com/articles/nbt.4048 #' @keywords data ""guide.annotation"" #' Big Papi sample and replicate annotations #' #' @name sample.replicate.annotation #' @description Sample and replicate annotations for the Big Papi SynLet dataset. #' The Big Papi dataset was published in Najm et al. 2018 (doi: 10.1038/nbt.4048). #' The sample and replicate annotations were acquired from Supplementary Table 3 #' @docType data #' @seealso https://www.nature.com/articles/nbt.4048 #' @keywords data ""sample.replicate.annotation"" #' Input object from Big Papi #' #' @name Input #' @description A gemini.input object created from the Big Papi SynLet dataset. #' The Big Papi dataset was published in Najm et al. 2018 (doi: 10.1038/nbt.4048). #' The Input object here is created from the data in \link{counts}, #' \link{guide.annotation}, and \link{sample.replicate.annotation} #' using the \code{\link{gemini_create_input}} function. #' @docType data #' @seealso https://www.nature.com/articles/nbt.4048 #' @keywords data ""Input"" #' Model object from Big Papi #' #' @name Model #' @description A gemini.model object created from the Big Papi SynLet dataset after \code{gemini_inference} was run. #' The Big Papi dataset was published in Najm et al. 2018 (doi: 10.1038/nbt.4048). #' The Model object here is created from the data in \link{Input} using the \code{\link{gemini_initialize}} function. #' @docType data #' @seealso https://www.nature.com/articles/nbt.4048 #' @keywords data ""Model"" ","R" "CRISPR","sellerslab/gemini","R/gemini_inference.R",".R","5263","130","#' gemini_inference #' #' @description #' Estimate the posterior using a variational inference technique. Inference is performed #' through an iterative process until convergence. #' #' @param Model an object of class gemini.model #' @param mean_x a numeric indicating prior mean of x (default=1). #' @param sd_x a numeric indicating prior sd of x (default=1). #' @param mean_xx a numeric indicating prior mean of xx (default=1). #' @param sd_xx a numeric indicating prior sd of xx (default=1) #' @param mean_y a numeric indicating prior mean of y (default=0) #' @param sd_y a numeric indicating prior sd of y (default=10). #' @param mean_s a numeric indicating prior mean of s(default=0) #' @param sd_s a numeric indicating prior sd of s (default=10) #' @param n_iterations a numeric indicating the maximum number of iterations (default=20). #' @param threshold a numeric indicating the threshold of change in MAE at which to stop the iterative process (default=0.001). #' @param cores a numeric indicating the number of cores to use. See details in gemini_parallel. (default=1) #' @param force_results a logical indicating if the CAVI algorithm should be halted if non-convergence is detected. (default=FALSE) #' @param verbose default FALSE #' @param save_iterations for especially large libraries that require long computations, #' saves the latest iteration of each update. default FALSE #' #' @details #' GEMINI uses the following parameters, which are described in Zamanighomi et al. and translated here for clarity: #' \itemize{ #' \item \strong{y:} individual gene effect #' \item \strong{s:} combination effect #' \item \strong{x:} screen variation corresponding to individual guides #' \item \strong{xx:} screen variation corresponding to paired guides #' } #' #' Default parameters may need to be changed if convergence is not achieved. See README for #' more details. #' #' @return a gemini.model object with estimated posteriors #' #' @export #' #' @examples #' data(""Model"", package = ""gemini"") #' Model %<>% gemini_inference(verbose = FALSE, n_iterations = 1) # iterations set to 1 for testing #' gemini_inference <- function(Model, n_iterations = 20, # update_x_pb params: mean_x = 1, sd_x = 1, mean_xx = 1, sd_xx = 1, # update_y_pb params: mean_y = 0, sd_y = 10, # update_s_pb params: mean_s = 0, sd_s = 10, # Run-time params: threshold = 1e-3, cores = 1, force_results = FALSE, verbose = FALSE, save_iterations = FALSE) { # perform n_iterations for (i in seq_len(n_iterations)) { if (verbose) cat(paste(""iteration:"", i, ""\n"")) Model %<>% update_x_pb( mean_x = mean_x, sd_x = sd_x, mean_xx = mean_xx, sd_xx = sd_xx, cores = cores, verbose = verbose ) %>% update_y_pb(mean_y = mean_y, sd_y = sd_y, verbose = verbose) %>% update_s_pb( mean_s = mean_s, sd_s = sd_s, cores = cores, verbose = verbose ) %>% update_tau_pb(cores = cores, verbose = verbose) %>% update_mae(verbose = verbose) # save the Model object after every iteration - useful for large screens with heavy computation if (!is.null(save_iterations)) { if (is.logical(save_iterations)) { save_flag = save_iterations save_file = ""Model"" } else if (is.character(save_iterations)) { save_flag = TRUE save_file = save_iterations } else{ if (verbose) warning(""Could not parse save_iterations argument."") save_flag = FALSE } if (isTRUE(save_flag)) { if (file.exists(paste0(save_file, ""_"", i - 1, "".rds""))) { file.remove(paste0(save_file, ""_"", i - 1, "".rds"")) } saveRDS(Model, file = paste0(save_file, ""_"", i, "".rds"")) } } # break loop if mae does not change more than the threshold if (verbose) { message(""MAE: "", Model$mae[i + 1]) } if (abs(Model$mae[i + 1] - Model$mae[i]) < threshold) { break } if (!force_results) { if (Model$mae[i + 1] > Model$mae[i]) { stop(""Model not converging! Please adjust parameters and try again."") } } } # output return(Model) } ","R" "CRISPR","sellerslab/gemini","R/gemini_score.R",".R","10547","263","#' Scoring Combination Effect #' #' @description Score genetic interactions from a gemini.model and produce a gemini.score object, and generate p-values and FDRs if negative control #' pairs (\code{nc_pairs}) are available. #' #' @param Model an object of class gemini.model #' @param pc_gene a character vector of any length naming genes to use as positive controls #' @param pc_weight a weighting applied to the positive control #' (\code{pc_gene}) to filter genes whose individual phenotype is #' more lethal than \eqn{pc_weight*y(pc_gene)}. #' @param pc_threshold a numeric value to indicate the LFC corresponding to a positive control, if no pc_gene is specified. #' @param nc_pairs a set of non-interacting gene pairs to define #' statistical significance. #' #' @return An object of class gemini.score containing score values for #' strong interactions and sensitive lethality and recovery, and if \code{nc_pairs} is specified, statistical significance for each scoring type. #' #' @importFrom magrittr set_rownames #' @importFrom magrittr set_names #' @importFrom magrittr subtract #' @importFrom magrittr add #' @importFrom mixtools normalmixEM #' @importFrom dplyr bind_rows #' @importFrom stats p.adjust #' @importFrom stats pnorm #' @importFrom stats quantile #' @importFrom utils capture.output #' #' @export #' #' @examples #' data(""Model"", package = ""gemini"") #' Score <- gemini_score(Model, pc_gene = ""EEF2"") gemini_score <- function(Model, pc_gene = NA, pc_threshold = NULL, pc_weight = 0.5, nc_pairs = NA) { # Check input stopifnot(""gemini.model"" %in% class(Model)) Score <- list() class(Score) <- c(class(Score), ""gemini.score"") ###### Paired genes mapped to their corresponding Single genes Pgenes2Sgenes <- lapply(rownames(Model$s), function(x) { s <- strsplit(x, split = Model$pattern_join, fixed = TRUE)[[1]] data.frame( gene1 = s[1], gene2 = s[2], stringsAsFactors = FALSE ) }) %>% dplyr::bind_rows() %>% magrittr::set_rownames(rownames(Model$s)) ###### Score combination effects and calculate pvalue and fdr using nc_pairs Score$strong <- matrix( NA, nrow = nrow(Model$s), ncol = ncol(Model$s), dimnames = list(rownames(Model$s), colnames(Model$s)) ) Score$sensitive_lethality <- matrix( NA, nrow = nrow(Model$s), ncol = ncol(Model$s), dimnames = list(rownames(Model$s), colnames(Model$s)) ) Score$sensitive_recovery <- matrix( NA, nrow = nrow(Model$s), ncol = ncol(Model$s), dimnames = list(rownames(Model$s), colnames(Model$s)) ) Score$pvalue_strong <- matrix( NA, nrow = nrow(Model$s), ncol = ncol(Model$s), dimnames = list(rownames(Model$s), colnames(Model$s)) ) Score$pvalue_sensitive_lethality <- matrix( NA, nrow = nrow(Model$s), ncol = ncol(Model$s), dimnames = list(rownames(Model$s), colnames(Model$s)) ) Score$pvalue_sensitive_recovery <- matrix( NA, nrow = nrow(Model$s), ncol = ncol(Model$s), dimnames = list(rownames(Model$s), colnames(Model$s)) ) Score$fdr_strong <- matrix( NA, nrow = nrow(Model$s), ncol = ncol(Model$s), dimnames = list(rownames(Model$s), colnames(Model$s)) ) Score$fdr_sensitive_lethality <- matrix( NA, nrow = nrow(Model$s), ncol = ncol(Model$s), dimnames = list(rownames(Model$s), colnames(Model$s)) ) Score$fdr_sensitive_recovery <- matrix( NA, nrow = nrow(Model$s), ncol = ncol(Model$s), dimnames = list(rownames(Model$s), colnames(Model$s)) ) for (i in colnames(Model$s)) { # mean sgh_mean <- Model$s[, i] yg_mean <- Model$y[Pgenes2Sgenes[, 1], i] yh_mean <- Model$y[Pgenes2Sgenes[, 2], i] # sd sgh_sd <- (Model$s2[, i] - Model$s[, i] ^ 2) ^ 0.5 yg_sd <- (Model$y2[Pgenes2Sgenes[, 1], i] - Model$y[Pgenes2Sgenes[, 1], i] ^ 2) ^ 0.5 yh_sd <- (Model$y2[Pgenes2Sgenes[, 2], i] - Model$y[Pgenes2Sgenes[, 2], i] ^ 2) ^ 0.5 # strong: Score synergies accroding to Score = abs(sgh_mean) - max(abs(yg_mean),abs(yh_mean) Score$strong[, i] <- abs(sgh_mean) - apply(cbind(abs(yg_mean), abs(yh_mean)), 1 , function(x) max(x, na.rm = TRUE)) %>% unlist() %>% magrittr::set_names(rownames(Model$s)) # lethality: Score synergies accroding to Score = min(yg_mean,yh_mean) - yg_mean - yh_mean - sgh_mean Score$sensitive_lethality[, i] <- apply(cbind(yg_mean, yh_mean), 1 , function(x) min(x, na.rm = TRUE)) %>% unlist() %>% magrittr::set_names(rownames(Model$s)) %>% magrittr::subtract(sgh_mean) %>% magrittr::subtract(yg_mean) %>% magrittr::subtract(yh_mean) # recovery: Score synergies accroding to Score = yg_mean + yh_mean + sgh_mean - min(yg_mean,yh_mean) Score$sensitive_recovery[, i] <- sgh_mean %>% magrittr::add(yg_mean) %>% magrittr::add(yh_mean) %>% magrittr::subtract(apply(cbind(yg_mean, yh_mean), 1, function(x) min(x, na.rm = TRUE)) %>% unlist() %>% magrittr::set_names(rownames(Model$s))) # keep pairs if yg & yh > 0.5*ypc_gene if (sum(!is.na(pc_gene)) > 0 & is.null(pc_threshold)) { pc_gene <- pc_gene[!is.na(pc_gene)] threshold <- median(Model$y[pc_gene, i], na.rm = TRUE) * pc_weight } else if (sum(!is.na(pc_gene)) == 0 & !is.null(pc_threshold)) { threshold <- pc_threshold } else if (sum(!is.na(pc_gene)) > 0 & !is.null(pc_threshold)) { warning(""Both pc_gene and pc_threshold specified - defaulting to pc_gene."") pc_gene <- pc_gene[!is.na(pc_gene)] threshold <- median(Model$y[pc_gene, i], na.rm = TRUE) * pc_weight } else { # If no threshold specified, use bottom 1-percentile of data threshold = as.numeric(quantile(Model$y[, i], probs = 0.01)) * pc_weight } remove_lethal = yg_mean < threshold | yh_mean < threshold remove_recovery = yg_mean > threshold & yh_mean > threshold Score$sensitive_lethality[remove_lethal , i] <- NA Score$sensitive_recovery[remove_recovery , i] <- NA } # end for ###### calculate pvalue and fdr using difference_constant or difference_quantile if (any(!is.na(nc_pairs))) { if (!requireNamespace(""mixtools"")) { stop(""Please install the mixtools package: install.packages('mixtools')."") } # construct negetaive model using mixture of two normal distributions # strong nc_pairs <- nc_pairs[!is.na(nc_pairs)] nc_values <- as.vector(Score$strong[nc_pairs, ]) nc_values <- nc_values[!is.na(nc_values)] #cat(""running EM algorithm on strong scoring \n"") invisible(capture.output({ nc_model_strong <- mixtools::normalmixEM(nc_values) })) # lethality nc_values <- as.vector(Score$sensitive_lethality[nc_pairs, ]) nc_values <- nc_values[!is.na(nc_values)] #cat(""running EM algorithm on lethality scoring \n"") invisible(capture.output({ nc_model_lethality <- mixtools::normalmixEM(nc_values) })) # recovery nc_values <- as.vector(Score$sensitive_recovery[nc_pairs, ]) nc_values <- nc_values[!is.na(nc_values)] #cat(""running EM algorithm on recovery ranking \n"") invisible(capture.output({ nc_model_recovery <- mixtools::normalmixEM(nc_values) })) # calculate p-values # strong Score$pvalue_strong <- nc_model_strong$lambda[1] * pnorm( Score$strong, mean = nc_model_strong$mu[1], sd = nc_model_strong$sigma[1], lower.tail = FALSE ) + nc_model_strong$lambda[2] * pnorm( Score$strong, mean = nc_model_strong$mu[2], sd = nc_model_strong$sigma[2], lower.tail = FALSE ) # null hypothesis: nc_model_strong > Score$strong # lethality Score$pvalue_sensitive_lethality <- nc_model_lethality$lambda[1] * pnorm( Score$sensitive_lethality, mean = nc_model_lethality$mu[1], sd = nc_model_lethality$sigma[1], lower.tail = FALSE ) + nc_model_lethality$lambda[2] * pnorm( Score$sensitive_lethality, mean = nc_model_lethality$mu[2], sd = nc_model_lethality$sigma[2], lower.tail = FALSE ) # null hypothesis: nc_model_lethality > Score$sensitive_lethality # recovery Score$pvalue_sensitive_recovery <- nc_model_recovery$lambda[1] * pnorm( Score$sensitive_recovery, mean = nc_model_recovery$mu[1], sd = nc_model_recovery$sigma[1], lower.tail = FALSE ) + nc_model_recovery$lambda[2] * pnorm( Score$sensitive_recovery, mean = nc_model_recovery$mu[2], sd = nc_model_recovery$sigma[2], lower.tail = FALSE ) # null hypothesis: nc_model_recovery > Score$sensitive_recovery Score$nc_model_strong <- nc_model_strong Score$nc_model_lethality <- nc_model_lethality Score$nc_model_recovery <- nc_model_recovery } # calculate the adjusted p-values if (sum(!is.na(nc_pairs)) != 0) { # strong Score$fdr_strong <- apply(Score$pvalue_strong, 2, function(x) p.adjust(x, method = ""fdr"")) # lethality Score$fdr_sensitive_lethality <- apply(Score$pvalue_sensitive_lethality, 2, function(x) p.adjust(x, method = ""fdr"")) # recovery Score$fdr_sensitive_recovery <- apply(Score$pvalue_sensitive_recovery, 2, function(x) p.adjust(x, method = ""fdr"")) } # output Score <- Score[!unlist(lapply(Score, function(x) all(is.na(x))))] return(Score) } ","R" "CRISPR","sellerslab/gemini","R/gemini_initialize.R",".R","5662","127","#' gemini_initialize #' @description Creates a gemini.model object given Input data and initialization parameters. #' #' @param Input an object of class gemini.input #' @param guide.pair.annot the name of an object within \code{Input} containing guide to gene annotations (Default = ""guide.pair.annot"") #' @param replicate.map the name of an object within \code{Input} containing replicate and sample mappings #' (Default = ""replicate.map"") #' @param sample.column.name a character or integer indicating which column of \code{Input$replicate.map} describes the samples. #' @param LFC.name a character indicating an object within Input to treat as LFC. By default, ""LFC"" is used, #' which is the output of \code{\link[gemini]{gemini_calculate_lfc}}. #' @param nc_gene a character naming the gene to use as a negative control. See details for more. #' @param CONSTANT a numeric indicating a constant value that shifts counts to reduce outliers, see Details (default = 32). #' @param concordance a numeric value to initialize x (default = 1) #' @param prior_shape shape parameter of Gamma distribution used to model the variation in the #' data in \code{Input} (default = 0.5) #' @param pattern_join a character to join the gene combinations found in #' \code{guide.pair.annot}. Default ';' #' @param pattern_split a character to split the guide combinations found in #' \code{guide.pair.annot}. Default ';' #' @param window a numeric if window smoothing should be done on initialized tau values, #' otherwise NULL (default) for no window smoothing #' @param monotonize a logical specifying whether the variance should be monotonically increasing. (default FALSE) #' @param verbose default FALSE #' @param cores numeric indicating the number of cores to use. See details in \code{\link[gemini]{gemini_parallelization}}. #' @param save a character (file path) or logical indicating whether the initialized model should be saved. #' #' @details #' guide.pair.annot is created with the following format: #' \itemize{ #' \item 1st column contains guide pairs, joined by \code{pattern_split}. #' \item 2nd column contains the name of gene mapping to the first guide in the 1st column. #' \item 3rd column contains the name of gene mapping to the second guide in the 1st column. #' } #' Additional columns may be appended to guide.pair.annot, but the first three columns must be defined as #' above. #' #' \strong{Use of negative control}{ #' As described in Zamanighomi et al., it is highly recommended to specify a negative control. In the event that no negative control is specified, GEMINI will use the median LFC of all guide pairs targeting a gene to initialize that gene's effect. While this may be reasonable in large all-by-all screens, it is \strong{not recommended} in smaller screens or some-by-some screens. As a result, when possible, be sure to specify a negative control. #' } #' #' @return a Model object of class gemini.model #' @export #' #' @examples #' data(""Input"", package = ""gemini"") #' Model <- gemini_initialize(Input, nc_gene = ""CD81"") #' gemini_initialize <- function(Input, guide.pair.annot = ""guide.pair.annot"", replicate.map = ""replicate.map"", sample.column.name = ""samplename"", LFC.name = ""LFC"", nc_gene, CONSTANT = 32, concordance = 1, prior_shape = 0.5, pattern_join = "";"", pattern_split = "";"", window = NULL, monotonize = FALSE, verbose = FALSE, cores = 1, save = NULL) { # Check Input stopifnot(""gemini.input"" %in% class(Input)) # Check parallelization - always leave 1 core free if (cores >= parallel::detectCores()) { cores = parallel::detectCores() - 1 } if (!""LFC"" %in% names(Input)) { stop(""No LFC found! Did you run gemini_calculate_lfc?"") } # Create an empty model object Model <- list() class(Model) <- c(class(Model), ""gemini.model"") # Initialize all Input values Model$Input <- Input Model$guide.pair.annot = guide.pair.annot Model$replicate.map = replicate.map Model$sample.column.name = sample.column.name Model$nc_gene = nc_gene Model$LFC.name = LFC.name Model$pattern_join = pattern_join Model$pattern_split = pattern_split # Run initialization functions Model %<>% initialize_x(concordance = concordance, cores = cores, verbose = verbose) %>% initialize_y(verbose = verbose, cores = cores) %>% initialize_s(verbose = verbose, cores = cores) %>% initialize_tau( CONSTANT = CONSTANT, prior_shape = prior_shape, window = window, monotonize = monotonize, verbose = verbose ) # initialize mae Model$mae <- numeric() # mae calculated using initial values Model <- update_mae(Model = Model, verbose = verbose) if (verbose) message(""Model initialized."") if (!is.null(save)) { # Save initialized model if (!is.character(save) & length(save) == 1) { save = ""gemini_initialized_model"" } saveRDS(Model, file = save) } return(Model) } ","R" "CRISPR","sellerslab/gemini","R/utility.R",".R","4348","142","#' Compound pipe #' #' @name %<>% #' @importFrom magrittr %<>% #' @rdname compound #' @param lhs,rhs An object modified in place, and a function to apply to it #' @export #' @examples #' a <- 1:5 #' a %<>% sum() # a is modified in place #' NULL #' Pipe #' #' @importFrom magrittr %>% #' @name %>% #' @rdname pipe #' @export #' @param lhs,rhs An object, and a function to apply to it #' @examples #' a <- 1:5 #' b <- a %>% sum() NULL #' Median normalization #' @name .median_normalize #' @param counts a counts matrix derived from Input #' @param CONSTANT a pseudo-count to use (default = 32) #' @importFrom stats median #' @return median-normalized counts object #' @examples #' \dontrun{ #' .median_normalize(rnorm(n = 1000)) #' } .median_normalize <- function(counts, CONSTANT = 32) { m = log2(counts + CONSTANT) - median(log2(counts + CONSTANT), na.rm = TRUE) # output return(m) } .window_smooth <- function(x, window = 800) { #flog.debug(""Smoothing"") N = length(x) m = rep(0, N) # mean variance in window m[seq_len(window + 1)] = mean(x[seq_len(2 * window + 1)]) # left shoulder; assume constant start to avoid high variance m[(N - window):N] = mean(x[(N - 2 * window):N]) # right shoulder; assume constant start to avoid high variance for (k in (window + 2):(N - window - 1)) { m[k] = m[k - 1] + (x[k + window + 1] - x[k - window]) / (2 * window + 1) } # linear time average #for (k in (window+2):(N-window-1)) { m[k] = mean(x[(k-window):(k+window+1)])} # linear time average return(m) } # monotonizing .monotonize <- function(x) { #flog.debug(""Monotonizing"") N = length(x) for (i in seq_len(N)) { if (!is.nan(x[N - i + 1])) { x[N - i] = max(x[N - i + 1], x[N - i]) } } return(x) } ### Hash functions: #' Gene hashing #' @name Sgene2Pguides_hash #' @param guide2gene derived from Input object #' @param cores number of cores to use (default 1) #' @importFrom parallel mclapply #' @return Gene hash/list #' @examples #' \dontrun{ #' #' data(""Input"", package = ""gemini"") #' Sgene2Pguides_hash(Input$guide.pair.annot[1:10,]) #' } Sgene2Pguides_hash <- function(guide2gene, cores = 1) { # Single gene to pair guide hash: # First, take all unique genes involved in screen genes = unique(c(guide2gene[, 2], guide2gene[, 3])) # Now identify paired guides associated with each individual gene hash = parallel::mclapply(genes, function(x) { guide2gene[(guide2gene[, 2] == x | guide2gene[, 3] == x), 1] }, mc.cores = cores) %>% magrittr::set_names(genes) # output return(hash) } #' Guide hashing #' @name Sguide2Pguides_hash #' @param guide2gene derived from Input object #' @param split character to split guides #' @param cores number of cores to use (default 1) #' #' @importFrom parallel mclapply #' @importFrom magrittr set_rownames #' @importFrom dplyr bind_rows #' @return Guide hash/list #' @examples #' \dontrun{ #' data(""Input"", package = ""gemini"") #' Sguide2Pguides_hash(gemini::Input$guide.pair.annot[1:10,]) #' } Sguide2Pguides_hash <- function(guide2gene, split = "";"", cores = 1) { # split guide sequences according to the pattern ""split"" paired_guide = parallel::mclapply(guide2gene[, 1], function(x) { s = strsplit(x, split = split, fixed = TRUE)[[1]] data.frame( guide1.sequence = s[1], guide2.sequence = s[2], stringsAsFactors = FALSE ) }, mc.cores = cores, mc.cleanup = TRUE) %>% dplyr::bind_rows() %>% magrittr::set_rownames(guide2gene[, 1]) if (all(is.na(paired_guide$guide1.sequence)) | all(is.na(paired_guide$guide2.sequence))) { stop(""NAs detected for guide splitting - is pattern_split correct?"") } # guide.sequence mapped to the paired guides containing the single guide hash <- lapply(unique(c(paired_guide$guide1.sequence, paired_guide$guide2.sequence)), function(x){ rownames(paired_guide)[paired_guide$guide1.sequence == x | paired_guide$guide2.sequence == x] }) %>% magrittr::set_names(unique(c(paired_guide$guide1.sequence, paired_guide$guide2.sequence))) return(list( hash = hash, paired_guide = paired_guide )) } ","R" "CRISPR","sellerslab/gemini","R/initialize_x.R",".R","3315","90","#' intialize_x #' @description Initialize all x values to the value of \code{concordance} #' #' @param Model a Model object of class gemini.model #' @param concordance a numeric value to initialize x #' @param cores a numeric indicating the number of cores to use. See \code{\link[gemini]{gemini_parallelization}} default 1. #' @param verbose default FALSE #' #' @note As there is much hashing involved in this function, this tends to be computationally intensive. #' As such, we have enabled parallelization of most hash steps, but this may still be rate-limited by the #' amount of memory consumed. #' #' @return a Model object of class gemini.model including new slots for x values and internal-use hashes #' #' @examples #' data(""Model"", package = ""gemini"") #' Model %<>% initialize_x() #' #' @importFrom magrittr set_names #' @importFrom parallel mclapply #' @export initialize_x <- function(Model, concordance = 1, cores = 1, verbose = FALSE) { # Check input stopifnot(""gemini.model"" %in% class(Model)) # User message if (verbose) message(""Initializing x"") Input <- Model$Input LFC <- Input[[Model$LFC.name]] guide2gene <- Input[[Model$guide.pair.annot]] # single guide to paired genes hashmap hash = Sguide2Pguides_hash(guide2gene, Model$pattern_split, cores = cores) # paired guides corresponding to nc_gene;nc_gene remove_seq1 = guide2gene[(guide2gene[, 2] %in% Model$nc_gene), 1] remove_seq2 = guide2gene[(guide2gene[, 3] %in% Model$nc_gene), 1] # guides designed for nc_gene paired_guide_remove_seq1 = as.character(hash$paired_guide[remove_seq1, 1]) %>% unique() paired_guide_remove_seq2 = as.character(hash$paired_guide[remove_seq2, 2]) %>% unique() paired_guide_remove = c(paired_guide_remove_seq1, paired_guide_remove_seq2) # remove nc_gene guides from hashes hash$hash = hash$hash[!is.element(names(hash$hash), paired_guide_remove)] Model$hashes_x <- hash # single guide concordance if (length(concordance) == 1 & is.numeric(concordance)) { Model$x = x_seq = rep(concordance, length(names(hash$hash))) %>% magrittr::set_names(names(hash$hash)) Model$x2 = x_seq ^ 2 } else{ stop( ""No single concordance value specified. Please specify a single concordance value for x."" ) } # hash # genes corresponding to x_seq x_seq_genes = parallel::mclapply( X = names(x_seq), FUN = function(x) { gihj = hash$hash[[x]][1] ij = strsplit(gihj, split = Model$pattern_split, fixed = TRUE)[[1]] gene.col = which(ij == x) + 1 g = guide2gene[match(gihj, guide2gene[, 1]), gene.col] return(g) }, mc.cores = cores ) %>% unlist() %>% magrittr::set_names(names(x_seq)) Model$hashes_x$gene_hash <- x_seq_genes # paired guides concordance xx_names = guide2gene[!(guide2gene[, 2] %in% Model$nc_gene | guide2gene[, 3] %in% Model$nc_gene), 1] Model$xx = xx = rep(concordance, length(xx_names)) %>% magrittr::set_names(xx_names) Model$xx2 = xx ^ 2 # output return(Model) } ","R" "CRISPR","sellerslab/gemini","R/gemini_boxplot.R",".R","12449","312","#' gemini_boxplot #' #' @description A function to visualize the results of GEMINI over the raw data. #' #' @param Model a gemini.model object #' @param g a character naming a gene to visualize #' @param h a character naming another gene to visualize #' @param sample a character naming the sample to visualize #' @param show_inference a logical indicating whether to show the #' inferred individual or combined values for each gene/gene pair (default TRUE) #' @param color_x a logical indicating whether to visualize the #' sample-independent effects for each individual guide or guide pair (default FALSE) #' @param identify_guides a logical indicating whether to identify #' guides with unique colors and shapes (default FALSE) #' @param nc_gene a character naming the gene to use as a negative control, #' to be paired with each individual g and h. Defaults to \code{Model$nc_gene}. #' #' @details Raw LFC data is plotted for each gene combination (`g`-`nc_gene`, `h`-`nc_gene`, `g`-`h`) in a standard boxplot. #' Horizontal green line segments are plotted over the box plots indicating the individual gene effects or #' the inferred total effect of a particular gene combination. Each guide #' pair can be colored based on the inferred sample independent effects #' \eqn{g_i}, \eqn{h_j}, and \eqn{g_i,h_j}. Additionally, colors and shapes #' can be used to distinguish unique guides targeting gene g and h, respectively. #' #' @import ggplot2 #' @importFrom dplyr mutate #' @importFrom grDevices hcl #' #' @return a ggplot2 object #' #' @export #' #' @examples #' #' data(""Model"", package = ""gemini"") #' #' gemini_boxplot(Model, g = ""BRCA2"", h = ""PARP1"", nc_gene = ""CD81"", #' sample = ""A549"", show_inference = TRUE, #' color_x = FALSE, identify_guides = FALSE) #' #' gemini_boxplot <- function(Model, g, h, nc_gene = NULL, sample, show_inference = TRUE, color_x = FALSE, identify_guides = FALSE) { # Extract params from Model Input = Model$Input if (is.null(nc_gene)) nc_gene = Model$nc_gene stopifnot(!is.null(nc_gene)) # if no nc_gene provided, require for plotting. # load required packages, and suggest installation if not already installed. if (!requireNamespace(""ggplot2"")) stop(""Please install the ggplot2 package: install.packages('ggplot2')"") if (!requireNamespace(""magrittr"")) stop(""Please install the magrittr package: install.packages('magrittr')"") # Check inputs: stopifnot(sample %in% colnames(Model$y)) stopifnot(g %in% rownames(Model$y) & h %in% rownames(Model$y)) if (color_x & identify_guides) { color_x = FALSE warning( ""color_x and identify_guides cannot be concurrently visualized. Defaulting to identify_guides."" ) } gihj = Model$hash_s[[paste0(sort(c(g, h)), collapse = Model$pattern_join)]] gh = paste0(sort(c(g, h)), collapse = Model$pattern_join) ginc = Model$hash_s[[paste0(sort(c(g, nc_gene)), collapse = Model$pattern_join)]] hjnc = Model$hash_s[[paste0(sort(c(h, nc_gene)), collapse = Model$pattern_join)]] # For cases in which the negative control pairs were not # included in the inference (i.e. used in the inference process) if (is.null(ginc) | is.null(hjnc)) { ginc = Input$guide.pair.annot$rowname[Input$guide.pair.annot[, 2] == g & Input$guide.pair.annot[, 3] == nc_gene | Input$guide.pair.annot[, 2] == nc_gene & Input$guide.pair.annot[, 3] == g] hjnc = Input$guide.pair.annot$rowname[Input$guide.pair.annot[, 2] == h & Input$guide.pair.annot[, 3] == nc_gene | Input$guide.pair.annot[, 2] == nc_gene & Input$guide.pair.annot[, 3] == h] } # Create data frame using negative control pairs with all g_i df_ginc <- lapply(ginc, function(x) { df = data.frame( gihj = x, gi = strsplit(x, split = Model$pattern_split, fixed = TRUE)[[1]][1], hj = strsplit(x, split = Model$pattern_split, fixed = TRUE)[[1]][2], D = Input$LFC[x, sample], stringsAsFactors = FALSE ) %>% mutate(x_gi = Model$x[.$`gi`]) %>% mutate(x_hj = Model$x[.$`hj`]) %>% mutate(xx_gihj = Model$xx[x]) %>% mutate(y = Model$y[g, sample]) %>% mutate(label = paste0(c(g, nc_gene), collapse = Model$pattern_join)) }) %>% do.call(rbind, .) # Create data frame using negative control pairs with all h_j df_hjnc <- lapply(hjnc, function(x) { df = data.frame( gihj = x, gi = strsplit(x, split = Model$pattern_split, fixed = TRUE)[[1]][1], hj = strsplit(x, split = Model$pattern_split, fixed = TRUE)[[1]][2], stringsAsFactors = FALSE ) %>% mutate(x_gi = Model$x[gi]) %>% mutate(x_hj = Model$x[hj]) %>% mutate(xx_gihj = Model$xx[x]) %>% mutate(D = Input$LFC[x, sample]) %>% mutate(y = Model$y[h, sample]) %>% mutate(label = paste0(c(h, nc_gene), collapse = Model$pattern_join)) }) %>% do.call(rbind, .) # Create data frame using all g_i with all h_j df_gihj <- lapply(gihj, function(x) { df = data.frame( gihj = x, gi = strsplit(x, split = Model$pattern_split, fixed = TRUE)[[1]][1], hj = strsplit(x, split = Model$pattern_split, fixed = TRUE)[[1]][2], stringsAsFactors = FALSE ) %>% mutate(x_gi = Model$x[.$`gi`]) %>% mutate(x_hj = Model$x[.$`hj`]) %>% mutate(xx_gihj = Model$xx[x]) %>% mutate(D = Input$LFC[x, sample]) %>% mutate(y = Model$y[g, sample] + Model$y[h, sample] + Model$s[gh, sample]) %>% mutate(label = gh) }) %>% do.call(rbind, .) # Bind all dataframes together to make final data structure for plotting data <- do.call(rbind, list(df_ginc, df_hjnc, df_gihj)) # Add labels to x-axis of boxplot data$label <- factor(data$label, levels = c( paste0(c(g, nc_gene), collapse = Model$pattern_join), gh, paste0(c(h, nc_gene), collapse = Model$pattern_join) )) if (color_x) { # Process x-values for visualization xs = cbind(data$x_gi, data$x_hj, data$xx_gihj) abs_xs = (xs - 1) # data %<>% # mutate(not_NA = apply(xs, 1, function(x) # sum(!is.na(x)))) %>% # mutate(abs_max = apply(abs_xs, 1, function(x) # x[which.max(abs(x))])) %>% # mutate(avg_x = apply(xs, 1, mean, na.rm = TRUE)) data$vis_x <- data$xx_gihj data$vis_x[is.na(data$vis_x)] <- data$x_gi[is.na(data$vis_x)] data$vis_x[is.na(data$vis_x)] <- data$x_hj[is.na(data$vis_x)] # Generate plot using data p = ggplot(data = data, aes_string( x = ""label"", y = ""D"", color = ""vis_x"" )) + geom_boxplot(outlier.shape = NA) + geom_jitter( data = data, mapping = aes_string(color = ""vis_x""), width = 0.2, size = 2.5, height = 0 ) + scale_color_gradient2( midpoint = 1, high = ""red"", mid = ""black"", low = 'yellow' ) + labs( x = """", y = ""Log-fold change"", color = ""Avg inferred x"", title = sample ) + theme( axis.text = element_text(color = 'black'), axis.ticks = element_line(color = 'black'), panel.background = element_blank() ) + labs(x = """", y = ""Log-fold change"", title = sample) } else if (identify_guides) { # Get guide sequences g_seqs <- names(which(Model$hashes_x$gene_hash == g)) h_seqs <- names(which(Model$hashes_x$gene_hash == h)) # Identify color/shape matches for each guide data$color <- g_seqs[match(data$gi, g_seqs)] data$color[is.na(data$color)] <- g_seqs[match(data$hj[is.na(data$color)], g_seqs)] data$color[is.na(data$color)] <- nc_gene data$shape <- h_seqs[match(data$gi, h_seqs)] data$shape[is.na(data$shape)] <- h_seqs[match(data$hj[is.na(data$shape)], h_seqs)] data$shape[is.na(data$shape)] <- nc_gene # Transform to factor for plotting data$shape <- factor(data$shape, levels = c(unique(data$shape[data$shape != nc_gene]), nc_gene)) nshapes = length(unique(data$shape[!is.na(data$shape)])) - 1 data$color <- factor(data$color, levels = c(unique(data$color[data$color != nc_gene]), nc_gene)) ncolors = length(unique(data$color[!is.na(data$color)])) - 1 # Create color picking function to select from color wheel gg_color_hue <- function(n) { hues = seq(15, 375, length = n + 1) pickedcolors = grDevices::hcl(h = hues, l = 65, c = 100)[seq_len(n)] pickedcolors = c(pickedcolors, grDevices::hcl(0, 0, 0)) return(pickedcolors) } gg_shape_select <- function(n) { allshapes = c(3, 7, 8, 15, 18, 17, 11, 9, 10, 4) if (n > length(allshapes)) { warning( ""More guides than available shapes: Not all guides (shapes) may be distinguishable!"" ) pickedshapes <- sample(allshapes, size = n, replace = TRUE) } else{ pickedshapes <- sample(allshapes, size = n, replace = FALSE) } pickedshapes <- c(pickedshapes, 16) return(pickedshapes) } p = ggplot(data = data, aes_string(x = ""label"", y = ""D"")) + geom_boxplot(outlier.shape = NA) + geom_jitter( data = data, aes_string(color = ""color"", shape = ""shape""), width = 0.2, size = 2.5, height = 0 ) + scale_color_manual(values = gg_color_hue(ncolors)) + scale_shape_manual(values = gg_shape_select(nshapes)) + theme( axis.text = element_text(color = 'black'), axis.ticks = element_line(color = 'black'), panel.background = element_blank() ) + labs(x = """", y = ""Log-fold change"", title = sample) } else{ # Plot default boxplot values p = ggplot(data = data, aes_string(x = ""label"", y = ""D"")) + geom_boxplot(outlier.shape = NA) + geom_jitter( data = data, width = 0.2, size = 2.5, height = 0, color = 'black' ) + theme( axis.text = element_text(color = 'black'), axis.ticks = element_line(color = 'black'), panel.background = element_blank() ) + labs(x = """", y = ""Log-fold change"", title = sample) } if (show_inference) { p = p + geom_segment( mapping = aes( x = as.numeric(label) - 0.5, y = y, yend = y, xend = as.numeric(label) + 0.5 ), color = ""green"" ) } return(p) } ","R" "CRISPR","sellerslab/gemini","R/update_x_pb.R",".R","13550","347","#' update_x_p #' @description Update values of x using data from \code{Input} and current values of other parameters. #' #' @param Model a Model object of class gemini.model #' @param mean_x a numeric indicating prior mean of x #' @param sd_x a numeric indicating prior sd of x #' @param mean_xx a numeric indicating prior mean of xx #' @param sd_xx a numeric indicating prior sd of xx #' @param cores a numeric indicating the number of cores to use. See \code{\link[gemini]{gemini_parallelization}} for details. (default=1). #' @param verbose default FALSE #' #' @return An object of class gemini.model #' @note The structure of the screen may impede parallelization. Our ability to parallelize the updates is #' contingent upon the independence between guides in position 1 and 2. #' To account for potential dependence, we define three groups of guides: group 1 (guides only in position 1 #' ), group 2 (guides only in position 2), and group 3 (guides in both position 1 and position 2). #' Parallelization is possible for groups 1 and 2, but only serial updates are possible for group 3. #' As such, updates for this group will take longer. #' @importFrom parallel mclapply #' @importFrom pbmcapply pbmclapply #' @importFrom magrittr extract #' #' @importFrom utils setTxtProgressBar #' @importFrom utils getTxtProgressBar #' #' @examples #' data(""Model"", package = ""gemini"") #' Model %<>% update_x_pb() #' #' @export update_x_pb <- function(Model, mean_x = 1, sd_x = 1, mean_xx = 1, sd_xx = 1, cores = 1, verbose = FALSE) { if (verbose) { message(""Updating x..."") message(""\tUsing "", cores, "" core(s)."") tstart = Sys.time() } Input <- Model$Input guide2gene <- Input[[Model$guide.pair.annot]] LFC <- Input[[Model$LFC.name]] # genes corresponding to x_seq x_seq_genes = Model$hashes_x$gene_hash # mean of gamma distribution tau = Model$alpha / Model$beta # Allow looping through sd_x if lists are provided if (length(sd_x) == 1) { sd_x = rep(sd_x, length(Model$hashes_x$hash)) names(sd_x) <- names(Model$hashes_x$hash) } if (length(mean_x) == 1) { mean_x = rep(mean_x, length(Model$hashes_x$hash)) names(mean_x) <- names(Model$hashes_x$hash) } if (length(mean_xx) == 1) { mean_xx = rep(mean_xx, nrow(Model$hashes_x$paired_guide)) names(mean_xx) <- rownames(Model$hashes_x$paired_guide) } if (length(sd_xx) == 1) { sd_xx = rep(sd_xx, nrow(Model$hashes_x$paired_guide)) names(sd_xx) <- rownames(Model$hashes_x$paired_guide) } # update x_seq1 and x2_seq1 x_loop <- function(i, Model, guide2gene, LFC, tau, x_seq_genes, mean_x, sd_x) { # get individual mean_xi and sd_xi for guide i # NOTE: mean_x/sd_x should be a named numeric vector, where names correspond to guide labels mean_xi = mean_x[i] sd_xi = sd_x[i] # x_seq to gene names g = as.character(x_seq_genes[i]) # gene g corresponding to guide i gihj = Model$hashes_x$hash[[i]] # all guide pairs containing i h.col = vapply(gihj, function(x){ guidepair = strsplit(x,split = Model$pattern_split, fixed = TRUE)[[1]] return(which(guidepair!=i)) }, numeric(1)) # identify genes h paired with gene g h = guide2gene[match(gihj, guide2gene[, 1]), 2] h[h.col==2] <- guide2gene[match(gihj, guide2gene[, 1]), 3][h.col==2] # if any h in position 1 # identify guides hj paired with guide gi hj = Model$hashes_x$paired_guide[match(gihj, rownames(Model$hashes_x$paired_guide)), 1] # guides for genes h hj[h.col==2] <- Model$hashes_x$paired_guide[match(gihj, rownames(Model$hashes_x$paired_guide)), 2][h.col==2] # if any hj in position 1 gh = apply(cbind(rep(g, length(h)), h), 1, function(x) paste(sort(x), collapse = Model$pattern_join)) # gene g paired with genes h # calculating numerator numerator = LFC[gihj[!h %in% Model$nc_gene], ] - Model$x[hj[!h %in% Model$nc_gene]] * Model$y[h[!h %in% Model$nc_gene], ] - Model$xx[gihj[!h %in% Model$nc_gene]] * Model$s[gh[!h %in% Model$nc_gene], ] numerator = tau[gihj[!h %in% Model$nc_gene], ] * numerator if (sum(!h %in% Model$nc_gene)>1 | sum(!h %in% Model$nc_gene)==0){ numerator = colSums(as.matrix(numerator), na.rm = TRUE) } else{ numerator = colSums(as.matrix(t(numerator)), na.rm = TRUE) } if (sum(h %in% Model$nc_gene)>1 | sum(h %in% Model$nc_gene)==0){ numerator = numerator + colSums(as.matrix(tau[gihj[h %in% Model$nc_gene], ] * LFC[gihj[h %in% Model$nc_gene], ]), na.rm = TRUE) } else{ numerator = numerator + colSums(as.matrix(t(tau[gihj[h %in% Model$nc_gene], ] * LFC[gihj[h %in% Model$nc_gene], ])), na.rm = TRUE) } #numerator = colSums(as.matrix(numerator), na.rm = TRUE) + # colSums(as.matrix(tau[gihj[h %in% Model$nc_gene], ] * LFC[gihj[h %in% Model$nc_gene], ]), na.rm = TRUE) numerator = sum(Model$y[g, ] * numerator, na.rm = TRUE) numerator = mean_xi / (sd_xi ^ 2) + numerator # calculating denominator if(length(gihj)>1){ denominator = sum(colSums(as.matrix(tau[gihj, ]), na.rm = TRUE) * Model$y2[g, ], na.rm = TRUE) } else{ denominator = sum(colSums(as.matrix(t(tau[gihj, ])), na.rm = TRUE) * Model$y2[g, ], na.rm = TRUE) } #denominator = sum(colSums(as.matrix(tau[gihj, ]), na.rm = TRUE) * Model$y2[g, ], na.rm = TRUE) denominator = 1 / (sd_xi ^ 2) + denominator x_seq = numerator / denominator x2_seq = x_seq ^ 2 + 1 / denominator return(list(x_seq = x_seq, x2_seq = x2_seq)) } xx_loop <- function(i, Model, LFC, x_seq_genes, tau, mean_xx, sd_xx) { # Getting individual mean_xxij and sd_xxij values for each guide pair ij mean_xxij = mean_xx[i] sd_xxij = sd_xx[i] # check if both gihj and higj exist i_split = strsplit(x = i, split = Model$pattern_split, fixed = TRUE)[[1]] i_inv = paste0(rev(i_split), collapse = Model$pattern_split) if (!is.na(Model$xx[i_inv])){ i = c(i,i_inv) } # Get genes gh and guides ij gi = Model$hashes_x$paired_guide[i, 1] hj = Model$hashes_x$paired_guide[i, 2] g = x_seq_genes[gi] h = x_seq_genes[hj] #gh = paste(sort(c(g, h)), collapse = Model$pattern_join) gh = vapply(seq_len(length(g)), function(x){ return(paste(sort(c(g[x], h[x])), collapse = Model$pattern_join)) }, character(1)) numerator = Model$s[gh, ] * tau[i, ] * (LFC[i, ] - Model$x[gi] * Model$y[g, ] - Model$x[hj] * Model$y[h, ]) numerator = mean_xxij / (sd_xxij ^ 2) + sum(numerator, na.rm = TRUE) denominator = 1 / (sd_xxij ^ 2) + sum(Model$s2[gh, ] * tau[i, ], na.rm = TRUE) xx = numerator / denominator xx2 = xx ^ 2 + 1 / denominator return(list(xx = xx, xx2 = xx2)) } if (verbose) { message(""\tUpdating x:"") } #### DEBUGGING: ### # x_res <- list() # for(x in names(Model$x)){ # x_res[[x]] <- try({ # x_loop(i = x, # Model = Model, # guide2gene = guide2gene, # LFC = LFC, # tau = tau, # x_seq_genes = x_seq_genes, # mean_x = mean_x, # sd_x = sd_x) # }) # if(""try-error"" %in% class(x_res[[x]])){ # print(x) # } # } ################### group1 <- intersect(names(Model$x), setdiff(Model$hashes_x$paired_guide[,1], Model$hashes_x$paired_guide[,2])) group2 <- intersect(names(Model$x), setdiff(Model$hashes_x$paired_guide[,2], Model$hashes_x$paired_guide[,1])) group3 <- intersect(names(Model$x), intersect(Model$hashes_x$paired_guide[,1], Model$hashes_x$paired_guide[,2])) if(length(group1) > 0){ if(verbose) { message(""\t\tUpdating x for group 1..."") x_group1 <- pbmcapply::pbmclapply( X = group1, FUN = x_loop, Model = Model, guide2gene = guide2gene, LFC = LFC, tau = tau, x_seq_genes = x_seq_genes, mean_x = mean_x, sd_x = sd_x, mc.cores = cores, ignore.interactive = verbose ) }else{ x_group1 <- parallel::mclapply( X = group1, FUN = x_loop, Model = Model, guide2gene = guide2gene, LFC = LFC, tau = tau, x_seq_genes = x_seq_genes, mean_x = mean_x, sd_x = sd_x, mc.cores = cores ) } Model$x[group1] <- lapply(x_group1, magrittr::extract, ""x_seq"") %>% unlist(recursive = TRUE, use.names = FALSE) Model$x2[group1] <- lapply(x_group1, magrittr::extract, ""x2_seq"") %>% unlist(recursive = TRUE, use.names = FALSE) } if(length(group2) > 0){ if(verbose){ message(""\t\tUpdating x for group 2..."") x_group2 <- pbmcapply::pbmclapply( X = group2, FUN = x_loop, Model = Model, guide2gene = guide2gene, LFC = LFC, tau = tau, x_seq_genes = x_seq_genes, mean_x = mean_x, sd_x = sd_x, mc.cores = cores, ignore.interactive = verbose ) }else{ x_group2 <- parallel::mclapply( X = group2, FUN = x_loop, Model = Model, guide2gene = guide2gene, LFC = LFC, tau = tau, x_seq_genes = x_seq_genes, mean_x = mean_x, sd_x = sd_x, mc.cores = cores ) } Model$x[group2] <- lapply(x_group2, magrittr::extract, ""x_seq"") %>% unlist(recursive = TRUE, use.names = FALSE) Model$x2[group2] <- lapply(x_group2, magrittr::extract, ""x2_seq"") %>% unlist(recursive = TRUE, use.names = FALSE) } if(length(group3) > 0){ if(verbose){ message(""\t\tUpdating x for group 3..."") pb <- pbmcapply::progressBar(max = length(group3)) } for(i in group3){ i_res <- x_loop(Model = Model, i = i, guide2gene = guide2gene, LFC = LFC, tau = tau, x_seq_genes = x_seq_genes, mean_x = mean_x, sd_x = sd_x) Model$x[i] <- magrittr::extract(i_res, ""x_seq"") %>% unlist(recursive = TRUE, use.names = FALSE) Model$x2[i] <- magrittr::extract(i_res, ""x2_seq"") %>% unlist(recursive = TRUE, use.names = FALSE) if(verbose) setTxtProgressBar(pb, value = getTxtProgressBar(pb)+1) } if(verbose) close(pb) } if (verbose) { message(""\tUpdating xx:"") xx_res <- pbmcapply::pbmclapply( names(Model$xx), FUN = xx_loop, Model = Model, LFC = LFC, x_seq_genes = x_seq_genes, tau = tau, mean_xx = mean_xx, sd_xx = sd_xx, mc.cores = cores, ignore.interactive = verbose ) }else{ xx_res <- parallel::mclapply( names(Model$xx), FUN = xx_loop, Model = Model, LFC = LFC, x_seq_genes = x_seq_genes, tau = tau, mean_xx = mean_xx, sd_xx = sd_xx, mc.cores = cores ) } Model$xx[] <- lapply(xx_res, magrittr::extract, ""xx"") %>% unlist(use.names = FALSE) Model$xx2[] <- lapply(xx_res, magrittr::extract, ""xx2"") %>% unlist(use.names = FALSE) # output if (verbose) { tend = Sys.time() tdiff = difftime(tend, tstart) message(""\tCompleted update of x."") message(""\tTime to completion: "", round(tdiff, digits = 3), ' ', units(tdiff)) } return(Model) } ","R" "CRISPR","sellerslab/gemini","R/update_s_pb.R",".R","3382","102","#' update_s #' @description Update values of s using data from \code{Input} and current values of other parameters. #' #' @param Model a Model object of class gemini.model #' @param mean_s numeric indicating prior mean of s (default 0) #' @param sd_s numeric indicating prior sd of s (default 10) #' @param cores a numeric indicating the number of cores to use, see \code{\link[gemini]{gemini_parallelization}}. default=1. #' @param verbose default FALSE #' #' @return An object of class gemini.model #' #' @importFrom pbmcapply pbmclapply #' @importFrom parallel mclapply #' @export #' #' @examples #' #' data(""Model"", package = ""gemini"") #' Model %<>% update_s_pb() #' update_s_pb <- function(Model, mean_s = 0, sd_s = 10, cores = 1, verbose = FALSE){ if(verbose) { message(""Updating s..."") message(""\tUsing "", cores, "" core(s)."") tstart = Sys.time() } Input <- Model$Input LFC <- Input[[Model$LFC.name]] guide2gene <- Input[[Model$guide.pair.annot]] # mean of gamma distribution tau = Model$alpha/Model$beta # updating synergy s_loop <- function(gh, Model, guide2gene, LFC, tau, mean_s, sd_s){ gihj = Model$hash_s[[gh]] gi = Model$hashes_x$paired_guide[gihj,1] hj = Model$hashes_x$paired_guide[gihj,2] g = guide2gene[match(gihj,guide2gene[,1]),2] h = guide2gene[match(gihj,guide2gene[,1]),3] # numerator for pair of genes numerator = (Model$xx[gihj]*tau[gihj,])*(LFC[gihj,] - Model$x[gi]*Model$y[g,] - Model$x[hj]*Model$y[h,]) if (length(gihj)>1){ numerator = mean_s/(sd_s^2) + colSums(as.matrix(numerator), na.rm = TRUE) } else{ # transpose because of R numerator = mean_s/(sd_s^2) + colSums(as.matrix(t(numerator)), na.rm = TRUE) } # denominator for pair of genes if (length(gihj)>1){ denominator = 1/(sd_s^2) + colSums(as.matrix(Model$xx2[gihj]*tau[gihj,]), na.rm = TRUE) } else{ # transpose because of R denominator = 1/(sd_s^2) + colSums(as.matrix(t(Model$xx2[gihj]*tau[gihj,])), na.rm = TRUE) } # updating s and s2 s = numerator/denominator s2 = s^2 + 1/denominator return(list(s = s, s2 = s2)) } if(verbose){ s_res <- pbmcapply::pbmclapply(X = rownames(Model$s), FUN = s_loop, Model = Model, guide2gene = guide2gene, LFC = LFC, tau = tau,mean_s = mean_s, sd_s = sd_s, mc.cores = cores) }else{ s_res <- parallel::mclapply(X = rownames(Model$s), FUN = s_loop, Model = Model, guide2gene = guide2gene, LFC = LFC, tau = tau,mean_s = mean_s, sd_s = sd_s, mc.cores = cores) } Model$s[] <- lapply(s_res, extract, ""s"") %>% unlist(recursive = FALSE, use.names = FALSE) %>% do.call(rbind, .) Model$s2[] <- lapply(s_res, extract, ""s2"") %>% unlist(recursive = FALSE, use.names = FALSE) %>% do.call(rbind, .) # output if(verbose){ tend = Sys.time() tdiff = difftime(tend, tstart) message(""\tCompleted update of s."") message(""\tTime to completion: "", round(tdiff, digits = 3), ' ', units(tdiff)) } return(Model) } ","R" "CRISPR","sellerslab/gemini","R/gemini_create_input.R",".R","7855","179","#' gemini_create_input #' #' @description Creates a gemini.input object from a counts matrix with given annotations. #' @param counts.matrix a matrix of counts with rownames corresponding to features (e.g. guides) and colnames corresponding to samples. #' @param sample.replicate.annotation a data.frame of annotations for each sample/replicate pair. #' Note that at least one column in \code{sample.replicate.annotation} must correspond to the colnames of \code{counts.matrix} (see Details) (default = NULL) #' @param guide.annotation a data.frame of annotations for each guide. Note that at least one column in \code{guide.annotation} must correspond to the rownames of counts.matrix (default = NULL) #' @param samplesAreColumns a logical indicating if samples are on the columns or rows of counts.matrix. (default = TRUE) #' @param sample.column.name a character or integer indicating which column of \code{sample.replicate.annotation} describes the samples. #' @param gene.column.names a character or integer vector of length(2) indicating which columns of \code{guide.annotation} describe the genes being targeted. #' @param ETP.column a character or integer vector indicating which column(s) of \code{counts.matrix} contain the early time-point(s) of the screen (i.e. pDNA, early sequencing, etc.). Defaults to the first column. #' @param LTP.column a character or integer vector indicating which column(s) is the later time-point of the screen (i.e. day21, post-treatment, etc.). Defaults to \code{(1:ncol(counts.matrix))[-ETP.column]}, or all other columns except for those specified by \code{ETP.column}. #' @param verbose Verbosity (default FALSE) #' @return a gemini.input object #' #' @details #' This function initializes a gemini.input object from a counts matrix. There are a few key assumptions made in the input format. #' \itemize{ #' \item The counts matrix is regular. #' \item The counts matrix structure is in accordance with the \code{samplesAreColumns} parameter. #' \item The first column of \code{sample.replicate.annotation} matches with the existing dimension names of the counts matrix. #' \item The first column of \code{guide.annotations} matches with the existing dimension names of the counts matrix. #' \item \code{sample.column.name} must specify a column in \code{sample.replicate.annotation} (either by name or index) that describes unique samples. #' \item \code{gene.column.names} must specify two columns in \code{sample.replicate.annotation} (either by name or index) that describe genes. #' } #' #' @importFrom dplyr mutate #' #' @examples #' data(""counts"", package = ""gemini"") #' data(""sample.replicate.annotation"", package = ""gemini"") #' data(""guide.annotation"", package = ""gemini"") #' Input <- gemini_create_input( #' counts.matrix = counts, #' sample.replicate.annotation = sample.replicate.annotation, #' guide.annotation = guide.annotation, #' sample.column.name = ""samplename"", #' gene.column.names = c(""U6.gene"", ""H1.gene"") #' ) #' #' @export gemini_create_input <- function(counts.matrix, sample.replicate.annotation = NULL, guide.annotation = NULL, samplesAreColumns = TRUE, sample.column.name = ""samplename"", gene.column.names = NULL, ETP.column = 1, LTP.column = NULL, verbose = FALSE) { # Check ETP/LTP column identification if (is.numeric(ETP.column) & is.null(LTP.column)) { LTP.column <- seq(from = 1, to = ncol(counts.matrix))[-ETP.column] } else if (is.character(ETP.column) & is.null(LTP.column)) { ETP.column <- which(colnames(counts.matrix) %in% ETP.column) LTP.column <- seq(from = 1, to = ncol(counts.matrix))[-ETP.column] } # Require dimension names for counts matrix if no guide and replicate annotations provided if (is.null(dimnames(counts.matrix)) | is.null(guide.annotation) | is.null(sample.replicate.annotation)) stop(""No dimnames for counts.matrix - no annotations available."", """") # Require sample.column.name and gene.column.names specification if (is.null(gene.column.names) | is.null(sample.column.name)) { stop(""Did you provide gene.column.names and/or sample.column.name?"") } # transpose matrix if (!samplesAreColumns) { if (verbose) message(""Transposing matrix..."") # transpose and preserve dimnames dn <- dimnames(counts.matrix) counts.matrix <- t(counts.matrix) dimnames(counts.matrix) <- rev(dn) } # default guide annotations to rownames of counts matrix gannot <- data.frame(rowname = rownames(counts.matrix), stringsAsFactors = FALSE) # Default sample annotations to column names of counts matrix, ordering by ETP -> LTP sannot <- data.frame( colname = colnames(counts.matrix)[c(ETP.column, LTP.column)], stringsAsFactors = FALSE, row.names = seq(from = 1, to = length(c( ETP.column, LTP.column ))) ) %>% dplyr::mutate(TP = c(rep(""ETP"", length(ETP.column)), rep(""LTP"", length(LTP.column)))) # Merge existing sample annotations with colnames, ensuring formatting and matching names if (!is.null(sample.replicate.annotation) & !is.null(sample.column.name)) { colnames(sample.replicate.annotation)[colnames(sample.replicate.annotation) == sample.column.name] <- ""samplename"" # Set sample column name to ""samplename"" if (verbose) message(""Merging sample annotations with colnames of counts.matrix..."") i = which(apply(sample.replicate.annotation, 2, function(x) all(x %in% sannot[, 1]))) if (!length(i) > 0) { if (verbose) message( ""No columns found in sample.replicate.annotation which completely match colnames of counts.matrix..."" ) } sannot <- merge( sannot, sample.replicate.annotation, by.x = 1, by.y = i[1], no.dups = FALSE, all = FALSE, sort = FALSE, suffixes = c("""", "".y"") ) } else{ stop( ""Could not determine samplename. Please add sample/replicate annotation and specify and sample.column.name. See ?gemini_create_input."" ) } # Merge guide annotations with existing rownames, ensuring formatting and matching names if (!is.null(guide.annotation)) { if (verbose) message(""Merging guide annotations with rownames()..."") i = which(apply(guide.annotation, 2, function(x) all(x %in% gannot[, 1]))) if (!length(i) > 0) { if (verbose) message(""No columns found in guide.annotation which completely match rownames()..."") } gannot <- merge( gannot, guide.annotation, by.x = 1, by.y = i, no.dups = FALSE, all = FALSE, sort = FALSE, suffixes = c("""", "".y"") ) } else{ stop( ""Could not determine gene/guide data. Please add guide annotation and specify and gene.column.names. See ?gemini_create_input."" ) } # Create new Input object Output <- list( counts = data.matrix(counts.matrix[, c(ETP.column, LTP.column)]), replicate.map = as.data.frame( sannot, optional = TRUE, row.names = seq(from = 1, to = nrow(sannot)) ), guide.pair.annot = as.data.frame( gannot, optional = TRUE, rownames = seq(from = 1, to = nrow(gannot)) ) ) Output <- gemini_prepare_input(Output, gene.columns = gene.column.names) class(Output) <- union(class(Output), ""gemini.input"") if (verbose) message(""Created gemini input object."") return(Output) } ","R" "CRISPR","sellerslab/gemini","R/gemini_calculate_lfc.R",".R","6080","140","#' Calculate log-fold change #' @description Given a gemini.input object, calculates log-fold change from \code{counts}. #' @param Input a gemini.input object containing an object named \code{counts}. #' @param counts a character indicating the name of a matrix of counts within \code{Input} that can be used to calculate log-fold changes (defaults to ""counts""). #' @param sample.column.name a character or integer indicating which column of \code{Input$replicate.map} describes the samples. #' @param normalize a logical indicating if counts should be median-normalized, see Details (default = TRUE) #' @param CONSTANT a numeric indicating a constant value that shifts counts to reduce outliers, see Details (default = 32). #' @return a gemini object identical to \code{Input} that also contains new objects called \code{LFC} and \code{sample.annot}. #' #' @details #' See Methods from Zamanighomi et al. 2019 for a comprehensive #' description of the calculation of log-fold change, normalization, #' and count processing. #' #' If multiple early time-points are provided for a given sample, they are treated as replicates and averaged, #' and used to compute log-fold change against any specified late time points. #' #' If a sample has a specific early-time point, these are matched as long as the sample names are identical between #' the early and late timepoints in \code{sample.column.name} #' #' @importFrom stats median #' @importFrom magrittr subtract #' @importFrom magrittr set_names #' @importFrom magrittr set_rownames #' @importFrom dplyr mutate #' @importFrom dplyr filter #' @importFrom dplyr select #' @importFrom dplyr bind_cols #' @export #' #' @usage gemini_calculate_lfc(Input, counts = ""counts"", sample.column.name = ""samplename"", #' normalize = TRUE, CONSTANT = 32) #' #' @examples #' #' data(""Input"", package = ""gemini"") #' Input <- gemini_calculate_lfc(Input) #' #' head(Input$LFC) #' gemini_calculate_lfc <- function(Input, counts = ""counts"", sample.column.name = ""samplename"", normalize = TRUE, CONSTANT = 32) { stopifnot(""gemini.input"" %in% class(Input)) stopifnot(counts %in% names(Input)) # normalize and scale counts mat <- Input[[counts]] total.counts = sum(mat, na.rm = TRUE) SCALE = (total.counts / ncol(mat)) if (normalize) { norm.mat = apply(mat, 2, function(x) { x = ((x / sum(x, na.rm = TRUE)) * SCALE) + CONSTANT }) Input[[paste0(""normalized_"", counts)]] <- norm.mat # compute median-normalized log counts data <- norm.mat } else{ data <- mat } data = apply(data, 2, function(x) { log2(x) - stats::median(log2(x), na.rm = TRUE) }) # compute log-fold changes ETP.cols <- which(Input$replicate.map$TP == ""ETP"") ETP.samples <- unique(Input$replicate.map[ETP.cols, ][[sample.column.name]]) if (length(ETP.cols) == 0) { stop( ""No ETP samples identified. Make sure at least one ETP column is specified in Input$replicate.map$TP"" ) } else if (length(ETP.cols) == 1) { # If only 1 ETP column specified ETP = data[, ETP.cols] } else if (length(ETP.cols) > 1 & !any(ETP.samples %in% Input$replicate.map[-ETP.cols, ][[sample.column.name]])) { # If multiple ETP replicates belonging to only 1 sample (which is not found in LTP samples, i.e. pDNA) ETP = data[, ETP.cols] %>% as.data.frame() %>% rowMeans(na.rm = TRUE) } # If ETPs match LTPs by sample, that is handled here: LTP.cols <- which(Input$replicate.map$TP == ""LTP"") LTP <- as.matrix(data[, LTP.cols]) colnames(LTP) <- Input$replicate.map$colname[LTP.cols] LTP_df <- lapply(unique(Input$replicate.map[[sample.column.name]][Input$replicate.map$TP == ""LTP""]), function(x) { if (!exists('ETP')) { # Check if an ETP dataframe has been established ETP.cols = which(Input$replicate.map$TP == ""ETP"" & Input$replicate.map[[sample.column.name]] == x) if (!length(ETP.cols) > 0) stop(""No ETP specified for "", x) ETP = data[, ETP.cols] %>% as.data.frame() %>% rowMeans(na.rm = TRUE) # Create ETP df for this sample } cols <- Input$replicate.map$colname[Input$replicate.map[[sample.column.name]] == x & Input$replicate.map$TP == ""LTP""] LFC <- LTP[, match(cols, colnames(LTP), nomatch = 0)] %>% as.data.frame(optional = TRUE) %>% rowMeans(na.rm = TRUE) %>% magrittr::subtract(ETP) return(LFC) }) %>% magrittr::set_names(unique(Input$replicate.map[[sample.column.name]][Input$replicate.map$TP == ""LTP""])) %>% dplyr::bind_cols() %>% as.data.frame(optional = TRUE, stringsAsFactors = FALSE) %>% magrittr::set_rownames(Input$guide.pair.annot[, 1]) # Consolidate LFC to sample level unique.to.sample <- names(which( apply(Input$replicate.map, 2, function(x) length(unique(x))) == length(unique(Input$replicate.map[[sample.column.name]])) )) Input$sample.annot <- Input$replicate.map %>% dplyr::filter(.$`TP` == ""LTP"") %>% dplyr::select(dplyr::all_of(c(sample.column.name, 'TP', unique.to.sample))) %>% unique() %>% magrittr::set_rownames(seq(from = 1, to = nrow(.))) %>% dplyr::mutate(rowname = colnames(LTP_df)) Input[[""LFC""]] <- LTP_df %>% dplyr::select(unique(Input$replicate.map[[sample.column.name]][Input$replicate.map$TP != ""ETP""])) %>% as.matrix() # Return object Output <- Input class(Output) <- c(class(Output), ""gemini.input"") return(Output) } ","R" "CRISPR","sellerslab/gemini","R/gemini_prepare_input.R",".R","1927","46","#' Prepare input before Model creation #' #' @description This is an internal function to GEMINI, allowing for data cleanup and preprocessing before a Model object is created. This removes any gene pairs targeting the same gene twice, and removes any empty samples/replicates. #' #' @param Input An object of class gemini.input #' @param gene.columns a character vector of length(2) #' @param sample.col.name a character indicating the name of the sample column (default = ""samplename"") #' #' @return a (prepared) gemini.input object #' #' @examples #' data(""Input"", package = ""gemini"") #' Input %<>% gemini_prepare_input(gene.columns = c(""U6.gene"", ""H1.gene"")) #' #' @importFrom dplyr filter #' @importFrom dplyr select #' #' @export #' gemini_prepare_input <- function(Input, gene.columns, sample.col.name = ""samplename"") { LFC = ""LFC"" newInput <- list() class(newInput) <- base::union(class(Input), ""gemini.input"") dups <- apply(Input$guide.pair.annot[, gene.columns], 1, function(x) any(duplicated(x))) newInput[[""counts""]] <- Input$counts[!dups, colSums(!is.na(Input$counts)) != 0] newInput[[""replicate.map""]] <- Input$replicate.map %>% dplyr::filter(colSums(!is.na(Input$counts)) != 0) %>% dplyr::select(c(""colname"", sample.col.name, ""TP"")) newInput[[""guide.pair.annot""]] <- Input$guide.pair.annot %>% dplyr::filter(!dups) %>% dplyr::select(c(""rowname"", gene.columns)) if (LFC %in% names(Input)) { newInput[[""LFC""]] <- data.matrix(Input[[LFC]][!dups, unique(newInput$replicate.map$sample[newInput$replicate.map$TP == ""LTP""])]) colnames(newInput[[""LFC""]]) <- colnames(Input[[LFC]]) } return(newInput) } ","R" "CRISPR","sellerslab/gemini","R/initialize_tau.R",".R","13694","321","#' initialize_tau #' @description Initialize all tau values based on the observed replicate variance. #' #' @param Model an object of class gemini.model #' @param CONSTANT a numeric indicating a constant value that shifts counts to reduce outliers (default = 32). #' @param prior_shape shape parameter of Gamma distribution used to model the variation in the data in \code{Input}. If single numeric value, then shape parameters for all samples are assumed equal. Otherwise, a named numeric vector of shape parameters the same length as the number of samples (excluding early time point). #' @param window numeric if window smoothing should be done on initialized tau values, otherwise NULL (default) for no window smoothing #' @param monotonize logical specifying whether the variance should be monotonically increasing (default FALSE) #' @param verbose default FALSE #' #' @return a Model object of class gemini.model including new slots for alpha and beta values #' #' @importFrom stats sd #' @importFrom magrittr set_rownames #' @importFrom magrittr set_colnames #' @export #' @examples #' data(""Model"", package = ""gemini"") #' Model <- initialize_tau(Model, CONSTANT = 32, prior_shape = 0.5) initialize_tau <- function(Model, CONSTANT = 32, prior_shape = 0.5, window = NULL, monotonize = FALSE, verbose = FALSE) { # Check input stopifnot(""gemini.model"" %in% class(Model)) # User message if (verbose) message(""Initializing tau"") Input <- Model$Input sample2replicate <- Input[[Model$replicate.map]] # cell line names sample_early = unique(sample2replicate[sample2replicate[, ""TP""] == ""ETP"", Model$sample.column.name]) sample_late = unique(sample2replicate[sample2replicate[, ""TP""] == ""LTP"", Model$sample.column.name]) # Pass to appropriate helper function, given the number of ETP samples if (length(intersect(sample_early, sample_late))==0) { Model <- initialize_tau_single_etp( Model, CONSTANT, prior_shape, window, monotonize, verbose ) } else{ Model <- initialize_tau_multi_etp( Model, CONSTANT, prior_shape, window, monotonize, verbose ) } return(Model) } initialize_tau_multi_etp <- function(Model, CONSTANT = 32, prior_shape = 0.5, window = NULL, monotonize = FALSE, verbose = FALSE) { Input <- Model$Input sample2replicate <- Input[[Model$replicate.map]] # cell line names sample_early = unique(sample2replicate[sample2replicate[, ""TP""] == ""ETP"", Model$sample.column.name]) sample_late = unique(sample2replicate[sample2replicate[, ""TP""] == ""LTP"", Model$sample.column.name]) # prior shape as vector or constant? if (length(prior_shape) == 1) { prior_shape <- rep(prior_shape, length(sample_late)) names(prior_shape) <- sample_late } else if (length(prior_shape) != length(sample_late)) { stop( ""Prior shape not defined for each sample! Please ensure that length of prior shape is the same as the number of LTP samples."" ) } if(!all(sample_late %in% names(prior_shape))){ stop(""Prior shape not defined for each LTP sample! Please ensure that length of prior shape is the same as the number of LTP samples and that names of prior_shape match sample names."") } Model$prior_shape <- prior_shape # define mean and sd matrix meanmat = sdmat = matrix( nrow = nrow(Input$counts), ncol = length(sample_late), dimnames = list(rownames(Input$counts), sample_late) ) meanmat_etp = sdmat_etp = matrix( nrow = nrow(Input$counts), ncol = length(sample_early), dimnames = list(rownames(Input$counts), sample_early) ) # average counts across all samples countavr = sum(Input$counts, na.rm = TRUE) / (ncol(Input$counts)) # mean and sd calculation for (i in sample_early) { col.ind = sample2replicate[sample2replicate[, Model$sample.column.name] == i & sample2replicate[, ""TP""] == ""ETP"", 1] # replicate names for cell line i count_replicates = as.matrix(Input$counts[, col.ind]) count_replicates = apply(count_replicates, 2, function(x) x / sum(x, na.rm = TRUE)) * countavr # normalize samples by total counts count_replicates_mednorm = apply(count_replicates, 2, function(x) .median_normalize(x, CONSTANT)) # median-normalize samples meanmat_etp[, i] = rowMeans(count_replicates_mednorm, na.rm = TRUE) # calculate mean across rows sdmat_etp[, i] = apply(count_replicates_mednorm, 1, function(x) sd(x, na.rm = TRUE)) # calculate sd across rows } for (i in sample_late) { col.ind = sample2replicate[sample2replicate[, Model$sample.column.name] == i & sample2replicate[, ""TP""] == ""LTP"", 1] # replicate names for cell line i count_replicates = as.matrix(Input$counts[, col.ind]) count_replicates = apply(count_replicates, 2, function(x) x / sum(x, na.rm = TRUE)) * countavr # normalize samples by total counts count_replicates_mednorm = apply(count_replicates, 2, function(x) .median_normalize(x, CONSTANT)) # median-normalize samples meanmat[, i] = rowMeans(count_replicates_mednorm, na.rm = TRUE) # calculate mean sdmat[, i] = apply(count_replicates_mednorm, 1, function(x) sd(x, na.rm = TRUE)) # calculate sd } # window smoothing and monotonizing if (!is.null(window)) { for (i in seq_len(length(sample_early))) { I = order(meanmat_etp[, i], decreasing = FALSE) vars = sdmat_etp[I, i] ^ 2 # window smoothing vars = .window_smooth(vars, window) # monotonizing if (monotonize) { vars = .monotonize(vars) } sdmat_etp[I, i] = vars ^ 0.5 } for (i in seq_len(length(sample_late))) { I = order(meanmat[, i], decreasing = FALSE) vars = sdmat[I, i] ^ 2 # window smoothing vars = .window_smooth(vars, window) # monotonizing if (monotonize) { vars = .monotonize(vars) } sdmat[I, i] = vars ^ 0.5 } } # sd calculation when one replicate available if (any(!is.na(sdmat)) | any(!is.na(sdmat_etp))) { # at least two replicates available for minimum one cell line # median uncertainty across all cell lines if no replicate available for a cell line sdmat[, colSums(!is.na(sdmat)) == 0] = median(cbind(sdmat, sdmat_etp), na.rm = TRUE) sdmat_etp[, colSums(!is.na(sdmat_etp)) == 0] = median(cbind(sdmat, sdmat_etp), na.rm = TRUE) # median uncertainty within one cell line if no replicate available for a guide sdmat = apply(sdmat, 2, function(x) { x[is.na(x)] = median(x, na.rm = TRUE) return(x) }) sdmat_etp = apply(sdmat_etp, 2, function(x) { x[is.na(x)] = median(x, na.rm = TRUE) return(x) }) beta <- matrix( nrow = nrow(sdmat), ncol = length(sample_late), dimnames = list(rownames(sdmat), sample_late) ) for (i in sample_late) { beta[, i] = prior_shape[i] * sdmat[, i] ^ 2 + sdmat_etp[, sample_early == i] ^ 2 + 2 * 1e-2 } } else { # if no replicate available for any cell line beta = matrix( 0.2 * prior_shape[sample_late], nrow = nrow(sdmat), ncol = ncol(sdmat), dimnames = list(rownames(sdmat), sample_late), byrow = TRUE ) # assume beta = 0.2*prior_shape, leading to the variance beta/alpha = 0.2 for LFCs } alpha = matrix( prior_shape[sample_late], nrow = nrow(beta), ncol = ncol(beta), dimnames = list(rownames(beta), colnames(beta)), byrow = TRUE ) # output Model$alpha = alpha Model$beta = Model$beta_prior = beta return(Model) } initialize_tau_single_etp <- function(Model, CONSTANT = 32, prior_shape = 0.5, window = NULL, monotonize = FALSE, verbose = FALSE) { Input <- Model$Input sample2replicate <- Input[[Model$replicate.map]] # cell line names sample_early = unique(sample2replicate[sample2replicate[, ""TP""] == ""ETP"", Model$sample.column.name]) sample = unique(sample2replicate[,Model$sample.column.name]) # prior shape as vector or constant? if (length(prior_shape) == 1) { prior_shape <- rep(prior_shape, length(unique(sample2replicate$samplename[sample2replicate[, ""TP""] == 'LTP']))) names(prior_shape) <- unique(sample2replicate$samplename[sample2replicate[, ""TP""] == 'LTP']) } else if (length(prior_shape) != length(unique(sample2replicate[sample2replicate[, ""TP""] == ""LTP"", Model$sample.column.name]))) { stop( ""Prior shape not defined for each LTP sample! Please ensure that length of prior shape is the same as the number of LTP samples, or that one prior shape is defined for all."" ) } if(!all(unique(sample2replicate[sample2replicate[, ""TP""] == ""LTP"", Model$sample.column.name]) %in% names(prior_shape))){ stop(""Prior shape not defined for each LTP sample! Please ensure that length of prior shape is the same as the number of LTP samples and that names of prior_shape match sample names."") } Model$prior_shape <- prior_shape # define mean and sd matrix meanmat = sdmat = matrix( nrow = nrow(Input$counts), ncol = length(sample), dimnames = list(rownames(Input$counts), sample) ) countavr = sum(Input$counts, na.rm = TRUE) / (ncol(Input$counts)) # average counts per replicate # mean and sd calculation for (i in sample) { col.ind = sample2replicate[sample2replicate[, Model$sample.column.name] == i, 1] # replicate names for sample i count_replicates = as.matrix(Input$counts[, col.ind]) count_replicates = apply(count_replicates, 2, function(x) x / sum(x, na.rm = TRUE)) * countavr # normalize samples by total counts count_replicates_mednorm = apply(count_replicates, 2, function(x) .median_normalize(x, CONSTANT)) # median-normalize samples meanmat[, i] = rowMeans(count_replicates_mednorm, na.rm = TRUE) # calculate mean sdmat[, i] = apply(count_replicates_mednorm, 1, function(x) sd(x, na.rm = TRUE)) # calculate sd } # window smoothing and monotonizing if (!is.null(window)) { for (i in seq_len(length(sample))) { I = order(meanmat[, i], decreasing = FALSE) vars = sdmat[I, i] ^ 2 # window smoothing vars = .window_smooth(vars, window) # monotonizing if (monotonize) { vars = .monotonize(vars) } sdmat[I, i] = vars ^ 0.5 } } # sd calculation when one replicate available if (any(!is.na(sdmat))) { # at least two replicates available for minimum one cell line # median uncertainty across all cell lines if no replicate available for a cell line sdmat[, colSums(!is.na(sdmat)) == 0] = median(sdmat, na.rm = TRUE) # median uncertainty within one cell line if no replicate available for a guide sdmat = apply(sdmat, 2, function(x) { x[is.na(x)] = median(x, na.rm = TRUE) return(x) }) beta = t(t(sdmat[,!(sample_early == colnames(sdmat))] ^ 2 + sdmat[, sample_early] ^ 2 + 2 * 1e-2) * prior_shape[sample[!(sample_early == colnames(sdmat))]]) %>% as.matrix() %>% magrittr::set_colnames(sample[!(sample_early == colnames(sdmat))]) %>% magrittr::set_rownames(rownames(sdmat)) } else { # if no replicate available for any cell line beta = matrix( 0.2 * prior_shape[sample[!(sample_early == colnames(sdmat))]], nrow = dim(sdmat)[1], ncol = sum(!(sample_early == colnames(sdmat))), dimnames = list(rownames(sdmat), sample[!(sample_early == colnames(sdmat))]), byrow = TRUE ) # assume beta = 0.2*prior_shape, leading to the variance beta/alpha = 0.2 for LFCs } alpha = matrix( prior_shape[sample[!(sample_early == colnames(sdmat))]], nrow = dim(beta)[1], ncol = dim(beta)[2], dimnames = list(rownames(beta), colnames(beta)), byrow = TRUE ) # output Model$alpha = alpha Model$beta = Model$beta_prior = beta return(Model) } ","R" "CRISPR","sellerslab/gemini","R/gemini_parallelization.R",".R","2297","31","#' @title Parallelization in GEMINI #' @name gemini_parallelization #' @description Notes about parallelization in combinatorial CRISPR analysis #' #' @section Implementation: #' #' To improve efficiency and scalability, GEMINI employs parallelization, enabling a rapid initialization and update routine. #' Parallelization was implemented using the R \code{pbmclapply} package, and specifically through the \code{\link[pbmcapply]{pbmclapply}} function. #' As pbmclapply (and it's parent function, \code{\link{mclapply}}) relies on forking, parallelization is currently limited to Unix-like (Linux flavors and macOS) machines, but may be extended to other OS in later versions through socket parallelization. In the event that GEMINI is used on a Windows machine, all computations are performed in serial. #' #' @section Parallelized processes: #' #' GEMINI enables parallelization of both initialization and inference. For initialization, parallelization is used to quickly hash the data. For the inference procedure, parallelization is used to speed up the CAVI approach by performing updates independently across cores. #' #' @section Caveats: #' To note, there is usually a trade-off in terms of number of cores and shared resources/memory transfer. See inst/figs/gemini-benchmarking.png for a visual depiction. #' #' Also, while most functions in GEMINI have been parallelized, initialization of tau, update of x (group 3), and updates of y are performed in serial. As such, especially in large libraries, tau initialization and x (group 3) updates may take some time. Updating y is usually fast, as the number of genes tends to be the smallest in parameter space. However, these functions may be parallelized in the future as well. #' #' @section Active Development: #' Noticed that in some cases, after using multicore processing through pbmclapply, #' warnings have been produced: #' ""In selectChildren(pids[!fin], -1) : cannot wait for child ... as it does not exist"" #' ""In parallel::mccollect(...) : 1 parallel job did not deliver a result"" #' R.version=3.6.0 #' These warnings, although they appear menacing, are in fact harmless. #' See: http://r.789695.n4.nabble.com/Strange-error-messages-from-parallel-mcparallel-family-under-3-6-0-td4756875.html#a4756939 #' #' NULL ","R" "CRISPR","sellerslab/gemini","R/initialize_y.R",".R","2542","79","#' initialize_y #' @description Initialize all y values from guide pairs including a negative control. #' #' @param Model an object of class gemini.model #' @param verbose default FALSE #' @param cores a numeric indicating the number of cores to use. See details in \code{\link[gemini]{gemini_parallelization}}. (default=1) #' #' @return a Model object of class gemini.model including new slots for y values #' #' @examples #' data(""Model"", package = ""gemini"") #' Model %<>% initialize_y() #' #' @export initialize_y <- function(Model, verbose = FALSE, cores = 1) { # Check input stopifnot(""gemini.model"" %in% class(Model)) if (verbose) message(""Initializing y"") # Create inputs Input <- Model$Input guide2gene <- Input[[Model$guide.pair.annot]] LFC <- Input[[Model$LFC.name]] # gene pairs containing nc_gene guide2nc_gene = guide2gene[guide2gene[, 2] %in% Model$nc_gene | guide2gene[, 3] %in% Model$nc_gene, ] # genes mapped to guides hash_nc = Sgene2Pguides_hash(guide2nc_gene, cores) hash_others = Sgene2Pguides_hash(guide2gene, cores) # gene list genes = unique(c(guide2gene[, 2], guide2gene[, 3])) # removing nc_gene from gene list genes = genes[!is.element(genes, Model$nc_gene)] # define matrix y y = matrix( nrow = length(genes), ncol = ncol(LFC), dimnames = list(genes, colnames(LFC)) ) # estimate y for (i in genes) { # all genes should be paired with nc_gene ind = hash_nc[[i]] if (length(ind) > 1) { y[i, ] = apply(as.matrix(LFC[ind, ]), 2, function(x) median(x, na.rm = TRUE)) } else if (length(ind) == 1){ y[i, ] = apply(as.matrix(t(LFC[ind, ])), 2, function(x) median(x, na.rm = TRUE)) } else{ # ... but if not, use the median LFC of all interactions involving the gene # NOTE: only a good assumption if you have an all-by-all screen! ind = hash_others[[i]] if (length(ind) > 1) { y[i, ] = apply(as.matrix(LFC[ind, ]), 2, function(x) median(x, na.rm = TRUE)) } else{ y[i, ] = apply(as.matrix(t(LFC[ind, ])), 2, function(x) median(x, na.rm = TRUE)) } } } # output Model$y <- y Model$y2 <- y ^ 2 return(Model) } ","R" "CRISPR","sellerslab/gemini","R/update_y_pb.R",".R","5354","139","#' update_y_pb #' @description Update values of y using data from \code{Input} #' and current values of other parameters. #' #' @param Model a Model object of class gemini.model #' @param mean_y numeric indicating prior mean of y #' @param sd_y numeric indicating prior sd of y #' @param verbose default FALSE #' #' @return An object of class gemini.model #' #' @importFrom pbmcapply pbmclapply #' @importFrom magrittr set_names #' @importFrom pbmcapply progressBar #' @importFrom utils getTxtProgressBar #' @importFrom utils setTxtProgressBar #' #' @examples #' data(""Model"", package = ""gemini"") #' Model %<>% update_y_pb() #' #' @export update_y_pb <- function(Model, mean_y = 0, sd_y = 10, verbose = FALSE) { if (verbose) { message(""Updating y..."") message(""\tUsing 1 core (serial)."") tstart = Sys.time() pb <- pbmcapply::progressBar(min = 1, max = length(rownames(Model$y))) } Input <- Model$Input LFC <- Input[[Model$LFC.name]] guide2gene <- Input[[Model$guide.pair.annot]] # genes corresponding to x_seq1 x_seq_genes = Model$hashes_x$gene_hash # mean of gamma distribution tau = Model$alpha / Model$beta # update y for (g in rownames(Model$y)) { gi_seq = names(x_seq_genes)[x_seq_genes == g] gi_seq_hj = lapply(gi_seq, function(x) unlist(Model$hashes_x$hash[x])) %>% magrittr::set_names(gi_seq) # calculating updates for each x_seq numerator = denominator = numeric(ncol(LFC)) %>% magrittr::set_names(colnames(LFC)) for (i in gi_seq) { # identify which position the partner gene (h) is in h.col <- vapply(gi_seq_hj[[i]], function(s) { ss = strsplit(s, split = Model$pattern_split, fixed = TRUE)[[1]] return(which(ss != i)) }, numeric(1)) # identify cases in which the partner gene is nc_gene ind_nc = guide2gene[match(gi_seq_hj[[i]], guide2gene[, 1]), 3] ind_nc[h.col == 1] = guide2gene[match(gi_seq_hj[[i]], guide2gene[, 1]), 2][h.col == 1] ind_nc = ind_nc %in% Model$nc_gene # identify partner guides, filtering out nc_gene guides hj = Model$hashes_x$paired_guide[gi_seq_hj[[i]], 2] hj[h.col == 1] = Model$hashes_x$paired_guide[gi_seq_hj[[i]], 1][h.col == 1] hj = hj[!ind_nc] # gene g paired with genes h h = x_seq_genes[hj] gh = apply(cbind(rep(g, length(h)), h), 1, function(x) paste(sort(x), collapse = Model$pattern_join)) # numerator for each guide i numerator_i = LFC[gi_seq_hj[[i]][!ind_nc],] - Model$x[hj] * Model$y[h,] - Model$xx[gi_seq_hj[[i]][!ind_nc]] * Model$s[gh,] numerator_i = (Model$x[i] * tau[gi_seq_hj[[i]][!ind_nc],]) * numerator_i if (sum(!ind_nc) > 1 | sum(!ind_nc) == 0) { numerator_i = colSums(as.matrix(numerator_i), na.rm = TRUE) } else{ numerator_i = colSums(as.matrix(t(numerator_i)), na.rm = TRUE) } numerator_nc_i = (Model$x[i] * tau[gi_seq_hj[[i]][ind_nc],]) * LFC[gi_seq_hj[[i]][ind_nc],] if (sum(ind_nc) > 1 | sum(ind_nc) == 0) { numerator_nc_i = colSums(as.matrix(numerator_nc_i), na.rm = TRUE) } else{ numerator_nc_i = colSums(as.matrix(t(numerator_nc_i)), na.rm = TRUE) } numerator_i = numerator_i + numerator_nc_i numerator = numerator_i + numerator # denominator for each guide i if (length(gi_seq_hj[[i]]) > 1) { denominator_i = colSums(as.matrix(Model$x2[i] * tau[gi_seq_hj[[i]],]), na.rm = TRUE) } else{ denominator_i = colSums(as.matrix(t(Model$x2[i] * tau[gi_seq_hj[[i]],])), na.rm = TRUE) } #denominator_i = colSums(as.matrix(Model$x2[i] * tau[gi_seq_hj[[i]], ]), na.rm = TRUE) denominator = denominator_i + denominator } # update progress bar if (verbose) utils::setTxtProgressBar(pb = pb, value = utils::getTxtProgressBar(pb) + 1) # adding prior values to the numerator and denominator numerator = mean_y / (sd_y ^ 2) + numerator denominator = 1 / (sd_y ^ 2) + denominator # updating y and y2 Model$y[g,] = numerator / denominator Model$y2[g,] = Model$y[g,] ^ 2 + 1 / denominator } # output if (verbose) { close(pb) tend = Sys.time() tdiff = difftime(tend, tstart) message(""\tCompleted update of y."") message(""\tTime to completion: "", round(tdiff, digits = 3), ' ', units(tdiff)) } return(Model) } ","R" "CRISPR","sellerslab/gemini","R/initialize_s.R",".R","2401","79","#' initialize_s #' @description Initialize s values using initialized y values and data from \code{Input} #' #' @param Model an object of class gemini.model #' @param cores a numeric indicating the number of cores to use. See \code{\link[gemini]{gemini_parallelization}} default 1. #' @param verbose default FALSE #' #' @return a Model object of class gemini.model including new slots for s values #' #' @importFrom magrittr set_names #' @export #' #' @examples #' data(""Model"", package = ""gemini"") #' Model <- initialize_s(Model) initialize_s <- function(Model, cores = 1, verbose = FALSE) { # Check input stopifnot(""gemini.model"" %in% class(Model)) # User message if (verbose) message(""Initializing s"") Input <- Model$Input guide2gene <- Input[[Model$guide.pair.annot]] LFC <- Input[[Model$LFC.name]] # calculate initial y y = Model$y # remove control gene guide2gene = guide2gene[!(guide2gene[, 2] %in% Model$nc_gene | guide2gene[, 3] %in% Model$nc_gene), ] # find unique gene pairs guide2gene$Key <- apply(guide2gene[, c(2, 3)], 1, function(x) paste(sort(x), collapse = Model$pattern_join)) Pairs = unique(guide2gene$Key) # paired genes mapped to paired guides hash <- parallel::mclapply(Pairs, function(x) { as.character(guide2gene[guide2gene$Key == x, 1]) }, mc.cores = cores) %>% magrittr::set_names(Pairs) # Initialize s using initialized y values res = parallel::mclapply(Pairs, function(i) { ind = unlist(hash[i]) if (length(ind)>1){ vec = apply(as.matrix(LFC[ind, ]), 2, function(x) median(x, na.rm = TRUE)) } else{ vec = apply(as.matrix(t(LFC[ind, ])), 2, function(x) median(x, na.rm = TRUE)) } g = strsplit(i, Model$pattern_join)[[1]][1] h = strsplit(i, Model$pattern_join)[[1]][2] vec = vec - y[g, ] - y[h, ] return(vec) }, mc.cores = cores) s = matrix( unlist(res), byrow = TRUE, nrow = length(Pairs), ncol = ncol(LFC), dimnames = list(Pairs, colnames(LFC)) ) # save output Model$s <- s Model$s2 <- s ^ 2 Model$hash_s <- hash return(Model) } ","R" "CRISPR","sellerslab/gemini","R/update_tau_pb.R",".R","4035","117","#' update_tau_pb #' @description Update parameters of tau using data from \code{Input} and current values of other parameters. #' #' @param Model a Model object of class gemini.model #' @param cores a numeric indicating the number of cores to use. See \code{\link[gemini]{gemini_parallelization}} for details. (default=1). #' @param verbose default FALSE #' #' @return An object of class gemini.model #' #' @importFrom pbmcapply pbmclapply #' @importFrom parallel mclapply #' #' @examples #' data(""Model"", package = ""gemini"") #' Model %<>% update_tau_pb() #' #' @export update_tau_pb <- function(Model, cores = 1, verbose = FALSE) { if (verbose) { message(""Updating tau..."") message(""\tUsing "", cores, ' core(s).') tstart = Sys.time() } Input <- Model$Input LFC <- Input[[Model$LFC.name]] guide2gene <- Input[[Model$guide.pair.annot]] # mean of gamma distribution tau = Model$alpha / Model$beta # define loop function tau_loop <- function(gihj, Model, guide2gene, LFC) { gi = Model$hashes_x$paired_guide[gihj, 1] hj = Model$hashes_x$paired_guide[gihj, 2] g = guide2gene[match(gihj, guide2gene[, 1]), 2] h = guide2gene[match(gihj, guide2gene[, 1]), 3] gh = paste(sort(c(g, h)), collapse = Model$pattern_join) # calculating beta* gnc = g %in% Model$nc_gene hnc = h %in% Model$nc_gene if (!(gnc) & !(hnc)) { beta_star = LFC[gihj,] ^ 2 - 2 * LFC[gihj,] * (Model$x[gi] * Model$y[g,] + Model$x[hj] * Model$y[h,] + Model$xx[gihj] * Model$s[gh,]) + Model$x2[gi] * Model$y2[g,] + 2 * Model$x[gi] * Model$y[g,] * (Model$x[hj] * Model$y[h,] + Model$xx[gihj] * Model$s[gh,]) + Model$x2[hj] * Model$y2[h,] + Model$xx2[gihj] * Model$s2[gh,] + 2 * Model$x[hj] * Model$y[h,] * Model$xx[gihj] * Model$s[gh,] } else if (gnc & !(hnc)) { beta_star = LFC[gihj,] ^ 2 + Model$x2[hj] * Model$y2[h,] - 2 * LFC[gihj,] * Model$x[hj] * Model$y[h,] } else if (!(gnc) & hnc) { beta_star = LFC[gihj,] ^ 2 + Model$x2[gi] * Model$y2[g,] - 2 * LFC[gihj,] * Model$x[gi] * Model$y[g,] } else { beta_star = LFC[gihj,] ^ 2 } # updating alpha and beta alpha_gihj = Model$prior_shape + 0.5 beta_gihj = Model$beta_prior[gihj,] + 0.5 * beta_star return(list(alpha = alpha_gihj, beta = beta_gihj)) } if(verbose){ res <- pbmcapply::pbmclapply( X = rownames(Model$alpha), FUN = tau_loop, Model = Model, guide2gene = guide2gene, LFC = LFC, mc.cores = cores ) }else{ res <- parallel::mclapply( X = rownames(Model$alpha), FUN = tau_loop, Model = Model, guide2gene = guide2gene, LFC = LFC, mc.cores = cores ) } Model$beta[,] <- lapply(res, magrittr::extract, ""beta"") %>% unlist(recursive = FALSE, use.names = FALSE) %>% do.call(rbind, .) Model$alpha[,] <- lapply(res, magrittr::extract, ""alpha"") %>% unlist(recursive = FALSE, use.names = FALSE) %>% do.call(rbind, .) # output if (verbose) { tend = Sys.time() tdiff = difftime(tend, tstart) message(""\tCompleted update of tau."") message(""\tTime to completion: "", round(tdiff, digits = 3), ' ', units(tdiff)) } return(Model) } ","R" "CRISPR","sellerslab/gemini","R/update_mae.R",".R","1961","58","#' update_mae #' #' @description Calculate mean absolute error across all guide combinations. #' #' @param Model a Model object of class gemini.model #' @param verbose default FALSE #' #' @return An object of class gemini.model #' #' @examples #' data(""Model"", package = ""gemini"") #' Model %<>% update_mae() #' #' @export update_mae <- function(Model, verbose = FALSE){ stopifnot(""gemini.model"" %in% class(Model)) # Calculate MAE if(verbose) message(""Updating mae"") Input <- Model$Input LFC = Input[[Model$LFC.name]] guide2gene = Input[[Model$guide.pair.annot]] # Find each level of information - guide pair/guide, gene pair/gene gihj = rownames(LFC) gi = Model$hashes_x$paired_guide[gihj,1] hj = Model$hashes_x$paired_guide[gihj,2] g = guide2gene[match(gihj,guide2gene[,1]),2] h = guide2gene[match(gihj,guide2gene[,1]),3] gh = apply(cbind(g,h), 1, function(x) paste(sort(x),collapse = Model$pattern_join)) # Initialize empty error matrix error = matrix(0, nrow = nrow(LFC), ncol = ncol(LFC), dimnames = list(rownames(LFC), colnames(LFC))) # Calculate error for each non-negative control pair ind = (!g %in% Model$nc_gene) & (!h %in% Model$nc_gene) error[ind,] = LFC[ind,] - Model$x[gi[ind]]*Model$y[g[ind],] - Model$x[hj[ind]]*Model$y[h[ind],] - Model$xx[gihj[ind]]*Model$s[gh[ind],] # Calculate error for each pairs with 1 NC ind = (!g %in% Model$nc_gene) & (h %in% Model$nc_gene) error[ind,] = LFC[ind,] - Model$x[gi[ind]]*Model$y[g[ind],] ind = (g %in% Model$nc_gene) & (!h %in% Model$nc_gene) error[ind,] = LFC[ind,] - Model$x[hj[ind]]*Model$y[h[ind],] # Do not calculate error for pairs with 2 NCs ind = (g %in% Model$nc_gene & h %in% Model$nc_gene) error[ind,] = NA # output Model$mae = c(Model$mae, mean(abs(error), na.rm = TRUE)) Model$residuals = error return(Model) } ","R" "CRISPR","sellerslab/gemini","tests/testthat.R",".R","55","4","library(testthat) library(gemini) test_check(""gemini"")","R" "CRISPR","sellerslab/gemini","tests/testthat/test_data.R",".R","1464","34","library(""gemini"") testthat::test_that(""data is correct"", code = ({ data(""counts"", package = ""gemini"") data(""guide.annotation"", package = ""gemini"") data(""sample.replicate.annotation"", package = ""gemini"") data(""Input"", package = ""gemini"") data(""Model"", package = ""gemini"") # Make sure that dimensions match up expect_equal(nrow(counts), nrow(guide.annotation)) expect_equal(rownames(counts), guide.annotation[,1]) expect_equal(ncol(counts), nrow(sample.replicate.annotation)) expect_equal(colnames(counts), sample.replicate.annotation[,1]) })) testthat::test_that(""Input object is reproducible"", code = ({ data(""counts"", package = ""gemini"") data(""guide.annotation"", package = ""gemini"") data(""sample.replicate.annotation"", package = ""gemini"") Input.new <- gemini_create_input(counts.matrix = counts, sample.replicate.annotation = sample.replicate.annotation, guide.annotation = guide.annotation, sample.column.name = 'samplename', gene.column.names = c(""U6.gene"", ""H1.gene""), ETP.column = 1, verbose = TRUE) Input.new %<>% gemini_calculate_lfc() data(""Input"", package = ""gemini"") expect_equal(Input.new, Input) }) ) ","R" "CRISPR","sellerslab/gemini","tests/testthat/test_plots.R",".R","333","10","library(""gemini"") test_that(""plots are working"", { data(""Model"", package = ""gemini"") gg = gemini_plot_mae(Model) testthat::expect_is(object = gg, class = ""ggplot"") gg2 = gemini_boxplot(Model, g = ""BRCA1"", h = ""BRCA2"", nc_gene = ""CD81"", sample = ""A549"") testthat::expect_is(object = gg2, class = ""ggplot"") })","R" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","CHANGELOG.md",".md","1053","40","# Changelog ## 1.0.0 (2023-12-05) ### New Features Snakemake Pipeline * All the different components of ABC were moved into Snakemake, allowing easy execution of the entire ABC codebase with 1 snakemake command Customization of ABC via config files * Customization of ABC done in config files, instead of CLI arguments Streaming of .hic files * Support reading .hic files directly for the contact portion of the model Support ATAC and scATAC as input Support passing multiple input files (e.g 2 DHS BAM files) Documentation overhaul to ReadTheDocs QC Plots for all ABC runs Updated hg38 reference files ### Reliability Improvements Conda Environments * Conda environment yml file that can get built successfully on linux and macosx * To prevent environment breakages, the conda environment gets built everyday via CircleCI End to End Tests * Tests that run ABC end to end and verifies there are no correctness regressions ### Bug Fixes/Improvements Fixes to powerlaw computation, NaN ABC scores, sex chromosome normalization, and more ","Markdown" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/filter_predictions.py",".py","2344","76","import click import pandas as pd from predictor import make_gene_prediction_stats from tools import write_connections_bedpe_format @click.command() @click.option(""--output_tsv_file"", type=str) @click.option(""--output_slim_tsv_file"", type=str) @click.option(""--output_bed_file"", type=str) @click.option(""--output_gene_stats_file"", type=str) @click.option(""--pred_file"", type=str) @click.option(""--pred_nonexpressed_file"", type=str) @click.option( ""--score_column"", type=str, help=""Column name of score to use for thresholding"", ) @click.option(""--threshold"", type=float) @click.option(""--include_self_promoter"", type=bool) @click.option(""--only_expressed_genes"", type=bool) def main( output_tsv_file, output_slim_tsv_file, output_bed_file, output_gene_stats_file, pred_file, pred_nonexpressed_file, score_column, threshold, include_self_promoter, only_expressed_genes, ): slim_columns = [ ""chr"", ""start"", ""end"", ""name"", ""TargetGene"", ""TargetGeneTSS"", ""CellType"", score_column, ] all_putative = pd.read_csv(pred_file, sep=""\t"") if not only_expressed_genes: non_expressed = pd.read_csv(pred_nonexpressed_file, sep=""\t"") all_putative = pd.concat([all_putative, non_expressed], ignore_index=True) filtered_predictions = all_putative[all_putative[score_column] > threshold] filtered_predictions = remove_promoters(filtered_predictions, include_self_promoter) filtered_predictions.to_csv( output_tsv_file, sep=""\t"", index=False, header=True, float_format=""%.6f"" ) filtered_predictions_slim = filtered_predictions[slim_columns] filtered_predictions_slim.to_csv( output_slim_tsv_file, sep=""\t"", index=False, header=True, float_format=""%.6f"" ) write_connections_bedpe_format(filtered_predictions, output_bed_file, score_column) make_gene_prediction_stats( filtered_predictions, score_column, threshold, output_gene_stats_file ) def remove_promoters(pred_df: pd.DataFrame, keep_self_promoters: bool) -> pd.DataFrame: if keep_self_promoters: return pred_df[(pred_df[""class""] != ""promoter"") | pred_df[""isSelfPromoter""]] else: return pred_df[pred_df[""class""] != ""promoter""] if __name__ == ""__main__"": main() ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/hic.py",".py","9027","285","import os import time import numpy as np import pandas as pd import scipy.sparse as ssp def get_hic_file(chromosome, hic_dir, allow_vc=True, hic_type=""juicebox""): if hic_type == ""juicebox"": is_vc = False filetypes = [""KR"", ""INTERSCALE""] for filetype in filetypes: hic_file = os.path.join( hic_dir, chromosome, chromosome + f"".{filetype}observed.gz"" ) hic_norm = os.path.join( hic_dir, chromosome, chromosome + f"".{filetype}norm.gz"" ) if hic_exists(hic_file): print(""Using: "" + hic_file) return hic_file, hic_norm, False if allow_vc: hic_file = os.path.join(hic_dir, chromosome, chromosome + "".VCobserved.gz"") hic_norm = os.path.join(hic_dir, chromosome, chromosome + "".VCnorm.gz"") if hic_exists(hic_file): print( f""Could not find KR normalized hic file. Using VC normalized hic file: {hic_file}"" ) return hic_file, hic_norm, True raise RuntimeError( f""Could not find {', '.join(filetypes)} or VC normalized hic files"" ) elif hic_type == ""bedpe"": hic_file = os.path.join(hic_dir, chromosome, chromosome + "".bedpe.gz"") return hic_file, None, None elif hic_type == ""avg"": hic_file = os.path.join(hic_dir, chromosome, chromosome + "".bed.gz"") return hic_file, None, None def hic_exists(file): if not os.path.exists(file): return False elif file.endswith(""gz""): # gzip file still have some size. This is a hack return os.path.getsize(file) > 100 else: return os.path.getsize(file) > 0 def load_hic_juicebox( hic_file, hic_norm_file, hic_is_vc, hic_resolution, tss_hic_contribution, window, min_window, gamma, scale=None, apply_diagonal_bin_correction=True, ): print(""Loading HiC Juicebox"") HiC_sparse_mat = hic_to_sparse(hic_file, hic_norm_file, hic_resolution) HiC = process_hic( hic_mat=HiC_sparse_mat, hic_norm_file=hic_norm_file, hic_is_vc=hic_is_vc, resolution=hic_resolution, tss_hic_contribution=tss_hic_contribution, window=window, min_window=min_window, gamma=gamma, apply_diagonal_bin_correction=apply_diagonal_bin_correction, scale=scale, ) return HiC def load_hic_bedpe(hic_file): print(""Loading HiC bedpe"") return pd.read_csv( hic_file, sep=""\t"", names=[""chr1"", ""x1"", ""x2"", ""chr2"", ""y1"", ""y2"", ""name"", ""hic_contact""], ) def load_hic_avg(hic_file, hic_resolution): print(""Loading HiC avg"") cols = {""x1"": np.int64, ""x2"": np.int64, ""hic_contact"": np.float64} HiC = pd.read_csv( hic_file, sep=""\t"", names=cols.keys(), usecols=cols.keys(), dtype=cols ) HiC[""x1""] = np.floor(HiC[""x1""] / hic_resolution).astype(int) HiC[""x2""] = np.floor(HiC[""x2""] / hic_resolution).astype(int) HiC.rename(columns={""x1"": ""bin1"", ""x2"": ""bin2""}, inplace=True) return HiC # def juicebox_to_bedpe(hic, chromosome, resolution): # hic['chr'] = chromosome # hic['x1'] = hic['bin1'] * resolution # hic['x2'] = (hic['bin1'] + 1) * resolution # hic['y1'] = hic['bin2'] * resolution # hic['y2'] = (hic['bin2'] + 1) * resolution # return(hic) def process_hic( hic_mat, hic_norm_file, hic_is_vc, resolution, tss_hic_contribution, window, min_window=0, hic_is_doubly_stochastic=False, apply_diagonal_bin_correction=True, gamma=None, kr_cutoff=0.25, scale=None, ): # Make doubly stochastic. # Juicer produces a matrix with constant row/column sums. But sum is not 1 and is variable across chromosomes t = time.time() if not hic_is_doubly_stochastic and not hic_is_vc: # Any row with Nan in it will sum to nan # So need to calculate sum excluding nan temp = hic_mat temp.data = np.nan_to_num(temp.data, copy=False) sums = temp.sum(axis=0) sums = sums[~np.isnan(sums)] # assert(np.max(sums[sums > 0])/np.min(sums[sums > 0]) < 1.001) mean_sum = np.mean(sums[sums > 0]) if abs(mean_sum - 1) < 0.001: print( ""HiC Matrix has row sums of {}, continuing without making doubly stochastic"".format( mean_sum ) ) else: print( ""HiC Matrix has row sums of {}, making doubly stochastic..."".format( mean_sum ) ) hic_mat = hic_mat.multiply(1 / mean_sum) # Adjust diagonal of matrix based on neighboring bins # First and last rows need to be treated differently if apply_diagonal_bin_correction: last_idx = hic_mat.shape[0] - 1 nonzero_diag = hic_mat.nonzero()[0][ hic_mat.nonzero()[0] == hic_mat.nonzero()[1] ] nonzero_diag = list( set(nonzero_diag) - set(np.array([last_idx])) - set(np.array([0])) ) for ii in nonzero_diag: hic_mat[ii, ii] = ( max(hic_mat[ii, ii - 1], hic_mat[ii, ii + 1]) * tss_hic_contribution / 100 ) if hic_mat[0, 0] != 0: hic_mat[0, 0] = hic_mat[0, 1] * tss_hic_contribution / 100 if hic_mat[last_idx, last_idx] != 0: hic_mat[last_idx, last_idx] = ( hic_mat[last_idx, last_idx - 1] * tss_hic_contribution / 100 ) # Remove lower triangle if not hic_is_vc: hic_mat = ssp.triu(hic_mat) else: hic_mat = process_vc(hic_mat) # Turn into dataframe hic_mat = hic_mat.tocoo(copy=False) hic_df = pd.DataFrame( {""bin1"": hic_mat.row, ""bin2"": hic_mat.col, ""hic_contact"": hic_mat.data} ) # Prune to window hic_df = hic_df.loc[ np.logical_and( abs(hic_df[""bin1""] - hic_df[""bin2""]) <= window / resolution, abs(hic_df[""bin1""] - hic_df[""bin2""]) >= min_window / resolution, ) ] print( ""HiC has {} rows after windowing between {} and {}"".format( hic_df.shape[0], min_window, window ) ) print(""process.hic: Elapsed time: {}"".format(time.time() - t)) return hic_df def hic_to_sparse(filename, norm_file, resolution, hic_is_doubly_stochastic=False): t = time.time() HiC = pd.read_table( filename, names=[""bin1"", ""bin2"", ""hic_contact""], header=None, engine=""c"", memory_map=True, ) # verify our assumptions assert np.all(HiC.bin1 <= HiC.bin2) # Need load norms here to know the dimensions of the hic matrix norms = pd.read_csv(norm_file, header=None) hic_size = norms.shape[0] # convert to sparse matrix in CSR (compressed sparse row) format, chopping # down to HiC bin size. note that conversion to scipy sparse matrices # accumulates repeated indices, so this will do the right thing. row = np.floor(HiC.bin1.values / resolution).astype(int) col = np.floor(HiC.bin2.values / resolution).astype(int) dat = HiC.hic_contact.values # JN: Need both triangles in order to compute row/column sums to make double stochastic. # If juicebox is upgraded to return DS matrices, then can remove one triangle # TO DO: Remove one triangle when juicebox is updated. # we want a symmetric matrix. Easiest to do that during creation, but have to be careful of diagonal if not hic_is_doubly_stochastic: mask = row != col # off-diagonal row2 = col[mask] # note the row/col swap col2 = row[mask] dat2 = dat[mask] # concat and create row = np.hstack((row, row2)) col = np.hstack((col, col2)) dat = np.hstack((dat, dat2)) print(""hic.to.sparse: Elapsed time: {}"".format(time.time() - t)) return ssp.csr_matrix((dat, (row, col)), (hic_size, hic_size)) def get_powerlaw_at_distance(distances, gamma, scale, min_distance=5000): assert gamma > 0 assert scale > 0 # The powerlaw is computed for distances > 5kb. We don't know what the contact freq looks like at < 5kb. # So just assume that everything at < 5kb is equal to 5kb. # TO DO: get more accurate powerlaw at < 5kb distances = np.clip(distances, min_distance, np.Inf) log_dists = np.log(distances + 1) powerlaw_contact = np.exp(scale + -1 * gamma * log_dists) return powerlaw_contact def process_vc(hic): # For a vc normalized matrix, need to make rows sum to 1. # Assume rows correspond to genes and cols to enhancers row_sums = hic.sum(axis=0) row_sums[row_sums == 0] = 1 norm_mat = ssp.dia_matrix( (1.0 / row_sums, [0]), (row_sums.shape[1], row_sums.shape[1]) ) # left multiply to operate on rows hic = norm_mat * hic return hic ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/make_bedgraph_from_HiC.py",".py","4734","144","import argparse import glob import os.path from hic import HiC import pandas import numpy as np import sys from neighborhoods import read_bed, process_gene_bed def parseargs(): parser = argparse.ArgumentParser( description=""Convert HiC matrices to bedgraphs for a set of genes"" ) parser.add_argument( ""--outdir"", required=True, help=""directory to write HiC bedgraphs"" ) parser.add_argument(""--hic_dir"", required=True, help=""location of HiC data"") # Genes parser.add_argument(""--genes"", required=True, help="".bed file of genes"") parser.add_argument( ""--gene_name_annotations"", default=""symbol"", help=""Comma delimited string of names corresponding to the gene identifiers present in the name field of the gene annotation bed file"", ) parser.add_argument( ""--primary_gene_identifier"", default=""symbol"", help=""Primary identifier used to identify genes. Must be present in gene_name_annotations"", ) # HiC Params parser.add_argument( ""--resolution"", type=int, default=5000, help=""HiC resolution to use"" ) parser.add_argument( ""--kr_cutoff"", type=float, default=0.1, help=""Measured data from Hi-C matrix for rows/columns with kr normalization vector below this value are not used. Instead they are interpolated from neighboring bins"", ) parser.add_argument( ""--window"", type=int, default=5000000, help=""maximum distance from each TSS to store (bp)"", ) parser.add_argument( ""--overwrite"", action=""store_true"", help=""force overwriting files"" ) return parser.parse_args() if __name__ == ""__main__"": args = parseargs() def match_files(*subdirs): return glob.glob(os.path.join(args.hic_dir, *subdirs)) # Read genes genes_bed = read_bed(args.genes) genes = process_gene_bed( genes_bed, args.gene_name_annotations, args.primary_gene_identifier, fail_on_nonunique=False, ) # Get raw hic and normalization files resolution = ""{}kb"".format(args.resolution // 1000) hic_files = {} for chr in set(genes[""chr""]): possible_files = match_files( ""{}"".format(chr), ""{}_{}.RAWobserved"".format(chr, resolution) ) possible_norms = match_files( ""{}"".format(chr), ""{}_{}.KRnorm"".format(chr, resolution) ) if possible_files: hic_files[""{}"".format(chr)] = (possible_files[0], possible_norms[0]) # create data accessor hic_data = HiC( hic_files, window=args.window, resolution=args.resolution, kr_cutoff=args.kr_cutoff, ) # create output directory os.makedirs(args.outdir, exist_ok=True) # os.makedirs(os.path.join(args.outdir, ""raw""), exist_ok=True) # Make a bedgraph per gene skipped = [] for idx, gene in genes.iterrows(): if gene.chr not in hic_data.chromosomes(): print(""No HiC data for {} on {}"".format(gene[""name""], gene.chr)) continue filename = os.path.join( args.outdir, ""{}_{}_{}.bg.gz"".format(gene[""name""] or ""UNK"", gene.chr, int(gene.tss)), ) if not args.overwrite: if os.path.exists(filename): skipped.append(gene[""name""]) print( ""Skipping {} on {} with tss {} since it already has hic data and --overwrite flag is not set"".format( gene[""name""], gene.chr, gene.tss ) ) continue hic_row = hic_data.row(gene.chr, gene.tss) # Include all values within args.window of the tss. This will facilitate interpolating NaNs values = [ ( gene.chr, idx * args.resolution, (idx + 1) * args.resolution, hic_row[0, idx], ) for idx in range(hic_row.A.shape[1]) if abs(idx * args.resolution - int(gene.tss)) < args.window ] # interpolate the nan's. Sometimes there may be nan's at the beginning/end of the vector - set to 0 # note this is only interpreting the nan's: missing data due to low kr norm value. This is not interpolating 0's in HiC df2 = pandas.DataFrame.from_records(values).interpolate().fillna(value=0) df2.to_csv(filename, sep=""\t"", compression=""gzip"", header=False, index=False) print(""Completed {} on {}"".format(gene[""name""], gene.chr)) if len(skipped) > 0: print( ""Skipped {} genes because they already have HiC files"".format(len(skipped)) ) ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/metrics.py",".py","8316","242","import glob import os from typing import List import matplotlib.pyplot as plt import numpy as np import pandas as pd import seaborn as sns from scipy import stats def grabStatistics(arr_values): mean = arr_values.mean() median = arr_values.median() std = arr_values.std() return mean, median, std def sort_by_chrom_order(series: pd.Series, chrom_order: List[str]) -> pd.Series: new_series = pd.Series() for chr in chrom_order: if chr in series: new_series[chr] = series[chr] return new_series # Generates QC Prediction Metrics: def GrabQCMetrics(prediction_df, chrom_order, outdir, pdf_writer): EnhancerPerGene = prediction_df.groupby([""TargetGene""]).size() EnhancerPerGene.to_csv(os.path.join(outdir, ""EnhancerPerGene.tsv""), sep=""\t"") pdf_writer.savefig( PlotDistribution( EnhancerPerGene, ""Number of Enhancers Per Gene"", x_label=""Enhancers per Gene"", density_line=False, ) ) # Grab Number of Enhancers Per Gene GeneMean, GeneMedian, GeneStdev = grabStatistics(EnhancerPerGene) # Grab Number of genes per enhancers NumGenesPerEnhancer = ( prediction_df[[""chr"", ""start"", ""end""]].groupby([""chr"", ""start"", ""end""]).size() ) NumGenesPerEnhancer.to_csv(os.path.join(outdir, ""GenesPerEnhancer.tsv""), sep=""\t"") pdf_writer.savefig( PlotDistribution( NumGenesPerEnhancer, ""Number Of Genes Per Enhancer"", x_label=""Genes Per Enhancer"", density_line=False, ) ) ( mean_genes_per_enhancer, median_genes_per_enhancer, stdev_genes_per_enhancer, ) = grabStatistics(NumGenesPerEnhancer) # Grab Number of Enhancer-Gene Pairs Per Chromsome enhancergeneperchrom = prediction_df.groupby([""chr""]).size() enhancergeneperchrom = sort_by_chrom_order(enhancergeneperchrom, chrom_order) enhancergeneperchrom.to_csv( os.path.join(outdir, ""EnhancerGenePairsPerChrom.txt""), sep=""\t"" ) pdf_writer.savefig( plotBarPlot( enhancergeneperchrom, enhancergeneperchrom.index, ""Enhancer-Gene Pairs Per Chromosome"", x_label=""Number of E-G pairs"", y_label=""Chromosome"", ) ) ( mean_enhancergeneperchrom, median_enhancergeneperchrom, stdev_enhancergeneperchrom, ) = grabStatistics(enhancergeneperchrom) # Enhancer-Gene Distancee distance = prediction_df[""distance""] distance = distance[distance > 0] log_dist = distance.apply(np.log10) pdf_writer.savefig( PlotDistribution( log_dist, ""Enhancer-Gene Distance"", x_label=""Log10 Distance"", stat=""density"", ) ) thquantile = np.percentile(distance, 10) testthquantile = np.percentile(distance, 90) # Number of Enhancers numEnhancers = len(prediction_df[[""chr"", ""start"", ""end""]].drop_duplicates()) pred_metrics = {} pred_metrics[""MedianEnhPerGene""] = GeneMedian pred_metrics[""StdEnhPerGene""] = GeneStdev pred_metrics[""MedianGenePerEnh""] = median_genes_per_enhancer pred_metrics[""StdGenePerEnh""] = stdev_genes_per_enhancer pred_metrics[""MeanEnhPerGene""] = GeneMean pred_metrics[""MeanGenePerEnh""] = mean_genes_per_enhancer pred_metrics[""MedianEGDist""] = np.median(distance) pred_metrics[""MeanEGDist""] = np.mean(distance) pred_metrics[""StdEGDist""] = np.std(distance) pred_metrics[""NumEnhancersPerChrom""] = median_enhancergeneperchrom pred_metrics[""MeanEnhancersPerChrom""] = mean_enhancergeneperchrom pred_metrics[""NumEnhancers""] = numEnhancers pred_metrics[""EG10th""] = thquantile pred_metrics[""EG90th""] = testthquantile return pred_metrics def plotBarPlot(x_data, y_data, title, x_label, y_label, color=""blue""): plt.clf() # make sure we're starting with a fresh plot ax = sns.barplot(x=x_data, y=y_data, color=color, orient=""h"") ax.set_title(title) ax.set_xlabel(x_label) ax.set_ylabel(y_label) return ax.get_figure() def NeighborhoodFileQC(pred_metrics, neighborhood_dir, feature): x = glob.glob( os.path.join( neighborhood_dir, ""Enhancers.{}.*CountReads.bedgraph"".format(feature) ) ) y = glob.glob( os.path.join( neighborhood_dir, ""Genes.TSS1kb.{}.*CountReads.bedgraph"".format(feature) ) ) z = glob.glob( os.path.join(neighborhood_dir, ""Genes.{}.*CountReads.bedgraph"".format(feature)) ) data = pd.read_csv(x[0], sep=""\t"", header=None) data1 = pd.read_csv(y[0], sep=""\t"", header=None) data2 = pd.read_csv(z[0], sep=""\t"", header=None) counts = data.iloc[:, 3].sum() counts2 = data1.iloc[:, 3].sum() counts3 = data2.iloc[:, 3].sum() pred_metrics[""countsEnhancers_{}"".format(feature)] = counts pred_metrics[""countsGeneTSS_{}"".format(feature)] = counts2 pred_metrics[""countsGenes_{}"".format(feature)] = counts3 return pred_metrics # Generates peak file metrics def PeakFileQC(pred_metrics, macs_peaks, pdf_writer): if macs_peaks.endswith("".gz""): peaks = pd.read_csv(macs_peaks, compression=""gzip"", sep=""\t"", header=None) else: peaks = pd.read_csv(macs_peaks, sep=""\t"", header=None) # Calculate metrics for candidate regions candidateRegions = pd.read_csv(macs_peaks, sep=""\t"", header=None) candidateRegions[""dist""] = candidateRegions[2] - candidateRegions[1] candreg = candidateRegions[""dist""] pdf_writer.savefig( PlotDistribution(candreg, ""WidthOfCandidateRegions"", x_label=""Width"") ) # Calculate width of peaks peaks[""dist""] = peaks[2] - peaks[1] pred_metrics[""NumPeaks""] = len(peaks[""dist""]) pred_metrics[""MedWidth""] = peaks[""dist""].median() pred_metrics[""MeanWidth""] = peaks[""dist""].mean() pred_metrics[""StdWidth""] = peaks[""dist""].std() pred_metrics[""NumCandidate""] = len(candidateRegions[""dist""]) pred_metrics[""MedWidthCandidate""] = candidateRegions[""dist""].median() pred_metrics[""MeanWidthCandidate""] = candidateRegions[""dist""].mean() pred_metrics[""StdWidthCandidate""] = candidateRegions[""dist""].std() return pred_metrics # Plots and saves a distribution as *.png def PlotDistribution( pd_series: pd.Series, title, x_label, stat=""count"", density_line=True ): plt.clf() # make sure we're starting with a fresh plot ax = sns.histplot( pd_series, kde=density_line, bins=50, kde_kws=dict(cut=3), stat=stat ) ax.set_title(title) ax.set_xlabel(x_label) ax.set_ylabel(stat.capitalize()) mean, median, _ = grabStatistics(pd_series) mean = round(mean, 3) # 3 decimal places median = round(median, 3) # 3 decimal places plt.axvline(x=mean, color=""red"", linestyle=""-"", label=f""Mean={mean}"") plt.axvline(x=median, color=""green"", linestyle=""-"", label=f""Median={median}"") plt.legend() return ax.get_figure() def HiCQC(df, gamma, scale, pdf_writer): # filter for e-g distances of >10kb and <1Mb df = df.loc[(df[""distance""] > 10000) & (df[""distance""] < 1000000)] max_samples = 10000 df = df.sample(min(max_samples, len(df))) if len(df): pdf_writer.savefig( PlotPowerLawRelationship( df, ""distance"", ""hic_contact"", ""E-G Pair HiC Powerlaw Fit"", gamma, scale ) ) def PlotPowerLawRelationship(df, x_axis_col, y_axis_col, title, gamma, scale): plt.clf() # make sure we're starting with a fresh plot # filter out zeros df = df[df[x_axis_col] > 0] df = df[df[y_axis_col] > 0] log_x_axis_label = f""natural log ({x_axis_col})"" log_y_axis_label = f""natural log ({y_axis_col})"" log_x_vals = np.log(df[x_axis_col]) log_y_vals = np.log(df[y_axis_col]) values = np.vstack([log_x_vals, log_y_vals]) kernel = stats.gaussian_kde(values)(values) ax = sns.scatterplot(x=log_x_vals, y=log_y_vals, c=kernel, cmap=""viridis"") fitted_y_vals = scale + -1 * gamma * log_x_vals sns.lineplot( x=log_x_vals, y=fitted_y_vals, color=""red"", label=""Fitted Powerlaw Fit"" ) ax.set(title=title) ax.set_xlabel(log_x_axis_label) ax.set_ylabel(log_y_axis_label) return ax.get_figure() ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/grabMetrics.py",".py","2552","76","#! bin/python3 import argparse import csv import glob import os.path import pandas as pd from matplotlib.backends.backend_pdf import PdfPages from metrics import GrabQCMetrics, HiCQC, NeighborhoodFileQC, PeakFileQC def parse_args(): parser = argparse.ArgumentParser() parser.add_argument( ""--macs_peaks"", required=True, help=""narrowPeak file output by macs2. (eg. /users/kmualim/K562/macs2_peaks.narrowPeak)"", ) parser.add_argument( ""--preds_file"", required=True, help=""Prediction file output by ABC"" ) parser.add_argument( ""--neighborhood_outdir"", required=True, help=""Neighborhood Directory"" ) parser.add_argument(""--chrom_sizes"", required=True, help=""Chromosome sizes file"") parser.add_argument(""--outdir"", required=True, help=""Metrics Directory"") parser.add_argument(""--output_qc_summary"", required=True) parser.add_argument(""--output_qc_plots"", required=True) parser.add_argument( ""--hic_gamma"", type=float, help=""Powerlaw exponent (gamma) to scale to. Must be positive"", ) parser.add_argument( ""--hic_scale"", type=float, help=""scale of hic data. Must be positive"", ) args = parser.parse_args() return args def generateQCMetrics(args): chrom_order = pd.read_csv(args.chrom_sizes, sep=""\t"", header=None)[0].tolist() # read prediction file prediction_df = pd.read_csv(args.preds_file, sep=""\t"") with PdfPages(args.output_qc_plots) as pdf_writer: pred_metrics = GrabQCMetrics( prediction_df, chrom_order, args.outdir, pdf_writer ) pred_metrics = PeakFileQC(pred_metrics, args.macs_peaks, pdf_writer) if ""hic_contact"" in prediction_df.columns: HiCQC(prediction_df, args.hic_gamma, args.hic_scale, pdf_writer) # Appends Percentage Counts in Promoters into PeakFileQCSummary.txt potential_features = [""DHS"", ""H3K27ac"", ""ATAC""] for feature in potential_features: pattern = os.path.join( args.neighborhood_outdir, f""Enhancers.{feature}.*CountReads.bedgraph"" ) if glob.glob(pattern): pred_metrics = NeighborhoodFileQC( pred_metrics, args.neighborhood_outdir, feature ) with open(args.output_qc_summary, ""w"") as f: writer = csv.writer(f, delimiter=""\t"") for key, val in pred_metrics.items(): writer.writerow((key, val)) if __name__ == ""__main__"": args = parse_args() generateQCMetrics(args) ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/tools.py",".py","3197","107","import os import re import sys from subprocess import PIPE, Popen, check_output from typing import Dict, Optional import numpy as np import pandas as pd import pyranges as pr # setting this to raise makes sure that any dangerous assignments to pandas # dataframe slices/subsets error rather than warn pd.set_option(""mode.chained_assignment"", ""raise"") def run_command(command): print(f""Running command: {command}"") return check_output(command, shell=True) def run_piped_commands(piped_commands): print(f""Running piped cmds: {piped_commands}"") # Initialize the first subprocess current_process = Popen(piped_commands[0], stdout=PIPE, shell=True) # Iterate through the remaining commands and pipe them together for cmd in piped_commands[1:]: current_process = Popen( cmd, stdin=current_process.stdout, stdout=PIPE, shell=True ) # Get the final output final_output, _ = current_process.communicate() return final_output def write_connections_bedpe_format(pred, outfile, score_column): # Output a 2d annotation file with EP connections in bedpe format for loading into IGV pred = pred.drop_duplicates() towrite = pd.DataFrame() towrite[""chr1""] = pred[""chr""] towrite[""x1""] = pred[""start""] towrite[""x2""] = pred[""end""] towrite[""chr2""] = pred[""chr""] towrite[""y1""] = pred[""TargetGeneTSS""] towrite[""y2""] = pred[""TargetGeneTSS""] towrite[""name""] = ( pred[""TargetGene""] + ""|"" + pred[""chr""] + "":"" + pred[""start""].astype(str) + ""-"" + pred[""end""].astype(str) ) towrite[""score""] = pred[score_column] towrite[""strand1""] = ""."" towrite[""strand2""] = ""."" towrite.to_csv(outfile, header=False, index=False, sep=""\t"") def determine_expressed_genes(genes, expression_cutoff, activity_quantile_cutoff): # Evaluate whether a gene should be considered 'expressed' so that it runs through the model # A gene is runnable if: # It is expressed OR (there is no expression AND its promoter has high activity) genes[""isExpressed""] = np.logical_or( genes.Expression >= expression_cutoff, np.logical_and( np.isnan(genes.Expression), genes.PromoterActivityQuantile >= activity_quantile_cutoff, ), ) return genes def write_params(args, file): with open(file, ""w"") as outfile: for arg in vars(args): outfile.write(arg + "" "" + str(getattr(args, arg)) + ""\n"") def df_to_pyranges( df, start_col=""start"", end_col=""end"", chr_col=""chr"", start_slop=0, end_slop=0, chrom_sizes_map: Optional[Dict[str, int]] = None, ): df[""Chromosome""] = df[chr_col] df[""Start""] = df[start_col] - start_slop df[""End""] = df[end_col] + end_slop if start_slop or end_slop: assert chrom_sizes_map, ""Must pass in chrom_sizes_map if using slop"" df[""chr_sizes""] = df[chr_col].apply(lambda x: chrom_sizes_map[x]) df[""Start""] = df[""Start""].apply(lambda x: max(x, 0)) df[""End""] = df[[""End"", ""chr_sizes""]].min(axis=1) df.drop(""chr_sizes"", axis=1, inplace=True) return pr.PyRanges(df) ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/predict.py",".py","10543","313","import argparse import os import os.path import time # isort:skip_file from predictor import make_predictions # hicstraw must be imported before pandas import pandas as pd from getVariantOverlap import test_variant_overlap from tools import determine_expressed_genes, write_params def get_model_argument_parser(): class formatter( argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter ): pass parser = argparse.ArgumentParser( description=""Predict enhancer relative effects."", formatter_class=formatter ) readable = argparse.FileType(""r"") # Basic parameters parser.add_argument( ""--enhancers"", required=True, help=""Candidate enhancer regions. Formatted as the EnhancerList.txt file produced by run.neighborhoods.py"", ) parser.add_argument( ""--genes"", required=True, help=""Genes to make predictions for. Formatted as the GeneList.txt file produced by run.neighborhoods.py"", ) parser.add_argument( ""--score_column"", default=""ABC.Score"", help=""Column name of score to use for thresholding"", ) parser.add_argument( ""--accessibility_feature"", default=None, nargs=""?"", help=""If both ATAC and DHS are provided, this flag must be set to either 'DHS' or 'ATAC' signifying which datatype to use in computing activity"", ) parser.add_argument(""--outdir"", required=True, help=""output directory"") parser.add_argument(""--cellType"", help=""Name of cell type"") parser.add_argument(""--chrom_sizes"", required=True, help=""Chromosome sizes file"") # hic parser.add_argument( ""--hic_file"", default=None, help=""HiC file: (file, web link, or directory)"" ) parser.add_argument(""--hic_resolution"", type=int, help=""HiC resolution"") parser.add_argument( ""--hic_pseudocount_distance"", type=int, required=True, help=""A pseudocount is added equal to the powerlaw fit at this distance"", ) parser.add_argument( ""--hic_type"", default=""hic"", choices=[""hic"", ""juicebox"", ""bedpe"", ""avg""], help=""format of hic files"", ) parser.add_argument( ""--hic_is_doubly_stochastic"", action=""store_true"", help=""If hic matrix is already doubly stochastic, can skip this step"", ) # Power law values parser.add_argument( ""--scale_hic_using_powerlaw"", action=""store_true"", help=""Quantile normalize Hi-C values using powerlaw relationship. This parameter will rescale Hi-C contacts from the input Hi-C data (specified by --hic_gamma and --hic_scale) to match the power-law relationship of a reference cell type (specified by --hic_gamma_reference)"", ) parser.add_argument( ""--hic_gamma"", type=float, help=""Powerlaw exponent (gamma) to scale to. Must be positive"", ) parser.add_argument( ""--hic_scale"", type=float, help=""scale of hic data. Must be positive"", ) parser.add_argument( ""--hic_gamma_reference"", type=float, default=0.87, help=""Powerlaw exponent (gamma) to scale to. Must be positive"", ) # Genes to run through model parser.add_argument( ""--expression_cutoff"", type=float, default=1, help=""Make predictions for genes with expression higher than this value. Use of this parameter is not recommended."", ) parser.add_argument( ""--promoter_activity_quantile_cutoff"", type=float, default=0.30, help=""Quantile cutoff on promoter activity. Used to consider a gene 'expressed' in the absence of expression data"", ) # Output formatting parser.add_argument( ""--make_all_putative"", action=""store_true"", help=""Make big file with concatenation of all genes file"", ) parser.add_argument( ""--use_hdf5"", action=""store_true"", help=""Write AllPutative file in hdf5 format instead of tab-delimited"", ) # Parameters used in development of ABC model that should not be changed for most use cases parser.add_argument( ""--window"", type=int, default=5000000, help=""Consider all candidate elements within this distance of the gene's TSS when computing ABC scores. This was a parameter optimized during development of ABC and should not typically be changed."", ) parser.add_argument( ""--tss_hic_contribution"", type=float, default=100, help=""Diagonal bin of Hi-C matrix is set to this percentage of the maximum of its neighboring bins. Default value (100%) means that the diagonal bin of the Hi-C matrix will be set exactly to the maximum of its two neighboring bins. This is a parameter used in development of the ABC model that should not typically be changed, unless experimenting with using different types of input 3D contact data that require different handling of the diagonal bin."", ) # Other parser.add_argument( ""--tss_slop"", type=int, default=500, help=""Distance from tss to search for self-promoters"", ) parser.add_argument( ""--chromosomes"", default=""all"", help=""chromosomes to make predictions for. Defaults to intersection of all chromosomes in --genes and --enhancers"", ) parser.add_argument( ""--include_chrY"", ""-y"", action=""store_true"", help=""Make predictions on Y chromosome"", ) return parser def get_predict_argument_parser(): parser = get_model_argument_parser() return parser def main(): parser = get_predict_argument_parser() args = parser.parse_args() validate_args(args) if not os.path.exists(args.outdir): os.makedirs(args.outdir) write_params(args, os.path.join(args.outdir, ""parameters.predict.txt"")) print(""reading genes"") genes = pd.read_csv(args.genes, sep=""\t"") genes = determine_expressed_genes( genes, args.expression_cutoff, args.promoter_activity_quantile_cutoff ) print(""reading enhancers"") enhancers_full = pd.read_csv(args.enhancers, sep=""\t"") enhancers_column_names = [""chr"", ""start"", ""end"", ""name"", ""class"", ""activity_base""] if args.accessibility_feature not in {""ATAC"", ""DHS""}: raise ValueError(""The feature has to be either ATAC or DHS!"") normalized_activity_col = f""normalized_{args.accessibility_feature.lower()}"" normalized_h3k27ac = ""normalized_h3k27ac"" genes_columns_to_subset = [ ""chr"", ""symbol"", ""tss"", ""Expression"", ""PromoterActivityQuantile"", ""isExpressed"", ""Ensembl_ID"", f""{args.accessibility_feature}.RPKM.quantile.TSS1Kb"", ] new_genes_column_names = [ ""chr"", ""TargetGene"", ""TargetGeneTSS"", ""TargetGeneExpression"", ""TargetGenePromoterActivityQuantile"", ""TargetGeneIsExpressed"", ""TargetGeneEnsembl_ID"", f""{normalized_activity_col}_prom"", ] if ""H3K27ac.RPKM.quantile.TSS1Kb"" in genes.columns: genes_columns_to_subset.append(""H3K27ac.RPKM.quantile.TSS1Kb"") new_genes_column_names.append(f""{normalized_h3k27ac}_prom"") genes = genes.loc[:, genes_columns_to_subset] genes.columns = new_genes_column_names enhancers = enhancers_full.loc[:, enhancers_column_names] enhancers[""activity_base_enh""] = enhancers_full[""activity_base""] enhancers[""activity_base_squared_enh""] = enhancers[""activity_base_enh""] ** 2 enhancers[f""{normalized_activity_col}_enh""] = enhancers_full[ f""{normalized_activity_col}"" ] if ""normalized_h3K27ac"" in enhancers_full.columns: enhancers[f""{normalized_h3k27ac}_enh""] = enhancers_full[""normalized_h3K27ac""] # Initialize Prediction files all_pred_file_expressed = os.path.join( args.outdir, ""EnhancerPredictionsAllPutative.tsv.gz"" ) all_pred_file_nonexpressed = os.path.join( args.outdir, ""EnhancerPredictionsAllPutativeNonExpressedGenes.tsv.gz"" ) all_putative_list = [] # Make predictions if args.chromosomes == ""all"": chromosomes = set(genes[""chr""]).intersection(set(enhancers[""chr""])) if not args.include_chrY: chromosomes.discard(""chrY"") chromosomes = sorted(chromosomes) else: chromosomes = args.chromosomes.split("","") chrom_sizes_map = pd.read_csv( args.chrom_sizes, sep=""\t"", header=None, index_col=0 ).to_dict()[1] for chromosome in chromosomes: print(""Making predictions for chromosome: {}"".format(chromosome)) t = time.time() this_enh = enhancers.loc[enhancers[""chr""] == chromosome, :].copy() this_genes = genes.loc[genes[""chr""] == chromosome, :].copy() this_chr = make_predictions( chromosome, this_enh, this_genes, args, args.hic_gamma, args.hic_scale, chrom_sizes_map, ) all_putative_list.append(this_chr) print( ""Completed chromosome: {}. Elapsed time: {} \n"".format( chromosome, time.time() - t ) ) # Subset predictions print(""Writing output files..."") all_putative = pd.concat(all_putative_list) all_putative[""CellType""] = args.cellType if args.hic_file: all_putative[""hic_contact_squared""] = all_putative[""hic_contact""] ** 2 all_putative.loc[all_putative.TargetGeneIsExpressed, :].to_csv( all_pred_file_expressed, sep=""\t"", index=False, header=True, compression=""gzip"", float_format=""%.6f"", na_rep=""NaN"", ) all_putative.loc[~all_putative.TargetGeneIsExpressed, :].to_csv( all_pred_file_nonexpressed, sep=""\t"", index=False, header=True, compression=""gzip"", float_format=""%.6f"", na_rep=""NaN"", ) test_variant_overlap(args, all_putative) print(""Done."") def validate_args(args): if args.hic_file and (args.hic_type == ""juicebox"" or args.hic_type == ""hic""): assert ( args.hic_resolution is not None ), ""HiC resolution must be provided if hic_type is hic or juicebox"" if not args.hic_file: print( ""WARNING: Hi-C not provided. Model will only compute ABC score using powerlaw!"" ) if __name__ == ""__main__"": main() ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/peaks.py",".py","6097","178","import os import os.path import pandas as pd from neighborhoods import run_count_reads from tools import run_piped_commands def make_candidate_regions_from_summits( macs_peaks, accessibility_files, genome_sizes, genome_sizes_bed, regions_includelist, regions_blocklist, n_enhancers, peak_extend, outdir, ): ## Generate enhancer regions from MACS summits: 1. Count reads in DHS peaks 2. Take top N regions, get summits, extend summits, merge outfile = os.path.join( outdir, os.path.basename(macs_peaks) + "".candidateRegions.bed"" ) includelist_command = get_includelist_command(regions_includelist, genome_sizes_bed) blocklist_command = get_blocklist_command(regions_blocklist) # 1. Count DHS/ATAC reads in candidate regions for all accessibility files provided, and return the filename of the average # reads reads_out = get_read_counts( accessibility_files, outdir, macs_peaks, genome_sizes, genome_sizes_bed ) # 2. Take top N regions, get summits, extend summits, merge, remove blocklist, add includelist, sort and merge # use -sorted in intersect command? Not worth it, both files are small piped_cmds = [ f""bedtools sort -i {reads_out} -faidx {genome_sizes}"", ""bedtools merge -i stdin -c 4 -o max"", ""sort -nr -k 4"", f""head -n {n_enhancers}"", f""bedtools intersect -b stdin -a {macs_peaks} -wa"", 'awk \'{{print $1 ""\\t"" $2 + $10 ""\\t"" $2 + $10}}\'', f""bedtools slop -i stdin -b {peak_extend} -g {genome_sizes}"", f""bedtools sort -i stdin -faidx {genome_sizes}"", ""bedtools merge -i stdin"", blocklist_command, ""cut -f 1-3"", includelist_command, f""bedtools sort -i stdin -faidx {genome_sizes}"", f""bedtools merge -i stdin > {outfile}"", ] run_piped_commands(piped_cmds) def make_candidate_regions_from_peaks( macs_peaks, accessibility_files, genome_sizes, genome_sizes_bed, regions_includelist, regions_blocklist, n_enhancers, peak_extend, minPeakWidth, outdir, ): ## Generate enhancer regions from MACS narrowPeak - do not use summits outfile = os.path.join( outdir, os.path.basename(macs_peaks) + "".candidateRegions.bed"" ) includelist_command = get_includelist_command(regions_includelist, genome_sizes_bed) blocklist_command = get_blocklist_command(regions_blocklist) # 1. Count DHS/ATAC reads in candidate regions reads_out = get_read_counts( accessibility_files, outdir, macs_peaks, genome_sizes, genome_sizes_bed ) # 2. Take top N regions, extend peaks (min size 500), merge, remove blocklist, add includelist, sort and merge # use -sorted in intersect command? Not worth it, both files are small piped_cmds = [ f""bedtools sort -i {reads_out} -faidx {genome_sizes}"", f""bedtools merge -i stdin -c 4 -o max"", ""sort -nr -k 4"", f""head -n {n_enhancers}"", f""bedtools intersect -b stdin -a {macs_peaks} -wa"", f""bedtools slop -i stdin -b {peak_extend} -g {genome_sizes}"", f'awk \'{{ l=$3-$2; if (l < {minPeakWidth}) {{ $2 = $2 - int(({minPeakWidth}-l)/2); $3 = $3 + int(({minPeakWidth}-l)/2) }} print $1 ""\\t"" $2 ""\\t"" $3}}\'', f""bedtools sort -i stdin -faidx {genome_sizes}"", ""bedtools merge -i stdin"", blocklist_command, ""cut -f 1-3"", includelist_command, f""bedtools sort -i stdin -faidx {genome_sizes} | bedtools merge -i stdin > {outfile}"", ] run_piped_commands(piped_cmds) def get_includelist_command(regions_includelist, genome_sizes_bed): if regions_includelist: return f""(bedtools intersect -a {regions_includelist} -b {genome_sizes_bed} -wa | cut -f 1-3 && cat)"" else: return """" def get_blocklist_command(regions_blocklist): if regions_blocklist: return f""bedtools intersect -v -wa -a stdin -b {regions_blocklist}"" else: return """" def get_read_counts( accessibility_files, outdir, macs_peaks, genome_sizes, genome_sizes_bed ): raw_counts_out = [] # initialize list for output file names for access_in in accessibility_files: # loop through input accessibilty files raw_counts_out.append( os.path.join( outdir, os.path.basename(macs_peaks) + ""."" + os.path.basename(access_in) + "".Counts.bed"", ) ) # 1. Count DHS/ATAC reads in candidate regions for all accessibility files provided, and return the filename of the average # reads reads_out = count_reads_over_peaks( accessibility_files, raw_counts_out, macs_peaks, genome_sizes, genome_sizes_bed, outdir, use_fast_count=True, ) return reads_out # count reads over however many DHS files and return average def count_reads_over_peaks( accessibility_files, raw_counts_out, macs_peaks, genome_sizes, genome_sizes_bed, outdir, use_fast_count=True, ): for access_in, counts_out in zip(accessibility_files, raw_counts_out): run_count_reads( access_in, counts_out, macs_peaks, genome_sizes, genome_sizes_bed, use_fast_count, ) nFiles = len(accessibility_files) if nFiles > 1: avg_out = os.path.join( outdir, os.path.basename(macs_peaks) + "".averageAccessibility.Counts.bed"" ) col_names = [""chrom"", ""start"", ""end"", ""count""] df1 = pd.read_csv(raw_counts_out[0], sep=""\t"", names=col_names) for i in range(1, nFiles): dfx = pd.read_csv( raw_counts_out[i], sep=""\t"", names=col_names, usecols=[""count""] ) df1[""count""] = df1[""count""].add(dfx[""count""]) df1[""count""] = df1[""count""] / nFiles df1.to_csv(avg_out, header=None, index=None, sep=""\t"") return avg_out else: return raw_counts_out[0] ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/neighborhoods.py",".py","28737","879","import linecache import os import os.path import time import traceback from subprocess import PIPE, Popen, check_call, check_output import numpy as np import pandas as pd import pyranges as pr from pyBigWig import open as open_bigwig import pysam from scipy import interpolate from tools import df_to_pyranges, run_command, run_piped_commands pd.options.display.max_colwidth = ( 10000 # seems to be necessary for pandas to read long file names... strange ) BED3_COLS = [""chr"", ""start"", ""end""] BED6_COLS = BED3_COLS + [""name"", ""score"", ""strand""] def read_gene_bed_file(bed_file): # BED6 format with extra columns for ensemble info columns = BED6_COLS + [""Ensembl_ID"", ""gene_type""] skip = 1 if (""track"" in open(bed_file, ""r"").readline()) else 0 result = pd.read_table( bed_file, names=columns, header=None, skiprows=skip, comment=""#"" ) ensembl_id_col = result.loc[:, ""Ensembl_ID""] if ensembl_id_col.isna().all() or not ensembl_id_col.str.contains(""EN"").all(): raise Exception(""Gene file doesn't follow the correct format with Ensembl info"") return result def load_genes( file, ue_file, chrom_sizes, outdir, expression_table_list, gene_id_names, primary_id, cellType, class_gene_file, ): # Add bed = read_gene_bed_file(file) genes = process_gene_bed(bed, gene_id_names, primary_id, chrom_sizes) genes[[""chr"", ""start"", ""end"", ""name"", ""score"", ""strand""]].to_csv( os.path.join(outdir, ""GeneList.bed""), sep=""\t"", index=False, header=False ) if len(expression_table_list) > 0: # Add expression information names_list = [] print(""Using gene expression from files: {} \n"".format(expression_table_list)) for expression_table in expression_table_list: try: name = os.path.basename(expression_table) expr = pd.read_table( expression_table, names=[primary_id, name + "".Expression""] ) expr[name + "".Expression""] = expr[name + "".Expression""].astype(float) expr = expr.groupby(primary_id).max() genes = genes.merge( expr, how=""left"", right_index=True, left_on=""symbol"" ) names_list.append(name + "".Expression"") except Exception as e: print(e) traceback.print_exc() print(""Failed on {}"".format(expression_table)) genes[""Expression""] = genes[names_list].mean(axis=1) genes[""Expression.quantile""] = genes[""Expression""].rank( method=""average"", na_option=""top"", ascending=True, pct=True ) else: genes[""Expression""] = np.NaN # Ubiquitously expressed annotation if ue_file is not None: ubiq = pd.read_csv(ue_file, sep=""\t"") genes[""is_ue""] = genes[""name""].isin(ubiq.iloc[:, 0].values.tolist()) # cell type genes[""cellType""] = cellType # genes for class assignment if class_gene_file is None: genes_for_class_assignment = genes else: genes_for_class_assignment = read_bed(class_gene_file) genes_for_class_assignment = process_gene_bed( genes_for_class_assignment, gene_id_names, primary_id, chrom_sizes, fail_on_nonunique=False, ) return genes, genes_for_class_assignment def annotate_genes_with_features( genes, genome_sizes, genome_sizes_bed, chrom_sizes_map, features={}, outdir=""."", use_fast_count=True, default_accessibility_feature="""", ): # Setup files for counting bounds_bed = os.path.join(outdir, ""GeneList.bed"") tss1kb = make_tss_region_file(genes, outdir, genome_sizes, chrom_sizes_map) tss1kb_file = os.path.join(outdir, ""GeneList.TSS1kb.bed"") # Count features over genes and promoters genes = count_features_for_bed( genes, bounds_bed, genome_sizes, genome_sizes_bed, features, outdir, ""Genes"", use_fast_count=use_fast_count, ) tsscounts = count_features_for_bed( tss1kb, tss1kb_file, genome_sizes, genome_sizes_bed, features, outdir, ""Genes.TSS1kb"", use_fast_count=use_fast_count, ) tsscounts = tsscounts.drop([""chr"", ""start"", ""end"", ""score"", ""strand""], axis=1) merged = genes.merge(tsscounts, on=""name"", suffixes=["""", "".TSS1Kb""]) access_col = default_accessibility_feature + "".RPKM.quantile.TSS1Kb"" if ""H3K27ac.RPKM.quantile.TSS1Kb"" in merged.columns: merged[""PromoterActivityQuantile""] = ( (0.0001 + merged[""H3K27ac.RPKM.quantile.TSS1Kb""]) * (0.0001 + merged[access_col]) ).rank(method=""average"", na_option=""top"", ascending=True, pct=True) else: merged[""PromoterActivityQuantile""] = ((0.0001 + merged[access_col])).rank( method=""average"", na_option=""top"", ascending=True, pct=True ) merged.to_csv( os.path.join(outdir, ""GeneList.txt""), sep=""\t"", index=False, header=True, float_format=""%.6f"", ) return merged def make_tss_region_file(genes, outdir, sizes, chrom_sizes_map, tss_slop=500): # Given a gene file, define 1kb regions around the tss of each gene tss1kb = genes.loc[:, [""chr"", ""start"", ""end"", ""name"", ""score"", ""strand""]] tss1kb[""start""] = genes[""tss""] tss1kb[""end""] = genes[""tss""] tss1kb = df_to_pyranges(tss1kb).slack(tss_slop) tss1kb = pr.gf.genome_bounds(tss1kb, chrom_sizes_map).df[ [""Chromosome"", ""Start"", ""End"", ""name"", ""score"", ""strand""] ] tss1kb.columns = [""chr"", ""start"", ""end"", ""name"", ""score"", ""strand""] tss1kb_file = os.path.join(outdir, ""GeneList.TSS1kb.bed"") tss1kb.to_csv(tss1kb_file, header=False, index=False, sep=""\t"") # The TSS1kb file should be sorted sort_command = ""bedtools sort -faidx {sizes} -i {tss1kb_file} > {tss1kb_file}.sorted; mv {tss1kb_file}.sorted {tss1kb_file}"".format( **locals() ) run_command(sort_command) return tss1kb def process_gene_bed( bed, name_cols, main_name, chrom_sizes=None, fail_on_nonunique=True ): try: bed = bed.drop( [ ""thickStart"", ""thickEnd"", ""itemRgb"", ""blockCount"", ""blockSizes"", ""blockStarts"", ], axis=1, ) except Exception as e: pass assert main_name in name_cols names = bed.name.str.split("";"", expand=True) assert len(names.columns) == len(name_cols.split("","")) names.columns = name_cols.split("","") bed = pd.concat([bed, names], axis=1) bed[""name""] = bed[main_name] # bed = bed.sort_values(by=['chr','start']) #JN Keep original sort order bed[""tss""] = get_tss_for_bed(bed) bed.drop_duplicates(inplace=True) # Remove genes that are not defined in chromosomes file if chrom_sizes is not None: sizes = read_bed(chrom_sizes) bed[""chr""] = bed[""chr""].astype( ""str"" ) # JN needed in case chromosomes are all integer bed = bed[bed[""chr""].isin(set(sizes[""chr""].values))] # Enforce that gene names should be unique if fail_on_nonunique: assert len(set(bed[""name""])) == len( bed[""name""] ), ""Gene IDs are not unique! Failing. Please ensure unique identifiers are passed to --genes"" return bed def get_tss_for_bed(bed): assert_bed3(bed) tss = bed[""start""].copy() tss.loc[bed.loc[:, ""strand""] == ""-""] = bed.loc[bed.loc[:, ""strand""] == ""-"", ""end""] return tss def assert_bed3(df): assert type(df).__name__ == ""DataFrame"" assert ""chr"" in df.columns assert ""start"" in df.columns assert ""end"" in df.columns assert ""strand"" in df.columns def load_enhancers( outdir=""."", genome_sizes="""", genome_sizes_bed="""", features={}, genes=None, candidate_peaks="""", skip_rpkm_quantile=False, cellType=None, tss_slop_for_class_assignment=500, use_fast_count=True, default_accessibility_feature="""", qnorm=None, class_override_file=None, chrom_sizes_map=None, ): enhancers = read_bed(candidate_peaks) enhancers[""chr""] = enhancers[""chr""].astype(""str"") enhancers = count_features_for_bed( enhancers, candidate_peaks, genome_sizes, genome_sizes_bed, features, outdir, ""Enhancers"", skip_rpkm_quantile, use_fast_count, ) # cellType if cellType is not None: enhancers[""cellType""] = cellType # Assign categories if genes is not None: print(""Assigning classes to enhancers"") enhancers = assign_enhancer_classes( enhancers, genes, chrom_sizes_map, tss_slop=tss_slop_for_class_assignment ) # TO DO: Should qnorm each bam file separately (before averaging). Currently qnorm being performed on the average enhancers = run_qnorm(enhancers, qnorm) enhancers = compute_activity(enhancers, default_accessibility_feature) enhancers[[""chr"", ""start"", ""end"", ""name""]].to_csv( os.path.join(outdir, ""EnhancerList.bed""), sep=""\t"", index=False, header=False, ) enhancers.to_csv( os.path.join(outdir, ""EnhancerList.txt.tmp""), sep=""\t"", index=False, header=True, float_format=""%.6f"", ) os.rename( os.path.join(outdir, ""EnhancerList.txt.tmp""), os.path.join(outdir, ""EnhancerList.txt""), ) # Kristy's version def assign_enhancer_classes(enhancers, genes, chrom_sizes_map, tss_slop=500): # build pyranges df tss_pyranges = df_to_pyranges( genes, start_col=""tss"", end_col=""tss"", start_slop=tss_slop, end_slop=tss_slop, chrom_sizes_map=chrom_sizes_map, ) gene_pyranges = df_to_pyranges(genes) def get_class_pyranges( enhancers, tss_pyranges=tss_pyranges, gene_pyranges=gene_pyranges ): """""" Takes in PyRanges objects : Enhancers, tss_pyranges, gene_pyranges Returns dataframe with uid (representing enhancer) and symbol of the gene/promoter that is overlapped """""" # genes genic_enh = enhancers.join(gene_pyranges, suffix=""_genic"") genic_enh = ( genic_enh.df[[""symbol"", ""uid""]] .groupby(""uid"", as_index=False) .aggregate(lambda x: "","".join(list(set(x)))) ) # promoters promoter_enh = enhancers.join(tss_pyranges, suffix=""_promoter"") promoter_enh = ( promoter_enh.df[[""symbol"", ""uid""]] .groupby(""uid"", as_index=False) .aggregate(lambda x: "","".join(list(set(x)))) ) return genic_enh, promoter_enh # label everything as intergenic enhancers[""class""] = ""intergenic"" enhancers[""uid""] = range(enhancers.shape[0]) enh = df_to_pyranges(enhancers) genes, promoters = get_class_pyranges(enh) enhancers = enh.df.drop([""Chromosome"", ""Start"", ""End""], axis=1) enhancers.loc[enhancers[""uid""].isin(genes.uid), ""class""] = ""genic"" enhancers.loc[enhancers[""uid""].isin(promoters.uid), ""class""] = ""promoter"" enhancers[""isPromoterElement""] = enhancers[""class""] == ""promoter"" enhancers[""isGenicElement""] = enhancers[""class""] == ""genic"" enhancers[""isIntergenicElement""] = enhancers[""class""] == ""intergenic"" # Output stats print(""Total enhancers: {}"".format(len(enhancers))) print("" Promoters: {}"".format(sum(enhancers[""isPromoterElement""]))) print("" Genic: {}"".format(sum(enhancers[""isGenicElement""]))) print("" Intergenic: {}"".format(sum(enhancers[""isIntergenicElement""]))) # Add promoter/genic symbol enhancers = enhancers.merge( promoters.rename(columns={""symbol"": ""promoterSymbol""}), on=""uid"", how=""left"" ).fillna(value={""promoterSymbol"": """"}) enhancers = enhancers.merge( genes.rename(columns={""symbol"": ""genicSymbol""}), on=""uid"", how=""left"" ).fillna(value={""genicSymbol"": """"}) enhancers.drop([""uid""], axis=1, inplace=True) # just to keep things consistent with original code enhancers[""name""] = enhancers.apply( lambda e: ""{}|{}:{}-{}"".format(e[""class""], e.chr, e.start, e.end), axis=1 ) return enhancers def run_count_reads( target, output, bed_file, genome_sizes, genome_sizes_bed, use_fast_count ): filename = os.path.basename(target) if filename.endswith("".bam""): count_bam( target, bed_file, output, genome_sizes=genome_sizes, use_fast_count=use_fast_count, ) elif ""tagAlign"" in filename: count_tagalign(target, bed_file, output, genome_sizes, genome_sizes_bed) elif isBigWigFile(filename): count_bigwig(target, bed_file, output) else: raise ValueError( ""File {} name format doesn't match bam, tagAlign, or bigWig"".format(target) ) double_sex_chrom_counts(output) def double_sex_chrom_counts(output): # Double the count values for sex chromosomes to make it seem # like they have 2 copies awk_command = r""""""awk 'BEGIN {FS=OFS=""\t""} (substr($1, length($1)) == ""X"" || substr($1, length($1)) == ""Y"") { $4 *= 2 } 1' """""" file_creation_command = f""{output} > {output}.tmp && mv {output}.tmp {output}"" run_command(awk_command + file_creation_command) def count_bam( bamfile, bed_file, output, genome_sizes, use_fast_count=True, verbose=True ): reads = pysam.AlignmentFile(bamfile) read_chrs = set(reads.references) bed_regions = pd.read_table(bed_file, header=None) bed_regions = bed_regions[bed_regions.columns[:3]] bed_regions.columns = ""chr start end"".split() counts = [ (reads.count(row.chr, row.start, row.end) if (row.chr in read_chrs) else 0) for _, row in bed_regions.iterrows() ] bed_regions[""count""] = counts bed_regions.to_csv(output, header=None, index=None, sep=""\t"") def count_tagalign(tagalign, bed_file, output, genome_sizes, genome_sizes_bed): index_file = tagalign + "".tbi"" if not os.path.exists(index_file): cmd = f""tabix -p bed {tagalign}"" run_command(cmd) remove_alt_chr_cmd = f""bedtools intersect -u -a {tagalign} -b {genome_sizes_bed}"" coverage_cmd = ( f""bedtools coverage -counts -sorted -g {genome_sizes} -b - -a {bed_file}"" ) awk_cmd = 'awk \'{{print $1 ""\\t"" $2 ""\\t"" $3 ""\\t"" $NF}}\'' + f"" > {output}"" piped_cmds = [remove_alt_chr_cmd, coverage_cmd, awk_cmd] run_piped_commands(piped_cmds) def count_bigwig(target, bed_file, output): bw = open_bigwig(target) bed = read_bed(bed_file) with open(output, ""wb"") as outfp: for chr, start, end, *rest in bed.itertuples(index=False, name=None): # if isinstance(name, np.float): # name = """" try: if chr not in bw.chroms(): val = 0 else: val = ( bw.stats(chr, int(start), int(end), type=""sum"", exact=True)[0] or 0 ) except RuntimeError: print(""Failed on"", chr, start, end) raise output = (""\t"".join([chr, str(start), str(end), str(val)]) + ""\n"").encode( ""ascii"" ) outfp.write(output) def isBigWigFile(filename): return ( filename.endswith("".bw"") or filename.endswith("".bigWig"") or filename.endswith("".bigwig"") ) def count_features_for_bed( df, bed_file, genome_sizes, genome_sizes_bed, features, directory, filebase, skip_rpkm_quantile=False, use_fast_count=True, ): for feature, feature_bam_list in features.items(): start_time = time.time() if isinstance(feature_bam_list, str): feature_bam_list = [feature_bam_list] for feature_bam in feature_bam_list: df = count_single_feature_for_bed( df, bed_file, genome_sizes, genome_sizes_bed, feature_bam, feature, directory, filebase, skip_rpkm_quantile, use_fast_count, ) df = average_features( df, feature.replace(""feature_"", """"), feature_bam_list, skip_rpkm_quantile ) elapsed_time = time.time() - start_time print(""Feature "" + feature + "" completed in "" + str(elapsed_time)) return df def count_single_feature_for_bed( df, bed_file, genome_sizes, genome_sizes_bed, feature_bam, feature, directory, filebase, skip_rpkm_quantile, use_fast_count, ): orig_df = df.copy() orig_shape = df.shape[0] feature_name = feature + ""."" + os.path.basename(feature_bam) feature_outfile = os.path.join( directory, ""{}.{}.CountReads.bedgraph"".format(filebase, feature_name) ) print(""Generating"", feature_outfile) print(""Counting coverage for {}"".format(filebase + ""."" + feature_name)) run_count_reads( feature_bam, feature_outfile, bed_file, genome_sizes, genome_sizes_bed, use_fast_count, ) domain_counts = read_bed(feature_outfile) score_column = domain_counts.columns[-1] total_counts = count_total(feature_bam) domain_counts = domain_counts[[""chr"", ""start"", ""end"", score_column]] featurecount = feature_name + "".readCount"" domain_counts.rename(columns={score_column: featurecount}, inplace=True) domain_counts[""chr""] = domain_counts[""chr""].astype(""str"") df = df.merge(domain_counts.drop_duplicates()) # df = smart_merge(df, domain_counts.drop_duplicates()) assert df.shape[0] == orig_shape, ""Dimension mismatch"" df[feature_name + "".RPM""] = 1e6 * df[featurecount] / float(total_counts) if not skip_rpkm_quantile: df[featurecount + "".quantile""] = df[featurecount].rank() / float(len(df)) df[feature_name + "".RPM.quantile""] = df[feature_name + "".RPM""].rank() / float( len(df) ) df[feature_name + "".RPKM""] = ( 1e3 * df[feature_name + "".RPM""] / (df.end - df.start).astype(float) ) df[feature_name + "".RPKM.quantile""] = df[feature_name + "".RPKM""].rank() / float( len(df) ) return df[~df.duplicated()] def average_features(df, feature, feature_bam_list, skip_rpkm_quantile): feature_RPM_cols = [ feature + ""."" + os.path.basename(feature_bam) + "".RPM"" for feature_bam in feature_bam_list ] df[feature + "".RPM""] = df[feature_RPM_cols].mean(axis=1) if not skip_rpkm_quantile: feature_RPKM_cols = [ feature + ""."" + os.path.basename(feature_bam) + "".RPKM"" for feature_bam in feature_bam_list ] df[feature + "".RPM.quantile""] = df[feature + "".RPM""].rank() / float(len(df)) df[feature + "".RPKM""] = df[feature_RPKM_cols].mean(axis=1) df[feature + "".RPKM.quantile""] = df[feature + "".RPKM""].rank() / float(len(df)) return df # From /seq/lincRNA/Jesse/bin/scripts/JuicerUtilities.R # bed_extra_colnames = [ ""name"", ""score"", ""strand"", ""thickStart"", ""thickEnd"", ""itemRgb"", ""blockCount"", ""blockSizes"", ""blockStarts"", ] # JN: 9/13/19: Don't assume chromosomes start with 'chr' # chromosomes = ['chr' + str(entry) for entry in list(range(1,23)) + ['M','X','Y']] # should pass this in as an input file to specify chromosome order def read_bed( filename, extra_colnames=bed_extra_colnames, chr=None, sort=False, skip_chr_sorting=True, ): skip = 1 if (""track"" in open(filename, ""r"").readline()) else 0 names = BED3_COLS + extra_colnames result = pd.read_table( filename, names=names, header=None, skiprows=skip, comment=""#"" ) result = result.dropna(axis=1, how=""all"") # drop empty columns assert result.columns[0] == ""chr"" result[""chr""] = pd.Categorical(result[""chr""], ordered=True) if chr is not None: result = result[result.chr == chr] if not skip_chr_sorting: result.sort_values(""chr"", inplace=True) if sort: result.sort_values(BED3_COLS, inplace=True) return result def read_bedgraph(filename): read_bed(filename, extra_colnames=[""score""], skip_chr_sorting=True) def count_bam_mapped(bam_file): # Counts number of reads in a BAM file WITHOUT iterating. Requires that the BAM is indexed # chromosomes = ['chr' + str(x) for x in range(1,23)] + ['chrX'] + ['chrY'] command = ""samtools idxstats "" + bam_file data = check_output(command, shell=True) lines = data.decode(""ascii"").split(""\n"") # vals = list(int(l.split(""\t"")[2]) for l in lines[:-1] if l.split(""\t"")[0] in chromosomes) vals = list(int(l.split(""\t"")[2]) for l in lines[:-1]) if not sum(vals) > 0: raise ValueError(""Error counting BAM file: count <= 0"") return sum(vals) def count_tagalign_total(tagalign): result = int( check_output( ""zcat {} | grep -E 'chr[1-9]|chr1[0-9]|chr2[0-2]|chrX|chrY' | wc -l"".format( tagalign ), shell=True, ) ) assert result > 0 return result def count_bigwig_total(bw_file): bw = open_bigwig(bw_file) result = sum( l * bw.stats(ch, 0, l, ""mean"", exact=True)[0] for ch, l in bw.chroms().items() ) assert ( abs(result) > 0 ) ## BigWig could have negative values, e.g. the negative-strand GroCAP bigwigs return result def count_total(infile): filename = os.path.basename(infile) if ""tagAlign"" in filename: total_counts = count_tagalign_total(infile) elif filename.endswith("".bam""): total_counts = count_bam_mapped(infile) elif isBigWigFile(filename): total_counts = count_bigwig_total(infile) else: raise RuntimeError(""Did not recognize file format of: "" + infile) return total_counts def parse_params_file(args): # Parse parameters file and return params dictionary params = {} params[""default_accessibility_feature""] = determine_accessibility_feature(args) params[""features""] = get_features(args) if args.expression_table: params[""expression_table""] = args.expression_table.split("","") else: params[""expression_table""] = """" return params def get_features(args): features = {} if args.H3K27ac: features[""H3K27ac""] = args.H3K27ac.split("","") if args.ATAC: features[""ATAC""] = args.ATAC.split("","") if args.DHS: features[""DHS""] = args.DHS.split("","") if args.supplementary_features is not None: supp = pd.read_csv(args.supplementary_features, sep=""\t"") for idx, row in supp.iterrows(): features[row[""feature_name""]] = row[""file""].split("","") return features def determine_accessibility_feature(args): if args.default_accessibility_feature is not None: return args.default_accessibility_feature elif (not args.ATAC) and (not args.DHS): raise RuntimeError( ""Both DHS and ATAC have been provided. Must set one file to be the default accessibility feature!"" ) elif args.ATAC: return ""ATAC"" elif args.DHS: return ""DHS"" else: raise RuntimeError(""At least one of ATAC or DHS must be provided!"") def compute_activity(df, access_col): if access_col == ""DHS"": if ""H3K27ac.RPM"" in df.columns: df[""activity_base""] = np.sqrt( df[""normalized_h3K27ac""] * df[""normalized_dhs""] ) df[""activity_base_no_qnorm""] = np.sqrt(df[""H3K27ac.RPM""] * df[""DHS.RPM""]) else: df[""activity_base""] = df[""normalized_dhs""] df[""activity_base_no_qnorm""] = df[""DHS.RPM""] elif access_col == ""ATAC"": if ""H3K27ac.RPM"" in df.columns: df[""activity_base""] = np.sqrt( df[""normalized_h3K27ac""] * df[""normalized_atac""] ) df[""activity_base_no_qnorm""] = np.sqrt(df[""H3K27ac.RPM""] * df[""ATAC.RPM""]) else: df[""activity_base""] = df[""normalized_atac""] df[""activity_base_no_qnorm""] = df[""ATAC.RPM""] else: raise RuntimeError(""At least one of ATAC or DHS must be provided!"") return df def run_qnorm(df, qnorm, qnorm_method=""rank"", separate_promoters=True): # Quantile normalize epigenetic data to a reference # # Option to qnorm promoters and nonpromoters separately if qnorm is None: if ""H3K27ac.RPM"" in df.columns: df[""normalized_h3K27ac""] = df[""H3K27ac.RPM""] if ""DHS.RPM"" in df.columns: df[""normalized_dhs""] = df[""DHS.RPM""] if ""ATAC.RPM"" in df.columns: df[""normalized_atac""] = df[""ATAC.RPM""] else: qnorm = pd.read_csv(qnorm, sep=""\t"") nRegions = df.shape[0] col_dict = { ""DHS.RPM"": ""normalized_dhs"", ""ATAC.RPM"": ""normalized_atac"", ""H3K27ac.RPM"": ""normalized_h3K27ac"", } # & operator doesn't work in newer versions https://pastebin.com/8d2Ra9L1 for col in set(df.columns.intersection(col_dict.keys())): # if there is no ATAC.RPM in the qnorm file, but there is ATAC.RPM in enhancers, then qnorm ATAC to DHS if col == ""ATAC.RPM"" and ""ATAC.RPM"" not in qnorm.columns: qnorm[""ATAC.RPM""] = qnorm[""DHS.RPM""] if not separate_promoters: qnorm = qnorm.loc[qnorm[""enh_class"" == ""any""]] if qnorm_method == ""rank"": interpfunc = interpolate.interp1d( qnorm[""rank""], qnorm[col], kind=""linear"", fill_value=""extrapolate"", ) df[col_dict[col]] = interpfunc( (1 - df[col + "".quantile""]) * nRegions ).clip(0) elif qnorm_method == ""quantile"": interpfunc = interpolate.interp1d( qnorm[""quantile""], qnorm[col], kind=""linear"", fill_value=""extrapolate"", ) df[col_dict[col]] = interpfunc(df[col + "".quantile""]).clip(0) else: for enh_class in [""promoter"", ""nonpromoter""]: this_qnorm = qnorm.loc[qnorm[""enh_class""] == enh_class] # Need to recompute quantiles within each class if enh_class == ""promoter"": this_idx = df.index[ np.logical_or( df[""class""] == ""tss"", df[""class""] == ""promoter"" ) ] else: this_idx = df.index[ np.logical_and( df[""class""] != ""tss"", df[""class""] != ""promoter"" ) ] df.loc[this_idx, col + enh_class + "".quantile""] = df.loc[ this_idx, col ].rank() / len(this_idx) if qnorm_method == ""rank"": interpfunc = interpolate.interp1d( this_qnorm[""rank""], this_qnorm[col], kind=""linear"", fill_value=""extrapolate"", ) df.loc[this_idx, col_dict[col]] = interpfunc( (1 - df.loc[this_idx, col + enh_class + "".quantile""]) * len(this_idx) ).clip(0) elif qnorm_method == ""quantile"": interpfunc = interpolate.interp1d( this_qnorm[""quantile""], this_qnorm[col], kind=""linear"", fill_value=""extrapolate"", ) df.loc[this_idx, col_dict[col]] = interpfunc( df.loc[this_idx, col + enh_class + "".quantile""] ).clip(0) return df ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/compute_powerlaw_fit_from_hic.py",".py","7012","205","import argparse import glob import os import sys import traceback import numpy as np import pandas as pd from hic import get_hic_file, load_hic_juicebox, load_hic_bedpe, load_hic_avg from scipy import stats from typing import Dict # To do: # 1. Use MLE to estimate exponent? # 2. Support bedpe def parseargs(): class formatter( argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter ): pass epilog = """" parser = argparse.ArgumentParser( description=""Helper to compute hic power-law fit parameters"", epilog=epilog, formatter_class=formatter, ) readable = argparse.FileType(""r"") parser.add_argument( ""--hic_dir"", help=""Directory containing observed HiC KR normalized matrices. File naming and structure should be: hicDir/chr*/chr*.{KR,Interscale}observed"", ) parser.add_argument(""--outDir"", help=""Output directory"") parser.add_argument( ""--hic_type"", default=""juicebox"", choices=[""juicebox"", ""bedpe"", ""avg""], help=""format of hic files"", ) parser.add_argument( ""--hic_resolution"", default=5000, type=int, help=""For Juicebox: resolution of hic dataset (in bp). For bedpe: distances will be binned to this resolution for powerlaw fit"", ) parser.add_argument( ""--minWindow"", default=5000, type=int, help=""Minimum distance between bins to include in powerlaw fit (bp). Recommended to be at least >= resolution to avoid using the diagonal of the HiC Matrix"", ) parser.add_argument( ""--maxWindow"", default=1000000, # 1Mbp type=int, help=""Maximum distance between bins to include in powerlaw fit (bp)"", ) parser.add_argument( ""--chr"", default=""all"", help=""Comma delimited list of chromosomes to use for fit. Defualts to chr[1..22],chrX"", ) args = parser.parse_args() return args def main(): args = parseargs() os.makedirs(args.outDir, exist_ok=True) if args.chr == ""all"": chromosomes = [""chr"" + str(x) for x in list(range(1, 23))] + [""chrX""] else: chromosomes = args.chr.split("","") HiC = load_hic_for_powerlaw( chromosomes, args.hic_dir, args.hic_type, args.hic_resolution, args.minWindow, args.maxWindow, ) # Run slope, intercept, hic_mean_var = do_powerlaw_fit(HiC, args.hic_resolution) # print res = pd.DataFrame( { ""resolution"": [args.hic_resolution], ""maxWindow"": [args.maxWindow], ""minWindow"": [args.minWindow], ""hic_gamma"": [slope * -1], # gamma defined as neg slope ""hic_scale"": [intercept], } ) res.to_csv( os.path.join(args.outDir, ""hic.powerlaw.tsv""), sep=""\t"", index=False, header=True, ) hic_mean_var.to_csv( os.path.join(args.outDir, ""hic.mean_var.tsv""), sep=""\t"", index=True, header=True ) def load_hic_for_powerlaw( chromosomes, hicDir, hic_type, hic_resolution, min_window, max_window ): all_data_list = [] for chrom in chromosomes: try: hic_file, hic_norm_file, hic_is_vc = get_hic_file( chrom, hicDir, hic_type=hic_type, allow_vc=False ) if hic_type == ""juicebox"": print(""Working on {}"".format(hic_file)) this_data = load_hic_juicebox( hic_file=hic_file, hic_norm_file=hic_norm_file, hic_is_vc=hic_is_vc, hic_resolution=hic_resolution, tss_hic_contribution=100, window=max_window, min_window=min_window, gamma=np.nan, scale=np.nan, interpolate_nan=False, ) this_data[""dist_for_fit""] = ( abs(this_data[""bin1""] - this_data[""bin2""]) * hic_resolution ) elif hic_type == ""bedpe"": print(""Working on {}"".format(hic_file)) this_data = load_hic_bedpe(hic_file) # Compute distance in bins as with juicebox data. # This is needed to in order to maintain consistency, but is probably slightly less accurate. # Binning also reduces noise level. rawdist = abs( (this_data[""x2""] + this_data[""x1""]) / 2 - (this_data[""y2""] + this_data[""y1""]) / 2 ) this_data[""dist_for_fit""] = (rawdist // hic_resolution) * hic_resolution this_data = this_data.loc[ np.logical_and( this_data[""dist_for_fit""] >= min_window, this_data[""dist_for_fit""] <= max_window, ) ] elif hic_type == ""avg"": print(""Working on {}"".format(hic_file)) this_data = load_hic_avg(hic_file, hic_resolution) this_data[""dist_for_fit""] = ( abs((this_data[""bin1""] - this_data[""bin2""]) / hic_resolution) * hic_resolution ) this_data[""dist_for_fit""] = this_data[""dist_for_fit""].astype(""int"") else: raise Exception(""invalid --hic_type"") all_data_list.append(this_data) except Exception as e: print(e) traceback.print_exc(file=sys.stdout) all_data = pd.concat(all_data_list) return all_data def do_powerlaw_fit(HiC, resolution): print(""Running regression"") # TO DO: # Print out mean/var plot of powerlaw relationship # Juicebox output is in sparse matrix format. This is an attempt to get a ""mean"" hic_contact for each distance bin since we don't have the total # of bins available. HiC_summary = HiC.groupby(""dist_for_fit"").agg({""hic_contact"": ""sum""}) # HiC_summary['hic_contact'] = HiC_summary.hic_contact / HiC_summary.hic_contact.sum() #technically this normalization should be over the entire genome (not just to maxWindow). Will only affect intercept though # get a better approximation of the total # of bins . total_num_bins = len(HiC.loc[HiC[""dist_for_fit""] == resolution]) print(total_num_bins) # idx = np.isfinite(HiC_summary['hic_contact']) & np.isfinite(HiC_summary.index) HiC_summary[""hic_contact""] = HiC_summary.hic_contact / total_num_bins pseudocount = 0.000001 # pseudocount = 0 res = stats.linregress( np.log(HiC_summary.index + pseudocount), np.log(HiC_summary[""hic_contact""] + pseudocount), ) hic_mean_var = HiC.groupby(""dist_for_fit"").agg({""hic_contact"": [""mean"", ""var""]}) hic_mean_var.columns = [""mean"", ""var""] return res.slope, res.intercept, hic_mean_var if __name__ == ""__main__"": main() ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/juicebox_dump.py",".py","2850","90","import argparse import subprocess from tools import run_command def parseargs(): parser = argparse.ArgumentParser(description=""Download and dump HiC data"") parser.add_argument(""--hic_file"", required=True, help=""Path or url to .hic file."") parser.add_argument( ""--juicebox"", required=True, default="""", help=""path to juicebox executable or java command invoking juicer_tools.jar. eg: 'java -jar juicer_tools.jar'"", ) parser.add_argument( ""--resolution"", default=5000, help=""Resolution of HiC to download. In units of bp."", ) parser.add_argument(""--outdir"", default=""."") parser.add_argument( ""--include_raw"", action=""store_true"", help=""Download raw matrix in addtion to KR"", ) parser.add_argument( ""--chromosomes"", default=""all"", help=""comma delimited list of chromosomes to download"", ) parser.add_argument(""--skip_gzip"", action=""store_true"", help=""dont gzip hic files"") return parser.parse_args() def main(args): if args.chromosomes == ""all"": chromosomes = list(range(1, 23)) + [""X""] else: chromosomes = args.chromosomes.split("","") for chromosome in chromosomes: print(""Starting chr"" + str(chromosome) + "" ... "") outdir = ""{0}/chr{1}/"".format(args.outdir, chromosome) command = ""mkdir -p "" + outdir run_command(command) ## Download observed matrix with KR normalization command = ( args.juicebox + "" dump observed KR {0} {1} {1} BP {3} {2}chr{1}.KRobserved"".format( args.hic_file, chromosome, outdir, args.resolution ) ) print(command) run_command(command) if not args.skip_gzip: run_command(""gzip {0}chr{1}.KRobserved"".format(outdir, chromosome)) ## Download KR norm file command = ( args.juicebox + "" dump norm KR {0} {1} BP {3} {2}chr{1}.KRnorm"".format( args.hic_file, chromosome, outdir, args.resolution ) ) run_command(command) print(command) if not args.skip_gzip: run_command(""gzip {0}chr{1}.KRnorm"".format(outdir, chromosome)) if args.include_raw: ## Download raw observed matrix command = ( args.juicebox + "" dump observed NONE {0} {1} {1} BP {3} {2}chr{1}.RAWobserved"".format( args.hic_file, chromosome, outdir, args.resolution ) ) print(command) run_command(command) if not args.skip_gzip: run_command(""gzip {0}chr{1}.RAWobserved"".format(outdir, chromosome)) if __name__ == ""__main__"": args = parseargs() main(args) ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/makeCandidateRegions.py",".py","3724","120","import argparse import os from peaks import make_candidate_regions_from_peaks, make_candidate_regions_from_summits from tools import write_params def parseargs(required_args=True): class formatter( argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter ): pass epilog = """" parser = argparse.ArgumentParser( description=""Make peaks file for a given cell type"", epilog=epilog, formatter_class=formatter, ) readable = argparse.FileType(""r"") parser.add_argument( ""--narrowPeak"", required=required_args, help=""narrowPeak file output by macs2. Must include summits (--call-summits)"", ) parser.add_argument( ""--accessibility"", required=required_args, nargs=""+"", help=""List of DNAase-Seq or ATAC-Seq bam/tagalign files"", ) parser.add_argument( ""--chrom_sizes"", required=required_args, help=""File listing chromosome size annotaions"", ) parser.add_argument( ""--chrom_sizes_bed"", required=required_args, help=""File listing chromosome size annotaions"", ) parser.add_argument(""--outDir"", required=required_args) parser.add_argument( ""--nStrongestPeaks"", default=175000, help=""Number of peaks to use for defining candidate regions"", ) parser.add_argument( ""--peakExtendFromSummit"", default=250, help=""Number of base pairs to extend each preak from its summit (or from both ends of region if using --ignoreSummits)"", ) parser.add_argument( ""--ignoreSummits"", action=""store_true"", help=""Compute peaks using the full peak regions, rather than extending from summit."", ) parser.add_argument( ""--minPeakWidth"", default=500, help=""Candidate regions whose width is below this threshold are expanded to this width. Only used with --ignoreSummits"", ) parser.add_argument( ""--regions_includelist"", default="""", help=""Bed file of regions to forcibly include in candidate enhancers. Overrides regions_blocklist"", ) parser.add_argument( ""--regions_blocklist"", default="""", help=""Bed file of regions to forcibly exclude from candidate enhancers"", ) args = parser.parse_args() return args def processCellType(args): os.makedirs(os.path.join(args.outDir), exist_ok=True) write_params(args, os.path.join(args.outDir, ""params.txt"")) # Make candidate regions if not args.ignoreSummits: make_candidate_regions_from_summits( macs_peaks=args.narrowPeak, accessibility_files=args.accessibility, genome_sizes=args.chrom_sizes, genome_sizes_bed=args.chrom_sizes_bed, regions_includelist=args.regions_includelist, regions_blocklist=args.regions_blocklist, n_enhancers=args.nStrongestPeaks, peak_extend=args.peakExtendFromSummit, outdir=args.outDir, ) else: make_candidate_regions_from_peaks( macs_peaks=args.narrowPeak, accessibility_files=args.accessibility, genome_sizes=args.chrom_sizes, genome_sizes_bed=args.chrom_sizes_bed, regions_includelist=args.regions_includelist, regions_blocklist=args.regions_blocklist, n_enhancers=args.nStrongestPeaks, peak_extend=args.peakExtendFromSummit, minPeakWidth=args.minPeakWidth, outdir=args.outDir, ) def main(args): processCellType(args) if __name__ == ""__main__"": args = parseargs() main(args) ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/getVariantOverlap.py",".py","1910","61","import argparse import os import pandas as pd import numpy as np def parse_args(): parser = argparse.ArgumentParser() parser.add_argument(""--all_putative"") parser.add_argument(""--score_column"", default=""ABC.Score"") parser.add_argument(""--chrom_sizes"") parser.add_argument(""--outdir"") args = parser.parse_args() return args def test_variant_overlap(args, all_putative): variant_overlap_file = os.path.join( args.outdir, ""EnhancerPredictionsAllPutative.ForVariantOverlap.shrunk150bp.tsv.gz"", ) # generate predictions for variant overlap score_t = all_putative[args.score_column] > 0.015 not_promoter = all_putative[""class""] != ""promoter"" is_promoter = all_putative[""class""] == ""promoter"" score_one = all_putative[args.score_column] > 0.1 all_putative[(score_t & not_promoter) | (is_promoter & score_one)] variant_overlap = all_putative[(score_t & not_promoter) | (is_promoter & score_one)] # remove nan predictions variant_overlap_pred = variant_overlap.dropna(subset=[args.score_column]) variant_overlap = variant_overlap_pred.loc[ variant_overlap_pred[""distance""] <= 2000000 ] variant_overlap.to_csv( variant_overlap_file + "".tmp"", sep=""\t"", index=False, header=True, compression=""gzip"", float_format=""%.6f"", ) # shrink regions os.system( ""zcat {}.tmp 2>/dev/null | head -1 | gzip > {}"".format( variant_overlap_file, variant_overlap_file ) ) os.system( ""zcat {}.tmp | sed 1d | bedtools slop -b -150 -g {} | gzip >> {}"".format( variant_overlap_file, args.chrom_sizes, variant_overlap_file ) ) print(""Done."") if __name__ == ""__main__"": args = parse_args() all_putative = pd.read_csv(args.all_putative, sep=""\t"") test_variant_overlap(args, all_putative) ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/makeAverageHiC.py",".py","6722","206","import pandas as pd import numpy as np from functools import reduce import argparse import sys, os, os.path from tools import write_params from hic import load_hic_juicebox, get_hic_file, get_powerlaw_at_distance # To do # Final output matrix needs to be KR normed as well def parseargs(): class formatter( argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter ): pass epilog = """" parser = argparse.ArgumentParser( description=""Make average HiC dataset"", epilog=epilog, formatter_class=formatter ) readable = argparse.FileType(""r"") parser.add_argument( ""--celltypes"", required=True, help=""Comma delimitted list of cell types"" ) parser.add_argument(""--chromosome"", required=True, help=""Chromosome to compute on"") parser.add_argument(""--basedir"", required=True, help=""Basedir"") parser.add_argument(""--outDir"", required=True, help=""Output directory"") parser.add_argument( ""--resolution"", default=5000, type=int, help=""Resolution of hic dataset (in bp)"" ) parser.add_argument( ""--ref_scale"", default=5.41, type=float, help=""Reference scale parameter"" ) parser.add_argument( ""--ref_gamma"", default=-0.876, type=float, help=""Reference gamma parameter"" ) parser.add_argument( ""--min_cell_types_required"", default=3, type=int, help=""Minimum number of non-nan entries required to calculate average for a hic bin"", ) args = parser.parse_args() return args def main(): args = parseargs() os.makedirs(args.outDir, exist_ok=True) # Write params file write_params(args, os.path.join(args.outDir, ""params.txt"")) # Parse cell types cell_types = args.celltypes.split("","") # chromosomes = ['chr' + str(x) for x in range(1,23)] + ['chrX'] # chromosomes = ['chr22'] special_value = np.Inf # for chromosome in chromosomes: hic_list = [ process_chr( cell_type, args.chromosome, args.basedir, args.resolution, args.ref_scale, args.ref_gamma, special_value, ) for cell_type in cell_types ] hic_list = [x for x in hic_list if x is not None] hic_list = [df.set_index([""bin1"", ""bin2""]) for df in hic_list] # Make average # Merge all hic matrices # Need to deal with nan vs 0 here. In the KR normalized matrices there are nan which we want to deal as missing. # Rows that are not present in the hic dataframe should be considered 0 # But after doing an outer join these rows will be represented as nan in the merged dataframe. # So need a way to distinguish nan vs 0. # Hack: convert all nan in the celltype specific hic dataframes to a special value. Then replace this special value after merging # TO DO: This is very memory intensive! (consider pandas.join or pandas.concat) # import pdb # pdb.set_trace() all_hic = pd.concat(hic_list, axis=1, join=""outer"", copy=False) hic_list = None # Clear from memory # import pdb # pdb.set_trace() # all_hic = pd.DataFrame().join(hic_list, how=""outer"", on=['bin1','bin2']) # all_hic = reduce(lambda x, y: pd.merge(x, y, on = ['bin1', 'bin2'], how = 'outer'), hic_list) all_hic.fillna(value=0, inplace=True) all_hic.replace(to_replace=special_value, value=np.nan, inplace=True) # compute the average cols_for_avg = list(filter(lambda x: ""hic_kr"" in x, all_hic.columns)) # all_hic['avg_hic'] = all_hic[cols_for_avg].mean(axis=1) # avg_hic = all_hic[cols_for_avg].mean(axis=1) avg_hic = all_hic.mean(axis=1) num_good = len(cols_for_avg) - np.isnan(all_hic).sum(axis=1) # Check minimum number of cols all_hic.drop(cols_for_avg, inplace=True, axis=1) all_hic.reset_index(level=all_hic.index.names, inplace=True) all_hic[""avg_hic""] = avg_hic.values all_hic.loc[num_good.values < args.min_cell_types_required, ""avg_hic""] = np.nan # Setup final matrix all_hic[""bin1""] = all_hic[""bin1""] * args.resolution all_hic[""bin2""] = all_hic[""bin2""] * args.resolution all_hic = all_hic.loc[ np.logical_or(all_hic[""avg_hic""] > 0, np.isnan(all_hic[""avg_hic""])), ] # why do these 0's exist? os.makedirs(os.path.join(args.outDir, args.chromosome), exist_ok=True) all_hic.to_csv( os.path.join(args.outDir, args.chromosome, args.chromosome + "".avg.gz""), sep=""\t"", header=False, index=False, compression=""gzip"", na_rep=np.nan, ) def scale_hic_with_powerlaw(hic, resolution, scale_ref, gamma_ref, scale, gamma): # get_powerlaw_at_distance expects positive gamma gamma_ref = -1 * gamma_ref gamma = -1 * gamma dists = (hic[""bin2""] - hic[""bin1""]) * resolution pl_ref = get_powerlaw_at_distance(dists, gamma_ref, scale_ref) pl = get_powerlaw_at_distance(dists, gamma, scale) hic[""hic_kr""] = hic[""hic_kr""] * (pl_ref / pl) return hic def process_chr( cell_type, chromosome, basedir, resolution, scale_ref, gamma_ref, special_value ): # import pdb # pdb.set_trace() hic_file, hic_norm_file, is_vc = get_hic_file( chromosome, os.path.join(basedir, cell_type, ""5kb_resolution_intra""), allow_vc=True, ) if is_vc: return None # hic_file = os.path.join(basedir, cell_type, ""5kb_resolution_intra"", chromosome, chromosome + "".KRobserved"") # hic_norm_file = os.path.join(basedir, cell_type, ""5kb_resolution_intra"", chromosome, chromosome + "".KRnorm"") # Load gamma and scale pl_summary = pd.read_csv( os.path.join( basedir, cell_type, ""5kb_resolution_intra/powerlaw/hic.powerlaw.txt"" ), sep=""\t"", ) # Read in and normalize to make DS hic = load_hic_juicebox( hic_file=hic_file, hic_norm_file=hic_norm_file, hic_is_vc=False, hic_resolution=resolution, tss_hic_contribution=np.NaN, window=np.Inf, min_window=0, gamma=-1 * pl_summary[""pl_gamma""].values[0], interpolate_nan=False, apply_diagonal_bin_correction=False, ) # power law scale hic = scale_hic_with_powerlaw( hic, resolution, scale_ref, gamma_ref, scale=pl_summary[""pl_scale""].values[0], gamma=pl_summary[""pl_gamma""].values[0], ) # fill nan in hic matrix with special value # this will be turned back to nan after merging assert not np.any(hic[""hic_kr""].values == special_value) hic.loc[np.isnan(hic[""hic_kr""]), ""hic_kr""] = special_value return hic if __name__ == ""__main__"": main() ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/run.neighborhoods.py",".py","6759","210","import argparse import os import pandas as pd from neighborhoods import * def parseargs(required_args=True): class formatter( argparse.ArgumentDefaultsHelpFormatter, argparse.RawTextHelpFormatter ): pass epilog = """" parser = argparse.ArgumentParser( description=""Run neighborhood for a given cell type"", epilog=epilog, formatter_class=formatter, ) readable = argparse.FileType(""r"") parser.add_argument( ""--candidate_enhancer_regions"", required=required_args, help=""Bed file containing candidate_enhancer_regions"", ) parser.add_argument( ""--outdir"", required=required_args, help=""Directory to write Neighborhood files to."", ) # genes parser.add_argument( ""--genes"", required=required_args, help=""bed file with gene annotations. Must be in bed-6 format. Will be used to assign TSS to genes."", ) parser.add_argument( ""--genes_for_class_assignment"", default=None, help=""bed gene annotations for assigning elements to promoter/genic/intergenic classes. Will not be used for TSS definition"", ) parser.add_argument( ""--ubiquitously_expressed_genes"", default=None, help=""File listing ubiquitously expressed genes. These will be flagged by the model, but this annotation does not affect model predictions"", ) parser.add_argument( ""--gene_name_annotations"", default=""symbol"", help=""Comma delimited string of names corresponding to the gene identifiers present in the name field of the gene annotation bed file"", ) parser.add_argument( ""--primary_gene_identifier"", default=""symbol"", help=""Primary identifier used to identify genes. Must be present in gene_name_annotations. The primary identifier must be unique"", ) parser.add_argument( ""--skip_gene_counts"", action=""store_true"", help=""Do not count over genes or gene bodies. Will not produce GeneList.txt. Do not use switch if intending to run Predictions"", ) # epi parser.add_argument( ""--H3K27ac"", default="""", nargs=""?"", help=""Comma delimited string of H3K27ac .bam files"", ) parser.add_argument( ""--DHS"", default="""", nargs=""?"", help=""Comma delimited string of DHS .bam files. Either ATAC or DHS must be provided"", ) parser.add_argument( ""--ATAC"", default="""", nargs=""?"", help=""Comma delimited string of ATAC .bam files. Either ATAC or DHS must be provided"", ) parser.add_argument( ""--default_accessibility_feature"", default=None, nargs=""?"", help=""If both ATAC and DHS are provided, this flag must be set to either 'DHS' or 'ATAC' signifying which datatype to use in computing activity"", ) parser.add_argument( ""--expression_table"", default="""", nargs=""?"", help=""Comma delimited string of gene expression files"", ) parser.add_argument( ""--qnorm"", default=None, help=""Quantile normalization reference file"" ) # Other parser.add_argument( ""--tss_slop_for_class_assignment"", default=500, type=int, help=""Consider an element a promoter if it is within this many bp of a tss"", ) parser.add_argument( ""--skip_rpkm_quantile"", action=""store_true"", help=""Do not compute RPKM and quantiles in EnhancerList.txt"", ) parser.add_argument( ""--use_secondary_counting_method"", action=""store_true"", help=""Use a slightly slower way to count bam over bed. Also requires more memory. But is more stable"", ) parser.add_argument( ""--chrom_sizes"", required=required_args, help=""Genome file listing chromosome sizes"", ) parser.add_argument( ""--chrom_sizes_bed"", required=required_args, help=""Associated .bed file of chrom_sizes"", ) parser.add_argument( ""--enhancer_class_override"", default=None, help=""Annotation file to override enhancer class assignment"", ) parser.add_argument( ""--supplementary_features"", default=None, help=""Additional features to count over regions"", ) parser.add_argument(""--cellType"", default=None, help=""Name of cell type"") # replace textio wrapper returned by argparse with actual filename args = parser.parse_args() for name, val in vars(args).items(): if hasattr(val, ""name""): setattr(args, name, val.name) print(args) return args def processCellType(args): params = parse_params_file(args) os.makedirs(args.outdir, exist_ok=True) # Setup Genes genes, genes_for_class_assignment = load_genes( file=args.genes, ue_file=args.ubiquitously_expressed_genes, chrom_sizes=args.chrom_sizes, outdir=args.outdir, expression_table_list=params[""expression_table""], gene_id_names=args.gene_name_annotations, primary_id=args.primary_gene_identifier, cellType=args.cellType, class_gene_file=args.genes_for_class_assignment, ) chrom_sizes_map = pd.read_csv( args.chrom_sizes, sep=""\t"", header=None, index_col=0 ).to_dict()[1] if not args.skip_gene_counts: annotate_genes_with_features( genes=genes, genome_sizes=args.chrom_sizes, genome_sizes_bed=args.chrom_sizes_bed, chrom_sizes_map=chrom_sizes_map, use_fast_count=(not args.use_secondary_counting_method), default_accessibility_feature=params[""default_accessibility_feature""], features=params[""features""], outdir=args.outdir, ) # Setup Candidate Enhancers load_enhancers( genes=genes_for_class_assignment, genome_sizes=args.chrom_sizes, genome_sizes_bed=args.chrom_sizes_bed, candidate_peaks=args.candidate_enhancer_regions, skip_rpkm_quantile=args.skip_rpkm_quantile, qnorm=args.qnorm, tss_slop_for_class_assignment=args.tss_slop_for_class_assignment, use_fast_count=(not args.use_secondary_counting_method), default_accessibility_feature=params[""default_accessibility_feature""], features=params[""features""], cellType=args.cellType, class_override_file=args.enhancer_class_override, outdir=args.outdir, chrom_sizes_map=chrom_sizes_map, ) print(""Neighborhoods Complete! \n"") def main(args): processCellType(args) if __name__ == ""__main__"": args = parseargs() main(args) ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/predictor.py",".py","18701","551","import math import time from collections import defaultdict from typing import Dict import hicstraw # hicstraw must be imported before pandas import numpy as np import pandas as pd from hic import ( get_hic_file, get_powerlaw_at_distance, load_hic_avg, load_hic_bedpe, load_hic_juicebox, ) from tools import df_to_pyranges def make_predictions( chromosome, enhancers, genes, args, hic_gamma, hic_scale, chrom_sizes_map ): pred = make_pred_table(chromosome, enhancers, genes, args.window, chrom_sizes_map) pred = annotate_predictions(pred, args.tss_slop) pred = add_powerlaw_to_predictions(pred, args, hic_gamma, hic_scale) # if Hi-C file is not provided, only powerlaw model will be computed if args.hic_file: if args.hic_type == ""hic"": pred = add_hic_from_hic_file( pred, args.hic_file, chromosome, args.hic_resolution ) else: pred = add_hic_from_directory( chromosome, enhancers, genes, pred, args.hic_file, args, hic_gamma, hic_scale, chrom_sizes_map, ) pred = qc_hic(pred, hic_gamma, hic_scale, args.hic_resolution) pred.fillna(value={""hic_contact"": 0}, inplace=True) # Add powerlaw scaling pred = scale_hic_with_powerlaw(pred, args) # Add pseudocount pred = add_hic_pseudocount(pred, args) print(""HiC Complete"") pred = compute_score( pred, [pred[""activity_base_enh""], pred[""hic_contact_pl_scaled_adj""]], ""ABC"", adjust_self_promoters=True, ) else: pred = compute_score( pred, [pred[""activity_base_enh""], pred[""powerlaw_contact""]], ""ABC"", adjust_self_promoters=True, ) pred = compute_score( pred, [pred[""activity_base_enh""], pred[""powerlaw_contact""]], ""powerlaw"", adjust_self_promoters=True, ) return pred def make_pred_table(chromosome, enh, genes, window, chrom_sizes_map: Dict[str, int]): print(""Making putative predictions table..."") t = time.time() enh[""enh_midpoint""] = (enh[""start""] + enh[""end""]) / 2 enh[""enh_idx""] = enh.index genes[""gene_idx""] = genes.index enh_pr = df_to_pyranges(enh) genes_pr = df_to_pyranges( genes, start_col=""TargetGeneTSS"", end_col=""TargetGeneTSS"", start_slop=window, end_slop=window, chrom_sizes_map=chrom_sizes_map, ) pred = enh_pr.join(genes_pr).df.drop( [""Start_b"", ""End_b"", ""chr_b"", ""Chromosome"", ""Start"", ""End""], axis=1 ) pred[""distance""] = abs(pred[""enh_midpoint""] - pred[""TargetGeneTSS""]) pred = pred.loc[pred[""distance""] < window, :] # for backwards compatability print( ""Done. There are {} putative enhancers for chromosome {}"".format( pred.shape[0], chromosome ) ) print(""Elapsed time: {}"".format(time.time() - t)) return pred def fill_diagonals(df, hic_resolution): """""" Fill diagonals based on the neighbors We want to search neighboring bins If hic_resolution is < 5kb, make sure we use a search space of 5kb for our neighbors """""" diagonal_bins = df[ df.index.get_level_values(""binX"") == df.index.get_level_values(""binY"") ] search_space_bins = 1 if hic_resolution < 5000: search_space_bins = math.ceil(5000 / hic_resolution) for (binX, binX), _ in diagonal_bins.iterrows(): max_contact = 0 for i in range(1, search_space_bins + 1): left_bin = (binX - i, binX) right_bin = ( binX, binX + i, ) # we have to look above b/c we haven't processed right bin yet for bin in [left_bin, right_bin]: if bin in df.index: max_contact = max(max_contact, df.loc[bin, ""counts""]) df.loc[(binX, binX), ""counts""] = max_contact def create_df_from_records(records, hic_resolution): """""" The bins returned from hic straw are in hic_resolution increments If resolution = 5k, we want to normalize the bins such that: 5000 -> bin 1 10000 -> bin 2 ... 100k -> bin 20 Where the left number is the genomic position of the bin We also handle filling the diagonals differently """""" df = pd.DataFrame(records, columns=[""binX"", ""binY"", ""counts""]) df[""binX""] = np.floor(df[""binX""] / hic_resolution).astype(int) df[""binY""] = np.floor(df[""binY""] / hic_resolution).astype(int) df = df.set_index([""binX"", ""binY""]) # Set indexes for performance fill_diagonals(df, hic_resolution) return df def get_chrom_format(hic: hicstraw.HiCFile, chromosome): """""" hic files can have 'chr1' or just '1' as the chromosome name we need to make sure we're using the format consistent with the hic file """""" hic_chrom_names = [chrom.name for chrom in hic.getChromosomes()] if hic_chrom_names[1].startswith(""chr""): # assume index 1 should be chr1 return chromosome else: return chromosome[3:] def get_chrom_size(hic: hicstraw.HiCFile, chromosome): for chrom in hic.getChromosomes(): if chrom.name == chromosome: return chrom.length raise Exception(f""{chromosome} not found in hic data"") def determine_num_rows_to_fetch( chrom_size, hic_resolution, desired_mem_usage=16e9, record_size_bytes=200 ): """""" Assuming each record takes up 200 bytes of memory, try to determine what is the max number of rows we can fetch from the hic matrix without going over the desired memory usage """""" num_records_per_row = math.ceil(chrom_size / hic_resolution) mem_usage_per_row = num_records_per_row * record_size_bytes max_rows = desired_mem_usage // mem_usage_per_row return int(max_rows) def add_records_to_bin_sums(records, bin_sums, start, end): """""" hicstraw will remove duplicates in records e.g say there's contact between bin 1 and bin 2 if i query for bin 1 and bin 2's rows in a single query, we will only get 1 value of (bin 1, bin 2). However, if we query for bin 1 and bin 2 separately, each result will give us (bin 1, bin 2). To correct for the duplicate values, we will divide a value in half if it'll get returned in a different query """""" for binX, binY, value in records: if binX < start or binY > end: value /= 2 if binX == binY: bin_sums[binX] += value else: bin_sums[binX] += value bin_sums[binY] += value def add_hic_from_hic_file(pred, hic_file, chromosome, hic_resolution): print(""Begin HiC"") start_time = time.time() pred[""enh_bin""] = np.floor(pred[""enh_midpoint""] / hic_resolution).astype(int) pred[""tss_bin""] = np.floor(pred[""TargetGeneTSS""] / hic_resolution).astype(int) pred[""binX""] = np.min(pred[[""enh_bin"", ""tss_bin""]], axis=1) pred[""binY""] = np.max(pred[[""enh_bin"", ""tss_bin""]], axis=1) hic = hicstraw.HiCFile(hic_file) chromosome = get_chrom_format(hic, chromosome) chromosome_size = get_chrom_size(hic, chromosome) matrix_object = hic.getMatrixZoomData( chromosome, chromosome, ""observed"", ""SCALE"", ""BP"", hic_resolution ) # start and end loci need to cover the entire chromosome b/c we do normalization start_loci = 0 end_loci = chromosome_size num_rows = 8000 # Using megamap with this number keeps memory usage right under 4GB bin_sums = defaultdict(float) step_size = num_rows * hic_resolution for i in range(start_loci, end_loci, step_size): start = i end = start + step_size - hic_resolution records = matrix_object.getRecords(start, end, start_loci, end_loci) if records: records = [[r.binX, r.binY, r.counts] for r in records] add_records_to_bin_sums(records, bin_sums, start, end) df = create_df_from_records(records, hic_resolution) pred = pred.merge( df, how=""left"", left_on=[""binX"", ""binY""], right_index=True, suffixes=(None, ""_""), ) if ""counts_"" in pred: # After the first join, we have to merge the new records into # the existing count column. It's really just replacing the # nan values in pred_df with new values from latest records pred[""counts""] = np.max(pred[[""counts"", ""counts_""]], axis=1) pred.drop(""counts_"", inplace=True, axis=1) row_mean = np.mean(list(bin_sums.values())) # normalize hic_contact by the row_mean to reflect a doubly stochastic hic matrix pred[""counts""] /= row_mean pred.drop( [ ""binX"", ""binY"", ""enh_idx"", ""gene_idx"", ""enh_midpoint"", ""tss_bin"", ""enh_bin"", ""max_neighbor_count"", ], inplace=True, axis=1, errors=""ignore"", ) print( ""HiC added to predictions table. Elapsed time: {}"".format( time.time() - start_time ) ) return pred.rename(columns={""counts"": ""hic_contact""}) def add_hic_from_directory( chromosome, enh, genes, pred, hic_dir, args, hic_gamma, hic_scale, chrom_sizes_map, ): hic_file, hic_norm_file, hic_is_vc = get_hic_file( chromosome, hic_dir, hic_type=args.hic_type ) print(""Begin HiC"") # Add hic to pred table # At this point we have a table where each row is an enhancer/gene pair. # We need to add the corresponding HiC matrix entry. # If the HiC is provided in juicebox format (ie constant resolution), then we can just merge using the indices # But more generally we do not want to assume constant resolution. In this case hic should be provided in bedpe format t = time.time() if args.hic_type == ""bedpe"": HiC = load_hic_bedpe(hic_file) # Use pyranges to compute overlaps between enhancers/genes and hic bedpe table # Consider each range of the hic matrix separately - and merge each range into both enhancers and genes. # Then remerge on hic index HiC[""hic_idx""] = HiC.index hic1 = df_to_pyranges(HiC, start_col=""x1"", end_col=""x2"", chr_col=""chr1"") hic2 = df_to_pyranges(HiC, start_col=""y1"", end_col=""y2"", chr_col=""chr2"") # Overlap in one direction enh_hic1 = ( df_to_pyranges( enh, start_col=""enh_midpoint"", end_col=""enh_midpoint"", end_slop=1, chrom_sizes_map=chrom_sizes_map, ) .join(hic1) .df ) genes_hic2 = ( df_to_pyranges( genes, start_col=""TargetGeneTSS"", end_col=""TargetGeneTSS"", end_slop=1, chrom_sizes_map=chrom_sizes_map, ) .join(hic2) .df ) ovl12 = enh_hic1[[""enh_idx"", ""hic_idx"", ""hic_contact""]].merge( genes_hic2[[""gene_idx"", ""hic_idx""]], on=""hic_idx"" ) # Overlap in the other direction enh_hic2 = ( df_to_pyranges( enh, start_col=""enh_midpoint"", end_col=""enh_midpoint"", end_slop=1, chrom_sizes_map=chrom_sizes_map, ) .join(hic2) .df ) genes_hic1 = ( df_to_pyranges( genes, start_col=""TargetGeneTSS"", end_col=""TargetGeneTSS"", end_slop=1, chrom_sizes_map=chrom_sizes_map, ) .join(hic1) .df ) ovl21 = enh_hic2[[""enh_idx"", ""hic_idx"", ""hic_contact""]].merge( genes_hic1[[""gene_idx"", ""hic_idx""]], on=[""hic_idx""] ) # Concatenate both directions and merge into preditions ovl = pd.concat([ovl12, ovl21]).drop_duplicates() pred = pred.merge(ovl, on=[""enh_idx"", ""gene_idx""], how=""left"") elif args.hic_type == ""juicebox"" or args.hic_type == ""avg"": if args.hic_type == ""juicebox"": HiC = load_hic_juicebox( hic_file=hic_file, hic_norm_file=hic_norm_file, hic_is_vc=hic_is_vc, hic_resolution=args.hic_resolution, tss_hic_contribution=args.tss_hic_contribution, window=args.window, min_window=0, gamma=hic_gamma, scale=hic_scale, ) else: HiC = load_hic_avg(hic_file, args.hic_resolution) # Merge directly using indices # Could also do this by indexing into the sparse matrix (instead of merge) but this seems to be slower # Index into sparse matrix # pred['hic_contact'] = [HiC[i,j] for (i,j) in pred[['enh_bin','tss_bin']].values.tolist()] pred[""enh_bin""] = np.floor(pred[""enh_midpoint""] / args.hic_resolution).astype( int ) pred[""tss_bin""] = np.floor(pred[""TargetGeneTSS""] / args.hic_resolution).astype( int ) if not hic_is_vc: # in this case the matrix is upper triangular. # pred[""bin1""] = np.amin(pred[[""enh_bin"", ""tss_bin""]], axis=1) pred[""bin2""] = np.amax(pred[[""enh_bin"", ""tss_bin""]], axis=1) pred = pred.merge(HiC, how=""left"", on=[""bin1"", ""bin2""]) else: # The matrix is not triangular, its full # For VC assume genes correspond to rows and columns to enhancers pred = pred.merge( HiC, how=""left"", left_on=[""tss_bin"", ""enh_bin""], right_on=[""bin1"", ""bin2""], ) pred.drop( [ ""x1"", ""x2"", ""y1"", ""y2"", ""bin1"", ""bin2"", ""enh_idx"", ""gene_idx"", ""hic_idx"", ""enh_midpoint"", ""tss_bin"", ""enh_bin"", ], inplace=True, axis=1, errors=""ignore"", ) print(""HiC added to predictions table. Elapsed time: {}"".format(time.time() - t)) return pred def scale_hic_with_powerlaw(pred, args): # Scale hic values to reference powerlaw if not args.scale_hic_using_powerlaw: # values = pred.loc[pred['hic_contact']==0].index.astype('int') # pred.loc[values, 'hic_contact'] = pred.loc[values, 'powerlaw_contact'] pred[""hic_contact_pl_scaled""] = pred[""hic_contact""] else: pred[""hic_contact_pl_scaled""] = pred[""hic_contact""] * ( pred[""powerlaw_contact_reference""] / pred[""powerlaw_contact""] ) return pred def add_powerlaw_to_predictions(pred, args, hic_gamma, hic_scale): pred[""powerlaw_contact""] = get_powerlaw_at_distance( pred[""distance""].values, hic_gamma, hic_scale ) # 4.80 and 11.63 come from a linear regression of scale on gamma across 20 # hic cell types at 5kb resolution. Do the params change across resolutions? hic_scale_reference = -4.80 + 11.63 * args.hic_gamma_reference pred[""powerlaw_contact_reference""] = get_powerlaw_at_distance( pred[""distance""].values, args.hic_gamma_reference, hic_scale_reference ) return pred def add_hic_pseudocount(pred, args): # Add a pseudocount based on the powerlaw expected count at a given distance pseudocount_distance = get_powerlaw_at_distance( args.hic_pseudocount_distance, args.hic_gamma, args.hic_scale, args.hic_pseudocount_distance, ) pred[""hic_pseudocount""] = pd.DataFrame( {""a"": pred[""powerlaw_contact""], ""b"": pseudocount_distance} ).min(axis=1) pred[""hic_contact_pl_scaled_adj""] = ( pred[""hic_contact_pl_scaled""] + pred[""hic_pseudocount""] ) return pred def qc_hic(pred, gamma, scale, resolution, threshold=0.01): # Gene promoters with insufficient hic coverage should get replaced with powerlaw summ = ( pred.loc[pred[""isSelfPromoter""], :] .groupby([""TargetGene""]) .agg({""hic_contact"": ""sum""}) ) bad_genes = summ.loc[summ[""hic_contact""] < threshold, :].index affected_pred = pred.loc[pred[""TargetGene""].isin(bad_genes), :] pred.loc[affected_pred.index, ""hic_contact""] = get_powerlaw_at_distance( affected_pred[""distance""].values, gamma, scale, min_distance=resolution, ) return pred def compute_score(enhancers, product_terms, prefix, adjust_self_promoters=True): scores = np.column_stack(product_terms).prod(axis=1) enhancers[prefix + "".Score.Numerator""] = scores enhancers[prefix + "".Score""] = enhancers[ prefix + "".Score.Numerator"" ] / enhancers.groupby([""TargetGene"", ""TargetGeneTSS""])[ prefix + "".Score.Numerator"" ].transform( ""sum"" ) # Self promoters by definition regulate the gene, so we # want to make sure they have a high score if adjust_self_promoters: self_promoters = enhancers[enhancers[""isSelfPromoter""]] enhancers.loc[self_promoters.index, prefix + "".Score""] = 1 return enhancers def annotate_predictions(pred, tss_slop=500): # TO DO: Add is self genic pred[""isSelfPromoter""] = np.logical_and.reduce( ( pred[""class""] == ""promoter"", pred.start - tss_slop < pred.TargetGeneTSS, pred.end + tss_slop > pred.TargetGeneTSS, ) ) return pred def make_gene_prediction_stats(pred, score_column, threshold, output_file): summ1 = pred.groupby([""chr"", ""TargetGene"", ""TargetGeneTSS""]).agg( { ""TargetGeneIsExpressed"": lambda x: set(x).pop(), score_column: lambda x: all(np.isnan(x)), ""name"": ""count"", } ) summ1.columns = [""geneIsExpressed"", ""geneFailed"", ""nEnhancersConsidered""] summ2 = ( pred.loc[pred[""class""] != ""promoter"", :] .groupby([""chr"", ""TargetGene"", ""TargetGeneTSS""]) .agg({score_column: lambda x: sum(x > threshold)}) ) summ2.columns = [""nDistalEnhancersPredicted""] summ1 = summ1.merge(summ2, left_index=True, right_index=True) summ1.to_csv(output_file, sep=""\t"", index=True) ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","workflow/scripts/extract_avg_hic.py",".py","1275","42","import gzip import os import subprocess import click @click.command() @click.option(""--avg_hic_bed_file"", type=str, required=True) @click.option(""--output_dir"", type=str, default=""."") def main(avg_hic_bed_file, output_dir): output_dir = os.path.join(output_dir, ""AvgHiC"") os.makedirs(output_dir, exist_ok=True) file_handles = {} with gzip.open(avg_hic_bed_file, ""rt"") as f: for line in f: if line.startswith(""#""): # header line continue chrom = line.split(""\t"")[0] hic_info = ""\t"".join(line.split(""\t"")[1:]) if chrom not in file_handles: print(f""Writing lines for {chrom}"") os.makedirs(os.path.join(output_dir, chrom), exist_ok=True) chrom_file = os.path.join( os.path.join(output_dir, chrom), f""{chrom}.bed"" ) file_handles[chrom] = open(chrom_file, ""w"") file_handles[chrom].write(hic_info) # Close all file handles for fh in file_handles.values(): filename = fh.name cmd = f""pigz -f {filename}"" print(f""Gzipping {filename}"") subprocess.run(cmd, shell=True, check=True) fh.close() if __name__ == ""__main__"": main() ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","docs/conf.py",".py","993","30","# Configuration file for the Sphinx documentation builder. # # For the full list of built-in configuration values, see the documentation: # https://www.sphinx-doc.org/en/master/usage/configuration.html # -- Project information ----------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information project = ""ABC-Enhancer-Gene-Prediction"" copyright = ""2023, Anthony Tan"" author = ""Anthony Tan"" # -- General configuration --------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration extensions = [] # type: ignore templates_path = [""_templates""] exclude_patterns = [""_build"", ""Thumbs.db"", "".DS_Store""] # -- Options for HTML output ------------------------------------------------- # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output html_css_files = [ ""custom.css"", ] html_theme = ""sphinx_rtd_theme"" ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","tests/replace_expected_output.sh",".sh","167","6","#!/bin/bash # Used when we want to change the expected output to match the latest test output run set -e rm -rf expected_output/* cp -R test_output/* expected_output/","Shell" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","tests/test_full_abc_run.py",".py","4302","115","import glob import logging import os import time import unittest from typing import Dict import numpy as np import pandas as pd import yaml from utils import get_biosample_names, get_filtered_dataframe, read_file, run_cmd logging.basicConfig(level=logging.INFO) CONFIG_FILE = ""tests/config/generic_config.yml"" with open(CONFIG_FILE, ""r"") as file: CONFIG = yaml.safe_load(file) COLUMNS_TO_COMPARE: Dict[str, type] = { ""chr"": str, ""start"": np.int64, ""end"": np.int64, ""name"": str, ""class"": str, ""TargetGene"": str, ""ABC.Score.Numerator"": np.float64, ""ABC.Score"": np.float64, ""powerlaw.Score"": np.float64, } TEST_OUTPUT_DIR = CONFIG[""results_dir""] EXPECTED_OUTPUT_DIR = f""tests/expected_output/{CONFIG['TEST_CONFIG_NAME']}"" ALL_PUTATIVE_PRED_FILE = ""Predictions/EnhancerPredictionsAllPutative.tsv.gz"" THRESHOLDED_PRED_FILE = ( ""Predictions/EnhancerPredictionsFull_threshold*_self_promoter.tsv"" ) INTERMEDIATE_FILES = [ # EnhancerList is not good to compare b/c genicSymbol column isn't deterministic # ""Neighborhoods/EnhancerList.txt"", ""Neighborhoods/GeneList.txt"", ""Peaks/macs2_peaks.narrowPeak.sorted.candidateRegions.bed"", ] class TestFullABCRun(unittest.TestCase): def compare_intermediate_files(self, biosample: str) -> None: for file in INTERMEDIATE_FILES: test_file = os.path.join(TEST_OUTPUT_DIR, biosample, file) expected_file = os.path.join(EXPECTED_OUTPUT_DIR, biosample, file) msg = f""Intermediate file comparison failed for {file}"" test_contents = read_file(test_file) expected_contents = read_file(expected_file) self.assertEqual(test_contents, expected_contents, msg) def compare_all_prediction_file(self, biosample: str, pred_file) -> None: test_file = os.path.join(TEST_OUTPUT_DIR, biosample, pred_file) expected_file = os.path.join(EXPECTED_OUTPUT_DIR, biosample, pred_file) print(f""Comparing biosample: {biosample} for pred_file: {pred_file}"") pd.testing.assert_frame_equal( get_filtered_dataframe(test_file, COLUMNS_TO_COMPARE), get_filtered_dataframe(expected_file, COLUMNS_TO_COMPARE), ) def compare_thresholded_prediction_file(self, biosample: str) -> None: test_files = glob.glob( os.path.join(TEST_OUTPUT_DIR, biosample, THRESHOLDED_PRED_FILE) ) expected_files = glob.glob( os.path.join(EXPECTED_OUTPUT_DIR, biosample, THRESHOLDED_PRED_FILE) ) if len(test_files) != 1: raise Exception( f""Multiple or no test thresholded files found. Please clean up. {test_files}"" ) if len(expected_files) != 1: raise Exception( f""Multiple or no expected thresholded files found. Please clean up. {expected_files}"" ) test_file = test_files[0] expected_file = expected_files[0] print( f""Comparing biosample: {biosample} for pred_file: {os.path.basename(test_file)}"" ) pd.testing.assert_frame_equal( get_filtered_dataframe(test_file, COLUMNS_TO_COMPARE), get_filtered_dataframe(expected_file, COLUMNS_TO_COMPARE), ) def run_test(self, config_file: str) -> None: start = time.time() cmd = f""snakemake -j4 -F --configfile {config_file}"" run_cmd(cmd) time_taken = time.time() - start biosample_names = get_biosample_names(CONFIG[""biosamplesTable""]) for biosample in biosample_names: self.compare_intermediate_files(biosample) self.compare_all_prediction_file(biosample, ALL_PUTATIVE_PRED_FILE) self.compare_thresholded_prediction_file(biosample) # Make sure the test doesn't take too long # May need to adjust as more biosamples are added, but we should keep # tests quick, so don't run ABC on all chromosomes max_time = 60 * 8 # 8 min self.assertLessEqual( time_taken, max_time, msg=f""Running ABC took too long: {int(time_taken)} seconds"", ) def test_full_abc_run(self) -> None: self.run_test(CONFIG_FILE) if __name__ == ""__main__"": unittest.main() ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","tests/utils.py",".py","990","41","import gzip import logging import subprocess from typing import Callable, List, Dict import pandas as pd def read_file(file_name: str) -> str: open_fn: Callable = open if file_name.endswith("".gz""): open_fn = gzip.open with open_fn(file_name, ""r"") as f: return """".join(sorted(f.readlines())) def get_filtered_dataframe(file: str, cols_to_compare: Dict[str, type]) -> pd.DataFrame: return pd.read_csv( file, sep=""\t"", dtype=cols_to_compare, usecols=cols_to_compare.keys(), ) def run_cmd(cmd: str, raise_ex: bool = True) -> bool: try: subprocess.run(cmd, shell=True, check=True) except subprocess.CalledProcessError as e: logging.error(f""Error: {e}"") if raise_ex: raise return False return True def get_biosample_names(biosamples_tsv: str) -> List[str]: biosample_data = pd.read_csv(biosamples_tsv, sep=""\t"") return biosample_data.iloc[:, 0].tolist() ","Python" "CRISPR","broadinstitute/ABC-Enhancer-Gene-Prediction","tests/test_predictor.py",".py","1500","40","import os import sys import unittest SCRIPTS_DIR = os.path.abspath(""workflow/scripts"") sys.path.insert(0, SCRIPTS_DIR) from predictor import add_hic_from_hic_file import pandas as pd HIC_FILE = ""https://encode-public.s3.amazonaws.com/2022/05/15/0571c671-3645-4f92-beae-51dfd3f42c36/ENCFF621AIY.hic"" # this file has 3k rows of E-G pairs with valid contact values # contact values were generated from the original doubly stochastic method # w/ juicebox data. prediction df was saved in add_hic_from_directory, prior # to the columns getting dropped # pred = pred[pred['hic_contact'] > 0].sample(n=5000) # pred.to_csv('tests/test_data/test_pred_df.tsv', sep='\t', index=False) PRED_DF_FILE = ""tests/test_data/test_pred_df.tsv"" class TestPredictor(unittest.TestCase): def test_adding_hic(self) -> None: """""" Verifies hic streaming fills in hic contact the same way as juicebox - normalizing hic matrix to be doubly stochastic - imputing diagonals of matrix based on neighboring bins """""" pred = pd.read_csv(PRED_DF_FILE, sep=""\t"") expected_hic_contact_values = pred[""hic_contact""] pred.drop(""hic_contact"", axis=1, inplace=True) pred = add_hic_from_hic_file(pred, HIC_FILE, ""chr22"", 5000) test_hic_contact_values = pred[""hic_contact""] pd.testing.assert_series_equal( test_hic_contact_values, expected_hic_contact_values, atol=1e-9, rtol=0 ) if __name__ == ""__main__"": unittest.main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Run_each_base_summary.sh",".sh","358","19","#!/bin/bash #################### ## User parameter ## ################################### user=SH project=24K_screening ################################### while read python_path;do python=$python_path done < ../PythonPath.txt nohup $python ./Each_base_summary.py $user $project > ./Output/${user}/${project}/Log/Each_base_summary_log.txt 2>&1 & ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Each_base_summary.py",".py","7248","131","#!/home/hkimlab/anaconda2/bin/python2.7 import os, sys from pdb import set_trace try: strUser = sys.argv[1] strProject = sys.argv[2] except IndexError: print('\n') print('usage : ./Each_base_summary.py user_name project_name\n') print('example : ./Each_base_summary.py SH p53_screening\n') sys.exit() def Make_target_ref_alt_summary(strSample='', strRef='', strAlt='', strFirstOutput=''): """""" row 0: header, 1: A and info, 2: C, 3: G, 4: T Sample Barcode Ref # of Total # of Insertion # of Deletion # of Combination C.-7 T.-6 C.-5 T.-4 G.-3 G.-2 G.-1 G.1 T.2 C.3 A.4 G.5 G.6 G.7 A.8 C.9 A.10 G.11 T.12 G.13 G.14 A.15 C.16 T.17 C.18 G.19 A.20 A.N G.G G.G A.1 G.2 A.3 Doench2014_1000 ACTAGCTATCGCTCA CTCTGGGGTCAGGGACAGTGGACTCGAAGGAGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA 5 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 0 0 0 0 00 0 0 0 0 0 0 0 0 0 0 0 0 0 """""" dAlt = {'A' : 1, 'C' : 2, 'G' : 3, 'T' : 4} lHeader = [] llResult = [] strSampleDir = './Output/{user}/{project}/{sample}'.format(user=strUser, project=strProject, sample=strSample) strSummaryDir = os.path.join(strSampleDir, 'Result') strMergeTargetDir = os.path.join(strSummaryDir, 'Merge_target_result') with open(os.path.join(strMergeTargetDir,strFirstOutput)) as Fisrt_output,\ open(os.path.join(strMergeTargetDir, '{sample}_{ref}to{alt}_Summary_addition.txt'.format(sample=strSample, ref=strRef, alt=strAlt)), 'w') as Output: strSummaryAllDir = os.path.join(strSampleDir,'Tmp/All') for iFile_cnt, sFile in enumerate(os.listdir(strSummaryAllDir)): with open(os.path.join(strSummaryAllDir, sFile)) as Input: lNone_alt_col = [] lBaseEdit_Info = [] for i, sRow in enumerate(Input): lCol = sRow.replace('\n', '').split('\t') if i == 0: for j, sCol_name in enumerate(lCol[7:]): if strRef not in sCol_name: lNone_alt_col.append(7+j) lCol[7+j] = ' ' if lHeader == []: lHeader = lCol elif lHeader: for iHeader_col, tHeader in enumerate(zip(lHeader[7:], lCol[7:])): sHeader_current, sHeader_update = tHeader if sHeader_update == ' ': continue if sHeader_current == ' ': lHeader[iHeader_col+7] = sHeader_update else: assert sHeader_current == sHeader_update, 'Check header %s %s' % (repr(sHeader_current), repr(sHeader_update)) elif i == 1: lBaseEdit_Info = lCol[:7] elif i == dAlt[strAlt]: for iNon_col in lNone_alt_col: lCol[iNon_col] = ' ' lCol[:7] = lBaseEdit_Info #print(i, lCol) #(3, ['Doench2014_1000', 'ACTAGCTATCGCTCA', 'CTCTGGGGTCAGGGACAGTGGACTCGAAGGAGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA', '5', '0', '0', '0', '', '', '', '', '', '', '', '', '', '', '0', '', '', '', '0', '', '0', '', '', '', '', '0', '', '', '', '', '0', '0', '', '', '0', '', '0']) llResult.append(lCol) print('Total_files: ', iFile_cnt + 1) Output.write('\t'.join(lHeader) + '\n') """""" All folder doesn't able to have any indel information if it hasn't any counts of alterantive alleles. That file has only a header. Hence, I check the first merged summary output data, then extract it doesn't have current additional output. """""" dAdditional_output = {} ## dictionary to check for only header files in the 'all' folder. for lResult in llResult: sSample = lResult[0] dAdditional_output[sSample] = '\t'.join(lResult) + '\n' for i, sRow in enumerate(Fisrt_output): if i == 0: continue ## header skip lCol = sRow.replace('\n', '').split('\t') sSample = lCol[0] try: Output.write(dAdditional_output[sSample]) except KeyError: ## Exclusive possession Output.write(sRow) def Main(): with open('./User/{user}/Additional_BaseEdit_process_list.tsv'.format(user=strUser)) as Input: for sRow in Input: if sRow[0] == '#': continue lCol = sRow.replace('\n', '').replace('\r', '').split('\t') if len(lCol) == 1: lCol = lCol[0].split() print(lCol) strSample = lCol[0] listRefAlt = lCol[1].split(',') strRef = listRefAlt[0] strAlt = listRefAlt[1] strFirstOutput = lCol[2] Make_target_ref_alt_summary(strSample=strSample, strRef=strRef, strAlt=strAlt, strFirstOutput=strFirstOutput) Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Sum_all_alt_freq.py",".py","2442","77","#!/media/hkim/7434A5B334A5792E/bin/Python/Python2/bin/python2 import os,sys import numpy as np from pdb import set_trace sProject = sys.argv[1] def Sum_all_freq(): sFile_path = './Output/%s/Summary/All' % sProject sHeader = '' """""" Sample Barcode Ref # of Total # of Insertion # of Deletion # of Combination T.-7 A.-6 G.-5 Doench2014_1001 ATACATAGCTACATG CAGCGGTCAGCTTACTCGACTTAA... 60 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 """""" lSum_total_and_indel_data = [] lSum_target_data = [] for iFile_num, sFile in enumerate(os.listdir(sFile_path)): #print(iFile_num) with open(sFile_path + '/' + sFile) as Input: lSum_target = [] for i, sRow in enumerate(Input): if i == 0: sHeader = sRow continue lCol = sRow.replace('\n','').split('\t') if i == 1: ## This data is in the second row lTotal_and_indel_col = map(int, lCol[3:7]) if lSum_total_and_indel_data == []: lSum_total_and_indel_data = np.zeros((len(lTotal_and_indel_col)), int) lSum_total_and_indel_data += lTotal_and_indel_col lTarget_col = map(int, lCol[7:]) if lSum_target_data == []: lSum_target_data = np.zeros((4, len(lTarget_col)), int) lSum_target.append(lTarget_col) if lSum_target: lSum_target_data += lSum_target print(lSum_target_data) with open('./Output/%s/Summary/Alt_freq.txt' % sProject, 'w') as Output: lHeader = sHeader.split('\t') lHeader[7:] = [sCol.split('.')[1] for sCol in lHeader[7:]] Output.write('Alt_base\t' + '\t'.join(lHeader[3:])) cnt = -1 for sBase, lSum in zip(['A','C','G','T'], lSum_target_data): cnt += 1 if cnt == 0: Output.write(sBase + '\t' + '\t'.join(map(str, lSum_total_and_indel_data)) + '\t' + '\t'.join(map(str, lSum)) + '\n') else: Output.write(sBase + '\t\t\t\t\t' + '\t'.join(map(str, lSum)) + '\n') def Main(): Sum_all_freq() Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Run_BaseEdit_freq.py",".py","12593","260","import os, re, sys, pdb, math, logging import subprocess as sp from pdb import set_trace from datetime import datetime from optparse import OptionParser sys.path.insert(0, os.path.dirname(os.getcwd())) from Core.CoreSystem import InitialFolder, UserFolderAdmin, Helper, RunMulticore, CheckProcessedFiles class clsBaseEditRunner(UserFolderAdmin): def __init__(self, strSample, strRef, options, InstInitFolder): UserFolderAdmin.__init__(self, strSample, strRef, options, InstInitFolder.strLogPath) self.strSample = strSample self._RemoveTmpBeforStart() self.MakeSampleFolder() ## inheritance self.strRef = strRef self.intCore = options.multicore self.strGapOpen = options.gap_open self.strGapExtend = options.gap_extend self.strTargetWindow = options.target_window self.strIndelCheckPos = options.indel_check_pos self.strTargetRefAlt = options.target_ref_alt self.strBarcodeFile = os.path.join(self.strRefDir, 'Barcode.txt') self.strReferenceSeqFile = os.path.join(self.strRefDir, 'Reference.txt') self.strRefFile = os.path.join(self.strRefDir, 'Reference.fa') self.strPamSeq = options.PAM_seq self.strPamPos = options.PAM_pos self.strGuidePos = options.Guide_pos Helper.MakeFolderIfNot('./Output/{user}/{project}/{sample}/Tmp/Alignment'.format(user=self.strUser, project=self.strProject, sample=self.strSample)) def MakeReference(self): with open(self.strBarcodeFile) as Barcode, \ open(self.strReferenceSeqFile) as Ref, \ open(self.strRefFile, 'w') as Output: listBarcode = Helper.RemoveNullAndBadKeyword(Barcode) listRef = Helper.RemoveNullAndBadKeyword(Ref) ## defensive assert len(listBarcode) == len(listRef), 'Barcode and Reference must be a same row number.' dictBarcode = {} for strBarcode in listBarcode: strBarcode = strBarcode.replace('\n','').replace('\r','').upper() Helper.CheckIntegrity(self.strBarcodeFile, strBarcode) ## defensive listBarcode = strBarcode.split(':') strBarSample = listBarcode[0] strBarcode = listBarcode[1] dictBarcode[strBarSample] = strBarcode for strRef in listRef: strRef = strRef.replace('\n','').replace('\r','').upper() Helper.CheckIntegrity(self.strBarcodeFile, strRef) ## defensive listRef = strRef.split(':') strRefSample = listRef[0] strRef = listRef[1] try: sBarcode = dictBarcode[strRefSample] Output.write('%s\t%s\t%s\n' % (strRefSample, sBarcode, strRef)) except KeyError: logging.error('no matching') logging.error(strRefSample,strRef) def MakeIndelSearcherCmd(self): listCmd = [] with open(self.strRefFile) as BarcodeRef: for strBarcodeRef in BarcodeRef: listBarcodeRef = strBarcodeRef.replace('\n', '').replace('\r','').split('\t') strFileName = listBarcodeRef[0] strBarcode = listBarcodeRef[1] strRef = listBarcodeRef[2] self._CheckOptionsCorrect(strBarcode) ## defensive strForwardQueryFile = './Input/{user}/Query/{project}/{sample}/{file_name}.txt'.format (user=self.strUser, project=self.strProject, sample=self.strSample, file_name=strFileName) strCmd = ('{python} ./BaseEdit_freq_crispresso.py {forw} {GapO} {GapE} {barcode} {ref} {target_window} {indel_check_pos}' ' {target_ref_alt} {outdir} {file_name} {PAM_seq} {PAM_pos} {guide_pos} {log}').format( python=self.strPython, forw=strForwardQueryFile, GapO=self.strGapOpen, GapE=self.strGapExtend, barcode=strBarcode, ref=strRef, target_window=self.strTargetWindow, indel_check_pos=self.strIndelCheckPos, target_ref_alt=self.strTargetRefAlt, outdir=self.strOutSampleDir, file_name=strFileName, PAM_seq=self.strPamSeq, PAM_pos=self.strPamPos, guide_pos=self.strGuidePos, log=self.strLogPath) listCmd.append(strCmd) return listCmd def MakeMergeTarget(self): strCmd = '{python} ./Summary_all_trim.py {output} {sample} {ref_alt}'.format(python=self.strPython, output=self.strOutSampleDir, sample=self.strSample, ref_alt=self.strTargetRefAlt) sp.call(strCmd, shell=True) def CopyToAllResultFolder(self): sp.call('cp $(find ./Output/{user}/{project}/*/Result/*Merge* -name ""*_Summary.txt"") ./Output/{user}/{project}/All_results'.format( user=self.strUser, project=self.strProject), shell=True) def _RemoveTmpBeforStart(self): strFolderPath = './Output/{user}/{project}/{sample}'.format(user=self.strUser, project=self.strProject, sample=self.strSample) if os.path.isdir(strFolderPath): strCmd = 'rm -r %s' % strFolderPath Helper.PreventFromRmMistake(strCmd) ## defensive logging.info('Delete the %s folder before starting if these were existed.' % self.strSample) sp.call(strCmd.format(user=self.strUser, project=self.strProject, sample=self.strSample), shell=True) ## defensive def _CheckOptionsCorrect(self, strBarcode): intBarcodeLen = len(strBarcode) intTargetStart = int(self.strTargetWindow.split('-')[0]) intTargetEnd = int(self.strTargetWindow.split('-')[1]) intIndelStart = int(self.strIndelCheckPos.split('-')[0]) intIndelEnd = int(self.strIndelCheckPos.split('-')[1]) intGuideStart = int(self.strGuidePos.split('-')[0]) intGuideEnd = int(self.strGuidePos.split('-')[1]) intPamStart = int(self.strPamPos.split('-')[0]) intPamEnd = int(self.strPamPos.split('-')[1]) intPamLen = len(self.strPamSeq) if intBarcodeLen >= intTargetStart: logging.error('Target window start position must be larger than barcode length') logging.error('Barcode length: %s, Window start: %s' % (intBarcodeLen, intTargetStart)) raise Exception if intTargetStart > intGuideStart or intTargetEnd < intGuideEnd: logging.error('Target window start, end range must be larger than guide range') logging.error('Target window: %s, Guide window: %s' % (self.strTargetWindow, self.strGuidePos)) raise Exception if intIndelStart >= intGuideEnd or intIndelEnd >= intGuideEnd: logging.error('Guide end position must be larger than Indel position') logging.error('Guide end position: %s, Indel position: %s' % (intGuideEnd, self.strIndelCheckPos)) raise Exception if intPamStart <= intGuideEnd or intPamEnd <= intGuideEnd: logging.error('PAM position must be larger than Guide end pos') logging.error('PAM position: %s, Guide end position: %s, ' % (self.strPamPos, intGuideEnd)) raise Exception if (intPamEnd - intPamStart + 1) != intPamLen: logging.error('PAM size and PAM seq must be same length.') logging.error('PAM pos: %s, PAM seq: %s, ' % (self.strPamPos, self.strPamSeq)) raise Exception def Main(): print('BaseEdit program start: %s' % datetime.now()) sCmd = (""BaseEdit frequency analyzer\n\n./Run_BaseEdit_freq.py -t 15 -w 16-48 --indel_check_pos 39-40 --target_ref_alt A,T --PAM_seq NGG --PAM_pos 43-45 --Guide_pos 23-42"" "" --gap_open -10 --gap_extend 1\n\n"" ""The sequence position is the one base position (start:1)\n"" ""1: Barcode\n"" ""2: Base target window (end pos = PAM pos +3)\n"" ""3: Indel check pos\n"" ""4: PAM pos\n"" ""5: Guide pos (without PAM)\n\n"" ""TATCTCTATCAGCACACAAGCATGCAATCACCTTGGGTCCAAAGGTCC\n"" ""<------1------><----------------2--------------->\n"" "" <3> <4> \n"" "" <---------5--------> \n\n"") parser = OptionParser(sCmd) parser.add_option(""-t"", ""--thread"", default=""1"", type=""int"", dest=""multicore"", help=""multiprocessing number"") parser.add_option('--gap_open', default='-10', type='float', dest='gap_open', help='gap open: -100~0') parser.add_option('--gap_extend', default='1', type='float', dest='gap_extend', help='gap extend: 1~100') parser.add_option(""-w"", ""--target_window"", type=""str"", dest=""target_window"", help=""a window size for target sequence : 20-48"") parser.add_option(""--indel_check_pos"", type=""str"", dest=""indel_check_pos"", help=""indel check position to filter : 39-40; insertion 39, deletion 39 & 40"") parser.add_option(""--target_ref_alt"", type=""str"", dest=""target_ref_alt"", help=""Ref 'A' is changed to Alt 'T': A,T"") parser.add_option(""--PAM_seq"", type=""str"", dest=""PAM_seq"", help=""PAM sequence: NGG, NGC ..."") parser.add_option(""--PAM_pos"", type=""str"", dest=""PAM_pos"", help=""PAM position range in the reference seqeunce : 43-45"") parser.add_option(""--Guide_pos"", type=""str"", dest=""Guide_pos"", help=""Guide position range in the reference seqeunce : 23-42"") parser.add_option('--python', dest='python', help='The python path including the CRISPResso2') parser.add_option('--user', dest='user_name', help='The user name with no space') parser.add_option('--project', dest='project_name', help='The project name with no space') options, args = parser.parse_args() InstInitFolder = InitialFolder(options.user_name, options.project_name, os.path.basename(__file__)) InstInitFolder.MakeDefaultFolder() InstInitFolder.MakeInputFolder() InstInitFolder.MakeOutputFolder() logging.basicConfig(format='%(process)d %(levelname)s %(asctime)s : %(message)s', level=logging.DEBUG, filename=InstInitFolder.strLogPath, filemode='a') logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logging.info('Program start') if options.multicore > 15: logging.warning('Optimal threads <= 15') logging.info(str(options)) with open(InstInitFolder.strProjectFile) as Sample_list: listSamples = Helper.RemoveNullAndBadKeyword(Sample_list) strInputProject = './Input/{user}/Query/{project}'.format(user=options.user_name, project=options.project_name) @CheckProcessedFiles def RunPipeline(**kwargs): for strSample in listSamples: if strSample[0] == '#': continue tupSampleInfo = Helper.SplitSampleInfo(strSample) if not tupSampleInfo: continue strSample, strRef, strExpCtrl = tupSampleInfo InstBaseEdit = clsBaseEditRunner(strSample, strRef, options, InstInitFolder) InstBaseEdit.MakeReference() listCmd = InstBaseEdit.MakeIndelSearcherCmd() ###print(lCmd[:5]) RunMulticore(listCmd, options.multicore) ## from CoreSystem.py InstBaseEdit.MakeMergeTarget() InstBaseEdit.CopyToAllResultFolder() RunPipeline(InstInitFolder=InstInitFolder, strInputProject=strInputProject, listSamples=listSamples, logging=logging) print('BaseEdit program end: %s' % datetime.now()) if __name__ == '__main__': Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Split_file.py",".py","915","42","#!/home/hkimlab/anaconda2/bin/python2.7 import sys import subprocess as sp sFile_path = sys.argv[1] iSplit_line = int(sys.argv[2]) #400000 iSplit_num = int(sys.argv[3]) #11 def Split(): with open(sFile_path) as fq: for num in range(1, iSplit_num+1): with open('%s_%s.fq' % (sFile_path, num), 'w') as out: iCount = 0 for sRow in fq: iCount += 1 out.write(sRow) if iCount == iSplit_line: break def Make_filelist(): with open('./LongGuide_Synthetic_2nd.txt', 'w') as filelist: for sFilename in sp.check_output('ls', shell=True).split('\n'): lFilename = sFilename.split('.') #print(lFilename) if lFilename[-1] == 'fq': filelist.write(sFilename+'\n') #Split() Make_filelist() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Make_user_folder.sh",".sh","661","19","#!/bin/bash user=JaeWoo project=JaeWoo_test_samples4 [ ! -d ./Input ] && { `mkdir ./Input`; } [ ! -d ./User ] && { `mkdir ./User`; } [ ! -d ./Output ] && { `mkdir ./Output`; } [ ! -d ./Input/${user} ] && { `mkdir ./Input/${user}`; } [ ! -d ./Input/${user}/Query ] && { `mkdir ./Input/${user}/Query`; } [ ! -d ./Input/${user}/Query/${project} ] && { `mkdir ./Input/${user}/Query/${project}`; } [ ! -d ./Input/${user}/Reference ] && { `mkdir ./Input/${user}/Reference`; } [ ! -d ./Input/${user}/Reference/${project} ] && { `mkdir ./Input/${user}/Reference/${project}`; } [ ! -d ./User/${user} ] && { `mkdir ./User/${user}`; } > ./User/${user}/${project}.txt ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/__init__.py",".py","0","0","","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Indel_contr_dict_making.py",".py","3425","82","#!/extdata1/JaeWoo/Tools/Python/miniconda2/bin/python2.7 import os, sys from pdb import set_trace import cPickle #strSampleFolder = sys.argv[1] def MakeIndelContrDict(): for strSampleFolder in ['18K_D0_1','18K_D0_2','18K_D0_3']: with open('./Output/%s/%s_IndelSubtarction.txt' % (strSampleFolder, strSampleFolder), 'w') as Output: dictSub = {} for strFile in os.listdir('./Output/%s/result' % strSampleFolder): if 'filtered' in strFile: with open('./Output/%s/result/%s' % (strSampleFolder, strFile)) as Input: strBarcodeName = strFile.replace('_filtered_indel.txt','') for strRow in Input: listCol = strRow.replace('\n','').split('\t') #set_trace() strIndelPos = listCol[2].replace(""['"",'').replace(""']"",'') listIndelPos = strIndelPos.split('M') intMatch = int(listIndelPos[0]) strRefseq = listCol[4] strQueryseq = listCol[5] if 'I' in strIndelPos: ## insertion intInsertion = int(listIndelPos[1].replace('I', '')) strInsertseq = strQueryseq[intMatch:intMatch+intInsertion] #set_trace() strInsertPosSeq = strIndelPos+'_'+strInsertseq try: dictSub[strBarcodeName+':'+strInsertPosSeq].append([strInsertPosSeq, strRefseq, strQueryseq]) except KeyError: dictSub[strBarcodeName+':'+strInsertPosSeq] = [[strInsertPosSeq, strRefseq, strQueryseq]] elif 'D' in strIndelPos: intDeletion = int(listIndelPos[1].replace('D', '')) strDeleteSeq = strRefseq[intMatch:intMatch+intDeletion] strDeletePosSeq = strIndelPos+'_'+strDeleteSeq try: dictSub[strBarcodeName+':'+strDeletePosSeq].append([strDeletePosSeq, strRefseq, strQueryseq]) except KeyError: dictSub[strBarcodeName+':'+strDeletePosSeq] = [[strDeletePosSeq, strRefseq, strQueryseq]] for strBarcodeName, list2IndelPosSeq in dictSub.items(): for listIndelPosSeq in list2IndelPosSeq: Output.write('\t'.join([strBarcodeName] + listIndelPosSeq) + '\n') def ConcatContrDict(): DictSubNoDup = {} for strSampleFolder in ['18K_D0_1', '18K_D0_2', '18K_D0_3']: with open('./Output/%s/%s_IndelSubtarction.txt' % (strSampleFolder, strSampleFolder)) as Input: for strRow in Input: listCol = strRow.replace('\n', '').split('\t') try: DictSubNoDup[listCol[0]] += 1 except KeyError: DictSubNoDup[listCol[0]] = 1 #print(DictSubNoDup) with open('./Output/DictSubNoDup.pickle', 'wb') as PickleObj: cPickle.dump(DictSubNoDup, PickleObj) def Main(): #MakeIndelContrDict() ConcatContrDict() Main()","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Run_cmd.sh",".sh","1044","34","#!/bin/bash #################### ## User parameter ## ################################### user=JaeWoo project=JaeWoo_test_samples target_window=20-59 indel_check_pos=50-51 target_ref_alt=A,G PAM_seq=NGG PAM_pos=54-56 Guide_pos=23-53 thread=15 gap_open=-10 ## default gap_extend=1 ## default ################################### while read python_path;do python=$python_path done < ../PythonPath.txt [ ! -d ./Output/${user} ] && { `mkdir ./Output/${user}`; } [ ! -d ./Output/${user}/${project} ] && { `mkdir ./Output/${user}/${project}`; } [ ! -d ./Output/${user}/${project}/Log ] && { `mkdir ./Output/${user}/${project}/Log`; } nohup $python ./Run_BaseEdit_freq.py --python $python --user $user --project $project -w $target_window --indel_check_pos $indel_check_pos \ --target_ref_alt $target_ref_alt --PAM_seq $PAM_seq --PAM_pos $PAM_pos --Guide_pos $Guide_pos \ --gap_open $gap_open --gap_extend $gap_extend -t $thread > ./Output/${user}/${project}/Log/log.txt 2>&1 & ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Kill_jobs.sh",".sh","252","8","#!/bin/bash # Confirm the jobs. # ps aux | grep hkim | grep BaseEdit_freq_ver1.0.py | less kill -9 $(ps aux | grep hkim | grep Run_BaseEdit_freq.py | awk '{print$2}') kill -9 $(ps aux | grep hkim | grep BaseEdit_freq_crispresso.py | awk '{print$2}') ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/MakeUserFolder.sh",".sh","650","19","#!/bin/bash user=SH project=24K_screening [ ! -d ./Input ] && { `mkdir ./Input`; } [ ! -d ./User ] && { `mkdir ./User`; } [ ! -d ./Output ] && { `mkdir ./Output`; } [ ! -d ./Input/${user} ] && { `mkdir ./Input/${user}`; } [ ! -d ./Input/${user}/Query ] && { `mkdir ./Input/${user}/Query`; } [ ! -d ./Input/${user}/Query/${project} ] && { `mkdir ./Input/${user}/Query/${project}`; } [ ! -d ./Input/${user}/Reference ] && { `mkdir ./Input/${user}/Reference`; } [ ! -d ./Input/${user}/Reference/${project} ] && { `mkdir ./Input/${user}/Reference/${project}`; } [ ! -d ./User/${user} ] && { `mkdir ./User/${user}`; } > ./User/${user}/${project}.txt ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Run_sequence_freq.sh",".sh","388","22","#!/bin/bash #################### ## User parameter ## ################################### user=SH project=24K_screening window=25-34 thread=4 ################################### while read python_path;do python=$python_path done < ../PythonPath.txt nohup $python ./Sequence_freq.py $user $project $window $thread > ./Output/${user}/${project}/Log/Sequence_freq_log.txt 2>&1 & ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Sequence_freq_add.py",".py","8986","216","#!/home/hkim/anaconda2/bin/python2.7 from pdb import set_trace ## D0 Sub list """""" Euchromatin_206_repeat5 TCTATCGTACATCGC Euchromatin_206_repeat5:39M2D_AC 1 ExtremeGC_811 CTACATCGTCATACA ExtremeGC_811:39M1D_G 1 """""" #strSubHiseq1 = './Sub_indel_result/Summation_Project_list_sub_indel.txt' ## total indel cnt : 8929 #strSubHiseq2 = './Sub_indel_result/Summation_Project_list2_sub_indel.txt' ## total indel cnt : 8367 #strSubNeon1 = './Sub_indel_result/Summation_Project_list3_sub_indel.txt' ## total indel cnt : 9396 #3strSubNeon2 = './Sub_indel_result/Summation_Project_list4_sub_indel.txt' ## total indel cnt : 8321 strSubHiseq1 = './Output/Summation_Project_list_sub_indel.txt' ## total indel cnt : 8929 strSubHiseq2 = './Output/Summation_Project_list2_sub_indel.txt' ## total indel cnt : 8367 strSubNeon1 = './Output/Summation_Project_list3_sub_indel.txt' ## total indel cnt : 9396 strSubNeon2 = './Output/Summation_Project_list4_sub_indel.txt' ## total indel cnt : 8321 ## Total sum file """""" Sample Barcode Ref # of Total # of Insertion # of Deletion # of Combination A.-7 0 Doench2014_1 CGCATATCATCATCA TAGATTGAAGAGAGACAGTACATGCCCTGGGAGAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA 322 0 0 0 0 """""" strTotalHiseq1 = './Output/Summation_Project_list.txt' strTotalHiseq2 = './Output/Summation_Project_list2.txt' strTotalNeon1 = './Output/Summation_Project_list3.txt' strTotalNeon2 = './Output/Summation_Project_list4.txt' ## Freq result file """""" Filename Seq Motif Count Total_cnt Proportion Substitution Doench2014_1 CGCATATCATCATCATAGATTGAAGAGAGACAGTACATGCCCTGGGAGAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA AGAGAGACA 246 257 0.9572 wt """""" strFreqHiseq1 = './Output/Group_result/180903_split_hiseq_R1/Seq_freq.txt' strFreqHiseq2 = './Output/Group_result/180903_split_hiseq_R2/Seq_freq.txt' strFreqNeon1 = './Output/Group_result/190311_Neon_splitBE4_R1/Seq_freq.txt' strFreqNeon2 = './Output/Group_result/190311_Neon_splitBE4_R2/Seq_freq.txt' ## Result """""" Filename Seq Motif Count Total_cnt Proportion Substitution Doench2014_1 CGCATATCATCATCATAGATTGAAGAGAGACAGTACATGCCCTGGGAGAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA AGAGAGACA 246 257-(D0 indel count) 0.9572 wt -> next line + indelcompelex sum count """""" strResultHiseq1 = './Output/Seq_freq_add_info_Hiseq1.txt' strResultHiseq2 = './Output/Seq_freq_add_info_Hiseq2.txt' strResultNeon1 = './Output/Seq_freq_add_info_Neon1.txt' strResultNeon2 = './Output/Seq_freq_add_info_Neon2.txt' def Add_info_result(strSub, strTotal, strFreq, strResult): with open(strSub) as Sub,\ open(strTotal) as Total,\ open(strFreq) as Freq,\ open(strResult, 'w') as Result: dictSubCnt = {} ## Doench2016_1948:39M1D_G, Doench2016_1948:39M1I_G -> Neon: two file name is same but the pattern is different. ## I should merge these pattern based on the file name. dictTotalAppliedSub = {} dictIndelSum = {} for strRow in Sub: listCol = strRow.replace('\n', '').split('\t') strFile = listCol[0] intCount = int(listCol[3]) try: dictSubCnt[strFile] += intCount except KeyError: dictSubCnt[strFile] = intCount # intSubIndelAllCnt = sum([v for k,v in dictSubCnt.items()]) # print('%s sub indel all count : %s' % (strSub, intSubIndelAllCnt)) ## checked all count is correct. #"""""" for i, strRow in enumerate(Total): if i == 0: continue ## header skip. listCol = strRow.replace('\n', '').split('\t') strFile = listCol[1] intTotal = int(listCol[4]) intIns = int(listCol[5]) intDel = int(listCol[6]) intCom = int(listCol[7]) try: intSub = dictSubCnt[strFile] except KeyError: intSub = 0 intTotalAppliedSub = intTotal - intSub ## The total count is not subtracted by DOindel, so apply it. dictTotalAppliedSub[strFile] = intTotalAppliedSub dictIndelSum[strFile] = intIns + intDel + intCom ## each file row indel complex count sum dictFreq = {} ## {'GECKO_346': [[Filename Seq Motif Count Total_cnt Proportion Substitution],[],[],[]]} strHeader = '' for i, strRow in enumerate(Freq): ## Freq total was removed by crispr indel. if i == 0: strHeader = strRow continue ## header skip. listCol = strRow.replace('\n', '').split('\t') strFile = listCol[0] intCount = int(listCol[3]) intTotal = int(listCol[4]) floProp = float(listCol[5]) listCol[3] = intCount listCol[4] = intTotal listCol[5] = floProp try: dictFreq[strFile].append(listCol) except KeyError: dictFreq[strFile] = [listCol] Result.write(strHeader.replace('\n','')+'\tTotal(D0)\tD0_indel\n') for strFile, list2Col in dictFreq.items(): list2Col[1:] = sorted(list2Col[1:], key=lambda x: x[5], reverse=True) ## sort by proportion intAltAllCnt = sum([listAlt[3] for listAlt in list2Col[1:]]) ## for validation listCountCheck = [] intTotalCheck = 0 for i, listCol in enumerate(list2Col): strSubstitution = listCol[6] intTotal = listCol[4] intTotalAppliedSub = dictTotalAppliedSub[strFile] intIndelSum = dictIndelSum[strFile] ## intIns + intDel + intCom intTotalD0 = intTotal + intIndelSum ## freq total are substrated by indel sum, so add it again intD0IndelCount = intTotalD0 - intTotalAppliedSub if strSubstitution == 'wt': ## modify WT count. Total - alt count = wt count intModiCount = intTotalAppliedSub - intAltAllCnt - intIndelSum if intModiCount < 0: print('minus value error, this integer is positive.') set_trace() listCol[3] = intModiCount #if listCol[0] == 'GECKO_7232': Neon1, 2761 # set_trace() listCountCheck.append(listCol[3]) ## for validation listCol[4] = intTotalAppliedSub try: listCol[5] = round(float(listCol[3]) / listCol[4], 4) except Exception: listCol[5] = 0 Result.write('\t'.join(map(str, listCol + [intTotalD0, intD0IndelCount]))+'\n') if i == 0: listCountCheck.append(intIndelSum) intTotalCheck = listCol[4] ## for validation listResultCol = len(listCol) * ['~'] + ['~', '~'] listResultCol[0] = strFile listResultCol[6] = 'Indel' listResultCol[3] = intIndelSum Result.write('\t'.join(map(str, listResultCol))+'\n') #if strFile == 'GECKO_7232': # set_trace() intCountCheckTotal = sum(listCountCheck) if intCountCheckTotal != intTotalCheck: print('Count total is diffrent. result:%s, file:%s, CountCheckTotal:%s, TotalCheck:%s' % (strResult, strFile, intCountCheckTotal, intTotalCheck)) #"""""" def Main(): for strSub, strTotal, strFreq, strResult in [[strSubHiseq1, strTotalHiseq1, strFreqHiseq1, strResultHiseq1], [strSubHiseq2, strTotalHiseq2, strFreqHiseq2, strResultHiseq2], [strSubNeon1, strTotalNeon1, strFreqNeon1, strResultNeon1], [strSubNeon2, strTotalNeon2, strFreqNeon2, strResultNeon2]]: Add_info_result(strSub, strTotal, strFreq, strResult) Main() """""" ## deprecated def Merge_sub_indel_and_dict(strInput1, strInput2): dictSubIndel = {} with open(strInput1) as Input1, \ open(strInput2) as Input2: for strRow in Input1: listCol = strRow.replace('\n', '').split('\t') strFile = listCol[0] strBarcode = listCol[1] strPattern = listCol[2] intCount = int(listCol[3]) dictSubIndel[strFile] = [strBarcode, strPattern, intCount] for strRow in Input2: listCol = strRow.replace('\n', '').split('\t') strFile = listCol[0] intCount = int(listCol[3]) dictSubIndel[strFile][2] += intCount """"""","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/BaseEdit_freq_crispresso.py",".py","26336","525","import os, re, sys, logging import numpy as np import subprocess as sp import cPickle as pickle from pdb import set_trace from datetime import datetime from collections import OrderedDict sys.path.insert(0, os.path.dirname(os.getcwd())) from Core.CoreSystem import CoreGotoh class clsParameter(object): """""" ./BaseEdit_freq_crispresso.py {forw} {GapO} {GapE} {barcode} {ref} {target_window} {indel_check_pos} {target_ref_alt} {outdir} {file_name} {PAM_seq} {PAM_pos} {Guide_pos} {ednafull} {log} """""" def __init__(self): if len(sys.argv) > 1: self.strForwPath = sys.argv[1] self.floOg = float(sys.argv[2]) self.floOe = float(sys.argv[3]) self.strBarcode = sys.argv[4] strRef = sys.argv[5] self.strRef = strRef[strRef.index(self.strBarcode):] ## 'ACTG'ACGACACACGCAT, leftside bases are redundant. self.listTargetWindow = sys.argv[6].split('-') self.listIndelCheckPos = sys.argv[7].split('-') self.listTargetRefAlt = sys.argv[8].split(',') self.strOutputDir = sys.argv[9] self.strFileName = sys.argv[10] self.strPamSeq = sys.argv[11] self.listPamPos = sys.argv[12].split('-') self.listGuidePos = sys.argv[13].split('-') self.strEDNAFULL = os.path.abspath('../EDNAFULL') self.strLogPath = sys.argv[14] else: sManual = """""" Usage: python2.7 ./indel_search_ver1.0.py splitted_input_1.fq splitted_input_2.fq reference.fa splitted_input_1.fq : forward splitted_input_2.fq : reverse Total FASTQ(fq) lines / 4 = remainder 0. """""" print sManual sys.exit() class clsBaseEditParser(): def __init__(self, InstParameter): self.strForwPath = InstParameter.strForwPath self.strRef = InstParameter.strRef self.strBarcode = InstParameter.strBarcode self.strEDNAFULL = InstParameter.strEDNAFULL self.floOg = InstParameter.floOg self.floOe = InstParameter.floOe self.listIndelCheckPos = InstParameter.listIndelCheckPos self.listTargetWindow = InstParameter.listTargetWindow def OpenSequenceFiles(self): lSequence_forward = [] with open(self.strForwPath) as fa_1: lSequence_forward = [sRow.replace('\n', '').upper() for sRow in fa_1] return lSequence_forward def CalculateBaseEditFreq(self, lQuery_seq=[]): dRef = {} dResult = {} dRef[self.strBarcode] = (self.strRef) # total matched reads, insertion, deletion, complex dResult[self.strBarcode] = [0, 0, 0, 0, [], [], [], [], [], [], []] # lRef : [(ref_seq, ref_seq_after_barcode, barcode, barcode end pos, indel end pos, indel from barcode),(...)] # dResult = [# of total, # of ins, # of del, # of com, [total FASTQ], [ins FASTQ], [del FASTQ], [com FASTQ], info] iCount = 0 InstGotoh = CoreGotoh(strEDNAFULL=self.strEDNAFULL, floOg=self.floOg, floOe=self.floOe) for sQuery_seq_raw in lQuery_seq: iBarcode_matched = 0 iNeedle_matched = 0 iInsert_count = 0 iDelete_count = 0 iComplex_count = 0 try: # Check the barcode pos and remove it. sQuery_seq_raw = sQuery_seq_raw.replace('\r', '') iBarcode_start_pos = sQuery_seq_raw.index(self.strBarcode) iBarcode_matched += 1 sQuery_seq_with_barcode = sQuery_seq_raw[iBarcode_start_pos:] ## this is not after barcode seq. including barcode npGapIncentive = InstGotoh.GapIncentive(self.strRef) try: lResult = InstGotoh.RunCRISPResso2(sQuery_seq_with_barcode.upper(), self.strRef.upper(), npGapIncentive) except Exception as e: logging.error(e, exc_info=True) continue sQuery_needle_ori = lResult[0] sRef_needle_ori = lResult[1] # if _check == 1: # print(sRef_needle_ori) # print(sQuery_needle_ori) # set_trace() # detach forward ---, backward --- # e.g. ref ------AAAGGCTACGATCTGCG------ # query AAAAAAAAATCGCTCTCGCTCTCCGATCT # trimmed ref AAAGGCTACGATCTGCG # trimmed qeury AAATCGCTCTCGCTCTC iReal_ref_needle_start = 0 iReal_ref_needle_end = len(sRef_needle_ori) iRef_needle_len = len(sRef_needle_ori) for i, sRef_nucle in enumerate(sRef_needle_ori): if sRef_nucle in ['A', 'C', 'G', 'T']: iReal_ref_needle_start = i break for i, sRef_nucle in enumerate(sRef_needle_ori[::-1]): if sRef_nucle in ['A', 'C', 'G', 'T']: iReal_ref_needle_end = iRef_needle_len - (i + 1) # forward 0 1 2 len : 3 # reverse 2 1 0, len - (2 + 1) = 0 break sRef_needle = sRef_needle_ori[iReal_ref_needle_start:iReal_ref_needle_end + 1] if iReal_ref_needle_start: sQuery_needle = sQuery_needle_ori[:iReal_ref_needle_end] sQuery_needle = sQuery_needle_ori[:len(sRef_needle)] # detaching completion # indel info making. iNeedle_match_pos_ref = 0 iNeedle_match_pos_query = 0 iNeedle_insertion = 0 iNeedle_deletion = 0 lInsertion_in_read = [] # insertion result [[100, 1], [119, 13]] lDeletion_in_read = [] # deletion result [[97, 1], [102, 3]] # print 'sRef_needle', sRef_needle # print 'sQuery_needle', sQuery_needle for i, (sRef_nucle, sQuery_nucle) in enumerate(zip(sRef_needle, sQuery_needle)): if sRef_nucle == '-': iNeedle_insertion += 1 if sQuery_nucle == '-': iNeedle_deletion += 1 if sRef_nucle in ['A', 'C', 'G', 'T']: if iNeedle_insertion: lInsertion_in_read.append([iNeedle_match_pos_ref, iNeedle_insertion]) iNeedle_insertion = 0 iNeedle_match_pos_ref += 1 if sQuery_nucle in ['A', 'C', 'G', 'T']: if iNeedle_deletion: lDeletion_in_read.append([iNeedle_match_pos_query, iNeedle_deletion]) iNeedle_match_pos_query += iNeedle_deletion iNeedle_deletion = 0 iNeedle_match_pos_query += 1 # print 'sRef_needle', sRef_needle # print 'sQuery_needle', sQuery_needle # print 'lInsertion_in_read: onebase', lInsertion_in_read # print 'lDeletion_in_read: onebase', lDeletion_in_read # print 'i5bp_front_Indel_end', i5bp_front_Indel_end # print 'iIndel_end_from_barcode_pos', iIndel_end_from_barcode_pos lTarget_indel_result = [] # ['20M2I', '23M3D' ...] """""" ins case ...............................NNNNNNNNNNNNNN....NNNNNNNNNNNNNNNNNNN*NNNNNAGCTT """""" iCleavage_window_start = int(self.listIndelCheckPos[0]) iCleavage_window_end = int(self.listIndelCheckPos[1]) - 1 for iMatch_pos, iInsertion_pos in lInsertion_in_read: if iCleavage_window_start <= iMatch_pos <= iCleavage_window_end: # iMatch_pos is one base iInsert_count = 1 lTarget_indel_result.append(str(iMatch_pos) + 'M' + str(iInsertion_pos) + 'I') """""" del case 1 ...............................NNNNNNNNNNNNNN....NNNNNNNNNNNNNNNNNNNNN**NNNAGCTT del case 2 ...............................NNNNNNNNNNNNNN....NNNNNNNNNNNNNNNNNNNNN**NNNNNCTT """""" for iMatch_pos, iDeletion_pos in lDeletion_in_read: """""" Insertion: 30M3I ^ ACGT---ACGT ACGTTTTACGT -> check this seq Insertion just check two position Deletion: 30M3D ^ ACGTTTTACGT ACGT---ACGT -> check this seq But deletion has to includes overlap deletion. """""" if iMatch_pos <= iCleavage_window_end and iCleavage_window_start <= (iMatch_pos + iDeletion_pos): iDelete_count = 1 lTarget_indel_result.append(str(iMatch_pos) + 'M' + str(iDeletion_pos) + 'D') if iInsert_count == 1 and iDelete_count == 1: iComplex_count = 1 iInsert_count = 0 iDelete_count = 0 # """""" test set # print 'sBarcode', sBarcode # print 'sTarget_region', sTarget_region # print 'sRef_seq_after_barcode', sRef_seq_after_barcode # print 'sSeq_after_barcode', sQuery_seq # print 'iIndel_start_from_barcode_pos', iIndel_start_from_barcode_pos # print 'iIndel_end_from_barcode_pos', iIndel_end_from_barcode_pos # """""" """""" 23M3I 23M is included junk_seq after barcode, barcorde junk targetseq others *********ACCCT-------------ACACACACC so should select target region. If junk seq is removed by target region seq index pos. """""" ## 8: indel info dResult[self.strBarcode][8].append( [self.strRef, sQuery_seq_raw, lTarget_indel_result, """", sRef_needle_ori, sQuery_needle_ori]) ## """" -> target seq, but this is not used this project. # end: try except ValueError as e: print(e) continue # total matched reads, insertion, deletion, complex dResult[self.strBarcode][0] += iBarcode_matched dResult[self.strBarcode][1] += iInsert_count dResult[self.strBarcode][2] += iDelete_count dResult[self.strBarcode][3] += iComplex_count ## base editing frequency """""" BaseEditPos : 0 1 2 [OrderedDict([('A',0),('C',0),('G',0),('T',0)]), OrderedDict([('A',0),('C',0),('G',0),('T',0)]), ... and sum the counts each position """""" ## No indel reads only if iInsert_count == 0 and iDelete_count == 0 and iComplex_count == 0: lBaseEdit = [] iTarget_len = int(self.listTargetWindow[1]) - int(self.listTargetWindow[0]) + 1 for i in range(iTarget_len): lBaseEdit.append(OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)])) iTarget_start = int(self.listTargetWindow[0]) - 1 iTarget_end = int(self.listTargetWindow[1]) """""" cleavage window start ^ [barcode]ACGACGTACGACGT[cleavage] [barcode]ACGACGTACGACGT[cleavage] """""" iBase_edit_event = 0 for i, tRef_Query_base in enumerate(zip(sRef_needle[iTarget_start: iTarget_end], sQuery_needle[iTarget_start: iTarget_end])): sRef_base = tRef_Query_base[0] sQuery_base = tRef_Query_base[1] if sRef_base == '-' or sQuery_base == '-': continue if sRef_base != sQuery_base and sQuery_base != 'N': iBase_edit_event = 1 lBaseEdit[i][sQuery_base] += 1 # print(sQuery_needle) dResult[self.strBarcode][9].append(lBaseEdit) ## Processed indel filtering and store aligned alt mut read. if iBase_edit_event == 1: dResult[self.strBarcode][10].append([self.strRef, sQuery_seq_raw, lTarget_indel_result, [list(orderedDict.values()) for orderedDict in lBaseEdit], sRef_needle_ori, sQuery_needle_ori]) # dResult[sBarcode] = [0, 0, 0, 0, [], [], [], [], [], [BaseEdit_freq_data]] iBarcode_matched = 0 iInsert_count = 0 iDelete_count = 0 iComplex_count = 0 # end: for sBarcode, lCol_ref # end: for lCol_FASTQ return dResult class clsOutputMaker(): def __init__(self, InstParameter): self.strForwPath = InstParameter.strForwPath self.strRef = InstParameter.strRef self.strFileName = InstParameter.strFileName self.strOutputDir = InstParameter.strOutputDir self.listTargetRefAlt = InstParameter.listTargetRefAlt self.listTargetWindow = InstParameter.listTargetWindow self.strPamSeq = InstParameter.strPamSeq self.listPamPos = InstParameter.listPamPos self.listGuidePos = InstParameter.listGuidePos # index name, constant variable. self.intNumOfTotal = 0 self.intNumOfIns = 1 self.intNumOfDel = 2 self.intNumOfCom = 3 self.intTotalFastq = 4 self.intInsFastq = 5 self.intDelFastq = 6 self.intComFastq = 7 self.intIndelInfo = 8 def MakeOutput(self, dResult): """""" {'TTTGGTGCACACACATATA': [6, 2, 2, 0, [], [], [], [], [['TATCTCTA..ref', 'GAGTCGGTG...query', [13M5D], '', 'TTTGGTGCACACACATATAACTGGAACACAAAGCATAGACTGCGGGGCG------------------------------------------------------------', 'TTTGGTGCACACACATATAACTGGAACACAAAGCATAGA-TGCGGGGCGTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA'], ['TTTGGTGCACACACATATAACTGGAACACAAAGCATAGACTGCGGGGCG', '', '', '', 'TTTGGTGCACACACATATAACTGGAACACAAAGCATAGACTGCGGGGCG------------------------------------------------------------', ... [[OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 1)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)])], [OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 1)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)]), OrderedDict([('A', 0), ('C', 0), ('G', 0), ('T', 0)])]]]} """""" with open('{outdir}/Tmp/Alignment/{file_name}_filtered_indel.txt'.format(outdir=self.strOutputDir, file_name=self.strFileName), 'w') as Filtered,\ open('{outdir}/Tmp/Alignment/{file_name}_aligned_BaseEdit.txt'.format(outdir=self.strOutputDir, file_name=self.strFileName), 'w') as Ref_Alt_edit: for sBarcode in dResult: for lAligned_indel_result in dResult[sBarcode][8]: # 8 : indel list if lAligned_indel_result[2]: Filtered.write('\t'.join(map(str, lAligned_indel_result)) + '\n') for lAligned_alt_result in dResult[sBarcode][10]: # 10 : alt base list if lAligned_alt_result: lAligned_alt_result[2] = str(lAligned_alt_result[2]) try: Ref_Alt_edit.write('\t'.join(map(str, lAligned_alt_result)) + '\n') except Exception: set_trace() """""" lAligned_result ['TATCTCTATCAGCACACAAGCATGCAATCACCTTGGGTCCAAAGGTCC', 'TCTTGAAAAAGTGGCACCGAGTCGGTGCTTTTTTGTATCTCTATCAGCACACAAGCATGCAATCACCTTGGGTCAAAGGTCCAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAAT\r', ['38M1D'], '', 'TATCTCTATCAGCACACAAGCATGCAATCACCTTGGGTCCAAAGGTCC-----------------------------------------------------------------', 'TATCTCTATCAGCACACAAGCATGCAATCACCTTGGGT-CAAAGGTCCAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAAT'] """""" dSelect_base = {'A': 0, 'C': 1, 'G': 2, 'T': 3} sTarget_ref = self.listTargetRefAlt[0] sTarget_alt = self.listTargetRefAlt[1] iTarget_base = dSelect_base[sTarget_alt] try: if not os.path.isdir('{outdir}/Tmp/All'.format(outdir=self.strOutputDir)): os.mkdir('{outdir}/Tmp/All'.format(outdir=self.strOutputDir)) if not os.path.isdir('{outdir}/Tmp/Target'.format(outdir=self.strOutputDir)): os.mkdir('{outdir}/Tmp/Target'.format(outdir=self.strOutputDir)) except OSError: pass for sBarcode, lValue in dResult.items(): iBarcode_start_pos = self.strRef.index(sBarcode) sRef_seq_without_barcode = self.strRef[iBarcode_start_pos+len(sBarcode):] llBaseEdit = lValue[9] lSum = [] for i, lBaseEdit in enumerate(llBaseEdit): if not lSum: lSum = [[0, 0, 0, 0] for iQuery in range(len(lBaseEdit))] for j in range(len(lBaseEdit)): for k, iCount in enumerate(list(llBaseEdit[i][j].values())): lSum[j][k] += iCount with open('{outdir}/Tmp/All/{file_name}_Summary.txt'.format(outdir=self.strOutputDir, file_name=self.strFileName), 'w') as Summary, \ open('{outdir}/Tmp/Target/{file_name}_{target}_Summary.txt'.format(outdir=self.strOutputDir, file_name=self.strFileName, target=sTarget_ref + 'to' + sTarget_alt), 'w') as Target_summary: ## This Ref has barcode. sRef_target = self.strRef[int(self.listTargetWindow[0]) - 1:int(self.listTargetWindow[1])] iPAM_start = int(self.listPamPos[0]) - 1 iPAM_end = int(self.listPamPos[1]) iGuide_start = int(self.listGuidePos[0]) - 1 iGuide_end = int(self.listGuidePos[1]) iGuide_len = iGuide_end - iGuide_start iBarcode_len = len(sBarcode) """""" barcode Guide st,ed <----><----------> NGG ACGTACGTACGTACGTACGTGGACG """""" #sRef_target[iPAM_start:iPAM_end] = sPAM_seq ## iWithout_target_len = len(sRef_target[iBarcode_len:iGuide_start]) -> weird part. ## So I corrected it. iWithout_target_len = iGuide_start - iBarcode_len lWithout_target_pos = [-(i+1) for i in range(iWithout_target_len)][::-1] lWith_target_pos = [i + 1 for i in range(iGuide_len)] lAfter_PAM_pos = [i + 1 for i in range(len(self.strRef) - iPAM_end + 1)] lPos_num = lWithout_target_pos + lWith_target_pos + list(self.strPamSeq) + lAfter_PAM_pos lPos_annotated_ref = [str(i)+'.'+str(j) for i,j in zip(sRef_target, lPos_num)] ## ['A.-7', 'C.-6', 'A.-5', 'A.-4', 'G.-3', 'C.-2', 'A.-1', 'T.1', 'G.2', 'C.3', 'A.4', 'A.5', 'T.6', 'C.7', 'A.8', 'C.9', 'C.10', 'T.11', 'T.12', 'G.13', 'G.14', lMasked_pos_annotated_ref_target = [] ## '' '' '' A '' '' '' A A '' '' for sBase_pos in lPos_annotated_ref: sBase_only = sBase_pos.split('.')[0] if sBase_only != sTarget_ref: lMasked_pos_annotated_ref_target.append(' ') else: lMasked_pos_annotated_ref_target.append(sBase_pos) #set_trace() strFormat = ""{sample}\t{bar}\t{ref}\t{NumTot}\t{NumIns}\t{NumDel}\t{NumCom}\t{BaseEditCount}\n"" ## Making a header Summary.write(""Sample\tBarcode\tRef\t# of Total\t# of Insertion\t# of Deletion\t# of Combination\t{refseq}\n"".format(refseq='\t'.join(lPos_annotated_ref))) Target_summary.write(""Sample\tBarcode\tRef\t# of Total\t# of Insertion\t# of Deletion\t# of Combination\t{refseq}\n"".format(refseq='\t'.join(lMasked_pos_annotated_ref_target))) for i, lBase_count in enumerate(zip(*lSum)): ## lBase_count [(0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), (0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0)] if i == 0: Summary.write(strFormat.format(sample=self.strFileName, bar=sBarcode, ref=sRef_seq_without_barcode, NumTot=lValue[self.intNumOfTotal], NumIns=lValue[self.intNumOfIns], NumDel=lValue[self.intNumOfDel], NumCom=lValue[self.intNumOfCom], BaseEditCount='\t'.join(map(str, lBase_count)))) else: Summary.write(""\t\t\t\t\t\t\t{BaseEditCount}\n"".format(BaseEditCount='\t'.join(map(str, lBase_count)))) try: lTarget_base_count = zip(*lSum)[iTarget_base] lMasked_target_base_count = [] ## '' 20 '' 30 '' '' '' '' 20 '' for sMasked_ref, fCount in zip(lMasked_pos_annotated_ref_target, lTarget_base_count): if sMasked_ref == ' ': lMasked_target_base_count.append(' ') else: lMasked_target_base_count.append(fCount) Target_summary.write((strFormat.format(sample=self.strFileName, bar=sBarcode, ref=sRef_seq_without_barcode, NumTot=lValue[self.intNumOfTotal], NumIns=lValue[self.intNumOfIns], NumDel=lValue[self.intNumOfDel], NumCom=lValue[self.intNumOfCom], BaseEditCount='\t'.join(map(str, lMasked_target_base_count))))) except IndexError: print('Null query: ', self.strForwPath) ## Null query base count is all zero. Target_summary.write( (strFormat.format(sample=self.strFileName, bar=sBarcode, ref=sRef_seq_without_barcode, NumTot=lValue[self.intNumOfTotal], NumIns=lValue[self.intNumOfIns], NumDel=lValue[self.intNumOfDel], NumCom=lValue[self.intNumOfCom], BaseEditCount='\t'.join(['0'] * len(lPos_annotated_ref))))) def Main(): InstParameter = clsParameter() logging.basicConfig(format='%(process)d %(levelname)s %(asctime)s : %(message)s', level=logging.DEBUG, filename=InstParameter.strLogPath, filemode='a') logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) # Output: 1. Count information of matched barcode e.g. TACGATCTA\t# total\tins\t# del\t# com # Output: 2. classify FASTQ. e.g. TAGAATATACACG.insertion.fastq logging.info('Program start : %s' % InstParameter.strFileName) InstParser = clsBaseEditParser(InstParameter) logging.info('File Open : %s' % InstParameter.strFileName) listSequenceForward = InstParser.OpenSequenceFiles() logging.info('Calculate base edit frequency : %s' % InstParameter.strFileName) dictResultForward = InstParser.CalculateBaseEditFreq(listSequenceForward) logging.info('Make output forward : %s' % InstParameter.strFileName) InstOutput = clsOutputMaker(InstParameter) InstOutput.MakeOutput(dictResultForward) logging.info('Program end : %s' % InstParameter.strFileName) # end: def Main if __name__ == '__main__': Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Indel_frequency_calculator.py",".py","4984","120","#!/home/hkimlab/anaconda2/bin/python2.7 import os import sys import pdb from datetime import datetime from collections import namedtuple as nt from collections import OrderedDict sOutput_dir = sys.argv[1] def Calculate_indel_freq(): if not os.path.isdir('{outdir}/result/freq/freq_result'.format(outdir=sOutput_dir)): os.mkdir('{outdir}/result/freq/freq_result'.format(outdir=sOutput_dir)) for sFile in os.listdir('{outdir}/result/freq'.format(outdir=sOutput_dir)): #print sFile if os.path.isfile(os.path.join('{outdir}/result/freq'.format(outdir=sOutput_dir), sFile)): with open(os.path.join('{outdir}/result/freq'.format(outdir=sOutput_dir), sFile)) as Input_freq,\ open(os.path.join('{outdir}/result/freq/freq_result'.format(outdir=sOutput_dir), sFile), 'w') as Output_freq: sRef = Input_freq.readline() # first row is ref. sDelemiter = Input_freq.readline() # second row is '-------' delemiter. Output_freq.write(sRef+sDelemiter) lSeq_indel = [] # [namedtuple1(['TGCA', '30M3I']) namedtuple2 ... dFreq_count = {} # {'30M3I':2 ... } for sRow in Input_freq: Seq_indel = nt('Seq_indel', ['seq', 'indel', 'freq', 'ref_needle', 'query_needle']) if sRow == sRef: continue if sRow[0] == '-': continue try: lCol = sRow.replace('\n', '').split('\t') Seq_indel.seq = lCol[0] Seq_indel.indel = lCol[1] Seq_indel.ref_needle = lCol[3] Seq_indel.query_needle = lCol[4] lSeq_indel.append(Seq_indel) except IndexError: print sFile, lCol continue try: dFreq_count[Seq_indel.indel] += 1 except KeyError: dFreq_count[Seq_indel.indel] = 1 #end: for sRow # Add freq infomation pre-result data. lResult = [] iTotal = len(lSeq_indel) #print 'dFreq_count', dFreq_count #print 'lSeq_indel', lSeq_indel for Seq_indel in lSeq_indel: iCount = dFreq_count[Seq_indel.indel] Seq_indel.freq = float(iCount) / iTotal lResult.append(Seq_indel) lResult.sort(key=lambda x: x.indel) lResult.sort(key=lambda x: x.freq, reverse=True) #print 'lResult', lResult for Seq_indel in lResult: #print Seq_indel.__dict__ Output_freq.write('\t'.join(map(str, [Seq_indel.seq, Seq_indel.indel, Seq_indel.freq, Seq_indel.ref_needle, Seq_indel.query_needle]))+'\n') #end: with open #end: if os.path #end: sFile def Make_indel_summary(): lOutput = [] for sFile in os.listdir('{outdir}/result/freq/freq_result'.format(outdir=sOutput_dir)): if os.path.isfile(os.path.join('{outdir}/result/freq/freq_result'.format(outdir=sOutput_dir), sFile)): with open(os.path.join('{outdir}/result/freq/freq_result'.format(outdir=sOutput_dir), sFile)) as Input_freq: sRef = Input_freq.readline() # first row is ref. sDelemiter = Input_freq.readline() # second row is '-------' delemiter. dINDEL = OrderedDict() lTable = [sRow.replace('\n', '').split('\t') for sRow in Input_freq] iTotal = len(lTable) for lCol in lTable: sINDEL = lCol[1] try: dINDEL[sINDEL] += 1 except KeyError: dINDEL[sINDEL] = 1 dINDEL = OrderedDict(sorted(dINDEL.items(), key=lambda t: t[1], reverse=True)) llINDEL = [[sKey, iValue, round(iValue/float(iTotal),3)*100] for sKey, iValue in dINDEL.items()] sINDEL_result = ''.join([':'.join(map(str, lINDEL))+', ' for lINDEL in llINDEL])[:-2] lOutput.append([sFile, iTotal, sINDEL_result]) #Output_freq.write('\t'.join([sFile, sTotal, sINDEL_result]) + '\n') lOutput = sorted(lOutput, key=lambda x: x[1], reverse=True) with open('{outdir}/result/freq/freq_result/Indel_summary.txt'.format(outdir=sOutput_dir), 'w') as Output_freq: for lCol in lOutput: Output_freq.write('\t'.join(map(str, lCol)) + '\n') if __name__ == '__main__': print 'Indel frequency calculator start: ', datetime.now() Calculate_indel_freq() Make_indel_summary() print 'Indel frequency calculator end: ', datetime.now() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/All_final_result_summation.py",".py","4313","113","#!/usr/bin/env python import os, sys import pandas as pd from pdb import set_trace strProjectList = sys.argv[1] #strProjectList = 'Project_list2.txt' def Summation_all_final_result(): with open(strProjectList) as Input: listdfResult = [] for i, strSample in enumerate(Input): #print(strSample) #if i == 2: break strSample = strSample.replace('\n','').replace('\r','').strip() strFinalResultDir = './Output/%s/Summary/Merge_target_result/' % strSample for j, strFinalResultFile in enumerate(os.listdir(strFinalResultDir)): if j > 0: print('I expected one file, but there are more. check the target base change file') sys.exit(1) print(strFinalResultFile) strFinalResultPath = './Output/%s/Summary/Merge_target_result/%s' % (strSample, strFinalResultFile) listdfResult.append(pd.read_table(strFinalResultPath, low_memory=False)) dfAll = pd.concat(listdfResult) dfForw = dfAll.iloc[:,0:3] dfReve = dfAll.iloc[:,3:].replace(' ', '0').astype('int64') dfAllResult = pd.concat([dfForw, dfReve], axis=1).groupby(['Sample','Barcode','Ref']).sum() dfAllResult.reset_index(inplace=True) dfAllResult.to_csv('./Output/Summation_'+strProjectList, sep='\t') #with open('./Output/%s/Summary/Merge_target_result/%s' % (strSample, strFinalResultFile)) as FinalResult: """""" for strRow in FinalResult: listCol = strRow.replace('\n','').split('\t') listSamBarRef = listCol[:3] = listCol[3:] """""" def SummationSubIndel(): with open(strProjectList) as Input,\ open('./Output/Summation_' + strProjectList.replace('.txt','') + '_sub_indel.txt', 'w') as Output: dictResult = {} for i, strSample in enumerate(Input): print(strSample) #if i == 2: break strSample = strSample.replace('\n','').replace('\r','').strip() strSubIndelDir = './Output/%s/result' % strSample for strSubIndelFile in os.listdir(strSubIndelDir): if 'sub' in strSubIndelFile: with open(strSubIndelDir + '/' + strSubIndelFile) as SubIndel: for strRow in SubIndel: listCol = strRow.replace('\n','').split('\t') setIndelPattern = set(listCol[3].split(',')) intCount = int(listCol[2]) strNameBarcodePattern = '-'.join(listCol[0:2])+'-'+''.join(setIndelPattern) try: dictResult[strNameBarcodePattern] += intCount except KeyError: dictResult[strNameBarcodePattern] = intCount for strNameBarcodePattern, intCount in dictResult.items(): Output.write('\t'.join(strNameBarcodePattern.split('-')) + '\t' + str(intCount) + '\n') def ConfirmValidation(): with open(strProjectList) as Input: listdfResult = [] for i, strSample in enumerate(Input): if i == 2: break print(strSample) strSample = strSample.replace('\n','').replace('\r','').strip() strFinalResultDir = './Output/%s/Summary/Merge_target_result/' % strSample for strFinalResultFile in os.listdir(strFinalResultDir): print(strFinalResultFile) strFinalResultPath = './Output/%s/Summary/Merge_target_result/%s' % (strSample, strFinalResultFile) listdfResult.append(pd.read_table(strFinalResultPath, low_memory=False)) dfAll = pd.concat(listdfResult) dfForw = dfAll.iloc[:,0:3] dfReve = dfAll.iloc[:,3:].replace(' ', '0').astype('int64') dfAllResult = pd.concat([dfForw, dfReve], axis=1).groupby(['Sample','Barcode','Ref']).sum() dfAllResult.reset_index(inplace=True) print(dfAllResult.iloc[:, 3:].sum().values.tolist()) def Main(): Summation_all_final_result() SummationSubIndel() #ConfirmValidation() Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Summary_all_trim.py",".py","2026","56","#!/media/hkim/7434A5B334A5792E/bin/Python/Python2/bin/python2 import os, sys import subprocess as sp from pdb import set_trace sOutput_dir = sys.argv[1] sSample = sys.argv[2] lRef_alt = sys.argv[3].split(',') def Concat_summary(): sRef = lRef_alt[0] sAlt = lRef_alt[1] sSummary_dir = ""{outdir}/Tmp/Target"".format(outdir=sOutput_dir) lHeader = [] lData = [] for sFile in os.listdir(sSummary_dir): if sRef + 'to' + sAlt in sFile: with open(sSummary_dir + '/' + sFile) as Input: for i, sRow in enumerate(Input): if i == 0: lCol = sRow.replace('\n', '').split('\t') if lHeader: for iCol_num in range(len(lHeader)): if iCol_num > 6: if lHeader[iCol_num] == """" or lHeader[iCol_num] == "" "": lHeader[iCol_num] = lCol[iCol_num] else: lHeader = lCol else: lData.append(sRow) #END: for #END: with #END: if #END: for if not os.path.isdir('{outdir}/Result/Merge_target_result'.format(outdir=sOutput_dir)): os.mkdir('{outdir}/Result/Merge_target_result'.format(outdir=sOutput_dir)) with open('{outdir}/Result/Merge_target_result/{sample}_{ref}to{alt}_Summary.txt'.format(outdir=sOutput_dir, sample=sSample, ref=sRef, alt=sAlt), 'w') as Output: Output.write('\t'.join(lHeader) +'\n') for sData in lData: Output.write(sData) if __name__ == '__main__': Concat_summary() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Base_edit_2/Sequence_freq.py",".py","18926","396","#!/home/hkim/anaconda2/bin/python2.7 import os,sys import numpy as np from collections import Counter from collections import OrderedDict import multiprocessing as mp import logging from pdb import set_trace logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S', level=logging.DEBUG) sys.path.insert(0, os.path.dirname(os.getcwd())) from Core.CoreSystem import Helper try: strUser = sys.argv[1] strProject = sys.argv[2] lWindow = sys.argv[3].split('-') iWinStart = int(lWindow[0]) iWinEnd = int(lWindow[1]) iCore = int(sys.argv[4]) except IndexError: print('\nUsage: ./Sequence_freq.py SH 24K_screening 25-33 10\n' ' ./Sequence_freq.py user_name project_name window_range thread\n') sys.exit() def Count_seq_freq(lPara): """""" aligned_BaseEdit.txt ACTAGCTATCGCTCACTCTGGGGTCAGGGACAGTGGACTCGAAGGAGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA CGCTTGAAAAAGTGGCACCGAGTCGGTGCTTTTTTGACTAGCTATCGCTCACTCTGGGGTCAGGGGCAGTGGACTCGAAGGAGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAATA [] [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 1, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]] ACTAGCTATCGCTCACTCTGGGGTCAGGGACAGTGGACTCGAAGGAGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTA--A ACTAGCTATCGCTCACTCTGGGGTCAGGGGCAGTGGACTCGAAGGAGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAATA """""" strSample = lPara[0] sFile_path = lPara[1] sTotal_readcnt_path = lPara[2] dInput_fa = lPara[3] print (""Count_seq_freq: "", strSample, sFile_path, sTotal_readcnt_path) try: with open('./Output/{user}/{project}/{sample}/Result/Seq_freq.txt'.format(user=strUser, project=strProject, sample=strSample), 'w') as Output: Output.write('Filename\tSeq\tMotif\tCount\tTotal_cnt\tProportion\tSubstitution\n') ## A project has many file. The total read count is summation in the each file. for iFile_num, sFile in enumerate(os.listdir(sFile_path)): #set_trace() if 'aligned' in sFile: # print(iFile_num) sFilename = sFile.replace('_aligned_BaseEdit', '').split('.')[:-1][0] ## To search filename in other folder. sTotal_readcnt_file = sFilename + '_Summary.txt' ## extract totral read count for the sequence frequency. with open(sFile_path + '/' + sFile) as aligned_BaseEdit,\ open(sTotal_readcnt_path + '/' + sTotal_readcnt_file) as Total_readcnt: #print(sFile_path + '/' + sFile) iTotal_wo_indel = 0 for i, sRow in enumerate(Total_readcnt): if i == 0: continue lCol = sRow.replace('\n', '').split('\t') iTotal_read = int(lCol[3]) ## This is read counts of a matched barcode. iIndel_read = int(lCol[4]) + int(lCol[5]) + int(lCol[6]) iTotal_wo_indel = iTotal_read - iIndel_read ## Total read is without indel reads break ## 2 row is target, over 3 is none lTarget_seq = [] sRef_seq = '' dSeq_wt_extend = {} ## WT + motif(target sequence) + WT for i, sRow in enumerate(aligned_BaseEdit): lCol = sRow.replace('\n', '').split('\t') sQuery_seq = lCol[5] if sRef_seq == '': ## Reference is same in the file, so store once. sRef_seq = lCol[0] dSeq_wt_extend[sRef_seq[iWinStart - 1: iWinEnd]] = sRef_seq lRef_seq_with_motif = list(sRef_seq) lRef_seq_with_motif[ iWinStart-1 : iWinEnd ] = list(sQuery_seq[ iWinStart-1 : iWinEnd ]) sRef_seq_with_motif = ''.join(lRef_seq_with_motif) dSeq_wt_extend[sQuery_seq[ iWinStart-1 : iWinEnd ]] = sRef_seq_with_motif lTarget_seq.append(sQuery_seq[ iWinStart-1 : iWinEnd ]) iNormal = iTotal_wo_indel - len(lTarget_seq) sRef_seq = sRef_seq[ iWinStart-1 : iWinEnd ] dSeq_cnt = Counter(lTarget_seq) try: iRef_cnt_in_aligned = dSeq_cnt[sRef_seq] ## check normal sequence because substitution exists outside of window size. iNormal = iNormal + iRef_cnt_in_aligned del dSeq_cnt[sRef_seq] except KeyError: pass if iNormal > 0: if sRef_seq == '': ## aligned result file can be none result file. So extract from input file. sRef_seq = dInput_fa[sFilename][1] ## dInput_fa[0] : full ref, dInput_fa[1] : target ref dSeq_wt_extend[sRef_seq] = dInput_fa[sFilename][0] try: Output.write('\t'.join(map(str, [sFilename, dSeq_wt_extend[sRef_seq], sRef_seq, iNormal, iTotal_wo_indel, round(iNormal/float(iTotal_wo_indel),4), 'ref_from_result']))+'\n') except Exception as e: print(e, 'line150') set_trace() elif iNormal == 0: ## if iNormal = 0, that means no result generation. because aligned_BaseEdit file is not contained non-read file. sRef_seq = dInput_fa[sFilename][1] dSeq_wt_extend[sRef_seq] = dInput_fa[sFilename][0] try: Output.write('\t'.join(map(str, [sFilename, dSeq_wt_extend[sRef_seq], sRef_seq, iNormal, iTotal_wo_indel, iNormal, 'ref_from_input'])) + '\n') except Exception as e: print(e, 'line158') set_trace() for sSeq, iCnt in dSeq_cnt.most_common(): try: Output.write('\t'.join(map(str, [sFilename, dSeq_wt_extend[sSeq], sSeq, iCnt, iTotal_wo_indel, round(iCnt/float(iTotal_wo_indel),4), 'alt']))+'\n') except Exception as e: print(lPara[0], sFilename) print(iCnt, iTotal_wo_indel) print(e, 'line175') #pass set_trace() #END: for #END: with #END: for #END: with except Exception as e: print(e) print(""Error in the input: "", strSample, sFilename, sTotal_readcnt_file) pass #END: def def Make_ref_dict(strRef): dInput_fa = {} with open('./Input/{user}/Reference/{project}/{ref}/Reference.fa'.format(user=strUser, project=strProject, ref=strRef)) as Input_ref: """""" YSKim_0525+01614_98_repeat1 TATACACGCATGTAT TTTGTATACACGCATGTATGCATCCTGCAGGTCTCGCTCTGACATGTGGGAAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA 1 file has 1 barcode. This should be done. """""" for sRow in Input_ref: lCol = sRow.replace('\n', '').split('\t') sInputFile = lCol[0] sBarcode = lCol[1] sInputRef = lCol[2] iBarcode_start = sInputRef.index(sBarcode) sBarcode_start_ref = sInputRef[iBarcode_start:] dInput_fa[sInputFile] = [sBarcode_start_ref, sBarcode_start_ref[iWinStart - 1: iWinEnd]] return dInput_fa def Count_group(): """""" Filename Seq Count Total_cnt Proportion Substitution Doench2014_1000 AGGGACA 13 14 0.9286 ref_from_result Doench2014_1000 AG----- 1 14 0.0714 alt Doench2014_1001 GGCGCCA 17 26 0.6538 ref_from_result Doench2014_1001 GGTGCCA 5 26 0.1923 alt Doench2014_1001 GGAGCCA 2 26 0.0769 alt Doench2014_1001 GGCGCTA 1 26 0.0385 alt """""" sHeader = '' dTotal_cnt = {} ## Make dictionary to sum the total reads count of the group. The total reads count is always same in their group. with open('Group_list.txt') as Group_list: for sGroupname in Group_list: if sGroupname[0] == ""#"": continue sGroupname = sGroupname.replace('\n', '').strip() if not os.path.isdir('./Output/Group_result'): os.mkdir('./Output/Group_result') for sFile in os.listdir('./Output'): if sGroupname in sFile: ## matched group names -> Sum the counts with open('./Output/%s/Summary/Seq_freq.txt' % sFile) as SeqFreq: sHeader = SeqFreq.readline() dSelect_one_total_cnt = {} for sRow in SeqFreq: lCol = sRow.replace('\n', '').split('\t') sFilename = lCol[0] try: iTotal_read_cnt = int(lCol[4]) except IndexError: set_trace() dSelect_one_total_cnt[sFilename] = iTotal_read_cnt for sFilename, iTotal_read_cnt in dSelect_one_total_cnt.items(): try: dTotal_cnt[sGroupname + '_' + sFilename] += iTotal_read_cnt except KeyError: dTotal_cnt[sGroupname + '_' + sFilename] = iTotal_read_cnt with open('Group_list.txt') as Group_list: for sGroupname in Group_list: if sGroupname[0] == ""#"": continue sGroupname = sGroupname.replace('\n', '').strip() dSeq_freq = OrderedDict() ## ('GECKO_6367_GATCTGCTC', ['GECKO_6367', 'GATCTGCTC', 2, 156, '0.0128']), ## Unique key, only one list. if not os.path.isdir('./Output/Group_result'): os.mkdir('./Output/Group_result') for sFile in os.listdir('./Output'): if sGroupname in sFile: ## matched group names -> Sum the counts with open('./Output/%s/Summary/Seq_freq.txt' % sFile) as SeqFreq: sHeader = SeqFreq.readline() for sRow in SeqFreq: lCol = sRow.replace('\n', '').split('\t') sFilename = lCol[0] sSeq_wt_extend = lCol[1] sFile_seq = lCol[0] + '_' + lCol[2] ## Unique name : Doench2014_1000_CTCTGGGGT iCount = int(lCol[3]) iTotal_read_cnt = dTotal_cnt[sGroupname + '_' + sFilename] lCol[3] = iCount lCol[4] = iTotal_read_cnt try: _ = dSeq_freq[sFile_seq] dSeq_freq[sFile_seq][3] += iCount #dSeq_freq[sFile_seq][4] = iTotal_read_cnt except KeyError: dSeq_freq[sFile_seq] = lCol ## initial assignment ## x[0] : key, x[1] : value, int(x[1][5]) : proportion, x[1][6]: alt, wt category, x[1][0]: filename, llSeq_freq = sorted(sorted(dSeq_freq.items(), key=lambda x:x[1][6], reverse=True), key=lambda x:x[1][0]) if not os.path.isdir('./Output/Group_result/%s' % sGroupname): os.mkdir('./Output/Group_result/%s' % sGroupname) with open('./Output/Group_result/%s/Seq_freq.txt' % sGroupname, 'w') as Output: Output.write(sHeader) for sFile_seq, lCol in llSeq_freq: try: try: lCol[5] = round(float(lCol[3])/lCol[4], 4) ## proportion calculation, previous proportion is not correct. except ZeroDivisionError: lCol[5] = 0 except Exception: set_trace() Output.write('\t'.join(map(str, lCol)).replace('ref_from_result', 'wt').replace('ref_from_input', 'wt')+'\n') #END: for #END: with def Trim_data(): """""" Remove gap seqs (e.g. AC---) """""" with open('Group_list.txt') as Group_list: for sGroupname in Group_list: if sGroupname[0] == ""#"": continue sGroupname = sGroupname.replace('\n', '').strip() dSeq_freq = OrderedDict() with open('./Output/Group_result/%s/Seq_freq.txt' % sGroupname) as Group_result,\ open('./Output/Group_result/%s/Trimmed_seq_freq.txt' % sGroupname, 'w') as Trimmed_result: sHeader = '' for i, sRow in enumerate(Group_result): if i == 0: sHeader = sRow continue lCol = sRow.replace('\n', '').split('\t') sFilename = lCol[0] ## Doench2014_1000 try: dSeq_freq[sFilename].append(lCol) except KeyError: dSeq_freq[sFilename] = [lCol] for sFilename in dSeq_freq: llFilename = dSeq_freq[sFilename] ## [[Doench2014_1000,ACAGCAGCGAAC...,ACGCATC, 12,30,0.4][],[]... ## A Same file name chunk in the group file. iRecal_total = 0 ## sub the gap seq cnt #lDele_key = [] llPre_recal_total = [] llRecal_total = [] for i, lFilename in enumerate(llFilename): sMotif = lFilename[2] iMotif_cnt = int(lFilename[3]) iTotal_read_cnt = int(lFilename[4]) if lFilename[6] == 'wt': iRecal_total = iTotal_read_cnt llPre_recal_total.append(lFilename) elif '-' in sMotif: iRecal_total -= iMotif_cnt continue else: llPre_recal_total.append(lFilename) ## store AC----- row key for lPre_recal_total in llPre_recal_total: lPre_recal_total[4] = iRecal_total try: lPre_recal_total[5] = round(float(lPre_recal_total[3])/iRecal_total,4) ## recal proportion because of sub. except ZeroDivisionError: pass llRecal_total.append(lPre_recal_total) #llRecal_total[1:] = sorted(llRecal_total[1:], key=lambda x: float(x[5]), reverse=True) dSeq_freq[sFilename] = llRecal_total ## reassign the total cnt #END for llFilename_chunk = sorted(dSeq_freq) ## key is a filename for sKey in llFilename_chunk: llCol = dSeq_freq[sKey] llCol = sorted(llCol, key=lambda x: x[6], reverse=True) ## wild type category first if llCol[0][6] != 'wt': logging.critical('error, wildtype must be fisrt row. If you see this error message, please contact the developer.') logging.critical('This program will be terminated.') sys.exit() if len(llCol) > 1: ## It has alt. only a wt file does not necessary. llCol[1:] = sorted(llCol[1:], key=lambda x: float(x[5]), reverse=True) dSeq_freq[sKey] = llCol Trimmed_result.write(sHeader) for llRecal_total_final in dSeq_freq.values(): for lRecal_total_final in llRecal_total_final: Trimmed_result.write('\t'.join(map(str,lRecal_total_final))+'\n') #END with #END for #END with def Main(): logging.info('Program Start') logging.info('Make commands for a multiple processing') lPara = [] with open('./User/{user}/{project}.txt'.format(user=strUser, project=strProject)) as Project_list: for strSample in Project_list: if strSample[0] == '#': continue tupSampleInfo = Helper.SplitSampleInfo(strSample) if not tupSampleInfo: continue strSample, strRef, strExpCtrl = tupSampleInfo strSample = strSample.replace('\n', '').replace('\r', '') sFile_path = './Output/{user}/{project}/{sample}/Tmp/Alignment'.format(user=strUser, project=strProject, sample=strSample) sTotal_readcnt_path = './Output/{user}/{project}/{sample}/Tmp/All'.format(user=strUser, project=strProject, sample=strSample) dInput_fa = Make_ref_dict(strRef) lPara.append([strSample, sFile_path, sTotal_readcnt_path, dInput_fa]) logging.info('Multiple processing Start') p = mp.Pool(iCore) p.map_async(Count_seq_freq, lPara).get() logging.info('Multiple processing End') #logging.info('Count group Start') #Count_group() #logging.info('Count group End') #logging.info('Trim data Start') #Trim_data() #logging.info('Trim data End') logging.info('Program End') Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Summary_Random_barcode.py",".py","10848","223","import os, sys import logging import multiprocessing as mp from argparse import ArgumentParser from collections import OrderedDict sys.path.insert(0, os.path.dirname(os.getcwd())) from Core.CoreSystem import Helper class clsParameters(): def __init__(self, options): self.strUser = options.user_name self.strProject = options.project_name.replace('.txt', '') ## A user can be confused the input. So I prevented from it using 'replace'. self.strGroup = options.group self.intCore = options.thread self.strSampleList = 'User/{user}/{project}.txt'.format(user=options.user_name, project=options.project_name) def SummaryRandomBarcode(sFile_path): """""" /Tmp 190819_Nahye_24k_2_D0_2-24kLib_Classified_Indel_barcode.fastq* -> process target 190819_Nahye_24k_2_D0_2-24kLib_Indel_freq.txt* 190819_Nahye_24k_2_D0_2-24kLib_Indel_summary.txt* 190819_Nahye_24k_2_D0_2-24kLib_Summary.txt* Pickle dBarcode_cnt = {'ACGTACTC_sorting_barcode': {'ACATACAC_random': 5, 'CGTGTTGA_random': 3, ...} """""" dictBarcodeCnt = {} strClassCheck = '' strSample = sFile_path.split('/')[-1] logging.info('Summary_random_barcode start : %s, %s' % (sFile_path, strSample)) for sFile in os.listdir(sFile_path+'/Tmp/'): if '.fastq' in sFile: with open(sFile_path+'/Tmp/'+sFile) as Input: for i, strRow in enumerate(Input): # @D00235:683:CE1P6ANXX:6:1114:2135:5231 1:N:0:CTGAAGCT+CCTATCCT:Barcode_TTTGCTATCTCGACGTATGGACAGTG:total if i % 4 == 0: listBarClass = strRow.replace('\n','').split('Barcode_')[1].split(':') strBarcode = listBarClass[0] strClass = listBarClass[1] if strClass == 'total': strClassCheck = 'total' if i % 4 == 1 and strClassCheck == 'total': strRow = strRow.replace('\n','').upper() intBarcodeStart = strRow.find(strBarcode) strRandom_barcode = strRow[intBarcodeStart-8:intBarcodeStart] try: _ = dictBarcodeCnt[strBarcode] except KeyError: dictBarcodeCnt[strBarcode] = {} try: dictBarcodeCnt[strBarcode][strRandom_barcode] += 1 except KeyError: dictBarcodeCnt[strBarcode][strRandom_barcode] = 1 #print(sBarcode, sRandom_barcode, iBarcode_start, sRow) strClassCheck = '' if not os.path.isdir(sFile_path + '/Summary_Random_barcode'): os.mkdir(sFile_path + '/Summary_Random_barcode') with open(sFile_path + '/Summary_Random_barcode/%s_all_random_barcode.txt' % strSample, 'w') as All_random,\ open(sFile_path + '/Summary_Random_barcode/%s_Unique_RandomBarcodeNumber_In_SortingBarcode.txt' % strSample, 'w') as Random_sorting: All_random.write('Sorting_barcode\tUnique_RandomBarcodeNumber_In_SortingBarcode\tRandomBarcode\tEach_RandomBarcode_read_count\n') Random_sorting.write('Sorting_barcode\tUnique_RandomBarcodeNumber_In_SortingBarcode\n') for sBarcode, dRandom_barcode_cnt in dictBarcodeCnt.items(): iRandom_barcode_num = len(dRandom_barcode_cnt.keys()) Random_sorting.write('\t'.join(map(str, [sBarcode, iRandom_barcode_num]))+'\n') for sRandom_barcode, iCnt in dRandom_barcode_cnt.items(): All_random.write('\t'.join(map(str, [sBarcode, iRandom_barcode_num, sRandom_barcode, iCnt]))+'\n') logging.info('Summary_random_barcode end: %s' % sFile_path) ## on going def CountGroup(InstParameters): """""" Sorting_barcode Unique_RandomBarcodeNumber_In_SortingBarcode RandomBarcode Each_RandomBarcode_read_count TATATCATAGCGTACTCATC 8 TGCGTTTG 3 TATATCATAGCGTACTCATC 8 CGCGTTTG 3 TATATCATAGCGTACTCATC 8 TAGTTTTG 1 TATATCATAGCGTACTCATC 8 ATAGTTTG 1 """""" sHeader = '' with open(InstParameters.strSampleList) as Sample: ## tmp input listSample = Sample.readlines() setGroup = set([strRow.replace('\n', '').split('\t')[2].upper() for strRow in listSample]) for strGroup in setGroup: if strGroup == 'CTRL': continue for strRow in listSample: if strGroup == strGroupOfSample: ## matched group names -> Sum the counts listCol = strRow.replace('\n', '').split('\t') strSample = listCol[0] strRef = listCol[1] strGroupOfSample = listCol[2] strProjectDir = './Output/{user}/{project}'.format(user=InstParameters.strUser, project=InstParameters.strProject) strGroupDir = os.path.join(strProjectDir, 'Group_result') Helper.MakeFolderIfNot(strGroupDir) dTotal_RandomBarcode_cnt_in_SortingBarcode = OrderedDict() ## ('GECKO_6367_GATCTGCTC', ['GECKO_6367', 'GATCTGCTC', 2, 156, '0.0128']), ## Unique key, only one list. with open('{project_dir}/{sample}_all_random_barcode.txt'.format(project_dir=strProjectDir, sample=strSample)) as RandomBarcode_SeqFreq: sHeader = RandomBarcode_SeqFreq.readline() for sRow in RandomBarcode_SeqFreq: lCol = sRow.replace('\n', '').split('\t') sSortingBarcode = lCol[0] #iTotal_RandomBarcode_cnt_in_SortingBarcode = int(lCol[1]) sSorting_and_Random_barcode_seq = lCol[0] + '_' + lCol[2] ## Unique name : Doench2014_1000_CTCTGGGGT iRandomBarcode_count = int(lCol[3]) lCol[3] = iRandomBarcode_count try: _ = dTotal_RandomBarcode_cnt_in_SortingBarcode[sSorting_and_Random_barcode_seq] dTotal_RandomBarcode_cnt_in_SortingBarcode[sSorting_and_Random_barcode_seq][3] += iRandomBarcode_count except KeyError: dTotal_RandomBarcode_cnt_in_SortingBarcode[sSorting_and_Random_barcode_seq] = lCol ## initial assignment #END for dRecal_total_kind_of_RandomBarcode = OrderedDict() for sSort_Rand_seq in dTotal_RandomBarcode_cnt_in_SortingBarcode: ## sSorting_and_Random_barcode_seq sSortBarcode = sSort_Rand_seq.split('_')[0] try: dRecal_total_kind_of_RandomBarcode[sSortBarcode].append(dTotal_RandomBarcode_cnt_in_SortingBarcode[sSort_Rand_seq]) except KeyError: dRecal_total_kind_of_RandomBarcode[sSortBarcode] = [dTotal_RandomBarcode_cnt_in_SortingBarcode[sSort_Rand_seq]] for sKey, llValue in dRecal_total_kind_of_RandomBarcode.items(): ## sKey: TATATCATAGCGTACTCATC, llValue : [[TATATCATAGCGTACTCATC, 8, TGCGTTTG, 3],[],[] ... iKind_of_RandomBarcode = len(llValue) ################## why do I make like this ????? for lValue in llValue: lValue[1] = iKind_of_RandomBarcode ## Recal using group total cnt. llValue = sorted(llValue, key=lambda x:x[3], reverse=True) dRecal_total_kind_of_RandomBarcode[sKey] = llValue strEachGroup = './Output/Group_result/%s' % strGroup Helper.MakeFolderIfNot(strEachGroup) with open(os.path.join(strEachGroup, 'Summary_all_random_barcode_in_group.txt'), 'w') as Sort_Random_cnt,\ open(os.path.join(strEachGroup, 'Summary_Unique_RandomBarcodeNumber_in_group.txt'), 'w') as Uniq_random_cnt: Sort_Random_cnt.write(sHeader) Uniq_random_cnt.write('Sorting_barcode\tUnique_RandomBarcodeNumber_In_SortingBarcode\n') for sSortBarcode, llCol in dRecal_total_kind_of_RandomBarcode.items(): Uniq_random_cnt.write('\t'.join(map(str, [sSortBarcode, len(llCol)]))+'\n') for lCol in llCol: Sort_Random_cnt.write('\t'.join(map(str, lCol))+'\n') #END: for #END: with def Main(): logging.info('Program Start') logging.info('Make commands for a multiple processing') parser = ArgumentParser(description='Script for counting the random barcodes') parser.add_argument('-u', '--user_name', type=str, dest='user_name', help='The user name in the /user subdir') parser.add_argument('-p', '--project_name', type=str, dest='project_name', help='The project name in the /user/user_name/ subdir') parser.add_argument('-g', '--group', type=str, dest='group', default='false', help='The group sum run of the barcodes, default: false') parser.add_argument('-t', '--thread', type=int, dest='thread', default='15', help='The multicore number 1~15') options = parser.parse_args() InstParameters = clsParameters(options) lPara = [] with open(InstParameters.strSampleList) as SampleList: for strSample in SampleList: if strSample[0] == '#' or strSample[0] in ['', ' ', '\r', '\n', '\r\n']: continue strSample = strSample.replace('\n', '').replace('\r', '').split('\t')[0] sFile_path = './Output/{user}/{project}/{sample}'.format(user=options.user_name, project=options.project_name, sample=strSample) #print('sFile_path', sFile_path) lPara.append(sFile_path) ## single_test #Summary_random_barcode(lPara[0]) logging.info('Multiple processing Start') p = mp.Pool(options.thread) p.map_async(SummaryRandomBarcode, lPara).get() logging.info('Multiple processing End') #logging.info('Count group Start') #CountGroup(InstParameters) #logging.info('Count group End') #logging.info('Program End') Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Run_indel_searcher.py",".py","19823","366","import os, re, sys, math, logging import cPickle as pickle import subprocess as sp from pdb import set_trace from datetime import datetime from optparse import OptionParser sys.path.insert(0, os.path.dirname(os.getcwd())) from Core.CoreSystem import InitialFolder, UserFolderAdmin, Helper, RunMulticore, CheckProcessedFiles class clsIndelSearcherRunner(UserFolderAdmin): """""" self.strOutputDir is inherited variable. """""" def __init__(self, strSample, strRef, options, InstInitFolder): UserFolderAdmin.__init__(self, strSample, strRef, options, InstInitFolder.strLogPath) self.MakeSampleFolder() self.strProjectFile = InstInitFolder.strProjectFile self.intChunkSize = options.chunk_number self.strQualCutoff = options.base_quality self.intInsertionWin = options.insertion_window # Insertion window 0,1,2,3,4 self.intDeletionWin = options.deletion_window # Deletion window 0,1,2,3,4 self.strPamType = options.pam_type # CRISPR type : Cpf1(2 cleavages), Cas9(1 cleavage) self.strPamPos = options.pam_pos # Barcode target position : Forward (barcode + target), Reverse (target + barcode) self.strPickle = options.pickle self.strClassFASTQ = options.class_fastq self.strSplit = options.split self.strLogPath = InstInitFolder.strLogPath self.strBarcodeFile = os.path.join(self.strRefDir, 'Barcode.txt') self.strReferenceSeqFile = os.path.join(self.strRefDir, 'Reference_sequence.txt') self.strTargetSeqFile = os.path.join(self.strRefDir, 'Target_region.txt') self.strRefFile = os.path.join(self.strRefDir, 'Reference.fa') ## The file name required for the user is 'B'arcode.txt but it may be written as 'b'arcode.txt by mistake. ## This part is to fix the situation as mentioned above. if not os.path.isfile(self.strBarcodeFile): if os.path.isfile(self.strRefDir + 'barcode.txt'): self.strBarcodeFile = self.strRefDir + 'barcode.txt' else: logging.error('Barcode path is not correct, please make sure the path correctly.') if not os.path.isfile(self.strReferenceSeqFile): if os.path.isfile(self.strRefDir + 'reference_sequence.txt'): self.strReferenceSeqFile = self.strRefDir + 'reference_sequence.txt' else: logging.error('Reference path is not correct, please make sure the path correctly.') if not os.path.isfile(self.strTargetSeqFile): if os.path.isfile(self.strRefDir + 'target_region.txt'): self.strTargetSeqFile = self.strRefDir + 'target_region.txt' else: logging.error('Target path is not correct, please make sure the path correctly.') self.strFastqDir = './Input/{user}/FASTQ/{project}'.format(user=self.strUser, project=self.strProject) ## './Input/JaeWoo/FASTQ/Test_samples/Sample_1' self.strSampleDir = os.path.join(self.strFastqDir, self.strSample) self.strFastq_name = '' for strFile in os.listdir(self.strSampleDir): if os.path.isfile(self.strSampleDir + '/' + strFile) and strFile.split('.')[-1] == 'fastq': self.strFastq_name = '.'.join(strFile.split('.')[:-1]) logging.info('File name : %s' % self.strFastq_name) ## './Input/JaeWoo/FASTQ/Test_samples/Sample_1/Fastq_file.fastq' self.strInputFile = os.path.join(self.strSampleDir, self.strFastq_name+'.fastq') ## './Input/JaeWoo/FASTQ/Test_samples/Sample_1/Fastq_file.txt' self.strInputList = os.path.join(self.strSampleDir, self.strFastq_name+'.txt') ## './Input/JaeWoo/FASTQ/Test_samples/Sample_1/Split_files' self.strSplitPath = os.path.join(self.strSampleDir, 'Split_files') Helper.MakeFolderIfNot(self.strSplitPath) self.strPair = 'False' # FASTQ pair: True, False def SplitFile(self): ### Defensive : original fastq wc == split fastq wc #intTotalLines = len(open(self.strInputFile).readlines()) intTotalLines = int(sp.check_output('wc -l {input_file}'.format(input_file=self.strInputFile), shell=True).split()[0]) intSplitNum = int(math.ceil(intTotalLines/float(self.intChunkSize))) ## e.g. 15.4 -> 16 if intSplitNum == 0: intSplitNum = 1 logging.info('Total lines:%s, Chunk size:%s, Split number:%s' % (intTotalLines, self.intChunkSize, intSplitNum)) with open(self.strInputFile) as fq, \ open(self.strInputList, 'w') as OutList: for intNum in range(1, intSplitNum + 1): strSplitFile = self.strSplitPath + '/{sample}_{num}.fq'.format(sample=os.path.basename(self.strInputFile), num=intNum) with open(strSplitFile, 'w') as out: OutList.write(os.path.basename(strSplitFile) + '\n') intCount = 0 for strRow in fq: intCount += 1 out.write(strRow) if intCount == self.intChunkSize: break ## defensive #strOriginal = sp.check_output('wc -l {input_file}'.format(input_file=self.strInputFile), shell=True) strSplited = sp.check_output('cat {splited}/*.fq | wc -l'.format(splited=self.strSplitPath), shell=True) #strOrigianlWc = strOriginal.split()[0] intSplitedWc = int(strSplited.replace('\n','')) if intTotalLines != intSplitedWc: logging.error('The number of total lines of splited file is not corresponded to origial fastq.') logging.error('Original FASTQ line number : %s, Splited FASTQ line number : %s' % (intTotalLines, strSplited)) sys.exit(1) def MakeReference(self): if not os.path.isfile(self.strRefFile): with open(self.strBarcodeFile) as Barcode, \ open(self.strTargetSeqFile) as Target, \ open(self.strReferenceSeqFile) as Ref, \ open(self.strRefFile, 'w') as Output: listBarcode = Helper.RemoveNullAndBadKeyword(Barcode) listTarget = Helper.RemoveNullAndBadKeyword(Target) listRef = Helper.RemoveNullAndBadKeyword(Ref) ## defensive assert len(listBarcode) == len(listTarget) == len(listRef), 'Barcode, Target and Reference must be a same row number.' listName = [] for strBar, strTar in zip(listBarcode, listTarget): strBar = strBar.replace('\n', '').replace('\r', '').strip().upper() strTar = strTar.replace('\n', '').replace('\r', '').strip().upper() Helper.CheckIntegrity(self.strBarcodeFile, strBar) ## defensive Helper.CheckIntegrity(self.strBarcodeFile, strTar) ## defensive listName.append(strBar + ':' + strTar + '\n') for i, strRow in enumerate(listRef): strRow = strRow.replace('\r', '').strip().upper() Output.write('>' + listName[i] + strRow + '\n') def MakeIndelSearcherCmd(self): listCmd = [] strReverse = 'None' with open(self.strInputList) as Input: for strFile in Input: listFile = strFile.replace('\n', '').split(' ') strForward = self.strSplitPath + '/' + listFile[0] #if self.strPair == 'True': # strReverse = self.strSplitPath + '/' + listFile[1] listCmd.append(('{python} Indel_searcher_crispresso_hash.py {forw} {reve} {ref} {pair} {GapO} {GapE}' ' {Insertion_win} {Deletion_win} {PAM_type} {PAM_pos} {Qual} {outdir} {logpath}').format( python=self.strPython, forw=strForward, reve=strReverse, ref=self.strRefFile, pair=self.strPair, GapO=self.strGapOpen, GapE=self.strGapExtend, Insertion_win=self.intInsertionWin, Deletion_win=self.intDeletionWin, PAM_type=self.strPamType, PAM_pos=self.strPamPos, Qual=self.strQualCutoff, outdir=self.strOutSampleDir, logpath=self.strLogPath)) return listCmd def RunIndelFreqCalculator(self): sp.call('{python} Indel_frequency_calculator.py {outdir} {sample} {logpath}'.format(python=self.strPython, outdir=self.strOutSampleDir, sample=self.strSample, logpath=self.strLogPath), shell=True) sp.call('{python} Summary_all_trim.py {outdir} {sample} {logpath}'.format(python=self.strPython, outdir=self.strOutSampleDir, sample=self.strSample, logpath=self.strLogPath), shell=True) sp.call('cp $(find ./Output/{user}/{project} -name ""*.tsv"") ./Output/{user}/{project}/All_results'.format(user=self.strUser, project=self.strProject), shell=True) def IndelNormalization(self): sp.call('{python} Indel_normalization.py {project_file} {user} {project}'.format(python=self.strPython, project_file=self.strProjectFile, user=self.strUser, project=self.strProject), shell=True) def MakeOutput(self): """""" dictResult {'TTTGTAGTCATACATCGCAATGTCAA': [0, 0, 0, 0, [], [], [], [], []]} dictResultIndelFreq {'TTTGCTCAGTCACACGTCACGAGCTG': [['TCATCGACTTGCAGGACATTAGGCGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTC', ['TCATCGACTTGCAGGACGAAGCTTGGCGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAATA'], '19M3I', 1.0, 'TCATCGACTTGCAGGACATTAGGCGA', ['TCATCGACTTGCAGGACAT---TAGGCGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTC---------'], ['TCATCGACTTGCAGGACGAAGCTTGGCGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAATA']]]} strBarcodePamPos Foward """""" # index name, constant variable. intTotal = 0 intNumIns = 1 intNumDel = 2 intNumCom = 3 intTotalFastq = 4 intInsFastq = 5 intDelFastq = 6 intComFastq = 7 intIndelInfo = 8 with open('{outdir}/Tmp/{sample}_Summary.txt'.format(outdir=self.strOutSampleDir, sample=self.strSample), 'w') as Summary, \ open('{outdir}/Tmp/{sample}_Classified_Indel_barcode.fastq'.format(outdir=self.strOutSampleDir, sample=self.strSample), 'w') as FastqOut, \ open('{outdir}/Tmp/{sample}_Indel_freq.txt'.format(outdir=self.strOutSampleDir, sample=self.strSample), 'w') as FreqOut: for binPickle in os.listdir('{outdir}/Tmp/Pickle'.format(outdir=self.strOutSampleDir)): with open('{outdir}/Tmp/Pickle/{pickle}'.format(outdir=self.strOutSampleDir, pickle=binPickle), 'rb') as PickleResult: dictPickleResult = pickle.load(PickleResult) dictResult = dictPickleResult['dictResult'] dictResultIndelFreq = dictPickleResult['dictResultIndelFreq'] strBarcodePamPos = dictPickleResult['strBarcodePamPos'] for strBarcode, listValue in dictResult.items(): if strBarcodePamPos == 'Reverse': strBarcode = strBarcode[::-1] Summary.write(""{Bar}\t{NumTot}\t{NumIns}\t{NumDel}\t{NumCom}\n"".format( Bar=strBarcode, NumTot=listValue[intTotal], NumIns=listValue[intNumIns], NumDel=listValue[intNumDel], NumCom=listValue[intNumCom])) if self.strClassFASTQ == 'True': for strJudge, intFastqKind in [('total', intTotalFastq), ('insertion', intInsFastq), ('deletion', intDelFastq), ('complex', intComFastq)]: for listFastq in listValue[intFastqKind]: ## category listFastqAddClass = [listFastq[0]+':Barcode_%s:%s' % (strBarcode, strJudge)] FastqOut.write('\n'.join(listFastqAddClass + listFastq[1:]) + '\n') for strBarcode in dictResultIndelFreq: # dictResultIndelFreq [sRef_seq, lQuery, float(iFreq)/iTotal, sTarget_region] if strBarcodePamPos == 'Reverse': strBarcode = strBarcode[::-1] for strRefSeq, listQuery, strINDEL, floFreq, strTargetRegion, listRefNeedle, listQueryNeedle in sorted(dictResultIndelFreq[strBarcode], key=lambda x: x[3], reverse=True): for strQuery, strRefNeedle, strQueryNeedle in zip(listQuery, listRefNeedle, listQueryNeedle): if strBarcodePamPos == 'Reverse': strQuery = strQuery[::-1] strRefNeedle = strRefNeedle[::-1] strQueryNeedle = strQueryNeedle[::-1] FreqOut.write('\t'.join([strBarcode, strQuery, strINDEL, str(round(floFreq, 4)), strRefNeedle, strQueryNeedle])+'\n') #END:for #END:with #END:for if self.strPickle == 'False': logging.info('Delete tmp pickles') sp.call('rm {outdir}/Tmp/Pickle/*.pickle'.format(outdir=self.strOutSampleDir), shell=True) elif self.strSplit == 'False': logging.info('Delete splited input files') sp.call('rm {split_path}/*.fq'.format(split_path=self.strSplitPath), shell=True) #END:with #END:def #END:cls def Main(): parser = OptionParser('Indel search program for CRISPR CAS9 & CPF1\n python2.7 Run_indel_searcher.py --pam_type Cas9 --pam_pos Forward') parser.add_option('-t', '--thread', default='1', type='int', dest='multicore', help='multiprocessing number, recommendation:t<16') parser.add_option('-c', '--chunk_number', default='400000', type='int', dest='chunk_number', help='split FASTQ, must be multiples of 4. file size < 1G recommendation:40000, size > 1G recommendation:400000') parser.add_option('-q', '--base_quality', default='20', dest='base_quality', help='NGS read base quality') parser.add_option('--gap_open', default='-10', type='float', dest='gap_open', help='gap open: -100~0') parser.add_option('--gap_extend', default='1', type='float', dest='gap_extend', help='gap extend: 1~100') parser.add_option('-i', '--insertion_window', default='4', type='int', dest='insertion_window', help='a window size for insertions') parser.add_option('-d', '--deletion_window', default='4', type='int', dest='deletion_window', help='a window size for deletions') parser.add_option('--pam_type', dest='pam_type', help='PAM type: Cas9 Cpf1') parser.add_option('--pam_pos', dest='pam_pos', help='PAM position: Forward Reverse') parser.add_option('--python', dest='python', help='The python path including the CRISPResso2') parser.add_option('--user', dest='user_name', help='The user name with no space') parser.add_option('--project', dest='project_name', help='The project name with no space') parser.add_option('--pickle', dest='pickle', default='False', help='Dont remove the pickles in the tmp folder : True, False') parser.add_option('--split', dest='split', default='False', help='Dont remove the split files in the input folder : True, False') parser.add_option('--classfied_FASTQ', dest='class_fastq', default='True', help='Dont remove the ClassfiedFASTQ in the tmp folder : True, False') parser.add_option('--ednafull', dest='ednafull', help='The nucleotide alignment matrix') options, args = parser.parse_args() InstInitFolder = InitialFolder(options.user_name, options.project_name, os.path.basename(__file__)) InstInitFolder.MakeDefaultFolder() InstInitFolder.MakeInputFolder() InstInitFolder.MakeOutputFolder() logging.basicConfig(format='%(process)d %(levelname)s %(asctime)s : %(message)s', level=logging.DEBUG, filename=InstInitFolder.strLogPath, filemode='a') logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logging.info('Program start') if options.multicore > 15: logging.warning('Optimal treads <= 15') logging.info(str(options)) with open(InstInitFolder.strProjectFile) as Sample_list: listSamples = Helper.RemoveNullAndBadKeyword(Sample_list) intProjectNumInTxt = len(listSamples) strInputProject = './Input/{user}/FASTQ/{project}'.format(user=options.user_name, project=options.project_name) @CheckProcessedFiles def RunPipeline(**kwargs): setGroup = set() for strSample in listSamples: tupSampleInfo = Helper.SplitSampleInfo(strSample) if not tupSampleInfo: continue strSample, strRef, strExpCtrl = tupSampleInfo setGroup.add(strExpCtrl) InstRunner = clsIndelSearcherRunner(strSample, strRef, options, InstInitFolder) #"""""" logging.info('SplitFile') InstRunner.SplitFile() logging.info('MakeReference') InstRunner.MakeReference() logging.info('MakeIndelSearcherCmd') listCmd = InstRunner.MakeIndelSearcherCmd() logging.info('RunMulticore') RunMulticore(listCmd, options.multicore) ## from CoreSystem.py logging.info('MakeOutput') InstRunner.MakeOutput() logging.info('RunIndelFreqCalculator') InstRunner.RunIndelFreqCalculator() #"""""" if setGroup == {'EXP', 'CTRL'}: InstRunner.IndelNormalization() elif setGroup in [set(), set([]), set(['']), set([' '])]: pass else: logging.error('The group category is not appropriate. : %s' % setGroup) logging.error('Please make sure your project file is correct.') logging.error('The group category must be Exp or Ctrl') raise Exception #"""""" RunPipeline(InstInitFolder=InstInitFolder, strInputProject=strInputProject, intProjectNumInTxt=intProjectNumInTxt, listSamples=listSamples, logging=logging) logging.info('Program end') #END:def if __name__ == '__main__': Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Run_flash.sh",".sh","407","21","#!/bin/bash #################### ## User parameter ## #################################### user=SH project=p53_screening flash=FLASH-1.2.11-Linux-x86_64 thread=4 #################################### while read python_path;do python=$python_path done < ../PythonPath.txt nohup $python ./Flash_pair_read_merge.py $user $project $flash $thread > ./Output/${user}/${project}/Log/flash_log.txt 2>&1 & ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Indel_searcher_crispresso_hash.py",".py","31553","727","import os, re, sys, logging import numpy as np import subprocess as sp import cPickle as pickle from pdb import set_trace sys.path.insert(0, os.path.dirname(os.getcwd())) from Core.CoreSystem import CoreHash, CoreGotoh class clsParameter(object): def __init__(self): if len(sys.argv) > 1: self.strForwardFqPath = sys.argv[1] self.strReverseFqPath = sys.argv[2] self.strRefFa = sys.argv[3] self.strPair = sys.argv[4] self.floOg = float(sys.argv[5]) self.floOe = float(sys.argv[6]) self.intInsertionWin = int(sys.argv[7]) self.intDeletionWin = int(sys.argv[8]) self.strPamType = sys.argv[9].upper() ## Cpf1, Cas9 self.strBarcodePamPos = sys.argv[10] ## PAM - BARCODE type (reverse) or BARCODE - PAM type (forward) self.intQualCutoff = int(sys.argv[11]) self.strOutputdir = sys.argv[12] self.strLogPath = sys.argv[13] self.strEDNAFULL = os.path.abspath('../EDNAFULL') else: sManual = """""" Usage: python2.7 ./indel_search_ver1.0.py splitted_input_1.fq splitted_input_2.fq reference.fa splitted_input_1.fq : forward splitted_input_2.fq : reverse Total FASTQ(fq) lines / 4 = remainder 0. """""" print(sManual) sys.exit() class clsFastqOpener(object): def __init__(self, InstParameter): self.strForwardFqPath = InstParameter.strForwardFqPath self.strReverseFqPath = InstParameter.strReverseFqPath def OpenFastqForward(self): listFastqForward = [] listStore = [] with open(self.strForwardFqPath) as Fastq1: for i, strRow in enumerate(Fastq1): i = i + 1 strRow = strRow.replace('\n', '').upper() if i % 4 == 1 or i % 4 == 2: listStore.append(strRow) elif i % 4 == 0: listQual = [ord(i) - 33 for i in strRow] listStore.append(listQual) listFastqForward.append(tuple(listStore)) listStore = [] return listFastqForward def OpenFastqReverse(self): listFastqReverse = [] listStore = [] dictRev = {'A': 'T', 'C': 'G', 'G': 'C', 'T': 'A', 'N': 'N'} #with open('./6_AsD0_2_small_test.fq') as fa_2: with open(self.strReverseFqPath) as Fastq2: for i, strRow in enumerate(Fastq2): i = i + 1 strRow = strRow.replace('\n', '').upper() if i % 4 == 1: listStore.append(strRow) elif i % 4 == 2: listStore.append(''.join([dictRev[strNucle] for strNucle in strRow[::-1]])) elif i % 4 == 0: listQual = [ord(i) - 33 for i in strRow][::-1] listStore.append(listQual) listFastqReverse.append(tuple(listStore)) listStore = [] return listFastqReverse #end1: return #end: def class clsIndelSearchParser(object): def __init__(self, InstParameter): # index name, constant variable. self.intNumOfTotal = 0 self.intNumOfIns = 1 self.intNumOfDel = 2 self.intNumofCom = 3 self.intTotalFastq = 4 self.intInsFastq = 5 self.intDelFastq = 6 self.intComFastq = 7 self.intIndelInfo = 8 self.strRefFa = InstParameter.strRefFa self.floOg = InstParameter.floOg self.floOe = InstParameter.floOe self.strEDNAFULL = InstParameter.strEDNAFULL self.strPamType = InstParameter.strPamType self.intInsertionWin = InstParameter.intInsertionWin self.intDeletionWin = InstParameter.intDeletionWin self.intQualCutoff = InstParameter.intQualCutoff def SearchBarcodeIndelPosition(self, sBarcode_PAM_pos): dRef = {} dResult = {} with open(self.strRefFa) as Ref: sBarcode = """" sTarget_region = """" intBarcodeLen = 0 for i, sRow in enumerate(Ref): if i % 2 == 0: ## >CGCTCTACGTAGACA:CTCTATTACTCGCCCCACCTCCCCCAGCCC sBarcode, sTarget_region, intBarcodeLen = self._SeperateFaHeader(sRow, sBarcode, sTarget_region, intBarcodeLen, sBarcode_PAM_pos) elif i % 2 != 0: ## AGCATCGATCAGCTACGATCGATCGATCACTAGCTACGATCGATCA sRef_seq, iIndel_start_pos, iIndel_end_pos = self._SearchIndelPos(sRow, sBarcode_PAM_pos, sTarget_region) try: self._MakeRefAndResultTemplate(sRef_seq, sBarcode, iIndel_start_pos, iIndel_end_pos, sTarget_region, dRef, dResult) except ValueError: continue assert len(dRef.keys()) == len(dResult.keys()) return dRef, dResult # end1: return def _SeperateFaHeader(self, sRow, sBarcode, sTarget_region, intBarcodeLen, sBarcode_PAM_pos): # barcode target region # >CGCTCTACGTAGACA:CTCTATTACTCGCCCCACCTCCCCCAGCCC sBarcode_indel_seq = sRow.strip().replace('\n', '').replace('\r', '').split(':') sBarcode = sBarcode_indel_seq[0].replace('>', '') if intBarcodeLen > 0: assert intBarcodeLen == len(sBarcode), 'All of the barcode lengths must be same.' intBarcodeLen = len(sBarcode) sTarget_region = sBarcode_indel_seq[1] ## Reverse the sentence. If it is done, all methods are same before work. if sBarcode_PAM_pos == 'Reverse': sBarcode = sBarcode[::-1] sTarget_region = sTarget_region[::-1] return (sBarcode, sTarget_region, intBarcodeLen) def _SearchIndelPos(self, sRow, sBarcode_PAM_pos, sTarget_region): sRef_seq = sRow.strip().replace('\n', '').replace('\r', '') if sBarcode_PAM_pos == 'Reverse': sRef_seq = sRef_seq[::-1] Seq_matcher = re.compile(r'(?=(%s))' % sTarget_region) # iIndel_start_pos = sRef_seq.index(sTarget_region) # There is possible to exist two indel. iIndel_start_pos = Seq_matcher.finditer(sRef_seq) for i, match in enumerate(iIndel_start_pos): iIndel_start_pos = match.start() # print iIndel_start_pos # print len(sTarget_region) # print sRef_seq iIndel_end_pos = iIndel_start_pos + len(sTarget_region) - 1 return (sRef_seq, iIndel_start_pos, iIndel_end_pos) def _MakeRefAndResultTemplate(self, sRef_seq, sBarcode, iIndel_start_pos, iIndel_end_pos, sTarget_region, dRef, dResult): iBarcode_start_pos = sRef_seq.index(sBarcode) # if iIndel_start_pos <= iBarcode_start_pos: # print(iIndel_start_pos, iBarcode_start_pos) # raise IndexError('indel is before barcode') iBarcode_end_pos = iBarcode_start_pos + len(sBarcode) - 1 sRef_seq_after_barcode = sRef_seq[iBarcode_end_pos + 1:] # modified. to -1 iIndel_end_next_pos_from_barcode_end = iIndel_end_pos - iBarcode_end_pos - 1 iIndel_start_next_pos_from_barcode_end = iIndel_start_pos - iBarcode_end_pos - 1 # ""barcode""-------------*(N) that distance. # ^ ^ ^ # *NNNN*NNNN # ^ ^ indel pos, the sequence matcher selects indel event pos front of it. ## Result dRef[sBarcode] = (sRef_seq, sTarget_region, sRef_seq_after_barcode, iIndel_start_next_pos_from_barcode_end, iIndel_end_next_pos_from_barcode_end, iIndel_start_pos, iIndel_end_pos) # total matched reads, insertion, deletion, complex dResult[sBarcode] = [0, 0, 0, 0, [], [], [], [], []] def SearchIndel(self, lFASTQ=[], dRef = {}, dResult={}, sBarcode_PAM_pos=""""): # lFASTQ : [(seq, qual),(seq, qual)] # lRef : [(ref_seq, ref_seq_after_barcode, barcode, barcode end pos, indel end pos, indel from barcode),(...)] # dResult = [# of total, # of ins, # of del, # of com, [total FASTQ], [ins FASTQ], [del FASTQ], [com FASTQ]] iCount = 0 intBarcodeLen = len(dRef.keys()[0]) #print('intBarcodeLen', intBarcodeLen) InstGotoh = CoreGotoh(strEDNAFULL=self.strEDNAFULL, floOg=self.floOg, floOe=self.floOe) for lCol_FASTQ in lFASTQ: sName = lCol_FASTQ[0] if sBarcode_PAM_pos == 'Reverse': sSeq = lCol_FASTQ[1][::-1] lQual = lCol_FASTQ[2][::-1] else: sSeq = lCol_FASTQ[1] lQual = lCol_FASTQ[2] assert isinstance(sName, str) and isinstance(sSeq, str) and isinstance(lQual, list) listSeqWindow = CoreHash.MakeHashTable(sSeq, intBarcodeLen) iBarcode_matched = 0 iInsert_count = 0 iDelete_count = 0 iComplex_count = 0 intFirstBarcode = 0 ## check whether a barcode is one in a sequence. for strSeqWindow in listSeqWindow: if intFirstBarcode == 1: break ## A second barcode in a sequence is not considerable. try: lCol_ref, sBarcode, intFirstBarcode = CoreHash.IndexHashTable(dRef, strSeqWindow, intFirstBarcode) except KeyError: continue sRef_seq = lCol_ref[0] sTarget_region = lCol_ref[1] iIndel_seq_len = len(sTarget_region) sRef_seq_after_barcode = lCol_ref[2] iIndel_start_from_barcode_pos = lCol_ref[3] iIndel_end_from_barcode_pos = lCol_ref[4] try: if self.strPamType == 'CAS9': iKbp_front_Indel_end = iIndel_end_from_barcode_pos - 6 ## cas9:-6, cpf1:-4 elif self.strPamType == 'CAF1': iKbp_front_Indel_end = iIndel_end_from_barcode_pos - 4 ## NN(N)*NNN(N)*NNNN except Exception: set_trace() """""" * ^ : iIndel_end_from_barcode_pos GGCG TCGCTCATGTACCTCCCGT TATAGTCTGTCATGCGATGGCG---TCGCTCATGTACCTCCCGTTACAGCCACAAAGCAGGA * GGCGTC GCTCATGTACCTCCCGT 6 17 """""" ## bug fix if sBarcode == """": continue (sSeq, iBarcode_matched, sQuery_seq_after_barcode, lQuery_qual_after_barcode) = \ self._CheckBarcodePosAndRemove(sSeq, sBarcode, iBarcode_matched, lQual) ## Alignment Seq to Ref npGapIncentive = InstGotoh.GapIncentive(sRef_seq_after_barcode) try: lResult = InstGotoh.RunCRISPResso2(sQuery_seq_after_barcode.upper(), sRef_seq_after_barcode.upper(), npGapIncentive) except Exception as e: logging.error(e, exc_info=True) continue sQuery_needle_ori = lResult[0] sRef_needle_ori = lResult[1] sRef_needle, sQuery_needle = self._TrimRedundantSideAlignment(sRef_needle_ori, sQuery_needle_ori) lInsertion_in_read, lDeletion_in_read = self._MakeIndelPosInfo(sRef_needle, sQuery_needle) # print 'sQuery_needle', sQuery_needle # print 'lInsertion_in_read: onebase', lInsertion_in_read # print 'lDeletion_in_read: onebase', lDeletion_in_read # print 'i5bp_front_Indel_end', i5bp_front_Indel_end # print 'iIndel_end_from_barcode_pos', iIndel_end_from_barcode_pos lTarget_indel_result = [] # ['20M2I', '23M3D' ...] iInsert_count = self._TakeInsertionFromAlignment(lInsertion_in_read, iKbp_front_Indel_end, lTarget_indel_result, iIndel_end_from_barcode_pos, iInsert_count) iDelete_count = self._TakeDeletionFromAlignment(lDeletion_in_read, iKbp_front_Indel_end, lTarget_indel_result, iIndel_end_from_barcode_pos, iDelete_count) if iInsert_count == 1 and iDelete_count == 1: iComplex_count = 1 iInsert_count = 0 iDelete_count = 0 # """""" test set # print 'sBarcode', sBarcode # print 'sTarget_region', sTarget_region # print 'sRef_seq_after_barcode', sRef_seq_after_barcode # print 'sSeq_after_barcode', sQuery_seq # print 'iIndel_start_from_barcode_pos', iIndel_start_from_barcode_pos # print 'iIndel_end_from_barcode_pos', iIndel_end_from_barcode_pos # """""" listResultFASTQ = self._MakeAndStoreQuality(sName, sSeq, lQual, dResult, sBarcode) """""" iQual_end_pos + 1 is not correct, because the position is like this. *NNNN*(N) So, '+ 1' is removed. Howerver, seqeunce inspects until (N) position. indel is detected front of *(N). """""" ################################################################ #print(lTarget_indel_result) #set_trace() # len(sQuery_seq_after_barcode) == len(lQuery_qual_after_barcode) if np.mean(lQuery_qual_after_barcode[iIndel_start_from_barcode_pos : iIndel_end_from_barcode_pos + 1]) >= self.intQualCutoff: ## Quality cutoff """""" 23M3I 23M is included junk_seq after barcode, barcorde junk targetseq others *********ACCCT-------------ACACACACC so should select target region. If junk seq is removed by target region seq index pos. """""" # filter start, iTarget_start_from_barcode = sRef_seq_after_barcode.index(sTarget_region) lTrimmed_target_indel_result = self._FixPos(lTarget_indel_result, iTarget_start_from_barcode) # print 'Check' # print sRef_seq_after_barcode # print sQuery_seq_after_barcode # print lTrimmed_target_indel_result # print('Trimmed', lTrimmed_target_indel_result) sRef_seq_after_barcode, sQuery_seq_after_barcode = self._StoreToDictResult(sRef_seq_after_barcode, sQuery_seq_after_barcode, iTarget_start_from_barcode, dResult, sBarcode, lTrimmed_target_indel_result, sTarget_region, sRef_needle_ori, sQuery_needle_ori, iInsert_count, iDelete_count, iComplex_count, listResultFASTQ) else: iInsert_count = 0 iDelete_count = 0 iComplex_count = 0 # total matched reads, insertion, deletion, complex dResult[sBarcode][self.intNumOfTotal] += iBarcode_matched dResult[sBarcode][self.intNumOfIns] += iInsert_count dResult[sBarcode][self.intNumOfDel] += iDelete_count dResult[sBarcode][self.intNumofCom] += iComplex_count iBarcode_matched = 0 iInsert_count = 0 iDelete_count = 0 iComplex_count = 0 #End:for #END:for return dResult def _CheckBarcodePosAndRemove(self, sSeq, sBarcode, iBarcode_matched, lQual): # Check the barcode pos and remove it. sSeq = sSeq.replace('\r', '') iBarcode_start_pos_FASTQ = sSeq.index(sBarcode) iBarcode_matched += 1 iBarcode_end_pos_FASTQ = iBarcode_start_pos_FASTQ + len(sBarcode) - 1 """""" junk seq target region ref: AGGAG AGAGAGAGAGA que: AGGAG AGAGAGAGAGA But, It doesnt know where is the target region because of existed indels. So, There is no way not to include it. """""" # Use this. sQuery_seq_after_barcode = sSeq[iBarcode_end_pos_FASTQ + 1:] lQuery_qual_after_barcode = lQual[iBarcode_end_pos_FASTQ:] return (sSeq, iBarcode_matched, sQuery_seq_after_barcode, lQuery_qual_after_barcode) def _TrimRedundantSideAlignment(self, sRef_needle_ori, sQuery_needle_ori): # detach forward ---, backward --- # e.g. ref ------AAAGGCTACGATCTGCG------ # query AAAAAAAAATCGCTCTCGCTCTCCGATCT # trimmed ref AAAGGCTACGATCTGCG # trimmed qeury AAATCGCTCTCGCTCTC iReal_ref_needle_start = 0 iReal_ref_needle_end = len(sRef_needle_ori) iRef_needle_len = len(sRef_needle_ori) for i, sRef_nucle in enumerate(sRef_needle_ori): if sRef_nucle in ['A', 'C', 'G', 'T']: iReal_ref_needle_start = i break for i, sRef_nucle in enumerate(sRef_needle_ori[::-1]): if sRef_nucle in ['A', 'C', 'G', 'T']: iReal_ref_needle_end = iRef_needle_len - (i + 1) # forward 0 1 2 len : 3 # reverse 2 1 0, len - (2 + 1) = 0 break sRef_needle = sRef_needle_ori[iReal_ref_needle_start:iReal_ref_needle_end + 1] if iReal_ref_needle_start: sQuery_needle = sQuery_needle_ori[:iReal_ref_needle_end] sQuery_needle = sQuery_needle_ori[:len(sRef_needle)] # detaching completion return (sRef_needle, sQuery_needle) def _MakeIndelPosInfo(self, sRef_needle, sQuery_needle): # indel info making. iNeedle_match_pos_ref = 0 iNeedle_match_pos_query = 0 iNeedle_insertion = 0 iNeedle_deletion = 0 lInsertion_in_read = [] # insertion result [[100, 1], [119, 13]] lDeletion_in_read = [] # deletion result [[97, 1], [102, 3]] # print 'sRef_needle', sRef_needle # print 'sQuery_needle', sQuery_needle for i, (sRef_nucle, sQuery_nucle) in enumerate(zip(sRef_needle, sQuery_needle)): if sRef_nucle == '-': iNeedle_insertion += 1 if sQuery_nucle == '-': iNeedle_deletion += 1 if sRef_nucle in ['A', 'C', 'G', 'T']: if iNeedle_insertion: lInsertion_in_read.append([iNeedle_match_pos_ref, iNeedle_insertion]) iNeedle_insertion = 0 iNeedle_match_pos_ref += 1 if sQuery_nucle in ['A', 'C', 'G', 'T']: if iNeedle_deletion: lDeletion_in_read.append([iNeedle_match_pos_query, iNeedle_deletion]) iNeedle_match_pos_query += iNeedle_deletion iNeedle_deletion = 0 iNeedle_match_pos_query += 1 # print 'sRef_needle', sRef_needle return (lInsertion_in_read, lDeletion_in_read) def _TakeInsertionFromAlignment(self, lInsertion_in_read, iKbp_front_Indel_end, lTarget_indel_result, iIndel_end_from_barcode_pos, iInsert_count): """""" ins case ...............................NNNNNNNNNNNNNN....NNNNNNNNNNNNNNNNNNN*NNNNNAGCTT """""" for iMatch_pos, iInsertion_pos in lInsertion_in_read: if self.strPamType == 'CAS9': # if i5bp_front_Indel_end == iMatch_pos -1 or iIndel_end_from_barcode_pos == iMatch_pos -1: # iMatch_pos is one base # original ver if iKbp_front_Indel_end - self.intInsertionWin <= iMatch_pos - 1 <= iKbp_front_Indel_end + self.intInsertionWin: # iMatch_pos is one base iInsert_count = 1 lTarget_indel_result.append(str(iMatch_pos) + 'M' + str(iInsertion_pos) + 'I') elif self.strPamType == 'CPF1': if iKbp_front_Indel_end - self.intInsertionWin <= iMatch_pos - 1 <= iKbp_front_Indel_end + self.intInsertionWin or \ iIndel_end_from_barcode_pos - self.intInsertionWin <= iMatch_pos - 1 <= iIndel_end_from_barcode_pos + self.intInsertionWin: # iMatch_pos is one base iInsert_count = 1 lTarget_indel_result.append(str(iMatch_pos) + 'M' + str(iInsertion_pos) + 'I') return iInsert_count def _TakeDeletionFromAlignment(self, lDeletion_in_read, iKbp_front_Indel_end, lTarget_indel_result, iIndel_end_from_barcode_pos, iDelete_count): """""" del case 1 ...............................NNNNNNNNNNNNNN....NNNNNNNNNNNNNNNNNNNNN**NNNAGCTT del case 2 ...............................NNNNNNNNNNNNNN....NNNNNNNNNNNNNNNNNNNNN**NNNNNCTT """""" for iMatch_pos, iDeletion_pos in lDeletion_in_read: """""" Insertion: 30M3I ^ ACGT---ACGT ACGTTTTACGT -> check this seq Insertion just check two position Deletion: 30M3D ^ ACGTTTTACGT ACGT---ACGT -> check this seq But deletion has to includes overlap deletion. """""" if self.strPamType == 'CAS9': if (iMatch_pos - self.intDeletionWin - 1 <= iKbp_front_Indel_end and iKbp_front_Indel_end < (iMatch_pos + iDeletion_pos + self.intDeletionWin - 1)): iDelete_count = 1 lTarget_indel_result.append(str(iMatch_pos) + 'M' + str(iDeletion_pos) + 'D') elif self.strPamType == 'CPF1': if (iMatch_pos - self.intDeletionWin - 1 <= iKbp_front_Indel_end and iKbp_front_Indel_end < (iMatch_pos + iDeletion_pos + self.intDeletionWin - 1)) or \ (iMatch_pos - self.intDeletionWin - 1 <= iIndel_end_from_barcode_pos and iIndel_end_from_barcode_pos < (iMatch_pos + iDeletion_pos + self.intDeletionWin - 1)): iDelete_count = 1 lTarget_indel_result.append(str(iMatch_pos) + 'M' + str(iDeletion_pos) + 'D') return iDelete_count def _MakeAndStoreQuality(self, sName, sSeq, lQual, dResult, sBarcode): listResultFASTQ = [sName, sSeq, '+', ''.join(chr(i + 33) for i in lQual)] dResult[sBarcode][self.intTotalFastq].append(listResultFASTQ) return listResultFASTQ def _FixPos(self, lTarget_indel_result, iTarget_start_from_barcode): lTrimmed_target_indel_result = [] for sINDEL in lTarget_indel_result: # B - A is not included B position, so +1 iMatch_target_start = int(sINDEL.split('M')[0]) - iTarget_start_from_barcode """""" This part determines a deletion range. ^ current match pos AGCTACGATCAGCATCTGACTTACTTC[barcode] ^ fix the match start at here. (target region) AGCTACGATCAGCATC TGACTTACTTC[barcode] if iMatch_target_start < 0: sContinue = 1 But, this method has some problems. ^ barcode start AGCTACGATCAGCAT*********C[barcode] Like this pattern doesn't seleted. because, deletion checking is begun the target region start position. Thus, I have fixed this problem. """""" if iMatch_target_start <= -(iTarget_start_from_barcode): # print(iMatch_target_start, iTarget_start_from_barcode) continue lTrimmed_target_indel_result.append(str(iMatch_target_start) + 'M' + sINDEL.split('M')[1]) # filter end return lTrimmed_target_indel_result def _StoreToDictResult(self, sRef_seq_after_barcode, sQuery_seq_after_barcode, iTarget_start_from_barcode, dResult, sBarcode, lTrimmed_target_indel_result, sTarget_region, sRef_needle_ori, sQuery_needle_ori, iInsert_count, iDelete_count, iComplex_count, listResultFASTQ): sRef_seq_after_barcode = sRef_seq_after_barcode[iTarget_start_from_barcode:] sQuery_seq_after_barcode = sQuery_seq_after_barcode[iTarget_start_from_barcode:] dResult[sBarcode][self.intIndelInfo].append([sRef_seq_after_barcode, sQuery_seq_after_barcode, lTrimmed_target_indel_result, sTarget_region, sRef_needle_ori, sQuery_needle_ori]) if iInsert_count: dResult[sBarcode][self.intInsFastq].append(listResultFASTQ) elif iDelete_count: dResult[sBarcode][self.intDelFastq].append(listResultFASTQ) elif iComplex_count: dResult[sBarcode][self.intComFastq].append(listResultFASTQ) return (sRef_seq_after_barcode, sQuery_seq_after_barcode) def CalculateIndelFrequency(self, dResult): dResult_INDEL_freq = {} for sBarcode, lValue in dResult.items(): # lValue[gINDEL_info] : [[sRef_seq_after_barcode, sQuery_seq_after_barcode, lTarget_indel_result, sTarget_region], ..]) sRef_seq_loop = '' llINDEL_store = [] # ['ACAGACAGA', ['20M2I', '23M3D']] dINDEL_freq = {} if lValue[self.intIndelInfo]: for sRef_seq_loop, sQuery_seq, lINDEL, sTarget_region, sRef_needle, sQuery_needle in lValue[self.intIndelInfo]: # llINDEL : [['20M2I', '23M3D'], ...] # print 'lINDEL', lINDEL for sINDEL in lINDEL: llINDEL_store.append([sQuery_seq, sINDEL, sRef_needle, sQuery_needle]) iTotal = len([lINDEL for sQuery_seq, lINDEL, sRef_needle, sQuery_needle in llINDEL_store]) for sQuery_seq, sINDEL, sRef_needle, sQuery_needle in llINDEL_store: dINDEL_freq[sINDEL] = [[], 0, [], []] for sQuery_seq, sINDEL, sRef_needle, sQuery_needle in llINDEL_store: dINDEL_freq[sINDEL][1] += 1 dINDEL_freq[sINDEL][0].append(sQuery_seq) dINDEL_freq[sINDEL][2].append(sRef_needle) dINDEL_freq[sINDEL][3].append(sQuery_needle) for sINDEL in dINDEL_freq: lQuery = dINDEL_freq[sINDEL][0] iFreq = dINDEL_freq[sINDEL][1] lRef_needle = dINDEL_freq[sINDEL][2] lQuery_needle = dINDEL_freq[sINDEL][3] try: dResult_INDEL_freq[sBarcode].append([sRef_seq_loop, lQuery, sINDEL, float(iFreq) / iTotal, sTarget_region, lRef_needle, lQuery_needle]) except (KeyError, TypeError, AttributeError) as e: dResult_INDEL_freq[sBarcode] = [] dResult_INDEL_freq[sBarcode].append([sRef_seq_loop, lQuery, sINDEL, float(iFreq) / iTotal, sTarget_region, lRef_needle, lQuery_needle]) # end: if lValue[gINDEL_info] # end: for sBarcode, lValue return dResult_INDEL_freq # end1: return # end: def #END:class class clsOutputMaker(object): def __init__(self, InstParameter): self.strOutputdir = InstParameter.strOutputdir self.strForwardFqPath = InstParameter.strForwardFqPath def MakePickleOutput(self, dictResult, dictResultIndelFreq, strBarcodePamPos=''): dictOutput = {'dictResult': dictResult, 'dictResultIndelFreq': dictResultIndelFreq, 'strBarcodePamPos': strBarcodePamPos} with open('{outdir}/Tmp/Pickle/{fq}.pickle'.format(outdir=self.strOutputdir, fq=os.path.basename(self.strForwardFqPath)), 'wb') as Pickle: pickle.dump(dictOutput, Pickle) def Main(): InstParameter = clsParameter() logging.basicConfig(format='%(process)d %(levelname)s %(asctime)s : %(message)s', level=logging.DEBUG, filename=InstParameter.strLogPath, filemode='a') logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logging.info('Program start : %s' % InstParameter.strForwardFqPath) logging.info('File Open') InstFileOpen = clsFastqOpener(InstParameter) listFastqForward = InstFileOpen.OpenFastqForward() if InstParameter.strPair == 'True': listFastqReverse = InstFileOpen.OpenFastqReverse() InstIndelSearch = clsIndelSearchParser(InstParameter) InstOutput = clsOutputMaker(InstParameter) if InstParameter.strPamType == 'CPF1': logging.info('Search barcode INDEL pos') dRef, dResult = InstIndelSearch.SearchBarcodeIndelPosition(InstParameter.strBarcodePamPos) # ref check. logging.info('Search INDEL forward') dResultForward = InstIndelSearch.SearchIndel(listFastqForward, dRef, dResult) if InstParameter.strPair == 'True': logging.info('Search INDEL reverse') dResultReverse = InstIndelSearch.SearchIndel(listFastqReverse, dRef, dResultForward) logging.info('Calculate INDEL frequency') dictResultIndelFreq = InstIndelSearch.CalculateIndelFrequency(dResultReverse) logging.info('Make pickle output forward') InstOutput.MakePickleOutput(dResultReverse, dictResultIndelFreq) else: logging.info('Calculate INDEL frequency') dictResultIndelFreq = InstIndelSearch.CalculateIndelFrequency(dResultForward) logging.info('Make pickle output forward') InstOutput.MakePickleOutput(dResultForward, dictResultIndelFreq) elif InstParameter.strPamType == 'CAS9': logging.info('Search barcode INDEL pos') dRef, dResult = InstIndelSearch.SearchBarcodeIndelPosition(InstParameter.strBarcodePamPos) logging.info('Search INDEL') dResult_forward = InstIndelSearch.SearchIndel(listFastqForward, dRef, dResult, InstParameter.strBarcodePamPos) logging.info('Calculate INDEL frequency') dResult_INDEL_freq = InstIndelSearch.CalculateIndelFrequency(dResult_forward) logging.info('Make pickle output forward') InstOutput.MakePickleOutput(dResult_forward, dResult_INDEL_freq, InstParameter.strBarcodePamPos) logging.info('Program end : %s' % InstParameter.strForwardFqPath) #END:def if __name__ == '__main__': Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Make_user_folder.sh",".sh","659","18","#!/bin/bash user=JaeWoo project=JaeWoo_test_samples [ ! -d ./Input ] && { `mkdir ./Input`; } [ ! -d ./User ] && { `mkdir ./User`; } [ ! -d ./Output ] && { `mkdir ./Output`; } [ ! -d ./Input/${user} ] && { `mkdir ./Input/${user}`; } [ ! -d ./Input/${user}/FASTQ ] && { `mkdir ./Input/${user}/FASTQ`; } [ ! -d ./Input/${user}/FASTQ/${project} ] && { `mkdir ./Input/${user}/FASTQ/${project}`; } [ ! -d ./Input/${user}/Reference ] && { `mkdir ./Input/${user}/Reference`; } [ ! -d ./Input/${user}/Reference/${project} ] && { `mkdir ./Input/${user}/Reference/${project}`; } [ ! -d ./User/${user} ] && { `mkdir ./User/${user}`; } > ./User/${user}/${project}.txt ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Debugger.py",".py","6512","187","#!/media/hkim/Pipeline/Indel_searcher_2/miniconda2/bin/python2.7 import os, re, sys, pickle import subprocess as sp from Bio import AlignIO from pdb import set_trace strFastq='/media/hkim/Pipeline/CRISPR_Indel_searcher/Input/FASTQ/190807_Nahye_24k_NG_rep1-24kLib/NG_rep1.extendedFrags.fastq' strBarcode='TTTGGTGATCTCACTCTCGACAACTC' sRef_fa = './Input/Reference/190807_Nahye_24k_NG_rep1-24kLib/Reference.fa' sBarcode_PAM_pos='Foward' def CountBar(): with open(strFastq) as Input: intCnt=0 for strRow in Input: if strBarcode in strRow: intCnt+=1 print(intCnt) def ExtractFastq(): with open(strFastq) as Input,\ open('./Input/FASTQ/Test1/Test1.fastq_target', 'w') as Output: listFastq = [] for i, strRow in enumerate(Input): listFastq.append(strRow.replace('\n', '')) if i % 4 == 3: #print(listFastq) if strBarcode in listFastq[1]: Output.write('\n'.join(listFastq)+'\n') listFastq = [] def LoadPickle(): with open('Output/Test1/Pickle/Test1.fastq_1.fq.pickle', 'rb') as Input: obj = pickle.load(Input) set_trace() def CheckSearch(): dRef = {} dResult = {} with open(sRef_fa) as Ref: iCount = 0 sBarcode = """" sTarget_region = """" for sRow in Ref: iCount += 1 if iCount % 2 != 0: # barcode target region # >CGCTCTACGTAGACA:CTCTATTACTCGCCCCACCTCCCCCAGCCC sBarcode_indel_seq = sRow.strip().replace('\n', '').replace('\r', '').split(':') sBarcode = sBarcode_indel_seq[0].replace('>', '') sTarget_region = sBarcode_indel_seq[1] ## Reverse the sentence. If it is done, all methods are same before work. if sBarcode_PAM_pos == 'Reverse': sBarcode = sBarcode[::-1] sTarget_region = sTarget_region[::-1] elif iCount % 2 == 0: ## Reverse sRef_seq = sRow.strip().replace('\n', '').replace('\r', '') if sBarcode_PAM_pos == 'Reverse': sRef_seq = sRef_seq[::-1] Seq_matcher = re.compile(r'(?=(%s))' % sTarget_region) # iIndel_start_pos = sRef_seq.index(sTarget_region) # There is possible to exist two indel. iIndel_start_pos = Seq_matcher.finditer(sRef_seq) for i, match in enumerate(iIndel_start_pos): iIndel_start_pos = match.start() # print iIndel_start_pos # print len(sTarget_region) # print sRef_seq iIndel_end_pos = iIndel_start_pos + len(sTarget_region) - 1 try: iBarcode_start_pos = sRef_seq.index(sBarcode) #if iIndel_start_pos <= iBarcode_start_pos: # print(iIndel_start_pos, iBarcode_start_pos) # raise IndexError('indel is before barcode') iBarcode_end_pos = iBarcode_start_pos + len(sBarcode) - 1 sRef_seq_after_barcode = sRef_seq[iBarcode_end_pos + 1:] # modified. to -1 iIndel_end_next_pos_from_barcode_end = iIndel_end_pos - iBarcode_end_pos - 1 iIndel_start_next_pos_from_barcode_end = iIndel_start_pos - iBarcode_end_pos - 1 # ""barcode""-------------*(N) that distance. # ^ ^ ^ # *NNNN*NNNN # ^ ^ indel pos, the sequence matcher selects indel event pos front of it. dRef[sBarcode] = (sRef_seq, sTarget_region, sRef_seq_after_barcode, iIndel_start_next_pos_from_barcode_end, iIndel_end_next_pos_from_barcode_end, iIndel_start_pos,iIndel_end_pos) # total matched reads, insertion, deletion, complex dResult[sBarcode] = [0, 0, 0, 0, [], [], [], [], []] except ValueError: continue with open('test.seq') as Input: iBarcode_matched = 0 for sSeq in Input: sSeq = sSeq.replace('\n','') listSeqWindow = [sSeq[i:i + 26] for i in range(len(sSeq))[:-25]] iNeedle_matched = 0 iInsert_count = 0 iDelete_count = 0 iComplex_count = 0 intFirstBarcode = 0 ## check whether a barcode is one in a sequence. for strSeqWindow in listSeqWindow: if intFirstBarcode == 1: break ## A second barcode in a sequence is not considerable. try: lCol_ref = dRef[strSeqWindow] sBarcode = strSeqWindow intFirstBarcode = 1 except KeyError: continue iBarcode_matched += 1 print(iBarcode_matched) def CheckNeedle(): sBarcode = 'TTTGACTAGTCATCACTATAGCATAA' sRef_seq_after_barcode = 'TACAGTGTTTTTTTTTTTTCAGAGGAAGCTTGGCGTAACTAGATCT' sQuery_seq_after_barcode = 'TACAGTGTTTTTTTTTTTCAGAGGAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAATA' sRef_seq = r'<(echo -e "">{name}\n{seq}"")'.format(name='Ref', seq=sRef_seq_after_barcode) sQuery_seq = r'<(echo -e "">{name}\n{seq}"")'.format(name='Query', seq=sQuery_seq_after_barcode) sNeedle_cmd = r""/bin/bash -c 'needle -filter {0} {1} -outfile stdout -gapopen {2} -gapextend {3} -endweight Y -endopen {4} -endextend {5}'"".format(sRef_seq, sQuery_seq, '20', '1', '20', '1') Needle_result = sp.Popen(sNeedle_cmd, stdout=sp.PIPE, stderr=sp.PIPE, universal_newlines=True,shell=True) lResult = [Instance.seq._data for Instance in AlignIO.read(Needle_result.stdout, ""emboss"")] print(lResult) def LoggingTest(): import logging logging.basicConfig(format='%(process)d %(levelname)s %(asctime)s : %(message)s', level=logging.DEBUG, filename='test.log', filemode='a' ) logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) logging.info('test') a = a * 10 def Main(): #CountBar() #ExtractFastq() #LoadPickle() #CheckSearch() #CheckNeedle() LoggingTest() Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Indel_normalization.py",".py","7748","195","import os, sys, logging from pdb import set_trace import pandas as pd sys.path.insert(0, os.path.dirname(os.getcwd())) from Core.CoreSystem import SplitSampleInfo, AttachSeqToIndel, Helper logging.basicConfig(format='%(process)d %(levelname)s %(asctime)s : %(message)s', level=logging.INFO) strProjectFile = sys.argv[1] strUserName = sys.argv[2] strProjectName = sys.argv[3] """""" /media/hkim/Pipeline/Indel_searcher_2/miniconda2/bin/python ./Indel_normalization.py User/JaeWoo/JaeWoo_test_samples.txt JaeWoo JaeWoo_test_samples """""" def MakeIndelSeqDict(): """""" dictD0Indel: {'sample_*': {'ACGATCGAT': {'Total': 300, {'ACGATCGAT_30M2I_AG': {'IndelCount': 3}}}}}}} validation ./Output/JaeWoo/JaeWoo_test_samples/190819_Nahye_12K_D7_2_D0_1-Cas9D7/Tmp grep TTTGGATCGTCTATCGTCG 190819_Nahye_12K_D7_2_D0_1-Cas9D7_Indel_freq.txt | grep 18M16D | wc -l -> Indel count """""" dictD0Indel = {} dictExpIndel = {} with open(strProjectFile) as SampleList: for strSample in SampleList: print(strSample) tupSampleInfo = SplitSampleInfo(strSample) if not tupSampleInfo: continue strSample, strRef, strExpCtrl = tupSampleInfo if strExpCtrl == 'CTRL': dictD0Indel[strSample] = {} elif strExpCtrl == 'EXP': dictExpIndel[strSample] = {} with open('./Output/{user}/{project}/{sample}/Tmp/{sample}_Indel_freq.txt'.format( user=strUserName, project=strProjectName, sample=strSample)) as IndelFreq,\ open('./Output/{user}/{project}/{sample}/Result/{sample}_Summary_result.tsv'.format( user=strUserName, project=strProjectName, sample=strSample)) as TotalResult: for strRow in IndelFreq: listCol = strRow.replace('\n','').split('\t') strBarcode = listCol[0] strIndelPos = listCol[2] strRefseq = listCol[4] strQueryseq = listCol[5] if strExpCtrl == 'CTRL': AttachSeqToIndel(strSample, strBarcode, strIndelPos, strRefseq, strQueryseq, dictD0Indel) elif strExpCtrl == 'EXP': AttachSeqToIndel(strSample, strBarcode, strIndelPos, strRefseq, strQueryseq, dictExpIndel) TotalResult.readline() ## skip header for strRow in TotalResult: listCol = strRow.replace('\n', '').split('\t') strBarcode = listCol[0] intTotal = int(listCol[1]) try: dictD0Indel[strSample][strBarcode]['Total'] = intTotal except KeyError: pass try: dictExpIndel[strSample][strBarcode]['Total'] = intTotal except KeyError: pass #set_trace() #print(dictSub.items())# return (dictD0Indel, dictExpIndel) def MakeTmp(dictD0Indel, dictExpIndel): for dictIndel in [dictD0Indel, dictExpIndel]: for strSample, dictBarcode in dictIndel.items(): strTmpDir = './Output/{user}/{project}/{sample}/Tmp'.format(user=strUserName, project=strProjectName, sample=strSample) with open(os.path.join(strTmpDir, strSample+'_indel_seq_count.txt'), 'w') as Output: for strBarcode, dictCountTotalAndIndel in dictBarcode.items(): for strIndelSeq, dictCount in dictCountTotalAndIndel.items(): if strIndelSeq == 'Total': continue Output.write('\t'.join([strIndelSeq, str(dictCount['IndelCount'])])+'\n') def MergeD0SampleResults(dictD0Indel): """""" dictD0Indel: {'sample_*': {'ACGATCGAT': {'Total': 300, {'ACGATCGAT_30M2I_AG': {'IndelCount': 3}}}}}}} -> sum total, sum indelcount dictD0IndelMerge: {'ACGATCGAT': {'Total': 600, {'ACGATCGAT_30M2I_AG': {'IndelCount': 5}}}}}}} """""" dictD0IndelMerge = {} for strD0SampleName in dictD0Indel: for strBarcode, dictCountTotalAndIndel in dictD0Indel[strD0SampleName].items(): try: dictD0IndelMerge[strBarcode]['Total'] += dictCountTotalAndIndel['Total'] except KeyError: dictD0IndelMerge[strBarcode] = {} dictD0IndelMerge[strBarcode]['Total'] = dictCountTotalAndIndel['Total'] for strIndelSeq, dictCount in dictCountTotalAndIndel.items(): ## dcitCount : {'TTTGAGCATATCACACGAT:33M1D_T': {'IndelCount': 0}} if strIndelSeq == 'Total': continue try: dictD0IndelMerge[strBarcode][strIndelSeq]['IndelCount'] += dictCount['IndelCount'] except KeyError: dictD0IndelMerge[strBarcode][strIndelSeq] = {} dictD0IndelMerge[strBarcode][strIndelSeq]['IndelCount'] = dictCount['IndelCount'] return dictD0IndelMerge def SubtractIndelWithD0(dictD0IndelMerge, dictExpIndel): """""" dictD0IndelMerge: indel proportion - dictExpIndel: indel proportion """""" strD0SubResultDir = './Output/{user}/{project}/All_results/D0SubResult'.format(user=strUserName, project=strProjectName) Helper.MakeFolderIfNot(strD0SubResultDir) for strSample, dictBarcode in dictExpIndel.items(): with open(os.path.join(strD0SubResultDir, '{sample}_D0SubResult.txt').format(sample=strSample), 'w') as Output: Output.write('Barcode_indel_seq\tD0_total\tD0_indel_prop\tExp_total\tExp_indel_prop\tD0_sub_indel_prop\n') for strBarcode, dictCountTotalAndIndel in dictBarcode.items(): intExpTotal = dictCountTotalAndIndel['Total'] for strIndelSeq, dictCount in dictCountTotalAndIndel.items(): if strIndelSeq == 'Total': continue try: intD0Total = dictD0IndelMerge[strBarcode]['Total'] intD0Count = dictD0IndelMerge[strBarcode][strIndelSeq]['IndelCount'] floD0Prop = round(intD0Count / float(intD0Total), 6) intExpCount = dictCount['IndelCount'] floExpProp = round(intExpCount / float(intExpTotal), 6) floSubExpIndel = floExpProp - floD0Prop if floSubExpIndel < 0: floSubExpIndel = 0 Output.write('\t'.join(map(str, [strIndelSeq,intD0Total, floD0Prop, intExpTotal, floExpProp, floSubExpIndel]))+'\n') except KeyError: intExpCount = dictCount['IndelCount'] floExpProp = round(intExpCount / float(intExpTotal), 6) Output.write('\t'.join(map(str, [strIndelSeq, 'None', 'None', intExpTotal, floExpProp, floExpProp]))+'\n') def Main(): logging.info(""Indel normalization Start"") logging.info(""MakeIndelSeqDict"") dictD0Indel, dictExpIndel = MakeIndelSeqDict() logging.info(""MakeTmp"") MakeTmp(dictD0Indel, dictExpIndel) logging.info(""MergeD0SampleResults"") dictD0IndelMerge = MergeD0SampleResults(dictD0Indel) logging.info(""SubtractIndelWithD0"") SubtractIndelWithD0(dictD0IndelMerge, dictExpIndel) logging.info(""Indel normalization End"") Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Run_cmd.sh",".sh","752","27","#!/bin/bash #################### ## User parameter ## ################################### user=JaeWoo project=JaeWoo_test_samples pam_type=Cas9 pam_pos=Forward thread=15 gap_open=-10 ## default gap_extend=1 ## default ################################### while read python_path;do python=$python_path done < ../PythonPath.txt [ ! -d ./Output/${user} ] && { `mkdir ./Output/${user}`; } [ ! -d ./Output/${user}/${project} ] && { `mkdir ./Output/${user}/${project}`; } [ ! -d ./Output/${user}/${project}/Log ] && { `mkdir ./Output/${user}/${project}/Log`; } nohup $python ./Run_indel_searcher.py --python $python --user $user --project $project --pam_type $pam_type --pam_pos $pam_pos -t $thread > ./Output/${user}/${project}/Log/log.txt 2>&1 & ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Kill_jobs.sh",".sh","253","8","#!/bin/bash # Confirm the jobs. # ps aux | grep hkim | grep BaseEdit_freq_ver1.0.py | less kill -9 $(ps aux | grep hkim | grep Run_indel_searcher | awk '{print$2}') kill -9 $(ps aux | grep hkim | grep Indel_searcher_crispresso_hash | awk '{print$2}') ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Flash_pair_read_merge.py",".py","2061","57","import os, sys import subprocess as sp strUser = sys.argv[1] strProject = sys.argv[2] strFlash = sys.argv[3] strThread = sys.argv[4] def RunFlash(): strFlashDir = '../{flash}'.format(flash=strFlash) strProjectDir = './Input/{user}/FASTQ/{project}'.format(user=strUser, project=strProject) for strSampleDir in os.listdir(strProjectDir): strSamplePath = os.path.join(strProjectDir, strSampleDir) if os.path.isdir(strSamplePath): listPairFiles = [] for strFile in os.listdir(os.path.join(strProjectDir, strSampleDir)): if '_1.fastq.gz' in strFile or '_2.fastq.gz' in strFile: listPairFiles.append(strFile) strForward = os.path.join(strSamplePath, listPairFiles[0]) strReverse = os.path.join(strSamplePath, listPairFiles[1]) strOutput = os.path.join(strSamplePath, listPairFiles[0].replace('_1.fastq.gz', '')) strLog = './Output/{user}/{project}/Log'.format(user=strUser, project=strProject) if not os.path.isdir(strLog): os.makedirs(strLog) strCmd = '{flash_dir}/flash -m 10 -M 400 -O -o {output} -t {thread} {r1} {r2} >{log}/flash.log 2>&1 '.format( flash_dir=strFlashDir, output=strOutput, thread=strThread, r1=strForward, r2=strReverse, log=strLog) print(strCmd) sp.call(strCmd, shell=True) print('complete, {fow} {rev} are moved to project folder'.format(fow=listPairFiles[0], rev=listPairFiles[1])) sp.call('mv {sample_path}/*.fastq.gz {project_dir} &&' ' rm {sample_path}/*hist* {project_dir} &&' ' rm {sample_path}/*notCombined* {project_dir}'.format(sample_path=strSamplePath, project_dir=strProjectDir), shell=True) def Main(): RunFlash() Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Run_random_barcode.sh",".sh","392","25","#!/bin/bash #################### ## User parameter ## #################################### user=SH project=p53_screening thread=2 #################################### while read python_path;do python=$python_path done < ../PythonPath.txt nohup $python ./Summary_Random_barcode.py -u $user -p $project -t $thread > ./Output/${user}/${project}/Log/Random_barcode_log.txt 2>&1 & ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Indel_frequency_calculator.py",".py","2996","77","import os, sys, logging from pdb import set_trace from datetime import datetime from collections import OrderedDict from collections import namedtuple as nt strOutputDir = sys.argv[1] strSample = sys.argv[2] strLogPath = sys.argv[3] logging.basicConfig(format='%(process)d %(levelname)s %(asctime)s : %(message)s', level=logging.DEBUG, filename=strLogPath, filemode='a') logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) def MakeIndelSummary(): """""" Input TTTGCAGAGTATATCACACCATATCA AGTCAGACAAGGAGCACCACACGGTGGAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA 17M1I 0.134 AGTCAGACAAGGAGCAC-ACACGGTGGAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTC------- AGTCAGACAAGGAGCACCACACGGTGGAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA 0: barcode 1: target region 2: indel pos 3: total freq 4: ref seq 5: query seq Output TTTGTCTCGTACACTCGTATGCTGCA 2 18M2D:1:50.0, 24M1I:1:50.0 TTTGACATCTACAGTGTCTCTCCACA 2 22M1I:2:100.0 """""" listOutput = [] with open('{outdir}/Tmp/{sample}_Indel_freq.txt'.format(sample=strSample, outdir=strOutputDir)) as InputFreq,\ open('{outdir}/Tmp/{sample}_Indel_summary.txt'.format(sample=strSample, outdir=strOutputDir), 'w') as OutputFreq: listTable = [strRow.replace('\n', '').split('\t') for strRow in InputFreq] intTotal = len(listTable) #strBarcode = listCol[0] dictINDEL = OrderedDict({listCol[0]:OrderedDict({'Total':0}) for listCol in listTable}) ## {'TTTGACATCTACAGTGTCTCTCCACA': {22M1I : 2, ...}} for listCol in listTable: strBarcode = listCol[0] strIndel = listCol[2] dictINDEL[strBarcode]['Total'] += 1 try: dictINDEL[strBarcode][strIndel] += 1 except KeyError: dictINDEL[strBarcode][strIndel] = 1 #dictINDEL = OrderedDict(sorted(dictINDEL.items(), key=lambda t: t[1], reverse=True)) ## sort value count. list2Result = [] for strBarcode in dictINDEL: intTotal = dictINDEL[strBarcode]['Total'] list2INDEL = [[strIndel, intCount, round(intCount/float(intTotal),3)*100] for strIndel, intCount in dictINDEL[strBarcode].items()] list2INDEL = sorted(list2INDEL, key=lambda x: x[1], reverse=True) strIndelResult = ''.join([':'.join(map(str, listINDEL))+', ' for listINDEL in list2INDEL if listINDEL[0] != 'Total']) list2Result.append([strBarcode, intTotal, strIndelResult]) for listResult in sorted(list2Result, key=lambda x: x[1], reverse=True): OutputFreq.write('\t'.join(map(str, listResult)) + '\n') if __name__ == '__main__': logging.info('Indel frequency calculator start: %s' % str(datetime.now())) MakeIndelSummary() logging.info('Indel frequency calculator end: %s' % str(datetime.now())) ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/BaseEdit_input_converter.py",".py","6100","130","import os,sys from pdb import set_trace import multiprocessing as mp sys.path.insert(0, os.path.dirname(os.getcwd())) from Core.CoreSystem import Helper strUser = sys.argv[1] strProject = sys.argv[2] print('Usage : python ./BaseEdit_input_converter.py user_name project_name') print('Usage : python ./BaseEdit_input_converter.py JaeWoo Test_samples') """""" --> Conversion format Barcode.txt ACACACACACACAGCTCATA:ACACACACACACAGCTCATA Reference.txt ACACACACACACAGCTCATA:TTTGTATACACGCATGTATGCATCCTGCAGGTCTCGCTCTGACATGTGGGAAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA Query reads ACACACACACACAGCTCATA.txt BaseEdit output Barcode.txt YSKim_0525+01614_98_repeat1:TATACACGCATGTAT ... Reference.txt YSKim_0525+01614_98_repeat1:TTTGTATACACGCATGTAT GCATCCTGCAGGTCTCGCTCTGACATGTGGGAAAGCTTGGCGTAACTAGATCTCTACTCTACCACTTGTACTTCAGCGGTCAGCTTACTCGACTTAA ... Read YSKim_0525+01614_98_repeat1.txt """""" def Convert_Indelsearcher_output(strSampleRefGroup): listSampleRefGroup = strSampleRefGroup.replace('\n', '').replace('\r', '').split('\t') strSample = listSampleRefGroup[0] strRef = listSampleRefGroup[1] print('Processing: %s, %s' % (strSample, strRef)) strBaseEditRefFolder = '../Base_edit_2/Input/{user}/Reference/{project}/{ref}'.format(user=strUser, project=strProject, ref=strRef) strBaseEditQueryFolder = '../Base_edit_2/Input/{user}/Query/{project}/{sample}'.format(user=strUser, project=strProject, sample=strSample) try: Helper.MakeFolderIfNot(strBaseEditRefFolder) Helper.MakeFolderIfNot(strBaseEditQueryFolder) except OSError as e: print(e) pass ## BaseEdit refer format : filename, barcode, reference ReferenceFile_in_IndelSearcher = open('./Input/{user}/Reference/{project}/{ref}/Reference_sequence.txt'.format(user=strUser, project=strProject, ref=strRef)) BarcodeFile_in_IndelSearcher = open('./Input/{user}/Reference/{project}/{ref}/Barcode.txt'.format(user=strUser, project=strProject, ref=strRef)) BarcodeFile_for_BaseEdit = open('../Base_edit_2/Input/{user}/Reference/{project}/{ref}/Barcode.txt'.format(user=strUser, project=strProject, ref=strRef), 'w') Reference_for_BaseEdit = open('../Base_edit_2/Input/{user}/Reference/{project}/{ref}/Reference.txt'.format(user=strUser, ref=strRef, project=strProject), 'w') ## conversion target to barcode:refseq dictBarcodeSeq = {} for strBarcodeIndelSearcher, strReferenceIndelSearcher in zip(BarcodeFile_in_IndelSearcher, ReferenceFile_in_IndelSearcher): strBarcodeIndelSearcher = strBarcodeIndelSearcher.replace('\n', '').strip() strReferenceIndelSearcher = strReferenceIndelSearcher.replace('\n', '').strip() dictBarcodeSeq[strBarcodeIndelSearcher] = [] BarcodeFile_for_BaseEdit.write(strBarcodeIndelSearcher + ':' + strBarcodeIndelSearcher + '\n') ## first is filename, second is barcode. BaseEdit barcode format Reference_for_BaseEdit.write(strBarcodeIndelSearcher + ':' + strReferenceIndelSearcher + '\n') ReferenceFile_in_IndelSearcher.close() BarcodeFile_in_IndelSearcher.close() Reference_for_BaseEdit.close() Total_result_file = open('./Output/{user}/{project}/{sample}/Tmp/{sample}_Classified_Indel_barcode.fastq'.format(user=strUser, project=strProject, sample=strSample)) intCheckTotLine = 0 intOneLineMore = 0 for i, strRow in enumerate(Total_result_file): ## for query reads if intOneLineMore == 1: intCheckTotLine = 0 intOneLineMore = 0 if i % 4 == 0: ## Classified_Indel_barcode has all total sequence. strBarcode = strRow.split('Barcode_')[1].split(':')[0] intCheckTotLine = 1 elif intCheckTotLine == 1: dictBarcodeSeq[strBarcode].append(strRow) intOneLineMore = 1 for strBarcode, listSeq in dictBarcodeSeq.items(): with open('../Base_edit_2/Input/{user}/Query/{project}/{sample}/{barcode}.txt'.format( user=strUser, project=strProject, sample=strSample, barcode=strBarcode), 'w') as Output: Output.write(''.join(listSeq)) Total_result_file.close() def Main(): print('Program Start') p = mp.Pool(2) with open('./User/{user}/{project}.txt'.format(user=strUser, project=strProject)) as SampleList: listSampleRefGroup = [strSampleRefGroup for strSampleRefGroup in SampleList if strSampleRefGroup[0] != '#'] p.map_async(Convert_Indelsearcher_output, listSampleRefGroup).get() p.close() print('Program End') Main() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Summary_all_trim.py",".py","2239","46","import os, sys, logging import pandas as pd import subprocess as sp from pdb import set_trace sOutput_dir = sys.argv[1] strSample = sys.argv[2] strLogPath = sys.argv[3] logging.basicConfig(format='%(process)d %(levelname)s %(asctime)s : %(message)s', level=logging.DEBUG, filename=strLogPath, filemode='a') logging.getLogger().addHandler(logging.StreamHandler(sys.stdout)) def Parsing_summary(): dfSummary = pd.read_table('{outdir}/Tmp/{sample}_Summary.txt'.format(sample=strSample, outdir=sOutput_dir), header=None) dfSummary.columns = ['Barcode', 'Total', 'Insertion', 'Deletion', 'Complex'] dfSummary = dfSummary.groupby(['Barcode']).sum() dfSummary['Total_indel'] = dfSummary['Insertion'] + dfSummary['Deletion'] + dfSummary['Complex'] dfSummary['IND/TOT'] = dfSummary['Total_indel'] / dfSummary['Total'] dfSummary['IND/TOT'].fillna(0, inplace=True) dfSummary.to_csv('{outdir}/Result/{sample}_Summary_result.tsv'.format(sample=strSample, outdir=sOutput_dir), sep='\t') def Annotate_final_result(): dfCount_INDEL = pd.read_table('{outdir}/Tmp/{sample}_Indel_summary.txt'.format(sample=strSample, outdir=sOutput_dir), header=None) dfSummary = pd.read_table('{outdir}/Result/{sample}_Summary_result.tsv'.format(sample=strSample, outdir=sOutput_dir), index_col='Barcode') dfCount_INDEL.set_index(0, inplace=True) dfConcat_result = pd.concat([dfCount_INDEL, dfSummary.loc[:,['Total_indel', 'Total', 'IND/TOT']]],axis=1) dfConcat_result.dropna(inplace=True) dfConcat_result = dfConcat_result.reset_index() dfConcat_result = dfConcat_result.loc[:,['index','Total_indel', 'Total', 'IND/TOT', 1,2]] dfConcat_result.columns = ['Barcode', 'Total_indel', 'Total', 'IND/TOT', 'Match','Info'] dfConcat_result = dfConcat_result.round(2) dfConcat_result.to_csv('{outdir}/Result/{sample}_Final_indel_result.tsv'.format(sample=strSample, outdir=sOutput_dir), sep='\t', index=False) if __name__ == '__main__': logging.info('Make a summary result.') Parsing_summary() Annotate_final_result() logging.info('The summary result has been completed.\n\n') ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Indel_searcher_2/Run_converter.sh",".sh","372","23","#!/bin/bash #################### ## User parameter ## #################################### user=JaeWoo project=JaeWoo_test_samples #################################### while read python_path;do python=$python_path done < ../PythonPath.txt nohup $python ./BaseEdit_input_converter.py $user $project > ./Output/${user}/${project}/Log/Converter_log.txt 2>&1 & ","Shell" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Core/CoreSystem.py",".py","11837","314","import os, re, sys, logging import subprocess as sp import multiprocessing as mp from pdb import set_trace from datetime import datetime import numpy as np from CRISPResso2 import CRISPResso2Align class Helper(object): @staticmethod def MakeFolderIfNot(strDir): if not os.path.isdir(strDir): os.makedirs(strDir) @staticmethod def RemoveNullAndBadKeyword(Sample_list): listSamples = [strRow for strRow in Sample_list.readlines() if strRow not in [""''"", '', '""""', '\n', '\r', '\r\n']] return listSamples @staticmethod ## defensive def CheckSameNum(strInputProject, listSamples): listProjectNumInInput = [i for i in sp.check_output('ls %s' % strInputProject, shell=True).split('\n') if i != ''] setSamples = set(listSamples) setProjectNumInInput = set(listProjectNumInInput) intProjectNumInTxt = len(listSamples) intProjectNumInInput = len(listProjectNumInInput) if intProjectNumInTxt != len(setSamples - setProjectNumInInput): logging.warning('The number of samples in the input folder and in the project list does not matched.') logging.warning('Input folder: %s, Project list samples: %s' % (intProjectNumInInput, intProjectNumInTxt)) raise AssertionError else: logging.info('The file list is correct, pass\n') @staticmethod ## defensive def CheckAllDone(strOutputProject, listSamples): intProjectNumInOutput = len([i for i in sp.check_output('ls %s' % strOutputProject, shell=True).split('\n') if i not in ['All_results', 'Log', '']]) if intProjectNumInOutput != len(listSamples): logging.warning('The number of samples in the output folder and in the project list does not matched.') logging.warning('Output folder: %s, Project list samples: %s\n' % (intProjectNumInOutput, len(listSamples))) else: logging.info('All output folders have been created.\n') @staticmethod def SplitSampleInfo(strSample): if strSample[0] == '#': return False logging.info('Processing sample : %s' % strSample) lSampleRef = strSample.replace('\n', '').replace('\r', '').replace(' ', '').split('\t') if len(lSampleRef) == 2: strSample = lSampleRef[0] strRef = lSampleRef[1] return (strSample, strRef, '') elif len(lSampleRef) == 3: strSample = lSampleRef[0] strRef = lSampleRef[1] strExpCtrl = lSampleRef[2].upper() return (strSample, strRef, strExpCtrl) else: logging.error('Confirm the file format is correct. -> Sample name\tReference name\tGroup') logging.error('Sample list input : %s\n' % lSampleRef) raise Exception @staticmethod def CheckIntegrity(strBarcodeFile, strSeq): ## defensive rec = re.compile(r'[A|C|G|T|N]') if ':' in strSeq: strSeq = strSeq.split(':')[1] strNucle = re.findall(rec, strSeq) if len(strNucle) != len(strSeq): logging.error('This sequence is not suitable, check A,C,G,T,N are used only : %s' % strBarcodeFile) set_trace() sys.exit(1) @staticmethod def PreventFromRmMistake(strCmd): rec = re.compile(r'rm.+-rf*.+(\.$|\/$|\*$|User$|Input$|Output$)') ## This reg can prevent . / * ./User User ... if re.findall(rec, strCmd): raise Exception('%s is critical mistake! never do like this.' % strCmd) class InitialFolder(object): def __init__(self, strUser, strProject, strProgram): self.strUser = strUser self.strProject = strProject self.strProgram = strProgram def MakeDefaultFolder(self): Helper.MakeFolderIfNot('Input') Helper.MakeFolderIfNot('Output') Helper.MakeFolderIfNot('User') def MakeInputFolder(self): ## './Input/JaeWoo' strUserInputDir = './Input/{user}'.format(user=self.strUser) Helper.MakeFolderIfNot(strUserInputDir) if self.strProgram == 'Run_indel_searcher.py': ## './Input/JaeWoo/FASTQ' strUserFastqDir = os.path.join(strUserInputDir, 'FASTQ') Helper.MakeFolderIfNot(strUserFastqDir) elif self.strProgram == 'Run_BaseEdit_freq.py': ## './Input/JaeWoo/Query' strUserFastqDir = os.path.join(strUserInputDir, 'Query') Helper.MakeFolderIfNot(strUserFastqDir) else: print('CoreSystem.py -> CoreSystem error, check the script.') raise Exception ## './Input/JaeWoo/FASTQ/Test_samples' strUserProjectDir = os.path.join(strUserFastqDir, self.strProject) Helper.MakeFolderIfNot(strUserProjectDir) ## './Input/JaeWoo/Reference' strUserReference = os.path.join(strUserInputDir, 'Reference') Helper.MakeFolderIfNot(strUserReference) ## './Input/JaeWoo/Reference/Test_samples' strUserRefProject = os.path.join(strUserReference, self.strProject) Helper.MakeFolderIfNot(strUserRefProject) ## './User/JaeWoo' strUserDir = './User/{user}'.format(user=self.strUser) Helper.MakeFolderIfNot(strUserDir) ## '> ./User/JaeWoo/Test_samples.txt' self.strProjectFile = os.path.join(strUserDir, self.strProject+'.txt') if not os.path.isfile(self.strProjectFile): sp.call('> ' + self.strProjectFile, shell=True) def MakeOutputFolder(self): ## './Output/JaeWoo' strOutputUserDir = './Output/{user}'.format(user=self.strUser) Helper.MakeFolderIfNot(strOutputUserDir) ## './Output/JaeWoo/Test_samples' self.strOutputProjectDir = os.path.join(strOutputUserDir, self.strProject) Helper.MakeFolderIfNot(self.strOutputProjectDir) ## './Output/JaeWoo/Test_samples/Log' strOutputLog = os.path.join(self.strOutputProjectDir, 'Log') Helper.MakeFolderIfNot(strOutputLog) strLogName = str(datetime.now()).replace('-', '_').replace(':', '_').replace(' ', '_').split('.')[0] self.strLogPath = os.path.join(self.strOutputProjectDir, 'Log/{logname}_log.txt'.format(logname=strLogName)) class UserFolderAdmin(object): """""" InitialFolder : out of the loop UserFolderAdmin : in the loop So InitialFolder and UserFolderAdmin must be distinguished. """""" def __init__(self, strSample, strRef, options, strLogPath): self.strSample = strSample self.strRef = strRef self.strLogPath = strLogPath self.strUser = options.user_name self.strProject = options.project_name self.intCore = options.multicore self.strGapOpen = options.gap_open # CRISPresso aligner option self.strGapExtend = options.gap_extend # self.strPython = options.python self.strOutProjectDir = '' self.strOutSampleDir = '' self.strRefDir = '' def MakeSampleFolder(self): ## './Output/Jaewoo/Test_samples' self.strOutProjectDir = './Output/{user}/{project}'.format(user=self.strUser, project=self.strProject) ## './Output/Jaewoo/Test_samples/Sample_1' self.strOutSampleDir = os.path.join(self.strOutProjectDir, self.strSample) Helper.MakeFolderIfNot(self.strOutSampleDir) ## './Output/Jaewoo/Test_samples/Sample_1/Tmp' Helper.MakeFolderIfNot(os.path.join(self.strOutSampleDir, 'Tmp')) ## './Output/Jaewoo/Test_samples/Sample_1/Tmp/Pickle' Helper.MakeFolderIfNot(os.path.join(self.strOutSampleDir, 'Tmp/Pickle')) ## './Output/Jaewoo/Test_samples/Sample_1/Result' Helper.MakeFolderIfNot(os.path.join(self.strOutSampleDir, 'Result')) ## './Output/Jaewoo/Test_samples/All_results strAllResultDir = os.path.join(self.strOutProjectDir, 'All_results') Helper.MakeFolderIfNot(strAllResultDir) self.strRefDir = './Input/{user}/Reference/{project}/{ref}'.format(user=self.strUser, project=self.strProject, ref=self.strRef) class CoreHash(object): @staticmethod def MakeHashTable(strSeq, intBarcodeLen): listSeqWindow = [strSeq[i:i + intBarcodeLen] for i in range(len(strSeq))[:-intBarcodeLen - 1]] return listSeqWindow @staticmethod def IndexHashTable(dictRef, strSeqWindow, intFirstBarcode): lCol_ref = dictRef[strSeqWindow] strBarcode = strSeqWindow intFirstBarcode = 1 return (lCol_ref, strBarcode, intFirstBarcode) class CoreGotoh(object): def __init__(self, strEDNAFULL='', floOg='', floOe=''): self.npAlnMatrix = CRISPResso2Align.read_matrix(strEDNAFULL) self.floOg = floOg self.floOe = floOe def GapIncentive(self, strRefSeqAfterBarcode): ## cripsress no incentive == gotoh intAmpLen = len(strRefSeqAfterBarcode) npGapIncentive = np.zeros(intAmpLen + 1, dtype=np.int) return npGapIncentive def RunCRISPResso2(self, strQuerySeqAfterBarcode, strRefSeqAfterBarcode, npGapIncentive): listResult = CRISPResso2Align.global_align(strQuerySeqAfterBarcode.upper(), strRefSeqAfterBarcode.upper(), matrix=self.npAlnMatrix, gap_open=self.floOg, gap_extend=self.floOe, gap_incentive=npGapIncentive) return listResult def CheckProcessedFiles(Func): def Wrapped_func(**kwargs): InstInitFolder = kwargs['InstInitFolder'] strInputProject = kwargs['strInputProject'] listSamples = kwargs['listSamples'] logging = kwargs['logging'] logging.info('File num check: input folder and project list') Helper.CheckSameNum(strInputProject, listSamples) Func(**kwargs) logging.info('Check that all folder are well created.') Helper.CheckAllDone(InstInitFolder.strOutputProjectDir, listSamples) return Wrapped_func def AttachSeqToIndel(strSample, strBarcodeName, strIndelPos, strRefseq, strQueryseq, dictSub): listIndelPos = strIndelPos.split('M') intMatch = int(listIndelPos[0]) if 'I' in strIndelPos: intInsertion = int(listIndelPos[1].replace('I', '')) strInDelSeq = strQueryseq[intMatch:intMatch + intInsertion] elif 'D' in strIndelPos: intDeletion = int(listIndelPos[1].replace('D', '')) strInDelSeq = strRefseq[intMatch:intMatch + intDeletion] else: logging.info('strIndelClass is included I or D. This variable is %s' % strIndelPos) raise Exception strInDelPosSeq = strIndelPos + '_' + strInDelSeq try: _ = dictSub[strSample][strBarcodeName] except KeyError: dictSub[strSample][strBarcodeName] = {} try: dictSub[strSample][strBarcodeName][strBarcodeName + ':' + strInDelPosSeq]['IndelCount'] += 1 except KeyError: dictSub[strSample][strBarcodeName][strBarcodeName + ':' + strInDelPosSeq] = {'IndelCount':1} def RunProgram(sCmd): sp.call(sCmd, shell=True) def RunMulticore(lCmd, iCore): for sCmd in lCmd: print(sCmd) p = mp.Pool(iCore) p.map_async(RunProgram, lCmd).get() p.close() ","Python" "CRISPR","CRISPRJWCHOI/CRISPR_toolkit","Core/__init__.py",".py","0","0","","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/make_effector_fasta.py",".py","1165","32",""""""" Prints FASTA-formatted text containing the sequences of the given protein, from the operons passed into stdin. If there is more than one protein of the same name in the same operon, we pick the one with the lowest evalue. """""" import sys from typing import Optional from operon_analyzer import genes, load from tools.filters import fs def get_lowest_evalue_protein(operon: genes.Operon, protein_name: str) -> Optional[genes.Feature]: proteins = sorted([feature for feature in operon.get(protein_name, regex=True)], key=lambda x: x.e_val) if proteins: return proteins[0] return None if __name__ == '__main__': protein_name = sys.argv[1] sequences = [] for operon in load.load_operons(sys.stdin): fs.evaluate(operon) protein = get_lowest_evalue_protein(operon, protein_name) if protein: sequences.append((operon.contig, operon.start, operon.end, protein.accession, protein.start, protein.end, protein.sequence)) for contig, start, end, accession, pstart, pend, sequence in sequences: print(f"">{contig},{start},{end},{accession},{pstart},{pend}"") print(f""{sequence}"") ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/rules-nocas1-2.py",".py","247","11",""""""" Excludes systems that have Cas1 or Cas2. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().exclude('cas1').exclude('cas2') analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/rules-class1.py",".py","276","12",""""""" Selects potential Class I systems. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().contains_at_least_n_features(['cas5', 'cas6', 'cas7', 'cas8'], 3) analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/main.sh",".sh","18004","424","#!/usr/bin/env bash # This script runs the entire non-Tn7 CAST pipeline. set -euo pipefail # Halt the pipeline if any errors are encountered OUTPUT=../../output/nontn7 DATA=../../data STORE=$HOME/work INPUT=$(ls /stor/work/Wilke/amh7958/pipeline-results/*tar.gz /stor/work/Wilke/amh7958/pipeline-results/missing_effectors/*.tar.gz) BLASTN_DB=""$STORE/trnadb/trnas.fa"" BLASTP_DB=""$STORE/uniprotdb/uniprot_combined.fasta"" REBLAST_OUTPUT_DIR=""$OUTPUT/reblast"" ARRAYS_OPTIONAL_DIRECTORY=$OUTPUT/systems-with-or-without-crispr-arrays ARRAYS_REQUIRED_DIRECTORY=$OUTPUT/systems-with-crispr-arrays MIN_REBLAST_CLUSTER_SIZE=1 REBLAST_COUNT=5 KEEP_PATHS=""NO"" # change to ""YES"" if you're running this pipeline on some other system than the Wilke cluster. You will need to update the values for $STORE and $INPUT, and probably most of the hard-coded values listed above. declare -A proteins proteins[cas9]=""cas9"" proteins[cas12]=""cas12"" proteins[cas13]=""cas13"" # Sizes are the minimum and maximum length of the effector genes that we allow, in base pairs declare -A sizes sizes[cas9]=""2000 6000"" sizes[cas12]=""3000 6000"" sizes[cas13]=""2500 6000"" # These are the catalytic residues in the reference proteins declare -A residues residues[cas9]=""D10 H840"" residues[cas12]=""D908 E993"" residues[cas13]=""R472 H477 R1048 H1053"" # ====================================== # Make sure the output directories exist # ====================================== for directory in $OUTPUT $REBLAST_OUTPUT_DIR $ARRAYS_REQUIRED_DIRECTORY $ARRAYS_OPTIONAL_DIRECTORY; do mkdir -p $directory done arrays_optional_file=$OUTPUT/minimal_passing_systems.csv.gz arrays_required_file=$OUTPUT/minimal_passing_systems_with_crispr_arrays.csv.gz function echodone () { >&2 echo ""[DONE] $@"" } function echodo () { >&2 echo ""[RUNNING] $@"" } function find_minimal_systems () { # Applies our bare-minimum rules to all of the neighborhoods in the gene_finder output # This produces two files: one where CRISPR arrays are optional, and one where they are required local action=""Find minimal systems"" if [[ ! -e $arrays_optional_file ]]; then echodo $action for filename in $INPUT; do # stream tar files to stdout tar -xzOf $filename done | python fix_paths.py $KEEP_PATHS | python rules-minimal.py | python rules-nocas1-2.py | gzip > $arrays_optional_file else echodone $action fi # Make a separate dataset with the additional constraint that CRISPR arrays are required local action=""Find minimal systems with CRISPR arrays"" if [[ ! -e $arrays_required_file ]]; then echodo $action gzip -cd $arrays_optional_file | python rules-array.py | gzip > $arrays_required_file else echodone $action fi } function find_minimal_subsystems () { # We select a subset of systems with some common trait to help focus our search. local systemname=$1 local output=""$OUTPUT/minimal-$systemname.csv.gz"" local output_with_arrays=""$OUTPUT/minimal-$systemname-with-arrays.csv.gz"" local action=""Find minimal systems with potential $systemname transposons"" if [[ ! -e $output ]]; then echodo $action gzip -cd $arrays_optional_file | python rules-$systemname.py | python dedup.py | gzip > $output else echodone $action fi local action=""Find minimal systems with potential $systemname transposons and CRISPR arrays"" if [[ ! -e $output_with_arrays ]]; then echodo $action gzip -cd $output | python rules-array.py | gzip > $output_with_arrays else echodone $action fi } function apply_type_specific_rules () { # For Class 2 systems, apply type-specific rules, deduplicate operons, and select systems with # appropriately-sized effectors local minimal_file=$1 # the raw input that contains all plausible systems local output_dir=$2 # directory to put results in mkdir -p $output_dir for group in ""${!sizes[@]}""; do local action=""Find $group systems for $output_dir from $minimal_file"" if [[ ! -e ""$output_dir/$group.csv.gz"" ]]; then echodo $action protein_name=""${proteins[$group]}"" protein_range=""${sizes[$group]}"" echo $group $protein_name $protein_range else echodone $action fi done | parallel --colsep ' ' ""gzip -cd $minimal_file | python rules-{2}.py | python dedup.py | python size_select.py {2} {3} {4} | gzip > $output_dir/{1}.csv.gz"" # ====================================================================================================== # Apply our rules to the gene_finder output to find Class 1 systems. These have to be handled separately # here and throughout the script because the way we determine whether they are nuclease dead is done # implicitly by the absence of Cas3 or Cas10. # ====================================================================================================== class1_file=$output_dir/class1.csv.gz local action=""Find Class 1 systems for $output_dir"" if [[ ! -e $class1_file ]]; then echodo $action gzip -cd $minimal_file | python rules-nocas3-10.py | python rules-class1.py | python dedup.py | gzip > $class1_file else echodone $action fi } function make_clustering_file () { # ============================================================================================ # Make a FASTA file of each effector protein. For Class I proteins, we're using Cas7 at it is # essential and does not appear as a fusion with Cas5/6/8. For Class 2 proteins, we'll just # use the nuclease, either Cas9, Cas12 or Cas13. If more than one effector protein is present # in an operon, we pick the one with the lowest e-value. We also make a separate file for the # Class 2 systems, which has a reference protein at the top of the file. We will perform a # multiple sequence alignment on this file to determine which proteins are nuclease-active. # ============================================================================================ local directory=$1 # Class 2 for group in ""${!proteins[@]}""; do protein=""${proteins[$group]}"" clustering_file=""$directory/$group.for_clustering.fasta"" local action=""Make clustering file for $group"" if [[ ! -e $clustering_file ]]; then echodo $action # Make the FASTA file to be used for clustering gzip -cd $directory/$group.csv.gz | python make_effector_fasta.py $protein > $clustering_file # Make the FASTA file to be used for alignment cat $DATA/nontn7/$group.fasta $clustering_file > $directory/$group.for_alignment.fasta else echodone $action fi done # Class 1 class1_clustering_file=""$directory/class1.for_clustering.fasta"" if [[ ! -e $class1_clustering_file ]]; then echodo ""Make clustering file for Class 1"" gzip -cd $class1_file | python make_effector_fasta.py cas7 > $class1_clustering_file else echodone ""Make clustering file for Class1"" fi } perform_multiple_sequence_alignment () { # ================================================================================================== # Perform a multiple sequence alignment so we can identify nucleases with mutated catalytic residues # ================================================================================================== local directory=$1 for group in ""${!proteins[@]}""; do fasta=$directory/$group.for_alignment.fasta alignment=$directory/$group.afa mafft_strategy=""$directory/$group.mafft_strategy"" protein=""${proteins[$group]}"" residues_file=""$directory/$group.residues.csv"" nuclease_dead_operons=""$directory/$group.nuclease_dead.csv.gz"" # Perform the alignment local action=""Perform MSA for $group"" if [[ ! -e $alignment ]]; then echodo $action mafft --auto --thread 8 $fasta 2>$alignment.stderr > $alignment else echodone $action fi # Figure out what the strategy used by MAFFT was local action=""Determine MAFFT strategy for $group"" if [[ ! -e $mafft_strategy ]]; then strategy=$(rg --multiline 'Strategy:\n\s(.*)\n' $alignment.stderr --replace '$1') echodo $action echo ""$group $strategy"" > $mafft_strategy rm $alignment.stderr else echodone $action fi # Use the alignment and determine which nucleases have (potentially) been inactivated local action=""Identify catalytic residues for $group"" if [[ ! -e $residues_file ]]; then echodo $action python identify_catalytic_residues.py ${residues[$protein]} < $alignment > $residues_file else echodone $action fi # Gets operons with nuclease-dead effectors and save them to a new file local action=""Separate systems with nuclease-dead effectors for $group"" if [[ ! -e $nuclease_dead_operons ]]; then echodo $action gzip -cd $directory/$group.csv.gz | python load_nuclease_dead.py $protein $residues_file | gzip > $nuclease_dead_operons else echodone $action fi done } function cluster_nuclease_inactive_systems () { # For the nuclease-inactive systems (or Class 1 systems without a nuclease) we now group them together # by protein similarity, as many contigs are highly similar to several others and this reduces the burden # during the manual analysis, and also makes it easier to see patterns or deviations from patterns. # As before, we use Cas7 as the protein for Class 1 systems, and Cas9, Cas12 or Cas13 for Type 1 systems. local directory=$1 # Do the clustering for group in cas9 cas12 cas13 class1; do all_seqs_file=""$directory/$group.clustered_all_seqs.fasta"" clustering_file=""$directory/$group.for_clustering.fasta"" local action=""Cluster $group systems by nuclease sequence"" if [[ ! -e $all_seqs_file ]]; then echodo $action tempfile=/tmp/$group.mmseqs.temp mmseqs easy-cluster --min-seq-id 0.95 --write-lookup 1 $clustering_file $directory/$group.clustered $tempfile 2>/dev/null rm -r $tempfile mkdir -p $directory/$group.clusters gzip -cd $directory/$group.csv.gz | python get_clustered_operons.py $all_seqs_file $directory/$group.clusters else echodone $action fi done # If all of the operons in a cluster are nuclease-dead, we copy their data to a new directory for further processing # We don't need to set a threshold as we saw empirically that there were zero clusters with both nuclease-active and # nuclease dead systems for group in ""${!proteins[@]}""; do ndcluster_dir=$directory/$group.nuclease_dead_clusters local action=""Nuclease-dead analysis for $group"" if [[ -e $ndcluster_dir ]]; then echodone $action continue fi echodo $action mkdir -p $ndcluster_dir nuclease_dead_operons=""$directory/$group.nuclease_dead.csv.gz"" cluster_gzip_dir=$directory/$group.clusters for nuclease_dead_cluster_filename in $(python find_nuclease_dead_clusters.py $nuclease_dead_operons $cluster_gzip_dir); do cp $cluster_gzip_dir/$nuclease_dead_cluster_filename $ndcluster_dir done done } function find_self_targeting_spacers_and_inverted_repeats () { local directory=$1 # Find self-targeting spacers and inverted repeats in Class 2 systems for group in ""${!proteins[@]}""; do fully_analyzed_dir=$directory/$group.fully-analyzed local action=""Find inverted repeats and self-targeting spacers for $group"" if [[ -e $fully_analyzed_dir ]]; then echodone $action continue fi echodo $action mkdir -p $fully_analyzed_dir for filename in $(ls $directory/$group.nuclease_dead_clusters | rg '.*csv.gz'); do echo $group $filename done done | parallel -j 8 --colsep ' ' ""gzip -cd $directory/{1}.nuclease_dead_clusters/{2} | python self_targeting.py | python find_inverted_repeats.py | gzip > $directory/{1}.fully-analyzed/{2}"" # Find self-targeting spacers and inverted repeats in Class 1 systems fully_analyzed_dir=$directory/class1.fully-analyzed local action=""Find inverted repeats and self-targeting spacers for Class 1"" if [[ ! -e $fully_analyzed_dir ]]; then echodo $action mkdir -p $fully_analyzed_dir for filename in $(ls $directory/class1.clusters | rg '.*csv.gz'); do echo $filename done | parallel -j 8 --colsep ' ' ""gzip -cd $directory/class1.clusters/{1} | python self_targeting.py | python find_inverted_repeats.py | gzip > $fully_analyzed_dir/{1}"" else echodone $action fi } function reblast () { # Re-BLAST candidate systems with the TrEMBL, Swissprot, and tRNA databases local input_directory=$1 for group in ""${!proteins[@]}""; do filedir=$input_directory/$group.fully-analyzed for filename in $(ls $filedir); do python reblast.py $BLASTN_DB $BLASTP_DB $MIN_REBLAST_CLUSTER_SIZE $REBLAST_COUNT $REBLAST_OUTPUT_DIR $filedir/$filename done done } function plot_operons () { # Make side-by-side plots of the operons with annotations from our custom # transposon/Cas databases (on top) and the annotations from the re-BLAST # databases (on bottom) local input_directory=$1 for group in cas9 cas12 cas13 class1; do output_dir=""$input_directory/plots/$group"" local action=""Plot operons for $group in $input_directory"" if [[ -e $output_dir ]]; then echodone $action continue fi mkdir -p $output_dir echodo $action python plot_operons.py $input_directory/$group.fully-analyzed $output_dir done } function plot_reblasted_and_original_systems () { # Make side-by-side plots of the operons with annotations from our custom # transposon/Cas databases (on top) and the annotations from the re-BLAST # databases (on bottom) local input_directory=$1 for group in cas9 cas12 cas13 class1; do output_dir=""$input_directory/reblasted-plots/$group"" local action=""Plot re-BLASTed operons for $group in $input_directory"" if [[ ! -e $output_dir ]]; then mkdir -p $output_dir echodo $action fd '.*csv$' $OUTPUT/reblast | parallel -j2 'cat {}' | python plot_reblast.py $input_directory/$group.fully-analyzed $output_dir else echodone $action fi done } function examine_plausible_candidates () { # We manually looked at the reblasted results alongside their original # annotations and decided which ones looked plausible enough to merit further investigation local input_file=$OUTPUT/plausible-operon-ids.txt local output_file=$OUTPUT/plausible.csv.gz if [[ -e $input_file && ! -e $output_file ]]; then fd '.*csv.gz' $OUTPUT/*fully-analyzed* | parallel -j2 'gzip -cd {}' | python extract_candidates.py $input_file | gzip > $output_file fi } function reblast_interesting_candidates () { local input_directory=$1 for group in cas12 cas9 cas13 class1; do filedir=$input_directory/$group.fully-analyzed python reblast_interesting_candidates.py $BLASTN_DB $BLASTP_DB $REBLAST_COUNT $OUTPUT/interesting-candidates.csv $group $filedir $REBLAST_OUTPUT_DIR done } function run_complete_analysis () { # Takes a single input file of some set of candidate systems, and runs the complete analysis for Cas9, Cas12, Cas13 and Class 1 systems. local input_systems=$1 local output_directory=$2 apply_type_specific_rules $input_systems $output_directory make_clustering_file $output_directory perform_multiple_sequence_alignment $output_directory cluster_nuclease_inactive_systems $output_directory find_self_targeting_spacers_and_inverted_repeats $output_directory plot_operons $output_directory } # Run the pipeline find_minimal_systems # Perform analysis on systems with CRISPR arrays run_complete_analysis $arrays_required_file $ARRAYS_REQUIRED_DIRECTORY/all # Perform analysis on systems that may or may not have CRISPR arrays run_complete_analysis $arrays_optional_file $ARRAYS_OPTIONAL_DIRECTORY/all # Reblast interesting systems reblast_interesting_candidates $ARRAYS_OPTIONAL_DIRECTORY/all plot_reblasted_and_original_systems $ARRAYS_OPTIONAL_DIRECTORY/all # Isolate Cas12-Rpn systems # These were identified by manual inspection as meriting further analysis for cluster in 24 50 122 154 do; gzip -cd $ARRAYS_OPTIONAL_DIRECTORY/all/cas12.fully-analyzed/cluster$cluster.csv.gz done | python simple-reblast.py $BLASTN_DB $BLASTP_DB $ARRAYS_OPTIONAL_DIRECTORY/all/cas12.fully-analyzed/reblast cat $ARRAYS_OPTIONAL_DIRECTORY/all/cas12.fully-analyzed/reblast/*csv | python minced.py | python find-cas12-sts.py > $OUTPUT/cas12-rpn-candidates.csv # Assemble canonical nuclease-active Cas12a proteins to align them with the Rpn-associated ones if [[ ! -e $OUTPUT/cas12.afa ]]; then cat $DATA/cas12.fasta $DATA/lbcas12a.fasta $DATA/fncas12a.fasta $DATA/more-cas12a.fasta > $OUTPUT/cas12.fasta # Add the Rpn-associated Cas12 proteins # We eliminate the ""ORPV"" operon since it's a really tiny contig and not an Rpn-associated system python make_effector_fasta.py Cpf1 < $OUTPUT/cas12-rpn-candidates.csv | seqkit rmdup -s | rg -v ORPV >> $OUTPUT/cas12.fasta mafft --localpair --maxiterate 10000 $OUTPUT/cas12.fasta > $OUTPUT/cas12.afa fi ","Shell" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/rules-nocas3-10.py",".py","245","12",""""""" Removes systems with cas3 and cas10. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().exclude('cas3').exclude('cas10') analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/find_nuclease_dead_clusters.py",".py","654","21",""""""" Determines whether every candidate system in a group of candidates is nuclease dead, and if so, prints the filename of the gzipped CSV file to stdout """""" import os import sys from operon_analyzer import load nuclease_dead = set(load.load_gzipped_operons(sys.argv[1])) cluster_directory = sys.argv[2] for cluster_file in os.listdir(cluster_directory): if not cluster_file.endswith('csv.gz'): continue cluster = tuple(load.load_gzipped_operons(os.path.join(cluster_directory, cluster_file))) dead_count = sum([1 for operon in cluster if operon in nuclease_dead]) if dead_count == len(cluster): print(cluster_file) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/validate-plausible-candidates.py",".py","1380","35","# Creates a more readable text representation of each candidate system. The basic idea here is that # we went through the operon diagrams and found things that seemed interesting, and then wanted to look up the # details to see what exactly a particular gene BLASTed to or whether CRISPR targets had reasonable homology # and so forth. import sys from operon_analyzer import genes, load, visualize candidate_csv_gz = sys.argv[1] def print_details(operon: genes.Operon): for feature in operon: print(f""{feature.name} {feature.start}..{feature.end} {len(feature)} {feature.aln_len} {feature.pident} {feature.qcovhsp}"") plausible_candidates = list(load.load_gzipped_operons(candidate_csv_gz)) reblasted_operons = list(load.load_operons(sys.stdin)) for plausible, reblasted in visualize.make_operon_pairs(plausible_candidates, reblasted_operons): print(f""{plausible.contig},{plausible.start}..{plausible.end}"") print(""========"") print_details(reblasted) print("""") for feature in plausible: if feature.name == 'CRISPR target': print(feature.name, feature.description) if feature.name.startswith('IR'): print(feature.name, feature.start, feature.end, feature.description) if feature.name == 'CRISPR array': print(feature.start, feature.end, feature.description, feature.sequence) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/rules-minimal.py",".py","558","18",""""""" Accepts a stream of the raw gene_finder results and applies the most basic possible rules. This should then be used to create a smaller dataset that is more efficient to work with. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().require('transposase') \ .require(r'cas(5|6|7|8|9|10|11|12\w?|13\w?|phi)', regex=True) \ .exclude('tns[A-E]', regex=True) \ .exclude('tniQ') analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/cas12k-nuclease-dead-control.sh",".sh","462","14","#!/usr/bin/env bash # Aligns all Cas12k proteins from NCBI (plus two nuclease-active control Cas12a proteins) and confirms that our nuclease-dead analysis works. set -euo pipefail OUTPUT=../../output/nontn7 DATA=../../data/nontn7 alignment=$OUTPUT/cas12k.afa residues_file=$OUTPUT/cas12k.residues.csv mafft --auto --thread 8 $DATA/ncbi-cas12k-seqs.fasta 2>/dev/null > $alignment python identify_catalytic_residues.py D908 E993 < $alignment > $residues_file ","Shell" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/self_targeting.py",".py","542","17",""""""" Searches for self-targeting spacers in operons, add them as Feature objects, and rewrite all operons back to stdout regardless of what is found. """""" import sys from operon_analyzer import analyze, spacers from tools.filters import fs operons = analyze.load_operons(sys.stdin) filtered_operons = [] for operon in operons: fs.evaluate(operon) filtered_operons.append(operon) updated_operons = spacers.find_self_targeting_spacers(filtered_operons, 0.8, num_processes=32) for operon in updated_operons: print(operon.as_str()) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/fix_paths.py",".py","1417","37",""""""" In the raw gene_finder output, paths to the FASTA files are valid on TACC (where gene_finder was run), but do not point to the correct location on our local cluster. This script updates the paths in the Operon objects so that we can access raw nucleotide data in downstream analyses. """""" import csv import os import sys from operon_analyzer import parse def fix_path(contig_filename: str) -> str: # update paths from those at TACC to those on our local cluster leaf = contig_filename.replace(""/scratch/07227/hilla3/projects/CRISPR-Transposons/data/genomic/"", """") leaf = leaf.replace('genbank_bacteria_20210505', 'NCBI_redownload/genbank_bacteria_20210505') basedir = '/stor/scratch/Wilke/contig/database/metagenomic_contig_database' if not leaf.startswith(""NCBI""): if 'genbank_bacteria_20210505' not in contig_filename: basedir = f'{basedir}/EMBL_EBI' good_path = os.path.join(basedir, leaf) assert os.path.exists(good_path) return good_path if __name__ == '__main__': skip = sys.argv[1] if skip == 'YES': # This is useful is the pipeline is being run on a system other than our own for line in sys.stdin: print(line) else: writer = csv.writer(sys.stdout, delimiter=',') for line in parse.read_pipeline_output(sys.stdin): line[21] = fix_path(line[21]) writer.writerow(line) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/paper-stats.py",".py","4462","88",""""""" Computes values that we reference in the manuscript """""" import re import sys from collections import defaultdict import matplotlib import matplotlib.pyplot as plt from operon_analyzer import load from tools.colors import blue, gray, orange, red matplotlib.style.use('flab') regexes = {'transposase': re.compile(r'transposase|transposition|transposon|integrase|integration|resolvase|recombinase|recombination|\bIS\d+|(T|t)np', re.IGNORECASE), 'cas9': re.compile(r'\bcas9\w?', re.IGNORECASE), 'cas12': re.compile(r'(\bcas12\w?)|(cpf1)', re.IGNORECASE), 'cas13': re.compile(r'(\bcas13\w?)|(c2c2)', re.IGNORECASE), 'cas6': re.compile(r'(\bcas6)|(\bcase)|(\bcsy4)', re.IGNORECASE), 'cas5': re.compile(r'(\bcas5)|(\bcasd)|(\bcsc1)|(\bcsy2)|(\bcsf3)|(\bcsm4)|(\bcsx10)|(\bcmr3)', re.IGNORECASE), 'cas8': re.compile(r'(\bcas8)|(\bcasa)|(\bcsh1)|(\bcsd1)|(\bcse1)|(\bcsy1)|(\bcsf1)', re.IGNORECASE), 'cas7': re.compile(r'(\bcas7)|(\bcasc)|(\bcsd2)|(\bcsc2)|(\bcsy3)|(\bcsf2)|(\bcsm3)|(\bcsm5)|(\bcmr1)|(\bcmr6)|(\bcmr4)', re.IGNORECASE), 'cas11': re.compile(r'(\bcas11)|(\bcasb)|(\bcse2)|(\bcsm2)|(\bcmr5)', re.IGNORECASE), 'IR': re.compile(r'IR #\d+', re.IGNORECASE), 'target': re.compile(r'CRISPR target'), 'array': re.compile(r'(CRISPR )?array', re.IGNORECASE)} counts = defaultdict(int) facts = {'Cas only': 0, 'Tnp only': 0, 'Both': 0, 'Neither': 0} for n, operon in enumerate(load.load_operons(sys.stdin)): operon_counts = defaultdict(int) for name, regex in regexes.items(): for feature in operon: if regex.search(feature.name): operon_counts[name] += 1 has_cas = False has_tnp = False has_ir = False has_target = False for protein in 'cas5', 'cas6', 'cas7', 'cas8', 'cas11': if operon_counts[protein] > 0: has_cas = True break has_tnp = operon_counts['transposase'] > 0 has_ir = operon_counts['IR'] > 0 has_target = operon_counts['target'] > 0 if has_cas and has_tnp: facts['Both'] += 1 elif has_cas and not has_tnp: facts['Cas only'] += 1 elif not has_cas and has_tnp: facts['Tnp only'] += 1 else: facts['Neither'] += 1 for name, count in operon_counts.items(): if count == 0: continue counts[name] += 1 print(facts) fig, ax = plt.subplots() labels = [] values = [] for name, count in sorted(facts.items(), key=lambda x: -x[1]): labels.append(name) values.append(count) ax.bar([1, 2, 3, 4], values, color=[blue, red, orange, gray]) ax.set_xticklabels(labels) ax.set_xticks([1, 2, 3, 4]) ax.set_ylabel(""Number of putative operons"") plt.savefig(""reannotation-results.png"", bbox_inches='tight') # * We found ZZZ systems with IRs alone and ZZZ systems with both IRs and TSDs. # * We examined the spacer sequences of the systems and attempted to locate a corresponding target in the contig. We found ZZZ systems with targets of at least 80% homology that were within ZZZ base pairs of the IR or TSD. # # * Current and historical gene names for cas (1-13) and Tn7 proteins (tnsA-E and tniQ, also glmS) were used as queries against the UniRef50 protein cluster databases (ZZZ URL?). # * The three reference sets (tnsAB + transposases, tnsCDE + tniQ + glmS, and cas1-13) were each converted into blast databases using the NCBI blast+ command makeblastdb (version ZZZ) with default parameters. # * Approximately ZZZ% of the metagenomic operons that encoded a transposase and one Cas gene were nearly identical at the nucleotide sequence level. However, exact nucleotide comparisons were too slow to de-duplicate this large dataset. Instead, we considered two operons to be identical if they met the following properties: (1) they had the same protein-coding genes and CRISPR arrays in the same order; (2) the genes had the same relative distances to each other; and (3) the translated sequences of all proteins were identical. This de-duplication was applied to all operons prior to all downstream analysis. # * We used MAFFT (Katoh and Standley, 2013) to align the Cas9, Cas12 and Cas13 protein sequences to each other, respectively. [zzz-Consider including a sentence on benchmarking this strategy to known Cas12k systems]. We found ZZZ% of Cas9, ZZZ% of Cas12, and ZZZ% of Cas13 had nuclease-inactivating mutations or deletions. ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/load_nuclease_dead.py",".py","1263","32",""""""" Creates a gene_finder-formatted operon CSV, containing only operons with putatively dead nucleases. """""" import re import sys from operon_analyzer import analyze protein = sys.argv[1] residues_file = sys.argv[2] nuclease_active_residue_regex = {""cas9"": re.compile(r'(D|E)(R|H|K)'), ""cas12"": re.compile(r'(D|E){2}'), ""cas13"": re.compile(r'(R|H|K){4}')} regex = nuclease_active_residue_regex[protein] # note which operons still contain a catalytically-active CRISPR-Cas nuclease, so that we can exclude them later # many operons have multiple hits to our protein of interest so we can't make a determination by just examining # the first one. nuclease_active = set() with open(residues_file) as f: for line in f: motif, operon_data = line.strip().split() if regex.match(motif): contig_accession, contig_start, contig_end, _, _, _ = operon_data.split(',') nuclease_active.add((contig_accession, int(contig_start), int(contig_end))) # write the nuclease-dead operons to stdout for operon in analyze.load_operons(sys.stdin): if (operon.contig, operon.start, operon.end) in nuclease_active: continue sys.stdout.write(operon.as_str()) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/__init__.py",".py","0","0","","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/reblast.py",".py","3343","80",""""""" Runs gene_finder with given protein and nucleotide databases. This is used to examine our results with TrEMBL, Swissprot and a tRNA database to determine the context and accuracy of the annotations we made with our curated transposase and Cas databases. """""" import gzip import os import random import subprocess import sys from gene_finder import pipeline from operon_analyzer import analyze NUM_THREADS = 64 blastn_db_dir = sys.argv[1] blastp_db_dir = sys.argv[2] min_cluster_size = int(sys.argv[3]) reblast_count = int(sys.argv[4]) output_dir = sys.argv[5] input_file = sys.argv[6] with gzip.open(input_file, 'rt') as f: operons = sorted(analyze.load_operons(f), key=lambda operon: -len(operon)) if len(operons) < min_cluster_size: # This cluster has too few members, so we assume it's abberant and not worth looking into. This assumption could be # wrong! It's probably worth revisiting when the larger clusters have finished reblasting exit(0) # Get the operon with the most features first operons_to_reblast = [operons[0]] # Get the operon with the most coverage, if it's not the same one longest_operon = sorted([operon for operon in operons], key=lambda o: -abs(o.end-o.start))[0] if longest_operon != operons_to_reblast[0]: operons_to_reblast.append(longest_operon) remaining_operons = [op for op in operons if op not in operons_to_reblast] if remaining_operons and reblast_count > len(operons_to_reblast): additional_operons = random.sample(remaining_operons, min(len(remaining_operons), reblast_count - len(operons_to_reblast))) operons_to_reblast.extend(additional_operons) successful = 0 for operon in operons_to_reblast: assert os.path.exists(operon.contig_filename), f""missing file: {operon.contig_filename}"" # see if this operon has already been re-BLASTed job_id = f""{operon.contig}-{operon.start}-{operon.end}"" output_file = os.path.join(output_dir, f""{job_id}_results.csv"") if os.path.exists(output_file): print(f""[DONE] Re-BLAST {job_id}"", file=sys.stderr) continue # set up the pipeline p = pipeline.Pipeline() p.add_seed_with_coordinates_step(start=operon.start, end=operon.end, contig_id=operon.contig, db=blastp_db_dir, name=""blastdb"", e_val=1e-30, num_threads=NUM_THREADS, blast_type=""PROT"", parse_descriptions=False, blast_path='blastp-2.10') p.add_crispr_step() p.add_blastn_step(blastn_db_dir, 'tRNA', 1e-30, parse_descriptions=False, num_threads=NUM_THREADS, blastn_path='blastn-2.10') # run the pipeline on this one contig try: print(f""[RUNNING] Re-BLAST {job_id}"", file=sys.stderr) results = p.run(data=operon.contig_filename, output_directory=output_dir, job_id=job_id, gzip=True) except subprocess.CalledProcessError: # pilercr segfaults for some unknown reason, in the event that this # happens we'll just skip this operon continue else: successful += 1 if successful == reblast_count: break ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/paper-values.sh",".sh","2002","40","#!/usr/bin/env bash # This script calculates several numerical values that we report in the text of the paper. OUTPUT=""/stor/home/rybarskj/Metagenomics_CRISPR_transposons/output/nontn7/systems-with-crispr-arrays/all"" GROUPS=""cas9 cas12 cas13 class1"" function count_operons () { echo $(fd -a '.*csv.gz' $OUTPUT/$1.clusters | parallel -j2 'gzip -cd {}' | python count_operons.py) } function count_nd_operons() { echo $(fd -a '.*csv.gz' $OUTPUT/$1.fully-analyzed | parallel -j2 'gzip -cd {}' | python count_operons.py) } # 1. The count of the number of systems we found that meet the basic rules. cas9count=$(count_operons cas9) cas12count=$(count_operons cas12) cas13count=$(count_operons cas13) class1count=$(count_operons class1) printf ""The pipeline identified %'d putative Cas9-encoding systems, %'d Cas12-encoding systems, %'d Cas13-encoding systems and %'d Type I systems.\n"" $cas9count $cas12count $cas13count $class1count deduplicated_count=$(gzip -cd /stor/home/rybarskj/Metagenomics_CRISPR_transposons/output/nontn7/minimal_passing_systems_with_crispr_arrays.csv.gz | python dedup.py | python count_operons.py) original_count=$(gzip -cd /stor/home/rybarskj/Metagenomics_CRISPR_transposons/output/nontn7/minimal_passing_systems_with_crispr_arrays.csv.gz | python count_operons.py) printf ""There were %'d systems that passed our minimal rules, and %'d systems after deduplication.\n"" $original_count $deduplicated_count # 2. Determine the percentage of systems that were nuclease-dead. cas9nd_count=$(count_nd_operons cas9) cas9_nd_ratio=$(echo ""scale=4; $cas9nd_count/$cas9count*100"" | bc) cas12nd_count=$(count_nd_operons cas12) cas12_nd_ratio=$(echo ""scale=4; $cas12nd_count/$cas12count*100"" | bc) cas13nd_count=$(count_nd_operons cas13) cas13_nd_ratio=$(echo ""scale=4; $cas13nd_count/$cas13count*100"" | bc) printf ""We found %f%% of Cas9, %f%% of Cas12, and %f%% of Cas13 had nuclease-inactivating mutations or deletions.\n"" $cas9_nd_ratio $cas12_nd_ratio $cas13_nd_ratio ","Shell" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/identify_catalytic_residues.py",".py","1474","42",""""""" Determines the residues at a given position in an aligned sequence. The first sequence is a reference protein whose catalytic residues are known. We then see what the equivalent residues are in all other proteins. This is later used to determine which proteins might be nuclease-dead. """""" import sys from Bio import SeqIO # space-separated catalytic residues with their (1-based) index. # For example, AsCas12a would be: D908 E993 catalytic_residues = sys.argv[1:] # take user-supplied indices, converting to zero-indexed numbers amino_acids = [aa[0] for aa in catalytic_residues] interesting_indices = [int(val[1:]) - 1 for val in catalytic_residues] # Load the MSA and get the reference protein's alignment alignments = SeqIO.parse(sys.stdin, 'fasta') reference = next(alignments) # First, find the column of the catalytic residues in the reference protein index = 0 indices = [] residues = [] for residue in reference: if residue != ""-"": residues.append(residue) indices.append(index) index += 1 columns = [indices[index] for index in interesting_indices] # Make sure our user-supplied residues actually exist in the reference protein for column, aa in zip(columns, amino_acids): assert reference[column] == aa # Now write what each protein has in the catalytic protein position for record in alignments: record_residues = """".join([record[column] for column in columns]) print(f""{record_residues}\t{record.description}"") ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/extract_candidates.py",".py","980","36",""""""" Takes a list of candidate systems that was produced during the manual validation, finds the gene_finder output for those systems, and prints their serialized data to stdout """""" import sys from operon_analyzer import load candidate_list = sys.argv[1] with open(candidate_list) as f: candidates = [] for line in f: line = line.strip() if not line or line.startswith(""#""): continue _, accession, start, end = line.split('-') start, end = int(start), int(end) candidates.append((accession, start, end)) found = 0 operons = tuple(load.load_operons(sys.stdin)) for accession, start, end in candidates: for operon in operons: if (operon.contig, operon.start, operon.end) == (accession, start, end): found += 1 print(operon.as_str()) print(""\n\n"") break if found != len(candidates): raise ValueError(""Not all specified candidate systems were found!"") ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/rules-cas12.py",".py","242","12",""""""" Selects all potential Type V systems. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().require('cas12', regex=True) analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/reblast_interesting_candidates.py",".py","2695","64","import os import random import subprocess import sys from collections import defaultdict from gene_finder import pipeline from operon_analyzer import load random.seed(43) blastn_db_dir = sys.argv[1] blastp_db_dir = sys.argv[2] reblast_count = int(sys.argv[3]) interesting_candidate_filename = sys.argv[4] protein_of_interest = sys.argv[5] input_directory = sys.argv[6] output_directory = sys.argv[7] NUM_THREADS = 64 cluster_filenames = defaultdict(list) with open(interesting_candidate_filename) as f: for line in f: if line.startswith(""#""): continue protein, cluster_number = line.strip().split("","") cluster_filenames[protein].append(f""cluster{cluster_number}.csv.gz"") for filename in os.listdir(input_directory): if filename not in cluster_filenames[protein_of_interest]: continue operons = tuple(load.load_gzipped_operons(os.path.join(input_directory, filename))) good_operons = random.sample(operons, min(len(operons), reblast_count)) for operon in good_operons: job_id = f""{operon.contig}-{operon.start}-{operon.end}"" output_file = os.path.join(output_directory, f""{job_id}_results.csv"") if os.path.exists(output_file): print(f""[DONE] Re-BLAST {protein_of_interest} {filename} {job_id}"", file=sys.stderr) else: print(f""[RUNNING] Re-BLAST {protein_of_interest} {filename} {job_id}"", file=sys.stderr) p = pipeline.Pipeline() p.add_seed_with_coordinates_step(start=operon.start, end=operon.end, contig_id=operon.contig, db=blastp_db_dir, name=""blastdb"", e_val=1e-30, num_threads=NUM_THREADS, blast_type=""PROT"", parse_descriptions=False, blast_path='blastp-2.10') p.add_crispr_step() p.add_blastn_step(blastn_db_dir, 'tRNA', 1e-30, parse_descriptions=False, num_threads=NUM_THREADS, blastn_path='blastn-2.10') # run the pipeline on this one contig try: results = p.run(data=operon.contig_filename, output_directory=output_directory, job_id=job_id, gzip=True) except subprocess.CalledProcessError: # pilercr segfaults for some unknown reason, in the event that this # happens we'll just skip this operon continue ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/get_clustered_operons.py",".py","2327","69",""""""" Takes the all_seqs results from mmseqs2 and a stream of Operons and saves each to a separate gzipped CSV """""" import gzip import os import sys from collections import defaultdict from typing import IO, Dict, List, Tuple from operon_analyzer import load OperonLookup = Tuple[str, int, int] cluster_file = sys.argv[1] output_dir = sys.argv[2] def _parse_cluster_file(text: IO) -> List[List[OperonLookup]]: # parses the mmseqs2 output and makes a list of lists of the members of each cluster. # the members are stored as the operon accession and start/end coordinates clusters = [] for line in text: line = line.strip() if line.startswith("">""): nextline = next(text) if nextline.startswith("">""): # we're in a new group. line is the group, nextline is a member clusters.append([_parse_member(nextline[1:])]) else: clusters[-1].append(_parse_member(line[1:])) return clusters def _parse_member(member: str): # parse the unique sequence of each operon lookup accession, start, end, _, _, _ = member.split("","") start = int(start) end = int(end) return accession, start, end def _make_sensible_groups(clusters: List[List[OperonLookup]]) -> Dict[OperonLookup, str]: # reformat the clusters so that we can check group membership easily while going through # the stream operon objects grouped = {} for n, cluster in enumerate(clusters): name = f'cluster{n}' for lookup in cluster: grouped[lookup] = name return grouped if __name__ == '__main__': with open(cluster_file) as f: clusters = _parse_cluster_file(f) grouped = _make_sensible_groups(clusters) operons = load.load_operons(sys.stdin) operon_groups = defaultdict(list) for operon in operons: group = grouped.get((operon.contig, operon.start, operon.end)) if not group: continue operon_groups[group].append(operon) for group, members in operon_groups.items(): with gzip.open(os.path.join(output_dir, f'{group}.csv.gz'), 'w') as f: for member in members: text = f""{member.as_str()}\n"" f.write(text.encode()) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/plot_operons.py",".py","1406","36","import gzip import os import re import sys from operon_analyzer import analyze, visualize from tools.colors import feature_colors from tools.filters import fs cluster_regex = re.compile(r""cluster(\d+).csv.gz"") original_operons_dir = sys.argv[1] output_dir = sys.argv[2] for original_operon_gz in os.listdir(original_operons_dir): cluster_number = int(cluster_regex.match(original_operon_gz).group(1)) with gzip.open(os.path.join(original_operons_dir, original_operon_gz), 'rt') as f: for operon in analyze.load_operons(f): fs.evaluate(operon) # don't plot systems without inverted repeats or self-targeting spacers has_ir_or_sts = any([feature for feature in operon if feature.name.startswith(""IR #"") or feature.name.startswith(""CRISPR target"")]) if not has_ir_or_sts: continue try: filename = f""cluster{cluster_number:03d}-{operon.contig}-{operon.start}-{operon.end}.png"" out_filename = os.path.join(output_dir, filename) fig = visualize.create_operon_figure(operon, False, feature_colors, color_by_blast_statistic=False, nucl_per_line=20000, show_accession=False, show_description=True) if fig is None: continue visualize.save_operon_figure(fig, out_filename) except: continue ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/find_inverted_repeats.py",".py","355","14",""""""" Scans the entire contig where each putative operon is located and searches for inverted repeats """""" import sys from operon_analyzer import analyze, repeat_finder from tools.filters import fs for operon in analyze.load_operons(sys.stdin): fs.evaluate(operon) repeat_finder.find_inverted_repeats(operon, 500, 15) print(operon.as_str()) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/rules-array.py",".py","380","14",""""""" Accepts a stream of the raw gene_finder results and applies the most basic possible rules. This should then be used to create a smaller dataset that is more efficient to work with. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().require('CRISPR array') analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/rules-cas13.py",".py","243","12",""""""" Selects all potential Type VI systems. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().require('cas13', regex=True) analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/size_select.py",".py","508","22",""""""" Selects systems with a Feature that is within a given size range. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs feature_name = sys.argv[1] min_bp = int(sys.argv[2]) max_bp = int(sys.argv[3]) assert min_bp <= max_bp, ""Lower size limit must be less than or equal to the upper limit"" rs = rules.RuleSet().minimum_size(feature_name, min_bp) \ .maximum_size(feature_name, max_bp) analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/find-cas12-sts.py",".py","5809","118","# do a pairwise search between the source (defined above) and 25kb upstream of cas12 and 25kb downstream of the array # create Features of top hits and source import sys from operon_analyzer import load, genes from scan import DNASlice, scan_for_repeats for n, operon in enumerate(load.load_operons(sys.stdin)): sequence = load.load_sequence(operon) cas12_coords = None crispr_coords = [] for feature in operon: if 'cpf1' in feature.name.lower() or 'cpf1' in feature.description.lower() and len(feature) > 3000: if cas12_coords is not None and cas12_coords != (feature.start, feature.end): continue cas12_coords = feature.start, feature.end elif feature.name == 'Repeat Spacer' or feature.name == 'CRISPR array': crispr_coords.append((feature.start, feature.end)) if cas12_coords is None: continue best_array = 0 best_distance = 10000000 cas12_start, cas12_end = cas12_coords for n, (array_start, array_end) in enumerate(crispr_coords): distance = min(abs(cas12_start - array_start), abs(cas12_start - array_end), abs(cas12_end - array_start), abs(cas12_end - array_end)) if distance < best_distance: best_array = n best_distance = distance if not crispr_coords: continue array_start, array_end = crispr_coords[best_array] best_coords = sorted([cas12_start, cas12_end, array_start, array_end]) # pick the region where we might find atypical spacers # buffer by 50 bp on either side to help diminish accidental capture of CRISPR repeats spacer_region_start, spacer_region_end = best_coords[1] + 50, best_coords[2] - 50 if spacer_region_end <= spacer_region_start: continue # spacer_region_sequence = sequence[spacer_region_start: spacer_region_end] upstart = max(0, min(best_coords) - 25000) upend = min(best_coords) # target_up = sequence[upstart: upend] downstart = max(best_coords) downend = min(len(sequence), max(best_coords) + 25000) # target_down = sequence[downstart: downend] spacer_source = DNASlice(sequence, spacer_region_start, spacer_region_end) target_upstream = DNASlice(sequence, upstart, upend) target_downstream = DNASlice(sequence, downstart, downend) min_length = 16 max_length = 28 min_homology = 0.85 up_results = [] down_results = [] for inverted in (True, False): up_results.extend(scan_for_repeats(spacer_source, target_upstream, inverted, min_length, max_length, min_homology)) down_results.extend(scan_for_repeats(spacer_source, target_downstream, inverted, min_length, max_length, min_homology)) if not up_results and not down_results: continue # pick the best alignment from each side if up_results: up_result = sorted(up_results, key=lambda x: -x.ar.score)[0] up_spacer_feature = genes.Feature(f'Self-targeting spacer for {up_result.slice2.start}', (up_result.slice1.start, up_result.slice1.end), '', None, '', None, f'{up_result.ar.aligned_needle_sequence}\n{up_result.ar.comparison_string}\n{up_result.ar.aligned_haystack_sequence}', up_result.ar.aligned_needle_sequence) up_target_feature = genes.Feature(f'Target from {up_result.slice1.start}', (up_result.slice2.start, up_result.slice2.end), '', None, '', None, f'{up_result.ar.aligned_needle_sequence}\n{up_result.ar.comparison_string}\n{up_result.ar.aligned_haystack_sequence}', up_result.ar.aligned_haystack_sequence) operon._features.append(up_spacer_feature) operon._features.append(up_target_feature) if down_results: down_result = sorted(down_results, key=lambda x: -x.ar.score)[0] down_spacer_feature = genes.Feature(f'Self-targeting spacer for {down_result.slice2.start}', (down_result.slice1.start, down_result.slice1.end), '', None, '', None, f'{down_result.ar.aligned_needle_sequence}\n{down_result.ar.comparison_string}\n{down_result.ar.aligned_haystack_sequence}', down_result.ar.aligned_needle_sequence) down_target_feature = genes.Feature(f'Target from {down_result.slice1.start}', (down_result.slice2.start, down_result.slice2.end), '', None, '', None, f'{down_result.ar.aligned_needle_sequence}\n{down_result.ar.comparison_string}\n{down_result.ar.aligned_haystack_sequence}', down_result.ar.aligned_haystack_sequence) operon._features.append(down_spacer_feature) operon._features.append(down_target_feature) print(operon.as_str()) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/dedup.py",".py","321","13",""""""" Filters out putative operons that are extremely similar to one another. """""" import sys from operon_analyzer import analyze operons = analyze.load_operons(sys.stdin) unique = analyze.deduplicate_operons_approximate(operons) unique = analyze.dedup_supersets(unique) for operon in unique: print(operon.as_str()) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/plot_reblast.py",".py","1948","49",""""""" Makes operon diagrams with annotations from our curated database on top and TrEMBL/Swissprot/tRNA databases on bottom. """""" import gzip import os import re import sys from operon_analyzer import analyze, visualize from tools.colors import feature_colors from tools.filters import fs original_operons_dir = sys.argv[1] output_dir = sys.argv[2] reblasted_operons = tuple(analyze.load_operons(sys.stdin)) # The Uniprot/Swissprot annotations have a bunch of information # that makes it impossible to see the actual protein name when # plotting operons, so we remove those. remove_os = re.compile(r""OS=.+"") remove_parentheticals = re.compile(r""\(.+\)"") cluster_regex = re.compile(r""cluster(\d+).csv.gz"") for operon in reblasted_operons: for n, feature in enumerate(operon): feature.name = "" "".join(feature.name.split()[1:]) feature.name = remove_os.sub("""", feature.name) feature.name = remove_parentheticals.sub("""", feature.name) for original_operon_gz in os.listdir(original_operons_dir): cluster_number = int(cluster_regex.match(original_operon_gz).group(1)) with gzip.open(os.path.join(original_operons_dir, original_operon_gz), 'rt') as f: original_operons = tuple(analyze.load_operons(f)) for operon in original_operons: fs.evaluate(operon) assert original_operons, ""Invalid original operons file."" try: for operon, other in visualize.make_operon_pairs(original_operons, reblasted_operons): filename = f""cluster{cluster_number:03d}-{operon.contig}-{operon.start}-{operon.end}.png"" out_filename = os.path.join(output_dir, filename) visualize.plot_operon_pair(operon, other, None, None, out_filename, None, False, feature_colors) except ValueError as e: print(e) print(f""Couldn't plot {os.path.join(original_operons_dir, original_operon_gz)}"") continue ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/rules-cas9.py",".py","229","11",""""""" Selects all potential Type II systems. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().require('cas9') analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/simple-reblast.py",".py","2009","53","import sys from operon_analyzer import load from gene_finder import pipeline from genbank import load_sequence NUM_THREADS = 96 def find_system_bounds(operon, sequence): features = list(operon.all_features) positions = [] for feature in features: positions.append(feature.start) positions.append(feature.end) left_buffer_end = min(positions) left_buffer_start = max(0, left_buffer_end - 3000) right_buffer_start = max(positions) right_buffer_end = min(len(sequence), right_buffer_start + 3000) return left_buffer_start, right_buffer_end if __name__ == '__main__': blastn_db_dir = sys.argv[1] blastp_db_dir = sys.argv[2] output_dir = sys.argv[3] for n, operon in enumerate(load.load_operons(sys.stdin)): try: sequence = load_sequence(operon) except: sequence = load.load_sequence(operon) start, end = find_system_bounds(operon, sequence) job_id = f""{operon.contig}-{n}-{operon.start}-{operon.end}"" p = pipeline.Pipeline() p.add_seed_with_coordinates_step(start=start, end=end, contig_id=operon.contig, db=blastp_db_dir, name=""blastdb"", e_val=1e-30, num_threads=NUM_THREADS, blast_type=""PROT"", parse_descriptions=False, blast_path='blastp-2.10') p.add_blastn_step(blastn_db_dir, 'tRNA', 1e-4, parse_descriptions=False, num_threads=NUM_THREADS, blastn_path='blastn-2.10') # run the pipeline on this one contig print(f""[RUNNING] Re-BLAST {job_id}"", file=sys.stderr) results = p.run(data=operon.contig_filename, output_directory=output_dir, job_id=job_id, gzip=True) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/count_systems.py",".py","218","8",""""""" Counts the number of operons that are passed into the script from stdin and prints the result to stdout """""" import sys from operon_analyzer import load print(sum([1 for operon in load.load_operons(sys.stdin)])) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/tools/__init__.py",".py","0","0","","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/tools/colors.py",".py","1117","24","# Okabe Ito color palette black = (0.0, 0.0, 0.0) orange = (0.9019607843137255, 0.6235294117647059, 0.0) lightblue = (0.33725490196078434, 0.7058823529411765, 0.9137254901960784) green = (0.0, 0.6196078431372549, 0.45098039215686275) yellow = (0.9411764705882353, 0.8941176470588236, 0.25882352941176473) blue = (0.0, 0.4470588235294118, 0.6980392156862745) red = (0.8352941176470589, 0.3686274509803922, 0.0) purple = (0.8, 0.4745098039215686, 0.6549019607843137) # And an extra gray gray = (0.2, 0.2, 0.2) feature_colors = {'transposase|transposition|transposon|integrase|integration|resolvase|recombinase|recombination|IS\d+|(T|t)np': blue, 'cas(1$|2|4)': green, 'cas(3|9|10|12|13)': red, 'cas6|case|csy4': red, 'cas5|casd|csc1|csy2|csf3|csm4|csx10|cmr3': lightblue, 'cas7|casc|csd2|csc2|csy3|csf2|csm3|csm5|cmr1|cmr6|cmr4': purple, 'cas8|casa|csh1|csd1|cse1|csy1|csf1': yellow, 'cas11|casb|cse2|csm2|cmr5': red, '(CRISPR )?array': orange, '': gray} ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/nontn7/tools/filters.py",".py","1392","34","from operon_analyzer import rules, genes def _no_scarlet(operon: genes.Operon, ignored_reason_message: str): """""" There is an ABC transporter gene that was accidentally included in our database because its truncation was created with Cas9, and Cas9 was in its gene name. """""" for feature in operon.get('cas9'): if 'ABC' in feature.description: feature.ignore(ignored_reason_message) def _remove_arrays_inside_cds(operon: genes.Operon, ignored_reason_message: str): """""" Filters out CRISPR arrays that are contained within a CDS. These occur frequently due to the enthusiasm of pilercr. """""" genes = [feature for feature in operon.all_features if feature.name != 'CRISPR array'] for array in operon: if array.name != 'CRISPR array': continue for gene in genes: if rules._feature_distance(gene, array) == 0: array.ignore(ignored_reason_message) break _no_scarlet_mutation_filter = rules.Filter('no-scarlet', _no_scarlet) _arrays_inside_cds_filter = rules.Filter('array-is-inside-cds', _remove_arrays_inside_cds) fs = rules.FilterSet().pick_overlapping_features_by_bit_score(0.9) \ .must_be_within_n_bp_of_anything(30000) \ .custom(_arrays_inside_cds_filter) \ .custom(_no_scarlet_mutation_filter) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/initial_metagenome_blast_search/metagenomic_blast.py",".py","1187","25","# Searches an input contig (in fasta format) for regions with at least one cas gene (1-13) and one transposase no more than 25 kbp apart from gene_finder.pipeline import Pipeline import yaml import json, os, sys genomic_data = sys.argv[1] # path to input file, in fasta format output_directory = sys.argv[2] # directory to write output to # setup output directory, if it doesn't exist if not os.path.exists(output_directory): os.mkdir(output_directory) p = Pipeline() p.add_seed_step(db=""data/initial_metagenomic_blast_search/databases/transposase"", name=""transposase"", e_val=0.001, blast_type=""PROT"", num_threads=1) p.add_filter_step(db=""data/initial_metagenomic_blast_search/databases/cas_all"", name=""cas_all"", e_val=0.001, blast_type=""PROT"", num_threads=1) p.add_blast_step(db=""data/initial_metagenomic_blast_search/databases/tn7-accessory"", name=""tn7_accessory"", e_val=0.001, blast_type=""PROT"", num_threads=1) p.add_crispr_step() # use the input filename as the job id # results will be written to the file _results.csv job_id = os.path.basename(genomic_data) p.run(job_id=job_id, data=genomic_data, output_directory=output_directory, min_prot_len=90, span=25000) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/remove.ipynb",".ipynb","1390","60","{ ""cells"": [ { ""cell_type"": ""code"", ""execution_count"": 1, ""metadata"": {}, ""outputs"": [], ""source"": [ ""import os\n"", ""def Get_all_file(path):\n"", "" paths,files = [],[]\n"", "" # r=root, d=directories, f = files\n"", "" for r, d, f in os.walk(path):\n"", "" for file in f: \n"", "" #print (file)\n"", "" p = os.path.join(r, file)\n"", "" paths.append(os.path.abspath(p))\n"", "" files.append(file)\n"", "" for f in files:\n"", "" #print(f)\n"", "" pass\n"", "" return paths, files\n"", ""\n"", ""\n"", ""\n"", ""path = '/stor/work/Wilke/contig/database/metagenomic_contig_database/NCBI_redownload/genbank_bacteria_20210505'\n"", ""paths_flank, files_flank = Get_all_file(path) "" ] }, { ""cell_type"": ""code"", ""execution_count"": null, ""metadata"": {}, ""outputs"": [], ""source"": [] } ], ""metadata"": { ""kernelspec"": { ""display_name"": ""Python 3"", ""language"": ""python"", ""name"": ""python3"" }, ""language_info"": { ""codemirror_mode"": { ""name"": ""ipython"", ""version"": 3 }, ""file_extension"": "".py"", ""mimetype"": ""text/x-python"", ""name"": ""python"", ""nbconvert_exporter"": ""python"", ""pygments_lexer"": ""ipython3"", ""version"": ""3.6.9"" } }, ""nbformat"": 4, ""nbformat_minor"": 2 } ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/gene_finder_att_site.py",".py","1996","62","from gene_finder.pipeline import Pipeline import yaml import os, sys import os in_path,out_path,tns_DB,cas_DB,att_DB,ffs_DB = sys.argv[1:] def get_all_file_paths(path_to_dir): """""" Takes a path to a single directory and returns a list of the paths to each file in the directory. """""" fasta_files = os.listdir(path_to_dir) full_paths = [os.path.join(path_to_dir, f) for f in fasta_files] return full_paths def GF(name): """""" Command line args: 1. Path to input fasta file 2. Path to config file Constructs a Pipeline object to search for CRISPR-Transposon systems in the genome/config of interest. """""" min_prot_len= 80 # ORF aa cutoff length span=20000 # length (bp) upstream & downstream of bait hits to keep outfrmt=""CSV"" # output file format (can be either ""CSV"" or ""JSON"") gzip=False # make this True if the input contig file is gzipped genomic_data = name print(""Blasting file {}."".format(name)) # create a directory to write results to, if it doesn't exist already if not os.path.exists(out_path): os.mkdir(out_path) # results file will be called ""_results.csv"" job_id = os.path.basename(genomic_data) #outfile = os.path.join(conf[""out-dir""], ""{}_results.csv"".format(job_id)) p = Pipeline() p.add_seed_step(db=tns_DB, name='tns', e_val=0.001, blast_type=""PROT"") p.add_blastn_step(db=ffs_DB, name='ffs', e_val = 0.01, parse_descriptions=False) p.add_blast_step(db=cas_DB, name='cas', e_val=0.005, blast_type=""PROT"") p.add_blast_step(db=att_DB, name='att', e_val=0.001, blast_type=""PROT"") p.add_crispr_step() p.run(genomic_data, job_id, out_path, min_prot_len,span, gzip) import pandas as pd from multiprocessing import Pool if __name__ == '__main__': all_fasta_files = get_all_file_paths(in_path) p = Pool(80) p.map(GF, all_fasta_files) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/typeI-F_ffs.py",".py","638","15","import sys from operon_analyzer.analyze import analyze from operon_analyzer.rules import RuleSet, FilterSet input_genefinder_path,out_path = sys.argv[1:] rs = RuleSet().require('tnsB').require('tnsA').require('tniQ').require('cas7',regex=True).require('cas6',regex=True).require('ffs').max_distance('tnsA', 'tnsB', 2000,closest_pair_only=True).max_distance('tnsA', 'ffs', 2000,closest_pair_only=True) fs = FilterSet().pick_overlapping_features_by_bit_score(0.9).must_be_within_n_bp_of_anything(20000) with open(out_path, 'w', newline='') as csvfile: with open(input_genefinder_path, ""r"") as f: analyze(f, rs, fs,csvfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/typeI-B.py",".py","618","15","import sys from operon_analyzer.analyze import analyze from operon_analyzer.rules import RuleSet, FilterSet input_genefinder_path,out_path = sys.argv[1:] rs = RuleSet().require('tnsB').require('tnsA').require('cas7').require('cas6').require('cas5').require('glmS').max_distance('tnsA', 'tnsB', 1000,closest_pair_only=True).max_distance('tnsB', 'glmS', 3000,closest_pair_only=True) fs = FilterSet().pick_overlapping_features_by_bit_score(0.9).must_be_within_n_bp_of_anything(10000) with open(out_path, 'w', newline='') as csvfile: with open(input_genefinder_path, ""r"") as f: analyze(f, rs, fs,csvfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/fix_paths.py",".py","1252","35",""""""" In the raw gene_finder output, paths to the FASTA files are valid on TACC (where gene_finder was run), but do not point to the correct location on our local cluster. This script updates the paths in the Operon objects so that we can access raw nucleotide data in downstream analyses. """""" import csv import os import sys from operon_analyzer import parse def fix_path(contig_filename: str) -> str: # update paths from those at TACC to those on our local cluster leaf = contig_filename.replace(""/scratch/07227/hilla3/projects/CRISPR-Transposons/data/genomic/"", """") basedir = '/stor/scratch/Wilke/contig/database/metagenomic_contig_database' if not leaf.startswith(""NCBI""): basedir = f'{basedir}/EMBL_EBI' good_path = os.path.join(basedir, leaf) assert os.path.exists(good_path) return good_path if __name__ == '__main__': skip = sys.argv[1] if skip == 'YES': # This is useful is the pipeline is being run on a system other than our own for line in sys.stdin: print(line) else: writer = csv.writer(sys.stdout, delimiter=',') for line in parse.read_pipeline_output(sys.stdin): line[21] = fix_path(line[21]) writer.writerow(line) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/typeI-F_guaC.py",".py","640","15","import sys from operon_analyzer.analyze import analyze from operon_analyzer.rules import RuleSet, FilterSet input_genefinder_path,out_path = sys.argv[1:] rs = RuleSet().require('tnsB').require('tnsA').require('tniQ').require('cas7',regex=True).require('cas6',regex=True).require('guaC').max_distance('tnsA', 'tnsB', 2000,closest_pair_only=True).max_distance('tnsA', 'guaC', 2000,closest_pair_only=True) fs = FilterSet().pick_overlapping_features_by_bit_score(0.9).must_be_within_n_bp_of_anything(20000) with open(out_path, 'w', newline='') as csvfile: with open(input_genefinder_path, ""r"") as f: analyze(f, rs, fs,csvfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/visual.py",".py","710","24","import sys from operon_analyzer.analyze import load_analyzed_operons from operon_analyzer.visualize import build_operon_dictionary, plot_operons analysis_csv, pipeline_csv, image_directory = sys.argv[1:] good_operons = [] with open(pipeline_csv) as f: operons = build_operon_dictionary(f) with open(analysis_csv) as f: for contig, filename, start, end, result in load_analyzed_operons(f): if result[0] != 'pass': continue op = operons.get((contig, filename, start, end)) if op is None: continue good_operons.append(op) print(len(good_operons)) for x in good_operons: try: plot_operons([x], image_directory) except: pass ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/png_generator.py",".py","772","25","import sys from operon_analyzer.analyze import load_analyzed_operons from operon_analyzer.visualize import build_operon_dictionary, plot_operons analysis_csv, pipeline_csv, image_directory = sys.argv[1:] good_operons = [] with open(pipeline_csv) as f: operons = build_operon_dictionary(f) with open(analysis_csv) as f: for contig, filename, start, end, result in load_analyzed_operons(f): if result[0] != 'pass': continue op = operons.get((contig, filename, start, end)) if op is None: continue good_operons.append(op) print(""{} figures have been generated."".format(len(good_operons))) for x in good_operons: try: plot_operons([x], image_directory) print('1') except: raise ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/reblast.py",".py","3333","80",""""""" Runs gene_finder with given protein and nucleotide databases. This is used to examine our results with TrEMBL, Swissprot and a tRNA database to determine the context and accuracy of the annotations we made with our curated transposase and Cas databases. """""" import gzip import os import random import subprocess import sys from gene_finder import pipeline from operon_analyzer import analyze NUM_THREADS = 64 blastn_db_dir = sys.argv[1] blastp_db_dir = sys.argv[2] min_cluster_size = int(sys.argv[3]) reblast_count = int(sys.argv[4]) output_dir = sys.argv[5] input_file = sys.argv[6] with gzip.open(input_file, 'rt') as f: operons = sorted(analyze.load_operons(f), key=lambda operon: -len(operon)) if len(operons) < min_cluster_size: # This cluster has too few members, so we assume it's abberant and not worth looking into. This assumption could be # wrong! It's probably worth revisiting when the larger clusters have finished reblasting exit(0) # Get the operon with the most features first operons_to_reblast = [operons[0]] # Get the operon with the most coverage, if it's not the same one longest_operon = sorted([operon for operon in operons], key=lambda o: -abs(o.end-o.start))[0] if longest_operon != operons_to_reblast[0]: operons_to_reblast.append(longest_operon) remaining_operons = [op for op in operons if op not in operons_to_reblast] if remaining_operons and reblast_count > len(operons_to_reblast): additional_operons = random.sample(remaining_operons, min(len(remaining_operons), reblast_count - len(operons_to_reblast))) operons_to_reblast.extend(additional_operons) successful = 0 for operon in operons_to_reblast: assert os.path.exists(operon.contig_filename), f""missing file: {operon.contig_filename}"" # set up the pipeline p = pipeline.Pipeline() p.add_seed_with_coordinates_step(start=operon.start, end=operon.end, contig_id=operon.contig, db=blastp_db_dir, name=""blastdb"", e_val=1e-30, num_threads=NUM_THREADS, blast_type=""PROT"", parse_descriptions=False, blast_path='blastp-2.10') p.add_crispr_step() p.add_blastn_step(blastn_db_dir, 'tRNA', 1e-30, parse_descriptions=False, num_threads=NUM_THREADS, blastn_path='blastn-2.10') # run the pipeline on this one contig try: job_id = f""{operon.contig}-{operon.start}-{operon.end}"" output_file = os.path.join(output_dir, f""{job_id}_results.csv"") if os.path.exists(output_file) or len(os.listdir(output_dir)) >= reblast_count: continue print(output_file, file=sys.stderr) results = p.run(data=operon.contig_filename, output_directory=output_dir, job_id=job_id, gzip=True) except subprocess.CalledProcessError: # pilercr segfaults for some unknown reason, in the event that this # happens we'll just skip this operon continue else: successful += 1 if successful == reblast_count: break # signal that we're done with this file print(input_file) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/typeI-F_rsmJ.py",".py","640","15","import sys from operon_analyzer.analyze import analyze from operon_analyzer.rules import RuleSet, FilterSet input_genefinder_path,out_path = sys.argv[1:] rs = RuleSet().require('tnsB').require('tnsA').require('tniQ').require('cas7',regex=True).require('cas6',regex=True).require('rsmJ').max_distance('tnsA', 'tnsB', 2000,closest_pair_only=True).max_distance('tnsA', 'rsmJ', 2000,closest_pair_only=True) fs = FilterSet().pick_overlapping_features_by_bit_score(0.9).must_be_within_n_bp_of_anything(20000) with open(out_path, 'w', newline='') as csvfile: with open(input_genefinder_path, ""r"") as f: analyze(f, rs, fs,csvfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/commend.sh",".sh","462","4","#main python gene_finder_att_site.py fa_database genefinder_result /stor/work/Wilke/blastDB/classifer/tns /stor/work/Wilke/blastDB/classifer/cas /stor/work/Wilke/blastDB/classifer/att /stor/work/Wilke/blastDB/classifer/ffs python gene_finder_att_site.py /stor/work/Wilke/crisprtn7/NCBI_reblast ./genefinder /stor/work/Wilke/blastDB/classifer/tns /stor/work/Wilke/blastDB/classifer/cas /stor/work/Wilke/blastDB/classifer/att /stor/home/kh36969/p_database/ffs/ffs ","Shell" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/typeI-F_yciA.py",".py","640","15","import sys from operon_analyzer.analyze import analyze from operon_analyzer.rules import RuleSet, FilterSet input_genefinder_path,out_path = sys.argv[1:] rs = RuleSet().require('tnsB').require('tnsA').require('tniQ').require('cas7',regex=True).require('cas6',regex=True).require('yciA').max_distance('tnsA', 'tnsB', 2000,closest_pair_only=True).max_distance('tnsA', 'yciA', 2000,closest_pair_only=True) fs = FilterSet().pick_overlapping_features_by_bit_score(0.9).must_be_within_n_bp_of_anything(20000) with open(out_path, 'w', newline='') as csvfile: with open(input_genefinder_path, ""r"") as f: analyze(f, rs, fs,csvfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/plot_reblast.py",".py","2104","53",""""""" Makes operon diagrams with annotations from our curated database on top and TrEMBL/Swissprot/tRNA databases on bottom. """""" import gzip import os import re import sys from operon_analyzer import analyze, visualize from tools.colors import feature_colors from tools.filters import fs original_operons_dir = sys.argv[1] output_dir = sys.argv[2] reblasted_operons = tuple(analyze.load_operons(sys.stdin)) # The Uniprot/Swissprot annotations have a bunch of information # that makes it impossible to see the actual protein name when # plotting operons, so we remove those. remove_os = re.compile(r""OS=.+"") remove_parentheticals = re.compile(r""\(.+\)"") cluster_regex = re.compile(r""cluster(\d+).csv.gz"") for operon in reblasted_operons: for n, feature in enumerate(operon): feature.name = "" "".join(feature.name.split()[1:]) feature.name = remove_os.sub("""", feature.name) feature.name = remove_parentheticals.sub("""", feature.name) for original_operon_gz in os.listdir(original_operons_dir): print(original_operon_gz) cluster_number = int(cluster_regex.match(original_operon_gz).group(1)) # cluster_output_dir = os.path.join(output_dir, original_operon_gz) # os.makedirs(cluster_output_dir, exist_ok=True) with gzip.open(os.path.join(original_operons_dir, original_operon_gz), 'rt') as f: original_operons = tuple(analyze.load_operons(f)) for operon in original_operons: fs.evaluate(operon) assert original_operons, ""Invalid original operons file."" try: for operon, other in visualize.make_operon_pairs(original_operons, reblasted_operons): filename = f""cluster{cluster_number:03d}-{operon.contig}-{operon.start}-{operon.end}.png"" out_filename = os.path.join(output_dir, filename) visualize.plot_operon_pair(operon, other, None, None, out_filename, None, False, feature_colors) except ValueError as e: print(e) print(f""Couldn't plot {os.path.join(original_operons_dir, original_operon_gz)}"") continue ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI_NCBI/tools/colors.py",".py","1117","24","# Okabe Ito color palette black = (0.0, 0.0, 0.0) orange = (0.9019607843137255, 0.6235294117647059, 0.0) lightblue = (0.33725490196078434, 0.7058823529411765, 0.9137254901960784) green = (0.0, 0.6196078431372549, 0.45098039215686275) yellow = (0.9411764705882353, 0.8941176470588236, 0.25882352941176473) blue = (0.0, 0.4470588235294118, 0.6980392156862745) red = (0.8352941176470589, 0.3686274509803922, 0.0) purple = (0.8, 0.4745098039215686, 0.6549019607843137) # And an extra gray gray = (0.2, 0.2, 0.2) feature_colors = {'transposase|transposition|transposon|integrase|integration|resolvase|recombinase|recombination|IS\d+|(T|t)np': blue, 'cas(1$|2|4)': green, 'cas(3|9|10|12|13)': red, 'cas6|case|csy4': red, 'cas5|casd|csc1|csy2|csf3|csm4|csx10|cmr3': lightblue, 'cas7|casc|csd2|csc2|csy3|csf2|csm3|csm5|cmr1|cmr6|cmr4': purple, 'cas8|casa|csh1|csd1|cse1|csy1|csf1': yellow, 'cas11|casb|cse2|csm2|cmr5': red, '(CRISPR )?array': orange, '': gray} ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/gene_finder_att_site.py",".py","1994","62","from gene_finder.pipeline import Pipeline import yaml import os, sys import os in_path,out_path,tnsDB,cas_DB,att_DB,ffs_DB = sys.argv[1:] def get_all_file_paths(path_to_dir): """""" Takes a path to a single directory and returns a list of the paths to each file in the directory. """""" fasta_files = os.listdir(path_to_dir) full_paths = [os.path.join(path_to_dir, f) for f in fasta_files] return full_paths def GF(name): """""" Command line args: 1. Path to input fasta file 2. Path to config file Constructs a Pipeline object to search for CRISPR-Transposon systems in the genome/config of interest. """""" min_prot_len= 80 # ORF aa cutoff length span=20000 # length (bp) upstream & downstream of bait hits to keep outfrmt=""CSV"" # output file format (can be either ""CSV"" or ""JSON"") gzip=False # make this True if the input contig file is gzipped genomic_data = name print(""Blasting file {}."".format(name)) # create a directory to write results to, if it doesn't exist already if not os.path.exists(out_path): os.mkdir(out_path) # results file will be called ""_results.csv"" job_id = os.path.basename(genomic_data) #outfile = os.path.join(conf[""out-dir""], ""{}_results.csv"".format(job_id)) p = Pipeline() p.add_seed_step(db=tns_DB, name='tns', e_val=0.001, blast_type=""PROT"") p.add_blastn_step(db=ffs_DB, name='ffs', e_val = 0.01, parse_descriptions=False) p.add_blast_step(db=cas_DB, name='cas', e_val=0.005, blast_type=""PROT"") p.add_blast_step(db=att_DB, name='att', e_val=0.001, blast_type=""PROT"") p.add_crispr_step() p.run(genomic_data, job_id, out_path, min_prot_len,span, gzip) import pandas as pd from multiprocessing import Pool if __name__ == '__main__': all_fasta_files = get_all_file_paths(in_path) p = Pool(2) p.map(GF, all_fasta_files) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/typeI-F_ffs.py",".py","638","15","import sys from operon_analyzer.analyze import analyze from operon_analyzer.rules import RuleSet, FilterSet input_genefinder_path,out_path = sys.argv[1:] rs = RuleSet().require('tnsB').require('tnsA').require('tniQ').require('cas7',regex=True).require('cas6',regex=True).require('ffs').max_distance('tnsA', 'tnsB', 2000,closest_pair_only=True).max_distance('tnsA', 'ffs', 2000,closest_pair_only=True) fs = FilterSet().pick_overlapping_features_by_bit_score(0.9).must_be_within_n_bp_of_anything(20000) with open(out_path, 'w', newline='') as csvfile: with open(input_genefinder_path, ""r"") as f: analyze(f, rs, fs,csvfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/fix_paths.py",".py","1252","35",""""""" In the raw gene_finder output, paths to the FASTA files are valid on TACC (where gene_finder was run), but do not point to the correct location on our local cluster. This script updates the paths in the Operon objects so that we can access raw nucleotide data in downstream analyses. """""" import csv import os import sys from operon_analyzer import parse def fix_path(contig_filename: str) -> str: # update paths from those at TACC to those on our local cluster leaf = contig_filename.replace(""/scratch/07227/hilla3/projects/CRISPR-Transposons/data/genomic/"", """") basedir = '/stor/scratch/Wilke/contig/database/metagenomic_contig_database' if not leaf.startswith(""NCBI""): basedir = f'{basedir}/EMBL_EBI' good_path = os.path.join(basedir, leaf) assert os.path.exists(good_path) return good_path if __name__ == '__main__': skip = sys.argv[1] if skip == 'YES': # This is useful is the pipeline is being run on a system other than our own for line in sys.stdin: print(line) else: writer = csv.writer(sys.stdout, delimiter=',') for line in parse.read_pipeline_output(sys.stdin): line[21] = fix_path(line[21]) writer.writerow(line) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/typeI-F_guaC.py",".py","640","15","import sys from operon_analyzer.analyze import analyze from operon_analyzer.rules import RuleSet, FilterSet input_genefinder_path,out_path = sys.argv[1:] rs = RuleSet().require('tnsB').require('tnsA').require('tniQ').require('cas7',regex=True).require('cas6',regex=True).require('guaC').max_distance('tnsA', 'tnsB', 2000,closest_pair_only=True).max_distance('tnsA', 'guaC', 2000,closest_pair_only=True) fs = FilterSet().pick_overlapping_features_by_bit_score(0.9).must_be_within_n_bp_of_anything(20000) with open(out_path, 'w', newline='') as csvfile: with open(input_genefinder_path, ""r"") as f: analyze(f, rs, fs,csvfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/png_generator.py",".py","753","24","import sys from operon_analyzer.analyze import load_analyzed_operons from operon_analyzer.visualize import build_operon_dictionary, plot_operons analysis_csv, pipeline_csv, image_directory = sys.argv[1:] good_operons = [] with open(pipeline_csv) as f: operons = build_operon_dictionary(f) with open(analysis_csv) as f: for contig, filename, start, end, result in load_analyzed_operons(f): if result[0] != 'pass': continue op = operons.get((contig, filename, start, end)) if op is None: continue good_operons.append(op) print(""{} figures have been generated."".format(len(good_operons))) for x in good_operons: try: plot_operons([x], image_directory) except: raise ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/reblast.py",".py","3333","80",""""""" Runs gene_finder with given protein and nucleotide databases. This is used to examine our results with TrEMBL, Swissprot and a tRNA database to determine the context and accuracy of the annotations we made with our curated transposase and Cas databases. """""" import gzip import os import random import subprocess import sys from gene_finder import pipeline from operon_analyzer import analyze NUM_THREADS = 64 blastn_db_dir = sys.argv[1] blastp_db_dir = sys.argv[2] min_cluster_size = int(sys.argv[3]) reblast_count = int(sys.argv[4]) output_dir = sys.argv[5] input_file = sys.argv[6] with gzip.open(input_file, 'rt') as f: operons = sorted(analyze.load_operons(f), key=lambda operon: -len(operon)) if len(operons) < min_cluster_size: # This cluster has too few members, so we assume it's abberant and not worth looking into. This assumption could be # wrong! It's probably worth revisiting when the larger clusters have finished reblasting exit(0) # Get the operon with the most features first operons_to_reblast = [operons[0]] # Get the operon with the most coverage, if it's not the same one longest_operon = sorted([operon for operon in operons], key=lambda o: -abs(o.end-o.start))[0] if longest_operon != operons_to_reblast[0]: operons_to_reblast.append(longest_operon) remaining_operons = [op for op in operons if op not in operons_to_reblast] if remaining_operons and reblast_count > len(operons_to_reblast): additional_operons = random.sample(remaining_operons, min(len(remaining_operons), reblast_count - len(operons_to_reblast))) operons_to_reblast.extend(additional_operons) successful = 0 for operon in operons_to_reblast: assert os.path.exists(operon.contig_filename), f""missing file: {operon.contig_filename}"" # set up the pipeline p = pipeline.Pipeline() p.add_seed_with_coordinates_step(start=operon.start, end=operon.end, contig_id=operon.contig, db=blastp_db_dir, name=""blastdb"", e_val=1e-30, num_threads=NUM_THREADS, blast_type=""PROT"", parse_descriptions=False, blast_path='blastp-2.10') p.add_crispr_step() p.add_blastn_step(blastn_db_dir, 'tRNA', 1e-30, parse_descriptions=False, num_threads=NUM_THREADS, blastn_path='blastn-2.10') # run the pipeline on this one contig try: job_id = f""{operon.contig}-{operon.start}-{operon.end}"" output_file = os.path.join(output_dir, f""{job_id}_results.csv"") if os.path.exists(output_file) or len(os.listdir(output_dir)) >= reblast_count: continue print(output_file, file=sys.stderr) results = p.run(data=operon.contig_filename, output_directory=output_dir, job_id=job_id, gzip=True) except subprocess.CalledProcessError: # pilercr segfaults for some unknown reason, in the event that this # happens we'll just skip this operon continue else: successful += 1 if successful == reblast_count: break # signal that we're done with this file print(input_file) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/typeI-F_rsmJ.py",".py","640","15","import sys from operon_analyzer.analyze import analyze from operon_analyzer.rules import RuleSet, FilterSet input_genefinder_path,out_path = sys.argv[1:] rs = RuleSet().require('tnsB').require('tnsA').require('tniQ').require('cas7',regex=True).require('cas6',regex=True).require('rsmJ').max_distance('tnsA', 'tnsB', 2000,closest_pair_only=True).max_distance('tnsA', 'rsmJ', 2000,closest_pair_only=True) fs = FilterSet().pick_overlapping_features_by_bit_score(0.9).must_be_within_n_bp_of_anything(20000) with open(out_path, 'w', newline='') as csvfile: with open(input_genefinder_path, ""r"") as f: analyze(f, rs, fs,csvfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/typeI-F_yciA.py",".py","640","15","import sys from operon_analyzer.analyze import analyze from operon_analyzer.rules import RuleSet, FilterSet input_genefinder_path,out_path = sys.argv[1:] rs = RuleSet().require('tnsB').require('tnsA').require('tniQ').require('cas7',regex=True).require('cas6',regex=True).require('yciA').max_distance('tnsA', 'tnsB', 2000,closest_pair_only=True).max_distance('tnsA', 'yciA', 2000,closest_pair_only=True) fs = FilterSet().pick_overlapping_features_by_bit_score(0.9).must_be_within_n_bp_of_anything(20000) with open(out_path, 'w', newline='') as csvfile: with open(input_genefinder_path, ""r"") as f: analyze(f, rs, fs,csvfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/plot_reblast.py",".py","2104","53",""""""" Makes operon diagrams with annotations from our curated database on top and TrEMBL/Swissprot/tRNA databases on bottom. """""" import gzip import os import re import sys from operon_analyzer import analyze, visualize from tools.colors import feature_colors from tools.filters import fs original_operons_dir = sys.argv[1] output_dir = sys.argv[2] reblasted_operons = tuple(analyze.load_operons(sys.stdin)) # The Uniprot/Swissprot annotations have a bunch of information # that makes it impossible to see the actual protein name when # plotting operons, so we remove those. remove_os = re.compile(r""OS=.+"") remove_parentheticals = re.compile(r""\(.+\)"") cluster_regex = re.compile(r""cluster(\d+).csv.gz"") for operon in reblasted_operons: for n, feature in enumerate(operon): feature.name = "" "".join(feature.name.split()[1:]) feature.name = remove_os.sub("""", feature.name) feature.name = remove_parentheticals.sub("""", feature.name) for original_operon_gz in os.listdir(original_operons_dir): print(original_operon_gz) cluster_number = int(cluster_regex.match(original_operon_gz).group(1)) # cluster_output_dir = os.path.join(output_dir, original_operon_gz) # os.makedirs(cluster_output_dir, exist_ok=True) with gzip.open(os.path.join(original_operons_dir, original_operon_gz), 'rt') as f: original_operons = tuple(analyze.load_operons(f)) for operon in original_operons: fs.evaluate(operon) assert original_operons, ""Invalid original operons file."" try: for operon, other in visualize.make_operon_pairs(original_operons, reblasted_operons): filename = f""cluster{cluster_number:03d}-{operon.contig}-{operon.start}-{operon.end}.png"" out_filename = os.path.join(output_dir, filename) visualize.plot_operon_pair(operon, other, None, None, out_filename, None, False, feature_colors) except ValueError as e: print(e) print(f""Couldn't plot {os.path.join(original_operons_dir, original_operon_gz)}"") continue ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7/classI/tools/colors.py",".py","1117","24","# Okabe Ito color palette black = (0.0, 0.0, 0.0) orange = (0.9019607843137255, 0.6235294117647059, 0.0) lightblue = (0.33725490196078434, 0.7058823529411765, 0.9137254901960784) green = (0.0, 0.6196078431372549, 0.45098039215686275) yellow = (0.9411764705882353, 0.8941176470588236, 0.25882352941176473) blue = (0.0, 0.4470588235294118, 0.6980392156862745) red = (0.8352941176470589, 0.3686274509803922, 0.0) purple = (0.8, 0.4745098039215686, 0.6549019607843137) # And an extra gray gray = (0.2, 0.2, 0.2) feature_colors = {'transposase|transposition|transposon|integrase|integration|resolvase|recombinase|recombination|IS\d+|(T|t)np': blue, 'cas(1$|2|4)': green, 'cas(3|9|10|12|13)': red, 'cas6|case|csy4': red, 'cas5|casd|csc1|csy2|csf3|csm4|csx10|cmr3': lightblue, 'cas7|casc|csd2|csc2|csy3|csf2|csm3|csm5|cmr1|cmr6|cmr4': purple, 'cas8|casa|csh1|csd1|cse1|csy1|csf1': yellow, 'cas11|casb|cse2|csm2|cmr5': red, '(CRISPR )?array': orange, '': gray} ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/count_operons.py",".py","218","8",""""""" Counts the number of operons that are passed into the script from stdin and prints the result to stdout """""" import sys from operon_analyzer import load print(sum([1 for operon in load.load_operons(sys.stdin)])) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/sts.py",".py","6956","148","import sys from typing import List from operon_analyzer import load, genes from scan import scan_for_repeats, DNASlice, RepeatPair SPACER_SEARCH_SIZE = 200 TARGET_SEARCH_SIZE = 500 MIN_TARGET_SIZE = 10 MAX_TARGET_SIZE = 24 UPSTREAM = ""upstream"" DOWNSTREAM = ""downstream"" def create_search_regions(operon: genes.Operon): for feature, seed_location, direction in define_search_seed(operon): bounds_result = find_array_bounds(operon, feature, seed_location, direction) if not bounds_result: continue start, end = bounds_result array_start, array_end = min(start, end), max(start, end) sequence = load.load_sequence(operon) result = create_sts_search_regions(array_start, array_end, seed_location, direction, sequence) if result is None: continue source, target = result operon._features.append(source) operon._features.append(target) def find_self_targeting_spacers(operon: genes.Operon): sources = [] targets = [] for feature in operon: if feature.name == 'STS source': sources.append(feature) elif feature.name == 'STS target': targets.append(feature) sequence = load.load_sequence(operon) for source in sources: direction = source.description # we overloaded the description with the orientation of the nearest Cas12k repeats = [] for alignment_target in targets: for inverted in (False, True): source_slice = DNASlice(sequence, source.start, source.end) target_slice = DNASlice(sequence, alignment_target.start, alignment_target.end) repeats.extend(scan_for_repeats(source_slice, target_slice, inverted, MIN_TARGET_SIZE, MAX_TARGET_SIZE, 0.9)) if repeats: repeats.sort(key=lambda r: -r.ar.score) best = repeats[0] spacer = best.slice1 target = best.slice2 repeat_start, repeat_end = (spacer.start - 20, spacer.start) if direction == DOWNSTREAM else (spacer.end, spacer.end + 20) repeat = sequence[repeat_start: repeat_end] if direction == DOWNSTREAM else str(sequence[repeat_start: repeat_end].reverse_complement()) spacer_sequence = str(spacer.sequence) if direction == DOWNSTREAM else str(spacer.sequence.reverse_complement()) self_targeting_repeat = genes.Feature('STR', (repeat_start, repeat_end), '', 1 if direction == DOWNSTREAM else -1, '', None, '', repeat) self_targeting_spacer = genes.Feature('STS', (spacer.start, spacer.end), '', 1 if direction == DOWNSTREAM else -1, '', None, f'for {target.start - spacer.start}', spacer_sequence) target_is_inverted = (direction == DOWNSTREAM and best.ar.inverted) or (direction == UPSTREAM and not best.ar.inverted) if not target_is_inverted: pam_start, pam_end = target.start - 6, target.start pam_sequence = sequence[pam_start: pam_end] else: pam_start, pam_end = target.end, target.end + 6 pam_sequence = str(sequence[pam_start: pam_end].reverse_complement()) self_targeting_pam = genes.Feature('PAM', (pam_start, pam_end), '', 1 if not target_is_inverted else -1, '', None, '', pam_sequence) self_target_sequence = str(target.sequence) if not target_is_inverted else str(target.sequence.reverse_complement()) self_target = genes.Feature('ST', (target.start, target.end), '', 1 if not target_is_inverted else -1, '', None, f'from {spacer.start - target.start}', self_target_sequence) operon._features.append(self_targeting_repeat) operon._features.append(self_targeting_spacer) operon._features.append(self_targeting_pam) operon._features.append(self_target) def create_sts_search_regions(array_start, array_end, cas12_boundary, direction, sequence) -> List[RepeatPair]: assert array_start < array_end if direction == UPSTREAM: source = DNASlice(sequence, array_start - SPACER_SEARCH_SIZE, cas12_boundary) target = DNASlice(sequence, max(0, array_start - SPACER_SEARCH_SIZE - TARGET_SEARCH_SIZE), array_start - SPACER_SEARCH_SIZE) elif direction == DOWNSTREAM: source = DNASlice(sequence, cas12_boundary, array_end + SPACER_SEARCH_SIZE) target = DNASlice(sequence, array_end + SPACER_SEARCH_SIZE, min(len(sequence), array_end + SPACER_SEARCH_SIZE + TARGET_SEARCH_SIZE)) if len(source.sequence) < MAX_TARGET_SIZE or len(target.sequence) < MAX_TARGET_SIZE: return None # if the CRISPR array is too far from Cas12k, we assume it's not used if len(source.sequence) > 5000: return None source_feature = genes.Feature('STS source', (source.start, source.end), '', None, '', None, direction, source.sequence) target_feature = genes.Feature('STS target', (target.start, target.end), '', None, '', None, '', target.sequence) return source_feature, target_feature def define_search_seed(operon): """""" Finds Cas12k(s) and determines where to start searching. We start immediately downstream of the gene. """""" for feature in operon: if feature.name == 'cas12k': yield (feature, feature.end, DOWNSTREAM) if feature.strand == 1 else (feature, feature.start, UPSTREAM) def find_array_bounds(operon: genes.Operon, cas12k: genes.Feature, cas12k_end: int, direction: str): assert direction in (DOWNSTREAM, UPSTREAM) arrays = [] for feature in operon: is_array = feature.name in ('CRISPR array', 'Repeat Spacer') array_on_correct_side = ((feature.start > cas12k_end and direction == DOWNSTREAM) \ or (feature.start < cas12k_end and direction == UPSTREAM)) if is_array and array_on_correct_side: arrays.append(abs(cas12k_end - feature.start)) arrays.append(abs(cas12k_end - feature.end)) if not arrays: return None arrays.sort() start = arrays[0] end = arrays[1] if len(arrays) == 2: return (cas12k_end - start, cas12k_end - end) if direction == UPSTREAM else (cas12k_end + start, cas12k_end + end) for a, b in zip(arrays[1:], arrays[2:]): if b - a < 250: end = b else: break return (cas12k_end - start, cas12k_end - end) if direction == UPSTREAM else (cas12k_end + start, cas12k_end + end) if __name__ == '__main__': with open(sys.argv[1]) as f: operons = list(load.load_operons(f)) for operon in operons: create_search_regions(operon) find_self_targeting_spacers(operon) print(operon.as_str()) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/main.sh",".sh","4375","102","#!/usr/bin/env bash # This script runs the Tn7 Type V CRISPR-transposon pipeline. set -euo pipefail # Halt the pipeline if any errors are encountered OUTPUT=../../output/tn7-type-v DATA=../../data/tn7-type-v INPUT=$(ls /stor/work/Wilke/amh7958/pipeline-results/*tar.gz /stor/work/Wilke/amh7958/pipeline-results/missing_effectors/*.tar.gz) DATA=../../data/tn7-type-v KEEP_PATHS=""NO"" mkdir -p $OUTPUT $OUTPUT/plots $OUTPUT/reblast if [[ ! -e $OUTPUT/cas12k.csv.gz ]]; then >&2 echo ""Running systems through Cas12k rules"" for filename in $INPUT; do # stream tar files to stdout tar -xzOf $filename done | python fix_paths.py NO | python rules-cas12k.py | gzip > $OUTPUT/cas12k.csv.gz fi if [[ ! -e $OUTPUT/cas12k-tns.csv.gz ]]; then >&2 echo ""Running systems through Tn7 rules"" gzip -cd $OUTPUT/cas12k.csv.gz | python rules-tn7.py | python dedup.py | gzip > $OUTPUT/cas12k-tns.csv.gz fi if [[ ! -e $OUTPUT/cas12k-tns-minced.csv.gz ]]; then >&2 echo ""Finding CRISPR arrays"" gzip -cd $OUTPUT/cas12k-tns.csv.gz | python minced.py | gzip > $OUTPUT/cas12k-tns-minced.csv.gz fi if [[ ! -e $OUTPUT/cas12k-tns-minced-array.csv.gz ]]; then >&2 echo ""Filtering systems without arrays"" gzip -cd $OUTPUT/cas12k-tns-minced.csv.gz | python rules-array.py | gzip > $OUTPUT/cas12k-tns-minced-array.csv.gz fi if [[ ! -e $OUTPUT/unique-filenames.txt ]]; then >&2 echo ""Getting unique filenames"" gzip -cd $OUTPUT/cas12k-tns-minced-array.csv.gz | python extract-filenames.py | sort -u > $OUTPUT/unique-filenames.txt fi mkdir -p $OUTPUT/reblast if [[ ""$(ls $OUTPUT/reblast | wc -l)"" -eq ""0"" ]]; then >&2 echo ""Re-BLASTing systems"" cat $OUTPUT/unique-filenames.txt | parallel -j 96 ""python relook.py {} $OUTPUT/reblast"" fi mkdir -p $OUTPUT/reblast-minced if [[ ""$(ls $OUTPUT/reblast-minced | wc -l)"" -eq ""0"" ]]; then >&2 echo ""Running minced on re-BLASTed results"" for filename in $(ls $OUTPUT/reblast/*csv); do basename $filename done | parallel -j 96 ""cat $OUTPUT/reblast/{} | python minced.py > $OUTPUT/reblast-minced/{}"" fi if [[ ! -e $OUTPUT/reblasted-cas12k-with-sts.csv.gz ]]; then >&2 echo ""Finding self-targeting spacers"" for filename in $(ls $OUTPUT/reblast-minced/*csv); do echo $filename done | parallel -j 96 ""python sts.py {}"" | gzip > $OUTPUT/reblasted-cas12k-with-sts.csv.gz fi if [[ ! -e $OUTPUT/reblasted-cas12k-with-sts-rules-deduped.csv.gz ]]; then gzip -cd $OUTPUT/reblasted-cas12k-with-sts.csv.gz | python rules-cas12k.py | python rules-tn7.py | python rules-array.py | python dedup.py | gzip > $OUTPUT/reblasted-cas12k-with-sts-rules-deduped.csv.gz fi # Do the work needed to determine the target site identities if [[ ! -e $OUTPUT/self-target-context-seqs.fa ]]; then >&2 echo ""Making fasta file of target sequences so we can BLAST them"" gzip -cd $OUTPUT/reblasted-cas12k-with-sts.csv.gz | python make-self-target-fasta.py > $OUTPUT/self-target-context-seqs.fa fi if [[ ! -e $OUTPUT/self-target-blastn-nt.tsv ]]; then >&2 echo ""blastn att sites"" blastn-2.10 -db ~/work/nt/nt -query $OUTPUT/self-target-context-seqs.fa -evalue 1e-8 -outfmt '6 qseqid sseqid evalue qseq sseq pident stitle' -num_threads 16 -max_target_seqs 100 | rg -v 'genome' | rg -v 'chromosome' | rg -v 'complete sequence' | rg -v 'genomic( DNA)? sequence' > $OUTPUT/self-target-blastn-nt.tsv fi if [[ ! -e $OUTPUT/self-target-blastx-nr.tsv ]]; then >&2 echo ""blasttx att sites"" blastx-2.10 -db ~/work/nrdb/nr -query $OUTPUT/self-target-context-seqs.fa -evalue 1e-8 -outfmt '6 qseqid sseqid evalue qseq sseq pident stitle' -num_threads 16 -max_target_seqs 100 | rg -v 'genome' | rg -v 'chromosome' | rg -v 'complete sequence' | rg -v 'genomic( DNA)? sequence' > $OUTPUT/self-target-blastx-nr.tsv fi # Perform alignments for Figure 5 if [[ ! -e $OUTPUT/fig5d.afa ]]; then >&2 echo ""Fig 5D alignments"" mafft --auto $DATA/fig-5d-tnsc.fa > $OUTPUT/fig5d.afa fi if [[ ! -e $OUTPUT/fig5e.afa ]]; then >&2 echo ""Fig 5E alignments"" mafft --auto $DATA/fig-5e-tnsb.fa > $OUTPUT/fig5e.afa fi if [[ ! -e $OUTPUT/canonical-pams.txt ]]; then >&2 echo ""Getting sequences of self-targeting PAMs"" gzip -cd $OUTPUT/reblasted-cas12k-with-sts-rules-deduped.csv.gz | python get-pams.py > $OUTPUT/canonical-pams.txt 2> $OUTPUT/other-pams.txt fi ","Shell" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/extract-filenames.py",".py","244","12",""""""" Gets the filenames for each system. This is just needed to make it easy to parallelize the re-BLASTing step. """""" import sys from operon_analyzer import load for operon in load.load_operons(sys.stdin): print(operon.contig_filename) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/scan.py",".py","4464","110","import re from collections import namedtuple from typing import List, Tuple import more_itertools import parasail from Bio.Seq import Seq GAP_OPEN_PENALTY = 12 GAP_EXTEND_PENALTY = 12 cigar_regex = re.compile(r""(\d+)="") Coordinates = List[Tuple[int, int]] AlignmentResult = namedtuple('AlignmentResult', ['score', 'match_count', 'haystack_start', 'haystack_end', 'aligned_haystack_sequence', 'aligned_needle_sequence', 'comparison_string', 'inverted']) def _count_cigar_matches(string: str) -> int: """""" parasail provides a CIGAR string to encode the alignment. We parse this to determine the number of exact matches. """""" matches = cigar_regex.findall(string) return sum([int(match) for match in matches]) class DNASlice(object): """""" Represents a subsequence in a larger DNA, while retaining the global coordinates of the smaller slice. """""" def __init__(self, sequence: Seq, start: int, end: int): self.full_sequence = sequence self.start = start self.end = end def get_slice_from_local_coordinates(self, start: int, end: int): """""" When we hand out the sequence for local alignment, we'll get coordinates relative to that slice. This method takes those coordinates directly and updates the global location. """""" return DNASlice(self.full_sequence, self.start + start, self.start + end) @property def sequence(self): return self.full_sequence[self.start: self.end] class RepeatPair(object): def __init__(self, slice1: DNASlice, slice2: DNASlice, ar: AlignmentResult): self.slice1 = slice1 self.slice2 = slice2 self.ar = ar def align(needle: str, haystack: str, inverted: bool) -> AlignmentResult: """""" Run the local pairwise alignment of two strings and return alignment data. """""" # perform the alignment result = parasail.sw_trace(needle, haystack, GAP_OPEN_PENALTY, GAP_EXTEND_PENALTY, parasail.nuc44) # extract pertinent data from the alignment result cigar_text = result.cigar.decode.decode(""utf8"") match_count = _count_cigar_matches(cigar_text) haystack_sequence = result.traceback.ref.replace(""-"", """") haystack_end = result.end_ref + 1 haystack_start = haystack_end - len(haystack_sequence) return AlignmentResult(score=result.score, match_count=match_count, haystack_start=haystack_start, haystack_end=haystack_end, aligned_haystack_sequence=result.traceback.ref, aligned_needle_sequence=result.traceback.query, comparison_string=result.traceback.comp, inverted=inverted) def scan_for_repeats(source: DNASlice, target: DNASlice, inverted: bool, min_length: int, max_length: int, min_homology: float) -> List[RepeatPair]: repeats = [] for length in range(min_length, max_length): for source_start_coord, nucleotides in enumerate(more_itertools.windowed(source.sequence, length)): if nucleotides[-1] is None: break # prepare the source sequence for alignment sequence = Seq("""".join(nucleotides)) sequence = str(sequence.reverse_complement()) if inverted else str(sequence) # align the sequences alignment_result = align(sequence, str(target.sequence), inverted) # assess the quality of this alignment if len(alignment_result.aligned_haystack_sequence) < length: continue homology = alignment_result.match_count / len(alignment_result.aligned_haystack_sequence) if homology < min_homology: continue # document the sequence and coordinates of the repeat pair source_end_coord = source_start_coord + length source_slice = source.get_slice_from_local_coordinates(source_start_coord, source_end_coord) target_slice = target.get_slice_from_local_coordinates(alignment_result.haystack_start, alignment_result.haystack_end) repeats.append(RepeatPair(source_slice, target_slice, alignment_result)) return repeats ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/make-fastas-for-phylogenetic-tree.py",".py","1033","31",""""""" Separates protein sequences for making phylogenetic trees. We also keep the low e-value proteins because TnsC is usually mislabelled as TnsB. """""" import sys from operon_analyzer import load protein = sys.argv[1] limit = float(sys.argv[2]) evalues = [] good_seqs = set() bad_seqs = set() for operon in load.load_operons(sys.stdin): n = 0 m = 0 for feature in operon: if feature.name != protein: continue if feature.e_val < limit and feature.sequence not in good_seqs: print(f"">{operon.contig}_{operon.start}_{operon.end}_{feature.start}_{feature.end}_{n}"") print(f""{feature.sequence}"") good_seqs.add(feature.sequence) n += 1 elif feature.e_val >= limit and feature.sequence not in bad_seqs: print(f"">{operon.contig}_{operon.start}_{operon.end}_{feature.start}_{feature.end}_{n}"", file=sys.stderr) print(f""{feature.sequence}"", file=sys.stderr) bad_seqs.add(feature.sequence) m += 1 ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/count_sources.py",".py","449","23",""""""" Counts how many systems came from which of our two databases. """""" from operon_analyzer import load import sys ncbi = 0 embl = 0 other = 0 for operon in load.load_operons(sys.stdin): if 'NCBI' in operon.contig_filename: ncbi += 1 elif 'EMBL_EBI' in operon.contig_filename: embl += 1 else: other += 1 print(f""NCBI: {ncbi}"") print(f""EMBL: {embl}"") print(f""Other: {other}"") print(f""Total:{ncbi+embl+other}"") ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/rules-tn7.py",".py","705","19",""""""" Selects all potential Type V systems. """""" import sys from operon_analyzer import analyze, rules import custom_rules from tools.filters import fs tn7_proteins = (""tnsA"", ""tnsB"", ""tnsC"", ""tnsD"", ""tniQ"") rs = rules.RuleSet().custom(rule=custom_rules.contains_at_least_n_features_n_bp_apart(feature_list=tn7_proteins, feature_count=2, distance_bp=1500, count_multiple_copies=True)) analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/fix_paths.py",".py","1417","37",""""""" In the raw gene_finder output, paths to the FASTA files are valid on TACC (where gene_finder was run), but do not point to the correct location on our local cluster. This script updates the paths in the Operon objects so that we can access raw nucleotide data in downstream analyses. """""" import csv import os import sys from operon_analyzer import parse def fix_path(contig_filename: str) -> str: # update paths from those at TACC to those on our local cluster leaf = contig_filename.replace(""/scratch/07227/hilla3/projects/CRISPR-Transposons/data/genomic/"", """") leaf = leaf.replace('genbank_bacteria_20210505', 'NCBI_redownload/genbank_bacteria_20210505') basedir = '/stor/scratch/Wilke/contig/database/metagenomic_contig_database' if not leaf.startswith(""NCBI""): if 'genbank_bacteria_20210505' not in contig_filename: basedir = f'{basedir}/EMBL_EBI' good_path = os.path.join(basedir, leaf) assert os.path.exists(good_path) return good_path if __name__ == '__main__': skip = sys.argv[1] if skip == 'YES': # This is useful is the pipeline is being run on a system other than our own for line in sys.stdin: print(line) else: writer = csv.writer(sys.stdout, delimiter=',') for line in parse.read_pipeline_output(sys.stdin): line[21] = fix_path(line[21]) writer.writerow(line) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/rules-cas12k.py",".py","234","15",""""""" Selects all potential Type V systems. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().require('cas12k') analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/relook.py",".py","987","24",""""""" Re-runs the search for Type V CASTs, but uses the Cas12k database as the seed instead of the transposase one. We do this because we noticed that some Type V CASTs contain co-localized transposons or were actually insertions at the exact same attachment site. """""" import os import sys from gene_finder.pipeline import Pipeline filename = sys.argv[1] out_path = sys.argv[2] min_prot_len = 80 # ORF aa cutoff length span = 100000 # length (bp) upstream & downstream of bait hits to keep filename = filename.strip() job_id = os.path.basename(filename) p = Pipeline() p.add_seed_step(db='/stor/work/Wilke/amh7958/databases/cas12k/blast_db', name='cas12k', e_val=1e-30, blast_type=""PROT"", blast_path='blastp', num_threads=1) p.add_blast_step(db='/stor/work/Wilke/blastDB/classifer/tns', name='tns', e_val=1e-3, blast_type='PROT', blast_path='blastp', num_threads=1) p.add_crispr_step() p.run(filename, job_id, out_path, min_prot_len, span, False, gzip=True) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/get-pams.py",".py","1940","45","# Writes the sequences for the PAM for each self-target in the Type V systems. # This produces a flat text file that will be used to generate a sequence logo for the PAM # in Figure 5. There are some cases where the pairwise alignment seems to have made an # off-by-one error - in these cases, we adjust the alignment by one base pair. This is a # reasonable assumption given that there is both bioinformatic and experimental evidence # that the atypical repeat always ends in ""GAAAG"". # We split the output into two groups - those systems with canonical atypical repeats, # and all others. We believe the latter group is the result of spurious alignments from # systems that don't actually have self-targeting spacers (or are using them in trans). import sys from operon_analyzer import load for operon in load.load_operons(sys.stdin): data = {""STS"": [], ""STR"": [], ""PAM"": [], ""ST"": []} for feature in operon: if feature.name in ('STS', 'STR', 'PAM', 'ST'): data[feature.name].append(feature) seen_pams = [] for spacer, repeat, pam, target in zip(data[""STS""], data[""STR""], data[""PAM""], data[""ST""]): # If two systems target the exact same location, we don't want to double count that PAM if pam.start in seen_pams: continue seen_pams.append(pam.start) if repeat.sequence.endswith(""GAAA"") and spacer.sequence.startswith(""G""): # We've found a case that's probably an off-by-one error, so we adjust the sequences repeat.sequence = repeat.sequence[1:] + ""G"" spacer.sequence = spacer.sequence[1:] pam.sequence = pam.sequence[1:] + target.sequence[0] target.sequence = target.sequence[1:] if repeat.sequence.endswith(""GAAAG""): outfile = sys.stdout else: outfile = sys.stderr print(f""{pam.sequence}"", file=outfile) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/plot_operons.py",".py","690","22","import os import sys from operon_analyzer import visualize, load from tools.colors import feature_colors output_dir = sys.argv[1] os.makedirs(output_dir, exist_ok=True) for operon in load.load_operons(sys.stdin): try: filename = f""{operon.contig}-{operon.start}-{operon.end}.png"" out_filename = os.path.join(output_dir, filename) fig = visualize.create_operon_figure(operon, False, feature_colors, color_by_blast_statistic=False, nucl_per_line=20000, show_accession=False, show_description=True) if fig is None: continue visualize.save_operon_figure(fig, out_filename) except Exception as e: print(e) continue ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/rules-array.py",".py","302","13",""""""" Selects systems with CRISPR arrays located near Cas12k. """""" import sys from operon_analyzer import analyze, rules from tools.filters import fs rs = rules.RuleSet().max_distance('cas12k', 'Repeat Spacer', 1000, closest_pair_only=True) analyze.evaluate_rules_and_reserialize(sys.stdin, rs, fs) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/minced.py",".py","1339","40",""""""" Runs minCED on each system to find CRISPR arrays. For some reason, ~25% of Type V systems don't get their arrays deteceted by piler-cr. """""" import re import subprocess import sys from uuid import uuid4 from operon_analyzer import genes, load regex = re.compile(r""^(\d+)\s+(\w+)\s+(\w+).*"") def run_minced(operon): sequence = load.load_sequence(operon) opstart = max(0, operon.start-2000) opend = min(len(sequence), operon.end+2000) sequence = sequence[opstart: opend] uid = uuid4() with open(f""/tmp/mincedseq-{uid}.fa"", ""w"") as f: f.write(f"">seq\n{str(sequence)}"") subprocess.call(f'minced -minNR 2 /tmp/mincedseq-{uid}.fa /tmp/minced-{uid}.crisprs'.split()) with open(f""/tmp/minced-{uid}.crisprs"") as f: for line in f: match = regex.match(line) if match: start = int(match.group(1)) repeat = match.group(2) spacer = match.group(3) end = start + len(repeat) + len(spacer) feature = genes.Feature('Repeat Spacer', (start+opstart, end+opstart), '', None, '', None, f""{repeat} {spacer}"", spacer) operon._features.append(feature) if __name__ == '__main__': for operon in load.load_operons(sys.stdin): run_minced(operon) print(operon.as_str()) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/custom_rules.py",".py","11127","216",""""""" Extra rules needed to select Type V CASTs. """""" from operon_analyzer.rules import Rule, RuleSet, _feature_distance from operon_analyzer.genes import Operon, Feature from typing import List, Iterator import more_itertools import pytest def contains_at_least_n_features_n_bp_apart(feature_list: List[str], feature_count: int, distance_bp: int, count_multiple_copies: bool = False): """""" The operon must have at least feature_count given features at most distance_bp apart. In other words, checks if there exists at least one sub-operon that contains some combination of the features in the list and requires that those features be at most distance_bp apart. """""" serialized_list = ""|"".join(feature_list) custom_repr = f'contains-at-least-n-features-n-bp-apart:{serialized_list}-{feature_count}-{distance_bp}-{count_multiple_copies}' rule = Rule('contains_at_least_n_features_n_bp_apart', _contains_at_least_n_features_n_bp_apart, feature_list, feature_count, distance_bp, count_multiple_copies, custom_repr=custom_repr) return rule def contains_these_features_n_bp_apart(feature_list: List[str], distance_bp: int, allow_gaps: bool = False): """""" All features in the list must appear grouped together in at least one location in the operon. `distance_bp` sets the maximum allowed distance apart. By default, the features must be contiguous; setting `allow_gaps=True` permits other annotated features to interupt the sequence if they also adhere to the `distance_bp` requirement. """""" serialized_list= ""|"".join(feature_list) custom_repr = f'contains-these_features_n_bp_apart:{serialized_list}-{distance_bp}-{allow_gaps}' rule = Rule('contains-these_features_n_bp_apart', _contains_these_features_n_bp_apart, feature_list, distance_bp, allow_gaps, custom_repr=custom_repr) return rule def _contains_at_least_n_features(operon: Operon, feature_names: List[str], feature_count: int, count_multiple_copies: bool) -> bool: """""" Whether the operon has at least feature_count given features. """""" matches = [feature_name for feature_name in operon.feature_names if feature_name in feature_names] if len(matches) >= feature_count and count_multiple_copies: return True elif len(set(matches)) >= feature_count: return True else: return False def _contains_at_least_n_features_n_bp_apart(operon: Operon, feature_list: List[str], feature_count: int, distance_bp: int, count_multiple_copies: bool) -> bool: """""" Whether the operon has at least feature_count given features at most distance_bp apart. """""" # For this rule to be true, contains_at_least_n_features must be true also if not _contains_at_least_n_features(operon, feature_list, feature_count, count_multiple_copies): return False for sub_operon in _feature_clusters_with_same_orientation(operon, distance_bp): features_in_list = [feature for feature in sub_operon if feature in feature_list] if (len(features_in_list) >= feature_count and count_multiple_copies) or len(set(features_in_list)) >= feature_count: return True return False def _contains_these_features_n_bp_apart(operon: Operon, feature_list: List[str], distance_bp: int, allow_gaps: bool) -> bool: """""" Whether all features in the list appear grouped together in at least one location in the operon. """""" # For this rule to be true, contains_at_least_n_features must be true also if not _contains_at_least_n_features(operon, feature_list, feature_count=len(feature_list), count_multiple_copies=False): return False for sub_operon in _feature_clusters_with_same_orientation(operon, distance_bp): if set(sub_operon) == set(feature_list) or (set(feature_list).issubset(sub_operon) and allow_gaps): return True return False def _same_orientation_two_features(f1: Feature, f2: Feature) -> bool: """""" Checks if two features are in the same orientation. """""" # Somewhat arbitrarily, we say that two features cannot have the same # orientation if one is a CRISPR array or some other directionless entity if (f1.strand is None) or (f2.strand is None): return False return (f1.strand == f2.strand) def _feature_clusters_with_same_orientation(operon: Operon, distance_bp: int) -> Iterator[List[str]]: """""" Generates lists of names of features that appear in clusters in the operon. For a feature to be added to a cluster, it must be in the same orientation as the cluster and at most distance_bp from its nearest upstream neighbor. """""" operon_features = [feature for feature in operon] operon_features.sort(key = lambda feature: feature.start) last_feature = operon_features.pop(0) cluster = [last_feature.name] for this_feature in operon_features: if _feature_distance(this_feature, last_feature) <= distance_bp and _same_orientation_two_features(this_feature, last_feature): cluster.append(this_feature.name) else: yield cluster cluster = [this_feature.name] last_feature = this_feature yield cluster def contains_subset_group(feature_names: List[str], max_gap_distance_bp: int, require_same_orientation: bool, window_size: int): """""" Determines whether Features with the names in feature_names occur in any order without interruption by other Features, with gaps between each Feature no larger than max_gap_distance_bp. Groups do not need to contain all Features in feature_names, but the set of Features in the group must be <= the set of Features in feature_names. """""" rule = Rule('contains_subset_group', _contains_subset_group, feature_names, max_gap_distance_bp, require_same_orientation, window_size) return rule def _contains_subset_group(operon: Operon, feature_names: List[str], max_gap_distance_bp: int, require_same_orientation: bool, window_size: int) -> bool: """""" Determines whether Features with the names in feature_names occur in any order without interruption by other Features, with gaps between each Feature no larger than max_gap_distance_bp. Groups do not need to contain all Features in feature_names, but the set of Features in the group must be <= the set of Features in feature_names. """""" assert window_size > 1 if len(operon) < window_size: return False for operon_chunk in more_itertools.windowed(operon, window_size): operon_chunk_names = [feature.name for feature in operon_chunk] if set(operon_chunk_names) <= set(feature_names): max_gap_distance_in_group = 0 for feature1, feature2 in zip(operon_chunk, operon_chunk[1:]): max_gap_distance_in_group = max(_feature_distance(feature1, feature2), max_gap_distance_in_group) if max_gap_distance_in_group > max_gap_distance_bp: continue if require_same_orientation: strands = set((feature.strand for feature in operon_chunk if feature.strand is not None)) if len(strands) != 1: continue return True return False # TESTS @pytest.mark.parametrize('gene1_start,gene1_end,gene2_start,gene2_end,strand1,strand2,expected', [ (12, 400, 410, 600, 1, 1, True), (410, 600, 610, 400, 1, -1, False), (400, 500, 510, 600, 1, None, False), (400, 500, 510, 600, None, None, False) ]) def test_same_orientation_two_features(gene1_start, gene1_end, gene2_start, gene2_end, strand1, strand2, expected): f1 = Feature('f1', (gene1_start, gene1_end), '', strand1, '', 4e-19, 'a good gene', 'MCGYVER') f2 = Feature('f2', (gene2_start, gene2_end), '', strand2, '', 2e-5, 'a good gene', 'MGFRERAR') result = _same_orientation_two_features(f1, f2) assert result == expected @pytest.mark.parametrize('gene_list,feature_count,distance_bp,count_multiple,expected', [ ([""cas1"", ""cas2"", ""cas3"", ""cas4""], 4, 100, False, True), ([""cas1"", ""cas2"", ""cas3"", ""cas4""], 5, 100, False, False), ([""cas1"", ""cas2"", ""cas3"", ""cas4""], 5, 100, True, True), ([""cas1"", ""cas2"", ""cas3"", ""cas4""], 5, 10, True, False), ([""cas1"", ""cas2"", ""cas3"", ""cas4"", ""cas5""], 5, 100, False, False) ]) def test_contains_at_least_n_features_n_bp_apart(gene_list, feature_count, distance_bp, count_multiple, expected): genes = [ Feature('cas1', (12, 400), 'lcl|12|400|1|-1', 1, 'ACACEHFEF', 4e-19, 'a good gene', 'MCGYVER'), Feature('cas2', (450, 600), 'lcl|410|600|1|-1', 1, 'FGEYFWCE', 2e-5, 'a good gene', 'MGFRERAR'), Feature('cas3', (650, 680), 'lcl|410|600|1|-1', 1, 'FGEYFWCE', 2e-5, 'a good gene', 'MGFRERAR'), Feature('cas4', (700, 730), 'lcl|620|1200|1|-1', 1, 'NFBEWFUWEF', 6e-13, 'a good gene', 'MLAWPVTLE'), Feature('cas4', (740, 800), 'lcl|620|1200|1|-1', 1, 'NFBEWFUWEF', 6e-13, 'a good gene', 'MLAWPVTLE'), Feature('cas5', (900, 810), 'lcl|410|600|1|-1', -1, 'FGEYFWCE', 2e-5, 'a good gene', 'MGFRERAR') ] operon = Operon('QCDRTU', ""a file"", 0, 3400, genes) rs = RuleSet().custom(rule=contains_at_least_n_features_n_bp_apart(gene_list, feature_count, distance_bp, count_multiple)) result = rs.evaluate(operon) assert result.is_passing is expected @pytest.mark.parametrize('gene_list,distance_bp,allow_gaps,expected', [ ([""tniQ"", ""cas1"", ""cas2"", ""cas4""], 100, True, True), ([""tniQ"", ""cas1"", ""cas2"", ""cas3""], 100, False, False), ([""tniQ"", ""cas4""], 100, False, False) ]) def test_contains_these_features_n_bp_apart(gene_list, distance_bp, allow_gaps, expected): genes = [ Feature('tnsA', (20, 80), 'lcl|12|400|1|-1', 1, 'ACACEHFEF', 4e-19, 'a good gene', 'MCGYVER'), Feature('tniQ', (200, 340), 'lcl|12|400|1|-1', 1, 'ACACEHFEF', 4e-19, 'a good gene', 'MCGYVER'), Feature('cas1', (350, 400), 'lcl|12|400|1|-1', 1, 'ACACEHFEF', 4e-19, 'a good gene', 'MCGYVER'), Feature('cas2', (450, 600), 'lcl|410|600|1|-1', 1, 'FGEYFWCE', 2e-5, 'a good gene', 'MGFRERAR'), Feature('cas3', (650, 680), 'lcl|410|600|1|-1', 1, 'FGEYFWCE', 2e-5, 'a good gene', 'MGFRERAR'), Feature('cas4', (700, 730), 'lcl|620|1200|1|-1', 1, 'NFBEWFUWEF', 6e-13, 'a good gene', 'MLAWPVTLE'), Feature('cas4', (740, 800), 'lcl|620|1200|1|-1', 1, 'NFBEWFUWEF', 6e-13, 'a good gene', 'MLAWPVTLE'), Feature('cas5', (900, 810), 'lcl|410|600|1|-1', -1, 'FGEYFWCE', 2e-5, 'a good gene', 'MGFRERAR') ] operon = Operon('QCDRTU', ""a file"", 0, 3400, genes) rs = RuleSet().custom(rule=contains_these_features_n_bp_apart(gene_list, distance_bp, allow_gaps)) result = rs.evaluate(operon) assert result.is_passing is expected ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/dedup.py",".py","321","13",""""""" Filters out putative operons that are extremely similar to one another. """""" import sys from operon_analyzer import analyze operons = analyze.load_operons(sys.stdin) unique = analyze.deduplicate_operons_approximate(operons) unique = analyze.dedup_supersets(unique) for operon in unique: print(operon.as_str()) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/plot_architectures.py",".py","3104","76",""""""" Makes plots of each Type V CAST system, binning each architecture in separate directories. """""" import os import sys from itertools import zip_longest from operon_analyzer import load, visualize architectures = {} transposon_genes = set(['tnsA', 'tnsB', 'tnsC', 'tnsD', 'tnsE', 'tniQ', 'cas12k', 'ST', 'CANONSTS', 'STS', 'STR', 'PAM']) plot_directory = sys.argv[1] def plot_operons(operons, output_dir): for operon in operons: operon._features = [feature for feature in operon if feature.name not in ('STS source', 'STS target')] for feature in operon: if feature.name == 'Repeat Spacer': feature.description = '' try: filename = f""{operon.contig}-{operon.start}-{operon.end}.png"" out_filename = os.path.join(output_dir, filename) fig = visualize.create_operon_figure(operon, False, color_by_blast_statistic='e_val', nucl_per_line=20000, show_accession=False, show_description=True, colormin=1e-30, colormax=1e-3) if fig is None: continue visualize.save_operon_figure(fig, out_filename) except Exception as e: print(e) continue for operon in load.load_operons(sys.stdin): # First, find if any self-targeting spacers are canonical arrays = [feature for feature in operon if feature.name in ('Repeat Spacer', 'CRISPR array')] stss = operon.get('STS') for sts in stss: for array in arrays: if array.start < sts.start < array.end or array.start < sts.end < array.end: sts.name = 'CANONSTS' break features = [] sorted_features = list(sorted(operon, key=lambda feat: feat.start)) if len(sorted_features) < 2: continue deduplicated_features = [] for feature1, feature2 in zip_longest(sorted_features, sorted_features[1:], fillvalue=None): if feature2 is not None and feature1.name == feature2.name and feature1.start == feature2.start and feature1.end == feature2.end and feature1.sequence == feature2.sequence: continue deduplicated_features.append(feature1) for feature in deduplicated_features: expected_gene = feature.name in transposon_genes good_annotation = feature.e_val is None or feature.e_val <= 1e-3 if expected_gene and good_annotation: features.append(feature.name) features = tuple(features) if features in architectures: architectures[features].append(operon) elif tuple(reversed(features)) in architectures: architectures[tuple(reversed(features))].append(operon) else: architectures[features] = [operon] # Now make plots, with each different architecture in its own directory. for features, operons in architectures.items(): subdirectory_name = '-'.join(features) directory = os.path.join(plot_directory, subdirectory_name) os.makedirs(directory, exist_ok=True) plot_operons(operons, directory) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/make-self-target-fasta.py",".py","570","17",""""""" Makes FASTA files of the DNA 50 bp around each target so we can BLAST them. """""" import sys from operon_analyzer import load for operon in load.load_operons(sys.stdin): sequence = load.load_sequence(operon) for feature in operon: if feature.name == 'ST': start = max(0, feature.start - 50) end = min(len(sequence), feature.end + 50) target_sequence = sequence[start: end] print(f"">{operon.contig}_{operon.start}..{operon.end}_{feature.start}..{feature.end}"") print(str(target_sequence)) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/tools/__init__.py",".py","0","0","","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/tools/colors.py",".py","1154","25","# Okabe Ito color palette black = (0.0, 0.0, 0.0) orange = (0.9019607843137255, 0.6235294117647059, 0.0) lightblue = (0.33725490196078434, 0.7058823529411765, 0.9137254901960784) green = (0.0, 0.6196078431372549, 0.45098039215686275) yellow = (0.9411764705882353, 0.8941176470588236, 0.25882352941176473) blue = (0.0, 0.4470588235294118, 0.6980392156862745) red = (0.8352941176470589, 0.3686274509803922, 0.0) purple = (0.8, 0.4745098039215686, 0.6549019607843137) # And an extra gray gray = (0.2, 0.2, 0.2) feature_colors = {'transposase|transposition|transposon|integrase|integration|resolvase|recombinase|recombination|IS\d+|(T|t)np': blue, 'cas(1$|2|4)': green, 'cas(3|9|10|12|13)': red, 'cas6|case|csy4': red, 'cas5|casd|csc1|csy2|csf3|csm4|csx10|cmr3': lightblue, 'cas7|casc|csd2|csc2|csy3|csf2|csm3|csm5|cmr1|cmr6|cmr4': purple, 'cas8|casa|csh1|csd1|cse1|csy1|csf1': yellow, 'cas11|casb|cse2|csm2|cmr5': red, '(CRISPR )?array': orange, '.*trna.*': green, '': gray} ","Python" "CRISPR","wilkelab/Metagenomics_CAST","src/tn7-type-v/tools/filters.py",".py","1392","34","from operon_analyzer import rules, genes def _no_scarlet(operon: genes.Operon, ignored_reason_message: str): """""" There is an ABC transporter gene that was accidentally included in our database because its truncation was created with Cas9, and Cas9 was in its gene name. """""" for feature in operon.get('cas9'): if 'ABC' in feature.description: feature.ignore(ignored_reason_message) def _remove_arrays_inside_cds(operon: genes.Operon, ignored_reason_message: str): """""" Filters out CRISPR arrays that are contained within a CDS. These occur frequently due to the enthusiasm of pilercr. """""" genes = [feature for feature in operon.all_features if feature.name != 'CRISPR array'] for array in operon: if array.name != 'CRISPR array': continue for gene in genes: if rules._feature_distance(gene, array) == 0: array.ignore(ignored_reason_message) break _no_scarlet_mutation_filter = rules.Filter('no-scarlet', _no_scarlet) _arrays_inside_cds_filter = rules.Filter('array-is-inside-cds', _remove_arrays_inside_cds) fs = rules.FilterSet().pick_overlapping_features_by_bit_score(0.9) \ .must_be_within_n_bp_of_anything(30000) \ .custom(_arrays_inside_cds_filter) \ .custom(_no_scarlet_mutation_filter) ","Python" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/tree.cpp",".cpp","28698","1021","#include ""multaln.h"" #define TRACE 0 /*** Node has 0 to 3 neighbors: 0 neighbors: singleton root 1 neighbor: leaf, neighbor is parent 2 neigbors: non-singleton root 3 neighbors: internal node (other than root) Minimal rooted tree is single node. Minimal unrooted tree is single edge. Leaf node always has nulls in neighbors 2 and 3, neighbor 1 is parent. When tree is rooted, neighbor 1=parent, 2=left, 3=right. ***/ void Tree::AssertAreNeighbors(unsigned uNodeIndex1, unsigned uNodeIndex2) const { if (uNodeIndex1 >= m_uNodeCount || uNodeIndex2 >= m_uNodeCount) Quit(""AssertAreNeighbors(%u,%u), are %u nodes"", uNodeIndex1, uNodeIndex2, m_uNodeCount); if (m_uNeighbor1[uNodeIndex1] != uNodeIndex2 && m_uNeighbor2[uNodeIndex1] != uNodeIndex2 && m_uNeighbor3[uNodeIndex1] != uNodeIndex2) { LogMe(); Quit(""AssertAreNeighbors(%u,%u) failed"", uNodeIndex1, uNodeIndex2); } if (m_uNeighbor1[uNodeIndex2] != uNodeIndex1 && m_uNeighbor2[uNodeIndex2] != uNodeIndex1 && m_uNeighbor3[uNodeIndex2] != uNodeIndex1) { LogMe(); Quit(""AssertAreNeighbors(%u,%u) failed"", uNodeIndex1, uNodeIndex2); } if (HasEdgeLength(uNodeIndex1, uNodeIndex2) && GetEdgeLength(uNodeIndex1, uNodeIndex2) != GetEdgeLength(uNodeIndex2, uNodeIndex1)) { LogMe(); Quit(""Tree::AssertAreNeighbors, Edge length disagrees %u, %u"", uNodeIndex1, uNodeIndex2); } } void Tree::ValidateNode(unsigned uNodeIndex) const { if (uNodeIndex >= m_uNodeCount) Quit(""ValidateNode(%u), %u nodes"", uNodeIndex, m_uNodeCount); const unsigned uNeighborCount = GetNeighborCount(uNodeIndex); if (2 == uNeighborCount) { if (!m_bRooted) { LogMe(); Quit(""Tree::ValidateNode: Node %u has two neighbors, tree is not rooted"", uNodeIndex); } if (uNodeIndex != m_uRootNodeIndex) { LogMe(); Quit(""Tree::ValidateNode: Node %u has two neighbors, but not root node=%u"", uNodeIndex, m_uRootNodeIndex); } } const unsigned n1 = m_uNeighbor1[uNodeIndex]; const unsigned n2 = m_uNeighbor2[uNodeIndex]; const unsigned n3 = m_uNeighbor3[uNodeIndex]; if (NULL_NEIGHBOR == n2 && NULL_NEIGHBOR != n3) { LogMe(); Quit(""Tree::ValidateNode, n2=null, n3!=null"", uNodeIndex); } if (NULL_NEIGHBOR == n3 && NULL_NEIGHBOR != n2) { LogMe(); Quit(""Tree::ValidateNode, n3=null, n2!=null"", uNodeIndex); } if (n1 != NULL_NEIGHBOR) AssertAreNeighbors(uNodeIndex, n1); if (n2 != NULL_NEIGHBOR) AssertAreNeighbors(uNodeIndex, n2); if (n3 != NULL_NEIGHBOR) AssertAreNeighbors(uNodeIndex, n3); if (n1 != NULL_NEIGHBOR && (n1 == n2 || n1 == n3)) { LogMe(); Quit(""Tree::ValidateNode, duplicate neighbors in node %u"", uNodeIndex); } if (n2 != NULL_NEIGHBOR && (n2 == n1 || n2 == n3)) { LogMe(); Quit(""Tree::ValidateNode, duplicate neighbors in node %u"", uNodeIndex); } if (n3 != NULL_NEIGHBOR && (n3 == n1 || n3 == n2)) { LogMe(); Quit(""Tree::ValidateNode, duplicate neighbors in node %u"", uNodeIndex); } if (IsRooted()) { if (NULL_NEIGHBOR == GetParent(uNodeIndex)) { if (uNodeIndex != m_uRootNodeIndex) { LogMe(); Quit(""Tree::ValiateNode(%u), no parent"", uNodeIndex); } } else if (GetLeft(GetParent(uNodeIndex)) != uNodeIndex && GetRight(GetParent(uNodeIndex)) != uNodeIndex) { LogMe(); Quit(""Tree::ValidateNode(%u), parent / child mismatch"", uNodeIndex); } } } void Tree::Validate() const { for (unsigned uNodeIndex = 0; uNodeIndex < m_uNodeCount; ++uNodeIndex) ValidateNode(uNodeIndex); } bool Tree::IsEdge(unsigned uNodeIndex1, unsigned uNodeIndex2) const { assert(uNodeIndex1 < m_uNodeCount && uNodeIndex2 < m_uNodeCount); return m_uNeighbor1[uNodeIndex1] == uNodeIndex2 || m_uNeighbor2[uNodeIndex1] == uNodeIndex2 || m_uNeighbor3[uNodeIndex1] == uNodeIndex2; } double Tree::GetEdgeLength(unsigned uNodeIndex1, unsigned uNodeIndex2) const { assert(uNodeIndex1 < m_uNodeCount && uNodeIndex2 < m_uNodeCount); assert(HasEdgeLength(uNodeIndex1, uNodeIndex2)); if (m_uNeighbor1[uNodeIndex1] == uNodeIndex2) return m_dEdgeLength1[uNodeIndex1]; else if (m_uNeighbor2[uNodeIndex1] == uNodeIndex2) return m_dEdgeLength2[uNodeIndex1]; assert(m_uNeighbor3[uNodeIndex1] == uNodeIndex2); return m_dEdgeLength3[uNodeIndex1]; } void Tree::ExpandCache() { const unsigned uNodeCount = 100; unsigned uNewCacheCount = m_uCacheCount + uNodeCount; unsigned *uNewNeighbor1 = new unsigned[uNewCacheCount]; unsigned *uNewNeighbor2 = new unsigned[uNewCacheCount]; unsigned *uNewNeighbor3 = new unsigned[uNewCacheCount]; unsigned *uNewIds = new unsigned[uNewCacheCount]; memset(uNewIds, 0xff, uNewCacheCount*sizeof(unsigned)); double *dNewEdgeLength1 = new double[uNewCacheCount]; double *dNewEdgeLength2 = new double[uNewCacheCount]; double *dNewEdgeLength3 = new double[uNewCacheCount]; double *dNewHeight = new double[uNewCacheCount]; bool *bNewHasEdgeLength1 = new bool[uNewCacheCount]; bool *bNewHasEdgeLength2 = new bool[uNewCacheCount]; bool *bNewHasEdgeLength3 = new bool[uNewCacheCount]; bool *bNewHasHeight = new bool[uNewCacheCount]; char **ptrNewName = new char *[uNewCacheCount]; memset(ptrNewName, 0, uNewCacheCount*sizeof(char *)); if (m_uCacheCount > 0) { const unsigned uUnsignedBytes = m_uCacheCount*sizeof(unsigned); memcpy(uNewNeighbor1, m_uNeighbor1, uUnsignedBytes); memcpy(uNewNeighbor2, m_uNeighbor2, uUnsignedBytes); memcpy(uNewNeighbor3, m_uNeighbor3, uUnsignedBytes); memcpy(uNewIds, m_Ids, uUnsignedBytes); const unsigned uEdgeBytes = m_uCacheCount*sizeof(double); memcpy(dNewEdgeLength1, m_dEdgeLength1, uEdgeBytes); memcpy(dNewEdgeLength2, m_dEdgeLength2, uEdgeBytes); memcpy(dNewEdgeLength3, m_dEdgeLength3, uEdgeBytes); memcpy(dNewHeight, m_dHeight, uEdgeBytes); const unsigned uBoolBytes = m_uCacheCount*sizeof(bool); memcpy(bNewHasEdgeLength1, m_bHasEdgeLength1, uBoolBytes); memcpy(bNewHasEdgeLength2, m_bHasEdgeLength1, uBoolBytes); memcpy(bNewHasEdgeLength3, m_bHasEdgeLength1, uBoolBytes); memcpy(bNewHasHeight, m_bHasHeight, uBoolBytes); const unsigned uNameBytes = m_uCacheCount*sizeof(char *); memcpy(ptrNewName, m_ptrName, uNameBytes); delete[] m_uNeighbor1; delete[] m_uNeighbor2; delete[] m_uNeighbor3; delete[] m_Ids; delete[] m_dEdgeLength1; delete[] m_dEdgeLength2; delete[] m_dEdgeLength3; delete[] m_bHasEdgeLength1; delete[] m_bHasEdgeLength2; delete[] m_bHasEdgeLength3; delete[] m_bHasHeight; delete[] m_ptrName; } m_uCacheCount = uNewCacheCount; m_uNeighbor1 = uNewNeighbor1; m_uNeighbor2 = uNewNeighbor2; m_uNeighbor3 = uNewNeighbor3; m_Ids = uNewIds; m_dEdgeLength1 = dNewEdgeLength1; m_dEdgeLength2 = dNewEdgeLength2; m_dEdgeLength3 = dNewEdgeLength3; m_dHeight = dNewHeight; m_bHasEdgeLength1 = bNewHasEdgeLength1; m_bHasEdgeLength2 = bNewHasEdgeLength2; m_bHasEdgeLength3 = bNewHasEdgeLength3; m_bHasHeight = bNewHasHeight; m_ptrName = ptrNewName; } // Creates tree with single node, no edges. // Root node always has index 0. void Tree::CreateRooted() { Clear(); ExpandCache(); m_uNodeCount = 1; m_uNeighbor1[0] = NULL_NEIGHBOR; m_uNeighbor2[0] = NULL_NEIGHBOR; m_uNeighbor3[0] = NULL_NEIGHBOR; m_bHasEdgeLength1[0] = false; m_bHasEdgeLength2[0] = false; m_bHasEdgeLength3[0] = false; m_bHasHeight[0] = false; m_uRootNodeIndex = 0; m_bRooted = true; #if DEBUG Validate(); #endif } // Creates unrooted tree with single edge. // Nodes for that edge are always 0 and 1. void Tree::CreateUnrooted(double dEdgeLength) { Clear(); ExpandCache(); m_uNeighbor1[0] = 1; m_uNeighbor2[0] = NULL_NEIGHBOR; m_uNeighbor3[0] = NULL_NEIGHBOR; m_uNeighbor1[1] = 0; m_uNeighbor2[1] = NULL_NEIGHBOR; m_uNeighbor3[1] = NULL_NEIGHBOR; m_dEdgeLength1[0] = dEdgeLength; m_dEdgeLength1[1] = dEdgeLength; m_bHasEdgeLength1[0] = true; m_bHasEdgeLength1[1] = true; m_bRooted = false; #if DEBUG Validate(); #endif } void Tree::SetLeafName(unsigned uNodeIndex, const char *ptrName) { assert(uNodeIndex < m_uNodeCount); assert(IsLeaf(uNodeIndex)); free(m_ptrName[uNodeIndex]); m_ptrName[uNodeIndex] = strsave(ptrName); } void Tree::SetLeafId(unsigned uNodeIndex, unsigned uId) { assert(uNodeIndex < m_uNodeCount); assert(IsLeaf(uNodeIndex)); m_Ids[uNodeIndex] = uId; } const char *Tree::GetLeafName(unsigned uNodeIndex) const { assert(uNodeIndex < m_uNodeCount); assert(IsLeaf(uNodeIndex)); return m_ptrName[uNodeIndex]; } unsigned Tree::GetLeafId(unsigned uNodeIndex) const { assert(uNodeIndex < m_uNodeCount); assert(IsLeaf(uNodeIndex)); return m_Ids[uNodeIndex]; } // Append a new branch. // This adds two new nodes and joins them to an existing leaf node. // Return value is k, new nodes have indexes k and k+1 respectively. unsigned Tree::AppendBranch(unsigned uExistingLeafIndex) { if (0 == m_uNodeCount) Quit(""Tree::AppendBranch: tree has not been created""); #if DEBUG assert(uExistingLeafIndex < m_uNodeCount); if (!IsLeaf(uExistingLeafIndex)) { LogMe(); Quit(""AppendBranch(%u): not leaf"", uExistingLeafIndex); } #endif if (m_uNodeCount >= m_uCacheCount - 2) ExpandCache(); const unsigned uNewLeaf1 = m_uNodeCount; const unsigned uNewLeaf2 = m_uNodeCount + 1; m_uNodeCount += 2; assert(m_uNeighbor2[uExistingLeafIndex] == NULL_NEIGHBOR); assert(m_uNeighbor3[uExistingLeafIndex] == NULL_NEIGHBOR); m_uNeighbor2[uExistingLeafIndex] = uNewLeaf1; m_uNeighbor3[uExistingLeafIndex] = uNewLeaf2; m_uNeighbor1[uNewLeaf1] = uExistingLeafIndex; m_uNeighbor1[uNewLeaf2] = uExistingLeafIndex; m_uNeighbor2[uNewLeaf1] = NULL_NEIGHBOR; m_uNeighbor2[uNewLeaf2] = NULL_NEIGHBOR; m_uNeighbor3[uNewLeaf1] = NULL_NEIGHBOR; m_uNeighbor3[uNewLeaf2] = NULL_NEIGHBOR; m_dEdgeLength2[uExistingLeafIndex] = 0; m_dEdgeLength3[uExistingLeafIndex] = 0; m_dEdgeLength1[uNewLeaf1] = 0; m_dEdgeLength2[uNewLeaf1] = 0; m_dEdgeLength3[uNewLeaf1] = 0; m_dEdgeLength1[uNewLeaf2] = 0; m_dEdgeLength2[uNewLeaf2] = 0; m_dEdgeLength3[uNewLeaf2] = 0; m_bHasEdgeLength1[uNewLeaf1] = false; m_bHasEdgeLength2[uNewLeaf1] = false; m_bHasEdgeLength3[uNewLeaf1] = false; m_bHasEdgeLength1[uNewLeaf2] = false; m_bHasEdgeLength2[uNewLeaf2] = false; m_bHasEdgeLength3[uNewLeaf2] = false; m_bHasHeight[uNewLeaf1] = false; m_bHasHeight[uNewLeaf2] = false; return uNewLeaf1; } void Tree::LogMe() const { Log(""Tree::LogMe %u nodes, "", m_uNodeCount); if (IsRooted()) { Log(""rooted.\n""); Log(""\n""); Log(""Index Parnt LengthP Left LengthL Right LengthR Name\n""); Log(""----- ----- ------- ---- ------- ----- ------- ----\n""); } else { Log(""unrooted.\n""); Log(""\n""); Log(""Index Nbr_1 Length1 Nbr_2 Length2 Nbr_3 Length3 Name\n""); Log(""----- ----- ------- ----- ------- ----- ------- ----\n""); } for (unsigned uNodeIndex = 0; uNodeIndex < m_uNodeCount; ++uNodeIndex) { Log(""%5u "", uNodeIndex); const unsigned n1 = m_uNeighbor1[uNodeIndex]; const unsigned n2 = m_uNeighbor2[uNodeIndex]; const unsigned n3 = m_uNeighbor3[uNodeIndex]; if (NULL_NEIGHBOR != n1) Log(""%5u %7.3g "", n1, m_dEdgeLength1[uNodeIndex]); else Log("" ""); if (NULL_NEIGHBOR != n2) Log(""%5u %7.3g "", n2, m_dEdgeLength2[uNodeIndex]); else Log("" ""); if (NULL_NEIGHBOR != n3) Log(""%5u %7.3g "", n3, m_dEdgeLength3[uNodeIndex]); else Log("" ""); if (m_bRooted && uNodeIndex == m_uRootNodeIndex) Log(""[ROOT] ""); const char *ptrName = m_ptrName[uNodeIndex]; if (ptrName != 0) Log(""%s"", ptrName); Log(""\n""); } } void Tree::SetEdgeLength(unsigned uNodeIndex1, unsigned uNodeIndex2, double dLength) { assert(uNodeIndex1 < m_uNodeCount && uNodeIndex2 < m_uNodeCount); assert(IsEdge(uNodeIndex1, uNodeIndex2)); if (m_uNeighbor1[uNodeIndex1] == uNodeIndex2) { m_dEdgeLength1[uNodeIndex1] = dLength; m_bHasEdgeLength1[uNodeIndex1] = true; } else if (m_uNeighbor2[uNodeIndex1] == uNodeIndex2) { m_dEdgeLength2[uNodeIndex1] = dLength; m_bHasEdgeLength2[uNodeIndex1] = true; } else { assert(m_uNeighbor3[uNodeIndex1] == uNodeIndex2); m_dEdgeLength3[uNodeIndex1] = dLength; m_bHasEdgeLength3[uNodeIndex1] = true; } if (m_uNeighbor1[uNodeIndex2] == uNodeIndex1) { m_dEdgeLength1[uNodeIndex2] = dLength; m_bHasEdgeLength1[uNodeIndex2] = true; } else if (m_uNeighbor2[uNodeIndex2] == uNodeIndex1) { m_dEdgeLength2[uNodeIndex2] = dLength; m_bHasEdgeLength2[uNodeIndex2] = true; } else { assert(m_uNeighbor3[uNodeIndex2] == uNodeIndex1); m_dEdgeLength3[uNodeIndex2] = dLength; m_bHasEdgeLength3[uNodeIndex2] = true; } } unsigned Tree::UnrootFromFile() { #if TRACE Log(""Before unroot:\n""); LogMe(); #endif if (!m_bRooted) Quit(""Tree::Unroot, not rooted""); // Convention: root node is always node zero assert(IsRoot(0)); assert(NULL_NEIGHBOR == m_uNeighbor1[0]); const unsigned uThirdNode = m_uNodeCount++; m_uNeighbor1[0] = uThirdNode; m_uNeighbor1[uThirdNode] = 0; m_uNeighbor2[uThirdNode] = NULL_NEIGHBOR; m_uNeighbor3[uThirdNode] = NULL_NEIGHBOR; m_dEdgeLength1[0] = 0; m_dEdgeLength1[uThirdNode] = 0; m_bHasEdgeLength1[uThirdNode] = true; m_bRooted = false; #if TRACE Log(""After unroot:\n""); LogMe(); #endif return uThirdNode; } // In an unrooted tree, equivalent of GetLeft/Right is // GetFirst/SecondNeighbor. // uNeighborIndex must be a known neighbor of uNodeIndex. // This is the way to find the other two neighbor nodes of // an internal node. // The labeling as ""First"" and ""Second"" neighbor is arbitrary. // Calling these functions on a leaf returns NULL_NEIGHBOR, as // for GetLeft/Right. unsigned Tree::GetFirstNeighbor(unsigned uNodeIndex, unsigned uNeighborIndex) const { assert(uNodeIndex < m_uNodeCount); assert(uNeighborIndex < m_uNodeCount); assert(IsEdge(uNodeIndex, uNeighborIndex)); for (unsigned n = 0; n < 3; ++n) { unsigned uNeighbor = GetNeighbor(uNodeIndex, n); if (NULL_NEIGHBOR != uNeighbor && uNeighborIndex != uNeighbor) return uNeighbor; } return NULL_NEIGHBOR; } unsigned Tree::GetSecondNeighbor(unsigned uNodeIndex, unsigned uNeighborIndex) const { assert(uNodeIndex < m_uNodeCount); assert(uNeighborIndex < m_uNodeCount); assert(IsEdge(uNodeIndex, uNeighborIndex)); bool bFoundOne = false; for (unsigned n = 0; n < 3; ++n) { unsigned uNeighbor = GetNeighbor(uNodeIndex, n); if (NULL_NEIGHBOR != uNeighbor && uNeighborIndex != uNeighbor) { if (bFoundOne) return uNeighbor; else bFoundOne = true; } } return NULL_NEIGHBOR; } // Compute the number of leaves in the sub-tree defined by an edge // in an unrooted tree. Conceptually, the tree is cut at this edge, // and uNodeIndex2 considered the root of the sub-tree. unsigned Tree::GetLeafCountUnrooted(unsigned uNodeIndex1, unsigned uNodeIndex2, double *ptrdTotalDistance) const { assert(!IsRooted()); if (IsLeaf(uNodeIndex2)) { *ptrdTotalDistance = GetEdgeLength(uNodeIndex1, uNodeIndex2); return 1; } // Recurse down the rooted sub-tree defined by cutting the edge // and considering uNodeIndex2 as the root. const unsigned uLeft = GetFirstNeighbor(uNodeIndex2, uNodeIndex1); const unsigned uRight = GetSecondNeighbor(uNodeIndex2, uNodeIndex1); double dLeftDistance; double dRightDistance; const unsigned uLeftCount = GetLeafCountUnrooted(uNodeIndex2, uLeft, &dLeftDistance); const unsigned uRightCount = GetLeafCountUnrooted(uNodeIndex2, uRight, &dRightDistance); *ptrdTotalDistance = dLeftDistance + dRightDistance; return uLeftCount + uRightCount; } bool Tree::HasEdgeLength(unsigned uNodeIndex1, unsigned uNodeIndex2) const { assert(uNodeIndex1 < m_uNodeCount); assert(uNodeIndex2 < m_uNodeCount); assert(IsEdge(uNodeIndex1, uNodeIndex2)); if (m_uNeighbor1[uNodeIndex1] == uNodeIndex2) return m_bHasEdgeLength1[uNodeIndex1]; else if (m_uNeighbor2[uNodeIndex1] == uNodeIndex2) return m_bHasEdgeLength2[uNodeIndex1]; assert(m_uNeighbor3[uNodeIndex1] == uNodeIndex2); return m_bHasEdgeLength3[uNodeIndex1]; } void Tree::OrientParent(unsigned uNodeIndex, unsigned uParentNodeIndex) { if (NULL_NEIGHBOR == uNodeIndex) return; if (m_uNeighbor1[uNodeIndex] == uParentNodeIndex) ; else if (m_uNeighbor2[uNodeIndex] == uParentNodeIndex) { double dEdgeLength2 = m_dEdgeLength2[uNodeIndex]; m_uNeighbor2[uNodeIndex] = m_uNeighbor1[uNodeIndex]; m_dEdgeLength2[uNodeIndex] = m_dEdgeLength1[uNodeIndex]; m_uNeighbor1[uNodeIndex] = uParentNodeIndex; m_dEdgeLength1[uNodeIndex] = dEdgeLength2; } else { assert(m_uNeighbor3[uNodeIndex] == uParentNodeIndex); double dEdgeLength3 = m_dEdgeLength3[uNodeIndex]; m_uNeighbor3[uNodeIndex] = m_uNeighbor1[uNodeIndex]; m_dEdgeLength3[uNodeIndex] = m_dEdgeLength1[uNodeIndex]; m_uNeighbor1[uNodeIndex] = uParentNodeIndex; m_dEdgeLength1[uNodeIndex] = dEdgeLength3; } OrientParent(m_uNeighbor2[uNodeIndex], uNodeIndex); OrientParent(m_uNeighbor3[uNodeIndex], uNodeIndex); } unsigned Tree::FirstDepthFirstNode() const { assert(IsRooted()); // Descend via left branches until we hit a leaf unsigned uNodeIndex = m_uRootNodeIndex; while (!IsLeaf(uNodeIndex)) uNodeIndex = GetLeft(uNodeIndex); return uNodeIndex; } unsigned Tree::FirstDepthFirstNodeR() const { assert(IsRooted()); // Descend via left branches until we hit a leaf unsigned uNodeIndex = m_uRootNodeIndex; while (!IsLeaf(uNodeIndex)) uNodeIndex = GetRight(uNodeIndex); return uNodeIndex; } unsigned Tree::NextDepthFirstNode(unsigned uNodeIndex) const { #if TRACE Log(""NextDepthFirstNode(%3u) "", uNodeIndex); #endif assert(IsRooted()); assert(uNodeIndex < m_uNodeCount); if (IsRoot(uNodeIndex)) { #if TRACE Log("">> Node %u is root, end of traversal\n"", uNodeIndex); #endif return NULL_NEIGHBOR; } unsigned uParent = GetParent(uNodeIndex); if (GetRight(uParent) == uNodeIndex) { #if TRACE Log("">> Is right branch, return parent=%u\n"", uParent); #endif return uParent; } uNodeIndex = GetRight(uParent); #if TRACE Log("">> Descend left from right sibling=%u ... "", uNodeIndex); #endif while (!IsLeaf(uNodeIndex)) uNodeIndex = GetLeft(uNodeIndex); #if TRACE Log(""bottom out at leaf=%u\n"", uNodeIndex); #endif return uNodeIndex; } unsigned Tree::NextDepthFirstNodeR(unsigned uNodeIndex) const { #if TRACE Log(""NextDepthFirstNode(%3u) "", uNodeIndex); #endif assert(IsRooted()); assert(uNodeIndex < m_uNodeCount); if (IsRoot(uNodeIndex)) { #if TRACE Log("">> Node %u is root, end of traversal\n"", uNodeIndex); #endif return NULL_NEIGHBOR; } unsigned uParent = GetParent(uNodeIndex); if (GetLeft(uParent) == uNodeIndex) { #if TRACE Log("">> Is left branch, return parent=%u\n"", uParent); #endif return uParent; } uNodeIndex = GetLeft(uParent); #if TRACE Log("">> Descend right from left sibling=%u ... "", uNodeIndex); #endif while (!IsLeaf(uNodeIndex)) uNodeIndex = GetRight(uNodeIndex); #if TRACE Log(""bottom out at leaf=%u\n"", uNodeIndex); #endif return uNodeIndex; } void Tree::UnrootByDeletingRoot() { assert(IsRooted()); assert(m_uNodeCount >= 3); const unsigned uLeft = GetLeft(m_uRootNodeIndex); const unsigned uRight = GetRight(m_uRootNodeIndex); m_uNeighbor1[uLeft] = uRight; m_uNeighbor1[uRight] = uLeft; bool bHasEdgeLength = HasEdgeLength(m_uRootNodeIndex, uLeft) && HasEdgeLength(m_uRootNodeIndex, uRight); if (bHasEdgeLength) { double dEdgeLength = GetEdgeLength(m_uRootNodeIndex, uLeft) + GetEdgeLength(m_uRootNodeIndex, uRight); m_dEdgeLength1[uLeft] = dEdgeLength; m_dEdgeLength1[uRight] = dEdgeLength; } // Remove root node entry from arrays const unsigned uMoveCount = m_uNodeCount - m_uRootNodeIndex; const unsigned uUnsBytes = uMoveCount*sizeof(unsigned); memmove(m_uNeighbor1 + m_uRootNodeIndex, m_uNeighbor1 + m_uRootNodeIndex + 1, uUnsBytes); memmove(m_uNeighbor2 + m_uRootNodeIndex, m_uNeighbor2 + m_uRootNodeIndex + 1, uUnsBytes); memmove(m_uNeighbor3 + m_uRootNodeIndex, m_uNeighbor3 + m_uRootNodeIndex + 1, uUnsBytes); const unsigned uDoubleBytes = uMoveCount*sizeof(double); memmove(m_dEdgeLength1 + m_uRootNodeIndex, m_dEdgeLength1 + m_uRootNodeIndex + 1, uDoubleBytes); memmove(m_dEdgeLength2 + m_uRootNodeIndex, m_dEdgeLength2 + m_uRootNodeIndex + 1, uDoubleBytes); memmove(m_dEdgeLength3 + m_uRootNodeIndex, m_dEdgeLength3 + m_uRootNodeIndex + 1, uDoubleBytes); const unsigned uBoolBytes = uMoveCount*sizeof(bool); memmove(m_bHasEdgeLength1 + m_uRootNodeIndex, m_bHasEdgeLength1 + m_uRootNodeIndex + 1, uBoolBytes); memmove(m_bHasEdgeLength2 + m_uRootNodeIndex, m_bHasEdgeLength2 + m_uRootNodeIndex + 1, uBoolBytes); memmove(m_bHasEdgeLength3 + m_uRootNodeIndex, m_bHasEdgeLength3 + m_uRootNodeIndex + 1, uBoolBytes); const unsigned uPtrBytes = uMoveCount*sizeof(char *); memmove(m_ptrName + m_uRootNodeIndex, m_ptrName + m_uRootNodeIndex + 1, uPtrBytes); --m_uNodeCount; m_bRooted = false; // Fix up table entries for (unsigned uNodeIndex = 0; uNodeIndex < m_uNodeCount; ++uNodeIndex) { #define DEC(x) if (x != NULL_NEIGHBOR && x > m_uRootNodeIndex) --x; DEC(m_uNeighbor1[uNodeIndex]) DEC(m_uNeighbor2[uNodeIndex]) DEC(m_uNeighbor3[uNodeIndex]) #undef DEC } Validate(); } unsigned Tree::GetLeafParent(unsigned uNodeIndex) const { assert(IsLeaf(uNodeIndex)); if (IsRooted()) return GetParent(uNodeIndex); if (m_uNeighbor1[uNodeIndex] != NULL_NEIGHBOR) return m_uNeighbor1[uNodeIndex]; if (m_uNeighbor2[uNodeIndex] != NULL_NEIGHBOR) return m_uNeighbor2[uNodeIndex]; return m_uNeighbor3[uNodeIndex]; } // TODO: This is not efficient for large trees, should cache. double Tree::GetNodeHeight(unsigned uNodeIndex) const { if (!IsRooted()) Quit(""Tree::GetNodeHeight: undefined unless rooted tree""); if (IsLeaf(uNodeIndex)) return 0.0; if (m_bHasHeight[uNodeIndex]) return m_dHeight[uNodeIndex]; const unsigned uLeft = GetLeft(uNodeIndex); const unsigned uRight = GetRight(uNodeIndex); double dLeftLength = GetEdgeLength(uNodeIndex, uLeft); double dRightLength = GetEdgeLength(uNodeIndex, uRight); if (dLeftLength < 0) dLeftLength = 0; if (dRightLength < 0) dRightLength = 0; const double dLeftHeight = dLeftLength + GetNodeHeight(uLeft); const double dRightHeight = dRightLength + GetNodeHeight(uRight); const double dHeight = (dLeftHeight + dRightHeight)/2; m_bHasHeight[uNodeIndex] = true; m_dHeight[uNodeIndex] = dHeight; return dHeight; } unsigned Tree::GetNeighborSubscript(unsigned uNodeIndex, unsigned uNeighborIndex) const { assert(uNodeIndex < m_uNodeCount); assert(uNeighborIndex < m_uNodeCount); if (uNeighborIndex == m_uNeighbor1[uNodeIndex]) return 0; if (uNeighborIndex == m_uNeighbor2[uNodeIndex]) return 1; if (uNeighborIndex == m_uNeighbor3[uNodeIndex]) return 2; return NULL_NEIGHBOR; } unsigned Tree::GetNeighbor(unsigned uNodeIndex, unsigned uNeighborSubscript) const { switch (uNeighborSubscript) { case 0: return m_uNeighbor1[uNodeIndex]; case 1: return m_uNeighbor2[uNodeIndex]; case 2: return m_uNeighbor3[uNodeIndex]; } Quit(""Tree::GetNeighbor, sub=%u"", uNeighborSubscript); return NULL_NEIGHBOR; } // TODO: check if this is a performance issue, could cache a lookup table unsigned Tree::LeafIndexToNodeIndex(unsigned uLeafIndex) const { const unsigned uNodeCount = GetNodeCount(); unsigned uLeafCount = 0; for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex) { if (IsLeaf(uNodeIndex)) { if (uLeafCount == uLeafIndex) return uNodeIndex; else ++uLeafCount; } } Quit(""LeafIndexToNodeIndex: out of range""); return 0; } unsigned Tree::GetLeafNodeIndex(const char *ptrName) const { const unsigned uNodeCount = GetNodeCount(); for (unsigned uNodeIndex = 0; uNodeIndex < uNodeCount; ++uNodeIndex) { if (!IsLeaf(uNodeIndex)) continue; const char *ptrLeafName = GetLeafName(uNodeIndex); if (0 == strcmp(ptrName, ptrLeafName)) return uNodeIndex; } Quit(""Tree::GetLeafNodeIndex, name not found""); return 0; } // Create rooted tree from a vector description. // Node indexes are 0..N-1 for leaves, N..2N-2 for // internal nodes. // Vector subscripts are i-N and have values for // internal nodes only, but those values are node // indexes 0..2N-2. So e.g. if N=6 and Left[2]=1, // this means that the third internal node (node index 8) // has the second leaf (node index 1) as its left child. // uRoot gives the vector subscript of the root, so add N // to get the node index. void Tree::Create(unsigned uLeafCount, unsigned uRoot, const unsigned Left[], const unsigned Right[], const float LeftLength[], const float RightLength[], const unsigned LeafIds[], char **LeafNames) { Clear(); m_uNodeCount = 2*uLeafCount - 1; InitCache(m_uNodeCount); for (unsigned uNodeIndex = 0; uNodeIndex < uLeafCount; ++uNodeIndex) { m_Ids[uNodeIndex] = LeafIds[uNodeIndex]; m_ptrName[uNodeIndex] = strsave(LeafNames[uNodeIndex]); } for (unsigned uNodeIndex = uLeafCount; uNodeIndex < m_uNodeCount; ++uNodeIndex) { unsigned v = uNodeIndex - uLeafCount; unsigned uLeft = Left[v]; unsigned uRight = Right[v]; float fLeft = LeftLength[v]; float fRight = RightLength[v]; m_uNeighbor2[uNodeIndex] = uLeft; m_uNeighbor3[uNodeIndex] = uRight; m_bHasEdgeLength2[uNodeIndex] = true; m_bHasEdgeLength3[uNodeIndex] = true; m_dEdgeLength2[uNodeIndex] = fLeft; m_dEdgeLength3[uNodeIndex] = fRight; m_uNeighbor1[uLeft] = uNodeIndex; m_uNeighbor1[uRight] = uNodeIndex; m_dEdgeLength1[uLeft] = fLeft; m_dEdgeLength1[uRight] = fRight; m_bHasEdgeLength1[uLeft] = true; m_bHasEdgeLength1[uRight] = true; } m_bRooted = true; m_uRootNodeIndex = uRoot + uLeafCount; Validate(); } static void GetLeavesRecurse(const Tree &tree, unsigned uNodeIndex, unsigned Leaves[], unsigned &uLeafCount /* in-out */) { if (tree.IsLeaf(uNodeIndex)) { Leaves[uLeafCount] = uNodeIndex; ++uLeafCount; return; } const unsigned uLeft = tree.GetLeft(uNodeIndex); const unsigned uRight = tree.GetRight(uNodeIndex); GetLeavesRecurse(tree, uLeft, Leaves, uLeafCount); GetLeavesRecurse(tree, uRight, Leaves, uLeafCount); } void GetLeaves(const Tree &tree, unsigned uNodeIndex, unsigned Leaves[], unsigned *ptruLeafCount) { unsigned uLeafCount = 0; GetLeavesRecurse(tree, uNodeIndex, Leaves, uLeafCount); *ptruLeafCount = uLeafCount; } void Tree::InitCache(unsigned uCacheCount) { m_uCacheCount = uCacheCount; m_uNeighbor1 = new unsigned[m_uCacheCount]; m_uNeighbor2 = new unsigned[m_uCacheCount]; m_uNeighbor3 = new unsigned[m_uCacheCount]; m_Ids = new unsigned[m_uCacheCount]; m_dEdgeLength1 = new double[m_uCacheCount]; m_dEdgeLength2 = new double[m_uCacheCount]; m_dEdgeLength3 = new double[m_uCacheCount]; m_dHeight = new double[m_uCacheCount]; m_bHasEdgeLength1 = new bool[m_uCacheCount]; m_bHasEdgeLength2 = new bool[m_uCacheCount]; m_bHasEdgeLength3 = new bool[m_uCacheCount]; m_bHasHeight = new bool[m_uCacheCount]; m_ptrName = new char *[m_uCacheCount]; for (unsigned uNodeIndex = 0; uNodeIndex < m_uNodeCount; ++uNodeIndex) { m_uNeighbor1[uNodeIndex] = NULL_NEIGHBOR; m_uNeighbor2[uNodeIndex] = NULL_NEIGHBOR; m_uNeighbor3[uNodeIndex] = NULL_NEIGHBOR; m_bHasEdgeLength1[uNodeIndex] = false; m_bHasEdgeLength2[uNodeIndex] = false; m_bHasEdgeLength3[uNodeIndex] = false; m_bHasHeight[uNodeIndex] = false; m_dEdgeLength1[uNodeIndex] = dInsane; m_dEdgeLength2[uNodeIndex] = dInsane; m_dEdgeLength3[uNodeIndex] = dInsane; m_dHeight[uNodeIndex] = dInsane; m_ptrName[uNodeIndex] = 0; m_Ids[uNodeIndex] = uInsane; } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/pilercr.h",".h","9374","288","#ifdef _MSC_VER #pragma warning(disable: 4996) // deprecated functions #define _CRT_SECURE_NO_DEPRECATE 1 #endif #include #include #include #include #include #include #include #include #include ""myassert.h"" #define PILERCR_LONG_VERSION ""pilercr v1.06"" #if _MSC_VER #pragma warning(disable:4800) // don't warn about bool->int conversion #endif #ifdef _DEBUG #define DEBUG 1 #endif #if !defined(DEBUG) && !defined(NDEBUG) #define NDEBUG 1 #endif #ifdef WIN32 #define FILEIO_BINARY_MODE 1 #else #define FILEIO_BINARY_MODE 0 #define stricmp strcasecmp #define strnicmp strncasecmp #endif #include ""types.h"" #include ""progress.h"" #include ""params.h"" #include ""intlist.h"" #include ""utils.h"" #include ""multaln.h"" struct RowData { int RepeatLo; int RepeatLength; double PctId; }; typedef std::vector StrVec; struct ArrayAln { int Id; int Pos; // of first repeat Seq ConsSeq; Seq AlignedConsSeq; bool ClusterRevComp; StrVec LeftFlanks; StrVec Repeats; StrVec Spacers; }; struct ArrayData { int Id; int Lo; int ArrayLength; int RepeatLength; int SpacerLength; IntVec PileIndexes; Seq ConsSeq; Seq AlignedConsSeq; bool ClusterRevComp; ArrayAln *AA; }; const int CONTIG_MAP_BIN_SIZE = 32; const int MAX_CONTIGS = 1024*1024; extern FILE *fDiscardedHits; extern FILE *fPiles; extern FILE *g_fOut; extern std::vector g_Piles; extern int g_PileCount; extern std::vector g_Images; extern int g_ImageCount; extern IntVec g_HitIndexToPileIndexA; extern IntVec g_HitIndexToPileIndexB; extern std::vector g_Hits; extern int g_HitCount; extern char *g_SeqQ; extern int k; extern int CharToLetter[256]; extern bool Banded; extern int g_Diameter; extern int SeqLengthQ; extern ContigData *ContigsQ; extern int *ContigMapQ; extern int ContigCountQ; extern unsigned g_DiscardedHitCount; extern unsigned g_AcceptedHitCount; extern unsigned g_NotAcceptedHitCount; int pow4(int n); double pow4d(int n); double log4(double x); void SetLog(); void Usage(); void Credits(); int GetElapsedSecs(); FILE *OpenStdioFile(const char *FileName, FILEIO_MODE Mode = FILEIO_MODE_ReadOnly); int GetFileSize(FILE *f); void ProcessArgVect(int argc, char *argv[]); const char *ValueOpt(const char *Name); void IntOpt(const char *Name, int *ptrValue); void FloatOpt(const char *Name, double *ptrValue); const char *RequiredValueOpt(const char *Name); bool FlagOpt(const char *Name); void CommandLineError(const char *Format, ...); char *ReadMFA(const char FileName[], int *ptrLength, ContigData **ptrContigs, int *ptrContigCount, int **ptrContigMap); void MakeContigMap(const ContigData *Contigs, int ContigCount, int **ptrMap); void Complement(char *seq, int len); void LogContigs(const ContigData *Contigs, int ContigCount); double GetRAMSize(); int MinWordsPerFilterHit(int HitLength, int WordLength, int MaxErrors); void GetParams(int SeqLengthQ, int g_Diameter, int Length, double MinId, FilterParams *ptrFP, DPParams *ptrDP); double TotalMemRequired(int SeqLengthQ, const FilterParams &FP); double AvgIndexListLength(int SeqLengthT, const FilterParams &FP); void SaveFilterHit(int QFrom, int QTo, int DiagIndex); void WriteDPHits(FILE *f, bool Comp); void SetContigs(ContigData *ContigsT, ContigData *ContigsQ, int ContigCountT, int ContigCountQ, int *ContigMapT, int *ContigMapQ); int GetFilterHitCount(); int GetFilterHitCountComp(); void Filter(int Tlen_, char *B_, int Qlen_, bool Self, bool Comp, const int *Finger, const int *Pos, const FilterParams &FP); void FilterB(char *B_, int Qlen_, const FilterParams &FP); void SetFilterOutFile(FILE *f); void SetFilterOutFileComp(FILE *f); FilterHit *ReadFilterHits(FILE *f, int Count); void CloseFilterOutFile(); void CloseFilterOutFileComp(); Trapezoid *MergeFilterHits(const char *SeqT, int SeqLengthT, const char *SeqQ, int SeqLengthQ, bool Self, const FilterHit *FilterHits, int FilterHitCount, const FilterParams &FP, int *ptrTrapCount); void AlignTraps(char *A, int Alen, char *B, int Blen, Trapezoid *Traps, int TrapCount, int comp, const DPParams &DP); int SumTrapLengths(const Trapezoid *Traps); int SumDPLengths(const DPHit *Hits, int HitCount); int StringToCode(const char s[], int len); char *CodeToString(int code, int len); void MakeIndex(char *S, int Slen, int **ptrFinger, int **ptrPos); void CheckIndex(char *S, int Slen, const int Finger[], const int Pos[]); void FreeIndex(int Finger[], int Pos[]); // Memory wrappers. // Macro hacks, but makes code more readable // by hiding cast and sizeof. #define all(t, n) (t *) allocmem((n)*sizeof(t)) #define zero(p, t, n) memset(p, 0, (n)*sizeof(t)) void *allocmem(int bytes); void freemem(void *p); unsigned GetPeakMemUseBytes(); unsigned GetMemUseBytes(); int RevCompKmer(int Kmer); int GetKmersInWindow(); void *ckalloc(int size, const char *where); void *ckrealloc(void *p, int size, const char *where); void PILERCR(); bool AcceptHit(const DPHit &Hit); void WriteDPHit(FILE *f, const DPHit &Hit, bool Comp, const char *Annot = """"); void FindArrays(const CompData &Comp, std::vector &ADVec); double GetRatio(int x, int y); int GetHitLength(const DPHit &Hit); int GetHitLength(const PileData &Pile); int GetSpacerLength(const DPHit &Hit); int GetSpacerLength(const PileData &Pile1, const PileData &Pile2); int GetOverlap(unsigned lo1, unsigned hi1, unsigned lo2, unsigned hi2); inline int iabs(int x) { return x >= 0 ? x : -x; } int GlobalToLocal(int Pos, char **ptrLabel); int GlobalPosToContigIndex(int Pos); void FindPiles(); const ContigData &GlobalPosToContig(int Pos); bool GetArrayData(const IntVec &ArrayPileIndexes, ArrayData &AD); void ClusterCons(const std::vector &ADVec, IntVecVec &Clusters); void ClusterConsRC(std::vector &AAVec, IntVecVec &Clusters); void OutArrays(std::vector &AAVec); void AlignCluster(std::vector &AAVec, const IntVec &Cluster, Seq &ConsSymbols); void OutputArrayDetail(ArrayData &AD); void WriteArrays(FILE *f, const std::vector &ADVec); void PileToSeq(const std::vector &Piles, int PileIndex, Seq &s, int *ptrPosLo, int *ptrPosHi); void OutLocalAln(const char *A, unsigned LA, const char *B, unsigned LB, unsigned StartA, unsigned StartB, const char *Path_); void LinkPiles(); int GetPileLength(const PileData &Pile); int GetSpacerLength(const PileData &Pile1, const PileData &Pile2); void DeletePile(int PileIndex); void LogPile(int PileIndex); void LogHit(const DPHit &Hit); void LogHit(int HitIndex); void LinkHits(); const ImageData &GetImage(int ImageIndex); const DPHit &GetHit(int HitIndex); const PileData &GetPile(int PileIndex); PileData &GetModifiablePile(int PileIndex); DPHit &GetModifiableHit(int HitIndex); int GetHitLength(int ImageIndex); int GetSpacerLengthFromImage(int ImageIndex); int GetOverlap(const ImageData &Image1, const ImageData &Image2); void HitsToImages(); void ExtendArray(IntVec &ArrayHitIndexes); void GetBestArray(const IntVecVec &Arrays, IntVec &ArrayPileIndexes); bool Cmp_Lo(const DPHit &Hit1, const DPHit &Hit2); bool Cmp_Hi(const DPHit &Hit1, const DPHit &Hit2); int GetBestLink(int FromHitIndex, const IntVec &Links); void GetSubseq(int Lo, int Hi, Seq &s); void LogHits(); void WritePiles(); void LogImage(const ImageData &Image); bool IsDeletedHit(int HitIndex); void DeleteHit(int HitIndex); void SaveTraps(const Trapezoid *Traps); void SaveFilterHits(const FilterHit *FHits, int FHitCount); void WriteGFFRecord(FILE *f, int QueryFrom, int QueryTo, int TargetFrom, int TargetTo, bool Comp, char *Feature, int Score, char *Annot); FILE *CreateStdioFile(const char *FileName); void LogTraps(const Trapezoid *Traps); int GetConnComps(EdgeList &Edges, CompList &Fams, int MinComponentSize); void LogMx(); void ExpandPiles(); void Info(); void MakeGraph(EdgeList &Edges); void RevComp(char *S, unsigned L); double GetPctId(const char *A, const char *B, const char *Path); int PathALength(const char *Path); void AlignArray(const ArrayData &AD, ArrayAln &AA); void FixBounds(ArrayAln &AA); void LogAA(const ArrayAln &AA); void ValidateAA(const ArrayAln &AA); const int *GetCountsAA(const ArrayAln &AA, int ColIndex); void StripBlanksAndGaps(std::string &s); void GetConsSeqAA(const ArrayAln &AA, Seq &ConsSeq); void StripBlanksAndGaps(Seq &s); void OutDetailAA(const ArrayAln &AA); int GetAvgSpacerLength(const ArrayAln &AA); int GetAvgRepeatLength(const ArrayAln &AA); int GetArrayLength(const ArrayAln &AA); void AlignArrays(const std::vector &ADVec, std::vector &AAVec); int DistanceAA(const ArrayAln &AA1, const ArrayAln &AA2); bool AcceptedAA(const ArrayAln &AA); bool MergeAAs(ArrayAln &AA1, const ArrayAln &AA2); int UnalignedLength(const std::string &s); void OutPalindromes(const std::vector &AAVec); void SaveSeqs(FILE *f, const std::vector AAVec); void Cmp(); double GetFractId(const Seq &A, const Seq &B, unsigned StartA, unsigned StartB, std::string &Path); void Options(); ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/utils.h",".h","239","12","#ifndef UTILS_H #define UTILS_H void Quit(const char *Format, ...); void Warning(const char *Format, ...); void Log(const char *Format, ...); void Out(const char *Format, ...); char *strsave(const char *s); #endif // UTILS_H ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/progress.cpp",".cpp","2534","129","#include ""pilercr.h"" #include #include #include static time_t g_StartTime = time(0); static time_t g_StartTimeStep; static char *g_Msg = strsave(""""); static bool g_NL = false; bool g_ShowProgress = true; int GetElapsedSecs() { return (int) (time(0) - g_StartTime); } void ShowProgress(bool Show) { g_ShowProgress = Show; } static char *Resources() { static char Str[64]; int ElapsedSecs = GetElapsedSecs(); unsigned MemUseMB = (GetMemUseBytes() + 500000)/1000000; unsigned RAMMB = (unsigned) ((GetRAMSize() + 500000)/1000000); unsigned MemUsePct = (MemUseMB*100)/RAMMB; sprintf(Str, ""%4d s %6d Mb (%3d%%) "", ElapsedSecs, MemUseMB, MemUsePct); return Str; } void ProgressStep(int StepIndex, int StepCount) { if (!g_ShowProgress) return; double Pct = (double) StepIndex*100.0 / (double) StepCount; fprintf(stderr, ""\r%s %6.2f%% %s"", Resources(), Pct, g_Msg); // fprintf(stderr, ""%s %6.2f%% %s Step %d of %d\n"", Resources(), Pct, g_Msg, StepIndex, StepCount); g_NL = false; } void ProgressStart(const char *Format, ...) { g_StartTimeStep = time(0); char Str[4096]; va_list ArgList; va_start(ArgList, Format); vsprintf(Str, Format, ArgList); if (g_Msg != 0) free(g_Msg); g_Msg = strsave(Str); if (!g_ShowProgress) return; if (!g_NL) fprintf(stderr, ""\n""); ProgressStep(0, 1); } void ProgressDone() { if (0 == g_Msg) return; Log(""%s %s\n"", Resources(), g_Msg); if (g_ShowProgress) { fprintf(stderr, ""\r%s %6.2f%% %s\n"", Resources(), 100.0, g_Msg); g_NL = true; } free(g_Msg); g_Msg = 0; } void Progress(const char *Format, ...) { if (!g_ShowProgress) return; char Str[4096]; va_list ArgList; va_start(ArgList, Format); vsprintf(Str, Format, ArgList); Log(""%s %s\n"", Resources(), Str); if (g_ShowProgress) { if (!g_NL) fprintf(stderr, ""\n""); fprintf(stderr, ""%s %s\n"", Resources(), Str); g_NL = true; } } void ProgressNoRes(const char *Format, ...) { if (!g_ShowProgress) return; char Str[4096]; va_list ArgList; va_start(ArgList, Format); vsprintf(Str, Format, ArgList); Log(""%s\n"", Str); if (g_ShowProgress) { if (!g_NL) fprintf(stderr, ""\n""); fprintf(stderr, ""%s\n"", Str); g_NL = true; } } void ProgressExit() { time_t t = time(0); Log(""%s"", asctime(localtime(&t))); Progress(""Finished, total elapsed time %ld secs."", GetElapsedSecs()); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/pwpath.h",".h","2430","101","#ifndef PWPath_h #define PWPath_h /*** Each PWEdge in a PWPath specifies a column in a pair-wise (PW) alignment. ""Path"" is by analogy with the path through an HMM. Edge types are: 'M' LetterA + LetterB 'D' LetterA + GapB 'I' GapB + LetterA The mnemomic is Match, Delete, Insert (with respect to A). Here is a global alignment of sequences A and B. A: AMQT-F B: -M-TIF The path for this example is: Edge cType uPrefixLengthA uPrefixLengthB 0 D 1 0 1 M 2 1 2 D 3 1 3 M 4 2 4 I 4 3 5 M 5 4 Given the starting positions in each alignment (e.g., column zero for a global alignment), the prefix length fields are redundant; they are included only for convenience and as a sanity check, we are not trying to optimize for speed or space here. We use prefix lengths rather than column indexes because of the problem of representing the special case of a gap in the first position. ***/ class Seq; class MSA; class SatchmoParams; class PW; class TextFile; class PWScore; class PWEdge { public: char cType; unsigned uPrefixLengthA; unsigned uPrefixLengthB; bool Equal(const PWEdge &e) const { return uPrefixLengthA == e.uPrefixLengthA && uPrefixLengthB == e.uPrefixLengthB && cType == e.cType; } }; class PWPath { // Disable compiler defaults private: PWPath &operator=(const PWPath &rhs); PWPath(const PWPath &rhs); public: PWPath(); virtual ~PWPath(); public: void Clear(); void FromStr(const char Str[]); void Copy(const PWPath &Path); void AppendEdge(const PWEdge &Edge); void AppendEdge(char cType, unsigned uPrefixLengthA, unsigned uPrefixLengthB); void PrependEdge(const PWEdge &Edge); unsigned GetEdgeCount() const { return m_uEdgeCount; } const PWEdge &GetEdge(unsigned uEdgeIndex) const; void Validate(const PWScore &PWS) const; void Validate() const; void LogMe() const; void FromFile(TextFile &File); void ToFile(TextFile &File) const; void FromMSAPair(const MSA &msaA, const MSA &msaB); void AssertEqual(const PWPath &Path) const; bool Equal(const PWPath &Path) const; unsigned GetMatchCount() const; unsigned GetDeleteCount() const; unsigned GetInsertCount() const; private: void ExpandPath(unsigned uAdditionalEdgeCount); private: unsigned m_uEdgeCount; unsigned m_uArraySize; PWEdge *m_Edges; }; #endif // PWPath_h ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/writepiles.cpp",".cpp","710","31","#include ""pilercr.h"" void WritePiles() { const char *FileName = ValueOpt(""piles""); if (FileName == 0) return; FILE *f = OpenStdioFile(FileName, FILEIO_MODE_WriteOnly); ProgressStart(""Writing piles""); for (int PileIndex = 0; PileIndex < g_PileCount; ++PileIndex) { if (PileIndex%100 == 0) ProgressStep(PileIndex, g_PileCount); PileData &Pile = g_Piles[PileIndex]; IntVec &HitIndexes = Pile.HitIndexes; for_CIntVec(HitIndexes, p) { int HitIndex = *p; const DPHit &Hit = GetHit(HitIndex); char Annot[128]; sprintf(Annot, ""Hit(%d) ; Pile(%d)"", HitIndex, PileIndex); WriteDPHit(f, Hit, false, Annot); } } ProgressDone(); fclose(f); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/savefilterhit.cpp",".cpp","4705","183","#include ""pilercr.h"" static FILE *g_fFilterOut = 0; static FILE *g_fFilterOutComp = 0; extern int SeqLengthQ; extern ContigData *ContigsQ; extern int *ContigMapQ; extern int ContigCountQ; extern bool FilterComp; static int g_FilterHitCount = 0; static int g_FilterHitCountComp = 0; void SetFilterOutFile(FILE *f) { g_fFilterOut = f; } void SetFilterOutFileComp(FILE *f) { g_fFilterOutComp = f; } void CloseFilterOutFile() { fclose(g_fFilterOut); g_fFilterOut = 0; } void CloseFilterOutFileComp() { fclose(g_fFilterOutComp); g_fFilterOutComp = 0; } int GetFilterHitCount() { return g_FilterHitCount; } int GetFilterHitCountComp() { return g_FilterHitCountComp; } void SaveFilterHit(int qLo, int qHi, int DiagIndex) { if (FilterComp) { fprintf(g_fFilterOutComp, ""%d;%d;%d\n"", qLo, qHi, DiagIndex); ++g_FilterHitCountComp; } else { fprintf(g_fFilterOut, ""%d;%d;%d\n"", qLo, qHi, DiagIndex); ++g_FilterHitCount; } } void WriteDPHit(FILE *f, const DPHit &Hit, bool Comp, const char *Annot) { int TargetFrom = Hit.aLo; int TargetTo = Hit.aHi; int QueryFrom; int QueryTo; if (Comp) { // Another lazy hack: empirically found off-by-one // complemented hits have query pos off-by-one, so // fix by this change. Should figure out what's really // going on. // QueryFrom = SeqLengthQ - Hit.bHi - 1; // QueryTo = SeqLengthQ - Hit.bLo - 1; QueryFrom = SeqLengthQ - Hit.bHi; QueryTo = SeqLengthQ - Hit.bLo; if (QueryFrom >= QueryTo) Quit(""WriteDPHit: QueryFrom > QueryTo (comp)""); } else { QueryFrom = Hit.bLo; QueryTo = Hit.bHi; if (QueryFrom >= QueryTo) Quit(""WriteDPHit: QueryFrom > QueryTo (not comp)""); } // DPHit coordinates sometimes over/underflow. // This is a lazy hack to work around it, should really figure // out what is going on. if (QueryFrom < 0) QueryFrom = 0; if (QueryTo >= SeqLengthQ) QueryTo = SeqLengthQ - 1; if (TargetFrom < 0) TargetFrom = 0; if (TargetTo >= SeqLengthQ) TargetTo = SeqLengthQ - 1; // Take midpoint of segment -- lazy hack again, endpoints // sometimes under / overflow const int TargetBin = (TargetFrom + TargetTo)/(2*CONTIG_MAP_BIN_SIZE); const int QueryBin = (QueryFrom + QueryTo)/(2*CONTIG_MAP_BIN_SIZE); const int BinCountT = (SeqLengthQ + CONTIG_MAP_BIN_SIZE - 1)/CONTIG_MAP_BIN_SIZE; const int BinCountQ = (SeqLengthQ + CONTIG_MAP_BIN_SIZE - 1)/CONTIG_MAP_BIN_SIZE; if (TargetBin < 0 || TargetBin >= BinCountT) { Warning(""Target bin out of range""); return; } if (QueryBin < 0 || QueryBin >= BinCountQ) { Warning(""Query bin out of range""); return; } if (ContigMapQ == 0) Quit(""ContigMap = 0""); const int TargetContigIndex = ContigMapQ[TargetBin]; const int QueryContigIndex = ContigMapQ[QueryBin]; if (TargetContigIndex < 0 || TargetContigIndex >= ContigCountQ) Quit(""WriteDPHit: bad target contig index""); if (QueryContigIndex < 0 || QueryContigIndex >= ContigCountQ) Quit(""WriteDPHit: bad query contig index""); const int TargetLength = TargetTo - TargetFrom + 1; const int QueryLength = QueryTo - QueryFrom + 1; if (TargetLength < 0 || QueryLength < 0) Quit(""WriteDPHit: Length < 0""); const ContigData &TargetContig = ContigsQ[TargetContigIndex]; const ContigData &QueryContig = ContigsQ[QueryContigIndex]; int TargetContigFrom = TargetFrom - TargetContig.From + 1; int QueryContigFrom = QueryFrom - QueryContig.From + 1; int TargetContigTo = TargetContigFrom + TargetLength - 1; int QueryContigTo = QueryContigFrom + QueryLength - 1; if (TargetContigFrom < 1) TargetContigFrom = 1; if (TargetContigTo > TargetContig.Length) TargetContigTo = TargetContig.Length; if (QueryContigFrom < 1) QueryContigFrom = 1; if (QueryContigTo > QueryContig.Length) QueryContigTo = QueryContig.Length; const char *TargetLabel = TargetContig.Label; const char *QueryLabel = QueryContig.Label; const char Strand = Comp ? '-' : '+'; // GFF Fields are: // [attributes] [comments] // 0 1 2 3 4 5 6 7 8 9 fprintf(f, ""%s\tcrisper\thit\t%d\t%d\t%d\t%c\t.\tTarget %s %d %d; maxe %.2g ; %s\n"", QueryLabel, QueryContigFrom, QueryContigTo, Hit.score, Strand, TargetLabel, TargetContigFrom, TargetContigTo, Hit.error, Annot); } void WriteDPHits(FILE *f, bool Comp) { for (int i = 0; i < g_HitCount; ++i) { const DPHit &Hit = g_Hits[i]; WriteDPHit(f, Hit, Comp); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/acceptaa.cpp",".cpp","2938","122","#include ""pilercr.h"" static double GetCons(const std::string &s1, const Seq &s2) { assert(s1.size() == s2.size()); size_t L = s1.size(); int Sum = 0; for (size_t i = 0; i < L; ++i) { if (toupper(s1[i]) == toupper(s2[i])) ++Sum; } return (double) Sum / (double) L; } bool AcceptedAA(const ArrayAln &AA) { const size_t ArraySize = AA.Repeats.size(); if (ArraySize < (size_t) g_MinArraySize) { Log(""Rejected size=%d, minarray=%d\n"", (int) ArraySize, g_MinArraySize); LogAA(AA); return false; } int MinRepeatLength = (int) AA.Repeats[0].size(); int MaxRepeatLength = 0; int AvgSpacerLength = GetAvgSpacerLength(AA); int AvgRepeatLength = GetAvgRepeatLength(AA); if (AvgSpacerLength < g_MinSpacerLength) { Log(""Rejected, avg spacer %d < min %d\n"", AvgSpacerLength, g_MinSpacerLength); return false; } if (AvgSpacerLength > g_MaxSpacerLength) { Log(""Rejected, avg spacer %d < max %d\n"", AvgSpacerLength, g_MaxSpacerLength); return false; } if (AvgRepeatLength < g_MinRepeatLength) { Log(""Rejected min repeat length array min %d min allowed %d\n"", AvgRepeatLength, g_MinRepeatLength); LogAA(AA); return false; } if (AvgRepeatLength > g_MaxRepeatLength) { Log(""Rejected Max repeat length array Max %d Max allowed %d\n"", AvgRepeatLength, g_MaxRepeatLength); LogAA(AA); return false; } int RunLength = 0; int MaxRunLength = 0; int RunStart = 0; int LastRunStart = 0; int RunEnd = 0; for (size_t RepeatIndex = 0; RepeatIndex < ArraySize; ++RepeatIndex) { const std::string &Repeat = AA.Repeats[RepeatIndex]; double Cons = GetCons(Repeat, AA.AlignedConsSeq); if (Cons >= g_MinCons) { if (RunLength == 0) LastRunStart = (int) RepeatIndex; ++RunLength; if (RunLength > MaxRunLength) { MaxRunLength = RunLength; RunStart = LastRunStart; RunEnd = (int) RepeatIndex; } } else RunLength = 0; } if (RunLength < g_MinArraySize) { Log(""Rejected, min cons / size\n""); LogAA(AA); return false; } double BestSpacerRatio = 1.0; for (int Base = 0; Base < (int) ArraySize - g_MinArraySize - 1; ++Base) { int MinSpacerLength = 999999; int MaxSpacerLength = 0; for (int RepeatIndex = Base; RepeatIndex < Base + g_MinArraySize; ++RepeatIndex) { assert(RepeatIndex < (int) ArraySize - 1); const std::string &Spacer = AA.Spacers[RepeatIndex]; int SpacerLength = (int) Spacer.size(); MinSpacerLength = std::min(MinSpacerLength, SpacerLength); MaxSpacerLength = std::max(MaxSpacerLength, SpacerLength); } double r = GetRatio(MinSpacerLength, MaxSpacerLength); if (r > BestSpacerRatio) BestSpacerRatio = r; } if (BestSpacerRatio < g_MinSpacerRatio) { Log(""Rejected spacer ratio\n""); LogAA(AA); return false; } return true; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/kmerdist.cpp",".cpp","6471","258","#include ""multaln.h"" #define TRACE 0 #define MIN(x, y) (((x) < (y)) ? (x) : (y)) #define MAX(x, y) (((x) > (y)) ? (x) : (y)) const unsigned TUPLE_COUNT = 4*4*4*4; static unsigned char Count1[TUPLE_COUNT]; static unsigned char Count2[TUPLE_COUNT]; // Nucleotide groups according to MAFFT (sextet5) // 0 = A // 1 = C // 2 = G // 3 = T // 4 = other static unsigned ResidueGroup[] = { 0, // NX_A, 1, // NX_C, 2, // NX_G, 3, // NX_T/U 0, // NX_N, 0, // NX_R, 0, // NX_Y, 0, // NX_GAP }; static unsigned uResidueGroupCount = sizeof(ResidueGroup)/sizeof(ResidueGroup[0]); static char *TupleToStr(int t) { static char Letter[4] = { 'A', 'C', 'G', 'T' }; static char s[7]; int t1, t2, t3, t4; t1 = t%4; t2 = (t/4)%4; t3 = (t/(4*4))%4; t4 = (t/(4*4*4))%4; s[3] = Letter[t1]; s[2] = Letter[t2]; s[1] = Letter[t3]; s[0] = Letter[t4]; return s; } static unsigned GetTuple(const unsigned uLetters[], unsigned n) { assert(uLetters[n] < uResidueGroupCount); assert(uLetters[n+1] < uResidueGroupCount); assert(uLetters[n+2] < uResidueGroupCount); assert(uLetters[n+3] < uResidueGroupCount); unsigned u1 = ResidueGroup[uLetters[n]]; unsigned u2 = ResidueGroup[uLetters[n+1]]; unsigned u3 = ResidueGroup[uLetters[n+2]]; unsigned u4 = ResidueGroup[uLetters[n+3]]; return u4 + u3*4 + u2*4*4 + u1*4*4*4; } static void CountTuples(const unsigned L[], unsigned uTupleCount, unsigned char Count[]) { memset(Count, 0, TUPLE_COUNT*sizeof(unsigned char)); for (unsigned n = 0; n < uTupleCount; ++n) { const unsigned uTuple = GetTuple(L, n); ++(Count[uTuple]); } } static void ListCount(const unsigned char Count[]) { for (unsigned n = 0; n < TUPLE_COUNT; ++n) { if (0 == Count[n]) continue; Log(""%s %u\n"", TupleToStr(n), Count[n]); } } void KmerDist(const SeqVect &Seqs, DistFunc &DF) { const unsigned uSeqCount = Seqs.Length(); DF.SetCount(uSeqCount); if (0 == uSeqCount) return; // Initialize distance matrix to zero for (unsigned uSeq1 = 0; uSeq1 < uSeqCount; ++uSeq1) { DF.SetDist(uSeq1, uSeq1, 0); DF.SetId(uSeq1, Seqs[uSeq1]->GetId()); for (unsigned uSeq2 = 0; uSeq2 < uSeq1; ++uSeq2) DF.SetDist(uSeq1, uSeq2, 0); } // Convert to letters unsigned **Letters = new unsigned *[uSeqCount]; for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { Seq &s = *(Seqs[uSeqIndex]); const unsigned uSeqLength = s.Length(); unsigned *L = new unsigned[uSeqLength]; Letters[uSeqIndex] = L; for (unsigned n = 0; n < uSeqLength; ++n) { char c = s[n]; L[n] = CharToLetterEx(c); if (L[n] >= 4) L[n] = 3; } } unsigned **uCommonTupleCount = new unsigned *[uSeqCount]; for (unsigned n = 0; n < uSeqCount; ++n) { uCommonTupleCount[n] = new unsigned[uSeqCount]; memset(uCommonTupleCount[n], 0, uSeqCount*sizeof(unsigned)); } const unsigned uPairCount = (uSeqCount*(uSeqCount + 1))/2; unsigned uCount = 0; for (unsigned uSeq1 = 0; uSeq1 < uSeqCount; ++uSeq1) { Seq &seq1 = *(Seqs[uSeq1]); const unsigned uSeqLength1 = seq1.Length(); if (uSeqLength1 < 5) continue; const unsigned uTupleCount = uSeqLength1 - 5; const unsigned *L = Letters[uSeq1]; CountTuples(L, uTupleCount, Count1); #if TRACE { Log(""Seq1=%d\n"", uSeq1); Log(""Groups:\n""); for (unsigned n = 0; n < uSeqLength1; ++n) Log(""%u"", ResidueGroup[L[n]]); Log(""\n""); Log(""Tuples:\n""); ListCount(Count1); } #endif for (unsigned uSeq2 = 0; uSeq2 <= uSeq1; ++uSeq2) { ++uCount; Seq &seq2 = *(Seqs[uSeq2]); const unsigned uSeqLength2 = seq2.Length(); if (uSeqLength2 < 4) { if (uSeq1 == uSeq2) DF.SetDist(uSeq1, uSeq2, 0); else DF.SetDist(uSeq1, uSeq2, 1); continue; } // First pass through seq 2 to count tuples const unsigned uTupleCount = uSeqLength2 <= 5 ? 0 : uSeqLength2 - 5; const unsigned *L = Letters[uSeq2]; CountTuples(L, uTupleCount, Count2); #if TRACE Log(""Seq2=%d Counts=\n"", uSeq2); ListCount(Count2); #endif // Second pass to accumulate sum of shared tuples unsigned uSum = 0; for (unsigned n = 0; n < uTupleCount; ++n) { const unsigned uTuple = GetTuple(L, n); uSum += MIN(Count1[uTuple], Count2[uTuple]); // This is a hack to make sure each unique tuple counted only once. Count2[uTuple] = 0; } #if TRACE { Seq &s1 = *(Seqs[uSeq1]); Seq &s2 = *(Seqs[uSeq2]); const char *pName1 = s1.GetName(); const char *pName2 = s2.GetName(); Log(""Common count %s(%d) - %s(%d) =%u\n"", pName1, uSeq1, pName2, uSeq2, uSum); } #endif uCommonTupleCount[uSeq1][uSeq2] = uSum; uCommonTupleCount[uSeq2][uSeq1] = uSum; } } uCount = 0; for (unsigned uSeq1 = 0; uSeq1 < uSeqCount; ++uSeq1) { Seq &s1 = *(Seqs[uSeq1]); const char *pName1 = s1.GetName(); double dCommonTupleCount11 = uCommonTupleCount[uSeq1][uSeq1]; if (0 == dCommonTupleCount11) dCommonTupleCount11 = 1; DF.SetDist(uSeq1, uSeq1, 0); for (unsigned uSeq2 = 0; uSeq2 < uSeq1; ++uSeq2) { ++uCount; double dCommonTupleCount22 = uCommonTupleCount[uSeq2][uSeq2]; if (0 == dCommonTupleCount22) dCommonTupleCount22 = 1; const double dDist1 = (dCommonTupleCount11 - uCommonTupleCount[uSeq1][uSeq2]) /dCommonTupleCount11; const double dDist2 = (dCommonTupleCount22 - uCommonTupleCount[uSeq1][uSeq2]) /dCommonTupleCount22; const double dMinDist = MIN(dDist1, dDist2); DF.SetDist(uSeq1, uSeq2, (float) dMinDist); #if TRACE Log(""%u,%d Common11=%g Common22=%g Common12=%u d1=%g d2=%g\n"", uSeq1, uSeq2, dCommonTupleCount11, dCommonTupleCount22, uCommonTupleCount[uSeq1][uSeq2], dDist1, dDist2); #endif } } for (unsigned n = 0; n < uSeqCount; ++n) { delete[] uCommonTupleCount[n]; delete[] Letters[n]; } delete[] uCommonTupleCount; delete[] Letters; } // //void Test() // { // DistFunc DF; // Seq *s1 = new Seq; // Seq *s2 = new Seq; // s1->FromString(""GCATCGCCCGCCAGCAATGGCGGGCGCGGATTGAAAC"", ""s1""); // s2->FromString(""GCATCGCCCCTCGGCAACGAGGGGCGCGGATTGAAAC"", ""s2""); // SeqVect Seqs; // Seqs.push_back(s1); // Seqs.push_back(s2); // KmerDist(Seqs, DF); // Log(""Dist=%.1f\n"", DF.GetDist(0, 1)); // Quit(""Test""); // } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/myassert.h",".h","238","12","#ifndef MYASSERT_H #define MYASSERT_H #ifdef assert #undef assert #endif void assert_(const char *, const char *, unsigned); #define assert(exp) (void)( (exp) || (assert_(#exp, __FILE__, __LINE__), 0) ) #endif // MYASSERT_H ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/readfilterhits.cpp",".cpp","630","25","#include ""pilercr.h"" FilterHit *ReadFilterHits(FILE *f, int Count) { if (0 == Count) return 0; int Ok = fseek(f, 0, SEEK_SET); long Pos = ftell(f); if (Pos != 0) Quit(""ReadFilterHits: rewind failed, fseek=%d ftell=%ld errno=%d"", Ok, Pos, errno); FilterHit *FilterHits = all(FilterHit, Count); for (int HitIndex = 0; HitIndex < Count; ++HitIndex) { FilterHit &Hit = FilterHits[HitIndex]; int n = fscanf(f, ""%d;%d;%d\n"", &Hit.QFrom, &Hit.QTo, &Hit.DiagIndex); if (n != 3) Quit(""Failed to read filter hit %d of %d, fscanf=%d"", HitIndex, Count, n); } return FilterHits; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/alignclust.cpp",".cpp","937","47","#include ""pilercr.h"" #define TRACE 0 void AlignCluster(std::vector &AAVec, const IntVec &Cluster, Seq &ConsSymbols) { #if TRACE Log(""AlignCluster:\n""); #endif SeqVect Seqs; const size_t ClusterSize = Cluster.size(); for (size_t i = 0; i < ClusterSize ; ++i) { size_t ArrayIndex = Cluster[i]; Seq *s = new Seq; #if TRACE ADVec[ArrayIndex]->ConsSeq.LogMe(); Log(""\n""); #endif const ArrayAln &AA = *(AAVec[ArrayIndex]); s->Copy(AA.ConsSeq); if (AA.ClusterRevComp && ClusterSize > 1) s->RevComp(); Seqs.push_back(s); } MSA Aln; MultipleAlign(Seqs, Aln); #if TRACE Aln.LogMe(); #endif GetConsSymbols(Aln, ConsSymbols); for (size_t i = 0; i < ClusterSize ; ++i) { size_t ArrayIndex = Cluster[i]; Aln.GetSeq((unsigned) i, AAVec[ArrayIndex]->AlignedConsSeq); #if TRACE Log(""Aligned=""); AAVec[i]->AlignedConsSeq.LogMe(); #endif } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/types.h",".h","2271","134","#ifndef TYPES_H #define TYPES_H #include ""intlist.h"" typedef int PILE_INDEX_TYPE; struct FilterParams { int WordSize; int SeedLength; int SeedDiffs; int TubeOffset; }; struct DPParams { int g_MinHitLength; double MinId; }; struct TubeState { int qLo; int qHi; int Count; }; struct ContigData { int From; int Length; int Index; char *Label; }; struct FilterHit { int QFrom; int QTo; int DiagIndex; }; struct Trapezoid { Trapezoid *next; // Organized in a list linked on this field int top, bot; // B (query) coords of top and bottom of trapzoidal zone int lft, rgt; // Left and right diagonals of trapzoidal zone }; struct DPHit { int aLo, bLo; // Start coordinate of local alignment int aHi, bHi; // End coordinate of local alignment int ldiag, hdiag; // Alignment is between (anti)diagonals ldiag & hdiag int score; // Score of alignment where match = 1, difference = -3 float error; // Lower bound on error rate of match bool Deleted; IntVec LinkedHits; }; struct PileData { int Lo; int Hi; bool Deleted; // IntVec LinkedPiles; IntVec HitIndexes; // int Spacer; }; struct ImageData { int Lo; int Hi; int HitIndex; bool IsA; }; struct EdgeData { int Node1; int Node2; bool Rev; }; typedef std::list EdgeList; typedef EdgeList::iterator PtrEdgeList; struct CompMemberData { int PileIndex; bool Rev; }; typedef std::list CompData; typedef CompData::iterator PtrFamData; typedef std::list CompList; typedef CompList::iterator PtrCompList; enum FILEIO_MODE { FILEIO_MODE_Undefined = 0, FILEIO_MODE_ReadOnly, FILEIO_MODE_ReadWrite, FILEIO_MODE_WriteOnly }; #if FILEIO_BINARY_MODE #define FILIO_STRMODE_ReadOnly ""rb"" #define FILIO_STRMODE_WriteOnly ""wb"" #define FILIO_STRMODE_ReadWrite ""w+b"" #else #define FILIO_STRMODE_ReadOnly ""r"" #define FILIO_STRMODE_WriteOnly ""w"" #define FILIO_STRMODE_ReadWrite ""w+"" #endif struct INDEX_ENTRY { int Kmer; // for debugging only int Pos; INDEX_ENTRY *Next; INDEX_ENTRY *Prev; }; enum TERMGAPS { TERMGAPS_Full, TERMGAPS_Half, TERMGAPS_Ext, }; #endif // TYPES_H ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/aligntraps.cpp",".cpp","4558","195","#include ""pilercr.h"" #include #define TRACE 0 extern void Align_Recursion(char *A, int Alen, char *B, int Blen, Trapezoid *b, int current, int comp, int MinLen, double MaxDiff, int Traplen); extern int TSORT(const void *l, const void *r); extern int StSORT(const void *l, const void *r); extern int FnSORT(const void *l, const void *r); // Sort by Lo bool Cmp_Lo(const DPHit &Hit1, const DPHit &Hit2) { if (Hit1.aLo < Hit2.aLo) return true; return false; } // Sort by Hi bool Cmp_Hi(const DPHit &Hit1, const DPHit &Hit2) { if (Hit1.aHi < Hit2.aHi) return true; return false; } // shared with aligntraps.cpp Trapezoid **Tarray = NULL; int *Covered; int SegMax = -1; static int fseg; static int TarMax = -1; void AlignTraps(char *A, int Alen, char *B, int Blen, Trapezoid *Traplist, int Traplen, int comp, const DPParams &DP) { Tarray = NULL; Covered = 0; SegMax = -1; fseg = 0; TarMax = -1; Progress(""Initializing trapezoid alignment""); const int MinLen = DP.g_MinHitLength; const double MaxDiff = 1.0 - DP.MinId; Trapezoid *b; int i; if (Traplen >= TarMax) { TarMax = (int) (1.2*Traplen + 500); Tarray = (Trapezoid **) ckrealloc(Tarray,(sizeof(Trapezoid *) + sizeof(int))*TarMax,""Trapezoid array""); Covered = (int *) (Tarray + TarMax); } // Arbitrary number to avoid thrashing g_Hits.reserve(10000); i = 0; b = Traplist; for (i = 0; i < Traplen; i++) { Tarray[i] = b; Covered[i] = 0; if (b == 0) { Traplen = i; Warning(""Internal problem: in AlignTraps, b=0, truncating list""); break; } b = b->next; } qsort(Tarray,Traplen,sizeof(Trapezoid *),TSORT); #ifdef SHOW_TRAP { int i; Trapezoid *t; for (i = 0; i < Traplen; i++) { t = Tarray[i]; printf("" [%d,%d] x [%d,%d]\n"",t->bot,t->top,t->lft,t->rgt); } } #endif #ifdef REPORT_DPREACH Al_depth = 0; #endif g_HitCount = 0; fseg = g_HitCount; ProgressStart(""Aligning trapezoids""); int Step = Traplen/50; if (Step == 0) Step = 1; for (i = 0; i < Traplen; i++) { if (i%Step == 0) ProgressStep(i, Traplen); if (! Covered[i]) { b = Tarray[i]; if (b->top - b->bot < k) continue; #if TRACE Log(""Align trap %d,%d - %d,%d\n"", b->lft, b->top, b->rgt, b->top); #endif if (b->lft < g_MinDiag) continue; Align_Recursion(A,Alen,B,Blen,b,i,comp,MinLen,MaxDiff,Traplen); } } ProgressDone(); /* Remove lower scoring segments that begin or end at the same point as a higher scoring segment. */ Progress(""Removing redundant hits""); if (g_HitCount > fseg) { int i, j; // qsort(g_Hits+fseg,g_HitCount-fseg,sizeof(DPHit),StSORT); std::vector::iterator pFrom = g_Hits.begin(); std::vector::iterator pTo = g_Hits.begin(); pFrom += fseg; pTo -= fseg; std::sort(pFrom, pTo, Cmp_Lo); for (i = fseg; i < g_HitCount; i = j) { for (j = i+1; j < g_HitCount; j++) { if (g_Hits[j].aLo != g_Hits[i].aLo) break; if (g_Hits[j].bLo != g_Hits[i].bLo) break; if (g_Hits[j].score > g_Hits[i].score) { g_Hits[i].score = -1; i = j; } else g_Hits[j].score = -1; } } std::sort(pFrom, pTo, Cmp_Hi); // qsort(g_Hits+fseg,g_HitCount-fseg,sizeof(DPHit),FnSORT); for (i = fseg; i < g_HitCount; i = j) { for (j = i+1; j < g_HitCount; j++) { if (g_Hits[j].aHi != g_Hits[i].aHi) break; if (g_Hits[j].bHi != g_Hits[i].bHi) break; if (g_Hits[j].score > g_Hits[i].score) { g_Hits[i].score = -1; i = j; } else g_Hits[j].score = -1; } } for (i = fseg; i < g_HitCount; i++) if (g_Hits[i].score >= 0) g_Hits[fseg++] = g_Hits[i]; g_HitCount = fseg; } #ifdef REPORT_SIZES printf(""\n %9d segments\n"",g_HitCount); fflush(stdout); #endif free(Tarray); Tarray = 0; g_HitCount = (int) g_Hits.size(); } int SumDPLengths(const DPHit *DPHits, int HitCount) { int Sum = 0; for (int i = 0; i < HitCount; ++i) { const DPHit &Hit = DPHits[i]; const int Length = Hit.aHi - Hit.aLo; if (Length < 0) Quit(""SumDPLengths, Length < 0""); Sum += Length; } return Sum; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/proffrommsa.cpp",".cpp","4490","192","#include ""multaln.h"" #define TRACE 0 static void LogF(FCOUNT f) { if (f > -0.00001 && f < 0.00001) Log("" ""); else Log("" %5.3f"", f); } static const char *LocalScoreToStr(SCORE s) { static char str[16]; if (s < -1e10 || s > 1e10) return "" *""; sprintf(str, ""%5.1f"", s); return str; } void ListProfile(const ProfPos *Prof, unsigned uLength, const MSA *ptrMSA) { Log("" Pos Occ LL LG GL GG Open Close\n""); Log("" --- --- -- -- -- -- ---- -----\n""); for (unsigned n = 0; n < uLength; ++n) { const ProfPos &PP = Prof[n]; Log(""%5u"", n); LogF(PP.m_fOcc); LogF(PP.m_LL); LogF(PP.m_LG); LogF(PP.m_GL); LogF(PP.m_GG); Log("" %5.1f"", -PP.m_scoreGapOpen); Log("" %5.1f"", -PP.m_scoreGapClose); if (0 != ptrMSA) { const unsigned uSeqCount = ptrMSA->GetSeqCount(); Log("" ""); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) Log(""%c"", ptrMSA->GetChar(uSeqIndex, n)); } Log(""\n""); } Log(""\n""); Log("" Pos G""); for (unsigned n = 0; n < g_AlphaSize; ++n) Log("" %c"", LetterExToChar(n)); Log(""\n""); Log("" --- -""); for (unsigned n = 0; n < g_AlphaSize; ++n) Log("" -----""); Log(""\n""); for (unsigned n = 0; n < uLength; ++n) { const ProfPos &PP = Prof[n]; Log(""%5u"", n); if (-1 == PP.m_uResidueGroup) Log("" -"", PP.m_uResidueGroup); else Log("" %d"", PP.m_uResidueGroup); for (unsigned uLetter = 0; uLetter < g_AlphaSize; ++uLetter) { FCOUNT f = PP.m_fcCounts[uLetter]; if (f == 0.0) Log("" ""); else Log("" %5.3f"", f); } if (0 != ptrMSA) { const unsigned uSeqCount = ptrMSA->GetSeqCount(); Log("" ""); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) Log(""%c"", ptrMSA->GetChar(uSeqIndex, n)); } Log(""\n""); } } static void SortCounts(const FCOUNT fcCounts[], unsigned SortOrder[]) { static unsigned InitialSortOrder[20] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; memcpy(SortOrder, InitialSortOrder, g_AlphaSize*sizeof(unsigned)); bool bAny = true; while (bAny) { bAny = false; for (unsigned n = 0; n < g_AlphaSize - 1; ++n) { unsigned i1 = SortOrder[n]; unsigned i2 = SortOrder[n+1]; if (fcCounts[i1] < fcCounts[i2]) { SortOrder[n+1] = i1; SortOrder[n] = i2; bAny = true; } } } } static unsigned NucleoGroupFromFCounts(const FCOUNT fcCounts[]) { bool bAny = false; unsigned uConsensusResidueGroup = RESIDUE_GROUP_MULTIPLE; for (unsigned uLetter = 0; uLetter < 4; ++uLetter) { if (0 == fcCounts[uLetter]) continue; const unsigned uResidueGroup = uLetter; if (bAny) { if (uResidueGroup != uConsensusResidueGroup) return RESIDUE_GROUP_MULTIPLE; } else { bAny = true; uConsensusResidueGroup = uResidueGroup; } } return uConsensusResidueGroup; } unsigned ResidueGroupFromFCounts(const FCOUNT fcCounts[]) { return NucleoGroupFromFCounts(fcCounts); } ProfPos *ProfileFromMSA(const MSA &a) { const unsigned uSeqCount = a.GetSeqCount(); const unsigned uColCount = a.GetColCount(); ProfPos *Pos = new ProfPos[uColCount]; unsigned uHydrophobicRunLength = 0; for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { ProfPos &PP = Pos[uColIndex]; PP.m_bAllGaps = a.IsGapColumn(uColIndex); FCOUNT fcGapStart; FCOUNT fcGapEnd; FCOUNT fcGapExtend; FCOUNT fOcc; a.GetFractionalWeightedCounts(uColIndex, false, PP.m_fcCounts, &fcGapStart, &fcGapEnd, &fcGapExtend, &fOcc, &PP.m_LL, &PP.m_LG, &PP.m_GL, &PP.m_GG); PP.m_fOcc = fOcc; SortCounts(PP.m_fcCounts, PP.m_uSortOrder); PP.m_uResidueGroup = ResidueGroupFromFCounts(PP.m_fcCounts); for (unsigned i = 0; i < g_AlphaSize; ++i) { SCORE scoreSum = 0; for (unsigned j = 0; j < g_AlphaSize; ++j) scoreSum += PP.m_fcCounts[j]*(*g_ptrScoreMatrix)[i][j]; PP.m_AAScores[i] = scoreSum; } SCORE sStartOcc = (SCORE) (1.0 - fcGapStart); SCORE sEndOcc = (SCORE) (1.0 - fcGapEnd); PP.m_fcStartOcc = sStartOcc; PP.m_fcEndOcc = sEndOcc; PP.m_scoreGapOpen = sStartOcc*g_scoreGapOpen/2; PP.m_scoreGapClose = sEndOcc*g_scoreGapOpen/2; } #if TRACE { Log(""ProfileFromMSA\n""); ListProfile(Pos, uColCount, &a); } #endif return Pos; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/readmfa.cpp",".cpp","4616","184","#include ""pilercr.h"" const int DP_PAD = 50; // padding to stop alignments static bool g_TruncateLabels = false; #define APPEND_CHAR(c) \ { \ if (Pos >= BufferSize) \ Quit(""ReadMFA: buffer too small""); \ Buffer[Pos++] = (c); \ } #define APPEND_LABEL(c) \ { \ if (LabelLength >= LabelBufferLength-1) \ { \ LabelBufferLength += 128; \ char *NewLabel = all(char, LabelBufferLength); \ memcpy(NewLabel, Label, LabelLength); \ freemem(Label); \ Label = NewLabel; \ } \ Label[LabelLength] = c; \ ++LabelLength; \ } #define INIT_CONTIGS() \ { \ ContigBufferCount = 128; \ Contigs = all(ContigData, ContigBufferCount); \ ContigCount = 0; \ } #define APPEND_CONTIG() \ { \ if (ContigCount >= ContigBufferCount) \ { \ ContigBufferCount += 128; \ ContigData *NewContigs = all(ContigData, ContigBufferCount); \ memcpy(NewContigs, Contigs, ContigCount*sizeof(ContigData)); \ freemem(Contigs); \ Contigs = NewContigs; \ } \ ++ContigCount; \ } void LogContigs(const ContigData *Contigs, int ContigCount) { Log("" Index Label From Length End\n""); Log(""------ -------------------------------- ----------- ----------- -----------\n""); for (int i = 0; i < ContigCount; ++i) { const ContigData *ptrContig = Contigs + i; Log(""%6d %32.32s %11d %11d %11d"", ptrContig->Index, ptrContig->Label, ptrContig->From, ptrContig->Length, ptrContig->From + ptrContig->Length - 1); if (ptrContig->From%CONTIG_MAP_BIN_SIZE) Log("" Bin %d Remainder %d"", ptrContig->From/CONTIG_MAP_BIN_SIZE, ptrContig->From%CONTIG_MAP_BIN_SIZE); Log(""\n""); } } char *ReadMFA(FILE *f, int *ptrLength, ContigData **ptrContigs, int *ptrContigCount) { rewind(f); int FileSize = GetFileSize(f); int BufferSize = FileSize + MAX_CONTIGS*CONTIG_MAP_BIN_SIZE; char *Buffer = all(char, BufferSize); char prev_c = '\n'; bool InLabel = false; int ContigFrom = 0; char *Label = 0; int LabelLength = 0; int LabelBufferLength = 0; int Pos = 0; int PrevContigTo = -1; int ContigBufferCount = 0; int ContigCount = 0; ContigData *Contigs; INIT_CONTIGS() for (;;) { int c = fgetc(f); if (EOF == c) { if (feof(f)) break; Quit(""Stream error""); } if (InLabel) { if (c == '\r') continue; if ('\n' == c) { APPEND_CONTIG() ContigData *ptrContig = Contigs + ContigCount - 1; ptrContig->From = ContigFrom; ptrContig->Index = ContigCount - 1; InLabel = false; } else { APPEND_LABEL(c) } } else { if ('>' == c && '\n' == prev_c) { InLabel = true; if (ContigCount > 0) { PrevContigTo = Pos - 1; ContigData *ptrPrevContig = Contigs + ContigCount - 1; ptrPrevContig->Length = PrevContigTo - ptrPrevContig->From + 1; Label[LabelLength] = 0; if (g_TruncateLabels) { char *ptrSpace = strchr(Label, ' '); if (0 != ptrSpace) *ptrSpace = 0; } ptrPrevContig->Label = strsave(Label); LabelLength = 0; int BinRemaining = CONTIG_MAP_BIN_SIZE - (PrevContigTo + 1)%CONTIG_MAP_BIN_SIZE; int PadLength = BinRemaining; if (PadLength < DP_PAD) PadLength += CONTIG_MAP_BIN_SIZE; for (int i = 0; i < PadLength; ++i) { APPEND_CHAR('!') } } ContigFrom = Pos; if (ContigFrom%CONTIG_MAP_BIN_SIZE != 0) Quit(""ReadMFA logic error""); } else if (!isspace(c)) { APPEND_CHAR(c) } } prev_c = c; } if (ContigCount > 0) { ContigData *ptrPrevContig = Contigs + ContigCount - 1; ptrPrevContig->Length = Pos - ptrPrevContig->From; Label[LabelLength] = 0; if (g_TruncateLabels) { char *ptrSpace = strchr(Label, ' '); if (0 != ptrSpace) *ptrSpace = 0; } ptrPrevContig->Label = strsave(Label); } *ptrContigs = Contigs; *ptrContigCount = ContigCount; *ptrLength = Pos; return Buffer; } char *ReadMFA(const char FileName[], int *ptrSeqLength, ContigData **ptrContigs, int *ptrContigCount, int **ptrContigMap) { FILE *f = OpenStdioFile(FileName); char *Seq = ReadMFA(f, ptrSeqLength, ptrContigs, ptrContigCount); MakeContigMap(*ptrContigs, *ptrContigCount, ptrContigMap); fclose(f); return Seq; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/alnarray.cpp",".cpp","5353","217","#include ""pilercr.h"" #include ""sw.h"" static void AllocAA(ArrayAln &AA, int RepeatCount) { for (int i = 0; i < RepeatCount; ++i) { AA.LeftFlanks.push_back(*new std::string); AA.Repeats.push_back(*new std::string); AA.Spacers.push_back(*new std::string); } } static ArrayAln *CopyAA(const ArrayAln &AA) { ArrayAln *NewAA = new ArrayAln; *NewAA = AA; return NewAA; } static bool EqAA(const ArrayAln &AA1, const ArrayAln &AA2) { if (AA1.Id != AA2.Id) return false; if (AA1.Pos != AA2.Pos) return false; const size_t RepeatCount = AA1.Repeats.size(); if (RepeatCount != AA2.Repeats.size()) return false; for (unsigned RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { if (AA1.Repeats != AA2.Repeats) return false; if (AA1.LeftFlanks != AA2.LeftFlanks) return false; if (AA1.Spacers != AA2.Spacers) return false; } return true; } static size_t UngappedLength(const std::string &s) { size_t Length = 0; for (size_t i = 0; i < s.size(); ++i) if (s[i] != '-') ++Length; return Length; } int GetArrayLength(const ArrayAln &AA) { size_t Length = 0; const size_t RepeatCount = AA.Repeats.size(); for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { size_t RepeatLength = UngappedLength(AA.Repeats[RepeatIndex]); Length += RepeatLength; if (RepeatIndex != RepeatCount - 1) { size_t SpacerLength = AA.Spacers[RepeatIndex].size(); Length += SpacerLength; } } return (int) Length; } void AlignArray(const ArrayData &AD, ArrayAln &AA) { const IntVec &PileIndexes = AD.PileIndexes; std::vector Rows; size_t RowCount = PileIndexes.size(); Rows.resize(RowCount); AllocAA(AA, (int) RowCount); AA.Id = AD.Id; const unsigned ConsSeqLen = AD.ConsSeq.Length(); char *ConsSeqStr = all(char, ConsSeqLen+1); AD.ConsSeq.ToString(ConsSeqStr, ConsSeqLen+1); SeqVect HitSeqs; int RowIndex = 0; for_CIntVec(PileIndexes, p) { RowData &Row = Rows[RowIndex++]; int PileIndex = *p; assert(PileIndex >= 0 && PileIndex < g_PileCount); Seq *PileSeq = new Seq; int Lo; int Hi; PileToSeq(g_Piles, PileIndex, *PileSeq, &Lo, &Hi); unsigned PileSeqLen = PileSeq->Length(); char *PileSeqStr = all(char, PileSeqLen+1); PileSeq->ToString(PileSeqStr, PileSeqLen+1); std::string Path; unsigned PileOffset; unsigned ConsOffset; SWSimple(PileSeqStr, PileSeqLen, ConsSeqStr, ConsSeqLen, &PileOffset, &ConsOffset, Path); Row.PctId = GetPctId(PileSeqStr+PileOffset, ConsSeqStr+ConsOffset, Path.c_str()); const PileData &Pile = g_Piles[PileIndex]; Row.RepeatLo = Lo + PileOffset; int RepeatLength = PathALength(Path.c_str()); Row.RepeatLength = RepeatLength; Seq *HitSeq = new Seq; const int ToPos = PileOffset + RepeatLength - 1; for (int Pos = PileOffset; Pos <= ToPos; ++Pos) HitSeq->push_back(PileSeqStr[Pos]); HitSeq->SetName(""hit""); HitSeq->SetId(0); HitSeqs.push_back(HitSeq); } freemem(ConsSeqStr); ConsSeqStr = 0; Seq *ConsSeq = new Seq; ConsSeq->Copy(AD.ConsSeq); HitSeqs.push_back(ConsSeq); MSA Aln; MultipleAlign(HitSeqs, Aln); if (g_LogAlns) { Out(""Refined alignment array %d:\n"", AD.Id); Aln.LogMe(); Out(""\n""); } const unsigned ColCount = Aln.GetColCount(); int SumSpacerLengths = 0; for (size_t RowIndex = 0; RowIndex < RowCount; ++RowIndex) { const RowData &Row = Rows[RowIndex]; char *Label; int LocalRepeatLo = GlobalToLocal(Row.RepeatLo, &Label); int NextLo = -1; int Hi = -1; int SpacerLength = -1; if (RowIndex + 1 != RowCount) { NextLo = Rows[RowIndex+1].RepeatLo; Hi = Row.RepeatLo + Row.RepeatLength - 1; SpacerLength = NextLo - Hi; if (SpacerLength < 4) { AA.Repeats.clear(); AA.Spacers.clear(); AA.LeftFlanks.clear(); return; } } // Left flank const ContigData &Contig = GlobalPosToContig(Row.RepeatLo); int ContigFrom = Contig.From; int ContigTo = ContigFrom + Contig.Length - 1; int LeftFlankStartPos = Row.RepeatLo - g_FlankSize; int LeftFlankBlanks = 0; if (LeftFlankStartPos < ContigFrom) { LeftFlankStartPos = ContigFrom; LeftFlankBlanks = g_FlankSize - (Row.RepeatLo - ContigFrom); } std::string &LeftFlank = AA.LeftFlanks[RowIndex]; for (int i = 0; i < LeftFlankBlanks; ++i) LeftFlank += ' '; for (int Pos = LeftFlankStartPos; Pos < Row.RepeatLo; ++Pos) LeftFlank += g_SeqQ[Pos]; // Repeat std::string &Repeat = AA.Repeats[RowIndex]; for (unsigned Col = 0; Col < ColCount; ++Col) Repeat += Aln.GetChar((unsigned) RowIndex, Col); // Spacer std::string &Spacer = AA.Spacers[RowIndex]; if (RowIndex + 1 == RowCount) { int RightFlankPos = Row.RepeatLo + Row.RepeatLength; int ToPos = RightFlankPos + 9; if (ToPos >= ContigTo) ToPos = ContigTo; for (int Pos = RightFlankPos; Pos <= ToPos; ++Pos) Spacer += g_SeqQ[Pos]; } else { for (int Pos = Hi + 1; Pos < NextLo; ++Pos) Spacer += g_SeqQ[Pos]; } } AA.Pos = Rows[0].RepeatLo; FixBounds(AA); GetConsSeqAA(AA, AA.AlignedConsSeq); AA.ConsSeq.Copy(AA.AlignedConsSeq); StripBlanksAndGaps(AA.ConsSeq); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/writearrays.cpp",".cpp","1057","37","#include ""pilercr.h"" static void WriteArray(FILE *f, const ArrayData &AD) { const int PileIndexCount = (int) AD.PileIndexes.size(); for (int i = 0; i < PileIndexCount; ++i) { int PileIndex = AD.PileIndexes[i]; assert(PileIndex >= 0 && PileIndex < g_PileCount); const PileData &Pile = g_Piles[PileIndex]; char *Label; int Lo = GlobalToLocal(Pile.Lo, &Label); int Hi = Lo + Pile.Hi - Pile.Lo + 1; // GFF Fields are: // [attributes] [comments] // 0 1 2 3 4 5 6 7 8 9 fprintf(f, ""%s\tcrisper\tpile\t%d\t%d\t0\t+\t.\tPile %d ; Array %d\n"", Label, Lo + 1, Hi + 1, PileIndex, AD.Id); } } void WriteArrays(FILE *f, const std::vector &ADVec) { const size_t ArrayCount = ADVec.size(); for (size_t ArrayIndex = 0; ArrayIndex < ArrayCount; ++ArrayIndex) { const ArrayData &AD = *(ADVec[ArrayIndex]); WriteArray(f, AD); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/expandpiles.cpp",".cpp","768","34","#include ""pilercr.h"" static void ExpandPile(int PileIndex) { PileData &Pile = GetModifiablePile(PileIndex); int Pos = Pile.Lo; int ContigIndex = GlobalPosToContigIndex(Pos); assert(ContigIndex >= 0 && ContigIndex < ContigCountQ); const ContigData &Contig = ContigsQ[ContigIndex]; if (Pos < Contig.From || Pos >= Contig.From + Contig.Length) return; int ContigTo = Contig.From + Contig.Length - 1; Pile.Lo -= g_PileExpandMargin; Pile.Hi += g_PileExpandMargin; if (Pile.Lo < Contig.From) Pile.Lo = Contig.From; if (Pile.Hi > ContigTo) Pile.Hi = ContigTo; } void ExpandPiles() { if (g_PileExpandMargin == 0) return; for (int PileIndex = 0; PileIndex < g_PileCount; ++PileIndex) ExpandPile(PileIndex); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/msa.h",".h","5133","149","#ifndef MSA_H #define MSA_H const int MAX_SEQ_NAME = 63; struct PathEdge; class TextFile; class Seq; class ClusterNode; class NodeCounts; class DataBuffer; class MSA { public: MSA(); virtual ~MSA(); public: // Ways to create an MSA void FromFile(TextFile &File); void FromFASTAFile(TextFile &File); void FromSeq(const Seq &s); void ToFile(TextFile &File) const; void ToFASTAFile(TextFile &File) const; void ToMSFFile(TextFile &File, const char *ptrComment = 0) const; void ToAlnFile(TextFile &File) const; void ToHTMLFile(TextFile &File) const; void ToPhySequentialFile(TextFile &File) const; void ToPhyInterleavedFile(TextFile &File) const; void SetSize(unsigned uSeqCount, unsigned uColCount); void SetSeqCount(unsigned uSeqCount); char GetChar(unsigned uSeqIndex, unsigned uIndex) const; unsigned GetLetter(unsigned uSeqIndex, unsigned uIndex) const; unsigned GetLetterEx(unsigned uSeqIndex, unsigned uIndex) const; const char *GetSeqName(unsigned uSeqIndex) const; unsigned GetSeqId(unsigned uSeqIndex) const; unsigned GetSeqIndex(unsigned uId) const; bool GetSeqIndex(unsigned uId, unsigned *ptruIndex) const; double GetOcc(unsigned uColIndex) const; void GetFractionalWeightedCounts(unsigned uColIndex, bool bNormalize, FCOUNT fcCounts[], FCOUNT *ptrfcGapStart, FCOUNT *ptrfcGapEnd, FCOUNT *fcGapExtend, FCOUNT *ptrfOcc, FCOUNT *fcLL, FCOUNT *fcLG, FCOUNT *fcGL, FCOUNT *fcGG) const; bool IsGap(unsigned uSeqIndex, unsigned uColIndex) const; bool IsWildcard(unsigned uSeqIndex, unsigned uColIndex) const; bool IsGapColumn(unsigned uColIndex) const; bool ColumnHasGap(unsigned uColIndex) const; bool IsGapSeq(unsigned uSeqIndex) const; void SetChar(unsigned uSeqIndex, unsigned uColIndex, char c); void SetSeqName(unsigned uSeqIndex, const char szName[]); void SetSeqId(unsigned uSeqIndex, unsigned uId); bool HasGap() const; bool IsLegalLetter(unsigned uLetter) const; void GetSeq(unsigned uSeqIndex, Seq &seq) const; void Copy(const MSA &msa); double GetCons(unsigned uColIndex) const; double GetAvgCons() const; double GetPctIdentityPair(unsigned uSeqIndex1, unsigned uSeqIndex2) const; bool GetSeqIndex(const char *ptrSeqName, unsigned *ptruSeqIndex) const; void DeleteCol(unsigned uColIndex); void DeleteColumns(unsigned uColIndex, unsigned uColCount); void CopySeq(unsigned uToSeqIndex, const MSA &msaFrom, unsigned uFromSeqIndex); void DeleteSeq(unsigned uSeqIndex); // void DeleteEmptyCols(bool bProgress = false); bool IsEmptyCol(unsigned uColIndex) const; unsigned GetGCGCheckSum(unsigned uSeqIndex) const; unsigned UniqueResidueTypes(unsigned uColIndex) const; void GetNodeCounts(unsigned uAlignedColIndex, NodeCounts &Counts) const; void ValidateBreakMatrices() const; unsigned GetCharCount(unsigned uSeqIndex, unsigned uColIndex) const; const char *GetSeqBuffer(unsigned uSeqIndex) const; unsigned AlignedColIndexToColIndex(unsigned uAlignedColIndex) const; unsigned GetSeqLength(unsigned uSeqIndex) const; void GetPWID(unsigned uSeqIndex1, unsigned uSeqIndex2, double *ptrdPWID, unsigned *ptruPosCount) const; void GetPairMap(unsigned uSeqIndex1, unsigned uSeqIndex2, int iMap1[], int iMap2[]) const; void LogMe() const; void GapInfoToDataBuffer(DataBuffer &Buffer) const; void GapInfoFromDataBuffer(const DataBuffer &Buffer); double GetPctGroupIdentityPair(unsigned uSeqIndex1, unsigned uSeqIndex2) const; void Clear() { Free(); } unsigned GetSeqCount() const { return m_uSeqCount; } unsigned GetColCount() const { return m_uColCount; } static bool SeqsEq(const MSA &a1, unsigned uSeqIndex1, const MSA &a2, unsigned uSeqIndex2); static void SetIdCount(unsigned uIdCount); private: void Free(); void AppendSeq(char *ptrSeq, unsigned uSeqLength, char *ptrLabel); void ExpandCache(unsigned uSeqCount, unsigned uColCount); void GetNameFromFASTAAnnotationLine(const char szLine[], char szName[], unsigned uBytes); void CopyCol(unsigned uFromCol, unsigned uToCol); private: unsigned m_uSeqCount; unsigned m_uColCount; unsigned m_uCacheSeqLength; unsigned m_uCacheSeqCount; char **m_szSeqs; char **m_szNames; static unsigned m_uIdCount; unsigned *m_IdToSeqIndex; unsigned *m_SeqIndexToId; }; void SeqVectFromMSA(const MSA &msa, SeqVect &v); void DeleteGappedCols(MSA &msa); void MSAFromColRange(const MSA &msaIn, unsigned uFromColIndex, unsigned uColCount, MSA &msaOut); void MSACat(const MSA &msa1, const MSA &msa2, MSA &msaCat); void MSAAppend(MSA &msa1, const MSA &msa2); void MSAFromSeqSubset(const MSA &msaIn, const unsigned uSeqIndexes[], unsigned uSeqCount, MSA &msaOut); void AssertMSAEq(const MSA &msa1, const MSA &msa2); void AssertMSAEqIgnoreCaseAndGaps(const MSA &msa1, const MSA &msa2); void MSASubsetByIds(const MSA &msaIn, const unsigned Ids[], unsigned uIdCount, MSA &msaOut); void SetMSAWeightsMuscle(MSA &msa); void SetClustalWWeightsMuscle(MSA &msa); void SetThreeWayWeightsMuscle(MSA &msa); #endif // MSA_H ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/savefhits.cpp",".cpp","134","7","#include ""pilercr.h"" void SaveFilterHits(const FilterHit *FHits, int FHitCount) { Quit(""SaveFilterHits not implemented""); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/utils_win32.cpp",".cpp","698","38","#include ""pilercr.h"" #if WIN32 #include #include double GetRAMSize() { MEMORYSTATUS MS; GlobalMemoryStatus(&MS); double m = (double) MS.dwTotalPhys; if (m > 1.8e9) m = 1.8e9; return (unsigned) m; } static unsigned g_uPeakMemUseBytes; unsigned GetPeakMemUseBytes() { return g_uPeakMemUseBytes; } unsigned GetMemUseBytes() { HANDLE hProc = GetCurrentProcess(); PROCESS_MEMORY_COUNTERS PMC; BOOL bOk = GetProcessMemoryInfo(hProc, &PMC, sizeof(PMC)); if (!bOk) return 1000000; unsigned uBytes = (unsigned) PMC.WorkingSetSize; if (uBytes > g_uPeakMemUseBytes) g_uPeakMemUseBytes = uBytes; return uBytes; } #endif ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/getconsaa.cpp",".cpp","1463","84","#include ""pilercr.h"" const int *GetCountsAA(const ArrayAln &AA, int ColIndex) { static int Counts[5]; const size_t RepeatCount = AA.Repeats.size(); for (int i = 0; i < 5; ++i) Counts[i] = 0; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { const std::string &Repeat = AA.Repeats[RepeatIndex]; assert(ColIndex >= 0 && ColIndex < (int) Repeat.size()); char c = Repeat[ColIndex]; switch (toupper(c)) { case 'A': ++(Counts[0]); break; case 'C': ++(Counts[1]); break; case 'G': ++(Counts[2]); break; case 'T': ++(Counts[3]); break; case '-': ++(Counts[4]); break; } } return Counts; } void GetConsSeqAA(const ArrayAln &AA, Seq &ConsSeq) { ConsSeq.clear(); ConsSeq.SetName(""cons""); size_t ColCount = AA.Repeats[0].size(); for (size_t ColIndex = 0; ColIndex < ColCount; ++ColIndex) { const int *Counts = GetCountsAA(AA, (int) ColIndex); int MaxCount = 0; int MaxLetter = 0; for (int i = 0; i < 5; ++i) { if (Counts[i] > MaxCount) { MaxCount = Counts[i]; MaxLetter = i; } } char c = '?'; switch (MaxLetter) { case 0: c = 'A'; break; case 1: c = 'C'; break; case 2: c = 'G'; break; case 3: c = 'T'; break; case 4: c = '-'; break; default: Quit(""Bad maxletter""); } ConsSeq.push_back(c); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/progaln.cpp",".cpp","4921","185","#include ""multaln.h"" #define TRACE 0 #define VALIDATE 0 #define TRACE_LENGTH_DELTA 0 static bool g_bVerbose = false; static void LogLeafNames(const Tree &tree, unsigned uNodeIndex) { const unsigned uNodeCount = tree.GetNodeCount(); unsigned *Leaves = new unsigned[uNodeCount]; unsigned uLeafCount; GetLeaves(tree, uNodeIndex, Leaves, &uLeafCount); for (unsigned i = 0; i < uLeafCount; ++i) { if (i > 0) Log("",""); Log(""%s"", tree.GetLeafName(Leaves[i])); } delete[] Leaves; } void ProgressiveAlign(const SeqVect &Seqs, const Tree &GuideTree, MSA &Aln) { assert(Seqs.GetSeqCount() > 0); assert(GuideTree.IsRooted()); #if TRACE Log(""GuideTree:\n""); GuideTree.LogMe(); #endif const unsigned uSeqCount = Seqs.Length(); const unsigned uNodeCount = 2*uSeqCount - 1; const unsigned uIterCount = uSeqCount - 1; ProgNode *ProgNodes = new ProgNode[uNodeCount]; unsigned uJoin = 0; unsigned uTreeNodeIndex = GuideTree.FirstDepthFirstNode(); do { if (GuideTree.IsLeaf(uTreeNodeIndex)) { if (uTreeNodeIndex >= uNodeCount) Quit(""TreeNodeIndex=%u NodeCount=%u\n"", uTreeNodeIndex, uNodeCount); ProgNode &Node = ProgNodes[uTreeNodeIndex]; unsigned uId = GuideTree.GetLeafId(uTreeNodeIndex); if (uId >= uSeqCount) Quit(""Seq index out of range""); const Seq &s = *(Seqs[uId]); Node.m_MSA.FromSeq(s); Node.m_MSA.SetSeqId(0, uId); Node.m_uLength = Node.m_MSA.GetColCount(); // TODO: Term gaps settable Node.m_Prof = ProfileFromMSA(Node.m_MSA); Node.m_EstringL = 0; Node.m_EstringR = 0; #if TRACE Log(""Leaf id=%u\n"", uId); Log(""MSA=\n""); Node.m_MSA.LogMe(); Log(""Profile (from MSA)=\n""); ListProfile(Node.m_Prof, Node.m_uLength, &Node.m_MSA); #endif } else { ++uJoin; const unsigned uMergeNodeIndex = uTreeNodeIndex; ProgNode &Parent = ProgNodes[uMergeNodeIndex]; const unsigned uLeft = GuideTree.GetLeft(uTreeNodeIndex); const unsigned uRight = GuideTree.GetRight(uTreeNodeIndex); if (g_bVerbose) { Log(""Align: (""); LogLeafNames(GuideTree, uLeft); Log("") (""); LogLeafNames(GuideTree, uRight); Log("")\n""); } ProgNode &Node1 = ProgNodes[uLeft]; ProgNode &Node2 = ProgNodes[uRight]; #if TRACE Log(""AlignTwoMSAs:\n""); #endif AlignProfiles(Node1.m_Prof, Node1.m_uLength, Node2.m_Prof, Node2.m_uLength, Parent.m_Path, &Parent.m_Prof, &Parent.m_uLength); #if TRACE_LENGTH_DELTA { unsigned L = Node1.m_uLength; unsigned R = Node2.m_uLength; unsigned P = Parent.m_Path.GetEdgeCount(); unsigned Max = L > R ? L : R; unsigned d = P - Max; Log(""LD%u;%u;%u;%u\n"", L, R, P, d); } #endif PathToEstrings(Parent.m_Path, &Parent.m_EstringL, &Parent.m_EstringR); #if VALIDATE { #if TRACE Log(""AlignTwoMSAs:\n""); #endif PWPath TmpPath; AlignTwoMSAs(Node1.m_MSA, Node2.m_MSA, Parent.m_MSA, TmpPath); ProfPos *P1 = ProfileFromMSA(Node1.m_MSA, true); ProfPos *P2 = ProfileFromMSA(Node2.m_MSA, true); unsigned uLength = Parent.m_MSA.GetColCount(); ProfPos *TmpProf = ProfileFromMSA(Parent.m_MSA, true); #if TRACE Log(""Node1 MSA=\n""); Node1.m_MSA.LogMe(); Log(""Node1 prof=\n""); ListProfile(Node1.m_Prof, Node1.m_MSA.GetColCount(), &Node1.m_MSA); Log(""Node1 prof (from MSA)=\n""); ListProfile(P1, Node1.m_MSA.GetColCount(), &Node1.m_MSA); AssertProfsEq(Node1.m_Prof, Node1.m_uLength, P1, Node1.m_MSA.GetColCount()); Log(""Node2 prof=\n""); ListProfile(Node2.m_Prof, Node2.m_MSA.GetColCount(), &Node2.m_MSA); Log(""Node2 MSA=\n""); Node2.m_MSA.LogMe(); Log(""Node2 prof (from MSA)=\n""); ListProfile(P2, Node2.m_MSA.GetColCount(), &Node2.m_MSA); AssertProfsEq(Node2.m_Prof, Node2.m_uLength, P2, Node2.m_MSA.GetColCount()); TmpPath.AssertEqual(Parent.m_Path); Log(""Parent MSA=\n""); Parent.m_MSA.LogMe(); Log(""Parent prof=\n""); ListProfile(Parent.m_Prof, Parent.m_uLength, &Parent.m_MSA); Log(""Parent prof (from MSA)=\n""); ListProfile(TmpProf, Parent.m_MSA.GetColCount(), &Parent.m_MSA); #endif // TRACE AssertProfsEq(Parent.m_Prof, Parent.m_uLength, TmpProf, Parent.m_MSA.GetColCount()); delete[] P1; delete[] P2; delete[] TmpProf; } #endif // VALIDATE Node1.m_MSA.Clear(); Node2.m_MSA.Clear(); delete[] Node1.m_Prof; delete[] Node2.m_Prof; Node1.m_Prof = 0; Node2.m_Prof = 0; } uTreeNodeIndex = GuideTree.NextDepthFirstNode(uTreeNodeIndex); } while (NULL_NEIGHBOR != uTreeNodeIndex); MakeRootMSA(Seqs, GuideTree, ProgNodes, Aln); delete[] ProgNodes; #if VALIDATE { unsigned uRootNodeIndex = GuideTree.GetRootNodeIndex(); const ProgNode &RootProgNode = ProgNodes[uRootNodeIndex]; AssertMSAEq(Aln, RootProgNode.m_MSA); } #endif } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/upgma.cpp",".cpp","9865","367","#include ""multaln.h"" // UPGMA clustering in O(N^2) time and space. #define TRACE 0 #define MIN(x, y) ((x) < (y) ? (x) : (y)) #define MAX(x, y) ((x) > (y) ? (x) : (y)) #define AVG(x, y) (((x) + (y))/2) static unsigned g_uLeafCount; static unsigned g_uTriangleSize; static unsigned g_uInternalNodeCount; static unsigned g_uInternalNodeIndex; // Triangular distance matrix is g_Dist, which is allocated // as a one-dimensional vector of length g_uTriangleSize. // TriangleSubscript(i,j) maps row,column=i,j to the subscript // into this vector. // Row / column coordinates are a bit messy. // Initially they are leaf indexes 0..N-1. // But each time we create a new node (=new cluster, new subtree), // we re-use one of the two rows that become available (the children // of the new node). This saves memory. // We keep track of this through the g_uNodeIndex vector. static dist_t *g_Dist; // Distance to nearest neighbor in row i of distance matrix. // Subscript is distance matrix row. static dist_t *g_MinDist; // Nearest neighbor to row i of distance matrix. // Subscript is distance matrix row. static unsigned *g_uNearestNeighbor; // Node index of row i in distance matrix. // Node indexes are 0..N-1 for leaves, N..2N-2 for internal nodes. // Subscript is distance matrix row. static unsigned *g_uNodeIndex; // The following vectors are defined on internal nodes, // subscripts are internal node index 0..N-2. // For g_uLeft/Right, value is the node index 0 .. 2N-2 // because a child can be internal or leaf. static unsigned *g_uLeft; static unsigned *g_uRight; static dist_t *g_Height; static dist_t *g_LeftLength; static dist_t *g_RightLength; static inline unsigned TriangleSubscript(unsigned uIndex1, unsigned uIndex2) { #if DEBUG if (uIndex1 >= g_uLeafCount || uIndex2 >= g_uLeafCount) Quit(""TriangleSubscript(%u,%u) %u"", uIndex1, uIndex2, g_uLeafCount); #endif unsigned v; if (uIndex1 >= uIndex2) v = uIndex2 + (uIndex1*(uIndex1 - 1))/2; else v = uIndex1 + (uIndex2*(uIndex2 - 1))/2; assert(v < (g_uLeafCount*(g_uLeafCount - 1))/2); return v; } static void ListState() { Log(""Dist matrix\n""); Log("" ""); for (unsigned i = 0; i < g_uLeafCount; ++i) { if (uInsane == g_uNodeIndex[i]) continue; Log("" %5u"", g_uNodeIndex[i]); } Log(""\n""); for (unsigned i = 0; i < g_uLeafCount; ++i) { if (uInsane == g_uNodeIndex[i]) continue; Log(""%5u "", g_uNodeIndex[i]); for (unsigned j = 0; j < g_uLeafCount; ++j) { if (uInsane == g_uNodeIndex[j]) continue; if (i == j) Log("" ""); else { unsigned v = TriangleSubscript(i, j); Log(""%5.2g "", g_Dist[v]); } } Log(""\n""); } Log(""\n""); Log("" i Node NrNb Dist\n""); Log(""----- ----- ----- --------\n""); for (unsigned i = 0; i < g_uLeafCount; ++i) { if (uInsane == g_uNodeIndex[i]) continue; Log(""%5u %5u %5u %8.3f\n"", i, g_uNodeIndex[i], g_uNearestNeighbor[i], g_MinDist[i]); } Log(""\n""); Log("" Node L R Height LLength RLength\n""); Log(""----- ----- ----- ------ ------- -------\n""); for (unsigned i = 0; i <= g_uInternalNodeIndex; ++i) Log(""%5u %5u %5u %6.2g %6.2g %6.2g\n"", i, g_uLeft[i], g_uRight[i], g_Height[i], g_LeftLength[i], g_RightLength[i]); } void UPGMA(const DistCalc &DC, Tree &tree) { g_uLeafCount = DC.GetCount(); g_uTriangleSize = (g_uLeafCount*(g_uLeafCount - 1))/2; g_uInternalNodeCount = g_uLeafCount - 1; g_Dist = new dist_t[g_uTriangleSize]; g_uNodeIndex = new unsigned[g_uLeafCount]; g_uNearestNeighbor = new unsigned[g_uLeafCount]; g_MinDist = new dist_t[g_uLeafCount]; unsigned *Ids = new unsigned [g_uLeafCount]; char **Names = new char *[g_uLeafCount]; g_uLeft = new unsigned[g_uInternalNodeCount]; g_uRight = new unsigned[g_uInternalNodeCount]; g_Height = new dist_t[g_uInternalNodeCount]; g_LeftLength = new dist_t[g_uInternalNodeCount]; g_RightLength = new dist_t[g_uInternalNodeCount]; for (unsigned i = 0; i < g_uLeafCount; ++i) { g_MinDist[i] = BIG_DIST; g_uNodeIndex[i] = i; g_uNearestNeighbor[i] = uInsane; Ids[i] = DC.GetId(i); Names[i] = strsave(DC.GetName(i)); } for (unsigned i = 0; i < g_uInternalNodeCount; ++i) { g_uLeft[i] = uInsane; g_uRight[i] = uInsane; g_LeftLength[i] = BIG_DIST; g_RightLength[i] = BIG_DIST; g_Height[i] = BIG_DIST; } // Compute initial NxN triangular distance matrix. // Store minimum distance for each full (not triangular) row. // Loop from 1, not 0, because ""row"" is 0, 1 ... i-1, // so nothing to do when i=0. for (unsigned i = 1; i < g_uLeafCount; ++i) { dist_t *Row = g_Dist + TriangleSubscript(i, 0); DC.CalcDistRange(i, Row); for (unsigned j = 0; j < i; ++j) { const dist_t d = Row[j]; if (d < g_MinDist[i]) { g_MinDist[i] = d; g_uNearestNeighbor[i] = j; } if (d < g_MinDist[j]) { g_MinDist[j] = d; g_uNearestNeighbor[j] = i; } } } #if TRACE Log(""Initial state:\n""); ListState(); #endif for (g_uInternalNodeIndex = 0; g_uInternalNodeIndex < g_uLeafCount - 1; ++g_uInternalNodeIndex) { #if TRACE Log(""\n""); Log(""Internal node index %5u\n"", g_uInternalNodeIndex); Log(""-------------------------\n""); #endif // Find nearest neighbors unsigned Lmin = uInsane; unsigned Rmin = uInsane; dist_t dtMinDist = BIG_DIST; for (unsigned j = 0; j < g_uLeafCount; ++j) { if (uInsane == g_uNodeIndex[j]) continue; dist_t d = g_MinDist[j]; if (d < dtMinDist) { dtMinDist = d; Lmin = j; Rmin = g_uNearestNeighbor[j]; assert(uInsane != Rmin); assert(uInsane != g_uNodeIndex[Rmin]); } } assert(Lmin != uInsane); assert(Rmin != uInsane); assert(dtMinDist != BIG_DIST); #if TRACE Log(""Nearest neighbors Lmin %u[=%u] Rmin %u[=%u] dist %.3g\n"", Lmin, g_uNodeIndex[Lmin], Rmin, g_uNodeIndex[Rmin], dtMinDist); #endif // Compute distances to new node // New node overwrites row currently assigned to Lmin dist_t dtNewMinDist = BIG_DIST; unsigned uNewNearestNeighbor = uInsane; for (unsigned j = 0; j < g_uLeafCount; ++j) { if (j == Lmin || j == Rmin) continue; if (uInsane == g_uNodeIndex[j]) continue; const unsigned vL = TriangleSubscript(Lmin, j); const unsigned vR = TriangleSubscript(Rmin, j); const dist_t dL = g_Dist[vL]; const dist_t dR = g_Dist[vR]; dist_t dtNewDist; // Minimum linkage dtNewDist = MIN(dL, dR); // Nasty special case. // If nearest neighbor of j is Lmin or Rmin, then make the new // node (which overwrites the row currently occupied by Lmin) // the nearest neighbor. This situation can occur when there are // equal distances in the matrix. If we don't make this fix, // the nearest neighbor pointer for j would become invalid. // (We don't need to test for == Lmin, because in that case // the net change needed is zero due to the change in row // numbering). if (g_uNearestNeighbor[j] == Rmin) g_uNearestNeighbor[j] = Lmin; #if TRACE Log(""New dist to %u = (%u/%.3g + %u/%.3g)/2 = %.3g\n"", j, Lmin, dL, Rmin, dR, dtNewDist); #endif g_Dist[vL] = dtNewDist; if (dtNewDist < dtNewMinDist) { dtNewMinDist = dtNewDist; uNewNearestNeighbor = j; } } assert(g_uInternalNodeIndex < g_uLeafCount - 1 || BIG_DIST != dtNewMinDist); assert(g_uInternalNodeIndex < g_uLeafCount - 1 || uInsane != uNewNearestNeighbor); const unsigned v = TriangleSubscript(Lmin, Rmin); const dist_t dLR = g_Dist[v]; const dist_t dHeightNew = dLR/2; const unsigned uLeft = g_uNodeIndex[Lmin]; const unsigned uRight = g_uNodeIndex[Rmin]; const dist_t HeightLeft = uLeft < g_uLeafCount ? 0 : g_Height[uLeft - g_uLeafCount]; const dist_t HeightRight = uRight < g_uLeafCount ? 0 : g_Height[uRight - g_uLeafCount]; g_uLeft[g_uInternalNodeIndex] = uLeft; g_uRight[g_uInternalNodeIndex] = uRight; g_LeftLength[g_uInternalNodeIndex] = dHeightNew - HeightLeft; g_RightLength[g_uInternalNodeIndex] = dHeightNew - HeightRight; g_Height[g_uInternalNodeIndex] = dHeightNew; // Row for left child overwritten by row for new node g_uNodeIndex[Lmin] = g_uLeafCount + g_uInternalNodeIndex; g_uNearestNeighbor[Lmin] = uNewNearestNeighbor; g_MinDist[Lmin] = dtNewMinDist; // Delete row for right child g_uNodeIndex[Rmin] = uInsane; #if TRACE Log(""\nInternalNodeIndex=%u Lmin=%u Rmin=%u\n"", g_uInternalNodeIndex, Lmin, Rmin); ListState(); #endif } unsigned uRoot = g_uLeafCount - 2; tree.Create(g_uLeafCount, uRoot, g_uLeft, g_uRight, g_LeftLength, g_RightLength, Ids, Names); #if TRACE tree.LogMe(); #endif delete[] g_Dist; delete[] g_uNodeIndex; delete[] g_uNearestNeighbor; delete[] g_MinDist; delete[] g_Height; delete[] g_uLeft; delete[] g_uRight; delete[] g_LeftLength; delete[] g_RightLength; for (unsigned i = 0; i < g_uLeafCount; ++i) free(Names[i]); delete[] Names; delete[] Ids; } class DistCalcTest : public DistCalc { virtual void CalcDistRange(unsigned i, dist_t Dist[]) const { static dist_t TestDist[5][5] = { 0, 2, 14, 14, 20, 2, 0, 14, 14, 20, 14, 14, 0, 4, 20, 14, 14, 4, 0, 20, 20, 20, 20, 20, 0, }; for (unsigned j = 0; j < i; ++j) Dist[j] = TestDist[i][j]; } virtual unsigned GetCount() const { return 5; } virtual unsigned GetId(unsigned i) const { return i; } virtual const char *GetName(unsigned i) const { return ""name""; } }; ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/findpiles.cpp",".cpp","2395","106","#include ""pilercr.h"" #define TRACE 0 void LogImage(const ImageData &Image) { Log(""Lo=%d Hi=%d Len=%d Hit=%d %c"", Image.Lo, Image.Hi, Image.Hi - Image.Lo + 1, Image.HitIndex, Image.IsA ? 'A' : 'B'); } // Requires sorted hits as input void FindPiles() { g_HitIndexToPileIndexA.clear(); g_HitIndexToPileIndexB.clear(); g_Piles.clear(); if (g_ImageCount == 0) return; // Just for speed. g_ImageCount/4 is arbitrary guess. g_Piles.reserve(g_ImageCount/4); // Maps aLo-aHi segment of hit to pile. g_HitCount = g_ImageCount/2; g_HitIndexToPileIndexA.resize(g_HitCount); g_HitIndexToPileIndexB.resize(g_HitCount); int PileIndex = 0; const ImageData &FirstImage = g_Images[0]; PileData Pile; Pile.Lo = FirstImage.Lo; Pile.Hi = FirstImage.Hi; Pile.Deleted = false; if (FirstImage.IsA) { g_HitIndexToPileIndexA[FirstImage.HitIndex] = 0; Pile.HitIndexes.push_back(FirstImage.HitIndex); } else g_HitIndexToPileIndexB[FirstImage.HitIndex] = 0; #if TRACE Log(""Image 0 =""); LogImage(FirstImage); Log(""\n""); #endif for (int ImageIndex = 1; ImageIndex < g_ImageCount; ++ImageIndex) { const ImageData &Image = g_Images[ImageIndex]; #if TRACE Log(""Pile Lo=%d Hi=%d Image%d "", Pile.Lo, Pile.Hi, ImageIndex); LogImage(Image); Log(""\n""); #endif if (Image.Lo > Pile.Hi) { #if DEBUG // Hack to validate coords GlobalPosToContig(Pile.Lo); GlobalPosToContig(Pile.Hi); #endif g_Piles.push_back(Pile); #if TRACE Log(""Image.Lo > Pile.Hi\n""); Log("" New pile ""); ++g_PileCount; LogPile(PileIndex); Log(""\n""); #endif Pile.Lo = Image.Lo; Pile.Hi = Image.Hi; Pile.HitIndexes.clear(); ++PileIndex; } else Pile.Hi = Image.Hi; if (Image.IsA) { g_HitIndexToPileIndexA[Image.HitIndex] = PileIndex; Pile.HitIndexes.push_back(Image.HitIndex); } else g_HitIndexToPileIndexB[Image.HitIndex] = PileIndex; } #if DEBUG // Hack to validate coords GlobalPosToContig(Pile.Lo); GlobalPosToContig(Pile.Hi); #endif g_Piles.push_back(Pile); g_PileCount = (int) g_Piles.size(); int SizeA = (int) g_HitIndexToPileIndexA.size(); int SizeB = (int) g_HitIndexToPileIndexB.size(); if (SizeA != g_HitCount || SizeB != g_HitCount) Quit(""SizeA=%d SizeB=%d != HitCount=%d"", SizeA, SizeB, g_HitCount); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/getsubseq.cpp",".cpp","145","9","#include ""pilercr.h"" void GetSubseq(int Lo, int Hi, Seq &s) { s.clear(); for (int i = Lo; i <= Hi; ++i) s.push_back(g_SeqQ[i]); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/options.cpp",".cpp","5741","223","#include ""pilercr.h"" struct VALUE_OPT { const char *m_pstrName; const char *m_pstrValue; }; struct FLAG_OPT { const char *m_pstrName; bool m_bSet; }; static VALUE_OPT ValueOpts[] = { ""in"", 0, ""minhitlength"", 0, ""minid"", 0, ""maxmem"", 0, ""log"", 0, ""loga"", 0, ""out"", 0, ""hits"", 0, ""discardedhits"", 0, ""piles"", 0, ""filterout"", 0, ""diameter"", 0, ""traps"", 0, ""fhits"", 0, ""seq"", 0, ""cmp"", 0, ""ref"", 0, ""minrepeat"", 0, ""maxrepeat"", 0, ""minspacer"", 0, ""maxspacer"", 0, ""minrepeatratio"", 0, ""minspacerratio"", 0, ""minarray"", 0, ""mincons"", 0, }; static int ValueOptCount = sizeof(ValueOpts)/sizeof(ValueOpts[0]); static FLAG_OPT FlagOpts[] = { ""quiet"", 0, ""version"", 0, ""help"", 0, ""options"", 0, ""loghits"", 0, ""logtraps"", 0, ""showhits"", 0, ""loghits"", 0, ""logimages"", 0, ""logalns"", 0, ""noinfo"", 0, ""segv"", 0, ""trimseqs"", 0, }; static int FlagOptCount = sizeof(FlagOpts)/sizeof(FlagOpts[0]); void CommandLineError(const char *Format, ...) { va_list ArgList; va_start(ArgList, Format); char Str[4096]; vsprintf(Str, Format, ArgList); Usage(); fprintf(stderr, ""\n*** Invalid command line ***\n""); fprintf(stderr, ""%s\n"", Str); exit(1); } static bool TestSetFlagOpt(const char *Arg) { for (int i = 0; i < FlagOptCount; ++i) if (!stricmp(Arg, FlagOpts[i].m_pstrName)) { FlagOpts[i].m_bSet = true; return true; } return false; } static bool TestSetValueOpt(const char *Arg, const char *Value) { for (int i = 0; i < ValueOptCount; ++i) if (!stricmp(Arg, ValueOpts[i].m_pstrName)) { if (0 == Value) CommandLineError(""Option -%s must have value\n"", Arg); ValueOpts[i].m_pstrValue = strsave(Value); return true; } return false; } bool FlagOpt(const char *Name) { for (int i = 0; i < FlagOptCount; ++i) if (!stricmp(Name, FlagOpts[i].m_pstrName)) return FlagOpts[i].m_bSet; Quit(""FlagOpt(%s) invalid"", Name); return false; } const char *ValueOpt(const char *Name) { for (int i = 0; i < ValueOptCount; ++i) if (!stricmp(Name, ValueOpts[i].m_pstrName)) return ValueOpts[i].m_pstrValue; Quit(""ValueOpt(%s) invalid"", Name); return 0; } const char *RequiredValueOpt(const char *Name) { const char *s = ValueOpt(Name); if (0 == s) CommandLineError(""Required option -%s not specified\n"", Name); return s; } void ProcessArgVect(int argc, char *argv[]) { if (argc == 0) { Usage(); exit(0); } if (argc == 1) { if (strcmp(""-help"", argv[0]) == 0 || strcmp(""--help"", argv[0]) == 0) { Usage(); exit(0); } } for (int iArgIndex = 0; iArgIndex < argc; ) { const char *Arg = argv[iArgIndex]; if (Arg[0] != '-') Quit(""Command-line option \""%s\"" must start with '-'\n"", Arg); const char *ArgName = Arg + 1; if (TestSetFlagOpt(ArgName)) { ++iArgIndex; continue; } char *Value = 0; if (iArgIndex < argc - 1) Value = argv[iArgIndex+1]; if (TestSetValueOpt(ArgName, Value)) { iArgIndex += 2; continue; } CommandLineError(""Invalid command line option \""%s\""\n"", ArgName); } } void IntOpt(const char *Name, int *ptrValue) { const char *strValue = ValueOpt(Name); if (strValue != 0) *ptrValue = atoi(strValue); } void FloatOpt(const char *Name, double *ptrValue) { const char *strValue = ValueOpt(Name); if (strValue != 0) *ptrValue = atof(strValue); } void Options() { fprintf(stderr, ""\n"" ""\n"" ""Basic options:\n"" "" -in Sequence file to analyze (FASTA format).\n"" "" -out Report file name (plain text).\n"" "" -seq Save consensus sequences to this FASTA file.\n"" "" -trimseqs Eliminate similar seqs from -seq file.\n"" "" -noinfo Don't write help to report file.\n"" "" -quiet Don't write progress messages to stderr.\n"" ""\n"" ""Criteria for CRISPR detection, defaults in parentheses:\n"" "" -minarray Must be at least repeats in array (3).\n"" "" -mincons Minimum conservation (0.9).\n"" "" At least N repeats must have identity\n"" "" >= F with the consensus sequence.\n"" "" Value is in range 0 .. 1.0.\n"" "" It is recommended to use a value < 1.0\n"" "" because using 1.0 may suppress true\n"" "" arrays due to boundary misidentification.\n"" "" -minrepeat Minimum repeat length (16).\n"" "" -maxrepeat Maximum repeat length (64).\n"" "" -minspacer Minimum spacer length (8).\n"" "" -maxspacer Maximum spacer length (64).\n"" "" -minrepeatratio Minimum repeat ratio (0.9).\n"" "" -minspacerratio Minimum spacer ratio (0.75).\n"" "" 'Ratios' are defined as minlength / maxlength,\n"" "" thus a value close to 1.0 requires lengths to\n"" "" be similar, 1.0 means identical lengths.\n"" "" Spacer lengths sometimes vary significantly, so\n"" "" the default ratio is smaller. As with -mincons,\n"" "" using 1.0 is not recommended.\n"" ""\n"" ""Parameters for creating local alignments:\n"" "" -minhitlength Minimum alignment length (16).\n"" "" -minid Minimum identity (0.94).\n"" ""\n"" ""\n"" ); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/getarraydata.cpp",".cpp","1702","83","#include ""pilercr.h"" static bool PileByPos(int PileIndex1, int PileIndex2) { return GetPile(PileIndex1).Lo < GetPile(PileIndex2).Lo; } bool GetArrayData(const IntVec &ArrayPileIndexes, ArrayData &AD) { if (ArrayPileIndexes.size() == 0) Quit(""GetArrayData, size=0""); #if TRACE Log(""\n""); Log(""Array\n""); Log(""=====\n""); #endif for_CIntVec(ArrayPileIndexes, p) AD.PileIndexes.push_back(*p); // Sort by position std::sort(AD.PileIndexes.begin(), AD.PileIndexes.end(), PileByPos); SeqVect Seqs; int Lo = -1; int Hi = -1; for_CIntVec(ArrayPileIndexes, p) { int PileIndex = *p; Seq *s = new Seq; PileToSeq(g_Piles, PileIndex, *s, &Lo, &Hi); if (Seqs.size() == 0) AD.Lo = Lo; Seqs.push_back(s); } MSA Aln; MultipleAlign(Seqs, Aln); int StartCol; int EndCol; double MinCons = g_DraftMinCons; const int SeqCount = (int) Aln.GetSeqCount(); if (SeqCount >= g_MinOneDiff) { double AltMinCons = ((double) (SeqCount - 1) / (double) SeqCount) - 0.1; if (AltMinCons < MinCons) MinCons = AltMinCons; } GetConsSeq(Aln, MinCons, &StartCol, &EndCol, AD.ConsSeq); if ((int) AD.ConsSeq.Length() < g_DraftMinRepeatLength) return false; char Label[128]; sprintf(Label, ""Cons%d"", AD.Id); AD.ConsSeq.SetName(Label); AD.ConsSeq.SetId(0); AD.RepeatLength = AD.ConsSeq.Length(); AD.SpacerLength = -1; if (g_LogAlns) { Log(""\n""); Log(""Draft alignment for array %d:\n"", AD.Id); Aln.LogMe(); Log(""\n""); Log(""Consensus: ""); AD.ConsSeq.LogMeSeqOnly(); Log(""\n""); Log(""\n""); } #if TRACE Aln.LogMe(); AD.ConsSeq.LogMe(); Log(""\n""); #endif return true; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/usage.cpp",".cpp","828","30","#include ""pilercr.h"" void Credits() { static bool Displayed = false; if (Displayed) return; fprintf(stderr, ""\n"" PILERCR_LONG_VERSION ""\n""); fprintf(stderr, ""http://www.drive5.com/piler\n""); fprintf(stderr, ""Written by Robert C. Edgar\n""); fprintf(stderr, ""This software is donated to the public domain.\n""); fprintf(stderr, ""Please visit web site for requested citation.\n\n""); Displayed = true; } void Usage() { Credits(); fprintf(stderr, ""\n""); fprintf(stderr, ""Basic usage:\n""); fprintf(stderr, ""\n""); fprintf(stderr, "" pilercr -in -out \n""); fprintf(stderr, ""\n""); fprintf(stderr, ""Sequence file is in FASTA format.\n""); fprintf(stderr, ""\n""); fprintf(stderr, ""For advanced options, type pilercr -options.\n""); fprintf(stderr, ""\n""); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/utils_linux.cpp",".cpp","1425","80","#include ""pilercr.h"" #if linux || __linux__ #include #include #include #include #include #include double GetRAMSize() { const double DEFAULT_RAM = 1e9; static double RAMMB = 0; if (RAMMB != 0) return RAMMB; int fd = open(""/proc/meminfo"", O_RDONLY); if (-1 == fd) return DEFAULT_RAM; char Buffer[128]; int n = read(fd, Buffer, sizeof(Buffer) - 1); close(fd); fd = -1; if (n <= 0) return DEFAULT_RAM; Buffer[n] = 0; char *pMem = strstr(Buffer, ""Mem: ""); if (0 == pMem) return DEFAULT_RAM; int Bytes = atoi(pMem+4); double m = Bytes; if (m > 1.8e9) m = 1.8e9; return m; } static unsigned g_uPeakMemUseBytes; unsigned GetPeakMemUseBytes() { return g_uPeakMemUseBytes; } unsigned GetMemUseBytes() { static char statm[64]; static int PageSize; if (0 == statm[0]) { PageSize = sysconf(_SC_PAGESIZE); pid_t pid = getpid(); sprintf(statm, ""/proc/%d/statm"", (int) pid); } int fd = open(statm, O_RDONLY); if (-1 == fd) return 1000000; char Buffer[64]; int n = read(fd, Buffer, sizeof(Buffer) - 1); close(fd); fd = -1; if (n <= 0) return 1000000; Buffer[n] = 0; int Pages = atoi(Buffer); unsigned uBytes = Pages*PageSize; if (uBytes > g_uPeakMemUseBytes) g_uPeakMemUseBytes = uBytes; return uBytes; } #endif ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/estring.cpp",".cpp","12119","638","#include ""multaln.h"" /*** An ""estring"" is an edit string that operates on a sequence. An estring is represented as a vector of integers. It is interpreted in order of increasing suffix. A positive value n means copy n letters. A negative value -n means insert n indels. Zero marks the end of the vector. Consecutive entries must have opposite sign, i.e. the shortest possible representation must be used. A ""tpair"" is a traceback path for a pairwise alignment represented as two estrings, one for each sequence. ***/ #define c2(c,d) (((unsigned char) c) << 8 | (unsigned char) d) unsigned LengthEstring(const short es[]) { unsigned i = 0; while (*es++ != 0) ++i; return i; } short *EstringNewCopy(const short es[]) { unsigned n = LengthEstring(es) + 1; short *esNew = new short[n]; memcpy(esNew, es, n*sizeof(short)); return esNew; } void LogEstring(const short es[]) { Log(""<""); for (unsigned i = 0; es[i] != 0; ++i) { if (i > 0) Log("" ""); Log(""%d"", es[i]); } Log("">""); } static bool EstringsEq(const short es1[], const short es2[]) { for (;;) { if (*es1 != *es2) return false; if (0 == *es1) break; ++es1; ++es2; } return true; } static void EstringCounts(const short es[], unsigned *ptruSymbols, unsigned *ptruIndels) { unsigned uSymbols = 0; unsigned uIndels = 0; for (unsigned i = 0; es[i] != 0; ++i) { short n = es[i]; if (n > 0) uSymbols += n; else if (n < 0) uIndels += -n; } *ptruSymbols = uSymbols; *ptruIndels = uIndels; } static char *EstringOp(const short es[], const char s[]) { unsigned uSymbols; unsigned uIndels; EstringCounts(es, &uSymbols, &uIndels); assert((unsigned) strlen(s) == uSymbols); char *sout = new char[uSymbols + uIndels + 1]; char *psout = sout; for (;;) { int n = *es++; if (0 == n) break; if (n > 0) for (int i = 0; i < n; ++i) *psout++ = *s++; else for (int i = 0; i < -n; ++i) *psout++ = '-'; } assert(0 == *s); *psout = 0; return sout; } void EstringOp(const short es[], const Seq &sIn, Seq &sOut) { #if DEBUG unsigned uSymbols; unsigned uIndels; EstringCounts(es, &uSymbols, &uIndels); assert(sIn.Length() == uSymbols); #endif sOut.Clear(); sOut.SetName(sIn.GetName()); int p = 0; for (;;) { int n = *es++; if (0 == n) break; if (n > 0) for (int i = 0; i < n; ++i) { char c = sIn[p++]; sOut.push_back(c); } else for (int i = 0; i < -n; ++i) sOut.push_back('-'); } } unsigned EstringOp(const short es[], const Seq &sIn, MSA &a) { unsigned uSymbols; unsigned uIndels; EstringCounts(es, &uSymbols, &uIndels); assert(sIn.Length() == uSymbols); unsigned uColCount = uSymbols + uIndels; a.Clear(); a.SetSize(1, uColCount); a.SetSeqName(0, sIn.GetName()); a.SetSeqId(0, sIn.GetId()); unsigned p = 0; unsigned uColIndex = 0; for (;;) { int n = *es++; if (0 == n) break; if (n > 0) for (int i = 0; i < n; ++i) { char c = sIn[p++]; a.SetChar(0, uColIndex++, c); } else for (int i = 0; i < -n; ++i) a.SetChar(0, uColIndex++, '-'); } assert(uColIndex == uColCount); return uColCount; } void PathToEstrings(const PWPath &Path, short **ptresA, short **ptresB) { // First pass to determine size of estrings esA and esB const unsigned uEdgeCount = Path.GetEdgeCount(); if (0 == uEdgeCount) { short *esA = new short[1]; short *esB = new short[1]; esA[0] = 0; esB[0] = 0; *ptresA = esA; *ptresB = esB; return; } unsigned iLengthA = 1; unsigned iLengthB = 1; const char cFirstEdgeType = Path.GetEdge(0).cType; char cPrevEdgeType = cFirstEdgeType; for (unsigned uEdgeIndex = 1; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &Edge = Path.GetEdge(uEdgeIndex); char cEdgeType = Edge.cType; switch (c2(cPrevEdgeType, cEdgeType)) { case c2('M', 'M'): case c2('D', 'D'): case c2('I', 'I'): break; case c2('D', 'M'): case c2('M', 'D'): ++iLengthB; break; case c2('I', 'M'): case c2('M', 'I'): ++iLengthA; break; case c2('I', 'D'): case c2('D', 'I'): ++iLengthB; ++iLengthA; break; default: assert(false); } cPrevEdgeType = cEdgeType; } // Pass2 for seq A { short *esA = new short[iLengthA+1]; unsigned iA = 0; switch (Path.GetEdge(0).cType) { case 'M': case 'D': esA[0] = 1; break; case 'I': esA[0] = -1; break; default: assert(false); } char cPrevEdgeType = cFirstEdgeType; for (unsigned uEdgeIndex = 1; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &Edge = Path.GetEdge(uEdgeIndex); char cEdgeType = Edge.cType; switch (c2(cPrevEdgeType, cEdgeType)) { case c2('M', 'M'): case c2('D', 'D'): case c2('D', 'M'): case c2('M', 'D'): ++(esA[iA]); break; case c2('I', 'D'): case c2('I', 'M'): ++iA; esA[iA] = 1; break; case c2('M', 'I'): case c2('D', 'I'): ++iA; esA[iA] = -1; break; case c2('I', 'I'): --(esA[iA]); break; default: assert(false); } cPrevEdgeType = cEdgeType; } assert(iA == iLengthA - 1); esA[iLengthA] = 0; *ptresA = esA; } { // Pass2 for seq B short *esB = new short[iLengthB+1]; unsigned iB = 0; switch (Path.GetEdge(0).cType) { case 'M': case 'I': esB[0] = 1; break; case 'D': esB[0] = -1; break; default: assert(false); } char cPrevEdgeType = cFirstEdgeType; for (unsigned uEdgeIndex = 1; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &Edge = Path.GetEdge(uEdgeIndex); char cEdgeType = Edge.cType; switch (c2(cPrevEdgeType, cEdgeType)) { case c2('M', 'M'): case c2('I', 'I'): case c2('I', 'M'): case c2('M', 'I'): ++(esB[iB]); break; case c2('D', 'I'): case c2('D', 'M'): ++iB; esB[iB] = 1; break; case c2('M', 'D'): case c2('I', 'D'): ++iB; esB[iB] = -1; break; case c2('D', 'D'): --(esB[iB]); break; default: assert(false); } cPrevEdgeType = cEdgeType; } assert(iB == iLengthB - 1); esB[iLengthB] = 0; *ptresB = esB; } #if DEBUG { const PWEdge &LastEdge = Path.GetEdge(uEdgeCount - 1); unsigned uSymbols; unsigned uIndels; EstringCounts(*ptresA, &uSymbols, &uIndels); assert(uSymbols == LastEdge.uPrefixLengthA); assert(uSymbols + uIndels == uEdgeCount); EstringCounts(*ptresB, &uSymbols, &uIndels); assert(uSymbols == LastEdge.uPrefixLengthB); assert(uSymbols + uIndels == uEdgeCount); PWPath TmpPath; EstringsToPath(*ptresA, *ptresB, TmpPath); TmpPath.AssertEqual(Path); } #endif } void EstringsToPath(const short esA[], const short esB[], PWPath &Path) { Path.Clear(); unsigned iA = 0; unsigned iB = 0; int nA = esA[iA++]; int nB = esB[iB++]; unsigned uPrefixLengthA = 0; unsigned uPrefixLengthB = 0; for (;;) { char cType; if (nA > 0) { if (nB > 0) { cType = 'M'; --nA; --nB; } else if (nB < 0) { cType = 'D'; --nA; ++nB; } else assert(false); } else if (nA < 0) { if (nB > 0) { cType = 'I'; ++nA; --nB; } else assert(false); } else assert(false); switch (cType) { case 'M': ++uPrefixLengthA; ++uPrefixLengthB; break; case 'D': ++uPrefixLengthA; break; case 'I': ++uPrefixLengthB; break; } PWEdge Edge; Edge.cType = cType; Edge.uPrefixLengthA = uPrefixLengthA; Edge.uPrefixLengthB = uPrefixLengthB; Path.AppendEdge(Edge); if (nA == 0) { if (0 == esA[iA]) { assert(0 == esB[iB]); break; } nA = esA[iA++]; } if (nB == 0) nB = esB[iB++]; } } /*** Multiply two estrings to make a third estring. The product of two estrings e1*e2 is defined to be the estring that produces the same result as applying e1 then e2. Multiplication is not commutative. In fact, the reversed order is undefined unless both estrings consist of a single, identical, positive entry. A primary motivation for using estrings is that multiplication is very fast, reducing the time needed to construct the root alignment. Example <-1,3>(XXX) = -XXX <2,-1,2>(-XXX) = -X-XX Therefore, <-1,3>*<2,-1,2> = <-1,1,-1,2> ***/ static bool CanMultiplyEstrings(const short es1[], const short es2[]) { unsigned uSymbols1; unsigned uSymbols2; unsigned uIndels1; unsigned uIndels2; EstringCounts(es1, &uSymbols1, &uIndels1); EstringCounts(es2, &uSymbols2, &uIndels2); return uSymbols1 + uIndels1 == uSymbols2; } static inline void AppendGaps(short esp[], int &ip, int n) { if (-1 == ip) esp[++ip] = n; else if (esp[ip] < 0) esp[ip] += n; else esp[++ip] = n; } static inline void AppendSymbols(short esp[], int &ip, int n) { if (-1 == ip) esp[++ip] = n; else if (esp[ip] > 0) esp[ip] += n; else esp[++ip] = n; } void MulEstrings(const short es1[], const short es2[], short esp[]) { assert(CanMultiplyEstrings(es1, es2)); unsigned i1 = 0; int ip = -1; int n1 = es1[i1++]; for (unsigned i2 = 0; ; ++i2) { int n2 = es2[i2]; if (0 == n2) break; if (n2 > 0) { for (;;) { if (n1 < 0) { if (n2 > -n1) { AppendGaps(esp, ip, n1); n2 += n1; n1 = es1[i1++]; } else if (n2 == -n1) { AppendGaps(esp, ip, n1); n1 = es1[i1++]; break; } else { assert(n2 < -n1); AppendGaps(esp, ip, -n2); n1 += n2; break; } } else { assert(n1 > 0); if (n2 > n1) { AppendSymbols(esp, ip, n1); n2 -= n1; n1 = es1[i1++]; } else if (n2 == n1) { AppendSymbols(esp, ip, n1); n1 = es1[i1++]; break; } else { assert(n2 < n1); AppendSymbols(esp, ip, n2); n1 -= n2; break; } } } } else { assert(n2 < 0); AppendGaps(esp, ip, n2); } } esp[++ip] = 0; #if DEBUG { int MaxLen = (int) (LengthEstring(es1) + LengthEstring(es2) + 1); assert(ip < MaxLen); if (ip >= 2) for (int i = 0; i < ip - 2; ++i) { if (!(esp[i] > 0 && esp[i+1] < 0 || esp[i] < 0 && esp[i+1] > 0)) { Log(""Bad result of MulEstring: ""); LogEstring(esp); Quit(""Assert failed (alternating signs)""); } } unsigned uSymbols1; unsigned uSymbols2; unsigned uSymbolsp; unsigned uIndels1; unsigned uIndels2; unsigned uIndelsp; EstringCounts(es1, &uSymbols1, &uIndels1); EstringCounts(es2, &uSymbols2, &uIndels2); EstringCounts(esp, &uSymbolsp, &uIndelsp); if (uSymbols1 + uIndels1 != uSymbols2) { Log(""Bad result of MulEstring: ""); LogEstring(esp); Quit(""Assert failed (counts1 %u %u %u)"", uSymbols1, uIndels1, uSymbols2); } } #endif } static void test(const short es1[], const short es2[], const short esa[]) { unsigned uSymbols1; unsigned uSymbols2; unsigned uIndels1; unsigned uIndels2; EstringCounts(es1, &uSymbols1, &uIndels1); EstringCounts(es2, &uSymbols2, &uIndels2); char s[4096]; memset(s, 'X', sizeof(s)); s[uSymbols1] = 0; char *s1 = EstringOp(es1, s); char *s12 = EstringOp(es2, s1); memset(s, 'X', sizeof(s)); s[uSymbols2] = 0; char *s2 = EstringOp(es2, s); Log(""%s * %s = %s\n"", s1, s2, s12); LogEstring(es1); Log("" * ""); LogEstring(es2); Log("" = ""); LogEstring(esa); Log(""\n""); short esp[4096]; MulEstrings(es1, es2, esp); LogEstring(esp); if (!EstringsEq(esp, esa)) Log("" *ERROR* ""); Log(""\n""); memset(s, 'X', sizeof(s)); s[uSymbols1] = 0; char *sp = EstringOp(esp, s); Log(""%s\n"", sp); Log(""\n==========\n\n""); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/alignprofs.cpp",".cpp","424","17","#include ""multaln.h"" SCORE AlignProfiles( const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path, ProfPos **ptrPout, unsigned *ptruLengthOut) { assert(uLengthA < 100000); assert(uLengthB < 100000); SCORE Score = GlobalAlign(PA, uLengthA, PB, uLengthB, Path); AlignTwoProfsGivenPath(Path, PA, uLengthB, PB, uLengthB, ptrPout, ptruLengthOut); return Score; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/cmp.cpp",".cpp","5721","249","#include ""pilercr.h"" #include ""sw.h"" #define TRACE 0 static double MinId = 0.899; static void LogAln(const Seq &RefSeq, const Seq &TestSeq_, unsigned StartRef, unsigned StartTest, std::string &Path, bool Rev) { Seq TestSeq; TestSeq.Copy(TestSeq_); if (Rev) TestSeq.RevComp(); unsigned AlnLength = (unsigned) Path.size(); unsigned RefLength = RefSeq.Length(); unsigned TestLength = TestSeq.Length(); // Ref seq if (StartTest > StartRef) for (unsigned i = StartRef; i < StartTest; ++i) Log("".""); for (unsigned i = 0; i < StartRef; ++i) Log(""%c"", tolower(RefSeq[i])); unsigned RefPos = StartRef; for (unsigned i = 0; i < AlnLength; ++i) { switch (Path[i]) { case 'M': case 'D': Log(""%c"", toupper(RefSeq[RefPos++])); break; case 'I': Log(""-""); break; } } while (RefPos < RefLength) Log(""%c"", tolower(RefSeq[RefPos++])); Log(""\n""); // Test seq if (StartRef > StartTest) for (unsigned i = StartTest; i < StartRef; ++i) Log("".""); for (unsigned i = 0; i < StartTest; ++i) Log(""%c"", tolower(TestSeq[i])); unsigned TestPos = StartTest; for (unsigned i = 0; i < AlnLength; ++i) { switch (Path[i]) { case 'M': case 'I': Log(""%c"", toupper(TestSeq[TestPos++])); break; case 'D': Log(""-""); break; } } while (TestPos < TestLength) Log(""%c"", tolower(TestSeq[TestPos++])); Log(""\n""); } double GetFractId(const Seq &A, const Seq &B, unsigned StartA, unsigned StartB, std::string &Path) { unsigned APos = StartA; unsigned BPos = StartB; unsigned Same = 0; unsigned AlnLength = (unsigned) Path.size(); for (unsigned i = 0; i < AlnLength; ++i) { switch (Path[i]) { case 'M': if (toupper(A[APos]) == toupper(B[BPos])) ++Same; ++APos; ++BPos; break; case 'D': ++APos; break; case 'I': ++BPos; break; default: assert(false); } } unsigned LA = A.Length(); unsigned LB = B.Length(); if (LA == 0 || LB == 0) return 0.0; unsigned MaxLen = std::max(LA, LB); return (double) Same / (double) MaxLen; } void Cmp() { const char *TestFileName = RequiredValueOpt(""cmp""); const char *RefFileName = RequiredValueOpt(""ref""); FILE *fTest = OpenStdioFile(TestFileName); FILE *fRef = OpenStdioFile(RefFileName); SeqVect TestSeqs; SeqVect RefSeqs; TestSeqs.FromFASTAFile(fTest); RefSeqs.FromFASTAFile(fRef); fclose(fTest); fclose(fRef); fTest = 0; fRef = 0; int TestSeqCount = (int) TestSeqs.Length(); int RefSeqCount = (int) RefSeqs.Length(); for (int RefSeqIndex = 0; RefSeqIndex < RefSeqCount; ++RefSeqIndex) { const Seq &RefSeq = *(RefSeqs[RefSeqIndex]); int BestTestSeqIndex = -1; bool Exact = false; bool Rev = false; double BestId = 0.0; unsigned BestStartTest; unsigned BestStartRef; std::string BestPath; for (int TestSeqIndex = 0; TestSeqIndex < TestSeqCount; ++TestSeqIndex) { const Seq &TestSeq = *(TestSeqs[TestSeqIndex]); unsigned StartTest; unsigned StartRef; std::string Path; score_t Score = SW(RefSeq, TestSeq, &StartRef, &StartTest, Path); #if TRACE Log(""SW(%s,%s)=%.1f\n"", TestSeq.GetName(), RefSeq.GetName(), Score); Log(""Test=""); for (unsigned i = 0; i < TestSeq.Length(); ++i) Log(""%c"", TestSeq[i]); Log(""\n""); Log(""Ref =""); for (unsigned i = 0; i < RefSeq.Length(); ++i) Log(""%c"", RefSeq[i]); Log(""\n""); if (Score > 0) { Log(""Aln length = %d\n"", (int) Path.size()); LogAln(RefSeq, TestSeq, StartRef, StartTest, Path, false); } #endif if (Score > 0) { double Id = GetFractId(TestSeq, RefSeq, StartTest, StartRef, Path); #if TRACE Log(""Id = %.3f\n"", Id); #endif if (Id > 0.999) { Exact = true; Log(""Exact: ref=%s, test=%s\n"", RefSeq.GetName(), TestSeq.GetName()); break; } if (Id >= MinId) { BestTestSeqIndex = TestSeqIndex; BestStartTest = StartTest; BestStartRef = StartRef; BestPath = Path; BestId = Id; Rev = false; } } Seq TestSeqRC; TestSeqRC.Copy(TestSeq); TestSeqRC.RevComp(); Score = SW(RefSeq, TestSeqRC, &StartRef, &StartTest, Path); #if TRACE Log(""SW(rev %s,%s)=%.1f\n"", TestSeq.GetName(), RefSeq.GetName(), Score); Log(""Test=""); for (unsigned i = 0; i < TestSeqRC.Length(); ++i) Log(""%c"", TestSeqRC[i]); Log(""\n""); Log(""Ref =""); for (unsigned i = 0; i < RefSeq.Length(); ++i) Log(""%c"", RefSeq[i]); Log(""\n""); if (Score > 0) { Log(""Aln length = %d\n"", (int) Path.size()); LogAln(RefSeq, TestSeq, StartRef, StartTest, Path, true); } #endif if (Score > 0) { double Id = GetFractId(TestSeqRC, RefSeq, StartTest, StartRef, Path); #if TRACE Log(""Id = %.3f\n"", Id); #endif if (Id > 0.999) { Exact = true; Log(""Exact: rev ref=%s, test=%s\n"", RefSeq.GetName(), TestSeq.GetName()); break; } if (Id >= MinId) { BestTestSeqIndex = TestSeqIndex; BestId = Id; BestStartTest = StartTest; BestStartRef = StartRef; BestPath = Path; Rev = true; } } } if (Exact) continue; if (BestTestSeqIndex == -1) Log(""None: best id %.1f%% ref=%s\n"", BestId*100.0, RefSeq.GetName()); else { const Seq &TestSeq = *(TestSeqs[BestTestSeqIndex]); Log(""Close: %.1f%%: rev=%c ref=%s, test=%s\n"", BestId*100.0, Rev ? 'T' : 'F', RefSeq.GetName(), TestSeq.GetName()); LogAln(RefSeq, TestSeq, BestStartRef, BestStartTest, BestPath, Rev); } } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/assert.cpp",".cpp","239","8","#include ""pilercr.h"" void assert_(const char *Exp, const char *FileName, unsigned LineNr) { fprintf(stderr, ""Assertion failed(%s:%d) %s\n"", FileName, LineNr, Exp); Quit(""Assertion failed(%s:%d) %s\n"", FileName, LineNr, Exp); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/dp.cpp",".cpp","13170","618","#include ""pilercr.h"" #undef TEST_DPREACH #undef TEST_TRAPTRIM #undef STAT_DPREACH #undef SHOW_DIAGS #undef REPORT_DPREACH #undef REPORT_DPREACH #define MAXIGAP 5 #define DIFFCOST 3 #define SAMECOST 1 extern Trapezoid **Tarray; extern int *Covered; extern int SegMax; //extern DPHit *SegSols; //extern int NumSegs; static int BLOCKCOST = DIFFCOST*MAXIGAP; static int MATCHCOST = DIFFCOST+SAMECOST; static double RMATCHCOST = DIFFCOST+1.; /*** FORWARD AND REVERSE D.P. EXTENSION ROUTINES ***/ /* Called at the mid-point of trapezoid -- mid X [lo,hi], the extension is computed to an end point and the lowest and highest diagonals are recorded. These are returned in a partially filled DPHit record, that will be merged with that returned for extension in the opposite direction. */ static int VecMax = -1; static int *Vec1 = NULL; static int *Vec2; DPHit *TraceForwardPath(char *A, int Alen, char *B, int Blen, int mid, int lo, int hi) { static DPHit rez; int *V, odd; int mxv, mxl, mxr, mxi, mxj; int i, j; #ifdef STAT_DPREACH long dparea; #endif /* Set basis from (mid,lo) .. (mid,hi) */ if (lo < 0) lo = 0; if (hi > Blen) hi = Blen; if ((hi-lo)+MAXIGAP >= VecMax) { VecMax = (int) (1.2*((hi-lo) + MAXIGAP + 1) + 10000); Vec1 = (int *) ckrealloc(Vec1,2*VecMax*sizeof(int),""Vector D.P. arrays""); Vec2 = Vec1 + VecMax; } V = Vec1 - lo; odd = 1; for (j = lo; j <= hi; j++) V[j] = 0; hi += MAXIGAP; if (hi > Blen) hi = Blen; for (; j <= hi; j++) V[j] = V[j-1] - DIFFCOST; mxv = 0; mxr = mid - lo; mxl = mid - hi; mxi = mid; mxj = lo; #ifdef STAT_DPREACH dparea = (hi-lo+1); #endif /* Advance to next row */ int maxi = mid + g_MaxDPHitLen - 1; if (maxi >= Alen) maxi = Alen; for (i = mid; lo <= hi && i < maxi; i++) // for (i = mid; lo <= hi && i < Alen; i++) { int c, v; int *W; W = V; if (odd) V = Vec2 - lo; else V = Vec1 - lo; odd = 1-odd; #ifdef TEST_DPREACH Log(""\n%d [%d,%d] x = %d\n "",i,lo,hi,mxv); for (j = lo; j <= hi; j++) Log("" %c "",B[j]); Log(""\n ""); for (j = lo; j <= hi; j++) Log("" %3d"",W[j]); Log(""\n%c"",A[i]); #endif v = W[lo]; c = V[lo] = v - DIFFCOST; #ifdef TEST_DPREACH Log("" %3d"",c); #endif for (j = lo+1; j <= hi; j++) { int r, t; t = c; c = v; v = W[j]; if (A[i] == B[j-1] && CharToLetter[(unsigned char) (A[i])] >= 0) c += MATCHCOST; r = c; if (v > r) r = v; if (t > r) r = t; V[j] = c = r - DIFFCOST; if (c >= mxv) { mxv = c; mxi = i+1; mxj = j; } #ifdef TEST_DPREACH Log("" %3d"",c); #endif } if (j <= Blen) { int r; if (A[i] == B[j-1] && CharToLetter[(unsigned char) (A[i])] >= 0) v += MATCHCOST; r = v; if (c > r) r = c; V[j] = v = r - DIFFCOST; if (v > mxv) { mxv = v; mxi = i+1; mxj = j; } #ifdef TEST_DPREACH Log("" %3d"",v); #endif for (j++; j <= Blen; j++) { v -= DIFFCOST; if (v < mxv - BLOCKCOST) break; V[j] = v; #ifdef TEST_DPREACH Log("" %3d"",v); #endif } } #ifdef TEST_DPREACH Log(""\n""); #endif hi = j-1; while (lo <= hi && V[lo] < mxv - BLOCKCOST) lo += 1; while (lo <= hi && V[hi] < mxv - BLOCKCOST) hi -= 1; if ((hi-lo)+2 > VecMax) { VecMax = (int) (1.2*((hi-lo) + 2) + 10000); Vec1 = (int *) ckrealloc(Vec1,2*VecMax*sizeof(int),""Vector D.P. arrays""); Vec2 = Vec1 + VecMax; } if ((i+1) - lo > mxr) mxr = (i+1) - lo; if ((i+1) - hi < mxl) mxl = (i+1) - hi; #ifdef STAT_DPREACH dparea += (hi-lo+1); #endif } #ifdef STAT_DPREACH Log("" DP_Area = %ld Peak is %d @ (%d,%d) in [%d,%d]\n"", dparea,mxv,mxi,mxj,mxl,mxr); #endif rez.aHi = mxj; rez.bHi = mxi; rez.ldiag = mxl; rez.hdiag = mxr; rez.score = mxv; return (&rez); } DPHit *TraceReversePath(char *A, int Alen, char *B, int Blen, int top, int lo, int hi, int bot, int xfactor) { static DPHit rez; int *V, odd; int mxv, mxl, mxr, mxi, mxj; int i, j; #ifdef STAT_DPREACH long dparea; #endif /* Set basis from (top,lo) .. (top,hi) */ if (lo < 0) lo = 0; if (hi > Blen) hi = Blen; if ((hi-lo)+MAXIGAP >= VecMax) { VecMax = (int) (1.2*((hi-lo) + MAXIGAP + 1) + 10000); Vec1 = (int *) ckrealloc(Vec1,2*VecMax*sizeof(int),""Vector D.P. arrays""); Vec2 = Vec1 + VecMax; } V = Vec1 + ((VecMax-1) - hi); odd = 1; for (j = hi; j >= lo; j--) V[j] = 0; lo -= MAXIGAP; if (lo < 0) lo = 0; for (; j >= lo; j--) V[j] = V[j+1] - DIFFCOST; mxv = 0; mxr = top - lo; mxl = top - hi; mxi = top; mxj = lo; #ifdef STAT_DPREACH dparea = (hi-lo+1); #endif /* Advance to next row */ if (top-1 <= bot) xfactor = BLOCKCOST; int mini = top - g_MaxDPHitLen; if (mini < 0) mini = 0; for (i = top-1; lo <= hi && i >= mini; i--) // for (i = top-1; lo <= hi && i >= 0; i--) { int c, v; int *W; W = V; if (odd) V = Vec2 + ((VecMax-1) - hi); else V = Vec1 + ((VecMax-1) - hi); odd = 1-odd; #ifdef TEST_DPREACH Log(""\n%d [%d,%d] x = %d\n "",i,lo,hi,mxv); for (j = hi; j >= lo; j--) Log("" %c "",B[j-1]); Log(""\n ""); for (j = hi; j >= lo; j--) Log("" %3d"",W[j]); Log(""\n%c"",A[i]); #endif v = W[hi]; c = V[hi] = v - DIFFCOST; #ifdef TEST_DPREACH Log("" %3d"",c); #endif for (j = hi-1; j >= lo; j--) { int r, t; t = c; c = v; v = W[j]; if (A[i] == B[j] && CharToLetter[(unsigned char) (A[i])] >= 0) c += MATCHCOST; r = c; if (v > r) r = v; if (t > r) r = t; V[j] = c = r - DIFFCOST; if (c >= mxv) { mxv = c; mxi = i; mxj = j; } #ifdef TEST_DPREACH Log("" %3d"",c); #endif } if (j >= 0) { int r; if (A[i] == B[j] && CharToLetter[(unsigned char) (A[i])] >= 0) v += MATCHCOST; r = v; if (c > r) r = c; V[j] = v = r - DIFFCOST; if (v > mxv) { mxv = v; mxi = i; mxj = j; } #ifdef TEST_DPREACH Log("" %3d"",v); #endif for (j--; j >= 0; j--) { v -= DIFFCOST; if (v < mxv - xfactor) break; V[j] = v; #ifdef TEST_DPREACH Log("" %3d"",v); #endif } } #ifdef TEST_DPREACH Log(""\n""); #endif lo = j+1; while (lo <= hi && V[lo] < mxv - xfactor) lo += 1; while (lo <= hi && V[hi] < mxv - xfactor) hi -= 1; if (i == bot) xfactor = BLOCKCOST; if ((hi-lo)+2 > VecMax) { VecMax = (int) (1.2*((hi-lo) + 2) + 10000); Vec1 = (int *) ckrealloc(Vec1,2*VecMax*sizeof(int),""Vector D.P. arrays""); Vec2 = Vec1 + VecMax; } if (i-lo > mxr) mxr = i-lo; if (i-hi < mxl) mxl = i-hi; #ifdef STAT_DPREACH dparea += (hi-lo+1); #endif } #ifdef STAT_DPREACH Log("" DP_Area = %ld Peak is %d @ (%d,%d) in [%d,%d]\n"", dparea,mxv,mxi,mxj,mxl,mxr); #endif rez.aLo = mxj; rez.bLo = mxi; rez.ldiag = mxl; rez.hdiag = mxr; rez.score = mxv; return (&rez); } /*** FINDING ALIGNMENTS WITHIN A TRAPEZOIDAL ZONE ***/ int TSORT(const void *l, const void *r) { Trapezoid *x, *y; x = *((Trapezoid **) l); y = *((Trapezoid **) r); return (x->bot - y->bot); } int StSORT(const void *l, const void *r) { DPHit *x, *y; x = (DPHit *) l; y = (DPHit *) r; if (x->aLo < y->aLo) return (-1); else if (x->aLo > y->aLo) return (1); else return (x->bLo - y->bLo); } int FnSORT(const void *l, const void *r) { DPHit *x, *y; x = (DPHit *) l; y = (DPHit *) r; if (x->aHi < y->aHi) return (-1); else if (x->aHi > y->aHi) return (1); else return (x->bHi - y->bHi); } #ifdef REPORT_DPREACH static int Al_depth; #endif void Align_Recursion(char *A, int Alen, char *B, int Blen, Trapezoid *b, int current, int comp, int MinLen, double MaxDiff, int Traplen) { int j, mid, indel; float pcnt; DPHit *hend, *lend; Trapezoid ltrp, htrp; mid = (b->bot + b->top) / 2; #ifdef REPORT_DPREACH Log("" [%d,%d]x[%d,%d] = %d (Depth = %d)\n"", b->bot,b->top,b->lft,b->rgt,b->top - b->bot + 1,Al_depth); #endif lend = TraceForwardPath(B,Blen,A,Alen,mid,mid-b->rgt,mid-b->lft); { int x; x = 0; do { x += 1; hend = TraceReversePath(B,Blen,A,Alen, lend->bHi,lend->aHi,lend->aHi, mid+MAXIGAP,BLOCKCOST+2*x*DIFFCOST); } while (hend->bLo > mid + x*MAXIGAP && hend->score < lend->score); } hend->aHi = lend->aHi; hend->bHi = lend->bHi; #ifdef REPORT_DPREACH Log("" Got [%d,%d]x[%d,%d] ([%d,%d]) at score = %d\n"", hend->bLo,hend->bHi,hend->ldiag,hend->hdiag,hend->aLo,hend->aHi,hend->score); #endif ltrp = htrp = *b; ltrp.top = hend->bLo - MAXIGAP; htrp.bot = hend->bHi + MAXIGAP; if (hend->bHi - hend->bLo >= MinLen && hend->aHi - hend->aLo >= MinLen ) { indel = abs( (hend->aLo - hend->bLo) - (hend->aHi - hend->bHi) ); pcnt = (float)((1/RMATCHCOST) - (hend->score - indel) / (RMATCHCOST*(hend->bHi - hend->bLo))); if (pcnt <= MaxDiff) { hend->error = pcnt; for (j = current+1; j < Traplen; j++) { Trapezoid *t; int ta, tb, ua, ub; t = Tarray[j]; if (t->bot >= hend->bHi) break; tb = t->top - t->bot + 1; ta = t->rgt - t->lft + 1; if (t->lft < hend->ldiag) ua = hend->ldiag; else ua = t->lft; if (t->rgt > hend->hdiag) ub = hend->hdiag; else ub = t->rgt; if (ua > ub) continue; ua = ub - ua + 1; if (t->top > hend->bHi) ub = hend->bHi - t->bot + 1; else ub = tb; if (((1.*ua)/ta)*((1.*ub)/tb) > .99) Covered[j] = 1; } //if (NumSegs >= SegMax) // { SegMax = (int)(1.2*NumSegs + 500); // SegSols = (DPHit *) ckrealloc(SegSols, // sizeof(DPHit)*SegMax, // ""Segment Alignment array""); // } { int d; d = hend->ldiag; /* Oops, diags to this point are b-a, not a-b. */ hend->ldiag = - (hend->hdiag); hend->hdiag = - d; if (comp) { hend->bLo = Blen - hend->bLo; hend->bHi = Blen - hend->bHi; hend->ldiag = Blen + hend->ldiag; hend->hdiag = Blen + hend->hdiag; } } if (AcceptHit(*hend)) g_Hits.push_back(*hend); else { if (fDiscardedHits) { WriteDPHit(fDiscardedHits, *hend, false); ++g_DiscardedHitCount; } } #ifdef REPORT_DPREACH Log("" Hit from (%d,%d) to (%d,%d) within [%d,%d] score %d\n"", hend->aLo,hend->bLo,hend->aHi,hend->bHi, hend->ldiag,hend->hdiag,hend->score); #endif } } #ifdef REPORT_DPREACH Al_depth += 1; #endif if (ltrp.top - ltrp.bot > MinLen && ltrp.top < b->top - MAXIGAP) Align_Recursion(A,Alen,B,Blen,<rp,current,comp,MinLen,MaxDiff,Traplen); if (htrp.top - htrp.bot > MinLen) Align_Recursion(A,Alen,B,Blen,&htrp,current,comp,MinLen,MaxDiff,Traplen); #ifdef REPORT_DPREACH Al_depth -= 1; #endif } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/tree.h",".h","9534","340","#ifndef tree_h #define tree_h #include #include class Clust; const unsigned NULL_NEIGHBOR = UINT_MAX; enum NEWICK_TOKEN_TYPE { NTT_Unknown, // Returned from Tree::GetToken: NTT_Lparen, NTT_Rparen, NTT_Colon, NTT_Comma, NTT_Semicolon, NTT_String, // Following are never returned from Tree::GetToken: NTT_SingleQuotedString, NTT_DoubleQuotedString, NTT_Comment }; class Tree { public: Tree() { m_uNodeCount = 0; m_uCacheCount = 0; m_uNeighbor1 = 0; m_uNeighbor2 = 0; m_uNeighbor3 = 0; m_dEdgeLength1 = 0; m_dEdgeLength2 = 0; m_dEdgeLength3 = 0; m_dHeight = 0; m_bHasEdgeLength1 = 0; m_bHasEdgeLength2 = 0; m_bHasEdgeLength3 = 0; m_bHasHeight = 0; m_ptrName = 0; m_Ids = 0; } virtual ~Tree() { Clear(); } void Clear() { for (unsigned n = 0; n < m_uNodeCount; ++n) free(m_ptrName[n]); m_uNodeCount = 0; m_uCacheCount = 0; delete[] m_uNeighbor1; delete[] m_uNeighbor2; delete[] m_uNeighbor3; delete[] m_dEdgeLength1; delete[] m_dEdgeLength2; delete[] m_dEdgeLength3; delete[] m_bHasEdgeLength1; delete[] m_bHasEdgeLength2; delete[] m_bHasEdgeLength3; delete[] m_ptrName; delete[] m_Ids; delete[] m_bHasHeight; delete[] m_dHeight; m_uNeighbor1 = 0; m_uNeighbor2 = 0; m_uNeighbor3 = 0; m_dEdgeLength1 = 0; m_dEdgeLength2 = 0; m_dEdgeLength3 = 0; m_ptrName = 0; m_Ids = 0; m_uRootNodeIndex = 0; m_bHasHeight = 0; m_dHeight = 0; m_bRooted = false; } // Creation and manipulation void CreateRooted(); void CreateUnrooted(double dEdgeLength); void FromFile(TextFile &File); void FromClust(Clust &C); void Copy(const Tree &tree); void Create(unsigned uLeafCount, unsigned uRoot, const unsigned Left[], const unsigned Right[], const float LeftLength[], const float RightLength[], const unsigned LeafIds[], char *LeafNames[]); unsigned AppendBranch(unsigned uExistingNodeIndex); void SetLeafName(unsigned uNodeIndex, const char *ptrName); void SetLeafId(unsigned uNodeIndex, unsigned uId); void SetEdgeLength(unsigned uNodeIndex1, unsigned uNodeIndex2, double dLength); void RootUnrootedTree(unsigned uNodeIndex1, unsigned uNodeIndex2); void RootUnrootedTree(); void UnrootByDeletingRoot(); // Saving to file void ToFile(TextFile &File) const; // Accessor functions unsigned GetNodeCount() const { return m_uNodeCount; } unsigned GetLeafCount() const { if (m_bRooted) { assert(m_uNodeCount%2 == 1); return (m_uNodeCount + 1)/2; } else { assert(m_uNodeCount%2 == 0); return (m_uNodeCount + 2)/2; } } unsigned GetNeighbor(unsigned uNodeIndex, unsigned uNeighborSubscript) const; unsigned GetNeighbor1(unsigned uNodeIndex) const { assert(uNodeIndex < m_uNodeCount); return m_uNeighbor1[uNodeIndex]; } unsigned GetNeighbor2(unsigned uNodeIndex) const { assert(uNodeIndex < m_uNodeCount); return m_uNeighbor2[uNodeIndex]; } unsigned GetNeighbor3(unsigned uNodeIndex) const { assert(uNodeIndex < m_uNodeCount); return m_uNeighbor3[uNodeIndex]; } unsigned GetParent(unsigned uNodeIndex) const { assert(m_bRooted && uNodeIndex < m_uNodeCount); return m_uNeighbor1[uNodeIndex]; } bool IsRooted() const { return m_bRooted; } unsigned GetLeft(unsigned uNodeIndex) const { assert(m_bRooted && uNodeIndex < m_uNodeCount); return m_uNeighbor2[uNodeIndex]; } unsigned GetRight(unsigned uNodeIndex) const { assert(m_bRooted && uNodeIndex < m_uNodeCount); return m_uNeighbor3[uNodeIndex]; } const char *GetName(unsigned uNodeIndex) const { assert(uNodeIndex < m_uNodeCount); return m_ptrName[uNodeIndex]; } unsigned GetRootNodeIndex() const { assert(m_bRooted); return m_uRootNodeIndex; } unsigned GetNeighborCount(unsigned uNodeIndex) const { const unsigned n1 = m_uNeighbor1[uNodeIndex]; const unsigned n2 = m_uNeighbor2[uNodeIndex]; const unsigned n3 = m_uNeighbor3[uNodeIndex]; return (NULL_NEIGHBOR != n1) + (NULL_NEIGHBOR != n2) + (NULL_NEIGHBOR != n3); } bool IsLeaf(unsigned uNodeIndex) const { assert(uNodeIndex < m_uNodeCount); if (1 == m_uNodeCount) return true; return 1 == GetNeighborCount(uNodeIndex); } bool IsRoot(unsigned uNodeIndex) const { return IsRooted() && m_uRootNodeIndex == uNodeIndex; } unsigned GetLeafId(unsigned uNodeIndex) const; unsigned GetLeafNodeIndex(const char *ptrName) const; bool IsEdge(unsigned uNodeIndex1, unsigned uNodeIndex2) const; bool HasEdgeLength(unsigned uNodeIndex1, unsigned uNodeIndex2) const; double GetEdgeLength(unsigned uNodeIndex1, unsigned uNodeIndex2) const; const char *GetLeafName(unsigned uNodeIndex) const; unsigned GetNeighborSubscript(unsigned uNodeIndex, unsigned uNeighborIndex) const; double GetNodeHeight(unsigned uNodeIndex) const; // Depth-first traversal unsigned FirstDepthFirstNode() const; unsigned NextDepthFirstNode(unsigned uNodeIndex) const; unsigned FirstDepthFirstNodeR() const; unsigned NextDepthFirstNodeR(unsigned uNodeIndex) const; // Equivalent of GetLeft/Right in unrooted tree, works in rooted tree too. unsigned GetFirstNeighbor(unsigned uNodeIndex, unsigned uNeighborIndex) const; unsigned GetSecondNeighbor(unsigned uNodeIndex, unsigned uNeighborIndex) const; // Getting parent node in unrooted tree defined iff leaf unsigned GetLeafParent(unsigned uNodeIndex) const; // Misc const char *NTTStr(NEWICK_TOKEN_TYPE NTT) const; void FindCenterByLongestSpan(unsigned *ptrNodeIndex1, unsigned *ptrNodeIndex2) const; void PruneTree(const Tree &tree, unsigned Subfams[], unsigned uSubfamCount); unsigned LeafIndexToNodeIndex(unsigned uLeafIndex) const; // Debugging & trouble-shooting support void Validate() const; void ValidateNode(unsigned uNodeIndex) const; void AssertAreNeighbors(unsigned uNodeIndex1, unsigned uNodeIndex2) const; void LogMe() const; private: unsigned UnrootFromFile(); NEWICK_TOKEN_TYPE GetTokenVerbose(TextFile &File, char szToken[], unsigned uBytes) const { NEWICK_TOKEN_TYPE NTT = GetToken(File, szToken, uBytes); Log(""GetToken %10.10s %s\n"", NTTStr(NTT), szToken); return NTT; } void InitCache(unsigned uCacheCount); void ExpandCache(); NEWICK_TOKEN_TYPE GetToken(TextFile &File, char szToken[], unsigned uBytes) const; bool GetGroupFromFile(TextFile &File, unsigned uNodeIndex, double *ptrdEdgeLength); unsigned GetLeafCountUnrooted(unsigned uNodeIndex1, unsigned uNodeIndex2, double *ptrdTotalDistance) const; void ToFileNodeRooted(TextFile &File, unsigned uNodeIndex) const; void ToFileNodeUnrooted(TextFile &File, unsigned uNodeIndex, unsigned uParent) const; void OrientParent(unsigned uNodeIndex, unsigned uParentNodeIndex); double FromClustNode(const Clust &C, unsigned uClustNodeIndex, unsigned uPhyNodeIndex); unsigned GetAnyNonLeafNode() const; // Yuck. Data is made public for the convenience of Tree::Copy. // There has to be a better way. public: unsigned m_uNodeCount; unsigned m_uCacheCount; unsigned *m_uNeighbor1; unsigned *m_uNeighbor2; unsigned *m_uNeighbor3; double *m_dEdgeLength1; double *m_dEdgeLength2; double *m_dEdgeLength3; double *m_dHeight; bool *m_bHasEdgeLength1; bool *m_bHasEdgeLength2; bool *m_bHasEdgeLength3; bool *m_bHasHeight; unsigned *m_Ids; char **m_ptrName; bool m_bRooted; unsigned m_uRootNodeIndex; }; struct PhyEnumEdgeState { PhyEnumEdgeState() { m_bInit = false; m_uNodeIndex1 = NULL_NEIGHBOR; m_uNodeIndex2 = NULL_NEIGHBOR; } bool m_bInit; unsigned m_uNodeIndex1; unsigned m_uNodeIndex2; }; const unsigned NODE_CHANGED = (unsigned) (~0); extern bool PhyEnumBiParts(const Tree &tree, PhyEnumEdgeState &ES, unsigned Leaves1[], unsigned *ptruCount1, unsigned Leaves2[], unsigned *ptruCount2); extern bool PhyEnumBiPartsR(const Tree &tree, PhyEnumEdgeState &ES, unsigned Leaves1[], unsigned *ptruCount1, unsigned Leaves2[], unsigned *ptruCount2); extern void ClusterByHeight(const Tree &tree, double dMaxHeight, unsigned Subtrees[], unsigned *ptruSubtreeCount); void ClusterBySubfamCount(const Tree &tree, unsigned uSubfamCount, unsigned Subfams[], unsigned *ptruSubfamCount); void GetLeaves(const Tree &tree, unsigned uNodeIndex, unsigned Leaves[], unsigned *ptruLeafCount); void GetLeavesExcluding(const Tree &tree, unsigned uNodeIndex, unsigned uExclude, unsigned Leaves[], unsigned *ptruCount); void GetInternalNodesInHeightOrder(const Tree &tree, unsigned NodeIndexes[]); void ApplyMinEdgeLength(Tree &tree, double dMinEdgeLength); void LeafIndexesToLeafNames(const Tree &tree, const unsigned Leaves[], unsigned uCount, char *Names[]); void LeafIndexesToIds(const Tree &tree, const unsigned Leaves[], unsigned uCount, unsigned Ids[]); void MSASeqSubset(const MSA &msaIn, char *Names[], unsigned uSeqCount, MSA &msaOut); void DiffTrees(const Tree &Tree1, const Tree &Tree2, Tree &Diffs, unsigned IdToDiffsLeafNodeIndex[]); void DiffTreesE(const Tree &NewTree, const Tree &OldTree, unsigned NewNodeIndexToOldNodeIndex[]); void FindRoot(const Tree &tree, unsigned *ptruNode1, unsigned *ptruNode2, double *ptrdLength1, double *ptrdLength2); void FixRoot(Tree &tree); #endif // tree_h ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/multaln.cpp",".cpp","742","30","#include ""pilercr.h"" #include ""multaln.h"" void MultipleAlign(SeqVect &Seqs, MSA &Aln) { assert(Seqs.GetSeqCount() > 0); if ((int) Seqs.GetSeqCount() > g_MaxMSASeqs) Quit(""Array length %u, max is %d"", Seqs.GetSeqCount(), g_MaxMSASeqs); if (Seqs.GetSeqCount() == 1) { Seq &s = Seqs.GetSeq(0); s.SetId(0); Aln.FromSeq(s); return; } unsigned uSeqCount = Seqs.GetSeqCount(); MSA::SetIdCount(g_MaxMSASeqs); // Initialize sequence ids. // From this point on, ids must somehow propogate from here. for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) Seqs.SetSeqId(uSeqIndex, uSeqIndex); Tree GuideTree; GetGuideTree(Seqs, GuideTree); ProgressiveAlign(Seqs, GuideTree, Aln); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/mergearrays.cpp",".cpp","6063","226","#include ""pilercr.h"" #include ""sw.h"" int UnalignedLength(const std::string &s) { size_t L = s.size(); int N = 0; for (size_t i = 0; i < L; ++i) if (s[i] != '-') ++N; return N; } static bool GloballyAlignable(const char *Seq1, unsigned L1, const char *Seq2, unsigned L2) { std::string Path; unsigned Start1; unsigned Start2; score_t Score = SWSimple(Seq1, L1, Seq2, L2, &Start1, &Start2, Path); if (Score <= 0) return false; int AlnLen = (int) Path.size(); if (GetRatio(AlnLen, (int) L1) < 0.95) return false; return true; } // is i = nj for n approximately integer in range 1 .. 4? static int Multiple(int i, int j) { if (GetRatio(i, 1*j) >= 0.95) return 1; if (GetRatio(i, 2*j) >= 0.95) return 2; if (GetRatio(i, 3*j) >= 0.95) return 3; if (GetRatio(i, 4*j) >= 0.95) return 4; return -1; } int DistanceAA(const ArrayAln &AA1, const ArrayAln &AA2) { int End1 = AA1.Pos + GetArrayLength(AA1) + GetAvgSpacerLength(AA1) - 1; int Pos2 = AA2.Pos; int ContigIndex1 = GlobalPosToContigIndex(End1); int ContigIndex2 = GlobalPosToContigIndex(Pos2); if (ContigIndex1 != ContigIndex2) return -1; int ci1 = GlobalPosToContigIndex(AA1.Pos); if (ContigIndex1 != ci1) Warning(""ContigIndex1=%u GlobalPosToContigIndex(AA1.Pos=%d) = %d"", ContigIndex1, AA1.Pos, ci1); return Pos2 - End1 - 1; } bool MergeAAs(ArrayAln &AA1, const ArrayAln &AA2) { int RepeatLength1 = GetAvgRepeatLength(AA1); int RepeatLength2 = GetAvgRepeatLength(AA2); if (RepeatLength1 != RepeatLength2) return false; int SpacerLength1 = GetAvgSpacerLength(AA1); int SpacerLength2 = GetAvgSpacerLength(AA2); if (GetRatio(SpacerLength1, SpacerLength2) < 0.95) return false; // Is distance between arrays a multiple of repeat+spacer length? int Distance = DistanceAA(AA1, AA2); int RepeatPlusSpacerLength = RepeatLength1 + SpacerLength1; int MissedRepeatCount = Multiple(Distance, RepeatPlusSpacerLength); if (MissedRepeatCount < 0) return false; int ConsSeqLength1 = AA1.ConsSeq.Length(); int ConsSeqLength2 = AA2.ConsSeq.Length(); char *Seq1 = all(char, ConsSeqLength1 + 1); char *Seq2 = all(char, ConsSeqLength2 + 1); AA1.ConsSeq.ToString(Seq1, ConsSeqLength1 + 1); AA2.ConsSeq.ToString(Seq2, ConsSeqLength2 + 1); if (!GloballyAlignable(Seq1, ConsSeqLength1, Seq2, ConsSeqLength2)) return false; IntVec RepeatStartPos; IntVec RepeatLengths; int LastSpacerStartPos = AA1.Pos + GetArrayLength(AA1); int EndPosOfLastRepeat = LastSpacerStartPos - 1; StrVec Repeats; for (int i = 0; i < MissedRepeatCount; ++i) { int GuessedRepeatPos = EndPosOfLastRepeat + SpacerLength1; int StartPos = GuessedRepeatPos - 8; int EndPos = GuessedRepeatPos + RepeatLength1 + 8; int SeqLength = EndPos - StartPos + 1; char *Seq = all(char, SeqLength); for (int i = 0; i < SeqLength; ++i) Seq[i] = g_SeqQ[StartPos + i]; char *ConsSeq = all(char, ConsSeqLength1 + 1); AA1.ConsSeq.ToString(ConsSeq, ConsSeqLength1 + 1); std::string Path; unsigned StartSeq; unsigned StartCons; score_t Score = SWSimple(Seq, SeqLength, ConsSeq, ConsSeqLength1, &StartSeq, &StartCons, Path); int AlnLength = (int) Path.size(); if (GetRatio(AlnLength, ConsSeqLength1) < 0.95) return false; std::string &Repeat = *new std::string; for (int i = 0; i < (int) StartCons; ++i) Repeat.push_back('-'); int SeqPos = StartPos + StartSeq; int RepeatPos = SeqPos; RepeatStartPos.push_back(RepeatPos); int RepeatLength = 0; for (int i = 0; i < AlnLength; ++i) { if (Path[i] == 'M' || Path[i] == 'D') { char c = g_SeqQ[SeqPos]; Repeat.push_back(c); ++SeqPos; ++RepeatLength; } else Repeat.push_back('-'); } if (!RepeatLengths.empty() && RepeatLength != RepeatLengths[0]) return false; RepeatLengths.push_back(RepeatLength); EndPosOfLastRepeat = RepeatPos + RepeatLength - 1; while (Repeat.size() < (size_t) ConsSeqLength1) Repeat.push_back('-'); Repeats.push_back(Repeat); } for (int i = 0; i < MissedRepeatCount; ++i) AA1.Repeats.push_back(Repeats[i]); for (int i = 0; i < MissedRepeatCount; ++i) { std::string &LeftFlank = *new std::string; int LeftFlankStartPos = RepeatStartPos[i] - g_FlankSize; for (int i = 0; i < g_FlankSize; ++i) { char c = g_SeqQ[LeftFlankStartPos + i]; LeftFlank.push_back(c); } AA1.LeftFlanks.push_back(LeftFlank); } int OldCount = (int) AA1.Spacers.size(); std::string &Spacer = *new std::string; int RepeatStartPos0 = RepeatStartPos[0]; int LastSpacerEndPos = RepeatStartPos0 - 1; assert(LastSpacerEndPos > LastSpacerStartPos); int Length = LastSpacerEndPos - LastSpacerStartPos + 1; for (int i = 0; i < Length; ++i) { char c = g_SeqQ[LastSpacerStartPos + i]; Spacer.push_back(c); } AA1.Spacers[OldCount-1] = Spacer; for (int i = 0; i < MissedRepeatCount; ++i) { std::string &Spacer = *new std::string; int SpacerStartPos = RepeatStartPos[i] + UnalignedLength(AA1.Repeats[OldCount+i]); int SpacerEndPos; if (i == MissedRepeatCount - 1) SpacerEndPos = AA2.Pos - 1; else SpacerEndPos = RepeatStartPos[i+1] - 1; assert(SpacerEndPos > SpacerStartPos); int Length = SpacerEndPos - SpacerStartPos + 1; for (int i = 0; i < Length; ++i) { char c = g_SeqQ[SpacerStartPos + i]; Spacer.push_back(c); } AA1.Spacers.push_back(Spacer); } size_t RepeatCount2 = AA2.Repeats.size(); size_t RepeatLength = 0; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount2; ++RepeatIndex) { AA1.LeftFlanks.push_back(AA2.LeftFlanks[RepeatIndex]); std::string Repeat = AA2.Repeats[RepeatIndex]; AA1.Repeats.push_back(Repeat); const std::string &Spacer = AA2.Spacers[RepeatIndex]; size_t L = Spacer.size(); AA1.Spacers.push_back(Spacer); } ValidateAA(AA1); Log(""MergeAAs\n""); return true; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/info.cpp",".cpp","3651","84","#include ""pilercr.h"" void Info() { Out ( ""Help on reading this report\n"" ""===========================\n"" ""\n"" ""This report has three sections: Detailed, Summary by Similarity\n"" ""and Summary by Position.\n"" ""\n"" ""The detailed section shows each repeat in each putative\n"" ""CRISPR array.\n"" ""\n"" ""The summary sections give one line for each array.\n"" ""\n"" ""An 'array' is a contiguous sequence of CRISPR repeats\n"" ""looking like this:\n"" ""\n"" "" REPEAT Spacer REPEAT Spacer REPEAT ... Spacer REPEAT\n"" ""\n"" ""Within one array, repeats have high similarity and spacers\n"" ""are, roughly speaking, unique within a window around the array.\n"" ""In a given array, each repeat has a similar length, and each\n"" ""spacer has a similar length. With default parameters, the\n"" ""algorithm allows a fair amount of variability in order to\n"" ""maximize sensitivity. This may allow identification of\n"" ""inactive (\""fossil\"") arrays, and may in rare cases also\n"" ""induce false positives due to other classes of repeats\n"" ""such as microsatellites, LTRs and arrays of RNA genes.\n"" ""\n"" ""\n"" ""Columns in the detailed section are:\n"" ""\n"" "" Pos Sequence position, starting at 1 for the first base.\n"" "" Repeat Length of the repeat.\n"" "" %%id Identity with the consensus sequence.\n"" "" Spacer Length of spacer to the right of this repeat.\n"" "" Left flank 10 bases to the left of this repeat.\n"" "" Repeat Sequence of this repeat.\n"" "" Dots indicate positions where this repeat\n"" "" agrees with the consensus sequence below.\n"" "" Spacer Sequence of spacer to the right of this repeat,\n"" "" or 10 bases if this is the last repeat.\n"" ""\n"" ""The left flank sequence duplicates the end of the spacer for the preceding\n"" ""repeat; it is provided to facilitate visual identification of cases\n"" ""where the algorithm does not correctly identify repeat endpoints.\n"" ""\n"" ""At the end of each array there is a sub-heading that gives the average\n"" ""repeat length, average spacer length and consensus sequence.\n"" ""\n"" ""Columns in the summary sections are:\n"" ""\n"" "" Array Number 1, 2 ... referring back to the detailed report.\n"" "" Sequence FASTA label of the sequence. May be truncated.\n"" "" From Start position of array.\n"" "" To End position of array.\n"" "" # copies Number of repeats in the array.\n"" "" Repeat Average repeat length.\n"" "" Spacer Average spacer length.\n"" "" + +/-, indicating orientation relative to first array in group.\n"" "" Distance Distance from previous array.\n"" "" Consensus Consensus sequence.\n"" ""\n"" ""In the Summary by Similarity section, arrays are grouped by similarity of their\n"" ""consensus sequences. If consensus sequences are sufficiently similar, they are\n"" ""aligned to each other to indicate probable relationships between arrays.\n"" ""\n"" ""In the Summary by Position section, arrays are sorted by position within the\n"" ""input sequence file.\n"" ""\n"" ""The Distance column facilitates identification of cases where a single\n"" ""array has been reported as two adjacent arrays. In such a case, (a) the\n"" ""consensus sequences will be similar or identical, and (b) the distance\n"" ""will be approximately a small multiple of the repeat length + spacer length.\n"" ""\n"" ""Use the -noinfo option to turn off this help.\n"" ""Use the -help option to get a list of command line options.\n"" ""\n"" ); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/log.cpp",".cpp","930","53","#include ""pilercr.h"" static FILE *g_fLog = 0; void SetLog() { bool Append = false; const char *FileName = ValueOpt(""log""); if (0 == FileName) { FileName = ValueOpt(""loga""); if (0 == FileName) return; Append = true; } g_fLog = fopen(FileName, Append ? ""a"" : ""w""); if (NULL == g_fLog) { fprintf(stderr, ""\n*** FATAL ERROR *** Cannot open log file\n""); perror(FileName); exit(1); } setbuf(g_fLog, 0); } void Log(const char Format[], ...) { if (0 == g_fLog) return; char Str[4096]; va_list ArgList; va_start(ArgList, Format); vsprintf(Str, Format, ArgList); fprintf(g_fLog, ""%s"", Str); if (g_FlushLog) fflush(g_fLog); } void Out(const char Format[], ...) { if (0 == g_fOut) return; char Str[4096]; va_list ArgList; va_start(ArgList, Format); vsprintf(Str, Format, ArgList); fprintf(g_fOut, ""%s"", Str); Log(""%s"", Str); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/loghits.cpp",".cpp","1050","46","#include ""pilercr.h"" static void LocalLogHit(int HitIndex) { const DPHit &Hit = GetHit(HitIndex); Seq *A = new Seq; Seq *B = new Seq; GetSubseq(Hit.aLo, Hit.aHi-1, *A); GetSubseq(Hit.bLo, Hit.bHi-1, *B); A->SetName(""A""); B->SetName(""B""); SeqVect Seqs; Seqs.push_back(A); Seqs.push_back(B); MSA Aln; MultipleAlign(Seqs, Aln); unsigned ColCount = Aln.GetColCount(); Log(""%5d %7d %7d %6d %5d "", HitIndex, Hit.aLo, Hit.aHi, Hit.aHi - Hit.aLo + 1, GetSpacerLength(Hit)); for (unsigned Col = 0; Col < ColCount; ++Col) Log(""%c"", Aln.GetChar(0, Col)); Log(""\n""); Log(""%5d %7d %7d %6d "", HitIndex, Hit.bLo, Hit.bHi, Hit.bHi - Hit.bLo + 1); for (unsigned Col = 0; Col < ColCount; ++Col) Log(""%c"", Aln.GetChar(1, Col)); Log(""\n""); Log(""\n""); } void LogHits() { Log(""\n""); Log("" Hit Lo Hi Length Space\n""); Log(""===== ======= ======= ====== =====\n""); for (int HitIndex = 0; HitIndex < g_HitCount; ++HitIndex) LocalLogHit(HitIndex); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/distcalc.cpp",".cpp","493","28","#include ""multaln.h"" void DistCalcDF::Init(const DistFunc &DF) { m_ptrDF = &DF; } void DistCalcDF::CalcDistRange(unsigned i, dist_t Dist[]) const { for (unsigned j = 0; j < i; ++j) Dist[j] = m_ptrDF->GetDist(i, j); } unsigned DistCalcDF::GetCount() const { return m_ptrDF->GetCount(); } unsigned DistCalcDF::GetId(unsigned i) const { return m_ptrDF->GetId(i); } const char *DistCalcDF::GetName(unsigned i) const { return m_ptrDF->GetName(i); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/progress.h",".h","355","15","#ifndef PROGRESS_H #define PROGRESS_H void ShowProgress(bool Show); void Progress(const char *Format, ...); void ProgressNoRes(const char *Format, ...); void ProgressStart(const char *Format, ...); void ProgressStep(int StepIndex, int StepCount); void ProgressDone(); void ProgressExit(); extern bool g_ShowProgress; #endif // PROGRESS_H ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/savetraps.cpp",".cpp","1330","52","#include ""pilercr.h"" static int GetTargetPos(int QueryPos, int DiagIndex) { return QueryPos - DiagIndex; } static void SaveTrap(FILE *f, const Trapezoid &Trap) { int QueryFrom = Trap.bot; int QueryTo = Trap.top; int TargetFrom = GetTargetPos(Trap.bot, Trap.rgt); int TargetTo = GetTargetPos(Trap.top, Trap.lft); WriteGFFRecord(f, QueryFrom, QueryTo, TargetFrom, TargetTo, false, ""trap"", 0, 0); } void SaveTraps(const Trapezoid *Traps) { const char *FileName = ValueOpt(""traps""); if (FileName == 0) return; FILE *f = CreateStdioFile(FileName); for (const Trapezoid *Trap = Traps; Trap; Trap = Trap->next) SaveTrap(f, *Trap); fclose(f); } static void LogTrap(const Trapezoid &Trap) { int TargetFrom = GetTargetPos(Trap.bot, Trap.rgt); int TargetTo = GetTargetPos(Trap.top, Trap.lft); Log(""%10d %10d %10d %10d %10d %10d\n"", Trap.bot, Trap.top, Trap.lft, Trap.rgt, TargetFrom, TargetTo); } void LogTraps(const Trapezoid *Traps) { if (!FlagOpt(""logtraps"")) return; Log(""\n""); Log("" QFrom QTo Left Right TFrom TTo\n""); Log(""========== ========== ========== ========== ========== ==========\n""); for (const Trapezoid *Trap = Traps; Trap; Trap = Trap->next) LogTrap(*Trap); Log(""\n""); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/pwpath.cpp",".cpp","7331","305","#include ""multaln.h"" PWPath::PWPath() { m_uArraySize = 0; m_uEdgeCount = 0; m_Edges = 0; } PWPath::~PWPath() { Clear(); } void PWPath::Clear() { delete[] m_Edges; m_Edges = 0; m_uArraySize = 0; m_uEdgeCount = 0; } void PWPath::ExpandPath(unsigned uAdditionalEdgeCount) { PWEdge *OldPath = m_Edges; unsigned uEdgeCount = m_uArraySize + uAdditionalEdgeCount; m_Edges = new PWEdge[uEdgeCount]; m_uArraySize = uEdgeCount; if (m_uEdgeCount > 0) memcpy(m_Edges, OldPath, m_uEdgeCount*sizeof(PWEdge)); delete[] OldPath; } void PWPath::AppendEdge(const PWEdge &Edge) { if (0 == m_uArraySize || m_uEdgeCount + 1 == m_uArraySize) ExpandPath(200); m_Edges[m_uEdgeCount] = Edge; ++m_uEdgeCount; } void PWPath::AppendEdge(char cType, unsigned uPrefixLengthA, unsigned uPrefixLengthB) { PWEdge e; e.uPrefixLengthA = uPrefixLengthA; e.uPrefixLengthB = uPrefixLengthB; e.cType = cType; AppendEdge(e); } void PWPath::PrependEdge(const PWEdge &Edge) { if (0 == m_uArraySize || m_uEdgeCount + 1 == m_uArraySize) ExpandPath(1000); if (m_uEdgeCount > 0) memmove(m_Edges + 1, m_Edges, sizeof(PWEdge)*m_uEdgeCount); m_Edges[0] = Edge; ++m_uEdgeCount; } const PWEdge &PWPath::GetEdge(unsigned uEdgeIndex) const { assert(uEdgeIndex < m_uEdgeCount); return m_Edges[uEdgeIndex]; } void PWPath::Validate() const { const unsigned uEdgeCount = GetEdgeCount(); if (0 == uEdgeCount) return; const PWEdge &FirstEdge = GetEdge(0); const PWEdge &LastEdge = GetEdge(uEdgeCount - 1); unsigned uStartA = FirstEdge.uPrefixLengthA; unsigned uStartB = FirstEdge.uPrefixLengthB; if (FirstEdge.cType != 'I') --uStartA; if (FirstEdge.cType != 'D') --uStartB; unsigned uPrefixLengthA = FirstEdge.uPrefixLengthA; unsigned uPrefixLengthB = FirstEdge.uPrefixLengthB; for (unsigned uEdgeIndex = 1; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &Edge = GetEdge(uEdgeIndex); switch (Edge.cType) { case 'M': if (uPrefixLengthA + 1 != Edge.uPrefixLengthA) Quit(""PWPath::Validate MA %u"", uPrefixLengthA); if (uPrefixLengthB + 1 != Edge.uPrefixLengthB) Quit(""PWPath::Validate MB %u"", uPrefixLengthB); ++uPrefixLengthA; ++uPrefixLengthB; break; case 'D': if (uPrefixLengthA + 1 != Edge.uPrefixLengthA) Quit(""PWPath::Validate DA %u"", uPrefixLengthA); if (uPrefixLengthB != Edge.uPrefixLengthB) Quit(""PWPath::Validate DB %u"", uPrefixLengthB); ++uPrefixLengthA; break; case 'I': if (uPrefixLengthA != Edge.uPrefixLengthA) Quit(""PWPath::Validate IA %u"", uPrefixLengthA); if (uPrefixLengthB + 1 != Edge.uPrefixLengthB) Quit(""PWPath::Validate IB %u"", uPrefixLengthB); ++uPrefixLengthB; break; } } } void PWPath::LogMe() const { for (unsigned uEdgeIndex = 0; uEdgeIndex < GetEdgeCount(); ++uEdgeIndex) { const PWEdge &Edge = GetEdge(uEdgeIndex); if (uEdgeIndex > 0) Log("" ""); Log(""%c%d.%d"", Edge.cType, Edge.uPrefixLengthA, Edge.uPrefixLengthB); if ((uEdgeIndex > 0 && uEdgeIndex%10 == 0) || uEdgeIndex == GetEdgeCount() - 1) Log(""\n""); } } void PWPath::Copy(const PWPath &Path) { Clear(); const unsigned uEdgeCount = Path.GetEdgeCount(); for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &Edge = Path.GetEdge(uEdgeIndex); AppendEdge(Edge); } } void PWPath::FromMSAPair(const MSA &msaA, const MSA &msaB) { const unsigned uColCount = msaA.GetColCount(); if (uColCount != msaB.GetColCount()) Quit(""PWPath::FromMSAPair, lengths differ""); Clear(); unsigned uPrefixLengthA = 0; unsigned uPrefixLengthB = 0; for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { bool bIsGapA = msaA.IsGapColumn(uColIndex); bool bIsGapB = msaB.IsGapColumn(uColIndex); PWEdge Edge; char cType; if (!bIsGapA && !bIsGapB) { cType = 'M'; ++uPrefixLengthA; ++uPrefixLengthB; } else if (bIsGapA && !bIsGapB) { cType = 'I'; ++uPrefixLengthB; } else if (!bIsGapA && bIsGapB) { cType = 'D'; ++uPrefixLengthA; } else { assert(bIsGapB && bIsGapA); continue; } Edge.cType = cType; Edge.uPrefixLengthA = uPrefixLengthA; Edge.uPrefixLengthB = uPrefixLengthB; AppendEdge(Edge); } } void PWPath::AssertEqual(const PWPath &Path) const { const unsigned uEdgeCount = GetEdgeCount(); if (uEdgeCount != Path.GetEdgeCount()) { Log(""PWPath::AssertEqual, this=\n""); LogMe(); Log(""\nOther path=\n""); Path.LogMe(); Log(""\n""); Quit(""PWPath::AssertEqual, Edge count different %u %u\n"", uEdgeCount, Path.GetEdgeCount()); } for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &e1 = GetEdge(uEdgeIndex); const PWEdge &e2 = Path.GetEdge(uEdgeIndex); if (e1.cType != e2.cType || e1.uPrefixLengthA != e2.uPrefixLengthA || e1.uPrefixLengthB != e2.uPrefixLengthB) { Log(""PWPath::AssertEqual, this=\n""); LogMe(); Log(""\nOther path=\n""); Path.LogMe(); Log(""\n""); Log(""This edge %c%u.%u, other edge %c%u.%u\n"", e1.cType, e1.uPrefixLengthA, e1.uPrefixLengthB, e2.cType, e2.uPrefixLengthA, e2.uPrefixLengthB); Quit(""PWPath::AssertEqual, edge %u different\n"", uEdgeIndex); } } } bool PWPath::Equal(const PWPath &Path) const { const unsigned uEdgeCount = GetEdgeCount(); if (uEdgeCount != Path.GetEdgeCount()) return false; for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &e1 = GetEdge(uEdgeIndex); const PWEdge &e2 = Path.GetEdge(uEdgeIndex); if (e1.cType != e2.cType || e1.uPrefixLengthA != e2.uPrefixLengthA || e1.uPrefixLengthB != e2.uPrefixLengthB) return false; } return true; } unsigned PWPath::GetMatchCount() const { unsigned uMatchCount = 0; const unsigned uEdgeCount = GetEdgeCount(); for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &e = GetEdge(uEdgeIndex); if ('M' == e.cType) ++uMatchCount; } return uMatchCount; } unsigned PWPath::GetInsertCount() const { unsigned uInsertCount = 0; const unsigned uEdgeCount = GetEdgeCount(); for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &e = GetEdge(uEdgeIndex); if ('I' == e.cType) ++uInsertCount; } return uInsertCount; } unsigned PWPath::GetDeleteCount() const { unsigned uDeleteCount = 0; const unsigned uEdgeCount = GetEdgeCount(); for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &e = GetEdge(uEdgeIndex); if ('D' == e.cType) ++uDeleteCount; } return uDeleteCount; } void PWPath::FromStr(const char Str[]) { Clear(); unsigned uPrefixLengthA = 0; unsigned uPrefixLengthB = 0; while (char c = *Str++) { switch (c) { case 'M': ++uPrefixLengthA; ++uPrefixLengthB; break; case 'D': ++uPrefixLengthA; break; case 'I': ++uPrefixLengthB; break; default: Quit(""PWPath::FromStr, invalid state %c"", c); } AppendEdge(c, uPrefixLengthA, uPrefixLengthB); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/findarrays.cpp",".cpp","5468","234","#include ""pilercr.h"" #include #define TRACE 0 static IntVec g_PIPos; void LogPile(int PileIndex) { const PileData &Pile = GetPile(PileIndex); Log(""Pile%d Lo=%d Hi=%d %s"", PileIndex, Pile.Lo, Pile.Hi, Pile.Deleted ? ""DEL"" : """"); } static int GetSpacer(int Index) { const int Count = (int) g_PIPos.size(); assert(Index >= 0 && Index < Count); int PileIndex = g_PIPos[Index]; const PileData &Pile = GetPile(PileIndex); for (int i = Index + 1; i < Count; ++i) { int NextPileIndex = g_PIPos[i]; const PileData &NextPile = GetPile(NextPileIndex); if (NextPile.Deleted) continue; return NextPile.Lo - Pile.Hi; } return -1; } static bool CmpPileIndexesLo(int PileIndex1, int PileIndex2) { const PileData &Pile1 = GetPile(PileIndex1); const PileData &Pile2 = GetPile(PileIndex2); return Pile1.Lo < Pile2.Lo; } static bool CmpIndexesSpacer(int Index1, int Index2) { return GetSpacer(Index1) < GetSpacer(Index2); } static void GetArray(int Index, IntVec &ArrayPileIndexes) { #if TRACE Log(""GetArray(Index=%d, PileIndex=%d)\n"", Index, g_PIPos[Index]); #endif ArrayPileIndexes.clear(); const int RootPileIndex = g_PIPos[Index]; const PileData Pile = GetPile(RootPileIndex); if (Pile.Deleted) return; if (GetSpacer(Index) < g_DraftMinSpacerLength) return; int PileLength = GetPileLength(Pile); int PileSpacer = GetSpacer(Index); const int Count = (int) g_PIPos.size(); ArrayPileIndexes.push_back(RootPileIndex); for (int PrevIndex = Index - 1; PrevIndex >= 0; --PrevIndex) { int PrevPileIndex = g_PIPos[PrevIndex]; const PileData &PrevPile = GetPile(PrevPileIndex); #if TRACE Log(""PrevPile = ""); LogPile(PrevPileIndex); Log(""\n""); #endif if (PrevPile.Deleted) continue; int PrevPileLength = GetPileLength(PrevPile); int PrevPileSpacer = GetSpacer(PrevIndex); if (PrevPileSpacer < g_DraftMinSpacerLength) break; double LengthRatio = GetRatio(PileLength, PrevPileLength); double SpacerRatio = GetRatio(PileSpacer + g_SpacerPadding, PrevPileSpacer + g_SpacerPadding); #if TRACE Log("" Spacer=%d PrevSpacer=%d LenR=%.1f SpacerR=%.1f "", PileSpacer, PrevPileSpacer, LengthRatio, SpacerRatio); #endif if (LengthRatio < g_DraftMinHitRatio || SpacerRatio < g_DraftMinSpacerRatio) { #if TRACE Log(""Bad ratio\n""); #endif break; } #if TRACE Log(""++ Add pile index %d\n"", PrevPileIndex); #endif ArrayPileIndexes.push_back(PrevPileIndex); } for (int NextIndex = Index + 1; NextIndex < Count; ++NextIndex) { int NextPileIndex = g_PIPos[NextIndex]; if (NextIndex == Count - 1) { ArrayPileIndexes.push_back(NextPileIndex); break; } const PileData &NextPile = GetPile(NextPileIndex); #if TRACE Log(""NextPile = ""); LogPile(NextPileIndex); Log(""\n""); #endif if (NextPile.Deleted) continue; int NextPileLength = GetPileLength(NextPile); int NextPileSpacer = GetSpacer(NextIndex); double LengthRatio = GetRatio(PileLength, NextPileLength); double SpacerRatio = GetRatio(PileSpacer + g_SpacerPadding, NextPileSpacer + g_SpacerPadding); #if TRACE Log("" Spacer=%d NextSpacer=%d LenR=%.1f SpacerR=%.1f "", PileSpacer, NextPileSpacer, LengthRatio, SpacerRatio); #endif if (LengthRatio < g_DraftMinHitRatio || SpacerRatio < g_DraftMinSpacerRatio) { #if TRACE Log(""Bad ratio\n""); #endif break; } #if TRACE Log(""++ Add pile index %d\n"", NextPileIndex); #endif ArrayPileIndexes.push_back(NextPileIndex); } #if TRACE Log(""GetArray done, size=%d\n"", (int) ArrayPileIndexes.size()); #endif if ((int) ArrayPileIndexes.size() < g_DraftMinArraySize) { DeletePile(RootPileIndex); ArrayPileIndexes.clear(); } } unsigned g_ArrayCount = 0; void FindArrays(const CompData &Comp, std::vector &ADVec) { const int CompSize = (int) Comp.size(); if (CompSize < g_DraftMinArraySize) return; // g_PIPos is pile indexes sorted by genome pos g_PIPos.resize(CompSize); int Count = 0; for (CompData::const_iterator p = Comp.begin(); p != Comp.end(); ++p) { const CompMemberData &Node = *p; int PileIndex = Node.PileIndex; g_PIPos[Count] = PileIndex; ++Count; } assert(Count == CompSize); // Sort by genome position std::sort(g_PIPos.begin(), g_PIPos.end(), CmpPileIndexesLo); #if TRACE { Log(""After sort by pos:\n""); for (int i = 0; i < CompSize; ++i) { Log(""Index=%d "", i); int PileIndex = g_PIPos[i]; LogPile(PileIndex); Log("" Length=%d"", GetPileLength(g_Piles[PileIndex])); Log("" Spacer=%d\n"", GetSpacer(i)); } } #endif // Sort by spacer lengths // ISpacer is indexes into g_PIPos sorted by spacer length IntVec ISpacer; ISpacer.resize(Count); for (int i = 0; i < Count; ++i) ISpacer[i] = i; std::sort(ISpacer.begin(), ISpacer.end(), CmpIndexesSpacer); for (int i = 0; i < CompSize; ++i) { IntVec ArrayPileIndexes; GetArray(ISpacer[i], ArrayPileIndexes); if (ArrayPileIndexes.size() == 0) continue; ArrayData *AD = new ArrayData; AD->Id = ++g_ArrayCount; bool Ok = GetArrayData(ArrayPileIndexes, *AD); if (!Ok) { delete AD; continue; } ADVec.push_back(AD); for_CIntVec(ArrayPileIndexes, p) { int PileIndex = *p; DeletePile(PileIndex); } } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/clustconsr.cpp",".cpp","3735","188","#include ""pilercr.h"" #define TRACE 0 // ClusterConsRC: // Cluster consensus sequences considering the sequence // or its reverse complement, but not both. // Best entry is one with largest number // of distances smaller than the threshold // Indexes into DistFunc are 2i for i'th array, // 2i+2 for reverse complement of i'th array. static int FindBest(std::vector &AAVec, const DistFunc &DF, BoolVec &Done, IntVec &Cluster) { Cluster.clear(); const int ArrayCount = (int) AAVec.size(); const int Count = DF.GetCount(); assert(Count == 2*ArrayCount); IntVec NrUnderThresh; for (int i = 0; i < Count; ++i) NrUnderThresh.push_back(0); for (int i = 0; i < Count; ++i) { if (Done[i/2]) continue; for (int j = 0; j < Count; ++j) { if (i == j || Done[j/2]) continue; #if TRACE Log(""Dist(""); AAVec[i/2]->ConsSeq.LogMeSeqOnly(); if (i%2 == 1) Log(""-""); else Log(""+""); Log("",""); AAVec[j/2]->ConsSeq.LogMeSeqOnly(); if (j%2 == 1) Log(""-""); else Log(""+""); Log("") = %.1f"", DF.GetDist(i, j)); #endif if (DF.GetDist(i, j) <= g_ClusterMaxDist) { #if TRACE Log("" Under\n""); #endif ++(NrUnderThresh[i]); } else { #if TRACE Log("" Over\n""); #endif ; } } } #if TRACE { Log(""FindBest:\n""); for (int i = 0; i < Count; ++i) Log("" i=%d Done=%c NrUnder=%d\n"", i, Done[i] ? 'T' : 'F', NrUnderThresh[i]); } #endif int Best = -1; unsigned BestCount = 0; for (int i = 0; i < Count; ++i) { if (NrUnderThresh[i] > BestCount) { Best = i; BestCount = NrUnderThresh[i]; } } if (Best >= 0) { for (int i = 0; i < Count; ++i) { if (Done[i/2]) continue; if (DF.GetDist(Best, i) <= g_ClusterMaxDist) { ArrayAln &AA = *(AAVec[i/2]); AA.ClusterRevComp = (i%2 == 1); Done[i/2] = true; Cluster.push_back(i/2); } } } if (Cluster.size() == 0) return -1; return Best; } // Enforce convention that first array is + strand. static void FixStrand(std::vector &AAVec, IntVec &Cluster) { int First = Cluster.front(); const ArrayAln &FirstAA = *(AAVec[First]); if (!FirstAA.ClusterRevComp) return; const size_t N = Cluster.size(); for (size_t i = 0; i < N; ++i) { int ArrayIndex = Cluster[i]; assert(ArrayIndex < (int) AAVec.size()); ArrayAln &AA = *(AAVec[ArrayIndex]); AA.ClusterRevComp = !AA.ClusterRevComp; } } void ClusterConsRC(std::vector &AAVec, IntVecVec &Clusters) { SeqVect Seqs; const size_t ArrayCount = AAVec.size(); for (size_t i = 0; i < ArrayCount; ++i) { const ArrayAln &AA = *(AAVec[i]); Seqs.push_back((Seq *) &AA.ConsSeq); Seq *r = new Seq; r->Copy(AA.ConsSeq); r->RevComp(); Seqs.push_back(r); } DistFunc DF; KmerDist(Seqs, DF); #if TRACE DF.LogMe(); #endif BoolVec Done; for (size_t i = 0; i < ArrayCount; ++i) Done.push_back(false); for (;;) { IntVec Cluster; int Best = FindBest(AAVec, DF, Done, Cluster); if (Best == -1) break; FixStrand(AAVec, Cluster); Clusters.push_back(Cluster); } for (size_t i = 0; i < ArrayCount; ++i) { if (!Done[i]) { IntVec Cluster; Cluster.push_back(i); FixStrand(AAVec, Cluster); Clusters.push_back(Cluster); } } #if TRACE { Log(""%d clusters\n"", (int) Clusters.size()); for (size_t i = 0; i < (int) Clusters.size(); ++i) { const IntVec &Cluster = Clusters[i]; Log("" ""); size_t N = Cluster.size(); for (size_t j = 0; j < N; ++j) Log("" %d"", Cluster[j]); Log(""\n""); } } #endif } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/intlist.h",".h","1677","51","#ifndef IntList_H #define IntList_H #include #include #include #include typedef std::list IntList; typedef IntList::iterator IntListIter; typedef IntList::const_iterator CIntListIter; typedef std::vector IntVec; typedef IntVec::iterator IntVecIter; typedef IntVec::const_iterator CIntVecIter; typedef std::set IntSet; typedef IntSet::iterator IntSetIter; typedef IntSet::const_iterator CIntSetIter; typedef std::map IntMap; typedef IntMap::iterator IntMapIter; typedef IntMap::const_iterator CIntMapIter; typedef std::vector IntVecVec; typedef std::vector IntListList; typedef std::vector BoolVec; // Warning: sorts A and B in place: void IntersectIntLists2(IntList &A, IntList &B, IntList &Common); // More expensive but safer (makes tmp copies of A and B): void IntersectIntLists(const IntList &A, const IntList &B, IntList &Common); void LogList(const IntList &List); #define for_IntList(L, p) for (IntListIter p = L.begin(); p != L.end(); ++p) #define for_CIntList(L, p) for (CIntListIter p = L.begin(); p != L.end(); ++p) #define for_IntVec(L, p) for (IntVecIter p = L.begin(); p != L.end(); ++p) #define for_CIntVec(L, p) for (CIntVecIter p = L.begin(); p != L.end(); ++p) #define for_IntSet(L, p) for (IntSetIter p = L.begin(); p != L.end(); ++p) #define for_CIntSet(L, p) for (CIntSetIter p = L.begin(); p != L.end(); ++p) #define for_IntMap(L, p) for (IntMapIter p = L.begin(); p != L.end(); ++p) #define for_CIntMap(L, p) for (CIntMapIter p = L.begin(); p != L.end(); ++p) #endif // IntList_H ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/scoremx.cpp",".cpp","776","39","#include ""multaln.h"" const float NUC_OPEN = -400; const float NUC_EXTEND = -25; const float NUC_SP_CENTER = 2*NUC_EXTEND; float g_scoreGapExtend = NUC_EXTEND; float g_scoreGapOpen = NUC_OPEN; #define v(x) ((float) x + NUC_SP_CENTER) #define ROW(A, C, G, T) \ { v(A), v(C), v(G), v(T) }, float NUC_SP[32][32] = { // A C G T ROW( 100, -50, -50, -50) // A ROW( -50, 100, -50, -50) // C ROW( -50, -50, 100, -50) // G ROW( -50, -50, -50, 100) // T }; PTR_SCOREMATRIX g_ptrScoreMatrix = &NUC_SP; void LogMx() { for (int i = 0; i < 32; ++i) { for (int j = 0; j < 32; ++j) { Log("" %5.1f"", NUC_SP[i][j]); } Log(""\n""); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/utils_other.cpp",".cpp","308","23","#include ""pilercr.h"" #if !WIN32 && !(linux || __linux__) double GetRAMSize() { return 1e9; } static unsigned g_uPeakMemUseBytes = (unsigned) 500e6; unsigned GetPeakMemUseBytes() { return g_uPeakMemUseBytes; } unsigned GetMemUseBytes() { return (unsigned) 500e6; } #endif ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/swsimple.cpp",".cpp","4676","225","#include ""pilercr.h"" #include ""multaln.h"" #include ""sw.h"" // Simple version of Smith-Waterman. // Could certainly be made smaller & faster if desired. #define TRACE 0 #define ScoreToStr LocalScoreToStr void SWTraceBack(const unsigned char *A, unsigned LA, const unsigned char *B, unsigned LB, unsigned Topi, unsigned Topj, score_t TopScore, const score_t *DPM_, const score_t *DPD_, const score_t *DPI_, std::string &Path, unsigned *ptrStartA, unsigned *ptrStartB); static const char *ScoreToStr(score_t s) { static char str[16]; if (s <= MINUS_INF/2) return "" *""; #if INTEGER_DP sprintf(str, ""%6d"", s); #else sprintf(str, ""%6.0f"", s); #endif return str; } #if TRACE static void LogDP(const score_t *DPM_, const unsigned char *A, const unsigned char *B, unsigned PCA, unsigned PCB) { Log("" ""); for (unsigned j = 0; j < PCB; ++j) { char c = ' '; if (j > 0) c = B[j - 1]; Log("" %4u:%c"", j, c); } Log(""\n""); for (unsigned i = 0; i < PCA; ++i) { char c = ' '; if (i > 0) c = A[i - 1]; Log(""%4u:%c "", i, c); for (unsigned j = 0; j < PCB; ++j) Log("" %s"", ScoreToStr(DPM(i, j))); Log(""\n""); } } #endif // TRACE score_t SW(const Seq &A, const Seq &B, unsigned *ptrStartA, unsigned *ptrStartB, std::string &Path) { unsigned LA = A.Length(); unsigned LB = B.Length(); char *sA = all(char, LA + 1); char *sB = all(char, LB + 1); A.ToString(sA, LA + 1); B.ToString(sB, LB + 1); score_t Score = SWSimple(sA, LA, sB, LB, ptrStartA, ptrStartB, Path); freemem(sA); freemem(sB); return Score; } score_t SWSimple(const char *A_, unsigned LA, const char *B_, unsigned LB, unsigned *ptrStartA, unsigned *ptrStartB, std::string &Path) { assert(LB > 0 && LA > 0); const unsigned char *A = (const unsigned char *) A_; const unsigned char *B = (const unsigned char *) B_; Path.clear(); const unsigned PCA = LA + 1; const unsigned PCB = LB + 1; // Allocate DP matrices const unsigned LM = PCA*PCB; score_t *DPM_ = all(score_t, LM); score_t *DPD_ = all(score_t, LM); score_t *DPI_ = all(score_t, LM); // Boundaries for (unsigned j = 0; j < PCB; ++j) { // M=LetterA+LetterB, impossible with empty prefix DPM(0, j) = 0; DPD(0, j) = 0; DPI(0, j) = 0; } for (unsigned i = 0; i < PCA; ++i) { DPM(i, 0) = 0; DPD(i, 0) = 0; DPI(i, 0) = 0; } // ============ // Main DP loop // ============ score_t TopScore = -1; unsigned Topi = 0; unsigned Topj = 0; for (unsigned i = 1; i < PCA; ++i) { const unsigned char cA = A[i-1]; for (unsigned j = 1; j < PCB; ++j) { const unsigned char cB = B[j-1]; { // Match M=LetterA+LetterB score_t scoreLL = SUBST(cA, cB); score_t scoreMM = DPM(i-1, j-1); score_t scoreDM = DPD(i-1, j-1); score_t scoreIM = DPI(i-1, j-1); score_t scoreBest; if (scoreMM >= scoreDM && scoreMM >= scoreIM) scoreBest = scoreMM; else if (scoreDM >= scoreMM && scoreDM >= scoreIM) scoreBest = scoreDM; else { assert(scoreIM >= scoreMM && scoreIM >= scoreDM); scoreBest = scoreIM; } score_t s = scoreBest + scoreLL; if (s > 0) { DPM(i, j) = s; if (s > TopScore) { TopScore = s; Topi = i; Topj = j; } } else DPM(i, j) = 0; } { // Delete D=LetterA+GapB score_t scoreMD = DPM(i-1, j) + GAPOPEN; score_t scoreDD = DPD(i-1, j) + GAPEXTEND; score_t scoreBest; if (scoreMD >= scoreDD) scoreBest = scoreMD; else { assert(scoreDD >= scoreMD); scoreBest = scoreDD; } if (scoreBest < 0) scoreBest = 0; DPD(i, j) = scoreBest; } // Insert I=GapA+LetterB { score_t scoreMI = DPM(i, j-1) + GAPOPEN; score_t scoreII = DPI(i, j-1) + GAPEXTEND; score_t scoreBest; if (scoreMI >= scoreII) scoreBest = scoreMI; else { assert(scoreII > scoreMI); scoreBest = scoreII; } if (scoreBest < 0) scoreBest = 0; DPI(i, j) = scoreBest; } } } #if TRACE Log(""DPM:\n""); LogDP(DPM_, A, B, PCA, PCB); Log(""DPD:\n""); LogDP(DPD_, A, B, PCA, PCB); Log(""DPI:\n""); LogDP(DPI_, A, B, PCA, PCB); #endif if (TopScore < 0) { *ptrStartA = 0; *ptrStartB = 0; return 0; } #if TRACE Log(""TopScore=%d Topi=%u Topj=%u\n"", TopScore, Topi, Topj); #endif SWTraceBack(A, LA, B, LB, Topi, Topj, TopScore, DPM_, DPD_, DPI_, Path, ptrStartA, ptrStartB); freemem(DPM_); freemem(DPD_); freemem(DPI_); return TopScore; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/distcalc.h",".h","1028","45","#ifndef DistCalc_h #define DistCalc_h typedef float dist_t; const dist_t BIG_DIST = (dist_t) 1e29; class DistFunc; class DistCalc { public: virtual void CalcDistRange(unsigned i, dist_t Dist[]) const = 0; virtual unsigned GetCount() const = 0; virtual unsigned GetId(unsigned i) const = 0; virtual const char *GetName(unsigned i) const = 0; }; class DistCalcDF : public DistCalc { public: void Init(const DistFunc &DF); virtual void CalcDistRange(unsigned i, dist_t Dist[]) const; virtual unsigned GetCount() const; virtual unsigned GetId(unsigned i) const; virtual const char *GetName(unsigned i) const; private: const DistFunc *m_ptrDF; }; class DistCalcMSA : public DistCalc { public: void Init(const MSA &msa); virtual void CalcDistRange(unsigned i, dist_t Dist[]) const; virtual unsigned GetCount() const; virtual unsigned GetId(unsigned i) const; virtual const char *GetName(unsigned i) const; private: const MSA *m_ptrMSA; }; #endif // DistCalc_h ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/params.cpp",".cpp","1016","42","#include ""params.h"" int g_DraftMinRepeatLength = 16; int g_DraftMaxRepeatLength = 128; int g_DraftMinSpacerLength = 8; int g_DraftMaxSpacerLength = 256; int g_DraftMinArraySize = 3; double g_DraftMinHitRatio = 0.6; double g_DraftMinSpacerRatio = 0.6; double g_DraftMinCons = 0.95; double g_DraftMinColCons = 0.90; int g_MinRepeatLength = 16; int g_MaxRepeatLength = 64; int g_MinSpacerLength = 8; int g_MaxSpacerLength = 64; int g_MinArraySize = 3; double g_MinRepeatRatio = 0.9; double g_MinSpacerRatio = 0.75; double g_MinCons = 0.90; int g_MaxMSASeqs = 4096; int g_HitPadding = 8; int g_FlankSize = 10; int g_MinOneDiff = 3; int g_PileExpandMargin = 8; int g_MinDiag = 8; int g_MaxDPHitLen = 512; int g_SpacerPadding = 16; double g_ClusterMaxDist = 0.5; double g_ColonThresh = 0.95; TERMGAPS g_TermGaps = TERMGAPS_Ext; bool g_ShowHits = false; bool g_LogHits = false; bool g_LogImages = false; bool g_LogAlns = false; bool g_FlushLog = false; bool g_NoInfo = false; ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/glbalign.cpp",".cpp","17237","711","#include ""multaln.h"" // NW small memory #define TRACE 0 #if TRACE extern bool g_bKeepSimpleDP; extern SCORE *g_DPM; extern SCORE *g_DPD; extern SCORE *g_DPI; extern char *g_TBM; extern char *g_TBD; extern char *g_TBI; #endif #if TRACE #define ALLOC_TRACE() \ const SCORE UNINIT = MINUS_INFINITY; \ const size_t LM = uPrefixCountA*uPrefixCountB; \ \ SCORE *DPM_ = new SCORE[LM]; \ SCORE *DPD_ = new SCORE[LM]; \ SCORE *DPI_ = new SCORE[LM]; \ \ char *TBM_ = new char[LM]; \ char *TBD_ = new char[LM]; \ char *TBI_ = new char[LM]; \ \ memset(TBM_, '?', LM); \ memset(TBD_, '?', LM); \ memset(TBI_, '?', LM); \ \ for (unsigned i = 0; i <= uLengthA; ++i) \ for (unsigned j = 0; j <= uLengthB; ++j) \ { \ DPM(i, j) = UNINIT; \ DPD(i, j) = UNINIT; \ DPI(i, j) = UNINIT; \ } #else #define ALLOC_TRACE() #endif #if TRACE #define SetDPM(i, j, x) DPM(i, j) = x #define SetDPD(i, j, x) DPD(i, j) = x #define SetDPI(i, j, x) DPI(i, j) = x #define SetTBM(i, j, x) TBM(i, j) = x #define SetTBD(i, j, x) TBD(i, j) = x #define SetTBI(i, j, x) TBI(i, j) = x #else #define SetDPM(i, j, x) /* empty */ #define SetDPD(i, j, x) /* empty */ #define SetDPI(i, j, x) /* empty */ #define SetTBM(i, j, x) /* empty */ #define SetTBD(i, j, x) /* empty */ #define SetTBI(i, j, x) /* empty */ #endif #define Rotate(a, b, c) { SCORE *tmp = a; a = b; b = c; c = tmp; } #define RECURSE_D(i, j) \ { \ SCORE DD = DRow[j] + e; \ SCORE MD = MPrev[j] + PA[i-1].m_scoreGapOpen;\ if (DD > MD) \ { \ DRow[j] = DD; \ SetTBD(i, j, 'D'); \ } \ else \ { \ DRow[j] = MD; \ /* SetBitTBD(TB, i, j, 'M'); */ \ TBRow[j] &= ~BIT_xD; \ TBRow[j] |= BIT_MD; \ SetTBD(i, j, 'M'); \ } \ SetDPD(i, j, DRow[j]); \ } #define RECURSE_D_ATerm(j) RECURSE_D(uLengthA, j) #define RECURSE_D_BTerm(j) RECURSE_D(i, uLengthB) #define RECURSE_I(i, j) \ { \ Iij += e; \ SCORE MI = MCurr[j-1] + PB[j-1].m_scoreGapOpen;\ if (MI >= Iij) \ { \ Iij = MI; \ /* SetBitTBI(TB, i, j, 'M'); */ \ TBRow[j] &= ~BIT_xI; \ TBRow[j] |= BIT_MI; \ SetTBI(i, j, 'M'); \ } \ else \ SetTBI(i, j, 'I'); \ SetDPI(i, j, Iij); \ } #define RECURSE_I_ATerm(j) RECURSE_I(uLengthA, j) #define RECURSE_I_BTerm(j) RECURSE_I(i, uLengthB) #define RECURSE_M(i, j) \ { \ SCORE DM = DRow[j] + PA[i-1].m_scoreGapClose; \ SCORE IM = Iij + PB[j-1].m_scoreGapClose; \ SCORE MM = MCurr[j]; \ TB[i+1][j+1] &= ~BIT_xM; \ if (MM >= DM && MM >= IM) \ { \ MNext[j+1] += MM; \ SetDPM(i+1, j+1, MNext[j+1]); \ SetTBM(i+1, j+1, 'M'); \ /* SetBitTBM(TB, i+1, j+1, 'M'); */ \ TB[i+1][j+1] |= BIT_MM; \ } \ else if (DM >= MM && DM >= IM) \ { \ MNext[j+1] += DM; \ SetDPM(i+1, j+1, MNext[j+1]); \ SetTBM(i+1, j+1, 'D'); \ /* SetBitTBM(TB, i+1, j+1, 'D'); */ \ TB[i+1][j+1] |= BIT_DM; \ } \ else \ { \ assert(IM >= MM && IM >= DM); \ MNext[j+1] += IM; \ SetDPM(i+1, j+1, MNext[j+1]); \ SetTBM(i+1, j+1, 'I'); \ /* SetBitTBM(TB, i+1, j+1, 'I'); */ \ TB[i+1][j+1] |= BIT_IM; \ } \ } #if TRACE static bool LocalEq(BASETYPE b1, BASETYPE b2) { if (b1 < -100000 && b2 < -100000) return true; double diff = fabs(b1 - b2); if (diff < 0.0001) return true; double sum = fabs(b1) + fabs(b2); return diff/sum < 0.005; } static char Get_M_Char(char Bits) { switch (Bits & BIT_xM) { case BIT_MM: return 'M'; case BIT_DM: return 'D'; case BIT_IM: return 'I'; } Quit(""Huh?""); return '?'; } static char Get_D_Char(char Bits) { return (Bits & BIT_xD) ? 'M' : 'D'; } static char Get_I_Char(char Bits) { return (Bits & BIT_xI) ? 'M' : 'I'; } static bool DPEq(char c, SCORE *g_DP, SCORE *DPD_, unsigned uPrefixCountA, unsigned uPrefixCountB) { SCORE *DPM_ = g_DP; for (unsigned i = 0; i < uPrefixCountA; ++i) for (unsigned j = 0; j < uPrefixCountB; ++j) if (!LocalEq(DPM(i, j), DPD(i, j))) { Log(""***DPDIFF*** DP%c(%d, %d) Simple = %.2g, Fast = %.2g\n"", c, i, j, DPM(i, j), DPD(i, j)); return false; } return true; } static bool CompareTB(char **TB, char *TBM_, char *TBD_, char *TBI_, unsigned uPrefixCountA, unsigned uPrefixCountB) { SCORE *DPM_ = g_DPM; bool Eq = true; for (unsigned i = 0; i < uPrefixCountA; ++i) for (unsigned j = 0; j < uPrefixCountB; ++j) { char c1 = TBM(i, j); char c2 = Get_M_Char(TB[i][j]); if (c1 != '?' && c1 != c2 && DPM(i, j) > -100000) { Log(""TBM(%d, %d) Simple = %c, NW = %c\n"", i, j, c1, c2); Eq = false; goto D; } } D: SCORE *DPD_ = g_DPD; for (unsigned i = 0; i < uPrefixCountA; ++i) for (unsigned j = 0; j < uPrefixCountB; ++j) { char c1 = TBD(i, j); char c2 = Get_D_Char(TB[i][j]); if (c1 != '?' && c1 != c2 && DPD(i, j) > -100000) { Log(""TBD(%d, %d) Simple = %c, NW = %c\n"", i, j, c1, c2); Eq = false; goto I; } } I: SCORE *DPI_ = g_DPI; for (unsigned i = 0; i < uPrefixCountA; ++i) for (unsigned j = 0; j < uPrefixCountB; ++j) { char c1 = TBI(i, j); char c2 = Get_I_Char(TB[i][j]); if (c1 != '?' && c1 != c2 && DPI(i, j) > -100000) { Log(""TBI(%d, %d) Simple = %c, NW = %c\n"", i, j, c1, c2); Eq = false; goto Done; } } Done: if (Eq) Log(""TB success\n""); return Eq; } static const char *LocalScoreToStr(SCORE s) { static char str[16]; if (s < -100000) return "" *""; sprintf(str, ""%6.1f"", s); return str; } static void LogDP(const SCORE *DPM_, const ProfPos *PA, const ProfPos *PB, unsigned uPrefixCountA, unsigned uPrefixCountB) { Log("" ""); for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB) { char c = ' '; if (uPrefixLengthB > 0) c = ConsensusChar(PB[uPrefixLengthB - 1]); Log("" %4u:%c"", uPrefixLengthB, c); } Log(""\n""); for (unsigned uPrefixLengthA = 0; uPrefixLengthA < uPrefixCountA; ++uPrefixLengthA) { char c = ' '; if (uPrefixLengthA > 0) c = ConsensusChar(PA[uPrefixLengthA - 1]); Log(""%4u:%c "", uPrefixLengthA, c); for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB) Log("" %s"", LocalScoreToStr(DPM(uPrefixLengthA, uPrefixLengthB))); Log(""\n""); } } static void LogBitTB(char **TB, const ProfPos *PA, const ProfPos *PB, unsigned uPrefixCountA, unsigned uPrefixCountB) { Log("" ""); for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB) { char c = ' '; if (uPrefixLengthB > 0) c = ConsensusChar(PB[uPrefixLengthB - 1]); Log("" %4u:%c"", uPrefixLengthB, c); } Log(""\n""); Log(""Bit TBM:\n""); for (unsigned uPrefixLengthA = 0; uPrefixLengthA < uPrefixCountA; ++uPrefixLengthA) { char c = ' '; if (uPrefixLengthA > 0) c = ConsensusChar(PA[uPrefixLengthA - 1]); Log(""%4u:%c "", uPrefixLengthA, c); for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB) { char c = Get_M_Char(TB[uPrefixLengthA][uPrefixLengthB]); Log("" %6c"", c); } Log(""\n""); } Log(""\n""); Log(""Bit TBD:\n""); for (unsigned uPrefixLengthA = 0; uPrefixLengthA < uPrefixCountA; ++uPrefixLengthA) { char c = ' '; if (uPrefixLengthA > 0) c = ConsensusChar(PA[uPrefixLengthA - 1]); Log(""%4u:%c "", uPrefixLengthA, c); for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB) { char c = Get_D_Char(TB[uPrefixLengthA][uPrefixLengthB]); Log("" %6c"", c); } Log(""\n""); } Log(""\n""); Log(""Bit TBI:\n""); for (unsigned uPrefixLengthA = 0; uPrefixLengthA < uPrefixCountA; ++uPrefixLengthA) { char c = ' '; if (uPrefixLengthA > 0) c = ConsensusChar(PA[uPrefixLengthA - 1]); Log(""%4u:%c "", uPrefixLengthA, c); for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB) { char c = Get_I_Char(TB[uPrefixLengthA][uPrefixLengthB]); Log("" %6c"", c); } Log(""\n""); } } static void ListTB(char *TBM_, const ProfPos *PA, const ProfPos *PB, unsigned uPrefixCountA, unsigned uPrefixCountB) { Log("" ""); for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB) { char c = ' '; if (uPrefixLengthB > 0) c = ConsensusChar(PB[uPrefixLengthB - 1]); Log("" %4u:%c"", uPrefixLengthB, c); } Log(""\n""); for (unsigned uPrefixLengthA = 0; uPrefixLengthA < uPrefixCountA; ++uPrefixLengthA) { char c = ' '; if (uPrefixLengthA > 0) c = ConsensusChar(PA[uPrefixLengthA - 1]); Log(""%4u:%c "", uPrefixLengthA, c); for (unsigned uPrefixLengthB = 0; uPrefixLengthB < uPrefixCountB; ++uPrefixLengthB) { char c = TBM(uPrefixLengthA, uPrefixLengthB); Log("" %6c"", c); } Log(""\n""); } } static const char *BitsToStr(char Bits) { static char Str[9]; sprintf(Str, ""%cM %cD %cI"", Get_M_Char(Bits), Get_D_Char(Bits), Get_I_Char(Bits)); } #endif // TRACE static inline void SetBitTBM(char **TB, unsigned i, unsigned j, char c) { char Bit; switch (c) { case 'M': Bit = BIT_MM; break; case 'D': Bit = BIT_DM; break; case 'I': Bit = BIT_IM; break; default: Quit(""Huh?!""); } TB[i][j] &= ~BIT_xM; TB[i][j] |= Bit; } static inline void SetBitTBD(char **TB, unsigned i, unsigned j, char c) { char Bit; switch (c) { case 'M': Bit = BIT_MD; break; case 'D': Bit = BIT_DD; break; default: Quit(""Huh?!""); } TB[i][j] &= ~BIT_xD; TB[i][j] |= Bit; } static inline void SetBitTBI(char **TB, unsigned i, unsigned j, char c) { char Bit; switch (c) { case 'M': Bit = BIT_MI; break; case 'I': Bit = BIT_II; break; default: Quit(""Huh?!""); } TB[i][j] &= ~BIT_xI; TB[i][j] |= Bit; } #if TRACE #define LogMatrices() \ { \ Log(""Bit DPM:\n""); \ LogDP(DPM_, PA, PB, uPrefixCountA, uPrefixCountB); \ Log(""Bit DPD:\n""); \ LogDP(DPD_, PA, PB, uPrefixCountA, uPrefixCountB); \ Log(""Bit DPI:\n""); \ LogDP(DPI_, PA, PB, uPrefixCountA, uPrefixCountB); \ Log(""Bit TB:\n""); \ LogBitTB(TB, PA, PB, uPrefixCountA, uPrefixCountB); \ bool Same; \ Same = DPEq('M', g_DPM, DPM_, uPrefixCountA, uPrefixCountB);\ if (Same) \ Log(""DPM success\n""); \ Same = DPEq('D', g_DPD, DPD_, uPrefixCountA, uPrefixCountB);\ if (Same) \ Log(""DPD success\n""); \ Same = DPEq('I', g_DPI, DPI_, uPrefixCountA, uPrefixCountB);\ if (Same) \ Log(""DPI success\n""); \ CompareTB(TB, g_TBM, g_TBD, g_TBI, uPrefixCountA, uPrefixCountB);\ } #else #define LogMatrices() /* empty */ #endif static unsigned uCachePrefixCountB; static unsigned uCachePrefixCountA; static SCORE *CacheMCurr; static SCORE *CacheMNext; static SCORE *CacheMPrev; static SCORE *CacheDRow; static char **CacheTB; static void SetTermGaps(const ProfPos *Prof, unsigned uLength) { if (0 == uLength) return; ProfPos *First = (ProfPos *) Prof; ProfPos *Last = (ProfPos *) (Prof + uLength - 1); switch (g_TermGaps) { case TERMGAPS_Full: break; case TERMGAPS_Half: // -infinity check for lock left/right if (First->m_scoreGapOpen != MINUS_INFINITY) First->m_scoreGapOpen = 0; if (uLength > 1 && Last->m_scoreGapClose != MINUS_INFINITY) Last->m_scoreGapClose = 0; case TERMGAPS_Ext: if (First->m_scoreGapOpen != MINUS_INFINITY) First->m_scoreGapOpen *= -1; if (uLength > 1 && Last->m_scoreGapClose != MINUS_INFINITY) Last->m_scoreGapClose *= -1; break; default: Quit(""Invalid g_TermGaps""); } } static SCORE ScoreProfPos(const ProfPos &PPA, const ProfPos &PPB) { SCORE Score = 0; for (unsigned n = 0; n < 4; ++n) { const unsigned uLetter = PPA.m_uSortOrder[n]; const FCOUNT fcLetter = PPA.m_fcCounts[uLetter]; if (0 == fcLetter) break; Score += fcLetter*PPB.m_AAScores[uLetter]; } return Score; } static void AllocCache(unsigned uPrefixCountA, unsigned uPrefixCountB) { if (uPrefixCountA <= uCachePrefixCountA && uPrefixCountB <= uCachePrefixCountB) return; delete[] CacheMCurr; delete[] CacheMNext; delete[] CacheMPrev; delete[] CacheDRow; for (unsigned i = 0; i < uCachePrefixCountA; ++i) delete[] CacheTB[i]; delete[] CacheTB; uCachePrefixCountA = uPrefixCountA + 1024; uCachePrefixCountB = uPrefixCountB + 1024; CacheMCurr = new SCORE[uCachePrefixCountB]; CacheMNext = new SCORE[uCachePrefixCountB]; CacheMPrev = new SCORE[uCachePrefixCountB]; CacheDRow = new SCORE[uCachePrefixCountB]; CacheTB = new char *[uCachePrefixCountA]; for (unsigned i = 0; i < uCachePrefixCountA; ++i) CacheTB[i] = new char [uCachePrefixCountB]; } SCORE GlobalAlign(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path) { if (0 == uLengthB || 0 == uLengthA ) Quit(""Internal error, NWSmall: length=0""); SetTermGaps(PA, uLengthA); SetTermGaps(PB, uLengthB); const unsigned uPrefixCountA = uLengthA + 1; const unsigned uPrefixCountB = uLengthB + 1; const SCORE e = g_scoreGapExtend; ALLOC_TRACE() AllocCache(uPrefixCountA, uPrefixCountB); SCORE *MCurr = CacheMCurr; SCORE *MNext = CacheMNext; SCORE *MPrev = CacheMPrev; SCORE *DRow = CacheDRow; char **TB = CacheTB; for (unsigned i = 0; i < uPrefixCountA; ++i) memset(TB[i], 0, uPrefixCountB); SCORE Iij = MINUS_INFINITY; SetDPI(0, 0, Iij); Iij = PB[0].m_scoreGapOpen; SetDPI(0, 1, Iij); for (unsigned j = 2; j <= uLengthB; ++j) { Iij += e; SetDPI(0, j, Iij); SetTBI(0, j, 'I'); } for (unsigned j = 0; j <= uLengthB; ++j) { DRow[j] = MINUS_INFINITY; SetDPD(0, j, DRow[j]); SetTBD(0, j, 'D'); } MPrev[0] = 0; SetDPM(0, 0, MPrev[0]); for (unsigned j = 1; j <= uLengthB; ++j) { MPrev[j] = MINUS_INFINITY; SetDPM(0, j, MPrev[j]); } MCurr[0] = MINUS_INFINITY; SetDPM(1, 0, MCurr[0]); MCurr[1] = ScoreProfPos(PA[0], PB[0]); SetDPM(1, 1, MCurr[1]); SetBitTBM(TB, 1, 1, 'M'); SetTBM(1, 1, 'M'); for (unsigned j = 2; j <= uLengthB; ++j) { MCurr[j] = ScoreProfPos(PA[0], PB[j-1]) + PB[0].m_scoreGapOpen + (j - 2)*e + PB[j-2].m_scoreGapClose; SetDPM(1, j, MCurr[j]); SetBitTBM(TB, 1, j, 'I'); SetTBM(1, j, 'I'); } // Main DP loop for (unsigned i = 1; i < uLengthA; ++i) { char *TBRow = TB[i]; Iij = MINUS_INFINITY; SetDPI(i, 0, Iij); DRow[0] = PA[0].m_scoreGapOpen + (i - 1)*e; SetDPD(i, 0, DRow[0]); MCurr[0] = MINUS_INFINITY; if (i == 1) { MCurr[1] = ScoreProfPos(PA[0], PB[0]); SetBitTBM(TB, i, 1, 'M'); SetTBM(i, 1, 'M'); } else { MCurr[1] = ScoreProfPos(PA[i-1], PB[0]) + PA[0].m_scoreGapOpen + (i - 2)*e + PA[i-2].m_scoreGapClose; SetBitTBM(TB, i, 1, 'D'); SetTBM(i, 1, 'D'); } SetDPM(i, 0, MCurr[0]); SetDPM(i, 1, MCurr[1]); for (unsigned j = 1; j < uLengthB; ++j) MNext[j+1] = ScoreProfPos(PA[i], PB[j]); for (unsigned j = 1; j < uLengthB; ++j) { RECURSE_D(i, j) RECURSE_I(i, j) RECURSE_M(i, j) } // Special case for j=uLengthB RECURSE_D_BTerm(i) RECURSE_I_BTerm(i) // Prev := Curr, Curr := Next, Next := Prev Rotate(MPrev, MCurr, MNext); } // Special case for i=uLengthA char *TBRow = TB[uLengthA]; MCurr[0] = MINUS_INFINITY; if (uLengthA > 1) MCurr[1] = ScoreProfPos(PA[uLengthA-1], PB[0]) + (uLengthA - 2)*e + PA[0].m_scoreGapOpen + PA[uLengthA-2].m_scoreGapClose; else MCurr[1] = ScoreProfPos(PA[uLengthA-1], PB[0]) + PA[0].m_scoreGapOpen + PA[0].m_scoreGapClose; SetBitTBM(TB, uLengthA, 1, 'D'); SetTBM(uLengthA, 1, 'D'); SetDPM(uLengthA, 0, MCurr[0]); SetDPM(uLengthA, 1, MCurr[1]); DRow[0] = MINUS_INFINITY; SetDPD(uLengthA, 0, DRow[0]); for (unsigned j = 1; j <= uLengthB; ++j) RECURSE_D_ATerm(j); Iij = MINUS_INFINITY; for (unsigned j = 1; j <= uLengthB; ++j) RECURSE_I_ATerm(j) LogMatrices(); SCORE MAB = MCurr[uLengthB]; SCORE DAB = DRow[uLengthB]; SCORE IAB = Iij; SCORE Score = MAB; char cEdgeType = 'M'; if (DAB > Score) { Score = DAB; cEdgeType = 'D'; } if (IAB > Score) { Score = IAB; cEdgeType = 'I'; } #if TRACE Log("" Fast: MAB=%.4g DAB=%.4g IAB=%.4g best=%c\n"", MAB, DAB, IAB, cEdgeType); #endif BitTraceBack(TB, uLengthA, uLengthB, cEdgeType, Path); #if DBEUG Path.Validate(); #endif return 0; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/cons.cpp",".cpp","5101","246","#include ""pilercr.h"" #include ""multaln.h"" #define TRACE 0 static const char Letter[5] = { 'A', 'C', 'G', 'T', '-'}; static void GetCounts(const MSA &Aln, int ColIndex, int Counts[5]) { memset(Counts, 0, 5*sizeof(unsigned)); const int SeqCount = Aln.GetSeqCount(); for (int SeqIndex = 0; SeqIndex < SeqCount; ++SeqIndex) { char c = Aln.GetChar(SeqIndex, ColIndex); c = toupper(c); switch (c) { case 'a': case 'A': ++(Counts[0]); break; case 'c': case 'C': ++(Counts[1]); break; case 'g': case 'G': ++(Counts[2]); break; case 't': case 'T': ++(Counts[3]); break; case '-': ++(Counts[4]); break; } } } static double GetCons(const MSA &Aln, int Col, char *ptrc) { int Counts[5]; GetCounts(Aln, Col, Counts); int MaxCount = -1; char c = '?'; for (int i = 0; i < 5; ++i) { if (Counts[i] > MaxCount) { MaxCount = Counts[i]; c = Letter[i]; } } *ptrc = c; return (double) MaxCount / (double) Aln.GetSeqCount();; } #if TRACE static void LogCol(const MSA &Aln, int Col) { int SeqCount = Aln.GetSeqCount(); for (int i = 0; i < SeqCount; ++i) Log(""%c"", Aln.GetChar(i, Col)); } #endif // Column is conserved if the two preceding and two following columns // are conserved. static void GetSmoothedCons(const MSA &Aln, double MinCons, BoolVec &ColCons) { int ColCount = (int) Aln.GetColCount(); ColCons.resize(ColCount, false); for (int Col = 0; Col < ColCount; ++Col) { char c; ColCons[Col] = (GetCons(Aln, Col, &c) >= MinCons); } for (int Col = 0; Col < ColCount; ++Col) { if (ColCons[Col]) continue; if (!ColCons[Col] && (Col > 0 && ColCons[Col-1]) && (Col > 1 && ColCons[Col-2]) && (Col < ColCount - 1 && ColCons[Col+1]) && (Col < ColCount - 2 && ColCons[Col+2])) ColCons[Col] = true; } } static void FindStartEnd(const MSA &Aln, double MinCons, int *ptrStart, int *ptrEnd) { BoolVec ColCons; GetSmoothedCons(Aln, MinCons, ColCons); int BestStart = 0; int BestEnd = 0; int Length = 0; int Start = 0; int ColCount = (int) Aln.GetColCount(); for (int Col = 0; Col <= ColCount; ++Col) { #if TRACE if (Col != ColCount) LogCol(Aln, Col); #endif bool ConsOk = (Col != ColCount && ColCons[Col]); bool ContinueBlock = (Col != ColCount && ConsOk); #if TRACE if (ContinueBlock) Log("" cont\n""); else Log("" ** END BLOCK **\n""); #endif if (ContinueBlock) { if (Start == -1) { Start = Col; Length = 1; } else ++Length; } else { if (Length > BestEnd - BestStart + 1) { BestStart = Start; BestEnd = Col - 1; if (BestEnd - BestStart + 1 != Length) Quit(""BestEnd""); } Length = -1; Start = -1; } } *ptrStart = BestStart; *ptrEnd = BestEnd; } static char ConsNextChar(const MSA &Aln, int EndCol) { const unsigned SeqCount = Aln.GetSeqCount(); const unsigned ColCount = Aln.GetColCount(); char Cons = '-'; for (unsigned SeqIndex = 0; SeqIndex < SeqCount; ++SeqIndex) { for (unsigned Col = EndCol + 1; Col < ColCount; ++Col) { char c = Aln.GetChar(SeqIndex, Col); if (c == '-') continue; else { if (Col == EndCol + 1) Cons = c; else if (Cons != c) return '-'; break; } } } return Cons; } void GetConsSeq(const MSA &Aln, double MinCons, int *ptrStartCol, int *ptrEndCol, Seq &ConsSeq) { int SeqCount = Aln.GetSeqCount(); if (SeqCount == 0) { ConsSeq.clear(); *ptrStartCol = -1; *ptrEndCol = -1; return; } int ColCount = Aln.GetColCount(); int StartCol = 0; int EndCol = ColCount - 1; FindStartEnd(Aln, MinCons, &StartCol, &EndCol); for (int Col = StartCol; Col <= EndCol; ++Col) { char c; GetCons(Aln, Col, &c); if (c != '-') ConsSeq.push_back(c); } // Eggregious hack to compensate for missing the end // of the concensus sequence sometimes. Check the // following letter to see if it is conserved. char Nextc = ConsNextChar(Aln, EndCol); if (Nextc != '-') ConsSeq.push_back(Nextc); *ptrStartCol = StartCol; *ptrEndCol = EndCol; } char GetConsSymbol(const MSA &Aln, unsigned Col) { int Counts[5]; GetCounts(Aln, (int) Col, Counts); const int SeqCount = (int) Aln.GetSeqCount(); int BigCount = 0; int BigLetter = 0; for (int i = 0; i < 5; ++i) { if (Counts[i] > BigCount) { BigCount = Counts[i]; BigLetter = i; } } if (BigLetter == 4) return ' '; if (BigCount == SeqCount) return '*'; if (((double) BigCount / (double) SeqCount) >= g_ColonThresh) return ':'; if (Counts[BigLetter] == SeqCount - 1 && SeqCount > 5) return ':'; return ' '; } void GetConsSymbols(const MSA &Aln, Seq &ConsSymbols) { const unsigned ColCount = Aln.GetColCount(); for (unsigned Col = 0; Col < ColCount; ++Col) { char c = GetConsSymbol(Aln, Col); ConsSymbols.push_back(c); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/forkmer.h",".h","859","37","#define FOR_EACH_KMER(S, Slen, i, c) \ { \ const int Kmask = pow4(k) - 1; \ unsigned char *ptrS = (unsigned char *) S; \ unsigned char *ptrSEnd = (unsigned char *) (S + Slen - 1); \ int c = 0; \ int h = 0; \ for (int j = 0; j < k - 1; ++j) \ { \ int x = CharToLetter[*ptrS++]; \ if (x >= 0) \ c = (c << 2) | x; \ else \ { \ c = 0; \ h = j + 1; \ } \ } \ int i = 0; \ for ( ; ptrS <= ptrSEnd; ++i) \ { \ int x = CharToLetter[*ptrS++]; \ if (x >= 0) \ c = ((c << 2) | x) & Kmask; \ else \ { \ c = 0; \ h = i + k; \ } \ if (i >= h) \ { #define END_FOR_EACH_KMER(S, Slen, i, c) \ } \ } \ } ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/estring.h",".h","527","14","#ifndef pathsum_h #define pathsum_h void PathToEstrings(const PWPath &Path, short **ptresA, short **ptresB); void EstringsToPath(const short esA[], const short esB[], PWPath &Path); void MulEstrings(const short es1[], const short es2[], short esp[]); void EstringOp(const short es[], const Seq &sIn, Seq &sOut); unsigned EstringOp(const short es[], const Seq &sIn, MSA &a); void LogEstring(const short es[]); unsigned LengthEstring(const short es[]); short *EstringNewCopy(const short es[]); #endif // pathsum_h ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/alpha.cpp",".cpp","2595","94","#include ""multaln.h"" const unsigned MAX_CHAR = 256; unsigned g_CharToLetter[MAX_CHAR]; unsigned g_CharToLetterEx[MAX_CHAR]; char g_LetterToChar[MAX_ALPHA]; char g_LetterExToChar[MAX_ALPHA_EX]; char g_UnalignChar[MAX_CHAR]; char g_AlignChar[MAX_CHAR]; bool g_IsWildcardChar[MAX_CHAR]; bool g_IsResidueChar[MAX_CHAR]; #define Res(c, Letter) \ { \ const unsigned char Upper = (unsigned char) toupper(c); \ const unsigned char Lower = (unsigned char) tolower(c); \ g_CharToLetter[Upper] = Letter; \ g_CharToLetter[Lower] = Letter; \ g_CharToLetterEx[Upper] = Letter; \ g_CharToLetterEx[Lower] = Letter; \ g_LetterToChar[Letter] = Upper; \ g_LetterExToChar[Letter] = Upper; \ g_IsResidueChar[Upper] = true; \ g_IsResidueChar[Lower] = true; \ g_AlignChar[Upper] = Upper; \ g_AlignChar[Lower] = Upper; \ g_UnalignChar[Upper] = Lower; \ g_UnalignChar[Lower] = Lower; \ } #define Wild(c, Letter) \ { \ const unsigned char Upper = (unsigned char) toupper(c); \ const unsigned char Lower = (unsigned char) tolower(c); \ g_CharToLetterEx[Upper] = Letter; \ g_CharToLetterEx[Lower] = Letter; \ g_LetterExToChar[Letter] = Upper; \ g_IsResidueChar[Upper] = true; \ g_IsResidueChar[Lower] = true; \ g_AlignChar[Upper] = Upper; \ g_AlignChar[Lower] = Upper; \ g_UnalignChar[Upper] = Lower; \ g_UnalignChar[Lower] = Lower; \ g_IsWildcardChar[Lower] = true; \ g_IsWildcardChar[Upper] = true; \ } static void SetGapChar(char c) { unsigned char u = (unsigned char) c; g_CharToLetterEx[u] = NX_GAP; g_LetterExToChar[NX_GAP] = (char) u; g_AlignChar[u] = u; g_UnalignChar[u] = u; } static void InitArrays() { memset(g_CharToLetter, 0xff, sizeof(g_CharToLetter)); memset(g_CharToLetterEx, 0xff, sizeof(g_CharToLetterEx)); memset(g_LetterToChar, '?', sizeof(g_LetterToChar)); memset(g_LetterExToChar, '?', sizeof(g_LetterExToChar)); memset(g_AlignChar, '?', sizeof(g_UnalignChar)); memset(g_UnalignChar, '?', sizeof(g_UnalignChar)); memset(g_IsWildcardChar, 0, sizeof(g_IsWildcardChar)); } static bool InitAlpha() { InitArrays(); SetGapChar('.'); SetGapChar('-'); Res('A', NX_A) Res('C', NX_C) Res('G', NX_G) Res('U', NX_T) Res('T', NX_T) Wild('N', NX_N) return true; } static bool Initialized = InitAlpha(); ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/params.h",".h","1185","53","#ifndef PARAMS_H #include ""types.h"" extern int g_DraftMinRepeatLength; extern int g_DraftMaxRepeatLength; extern int g_DraftMinSpacerLength; extern int g_DraftMaxSpacerLength; extern int g_DraftMinArraySize; // For determing linkage: extern double g_DraftMinHitRatio; extern double g_DraftMinSpacerRatio; extern int g_SpacerPadding; extern double g_DraftMinCons; extern double g_DraftMinColCons; extern int g_MinOneDiff; extern int g_MaxMSASeqs; extern int g_PileExpandMargin; extern int g_HitPadding; extern int g_FlankSize; extern int g_MinDiag; extern int g_MaxDPHitLen; extern double g_ClusterMaxDist; extern double g_ColonThresh; extern double g_MinPalindromeFractId; extern TERMGAPS g_TermGaps; extern bool g_ShowHits; extern bool g_LogHits; extern bool g_LogLinks; extern bool g_LogImages; extern bool g_LogAlns; extern bool g_FlushLog; extern bool g_NoInfo; extern int g_MinRepeatLength; extern int g_MaxRepeatLength; extern int g_MinSpacerLength; extern int g_MaxSpacerLength; extern int g_MinArraySize; extern double g_MinRepeatRatio; extern double g_MinSpacerRatio; extern double g_MinCons; #endif // PARAMS_H ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/mem.cpp",".cpp","830","42","#include ""pilercr.h"" #ifdef _MSC_VER #include #endif static int AllocatedBytes; static int PeakAllocatedBytes; // Allocate memory, fail on error, track total void *allocmem(int bytes) { assert(bytes < 0xfffffff0); // check for overlow char *p = (char *) malloc((size_t) (bytes + 4)); if (0 == p) Quit(""Out of memory (%d)"", bytes); int *pSize = (int *) p; *pSize = bytes; AllocatedBytes += bytes; if (AllocatedBytes > PeakAllocatedBytes) PeakAllocatedBytes = AllocatedBytes; return p + 4; } void freemem(void *p) { if (0 == p) return; int *pSize = (int *) ((char *) p - 4); int bytes = *pSize; assert(bytes <= AllocatedBytes); AllocatedBytes -= bytes; free(((char *) p) - 4); } void chkmem() { #ifdef _MSC_VER assert(_CrtCheckMemory()); #endif } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/main.cpp",".cpp","1032","56","#include ""pilercr.h"" #if WIN32 #include #endif bool g_Quiet = false; int main(int argc, char *argv[]) { #if WIN32 // Multi-tasking does not work well in CPU-bound // console apps running under Win32. // Reducing the process priority allows GUI apps // to run responsively in parallel. SetPriorityClass(GetCurrentProcess(), BELOW_NORMAL_PRIORITY_CLASS); #endif ProcessArgVect(argc - 1, argv + 1); SetLog(); for (int i = 0; i < argc; ++i) Log(""%s "", argv[i]); Log(""\n""); g_Quiet = FlagOpt(""quiet""); if (!g_Quiet) Credits(); if (FlagOpt(""help"")) { Usage(); exit(0); } if (FlagOpt(""options"")) { Options(); exit(0); } else if (FlagOpt(""version"")) { fprintf(stderr, PILERCR_LONG_VERSION ""\n""); exit(0); } else if (ValueOpt(""in"")) PILERCR(); else if (ValueOpt(""cmp"")) Cmp(); else Quit(""Bad command line""); Progress(""Elapsed time %d secs, peak mem use %.0f Mb"", GetElapsedSecs(), GetPeakMemUseBytes()/1e6); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/alignarrays.cpp",".cpp","1389","58","#include ""pilercr.h"" static bool CmpAA(const ArrayAln *AA1, const ArrayAln *AA2) { return AA1->Pos < AA2->Pos; } void AlignArrays(const std::vector &ADVec, std::vector &AAVec) { AAVec.clear(); // Create array alignments const size_t ArrayDataCount = ADVec.size(); for (size_t Index = 0; Index < ArrayDataCount; ++Index) { ArrayData &AD = *(ADVec[Index]); ArrayAln &AA = *new ArrayAln; AlignArray(AD, AA); if (AA.Repeats.size() > 0 && AcceptedAA(AA)) AAVec.push_back(&AA); } // Sort by position std::sort(AAVec.begin(), AAVec.end(), CmpAA); // Check for arrays where we missed some repeats, these got split // and can be merged. size_t ArrayIndex = 0; for (;;) { size_t ArrayCount = AAVec.size(); if (ArrayIndex + 1 >= ArrayCount) break; bool Merged = MergeAAs(*AAVec[ArrayIndex], *AAVec[ArrayIndex+1]); if (Merged) { // Delete entry from array and continue. // This allows merger of three or more arrays. assert(ArrayCount > 1); for (size_t i = ArrayIndex + 1; i < ArrayCount - 1; ++i) AAVec[i] = AAVec[i+1]; AAVec.resize(ArrayCount - 1); } ++ArrayIndex; } // Assign ids size_t ArrayCount = AAVec.size(); int Id = 1; for (size_t Index = 0; Index < ArrayCount; ++Index) { ArrayAln &AA = *(AAVec[Index]); AA.Id = Id++; } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/filterb2.cpp",".cpp","12929","536","#include ""pilercr.h"" #include ""forkmer.h"" // FilterB: Banded search of SeqQ // (There is no SeqT). #define TRACE 0 // static char *SeqT; static char *SeqQ; static int Qlen; static int MinMatch; static int MaxError; static int TubeOffset; static int TubeWidth; static int MinKmersPerHit; static TubeState *Tubes; static int MaxActiveTubes; static int MaxKmerDist; //============================================================== // Start rolling index stuff //============================================================== static INDEX_ENTRY *Entries; static INDEX_ENTRY **Heads; static INDEX_ENTRY **Tails; static INDEX_ENTRY *FreeEntries; static int KmerIndexCount; static int KmersInWindow; static int FreeListSize() { int Size = 0; for (INDEX_ENTRY *I = FreeEntries; I; I = I->Next) ++Size; return Size; } static void AddToFreeList(INDEX_ENTRY *IE) { #if DEBUG IE->Kmer = -2; IE->Pos = -2; #endif IE->Prev = 0; IE->Next = FreeEntries; if (0 != FreeEntries) FreeEntries->Prev = IE; FreeEntries = IE; #if TRACE Log(""AddToFreeList(%x), size when done=%d\n"", IE, FreeListSize()); #endif } static void AllocateIndex(int g_Diameter) { assert(KmersInWindow > 0); KmerIndexCount = pow4(k); int EntryCount = KmersInWindow + k; Entries = all(INDEX_ENTRY, EntryCount); zero(Entries, INDEX_ENTRY, EntryCount); Heads = all(INDEX_ENTRY *, KmerIndexCount); Tails = all(INDEX_ENTRY *, KmerIndexCount); zero(Heads, INDEX_ENTRY *, KmerIndexCount); zero(Tails, INDEX_ENTRY *, KmerIndexCount); for (int i = 0; i < EntryCount; ++i) AddToFreeList(&(Entries[i])); #if TRACE Log(""KmersInWindow = g_Diameter=%d - k=%d + 1 = %d\n"", g_Diameter, k, KmersInWindow); Log(""After AllocateIndex free list size = %d\n"", FreeListSize()); #endif } static void AddToIndex(int Kmer, int Pos) { #if TRACE Log(""AddToIndex(Kmer=%x=%s, Pos=%d)\n"", Kmer, CodeToString(Kmer, k), Pos); #endif if (-1 == Kmer) return; #if TRACE Log(""Free index has %d entries\n"", FreeListSize()); #endif assert(Kmer >= 0 && Kmer < KmerIndexCount); assert(FreeEntries != 0); INDEX_ENTRY *Entry = FreeEntries; FreeEntries = FreeEntries->Next; if (FreeEntries != 0) FreeEntries->Prev = 0; INDEX_ENTRY *Tail = Tails[Kmer]; // Insert after tail of list Entry->Kmer = Kmer; Entry->Pos = Pos; Entry->Next = 0; Entry->Prev = Tail; if (0 == Tail) Heads[Kmer] = Entry; else Tail->Next = Entry; Tails[Kmer] = Entry; } static inline int GetKmer(const char *Seq, int Pos) { assert(Pos + k <= SeqLengthQ); return StringToCode(Seq + Pos, k); } #define DeclareListPtr(p) INDEX_ENTRY *p static inline INDEX_ENTRY *GetListPtr(int Kmer) { assert(Kmer >= 0 && Kmer < KmerIndexCount); return Heads[Kmer]; } static inline bool NotEndOfList(INDEX_ENTRY *p) { return p != 0; } static inline INDEX_ENTRY *GetListNext(INDEX_ENTRY *p) { return p->Next; } static inline int GetListPos(INDEX_ENTRY *p) { return p->Pos; } static void ValidateIndex(const char *Seq, int WindowStart, int WindowEnd) { ProgressStart(""Validating index""); int FreeCount = 0; for (INDEX_ENTRY *p = FreeEntries; p != 0; p = p->Next) { if (++FreeCount > KmersInWindow) Quit(""Validate index failed free count""); if (p->Kmer != -2 || p->Pos != -2) Quit(""Validate index failed free != -2""); const INDEX_ENTRY *pNext = p->Next; if (0 != pNext && pNext->Prev != p) Quit(""Validate index failed free pNext->Prev != p""); const INDEX_ENTRY *pPrev = p->Prev; if (0 != pPrev && pPrev->Next != p) Quit(""Validate index failed free pPrev->Next != p""); } for (int Pos = WindowStart; Pos < WindowEnd; ++Pos) { const int Kmer = GetKmer(Seq, Pos); if (-1 == Kmer) continue; for (DeclareListPtr(p) = GetListPtr(Kmer); NotEndOfList(p); p = GetListNext(p)) { const int HitPos = GetListPos(p); if (HitPos == Pos) goto Found; } Quit(""Validate index failed, pos=%d not found for kmer %x=%s"", Pos, Kmer, CodeToString(Kmer, k)); Found:; } int IndexedCount = 0; for (int Kmer = 0; Kmer < KmerIndexCount; ++Kmer) { INDEX_ENTRY *Head = Heads[Kmer]; INDEX_ENTRY *Tail = Tails[Kmer]; if (Head != 0 && Head->Prev != 0) Quit(""Head->Prev != 0""); if (Tail != 0 && Tail->Next != 0) Quit(""Tail->Next != 0""); if ((Head == 0) != (Tail == 0)) Quit(""Head / tail""); int PrevHitPos = -1; int ListIndex = 0; for (DeclareListPtr(p) = GetListPtr(Kmer); NotEndOfList(p); p = GetListNext(p)) { ++IndexedCount; if (IndexedCount > KmersInWindow) Quit(""Valiate index failed, count""); const INDEX_ENTRY *pNext = p->Next; if (Kmer != p->Kmer) Quit(""Validate index failed, kmer""); if (0 != pNext && pNext->Prev != p) Quit(""Validate index failed pNext->Prev != p""); const INDEX_ENTRY *pPrev = p->Prev; if (0 != pPrev && pPrev->Next != p) Quit(""Validate index failed pPrev->Next != p""); const int HitPos = GetListPos(p); if (HitPos < WindowStart || HitPos > WindowEnd) Quit(""ValidateIndex failed, hit not in window kmer=%d %s"", Kmer, CodeToString(Kmer, k)); int IsTail = (p->Next == 0); if (HitPos < PrevHitPos) Quit(""Validate index failed, sort order Kmer=%d HitPos=%d PrevHitPos=%d ListIndex=%d IsTail=%d"", Kmer, HitPos, PrevHitPos, ListIndex, IsTail); PrevHitPos = HitPos; ++ListIndex; } } if (IndexedCount > KmersInWindow) Quit(""Validate index failed, count [2]""); ProgressDone(); } static void LogLocations(int Kmer) { Log(""LogLocations(%d %s)"", Kmer, CodeToString(Kmer, k)); for (DeclareListPtr(p) = GetListPtr(Kmer); NotEndOfList(p); p = GetListNext(p)) Log("" [%d]=%d"", p->Pos, StringToCode(SeqQ + p->Pos, k)); } // Pos not required; used for sanity check static void DeleteFirstInstanceFromIndex(int Kmer, int Pos) { #if TRACE Log(""DeleteFirstInstanceFromIndex(Kmer=%x=%s, Pos=%d)\n"", Kmer, CodeToString(Kmer, k), Pos); #endif if (-1 == Kmer) return; assert(Kmer >= 0 && Kmer < KmerIndexCount); INDEX_ENTRY *IE = Heads[Kmer]; if (IE == 0) Quit(""DFI Kmer=%d %s Pos=%d"", Kmer, CodeToString(Kmer, k), Pos); // assert(IE != 0); assert(0 == IE->Prev); assert(Pos == IE->Pos); // Delete from index INDEX_ENTRY *NewHead = IE->Next; if (NewHead == 0) { Heads[Kmer] = 0; Tails[Kmer] = 0; } else { assert(NewHead->Prev == IE); NewHead->Prev = 0; } Heads[Kmer] = NewHead; AddToFreeList(IE); } //============================================================== // End rolling index stuff //============================================================== #define CalcDiagIndex(t, q) (Qlen - (t) + (q)) #define CalcTubeIndex(DiagIndex) ((DiagIndex)/TubeOffset) static void AddHit(int TubeIndex, int qLo, int qHi) { #if TRACE Log(""AddHit(Tube=%d, qLo=%d, qHi=%d)\n"", Qlen - TubeIndex*TubeOffset, qLo, qHi + k); #endif SaveFilterHit(qLo, qHi + k, Qlen - TubeIndex*TubeOffset); } // Called when end of a tube is reached // A point in the tube -- the point with maximal q -- is (Qlen-1,q-1). static void TubeEnd(int q) { if (q <= 0) return; int DiagIndex = CalcDiagIndex(Qlen - 1, q - 1); int TubeIndex = CalcTubeIndex(DiagIndex); TubeState *Tube = Tubes + TubeIndex%MaxActiveTubes; #if TRACE Log(""TubeEnd(%d) DiagIndex=%d TubeIndex=%d Count=%d\n"", q, DiagIndex, TubeIndex, Tube->Count); #endif if (Tube->Count >= MinKmersPerHit) AddHit(TubeIndex, Tube->qLo, Tube->qHi); Tube->Count = 0; } // Called when q=Qlen - 1 to flush any hits in each tube. static void TubeFlush(int TubeIndex) { TubeState *Tube = Tubes + TubeIndex%MaxActiveTubes; #if TRACE Log(""TubeFlush(TubeIndex=%d) Count=%d\n"", TubeIndex, Tube->Count); #endif if (Tube->Count < MinKmersPerHit) return; AddHit(TubeIndex, Tube->qLo, Tube->qHi); Tube->Count = 0; } static void HitTube(int TubeIndex, int q) { TubeState *Tube = Tubes + TubeIndex%MaxActiveTubes; #if TRACE Log(""HitTube(TubeIndex=%d, q=%d) Count=%d\n"", TubeIndex, q, Tube->Count); #endif if (0 == Tube->Count) { Tube->Count = 1; Tube->qLo = q; Tube->qHi = q; return; } if (q - Tube->qHi > MaxKmerDist) { if (Tube->Count >= MinKmersPerHit) AddHit(TubeIndex, Tube->qLo, Tube->qHi); Tube->Count = 1; Tube->qLo = q; Tube->qHi = q; return; } ++(Tube->Count); Tube->qHi = q; } // Found a common k-mer static inline void CommonKmer(int t, int q) { assert(t >= 0 && t < Qlen - k + 1); assert(q >= 0 && q < Qlen - k + 1); if (q <= t) return; #if TRACE Log(""CommonKmer(%d,%d) SeqQ=%.*s SeqQ=%.*s\n"", q, t, k, SeqQ+q, k, SeqQ+t); #endif int DiagIndex = CalcDiagIndex(t, q); int TubeIndex = CalcTubeIndex(DiagIndex); #if TRACE Log(""HitTube(TubeIndex=%d, t=%d, q=%d)\n"", TubeIndex, t, q); #endif HitTube(TubeIndex, q); // Hit in overlapping tube preceding this one? if (DiagIndex%TubeOffset < MaxError) { if (0 == TubeIndex) TubeIndex = MaxActiveTubes - 1; else --TubeIndex; assert(TubeIndex >= 0); #if TRACE Log(""HitTube(TubeIndex=%d, t=%d, q=%d) [overlap]\n"", TubeIndex, t, q); #endif HitTube(TubeIndex, q); } } void FilterB(char *B_, int Qlen_, const FilterParams &FP) { SeqQ = B_; Qlen = Qlen_; MinMatch = FP.SeedLength; MaxError = FP.SeedDiffs; TubeOffset = FP.TubeOffset; const int Kmask = pow4(k) - 1; // Ukonnen's Lemma MinKmersPerHit = MinMatch + 1 - k*(MaxError + 1); // Maximum distance between SeqQ positions of two k-mers in a match // (More stringent bounds may be possible, but not a big problem // if two adjacent matches get merged). MaxKmerDist = MinMatch - k; TubeWidth = TubeOffset + MaxError; if (TubeOffset < MaxError) { Log(""TubeOffset < MaxError\n""); exit(1); } if (MinKmersPerHit <= 0) { Log(""MinKmersPerHit <= 0\n""); exit(1); } MaxActiveTubes = (Qlen + TubeWidth - 1)/TubeOffset + 1; Tubes = all(TubeState, MaxActiveTubes); zero(Tubes, TubeState, MaxActiveTubes); // Ticker tracks cycling of circular list of active tubes. int Ticker = TubeWidth; // Allocate memory for index ProgressStart(""Allocating index""); KmersInWindow = GetKmersInWindow(); AllocateIndex(g_Diameter); ProgressDone(); /*** Scan query sequence. Start is coordinate of first base in first k-mer in sliding window End is coordinate of first base in last k-mer in sliding window g_Diameter=10 ----------------- | | v v Start End = Start + g_Diameter - k v____ v____ |A|C|T|G|G|A|T|C|C|G|A|T|T|A|C|A|C|C|T|T|A|G|T|C|A| SeqQ --> ^---^ ^___^ . k=3 ^___^ . ^___^ . KmersInWindow = ^___^ . g_Diameter - k + 1 ^___^ . = 8 ^___^ . ^___^ . ^___^ ***/ ProgressStart(""Filtering""); // Position of last kmer in sequence const int LastKmerPos = Qlen - k; for (int EndPos = 0; EndPos <= LastKmerPos; ++EndPos) { int StartPos = EndPos - g_Diameter + k - 1; #if TRACE if (StartPos >= 0) Log(""START %4d %.*s\n"", StartPos, k, SeqQ+StartPos); else Log(""START < 0\n""); if (EndPos <= LastKmerPos) Log(""END %4d %.*s\n"", EndPos, k, SeqQ+EndPos); else Log(""END > End\n""); #endif if (StartPos%200000 == 0) ProgressStep(StartPos, LastKmerPos); if (StartPos >= 0) { int StartKmer = GetKmer(SeqQ, StartPos); if (StartKmer != -1) { DeleteFirstInstanceFromIndex(StartKmer, StartPos); for (DeclareListPtr(p) = GetListPtr(StartKmer); NotEndOfList(p); p = GetListNext(p)) { int HitPos = GetListPos(p); CommonKmer(StartPos, HitPos); } } } if (0 == --Ticker) { TubeEnd(EndPos); Ticker = TubeOffset; } if (EndPos <= LastKmerPos) { int EndKmer = GetKmer(SeqQ, EndPos); AddToIndex(EndKmer, EndPos); } } ProgressDone(); TubeEnd(Qlen - 1); int DiagFrom = CalcDiagIndex(Qlen - 1, Qlen - 1) - TubeWidth; int DiagTo = CalcDiagIndex(0, Qlen - 1) + TubeWidth; int TubeFrom = CalcTubeIndex(DiagFrom); if (TubeFrom < 0) TubeFrom = 0; int TubeTo = CalcTubeIndex(DiagTo); //for (int TubeIndex = TubeFrom; TubeIndex <= TubeTo; ++TubeIndex) // TubeFlush(TubeIndex); for (int TubeIndex = 0; TubeIndex < MaxActiveTubes; ++TubeIndex) TubeFlush(TubeIndex); freemem(Tubes); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/utils.cpp",".cpp","7350","360","#include ""pilercr.h"" #include #include unsigned char CompChar[256]; int CharToLetter[256]; static void InitCharToLetter() { for (int i = 0; i < 256; ++i) CharToLetter[i] = 4; CharToLetter['A'] = 0; CharToLetter['a'] = 0; CharToLetter['C'] = 1; CharToLetter['c'] = 1; CharToLetter['G'] = 2; CharToLetter['g'] = 2; CharToLetter['T'] = 3; CharToLetter['t'] = 3; } static void InitCompChar() { for (unsigned i = 0; i < 256; ++i) CompChar[i] = (unsigned char) i; CompChar['a'] = 't'; CompChar['c'] = 'g'; CompChar['g'] = 'c'; CompChar['t'] = 'a'; CompChar['n'] = 'n'; CompChar['A'] = 'T'; CompChar['C'] = 'G'; CompChar['G'] = 'C'; CompChar['T'] = 'A'; } static bool InitUtils() { InitCompChar(); InitCharToLetter(); return true; } static bool UtilsInitialized = InitUtils(); char *strsave(const char *s) { if (0 == s) return 0; char *ptrCopy = strdup(s); if (0 == ptrCopy) Quit(""Out of memory""); return ptrCopy; } static char *StdioStrMode(FILEIO_MODE Mode) { switch (Mode) { case FILEIO_MODE_ReadOnly: return FILIO_STRMODE_ReadOnly; case FILEIO_MODE_WriteOnly: return FILIO_STRMODE_WriteOnly; case FILEIO_MODE_ReadWrite: return FILIO_STRMODE_ReadWrite; } Quit(""StdioStrMode: Invalid mode""); return ""r""; } FILE *OpenStdioFile(const char *FileName, FILEIO_MODE Mode) { char *strMode = StdioStrMode(Mode); FILE *f = fopen(FileName, strMode); if (0 == f) Quit(""Cannot open %s, %s [%d]"", FileName, strerror(errno), errno); return f; } FILE *CreateStdioFile(const char *FileName) { FILE *f = fopen(FileName, ""wb+""); if (0 == f) Quit(""Cannot open %s, %s [%d]"", FileName, strerror(errno), errno); return f; } int GetFileSize(FILE *f) { long CurrPos = ftell(f); if (CurrPos < 0) Quit(""FileSize: ftell<0 (CurrPos), errno=%d"", errno); int Ok = fseek(f, 0, SEEK_END); if (Ok != 0) Quit(""FileSize fseek(END) != 0 errno=%d"", errno); long Size = ftell(f); if (Size < 0) Quit(""FileSize: ftell<0 (size), errno=%d"", errno); Ok = fseek(f, CurrPos, SEEK_SET); if (Ok != 0) Quit(""FileSize fseek(restore curr pos) != 0 errno=%d"", errno); long NewPos = ftell(f); if (CurrPos < 0) Quit(""FileSize: ftell=%ld != CurrPos=%ld"", CurrPos, NewPos); return (int) Size; } // 4^n int pow4(int n) { assert(n >= 0 && n < 16); return (1 << (2*n)); } // 4^d, but much less likely to under or overflow double pow4d(int n) { return pow(4.0, n); } double log4(double x) { static double LOG4 = log(4.0); return log(x)/LOG4; } // Ukonnen's Lemma int MinWordsPerFilterHit(int HitLength, int WordLength, int MaxErrors) { return HitLength + 1 - WordLength*(MaxErrors + 1); } int StringToCode(const char s[], int len) { int code = 0; for (int i = 0; i < len; ++i) { char c = s[i]; switch (c) { case 'a': case 'A': code <<= 2; code |= 0x00; break; case 'c': case 'C': code <<= 2; code |= 0x01; break; case 'g': case 'G': code <<= 2; code |= 0x02; break; case 't': case 'T': code <<= 2; code |= 0x03; break; default: return -1; } } return code; } char *CodeToString(int code, int len) { static char Str[100]; static char Symbol[] = { 'A', 'C', 'G', 'T' }; int i; assert(len < sizeof(Str)); Str[len] = 0; for (i = len-1; i >= 0; --i) { Str[i] = Symbol[code & 0x3]; code >>= 2; } return Str; } void *ckalloc(int size, const char *where) { void *p; p = malloc(size); if (p == NULL) Quit(""Out of memory (ckalloc)""); return (p); } void *ckrealloc(void *p, int size, const char *where) { p = realloc(p,size); if (p == NULL) Quit(""Out of memory (ckrealloc)""); return (p); } int RevCompKmer(int Kmer) { // Log(""Kmer=%s"", CodeToString(Kmer, k)); int RCKmer = 0; for (int i = 0; i < k; ++i) { int x = Kmer & 3; int cx = 3 - x; int shift = 2*(k - i - 1); RCKmer |= (cx << shift); Kmer >>= 2; } // Log("" Comp=%s\n"", CodeToString(RCKmer, k)); return RCKmer; } int GetHitLength(const DPHit &Hit) { assert(Hit.aHi >= Hit.aLo); // Plus only assert(Hit.bHi >= Hit.bLo); return (Hit.aHi - Hit.aLo + 1 + Hit.bHi - Hit.bLo + 1)/2; } int GetSpacerLength(const DPHit &Hit) { assert(Hit.aHi >= Hit.aLo); // Plus only assert(Hit.bHi >= Hit.bLo); return Hit.bLo - Hit.aHi; } int GetOverlap(unsigned lo1, unsigned hi1, unsigned lo2, unsigned hi2) { int maxlo = std::max(lo1, lo2); int minhi = std::min(hi1, hi2); if (maxlo > minhi) return 0; return minhi - maxlo + 1; } double GetRatio(int x, int y) { if (x == 0 && y == 0) return 0; if (x < y) return (double) x / (double) y; else return (double) y / (double) x; } int GetPileLength(const PileData &Pile) { return Pile.Hi - Pile.Lo + 1; } int GetSpacerLength(const PileData &Pile1, const PileData &Pile2) { assert(Pile2.Lo >= Pile1.Hi); return Pile2.Lo - Pile1.Hi; } void DeletePile(int PileIndex) { assert(PileIndex >= 0 && PileIndex < g_PileCount); g_Piles[PileIndex].Deleted = true; } const ImageData &GetImage(int ImageIndex) { assert(ImageIndex >= 0 && ImageIndex < g_ImageCount); return g_Images[ImageIndex]; } const DPHit &GetHit(int HitIndex) { assert(HitIndex >= 0 && HitIndex < g_HitCount); return g_Hits[HitIndex]; } const PileData &GetPile(int PileIndex) { assert(PileIndex >= 0 && PileIndex < g_PileCount); return g_Piles[PileIndex]; } PileData &GetModifiablePile(int PileIndex) { assert(PileIndex >= 0 && PileIndex < g_PileCount); return g_Piles[PileIndex]; } DPHit &GetModifiableHit(int HitIndex) { assert(HitIndex >= 0 && HitIndex < g_HitCount); return g_Hits[HitIndex]; } int GetHitLength(int ImageIndex) { const ImageData &Image = GetImage(ImageIndex); const DPHit &Hit = GetHit(Image.HitIndex); return GetHitLength(Hit); } int GetSpacerLengthFromImage(int ImageIndex) { const ImageData &Image = GetImage(ImageIndex); const DPHit &Hit = GetHit(Image.HitIndex); return GetSpacerLength(Hit); } int GetOverlap(const ImageData &Image1, const ImageData &Image2) { return GetOverlap(Image1.Lo, Image1.Hi, Image2.Lo, Image2.Hi); } void LogHit(const DPHit &Hit) { Log(""pos1=%d pos2=%d hitlen=%d space=%d"", Hit.aLo, Hit.bLo, GetHitLength(Hit), GetSpacerLength(Hit)); } void LogHit(int HitIndex) { const DPHit &Hit = GetHit(HitIndex); Log(""Hit%d "", HitIndex); LogHit(Hit); if (IsDeletedHit(HitIndex)) Log("" DEL""); } bool IsDeletedHit(int HitIndex) { assert(HitIndex >= 0 && HitIndex < g_HitCount); const DPHit &Hit = g_Hits[HitIndex]; if (Hit.Deleted) return true; if (g_PileCount > 0) { int PileIndex = g_HitIndexToPileIndexA[HitIndex]; const PileData &Pile = GetPile(PileIndex); if (Pile.Deleted) return true; } return false; } void DeleteHit(int HitIndex) { assert(HitIndex >= 0 && HitIndex < g_HitCount); DPHit &Hit = g_Hits[HitIndex]; Hit.Deleted = true; int PileIndex = g_HitIndexToPileIndexA[HitIndex]; PileData &Pile = GetModifiablePile(PileIndex); Pile.Deleted = true; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/comp.cpp",".cpp","999","46","#include ""pilercr.h"" void Complement(char *seq, int len) { static char WCinvert[256]; static int Firstime = 1; if (Firstime) /* Setup complementation array */ { int i; Firstime = 0; for(i = 0; i < 256;i++){ WCinvert[i] = '?'; } WCinvert['a'] = 't'; WCinvert['c'] = 'g'; WCinvert['g'] = 'c'; WCinvert['t'] = 'a'; WCinvert['n'] = 'n'; WCinvert['A'] = 'T'; WCinvert['C'] = 'G'; WCinvert['G'] = 'C'; WCinvert['T'] = 'A'; WCinvert['N'] = 'N'; WCinvert['-'] = '-'; // added this to enable alignment of gapped consensi } /* Complement and reverse sequence */ { register unsigned char *s, *t; int c; s = (unsigned char *) seq; t = (unsigned char *) (seq + (len-1)); while (s < t) { c = *s; *s++ = WCinvert[(int) *t]; *t-- = WCinvert[c]; } if (s == t) *s = WCinvert[(int) *s]; } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/clustcons.cpp",".cpp","2597","144","#include ""pilercr.h"" #define TRACE 0 // Best entry is one with largest number // of distances smaller than the threshold static int FindBest(const std::vector &ADVec, const DistFunc &DF, BoolVec &Done, IntVec &Cluster) { Cluster.clear(); const int Count = DF.GetCount(); IntVec NrUnderThresh; for (int i = 0; i < Count; ++i) NrUnderThresh.push_back(0); for (int i = 0; i < Count; ++i) { if (Done[i]) continue; for (int j = 0; j < Count; ++j) { if (i == j || Done[j]) continue; #if TRACE Log(""Dist(""); ADVec[i]->ConsSeq.LogMeSeqOnly(); Log("",""); ADVec[j]->ConsSeq.LogMeSeqOnly(); Log("") = %.1f"", DF.GetDist(i, j)); #endif if (DF.GetDist(i, j) <= g_ClusterMaxDist) { #if TRACE Log("" Under\n""); #endif ++(NrUnderThresh[i]); } else { #if TRACE Log("" Over\n""); #endif ; } } } #if TRACE { Log(""FindBest:\n""); for (int i = 0; i < Count; ++i) Log("" i=%d Done=%c NrUnder=%d\n"", i, Done[i] ? 'T' : 'F', NrUnderThresh[i]); } #endif int Best = -1; unsigned BestCount = 0; for (int i = 0; i < Count; ++i) { if (NrUnderThresh[i] > BestCount) { Best = i; BestCount = NrUnderThresh[i]; } } if (Best >= 0) { for (int i = 0; i < Count; ++i) { if (Done[i]) continue; if (DF.GetDist(Best, i) <= g_ClusterMaxDist) { Done[i] = true; Cluster.push_back(i); } } } return Best; } void ClusterCons(const std::vector &ADVec, IntVecVec &Clusters) { SeqVect Seqs; const size_t ArrayCount = ADVec.size(); for (size_t i = 0; i < ArrayCount; ++i) { const ArrayData &AD = *(ADVec[i]); Seq *s = new Seq; s->Copy(AD.ConsSeq); Seqs.push_back(s); } DistFunc DF; KmerDist(Seqs, DF); #if TRACE DF.LogMe(); #endif BoolVec Done; for (size_t i = 0; i < ArrayCount; ++i) Done.push_back(false); for (;;) { IntVec Cluster; int Best = FindBest(ADVec, DF, Done, Cluster); if (Best == -1) break; Clusters.push_back(Cluster); } for (size_t i = 0; i < ArrayCount; ++i) { if (!Done[i]) { IntVec Cluster; Cluster.push_back(i); Clusters.push_back(Cluster); } } #if TRACE { Log(""%d clusters\n"", (int) Clusters.size()); for (size_t i = 0; i < (int) Clusters.size(); ++i) { const IntVec &Cluster = Clusters[i]; Log("" ""); size_t N = Cluster.size(); for (size_t j = 0; j < N; ++j) Log("" %d"", Cluster[j]); Log(""\n""); } } #endif } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/quit.cpp",".cpp","1015","57","#include ""pilercr.h"" #include #ifdef WIN32 #define _WIN32_WINNT 0x0400 #include void Break() { DebugBreak(); } #endif // Exit immediately with error message, printf-style. void Quit(const char szFormat[], ...) { va_list ArgList; char szStr[4096]; va_start(ArgList, szFormat); vsprintf(szStr, szFormat, ArgList); fprintf(stderr, ""\n*** FATAL ERROR *** %s\n"", szStr); Log(""\n*** FATAL ERROR *** ""); Log(""%s\n"", szStr); #if DEBUG #ifdef WIN32 if (IsDebuggerPresent()) { int iBtn = MessageBox(NULL, szStr, ""piler"", MB_ICONERROR | MB_OKCANCEL); if (IDCANCEL == iBtn) Break(); } #endif #endif if (FlagOpt(""segv"")) raise(SIGSEGV); else abort(); } void Warning(const char szFormat[], ...) { va_list ArgList; char szStr[4096]; va_start(ArgList, szFormat); vsprintf(szStr, szFormat, ArgList); fprintf(stderr, ""\n*** Warning *** %s\n"", szStr); Log(""\n*** Warning *** ""); Log(""%s\n"", szStr); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/mkrootmsa.cpp",".cpp","5390","226","#include ""multaln.h"" #define TRACE 0 #define VALIDATE 0 static bool g_bStable = true; static void PathSeq(const Seq &s, const PWPath &Path, bool bRight, Seq &sOut) { short *esA; short *esB; PathToEstrings(Path, &esA, &esB); const unsigned uSeqLength = s.Length(); const unsigned uEdgeCount = Path.GetEdgeCount(); sOut.Clear(); sOut.SetName(s.GetName()); unsigned uPos = 0; for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &Edge = Path.GetEdge(uEdgeIndex); char cType = Edge.cType; if (bRight) { if (cType == 'I') cType = 'D'; else if (cType == 'D') cType = 'I'; } switch (cType) { case 'M': sOut.AppendChar(s[uPos++]); break; case 'D': sOut.AppendChar('-'); break; case 'I': sOut.AppendChar(s[uPos++]); break; default: Quit(""PathSeq, invalid edge type %c"", cType); } } } #if VALIDATE static void MakeRootSeq(const Seq &s, const Tree &GuideTree, unsigned uLeafNodeIndex, const ProgNode Nodes[], Seq &sRoot) { sRoot.Copy(s); unsigned uNodeIndex = uLeafNodeIndex; for (;;) { unsigned uParent = GuideTree.GetParent(uNodeIndex); if (NULL_NEIGHBOR == uParent) break; bool bRight = (GuideTree.GetLeft(uParent) == uNodeIndex); uNodeIndex = uParent; const PWPath &Path = Nodes[uNodeIndex].m_Path; Seq sTmp; PathSeq(sRoot, Path, bRight, sTmp); sRoot.Copy(sTmp); } } #endif // VALIDATE static short *MakeRootSeqE(const Seq &s, const Tree &GuideTree, unsigned uLeafNodeIndex, const ProgNode Nodes[], Seq &sRoot, short *Estring1, short *Estring2) { short *EstringCurr = Estring1; short *EstringNext = Estring2; const unsigned uSeqLength = s.Length(); EstringCurr[0] = uSeqLength; EstringCurr[1] = 0; unsigned uNodeIndex = uLeafNodeIndex; for (;;) { unsigned uParent = GuideTree.GetParent(uNodeIndex); if (NULL_NEIGHBOR == uParent) break; bool bRight = (GuideTree.GetLeft(uParent) == uNodeIndex); uNodeIndex = uParent; const PWPath &Path = Nodes[uNodeIndex].m_Path; const short *EstringNode = bRight ? Nodes[uNodeIndex].m_EstringL : Nodes[uNodeIndex].m_EstringR; MulEstrings(EstringCurr, EstringNode, EstringNext); #if TRACE Log(""\n""); Log(""Curr=""); LogEstring(EstringCurr); Log(""\n""); Log(""Node=""); LogEstring(EstringNode); Log(""\n""); Log(""Prod=""); LogEstring(EstringNext); Log(""\n""); #endif short *EstringTmp = EstringNext; EstringNext = EstringCurr; EstringCurr = EstringTmp; } EstringOp(EstringCurr, s, sRoot); #if TRACE Log(""Root estring=""); LogEstring(EstringCurr); Log(""\n""); Log(""Root seq=""); sRoot.LogMe(); #endif return EstringCurr; } static unsigned GetFirstNodeIndex(const Tree &tree) { if (g_bStable) return 0; return tree.FirstDepthFirstNode(); } static unsigned GetNextNodeIndex(const Tree &tree, unsigned uPrevNodeIndex) { if (g_bStable) { const unsigned uNodeCount = tree.GetNodeCount(); unsigned uNodeIndex = uPrevNodeIndex; for (;;) { ++uNodeIndex; if (uNodeIndex >= uNodeCount) return NULL_NEIGHBOR; if (tree.IsLeaf(uNodeIndex)) return uNodeIndex; } } unsigned uNodeIndex = uPrevNodeIndex; for (;;) { uNodeIndex = tree.NextDepthFirstNode(uNodeIndex); if (NULL_NEIGHBOR == uNodeIndex || tree.IsLeaf(uNodeIndex)) return uNodeIndex; } } void MakeRootMSA(const SeqVect &v, const Tree &GuideTree, ProgNode Nodes[], MSA &Aln) { assert(v.GetSeqCount() > 1); #if TRACE Log(""MakeRootMSA Tree=""); GuideTree.LogMe(); #endif const unsigned uSeqCount = v.GetSeqCount(); unsigned uColCount = uInsane; unsigned uSeqIndex = 0; const unsigned uTreeNodeCount = GuideTree.GetNodeCount(); const unsigned uRootNodeIndex = GuideTree.GetRootNodeIndex(); const PWPath &RootPath = Nodes[uRootNodeIndex].m_Path; const unsigned uRootColCount = RootPath.GetEdgeCount(); const unsigned uEstringSize = uRootColCount + 1; short *Estring1 = new short[uEstringSize]; short *Estring2 = new short[uEstringSize]; unsigned uTreeNodeIndex = GetFirstNodeIndex(GuideTree); do { unsigned uId = GuideTree.GetLeafId(uTreeNodeIndex); const Seq &s = *(v[uId]); Seq sRootE; short *es = MakeRootSeqE(s, GuideTree, uTreeNodeIndex, Nodes, sRootE, Estring1, Estring2); Nodes[uTreeNodeIndex].m_EstringL = EstringNewCopy(es); #if VALIDATE Seq sRoot; MakeRootSeq(s, GuideTree, uTreeNodeIndex, Nodes, sRoot); if (!sRoot.Eq(sRootE)) { Log(""sRoot=""); sRoot.LogMe(); Log(""sRootE=""); sRootE.LogMe(); Quit(""Root seqs differ""); } #endif #if TRACE Log(""MakeRootSeq=\n""); sRoot.LogMe(); #endif if (uInsane == uColCount) { uColCount = sRootE.Length(); Aln.SetSize(uSeqCount, uColCount); } else { assert(uColCount == sRootE.Length()); } Aln.SetSeqName(uSeqIndex, s.GetName()); Aln.SetSeqId(uSeqIndex, uId); for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) Aln.SetChar(uSeqIndex, uColIndex, sRootE[uColIndex]); ++uSeqIndex; uTreeNodeIndex = GetNextNodeIndex(GuideTree, uTreeNodeIndex); } while (NULL_NEIGHBOR != uTreeNodeIndex); delete[] Estring1; delete[] Estring2; assert(uSeqIndex == uSeqCount); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/makeindex.cpp",".cpp","2146","86","#include ""pilercr.h"" #include ""forkmer.h"" void FreeIndex(int Finger[], int Pos[]) { freemem(Finger); freemem(Pos); } // Check that index is correct void CheckIndex(char *S, int Slen, const int Finger[], const int Pos[]) { int Found = 0; FOR_EACH_KMER(S, Slen, i, c) bool bFound = false; for (int j = Finger[c]; j < Finger[c+1]; ++j) { if (Pos[j] == i) { ++Found; bFound = true; break; } } if (!bFound) Quit(""CheckIndex failed""); END_FOR_EACH_KMER(S, Slen, i, c) Log(""CheckIndex OK, %u kmers found\n"", Found); } // MakeIndex: make kmer index into S. // Index is two arrays Finger[] and Pos[]. // There is one entry in Finger for every possible kmer. // Consider a kmer with code k. Let i = Finger[k] and // j = Finger[k+1]. Then Pos[i], Pos[i+1] ... Pos[j-1] are // the locations in S where k is found. // If i = j, then the kmer is not present in S. // S [in] string to be indexed // Slen [in] number of letters in S // k [in] kmer length // *ptrFinger [out] Finger[] // *ptrPos [out] Pos[] void MakeIndex(char *S, int Slen, int **ptrFinger, int **ptrPos) { assert(k > 1); assert(Slen >= k); // ctop = number of distinct kmers = (max c) + 1, where c is code. const int ctop = pow4(k); int *Finger = all(int, ctop + 1); zero(Finger, int, ctop + 1); // KmersInS = number of kmers in S const int KmersInS = Slen - k + 1; int *Pos = all(int, KmersInS); // Set Finger[c+1] to be Count[c] = number of times kmer with // code c is found in S. int *TableBase = Finger + 1; FOR_EACH_KMER(S, Slen, i, c) ++(TableBase[c]); END_FOR_EACH_KMER(S, Slen, i, c) // Set Finger[c+1] = sum(i #include #include double GetRAMSize() { struct rlimit RL; int Ok = getrlimit(RLIMIT_DATA, &RL); if (Ok != 0) return 1e9; double m = RL.rlim_cur; if (m > 1.8e9) m = 1.8e9; return m; } static unsigned g_uPeakMemUseBytes = 1000000; unsigned GetPeakMemUseBytes() { return g_uPeakMemUseBytes; } unsigned GetMemUseBytes() { struct rusage RU; int Ok = getrusage(RUSAGE_SELF, &RU); if (Ok != 0) return 1000000; unsigned Bytes = RU.ru_maxrss*1000; if (Bytes > g_uPeakMemUseBytes) g_uPeakMemUseBytes = Bytes; return Bytes; } #endif ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/filterb.cpp",".cpp","14361","607","#include ""pilercr.h"" #include ""forkmer.h"" // FilterB: Banded search of SeqQ // (There is no SeqT). #define TRACE 0 // static char *SeqT; static char *SeqQ; static int Qlen; static int MinMatch; static int MaxError; static int TubeOffset; static int TubeWidth; static int MinKmersPerHit; static TubeState *Tubes; static int MaxActiveTubes; static int MaxKmerDist; //============================================================== // Start rolling index stuff //============================================================== static INDEX_ENTRY *Entries; static INDEX_ENTRY **Heads; static INDEX_ENTRY **Tails; static INDEX_ENTRY *FreeEntries; static int KmerIndexCount; static int KmersInWindow; static int FreeListSize() { int Size = 0; for (INDEX_ENTRY *I = FreeEntries; I; I = I->Next) ++Size; return Size; } static void AddToFreeList(INDEX_ENTRY *IE) { #if DEBUG IE->Kmer = -2; IE->Pos = -2; #endif IE->Prev = 0; IE->Next = FreeEntries; if (0 != FreeEntries) FreeEntries->Prev = IE; FreeEntries = IE; #if TRACE Log(""AddToFreeList(%x), size when done=%d\n"", IE, FreeListSize()); #endif } int GetKmersInWindow() { return g_Diameter - k + 1; } static void AllocateIndex(int g_Diameter) { assert(KmersInWindow > 0); KmerIndexCount = pow4(k); int EntryCount = KmersInWindow + k; Entries = all(INDEX_ENTRY, EntryCount); zero(Entries, INDEX_ENTRY, EntryCount); Heads = all(INDEX_ENTRY *, KmerIndexCount); Tails = all(INDEX_ENTRY *, KmerIndexCount); zero(Heads, INDEX_ENTRY *, KmerIndexCount); zero(Tails, INDEX_ENTRY *, KmerIndexCount); for (int i = 0; i < EntryCount; ++i) AddToFreeList(&(Entries[i])); #if TRACE Log(""KmersInWindow = g_Diameter=%d - k=%d + 1 = %d\n"", g_Diameter, k, KmersInWindow); Log(""After AllocateIndex free list size = %d\n"", FreeListSize()); #endif } static void AddToIndex(int Kmer, int Pos) { #if TRACE Log(""AddToIndex(Kmer=%x=%s, Pos=%d)\n"", Kmer, CodeToString(Kmer, k), Pos); #endif if (-1 == Kmer) return; #if TRACE Log(""Free index has %d entries\n"", FreeListSize()); #endif assert(Kmer >= 0 && Kmer < KmerIndexCount); assert(FreeEntries != 0); INDEX_ENTRY *Entry = FreeEntries; FreeEntries = FreeEntries->Next; if (FreeEntries != 0) FreeEntries->Prev = 0; INDEX_ENTRY *Tail = Tails[Kmer]; // Insert after tail of list Entry->Kmer = Kmer; Entry->Pos = Pos; Entry->Next = 0; Entry->Prev = Tail; if (0 == Tail) Heads[Kmer] = Entry; else Tail->Next = Entry; Tails[Kmer] = Entry; } static inline int GetKmer(const char *Seq, int Pos) { assert(Pos + k <= SeqLengthQ); return StringToCode(Seq + Pos, k); } #define DeclareListPtr(p) INDEX_ENTRY *p static inline INDEX_ENTRY *GetListPtr(int Kmer) { assert(Kmer >= 0 && Kmer < KmerIndexCount); return Heads[Kmer]; } static inline bool NotEndOfList(INDEX_ENTRY *p) { return p != 0; } static inline INDEX_ENTRY *GetListNext(INDEX_ENTRY *p) { return p->Next; } static inline int GetListPos(INDEX_ENTRY *p) { return p->Pos; } static void ValidateIndex(const char *Seq, int WindowStart, int WindowEnd) { ProgressStart(""Validating index""); int FreeCount = 0; for (INDEX_ENTRY *p = FreeEntries; p != 0; p = p->Next) { if (++FreeCount > KmersInWindow) Quit(""Validate index failed free count""); if (p->Kmer != -2 || p->Pos != -2) Quit(""Validate index failed free != -2""); const INDEX_ENTRY *pNext = p->Next; if (0 != pNext && pNext->Prev != p) Quit(""Validate index failed free pNext->Prev != p""); const INDEX_ENTRY *pPrev = p->Prev; if (0 != pPrev && pPrev->Next != p) Quit(""Validate index failed free pPrev->Next != p""); } for (int Pos = WindowStart; Pos < WindowEnd; ++Pos) { const int Kmer = GetKmer(Seq, Pos); if (-1 == Kmer) continue; for (DeclareListPtr(p) = GetListPtr(Kmer); NotEndOfList(p); p = GetListNext(p)) { const int HitPos = GetListPos(p); if (HitPos == Pos) goto Found; } Quit(""Validate index failed, pos=%d not found for kmer %x=%s"", Pos, Kmer, CodeToString(Kmer, k)); Found:; } int IndexedCount = 0; for (int Kmer = 0; Kmer < KmerIndexCount; ++Kmer) { INDEX_ENTRY *Head = Heads[Kmer]; INDEX_ENTRY *Tail = Tails[Kmer]; if (Head != 0 && Head->Prev != 0) Quit(""Head->Prev != 0""); if (Tail != 0 && Tail->Next != 0) Quit(""Tail->Next != 0""); if ((Head == 0) != (Tail == 0)) Quit(""Head / tail""); int PrevHitPos = -1; int ListIndex = 0; for (DeclareListPtr(p) = GetListPtr(Kmer); NotEndOfList(p); p = GetListNext(p)) { ++IndexedCount; if (IndexedCount > KmersInWindow) Quit(""Valiate index failed, count""); const INDEX_ENTRY *pNext = p->Next; if (Kmer != p->Kmer) Quit(""Validate index failed, kmer""); if (0 != pNext && pNext->Prev != p) Quit(""Validate index failed pNext->Prev != p""); const INDEX_ENTRY *pPrev = p->Prev; if (0 != pPrev && pPrev->Next != p) Quit(""Validate index failed pPrev->Next != p""); const int HitPos = GetListPos(p); if (HitPos < WindowStart || HitPos > WindowEnd) Quit(""ValidateIndex failed, hit not in window kmer=%d %s"", Kmer, CodeToString(Kmer, k)); int IsTail = (p->Next == 0); if (HitPos < PrevHitPos) Quit(""Validate index failed, sort order Kmer=%d HitPos=%d PrevHitPos=%d ListIndex=%d IsTail=%d"", Kmer, HitPos, PrevHitPos, ListIndex, IsTail); PrevHitPos = HitPos; ++ListIndex; } } if (IndexedCount > KmersInWindow) Quit(""Validate index failed, count [2]""); ProgressDone(); } static void LogLocations(int Kmer) { Log(""LogLocations(%d %s)"", Kmer, CodeToString(Kmer, k)); for (DeclareListPtr(p) = GetListPtr(Kmer); NotEndOfList(p); p = GetListNext(p)) Log("" [%d]=%d"", p->Pos, StringToCode(SeqQ + p->Pos, k)); } // Pos not required; used for sanity check static void DeleteFirstInstanceFromIndex(int Kmer, int Pos) { #if TRACE Log(""DeleteFirstInstanceFromIndex(Kmer=%x=%s, Pos=%d)\n"", Kmer, CodeToString(Kmer, k), Pos); #endif if (-1 == Kmer) return; assert(Kmer >= 0 && Kmer < KmerIndexCount); INDEX_ENTRY *IE = Heads[Kmer]; if (IE == 0) Quit(""DFI Kmer=%d %s Pos=%d"", Kmer, CodeToString(Kmer, k), Pos); // assert(IE != 0); assert(0 == IE->Prev); assert(Pos == IE->Pos); // Delete from index INDEX_ENTRY *NewHead = IE->Next; if (NewHead == 0) { Heads[Kmer] = 0; Tails[Kmer] = 0; } else { assert(NewHead->Prev == IE); NewHead->Prev = 0; } Heads[Kmer] = NewHead; AddToFreeList(IE); } //============================================================== // End rolling index stuff //============================================================== #define CalcDiagIndex(t, q) (Qlen - (t) + (q)) #define CalcTubeIndex(DiagIndex) ((DiagIndex)/TubeOffset) static void AddHit(int TubeIndex, int qLo, int qHi) { #if TRACE Log(""AddHit(Tube=%d, qLo=%d, qHi=%d)\n"", Qlen - TubeIndex*TubeOffset, qLo, qHi + k); #endif SaveFilterHit(qLo, qHi + k, Qlen - TubeIndex*TubeOffset); } // Called when end of a tube is reached // A point in the tube -- the point with maximal q -- is (Qlen-1,q-1). static void TubeEnd(int q) { if (q <= 0) return; int DiagIndex = CalcDiagIndex(Qlen - 1, q - 1); int TubeIndex = CalcTubeIndex(DiagIndex); TubeState *Tube = Tubes + TubeIndex%MaxActiveTubes; #if TRACE Log(""TubeEnd(%d) DiagIndex=%d TubeIndex=%d Count=%d\n"", q, DiagIndex, TubeIndex, Tube->Count); #endif if (Tube->Count >= MinKmersPerHit) AddHit(TubeIndex, Tube->qLo, Tube->qHi); Tube->Count = 0; } // Called when q=Qlen - 1 to flush any hits in each tube. static void TubeFlush(int TubeIndex) { TubeState *Tube = Tubes + TubeIndex%MaxActiveTubes; #if TRACE Log(""TubeFlush(TubeIndex=%d) Count=%d\n"", TubeIndex, Tube->Count); #endif if (Tube->Count < MinKmersPerHit) return; AddHit(TubeIndex, Tube->qLo, Tube->qHi); Tube->Count = 0; } static void HitTube(int TubeIndex, int q) { TubeState *Tube = Tubes + TubeIndex%MaxActiveTubes; #if TRACE Log(""HitTube(TubeIndex=%d, q=%d) Count=%d\n"", TubeIndex, q, Tube->Count); #endif if (0 == Tube->Count) { Tube->Count = 1; Tube->qLo = q; Tube->qHi = q; return; } if (q - Tube->qHi > MaxKmerDist) { if (Tube->Count >= MinKmersPerHit) AddHit(TubeIndex, Tube->qLo, Tube->qHi); Tube->Count = 1; Tube->qLo = q; Tube->qHi = q; return; } ++(Tube->Count); Tube->qHi = q; } // Found a common k-mer static inline void CommonKmer(int t, int q) { assert(t >= 0 && t < Qlen - k + 1); assert(q >= 0 && q < Qlen - k + 1); if (q <= t) return; #if TRACE Log(""CommonKmer(%d,%d) SeqQ=%.*s SeqQ=%.*s\n"", q, t, k, SeqQ+q, k, SeqQ+t); #endif int DiagIndex = CalcDiagIndex(t, q); int TubeIndex = CalcTubeIndex(DiagIndex); #if TRACE Log(""HitTube(TubeIndex=%d, t=%d, q=%d)\n"", TubeIndex, t, q); #endif HitTube(TubeIndex, q); // Hit in overlapping tube preceding this one? if (DiagIndex%TubeOffset < MaxError) { if (0 == TubeIndex) TubeIndex = MaxActiveTubes - 1; else --TubeIndex; assert(TubeIndex >= 0); #if TRACE Log(""HitTube(TubeIndex=%d, t=%d, q=%d) [overlap]\n"", TubeIndex, t, q); #endif HitTube(TubeIndex, q); } } void FilterBold(char *B_, int Qlen_, const FilterParams &FP) { SeqQ = B_; Qlen = Qlen_; MinMatch = FP.SeedLength; MaxError = FP.SeedDiffs; TubeOffset = FP.TubeOffset; const int Kmask = pow4(k) - 1; // Ukonnen's Lemma MinKmersPerHit = MinMatch + 1 - k*(MaxError + 1); // Maximum distance between SeqQ positions of two k-mers in a match // (More stringent bounds may be possible, but not a big problem // if two adjacent matches get merged). MaxKmerDist = MinMatch - k; TubeWidth = TubeOffset + MaxError; if (TubeOffset < MaxError) { Log(""TubeOffset < MaxError\n""); exit(1); } if (MinKmersPerHit <= 0) { Log(""MinKmersPerHit <= 0\n""); exit(1); } MaxActiveTubes = (Qlen + TubeWidth - 1)/TubeOffset + 1; Tubes = all(TubeState, MaxActiveTubes); zero(Tubes, TubeState, MaxActiveTubes); // Ticker tracks cycling of circular list of active tubes. int Ticker = TubeWidth; // Allocate memory for index ProgressStart(""Allocating index""); KmersInWindow = GetKmersInWindow(); AllocateIndex(g_Diameter); ProgressDone(); /*** Scan query sequence. Start is coordinate of first base in first k-mer in sliding window End is coordinate of first base in last k-mer in sliding window g_Diameter=10 ----------------- | | v v Start End = Start + g_Diameter - k v____ v____ |A|C|T|G|G|A|T|C|C|G|A|T|T|A|C|A|C|C|T|T|A|G|T|C|A| SeqQ --> ^---^ ^___^ . k=3 ^___^ . ^___^ . KmersInWindow = ^___^ . g_Diameter - k + 1 ^___^ . = 8 ^___^ . ^___^ . ^___^ ***/ ProgressStart(""Filtering""); // Position of last kmer in sequence const int LastKmerPos = Qlen - k; // Find first valid kmer in window int FirstValidKmerPos = 0; int FirstValidKmer = 0; for (;;) { if (FirstValidKmerPos >= Qlen) Quit(""No valid words in query""); FirstValidKmer = GetKmer(SeqQ, FirstValidKmerPos); if (FirstValidKmer != -1) break; ++FirstValidKmerPos; } AddToIndex(FirstValidKmer, FirstValidKmerPos); // Last valid kmer in window int LastValidKmerPos = FirstValidKmerPos; // Positions of first and last kmer in window int Start = -g_Diameter + k; int End = 0; int StartKmer = FirstValidKmer; int EndKmer = FirstValidKmer; #if TRACE Log(""Start %d\n"", Start); Log(""End %d\n"", End); Log(""FirstValidKmer %s\n"", CodeToString(FirstValidKmer, k)); Log(""FirstValidKmerPos %d\n"", FirstValidKmerPos); Log(""LastKmerPos %d\n"", LastKmerPos); #endif for (; Start <= LastKmerPos; ++Start, ++End) { #if TRACE if (Start < 0) Log(""START < 0\n""); else Log(""START %4d %.*s\n"", Start, k, SeqQ+Start); if (End > LastKmerPos) Log(""END > End\n""); else Log(""END %4d %.*s\n"", End, k, SeqQ+End); #endif if (Start%1000000 == 0) ProgressStep(End, LastKmerPos); if (Start >= FirstValidKmerPos) { assert(StartKmer == GetKmer(SeqQ, Start)); for (DeclareListPtr(p) = GetListPtr(StartKmer); NotEndOfList(p); p = GetListNext(p)) { int HitPos = GetListPos(p); CommonKmer(Start, HitPos); } DeleteFirstInstanceFromIndex(StartKmer, Start); } if (0 == --Ticker) { TubeEnd(Start); Ticker = TubeOffset; } { if (Start >= FirstValidKmerPos) { char c = SeqQ[Start + k]; int x = CharToLetter[c]; if (x < 0) { StartKmer = 0; FirstValidKmerPos = Start + k + 1; } else StartKmer = ((StartKmer << 2) | x) & Kmask; } } { if (End <= LastKmerPos) { if (End >= LastValidKmerPos) { #if DEBUG if (EndKmer != GetKmer(SeqQ, End)) { Log(""EndKmer=%s"", CodeToString(EndKmer, k)); Log("" != GetKmer(End=%d) = %s\n"", End, CodeToString(GetKmer(SeqQ, End), k)); Quit(""EndKmer != GetKmer""); } #endif AddToIndex(EndKmer, End); } char c = SeqQ[End + k]; int x = CharToLetter[c]; if (x < 0) { EndKmer = 0; LastValidKmerPos = End + k + 1; } else EndKmer = ((EndKmer << 2) | x) & Kmask; } } } ProgressDone(); TubeEnd(Qlen - 1); int DiagFrom = CalcDiagIndex(Qlen - 1, Qlen - 1) - TubeWidth; int DiagTo = CalcDiagIndex(0, Qlen - 1) + TubeWidth; int TubeFrom = CalcTubeIndex(DiagFrom); if (TubeFrom < 0) TubeFrom = 0; int TubeTo = CalcTubeIndex(DiagTo); for (int TubeIndex = TubeFrom; TubeIndex <= TubeTo; ++TubeIndex) TubeFlush(TubeIndex); freemem(Tubes); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/logaa.cpp",".cpp","763","31","#include ""pilercr.h"" static void LogStdStr(const std::string &s) { for (size_t i = 0; i < s.size(); ++i) Log(""%c"", s[i]); } void LogAA(const ArrayAln &AA) { const int RepeatCount = (int) AA.LeftFlanks.size(); assert(RepeatCount == AA.Repeats.size()); assert(RepeatCount == AA.Spacers.size()); Log(""AA Id=%d Pos=%d RepeatCount=%d\n"", AA.Id, AA.Pos, RepeatCount); for (int RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { const std::string &LeftFlank = AA.LeftFlanks[RepeatIndex]; const std::string &Repeat = AA.Repeats[RepeatIndex]; const std::string &Spacer = AA.Spacers[RepeatIndex]; LogStdStr(LeftFlank); Log("" ""); LogStdStr(Repeat); Log("" ""); LogStdStr(Spacer); Log(""\n""); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/outarray.cpp",".cpp","5286","201","#include ""pilercr.h"" #include ""multaln.h"" #define TRACE 0 void PileToSeq(const std::vector &Piles, int PileIndex, Seq &s, int *ptrPosLo, int *ptrPosHi) { const int PileCount = (int) Piles.size(); assert(PileIndex >= 0 && PileIndex < PileCount); const PileData &Pile = Piles[PileIndex]; const ContigData &Contig = GlobalPosToContig(Pile.Lo); int Lo = Pile.Lo - g_HitPadding; int Hi = Pile.Hi + g_HitPadding; if (Lo < Contig.From) Lo = Contig.From; int ContigTo = Contig.From + Contig.Length - 1; if (Hi >= ContigTo) Hi = ContigTo; int Length = Hi - Lo + 1; assert(Length > 0); int n = (int) strlen(Contig.Label) + 64; char *Name = all(char, n); sprintf(Name, ""%s:%d-%d"", Contig.Label, Lo, Hi); s.SetName(Name); freemem(Name); s.reserve(Length); for (int Pos = Lo; Pos <= Hi; ++Pos) s.push_back(g_SeqQ[Pos]); *ptrPosLo = Lo; *ptrPosHi = Hi; } static void OutputArrayHeaderSim() { Out(""\n\n""); Out(""Array Sequence Position Length # Copies Repeat Spacer + Consensus\n""); Out(""===== ================ ========== ========== ======== ====== ====== = =========\n""); } static void OutputArrayHeaderPos() { Out(""\n""); Out(""Array Sequence Position Length # Copies Repeat Spacer Distance Consensus\n""); Out(""===== ================ ========== ========== ======== ====== ====== ========== =========\n""); } static void OutputArraySummaryLineSim(const ArrayAln &AA) { const ContigData &Contig = GlobalPosToContig(AA.Pos); const char *Label = Contig.Label; int ArrayLength = GetArrayLength(AA); int RepeatCount = (int) AA.Repeats.size(); int AvgRepeatLength = GetAvgRepeatLength(AA); int AvgSpacerLength = GetAvgSpacerLength(AA); char Strand = (AA.ClusterRevComp ? '-' : '+'); char *TmpLabel; int LocalLo = GlobalToLocal(AA.Pos, &TmpLabel); Out(""%5d %16.16s %10d %10d %8d %6d %6d %c "", AA.Id, Label, LocalLo + 1, ArrayLength, RepeatCount, AvgRepeatLength, AvgSpacerLength, Strand); const Seq &s = AA.AlignedConsSeq; int Len = s.Length(); for (int i = 0; i < Len; ++i) Out(""%c"", s.GetChar(i)); Out(""\n""); } static void OutputArraySummaryLinePos(const ArrayAln &AA, int Distance) { const ContigData &Contig = GlobalPosToContig(AA.Pos); const char *Label = Contig.Label; int ArrayLength = GetArrayLength(AA); int RepeatCount = (int) AA.Repeats.size(); int AvgRepeatLength = GetAvgRepeatLength(AA); int AvgSpacerLength = GetAvgSpacerLength(AA); char *TmpLabel; int LocalLo = GlobalToLocal(AA.Pos, &TmpLabel); Out(""%5d %16.16s %10d %10d %8d %6d %6d "", AA.Id, Label, LocalLo + 1, ArrayLength, RepeatCount, AvgRepeatLength, AvgSpacerLength); if (Distance == -1) Out("" ""); else Out(""%10d "", Distance); const Seq &s = AA.ConsSeq; int Len = s.Length(); for (int i = 0; i < Len; ++i) Out(""%c"", s.GetChar(i)); Out(""\n""); } static void OutputArrayFooter(const Seq &ConsSymbols) { for (int i = 0; i < (5+2+16+2+10+2+10+8+2+6+2+6+2+2+3); i++) Out("" ""); int Len = ConsSymbols.Length(); for (int i = 0; i < Len; ++i) Out(""%c"", ConsSymbols.GetChar(i)); Out(""\n""); } static bool ByPos(const ArrayAln *A1, const ArrayAln *A2) { return A1->Pos < A2->Pos; } void OutArrays(std::vector &AAVec) { IntVecVec Clusters; ClusterConsRC(AAVec, Clusters); const size_t ClusterCount = Clusters.size(); Progress(""Creating report""); // Detail report Out(""\n""); Out(""\n""); Out(""DETAIL REPORT\n""); Out(""\n""); const size_t ArrayCount = AAVec.size(); for (size_t ArrayIndex = 0; ArrayIndex < ArrayCount; ++ArrayIndex) { const ArrayAln &AA = *(AAVec[ArrayIndex]); OutDetailAA(AA); } // Summary reports Out(""\n""); Out(""\n""); Out(""SUMMARY BY SIMILARITY\n""); Out(""\n""); OutputArrayHeaderSim(); for (size_t ClusterIndex = 0; ClusterIndex < ClusterCount; ++ClusterIndex) { const IntVec &Cluster = Clusters[ClusterIndex]; Seq ConsSymbols; AlignCluster(AAVec, Cluster, ConsSymbols); const size_t ArrayCount = Cluster.size(); for (size_t i = 0; i < ArrayCount; ++i) { unsigned ArrayIndex = Cluster[i]; ArrayAln &AA = *(AAVec[ArrayIndex]); if (ArrayCount == 1) AA.ClusterRevComp = false; OutputArraySummaryLineSim(AA); } if (ArrayCount > 1) OutputArrayFooter(ConsSymbols); Out(""\n""); } Out(""\n""); Out(""\n""); Out(""SUMMARY BY POSITION\n""); Out(""\n""); std::sort(AAVec.begin(), AAVec.end(), ByPos); int LastContigIndex = -1; int LastPos = -1; for (size_t ArrayIndex = 0; ArrayIndex < ArrayCount; ++ArrayIndex) { const ArrayAln &AA = *(AAVec[ArrayIndex]); int Pos = AA.Pos; int ContigIndex = GlobalPosToContigIndex(Pos); if (ContigIndex != LastContigIndex) { LastPos = -1; const ContigData &Contig = GlobalPosToContig(Pos); Out(""\n""); Out(""\n""); Out("">""); Out(Contig.Label); Out(""\n""); OutputArrayHeaderPos(); LastContigIndex = Contig.Index; } int Distance = -1; if (ArrayIndex > 0) Distance = DistanceAA(*(AAVec[ArrayIndex-1]), AA); OutputArraySummaryLinePos(AA, Distance); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/distfunc.cpp",".cpp","2381","112","#include ""multaln.h"" DistFunc::DistFunc() { m_Dists = 0; m_uCount = 0; m_uCacheCount = 0; m_Names = 0; m_Ids = 0; } DistFunc::~DistFunc() { if (0 != m_Names) { for (unsigned i = 0; i < m_uCount; ++i) free(m_Names[i]); } delete[] m_Dists; delete[] m_Names; delete[] m_Ids; } float DistFunc::GetDist(unsigned uIndex1, unsigned uIndex2) const { return m_Dists[VectorIndex(uIndex1, uIndex2)]; } unsigned DistFunc::GetCount() const { return m_uCount; } void DistFunc::SetCount(unsigned uCount) { m_uCount = uCount; if (uCount <= m_uCacheCount) return; delete[] m_Dists; m_Dists = new float[VectorLength()]; m_Names = new char *[m_uCount]; m_Ids = new unsigned[m_uCount]; m_uCacheCount = uCount; memset(m_Names, 0, m_uCount*sizeof(char *)); memset(m_Ids, 0xff, m_uCount*sizeof(unsigned)); memset(m_Dists, 0, VectorLength()*sizeof(float)); } void DistFunc::SetDist(unsigned uIndex1, unsigned uIndex2, float dDist) { m_Dists[VectorIndex(uIndex1, uIndex2)] = dDist; m_Dists[VectorIndex(uIndex2, uIndex1)] = dDist; } unsigned DistFunc::VectorIndex(unsigned uIndex1, unsigned uIndex2) const { assert(uIndex1 < m_uCount && uIndex2 < m_uCount); return uIndex1*m_uCount + uIndex2; } unsigned DistFunc::VectorLength() const { return m_uCount*m_uCount; } void DistFunc::SetName(unsigned uIndex, const char szName[]) { assert(uIndex < m_uCount); m_Names[uIndex] = strsave(szName); } void DistFunc::SetId(unsigned uIndex, unsigned uId) { assert(uIndex < m_uCount); m_Ids[uIndex] = uId; } const char *DistFunc::GetName(unsigned uIndex) const { assert(uIndex < m_uCount); return m_Names[uIndex]; } unsigned DistFunc::GetId(unsigned uIndex) const { assert(uIndex < m_uCount); return m_Ids[uIndex]; } void DistFunc::LogMe() const { Log(""DistFunc::LogMe count=%u\n"", m_uCount); Log("" ""); for (unsigned i = 0; i < m_uCount; ++i) Log("" %7u"", i); Log(""\n""); Log("" ""); for (unsigned i = 0; i < m_uCount; ++i) Log("" %7.7s"", m_Names[i] ? m_Names[i] : """"); Log(""\n""); for (unsigned i = 0; i < m_uCount; ++i) { Log(""%4u %10.10s : "", i, m_Names[i] ? m_Names[i] : """"); for (unsigned j = 0; j <= i; ++j) Log("" %7.4g"", GetDist(i, j)); Log(""\n""); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/makecontigmap.cpp",".cpp","3113","114","#include ""pilercr.h"" void MakeContigMap(const ContigData *Contigs, int ContigCount, int **ptrMap) { *ptrMap = 0; if (ContigCount <= 0) return; const ContigData &LastContig = Contigs[ContigCount-1]; const int SeqLength = LastContig.From + LastContig.Length - 1; const int BinCount = (SeqLength + CONTIG_MAP_BIN_SIZE - 1)/CONTIG_MAP_BIN_SIZE + 1; int *Map = all(int, BinCount); // Initialize, enables correctness check for (int i = 0; i < BinCount; ++i) Map[i] = -1; for (int ContigIndex = 0; ContigIndex < ContigCount; ++ContigIndex) { const ContigData &Contig = Contigs[ContigIndex]; // Contig required to start on bin boundary const int From = Contig.From; if (From%CONTIG_MAP_BIN_SIZE) Quit(""MakeContigMap: Contig does not start on bin boundary""); const int To = From + Contig.Length - 1; const int BinFrom = From/CONTIG_MAP_BIN_SIZE; const int BinTo = To/CONTIG_MAP_BIN_SIZE; for (int Bin = BinFrom; Bin <= BinTo; ++Bin) { if (-1 != Map[Bin]) Quit(""MakeContigMap logic error 1""); Map[Bin] = ContigIndex; } } *ptrMap = Map; for (int ContigIndex = 0; ContigIndex < ContigCount; ++ContigIndex) { const ContigData &Contig = Contigs[ContigIndex]; int ContigIndex2 = GlobalPosToContigIndex(Contig.From); if (ContigIndex2 != ContigIndex) { LogContigs(Contigs, ContigCount); Quit(""MakeContigMap: start pos %d of contig %d mapped to contig %d"", Contig.From, ContigIndex, ContigIndex2); } int To = Contig.From + Contig.Length - 1; int ContigIndex3 = GlobalPosToContigIndex(To); if (ContigIndex2 != ContigIndex) { LogContigs(Contigs, ContigCount); Quit(""MakeContigMap: end pos %d of contig %d mapped to contig index %d"", Contig.From, ContigIndex, ContigIndex3); } } } const ContigData &GlobalPosToContig(int Pos) { int ContigIndex = GlobalPosToContigIndex(Pos); assert(ContigIndex >= 0 && ContigIndex < ContigCountQ); const ContigData &CD = ContigsQ[ContigIndex]; if (Pos < CD.From || Pos >= CD.From + CD.Length) { LogContigs(ContigsQ, ContigCountQ); Quit(""GlobalPosToContig(%d): returned contig %d, out of range"", Pos, ContigIndex); } return CD; } int GlobalPosToContigIndex(int Pos) { int Bin = Pos/CONTIG_MAP_BIN_SIZE; const int BinCount = (SeqLengthQ + CONTIG_MAP_BIN_SIZE - 1)/CONTIG_MAP_BIN_SIZE; // Hack to avoid crashes if (Bin < 0) Bin = 0; if (Bin >= BinCount) Bin = BinCount; if (ContigMapQ == 0) Quit(""ContigMap = 0""); int ContigIndex = -1; // Awful hack... for (;;) { ContigIndex = ContigMapQ[Bin]; if (ContigIndex >= 0) break; if (Bin == 0) Quit(""GlobalPosToContigIndex""); --Bin; } assert(ContigIndex >= 0 && ContigIndex < ContigCountQ); return ContigIndex; } int GlobalToLocal(int Pos, char **ptrLabel) { int ContigIndex = GlobalPosToContigIndex(Pos); assert(ContigIndex >= 0 && ContigIndex < ContigCountQ); const ContigData &Contig = ContigsQ[ContigIndex]; *ptrLabel = Contig.Label; return Pos - Contig.From; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/getccs.cpp",".cpp","4919","234","#include ""pilercr.h"" enum REVSTATE { REVSTATE_Unknown = 0, REVSTATE_Normal = 1, REVSTATE_Reversed = 2 }; struct NeighborData { int NodeIndex; bool Rev; }; typedef std::list NeighborList; typedef NeighborList::iterator PtrNeighborList; struct NodeData { REVSTATE Rev; int Index; NeighborList *Neighbors; NodeData *Next; NodeData *Prev; NodeData **List; }; static NodeData *Nodes; static CompData *MakeFam(NodeData *Nodes) { CompData *Fam = new CompData; for (const NodeData *Node = Nodes; Node; Node = Node->Next) { CompMemberData CompMember; CompMember.PileIndex = Node->Index; switch (Node->Rev) { case REVSTATE_Unknown: Quit(""REVSTATE_Unknown""); case REVSTATE_Normal: CompMember.Rev = false; break; case REVSTATE_Reversed: CompMember.Rev = true; break; } Fam->push_back(CompMember); } return Fam; } static void AddNodeToList(NodeData *Node, NodeData **List) { NodeData *Head = *List; Node->Next = Head; Node->Prev = 0; if (Head != 0) Head->Prev = Node; Node->List = List; *List = Node; } static void DeleteNodeFromList(NodeData *Node, NodeData **List) { assert(Node->List == List); NodeData *Head = *List; if (Node->Next != 0) Node->Next->Prev = Node->Prev; if (Node->Prev != 0) Node->Prev->Next = Node->Next; else *List = Node->Next; Node->List = 0; } static NodeData *ListHead(NodeData **List) { return *List; } static void MoveBetweenLists(NodeData *Node, NodeData **FromList, NodeData **ToList) { DeleteNodeFromList(Node, FromList); AddNodeToList(Node, ToList); } static bool ListIsEmpty(NodeData **List) { return 0 == *List; } static bool NodeIsInList(NodeData *Node, NodeData **List) { return Node->List == List; } static void LogList(NodeData **List) { for (const NodeData *Node = *List; Node; Node = Node->Next) Log("" %d"", Node->Index); Log(""\n""); } static int GetMaxIndex(EdgeList &Edges) { int MaxIndex = -1; for (PtrEdgeList p = Edges.begin(); p != Edges.end(); ++p) { EdgeData &Edge = *p; if (Edge.Node1 > MaxIndex) MaxIndex = Edge.Node1; if (Edge.Node2 > MaxIndex) MaxIndex = Edge.Node2; } return MaxIndex; } static REVSTATE RevState(REVSTATE Rev1, bool Rev2) { switch (Rev1) { case REVSTATE_Normal: if (Rev2) return REVSTATE_Reversed; return REVSTATE_Normal; case REVSTATE_Reversed: if (Rev2) return REVSTATE_Normal; return REVSTATE_Reversed; } assert(false); return REVSTATE_Unknown; } int GetConnComps(EdgeList &Edges, CompList &Fams, int MinComponentSize) { Fams.clear(); if (0 == Edges.size()) return 0; int NodeCount = GetMaxIndex(Edges) + 1; Nodes = new NodeData[NodeCount]; for (int i = 0; i < NodeCount; ++i) { Nodes[i].Neighbors = new NeighborList; Nodes[i].Rev = REVSTATE_Unknown; Nodes[i].Index = i; } NodeData *NotVisitedList = 0; NodeData *PendingList = 0; NodeData *CurrentList = 0; for (PtrEdgeList p = Edges.begin(); p != Edges.end(); ++p) { EdgeData &Edge = *p; int From = Edge.Node1; int To = Edge.Node2; assert(From >= 0 && From < NodeCount); assert(To >= 0 && From < NodeCount); NeighborData NTo; NTo.NodeIndex = To; NTo.Rev = Edge.Rev; Nodes[From].Neighbors->push_back(NTo); NeighborData NFrom; NFrom.NodeIndex = From; NFrom.Rev = Edge.Rev; Nodes[To].Neighbors->push_back(NFrom); } for (int i = 0; i < NodeCount; ++i) AddNodeToList(&Nodes[i], &NotVisitedList); int FamCount = 0; while (!ListIsEmpty(&NotVisitedList)) { int ClassSize = 0; NodeData *Node = ListHead(&NotVisitedList); // This node becomes the first in the family // By convention, the first member defines reversal or lack thereof. Node->Rev = REVSTATE_Normal; assert(ListIsEmpty(&PendingList)); MoveBetweenLists(Node, &NotVisitedList, &PendingList); while (!ListIsEmpty(&PendingList)) { Node = ListHead(&PendingList); assert(REVSTATE_Normal == Node->Rev || REVSTATE_Reversed == Node->Rev); NeighborList *Neighbors = Node->Neighbors; for (PtrNeighborList p = Neighbors->begin(); p != Neighbors->end(); ++p) { NeighborData &Neighbor = *p; int NeighborIndex = Neighbor.NodeIndex; NodeData *NeighborNode = &(Nodes[NeighborIndex]); if (NodeIsInList(NeighborNode, &NotVisitedList)) { NeighborNode->Rev = RevState(Node->Rev, Neighbor.Rev); MoveBetweenLists(NeighborNode, &NotVisitedList, &PendingList); } } ++ClassSize; MoveBetweenLists(Node, &PendingList, &CurrentList); } if (ClassSize >= MinComponentSize) { CompData *Fam = MakeFam(CurrentList); Fams.push_back(Fam); ++FamCount; } CurrentList = 0; } return FamCount; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/bittb.cpp",".cpp","3310","206","#include ""multaln.h"" #define TRACE 0 static char XlatEdgeType(char c) { if ('E' == c) return 'D'; if ('J' == c) return 'I'; return c; } static const char *BitsToStr(char Bits) { static char Str[] = ""xM xD xI""; switch (Bits & BIT_xM) { case BIT_MM: Str[0] = 'M'; break; case BIT_DM: Str[0] = 'D'; break; case BIT_IM: Str[0] = 'I'; break; } switch (Bits & BIT_xD) { case BIT_MD: Str[3] = 'M'; break; case BIT_DD: Str[3] = 'D'; break; } switch (Bits & BIT_xI) { case BIT_MI: Str[6] = 'M'; break; case BIT_II: Str[6] = 'I'; break; } return Str; } static inline char XChar(char Bits, char cType) { switch (cType) { case 'M': { switch (Bits & BIT_xM) { case BIT_MM: return 'M'; case BIT_DM: return 'D'; case BIT_IM: return 'I'; #if DOUBLE_AFFINE case BIT_EM: return 'E'; case BIT_JM: return 'J'; #endif } Quit(""Huh!?""); return '?'; } case 'D': { switch (Bits & BIT_xD) { case BIT_MD: return 'M'; case BIT_DD: return 'D'; } Quit(""Huh!?""); return '?'; } case 'I': { switch (Bits & BIT_xI) { case BIT_MI: return 'M'; case BIT_II: return 'I'; } Quit(""Huh!?""); return '?'; } #if DOUBLE_AFFINE case 'E': { switch (Bits & BIT_xE) { case BIT_ME: return 'M'; case BIT_EE: return 'E'; } Quit(""Huh!?""); return '?'; } case 'J': { switch (Bits & BIT_xJ) { case BIT_MJ: return 'M'; case BIT_JJ: return 'J'; } Quit(""Huh!?""); return '?'; } #endif default: Quit(""Huh?""); return '?'; } } void BitTraceBack(char **TraceBack, unsigned uLengthA, unsigned uLengthB, char LastEdge, PWPath &Path) { #if TRACE Log(""BitTraceBack\n""); #endif Path.Clear(); PWEdge Edge; Edge.uPrefixLengthA = uLengthA; Edge.uPrefixLengthB = uLengthB; char Bits = TraceBack[uLengthA][uLengthB]; Edge.cType = LastEdge; for (;;) { #if TRACE Log(""Prepend %c%d.%d\n"", Edge.cType, Edge.uPrefixLengthA, Edge.uPrefixLengthB); #endif char cSave = Edge.cType; Edge.cType = XlatEdgeType(cSave); Path.PrependEdge(Edge); Edge.cType = cSave; unsigned PLA = Edge.uPrefixLengthA; unsigned PLB = Edge.uPrefixLengthB; char Bits = TraceBack[PLA][PLB]; char NextEdgeType = XChar(Bits, Edge.cType); #if TRACE Log(""XChar(%s, %c) = %c\n"", BitsToStr(Bits), Edge.cType, NextEdgeType); #endif switch (Edge.cType) { case 'M': { if (Edge.uPrefixLengthA == 0) Quit(""BitTraceBack MA=0""); if (Edge.uPrefixLengthB == 0) Quit(""BitTraceBack MA=0""); --(Edge.uPrefixLengthA); --(Edge.uPrefixLengthB); break; } case 'D': case 'E': { if (Edge.uPrefixLengthA == 0) Quit(""BitTraceBack DA=0""); --(Edge.uPrefixLengthA); break; } case 'I': case 'J': { if (Edge.uPrefixLengthB == 0) Quit(""BitTraceBack IB=0""); --(Edge.uPrefixLengthB); break; } default: Quit(""BitTraceBack: Invalid edge %c"", Edge); } if (0 == Edge.uPrefixLengthA && 0 == Edge.uPrefixLengthB) break; Edge.cType = NextEdgeType; } #if TRACE Path.LogMe(); #endif } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/revcomp.cpp",".cpp","693","38","#include ""types.h"" unsigned char CompMap[256]; static bool InitMap() { for (unsigned i = 0; i < 256; ++i) CompMap[i] = i; CompMap[(int) 'a'] = 't'; CompMap[(int) 'c'] = 'g'; CompMap[(int) 'g'] = 'c'; CompMap[(int) 't'] = 'a'; CompMap[(int) 'A'] = 'T'; CompMap[(int) 'C'] = 'G'; CompMap[(int) 'G'] = 'C'; CompMap[(int) 'T'] = 'A'; return true; } static bool InitDone = InitMap(); void RevComp(char *S, unsigned L) { unsigned char *s = (unsigned char *) S; unsigned char *t = (unsigned char *) (S + L - 1); while (s < t) { unsigned char c = *s; *s++ = CompMap[*t]; *t-- = CompMap[c]; } if (s == t) *s = CompMap[*s]; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/outdetailaa.cpp",".cpp","4182","159","#include ""pilercr.h"" static void OutputDetailHeader(const ArrayAln &AA) { unsigned RepeatColCount = (unsigned) AA.Repeats[0].size(); char *Label; GlobalToLocal(AA.Pos, &Label); Out(""\n\n""); Out(""Array %d\n"", AA.Id); Out("">%s\n"", Label); Out(""\n""); Out("" Pos Repeat %%id Spacer Left flank Repeat""); int Blanks = (int) RepeatColCount - 6; for (int i = 0; i < Blanks; ++i) Out("" ""); Out("" Spacer\n""); Out(""========== ====== ====== ====== ========== ""); // 1234567890 123456 123456 123456 1234567890 for (unsigned i = 0; i < RepeatColCount; ++i) Out(""=""); Out("" ======\n""); } int GetAvgSpacerLength(const ArrayAln &AA) { size_t RepeatCount = AA.Repeats.size(); size_t Sum = 0; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount - 1; ++RepeatIndex) Sum += AA.Spacers[RepeatIndex].size(); return (int) (Sum / (RepeatCount - 1)); } int GetAvgRepeatLength(const ArrayAln &AA) { size_t RepeatCount = AA.Repeats.size(); size_t Sum = 0; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) Sum += AA.Repeats[RepeatIndex].size(); return (int) (Sum / RepeatCount); } static void OutputDetailFooter(const ArrayAln &AA) { unsigned RepeatColCount = (unsigned) AA.Repeats[0].size(); Out(""========== ====== ====== ====== ========== ""); for (unsigned i = 0; i < RepeatColCount; ++i) Out(""=""); Out(""\n""); int RepeatCount = (int) AA.Repeats.size(); int RepeatLength = (int) AA.Repeats[0].size(); int SpacerLength = GetAvgSpacerLength(AA); Out(""%10d %6d %6d "", RepeatCount, RepeatLength, SpacerLength); assert(AA.AlignedConsSeq.size() == RepeatColCount); for (unsigned i = 0; i < RepeatColCount; ++i) Out(""%c"", AA.AlignedConsSeq[i]); Out(""\n""); } static double GetRepeatPctId(const ArrayAln &AA, size_t RepeatIndex) { assert(RepeatIndex < AA.Repeats.size()); const std::string &Repeat = AA.Repeats[RepeatIndex]; const Seq &ConsSeq = AA.AlignedConsSeq; size_t RepeatLength = Repeat.size(); assert(ConsSeq.size() == RepeatLength); int Same = 0; for (size_t i = 0; i < RepeatLength; ++i) { if (toupper(ConsSeq[i]) == toupper(Repeat[i])) ++Same; } return 100.0 * (double) Same / (double) RepeatLength; } static void OutDetailRepeat(const ArrayAln &AA, size_t RepeatIndex, int &Pos) { const std::string &LeftFlank = AA.LeftFlanks[RepeatIndex]; const std::string &Repeat = AA.Repeats[RepeatIndex]; const std::string &Spacer = AA.Spacers[RepeatIndex]; const Seq &ConsSeq = AA.AlignedConsSeq; size_t LeftFlankLength = LeftFlank.size(); size_t RepeatLength = Repeat.size(); size_t SpacerLength = Spacer.size(); assert(LeftFlankLength == g_FlankSize); double PctId = GetRepeatPctId(AA, RepeatIndex); const ContigData &Contig = GlobalPosToContig(Pos); const char *Label = Contig.Label; char *TmpLabel; int LocalLo = GlobalToLocal(Pos, &TmpLabel); // Pos Repeat %id Spacer Left flank Repeat // ========== ====== ====== ====== ========== ====== // 1234567890 123456 123456 123456 1234567890 Out(""%10d %6d %6.1f "", LocalLo + 1, // 1-based for user's benefit RepeatLength, PctId); const size_t RepeatCount = AA.Repeats.size(); if (RepeatIndex == RepeatCount - 1) Out("" ""); else Out(""%6d "", SpacerLength); for (size_t i = 0; i < LeftFlankLength; ++i) Out(""%c"", LeftFlank[i]); Out("" ""); for (size_t i = 0; i < RepeatLength; ++i) { if (Repeat[i] == ConsSeq[i]) { if (Repeat[i] == '-') Out(""-""); else Out("".""); } else Out(""%c"", Repeat[i]); } Out("" ""); for (size_t i = 0; i < SpacerLength; ++i) Out(""%c"", Spacer[i]); Out(""\n""); Pos += (int) (RepeatLength + SpacerLength); } void OutDetailAA(const ArrayAln &AA) { OutputDetailHeader(AA); int Pos = AA.Pos; size_t RepeatCount = AA.Repeats.size(); for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) OutDetailRepeat(AA, RepeatIndex, Pos); OutputDetailFooter(AA); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/pilercr.cpp",".cpp","7071","265","#include ""pilercr.h"" // for getpid: #if WIN32 #include #else #include #include #endif int k; char *g_SeqQ = 0; ContigData *ContigsQ = 0; int SeqLengthQ = -1; int *ContigMapQ = 0; int ContigCountQ = -1; bool FilterComp = false; int g_MinHitLength = 16; static double g_MinId = 0.94; unsigned g_AcceptedHitCount = 0; unsigned g_NotAcceptedHitCount = 0; std::vector g_Piles; int g_PileCount; std::vector g_Hits; int g_HitCount; IntVec g_HitIndexToPileIndexA; IntVec g_HitIndexToPileIndexB; std::vector g_Images; int g_ImageCount; int g_Diameter; extern bool g_ShowProgress; FILE *fDiscardedHits = 0; FILE *fPiles = 0; FILE *g_fOut = 0; FILE *g_fSeqs = 0; unsigned g_DiscardedHitCount = 0; static const char *GetFilterOutFileName(const char *FilterOutPrefix, const char *Ext) { if (0 == FilterOutPrefix) { static char s[32]; sprintf(s, ""./_pf%d"", getpid()); FilterOutPrefix = s; } size_t n = strlen(FilterOutPrefix) + strlen(Ext) + 1; char *FileName = all(char, (int) n); strcpy(FileName, FilterOutPrefix); strcat(FileName, Ext); assert(strlen(FileName) == n - 1); return FileName; } void PILERCR() { const char *InFileName = RequiredValueOpt(""in""); const char *OutFileName = RequiredValueOpt(""out""); const char *HitsFileName = ValueOpt(""hits""); const char *DiscardedHitsFileName = ValueOpt(""discardedhits""); const char *PilesFileName = ValueOpt(""piles""); const char *SeqsFileName = ValueOpt(""seq""); const char *FilterOutPrefix = ValueOpt(""filterout""); if (SeqsFileName != 0) g_fSeqs = CreateStdioFile(SeqsFileName); g_ShowHits = FlagOpt(""showhits""); g_LogHits = FlagOpt(""loghits""); g_LogImages = FlagOpt(""logimages""); g_LogAlns = FlagOpt(""logalns""); g_NoInfo = FlagOpt(""noinfo""); IntOpt(""minhitlength"", &g_MinHitLength); IntOpt(""minrepeat"", &g_MinRepeatLength); IntOpt(""maxrepeat"", &g_MaxRepeatLength); IntOpt(""minspacer"", &g_MinSpacerLength); IntOpt(""maxspacer"", &g_MaxSpacerLength); IntOpt(""minarray"", &g_MinArraySize); FloatOpt(""minid"", &g_MinId); FloatOpt(""minrepeatratio"", &g_MinRepeatRatio); FloatOpt(""minspacerratio"", &g_MinSpacerRatio); FloatOpt(""mincons"", &g_MinCons); bool Quiet = FlagOpt(""quiet""); if (Quiet) g_ShowProgress = false; g_DraftMinArraySize = g_MinArraySize - 2; if (g_DraftMinArraySize < 2) g_DraftMinArraySize = 2; Progress(""Reading sequences from %s"", InFileName); g_SeqQ = ReadMFA(InFileName, &SeqLengthQ, &ContigsQ, &ContigCountQ, &ContigMapQ); ProgressDone(); Progress(""%d sequences, total length %d bases (%.0f Mb)"", ContigCountQ, SeqLengthQ, SeqLengthQ/1e6); int g_MinHitLength = g_DraftMinRepeatLength; g_Diameter = 2*g_DraftMaxRepeatLength + g_DraftMaxSpacerLength; if (g_Diameter > SeqLengthQ) g_Diameter = SeqLengthQ; g_MaxDPHitLen = (3*g_DraftMaxRepeatLength)/2; FilterParams FP; DPParams DP; GetParams(SeqLengthQ, g_Diameter, g_MinHitLength, g_MinId, &FP, &DP); k = FP.WordSize; const double SeedPctId = (1.0 - (double) FP.SeedDiffs / (double) FP.SeedLength)*100.0; const double MemRequired = TotalMemRequired(SeqLengthQ, FP); const double AvgIndexList = AvgIndexListLength(SeqLengthQ, FP); Log(""Filter parameters:\n""); Log("" Word size %d\n"", FP.WordSize); Log("" Seed length %d\n"", FP.SeedLength); Log("" Seed diffs %d\n"", FP.SeedDiffs); Log("" Seed min id %.1f%%\n"", SeedPctId); Log("" Tube offset %d\n"", FP.TubeOffset); if (AvgIndexList > 2) Log("" Avg index list %.1f\n"", AvgIndexList); else Log("" Avg index list %.2g\n"", AvgIndexList); Log(""DP parameters:\n""); Log("" Min length %d\n"", DP.g_MinHitLength); Log("" Min id %.0f%%\n"", DP.MinId*100.0); Log(""Estd. memory %.0f Mb\n"", MemRequired/1e6); Log(""RAM %.0f Mb\n"", GetRAMSize()/1e6); int *Finger = 0; int *Pos = 0; const char *strFilterOutFileName = GetFilterOutFileName(FilterOutPrefix, "".f.tmp""); FILE *fFilterOut = OpenStdioFile(strFilterOutFileName, FILEIO_MODE_ReadWrite); SetFilterOutFile(fFilterOut); FilterB(g_SeqQ, SeqLengthQ, FP); const int FilterHitCount = GetFilterHitCount(); Progress(""%d filter hits"", FilterHitCount); FILE *fFilterOutComp = 0; int FilterHitCountComp = 0; const char *strFilterOutFileNameComp = 0; Progress(""Read filter hits""); FilterHit *FilterHits = ReadFilterHits(fFilterOut, FilterHitCount); CloseFilterOutFile(); if (0 == FilterOutPrefix) remove(strFilterOutFileName); Progress(""%d filter hits"", FilterHitCount); // SaveFilterHits(FilterHits, FilterHitCount); Progress(""Merge filter hits""); int TrapCount; Trapezoid *Traps = MergeFilterHits(g_SeqQ, SeqLengthQ, g_SeqQ, SeqLengthQ, true, FilterHits, FilterHitCount, FP, &TrapCount); LogTraps(Traps); SaveTraps(Traps); freemem(FilterHits); FilterHits = 0; const int SumLengths = SumTrapLengths(Traps); Progress(""%d trapezoids, total length %d"", TrapCount, SumLengths); if (DiscardedHitsFileName != 0) fDiscardedHits = OpenStdioFile(DiscardedHitsFileName, FILEIO_MODE_WriteOnly); AlignTraps(g_SeqQ, SeqLengthQ, g_SeqQ, SeqLengthQ, Traps, TrapCount, false, DP); if (HitsFileName != 0) { FILE *fHits = OpenStdioFile(HitsFileName, FILEIO_MODE_WriteOnly); WriteDPHits(fHits, false); fclose(fHits); } Progress(""Sorting hits""); std::sort(g_Hits.begin(), g_Hits.end(), Cmp_Lo); if (g_LogHits) LogHits(); if (fDiscardedHits != 0) { fclose(fDiscardedHits); fDiscardedHits = 0; } Progress(""%d DP hits, %d accepted"", g_NotAcceptedHitCount + g_AcceptedHitCount, g_AcceptedHitCount); Progress(""%u discarded hits"", g_DiscardedHitCount); HitsToImages(); Progress(""Finding piles""); FindPiles(); ExpandPiles(); WritePiles(); Progress(""%d piles found"", (int) g_Piles.size()); Progress(""Building graph""); EdgeList Edges; MakeGraph(Edges); Progress(""Find connected components""); CompList Comps; GetConnComps(Edges, Comps, g_DraftMinArraySize); Progress(""%d connected components"", (int) Comps.size()); Progress(""Find arrays""); std::vector ADVec; for (CompList::const_iterator p = Comps.begin(); p != Comps.end(); ++p) { const CompData *Comp = *p; FindArrays(*Comp, ADVec); } g_fOut = CreateStdioFile(OutFileName); if (!g_NoInfo) Info(); std::vector AAVec; AlignArrays(ADVec, AAVec); const int ArrayCount = (int) AAVec.size(); Progress(""%d arrays found"", (int) AAVec.size()); Out(PILERCR_LONG_VERSION ""\n""); Out(""By Robert C. Edgar\n\n""); Out(""%s: %d putative CRISPR arrays found.\n\n"", InFileName, ArrayCount); if (ArrayCount == 0) return; OutArrays(AAVec); fclose(g_fOut); g_fOut = 0; if (g_fSeqs != 0) { SaveSeqs(g_fSeqs, AAVec); g_fSeqs = 0; } freemem(g_SeqQ); g_SeqQ = 0; free(Traps); Traps = 0; Progress(""Done""); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/alngivenpath.cpp",".cpp","21953","811","#include ""multaln.h"" #define TRACE 0 static void LogPP(const ProfPos &PP) { Log(""ResidueGroup %u\n"", PP.m_uResidueGroup); Log(""AllGaps %d\n"", PP.m_bAllGaps); Log(""Occ %.3g\n"", PP.m_fOcc); Log(""LL=%.3g LG=%.3g GL=%.3g GG=%.3g\n"", PP.m_LL, PP.m_LG, PP.m_GL, PP.m_GG); Log(""Freqs ""); for (unsigned i = 0; i < g_AlphaSize; ++i) if (PP.m_fcCounts[i] > 0) Log(""%c=%.3g "", LetterToChar(i), PP.m_fcCounts[i]); Log(""\n""); } static void AssertProfPosEq(const ProfPos *PA, const ProfPos *PB, unsigned i) { const ProfPos &PPA = PA[i]; const ProfPos &PPB = PB[i]; #define eq(x) if (PPA.m_##x != PPB.m_##x) { LogPP(PPA); LogPP(PPB); Quit(""AssertProfPosEq."" #x); } #define be(x) if (!BTEq(PPA.m_##x, PPB.m_##x)) { LogPP(PPA); LogPP(PPB); Quit(""AssertProfPosEq."" #x); } eq(bAllGaps) eq(uResidueGroup) be(LL) be(LG) be(GL) be(GG) be(fOcc) be(scoreGapOpen) be(scoreGapClose) for (unsigned j = 0; j < g_AlphaSize; ++j) { #define eqj(x) if (PPA.m_##x != PPB.m_##x) Quit(""AssertProfPosEq j=%u "" #x, j); #define bej(x) if (!BTEq(PPA.m_##x, PPB.m_##x)) Quit(""AssertProfPosEq j=%u "" #x, j); bej(fcCounts[j]); // eqj(uSortOrder[j]) // may differ due to ties, don't check? bej(AAScores[j]) #undef eqj #undef bej } #undef eq #undef be } void AssertProfsEq(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB) { if (uLengthA != uLengthB) Quit(""AssertProfsEq: lengths differ %u %u"", uLengthA, uLengthB); for (unsigned i = 0; i < uLengthB; ++i) AssertProfPosEq(PA, PB, i); } #if DEBUG static void ValidateProf(const ProfPos *Prof, unsigned uLength) { for (unsigned i = 0; i < uLength; ++i) { const ProfPos &PP = Prof[i]; FCOUNT s1 = PP.m_LL + PP.m_LG + PP.m_GL + PP.m_GG; assert(BTEq(s1, 1.0)); if (i > 0) { const ProfPos &PPPrev = Prof[i-1]; FCOUNT s2 = PPPrev.m_LL + PPPrev.m_GL; FCOUNT s3 = PP.m_LL + PP.m_LG; assert(BTEq(s2, s3)); } if (i < uLength - 1) { const ProfPos &PPNext = Prof[i+1]; FCOUNT s4 = PP.m_LL + PP.m_GL; FCOUNT s5 = PPNext.m_LL + PPNext.m_LG; assert(BTEq(s4, s5)); } } } #else #define ValidateProf(Prof, Length) /* empty */ #endif static void SortCounts(const FCOUNT fcCounts[], unsigned SortOrder[]) { static unsigned InitialSortOrder[20] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19 }; memcpy(SortOrder, InitialSortOrder, g_AlphaSize*sizeof(unsigned)); bool bAny = true; while (bAny) { bAny = false; for (unsigned n = 0; n < g_AlphaSize - 1; ++n) { unsigned i1 = SortOrder[n]; unsigned i2 = SortOrder[n+1]; if (fcCounts[i1] < fcCounts[i2]) { SortOrder[n+1] = i1; SortOrder[n] = i2; bAny = true; } } } } static void ScoresFromFreqsPos(ProfPos *Prof, unsigned uLength, unsigned uPos) { ProfPos &PP = Prof[uPos]; SortCounts(PP.m_fcCounts, PP.m_uSortOrder); PP.m_uResidueGroup = 0; // ""Occupancy"" PP.m_fOcc = PP.m_LL + PP.m_GL; // Frequency of gap-opens in this position (i) // Gap open = letter in i-1 and gap in i // = iff LG in i FCOUNT fcOpen = PP.m_LG; // Frequency of gap-closes in this position // Gap close = gap in i and letter in i+1 // = iff GL in i+1 FCOUNT fcClose; if (uPos + 1 < uLength) fcClose = Prof[uPos + 1].m_GL; else fcClose = PP.m_GG + PP.m_LG; PP.m_scoreGapOpen = (SCORE) ((1.0 - fcOpen)*g_scoreGapOpen/2.0); PP.m_scoreGapClose = (SCORE) ((1.0 - fcClose)*g_scoreGapOpen/2.0); #if DOUBLE_AFFINE PP.m_scoreGapOpen2 = (SCORE) ((1.0 - fcOpen)*g_scoreGapOpen2/2.0); PP.m_scoreGapClose2 = (SCORE) ((1.0 - fcClose)*g_scoreGapOpen2/2.0); #endif for (unsigned i = 0; i < g_AlphaSize; ++i) { SCORE scoreSum = 0; for (unsigned j = 0; j < g_AlphaSize; ++j) scoreSum += PP.m_fcCounts[j]*(*g_ptrScoreMatrix)[i][j]; PP.m_AAScores[i] = scoreSum; } } void ProfScoresFromFreqs(ProfPos *Prof, unsigned uLength) { for (unsigned i = 0; i < uLength; ++i) ScoresFromFreqsPos(Prof, uLength, i); } static void AppendDelete(const MSA &msaA, unsigned &uColIndexA, unsigned uSeqCountA, unsigned uSeqCountB, MSA &msaCombined, unsigned &uColIndexCombined) { #if TRACE Log(""AppendDelete ColIxA=%u ColIxCmb=%u\n"", uColIndexA, uColIndexCombined); #endif for (unsigned uSeqIndexA = 0; uSeqIndexA < uSeqCountA; ++uSeqIndexA) { char c = msaA.GetChar(uSeqIndexA, uColIndexA); msaCombined.SetChar(uSeqIndexA, uColIndexCombined, c); } for (unsigned uSeqIndexB = 0; uSeqIndexB < uSeqCountB; ++uSeqIndexB) msaCombined.SetChar(uSeqCountA + uSeqIndexB, uColIndexCombined, '-'); ++uColIndexCombined; ++uColIndexA; } static void AppendInsert(const MSA &msaB, unsigned &uColIndexB, unsigned uSeqCountA, unsigned uSeqCountB, MSA &msaCombined, unsigned &uColIndexCombined) { #if TRACE Log(""AppendInsert ColIxB=%u ColIxCmb=%u\n"", uColIndexB, uColIndexCombined); #endif for (unsigned uSeqIndexA = 0; uSeqIndexA < uSeqCountA; ++uSeqIndexA) msaCombined.SetChar(uSeqIndexA, uColIndexCombined, '-'); for (unsigned uSeqIndexB = 0; uSeqIndexB < uSeqCountB; ++uSeqIndexB) { char c = msaB.GetChar(uSeqIndexB, uColIndexB); msaCombined.SetChar(uSeqCountA + uSeqIndexB, uColIndexCombined, c); } ++uColIndexCombined; ++uColIndexB; } static void AppendTplInserts(const MSA &msaA, unsigned &uColIndexA, unsigned uColCountA, const MSA &msaB, unsigned &uColIndexB, unsigned uColCountB, unsigned uSeqCountA, unsigned uSeqCountB, MSA &msaCombined, unsigned &uColIndexCombined) { #if TRACE Log(""AppendTplInserts ColIxA=%u ColIxB=%u ColIxCmb=%u\n"", uColIndexA, uColIndexB, uColIndexCombined); #endif const unsigned uLengthA = msaA.GetColCount(); const unsigned uLengthB = msaB.GetColCount(); unsigned uNewColCount = uColCountA; if (uColCountB > uNewColCount) uNewColCount = uColCountB; for (unsigned n = 0; n < uColCountA; ++n) { for (unsigned uSeqIndexA = 0; uSeqIndexA < uSeqCountA; ++uSeqIndexA) { char c = msaA.GetChar(uSeqIndexA, uColIndexA + n); c = UnalignChar(c); msaCombined.SetChar(uSeqIndexA, uColIndexCombined + n, c); } } for (unsigned n = uColCountA; n < uNewColCount; ++n) { for (unsigned uSeqIndexA = 0; uSeqIndexA < uSeqCountA; ++uSeqIndexA) msaCombined.SetChar(uSeqIndexA, uColIndexCombined + n, '.'); } for (unsigned n = 0; n < uColCountB; ++n) { for (unsigned uSeqIndexB = 0; uSeqIndexB < uSeqCountB; ++uSeqIndexB) { char c = msaB.GetChar(uSeqIndexB, uColIndexB + n); c = UnalignChar(c); msaCombined.SetChar(uSeqCountA + uSeqIndexB, uColIndexCombined + n, c); } } for (unsigned n = uColCountB; n < uNewColCount; ++n) { for (unsigned uSeqIndexB = 0; uSeqIndexB < uSeqCountB; ++uSeqIndexB) msaCombined.SetChar(uSeqCountA + uSeqIndexB, uColIndexCombined + n, '.'); } uColIndexCombined += uNewColCount; uColIndexA += uColCountA; uColIndexB += uColCountB; } static void AppendMatch(const MSA &msaA, unsigned &uColIndexA, const MSA &msaB, unsigned &uColIndexB, unsigned uSeqCountA, unsigned uSeqCountB, MSA &msaCombined, unsigned &uColIndexCombined) { #if TRACE Log(""AppendMatch ColIxA=%u ColIxB=%u ColIxCmb=%u\n"", uColIndexA, uColIndexB, uColIndexCombined); #endif for (unsigned uSeqIndexA = 0; uSeqIndexA < uSeqCountA; ++uSeqIndexA) { char c = msaA.GetChar(uSeqIndexA, uColIndexA); msaCombined.SetChar(uSeqIndexA, uColIndexCombined, c); } for (unsigned uSeqIndexB = 0; uSeqIndexB < uSeqCountB; ++uSeqIndexB) { char c = msaB.GetChar(uSeqIndexB, uColIndexB); msaCombined.SetChar(uSeqCountA + uSeqIndexB, uColIndexCombined, c); } ++uColIndexA; ++uColIndexB; ++uColIndexCombined; } void AlignTwoMSAsGivenPath(const PWPath &Path, const MSA &msaA, const MSA &msaB, MSA &msaCombined) { msaCombined.Clear(); #if TRACE Log(""FastAlignProfiles\n""); Log(""Template A:\n""); msaA.LogMe(); Log(""Template B:\n""); msaB.LogMe(); #endif const unsigned uColCountA = msaA.GetColCount(); const unsigned uColCountB = msaB.GetColCount(); const unsigned uSeqCountA = msaA.GetSeqCount(); const unsigned uSeqCountB = msaB.GetSeqCount(); msaCombined.SetSeqCount(uSeqCountA + uSeqCountB); // Copy sequence names into combined MSA for (unsigned uSeqIndexA = 0; uSeqIndexA < uSeqCountA; ++uSeqIndexA) { msaCombined.SetSeqName(uSeqIndexA, msaA.GetSeqName(uSeqIndexA)); msaCombined.SetSeqId(uSeqIndexA, msaA.GetSeqId(uSeqIndexA)); } for (unsigned uSeqIndexB = 0; uSeqIndexB < uSeqCountB; ++uSeqIndexB) { msaCombined.SetSeqName(uSeqCountA + uSeqIndexB, msaB.GetSeqName(uSeqIndexB)); msaCombined.SetSeqId(uSeqCountA + uSeqIndexB, msaB.GetSeqId(uSeqIndexB)); } unsigned uColIndexA = 0; unsigned uColIndexB = 0; unsigned uColIndexCombined = 0; const unsigned uEdgeCount = Path.GetEdgeCount(); for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &Edge = Path.GetEdge(uEdgeIndex); #if TRACE Log(""\nEdge %u %c%u.%u\n"", uEdgeIndex, Edge.cType, Edge.uPrefixLengthA, Edge.uPrefixLengthB); #endif const char cType = Edge.cType; const unsigned uPrefixLengthA = Edge.uPrefixLengthA; unsigned uColCountA = 0; if (uPrefixLengthA > 0) { const unsigned uNodeIndexA = uPrefixLengthA - 1; const unsigned uTplColIndexA = uNodeIndexA; if (uTplColIndexA > uColIndexA) uColCountA = uTplColIndexA - uColIndexA; } const unsigned uPrefixLengthB = Edge.uPrefixLengthB; unsigned uColCountB = 0; if (uPrefixLengthB > 0) { const unsigned uNodeIndexB = uPrefixLengthB - 1; const unsigned uTplColIndexB = uNodeIndexB; if (uTplColIndexB > uColIndexB) uColCountB = uTplColIndexB - uColIndexB; } // TODO: This code looks like a hangover from HMM estimation -- can we delete it? assert(uColCountA == 0); assert(uColCountB == 0); AppendTplInserts(msaA, uColIndexA, uColCountA, msaB, uColIndexB, uColCountB, uSeqCountA, uSeqCountB, msaCombined, uColIndexCombined); switch (cType) { case 'M': { assert(uPrefixLengthA > 0); assert(uPrefixLengthB > 0); const unsigned uColA = uPrefixLengthA - 1; const unsigned uColB = uPrefixLengthB - 1; assert(uColIndexA == uColA); assert(uColIndexB == uColB); AppendMatch(msaA, uColIndexA, msaB, uColIndexB, uSeqCountA, uSeqCountB, msaCombined, uColIndexCombined); break; } case 'D': { assert(uPrefixLengthA > 0); const unsigned uColA = uPrefixLengthA - 1; assert(uColIndexA == uColA); AppendDelete(msaA, uColIndexA, uSeqCountA, uSeqCountB, msaCombined, uColIndexCombined); break; } case 'I': { assert(uPrefixLengthB > 0); const unsigned uColB = uPrefixLengthB - 1; assert(uColIndexB == uColB); AppendInsert(msaB, uColIndexB, uSeqCountA, uSeqCountB, msaCombined, uColIndexCombined); break; } default: assert(false); } } unsigned uInsertColCountA = uColCountA - uColIndexA; unsigned uInsertColCountB = uColCountB - uColIndexB; // TODO: This code looks like a hangover from HMM estimation -- can we delete it? assert(uInsertColCountA == 0); assert(uInsertColCountB == 0); AppendTplInserts(msaA, uColIndexA, uInsertColCountA, msaB, uColIndexB, uInsertColCountB, uSeqCountA, uSeqCountB, msaCombined, uColIndexCombined); assert(msaCombined.GetColCount() == uEdgeCount); } static const ProfPos PPStart = { false, //m_bAllGaps; { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // m_uSortOrder[21]; { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // m_fcCounts[20]; 1.0, // m_LL; 0.0, // m_LG; 0.0, // m_GL; 0.0, // m_GG; { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }, // m_ALScores 0, // m_uResidueGroup; 1.0, // m_fOcc; 0.0, // m_fcStartOcc; 0.0, // m_fcEndOcc; 0.0, // m_scoreGapOpen; 0.0, // m_scoreGapClose; }; // MM // Ai–1 Ai Out // X X LL LL // X - LG LG // - X GL GL // - - GG GG // // Bj–1 Bj // X X LL LL // X - LG LG // - X GL GL // - - GG GG static void SetGapsMM( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPA = uPrefixLengthA > 0 ? PA[uPrefixLengthA-1] : PPStart; const ProfPos &PPB = uPrefixLengthB > 0 ? PB[uPrefixLengthB-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; PPO.m_LL = wA*PPA.m_LL + wB*PPB.m_LL; PPO.m_LG = wA*PPA.m_LG + wB*PPB.m_LG; PPO.m_GL = wA*PPA.m_GL + wB*PPB.m_GL; PPO.m_GG = wA*PPA.m_GG + wB*PPB.m_GG; } // MD // Ai–1 Ai Out // X X LL LL // X - LG LG // - X GL GL // - - GG GG // // Bj (-) // X - ?L LG // - - ?G GG static void SetGapsMD( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPA = uPrefixLengthA > 0 ? PA[uPrefixLengthA-1] : PPStart; const ProfPos &PPB = uPrefixLengthB > 0 ? PB[uPrefixLengthB-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; PPO.m_LL = wA*PPA.m_LL; PPO.m_LG = wA*PPA.m_LG + wB*(PPB.m_LL + PPB.m_GL); PPO.m_GL = wA*PPA.m_GL; PPO.m_GG = wA*PPA.m_GG + wB*(PPB.m_LG + PPB.m_GG); } // DD // Ai–1 Ai Out // X X LL LL // X - LG LG // - X GL GL // - - GG GG // // (-) (-) // - - ?? GG static void SetGapsDD( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPA = uPrefixLengthA > 0 ? PA[uPrefixLengthA-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; PPO.m_LL = wA*PPA.m_LL; PPO.m_LG = wA*PPA.m_LG; PPO.m_GL = wA*PPA.m_GL; PPO.m_GG = wA*PPA.m_GG + wB; } // MI // Ai (-) Out // X - ?L LG // - - ?G GG // Bj–1 Bj // X X LL LL // X - LG LG // - X GL GL // - - GG GG static void SetGapsMI( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPA = uPrefixLengthA > 0 ? PA[uPrefixLengthA-1] : PPStart; const ProfPos &PPB = uPrefixLengthB > 0 ? PB[uPrefixLengthB-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; PPO.m_LL = wB*PPB.m_LL; PPO.m_LG = wB*PPB.m_LG + wA*(PPA.m_LL + PPA.m_GL); PPO.m_GL = wB*PPB.m_GL; PPO.m_GG = wB*PPB.m_GG + wA*(PPA.m_LG + PPA.m_GG); } // DM // Ai–1 Ai Out // X X LL LL // X - LG LG // - X GL GL // - - GG GG // // (-) Bj // - X ?L GL // - - ?G GG static void SetGapsDM( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPA = uPrefixLengthA > 0 ? PA[uPrefixLengthA-1] : PPStart; const ProfPos &PPB = uPrefixLengthB > 0 ? PB[uPrefixLengthB-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; PPO.m_LL = wA*PPA.m_LL; PPO.m_LG = wA*PPA.m_LG; PPO.m_GL = wA*PPA.m_GL + wB*(PPB.m_LL + PPB.m_GL); PPO.m_GG = wA*PPA.m_GG + wB*(PPB.m_LG + PPB.m_GG); } // IM // (-) Ai Out // - X ?L GL // - - ?G GG // Bj–1 Bj // X X LL LL // X - LG LG // - X GL GL // - - GG GG static void SetGapsIM( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPA = uPrefixLengthA > 0 ? PA[uPrefixLengthA-1] : PPStart; const ProfPos &PPB = uPrefixLengthB > 0 ? PB[uPrefixLengthB-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; PPO.m_LL = wB*PPB.m_LL; PPO.m_LG = wB*PPB.m_LG; PPO.m_GL = wB*PPB.m_GL + wA*(PPA.m_LL + PPA.m_GL); PPO.m_GG = wB*PPB.m_GG + wA*(PPA.m_LG + PPA.m_GG); } // ID // (-) Ai Out // - X ?L GL // - - ?G GG // Bj (-) // X - ?L LG // - - ?G GG static void SetGapsID( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPA = uPrefixLengthA > 0 ? PA[uPrefixLengthA-1] : PPStart; const ProfPos &PPB = uPrefixLengthB > 0 ? PB[uPrefixLengthB-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; PPO.m_LL = 0; PPO.m_LG = wB*PPB.m_GL + wB*PPB.m_LL; PPO.m_GL = wA*PPA.m_GL + wA*PPA.m_LL; PPO.m_GG = wA*(PPA.m_LG + PPA.m_GG) + wB*(PPB.m_LG + PPB.m_GG); } // DI // Ai (-) Out // X - ?L LG // - - ?G GG // (-) Bj // - X ?L GL // - - ?G GG static void SetGapsDI( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPA = uPrefixLengthA > 0 ? PA[uPrefixLengthA-1] : PPStart; const ProfPos &PPB = uPrefixLengthB > 0 ? PB[uPrefixLengthB-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; PPO.m_LL = 0; PPO.m_LG = wA*PPA.m_GL + wA*PPA.m_LL; PPO.m_GL = wB*PPB.m_GL + wB*PPB.m_LL; PPO.m_GG = wA*(PPA.m_LG + PPA.m_GG) + wB*(PPB.m_LG + PPB.m_GG); } // II // (-) (-) Out // - - ?? GG // Bj–1 Bj // X X LL LL // X - LG LG // - X GL GL // - - GG GG static void SetGapsII( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPB = uPrefixLengthB > 0 ? PB[uPrefixLengthB-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; PPO.m_LL = wB*PPB.m_LL; PPO.m_LG = wB*PPB.m_LG; PPO.m_GL = wB*PPB.m_GL; PPO.m_GG = wB*PPB.m_GG + wA; } static void SetFreqs( const ProfPos *PA, unsigned uPrefixLengthA, float wA, const ProfPos *PB, unsigned uPrefixLengthB, float wB, ProfPos *POut, unsigned uColIndexOut) { const ProfPos &PPA = uPrefixLengthA > 0 ? PA[uPrefixLengthA-1] : PPStart; const ProfPos &PPB = uPrefixLengthB > 0 ? PB[uPrefixLengthB-1] : PPStart; ProfPos &PPO = POut[uColIndexOut]; for (unsigned i = 0; i < g_AlphaSize; ++i) PPO.m_fcCounts[i] = wA*PPA.m_fcCounts[i] + wB*PPB.m_fcCounts[i]; } void AlignTwoProfsGivenPath(const PWPath &Path, const ProfPos *PA, unsigned uPrefixLengthA, const ProfPos *PB, unsigned uPrefixLengthB, ProfPos **ptrPOut, unsigned *ptruLengthOut) { float wA = 0.5; float wB = 0.5; #if TRACE Log(""AlignTwoProfsGivenPath wA=%.3g wB=%.3g Path=\n"", wA, wB); Path.LogMe(); #endif assert(BTEq(wA + wB, 1.0)); unsigned uColIndexA = 0; unsigned uColIndexB = 0; unsigned uColIndexOut = 0; const unsigned uEdgeCount = Path.GetEdgeCount(); ProfPos *POut = new ProfPos[uEdgeCount]; char cPrevType = 'M'; for (unsigned uEdgeIndex = 0; uEdgeIndex < uEdgeCount; ++uEdgeIndex) { const PWEdge &Edge = Path.GetEdge(uEdgeIndex); const char cType = Edge.cType; const unsigned uPrefixLengthA = Edge.uPrefixLengthA; const unsigned uPrefixLengthB = Edge.uPrefixLengthB; #if TRACE Log(""\nEdge %u %c%u.%u ColA=%u ColB=%u\n"", uEdgeIndex, Edge.cType, Edge.uPrefixLengthA, Edge.uPrefixLengthB, uColIndexA, uColIndexB); #endif POut[uColIndexOut].m_bAllGaps = false; switch (cType) { case 'M': { assert(uPrefixLengthA > 0); assert(uPrefixLengthB > 0); SetFreqs( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); switch (cPrevType) { case 'M': SetGapsMM( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); break; case 'D': SetGapsDM( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); break; case 'I': SetGapsIM( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); break; default: Quit(""Bad cPrevType""); } ++uColIndexA; ++uColIndexB; ++uColIndexOut; break; } case 'D': { assert(uPrefixLengthA > 0); SetFreqs( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, 0, POut, uColIndexOut); switch (cPrevType) { case 'M': SetGapsMD( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); break; case 'D': SetGapsDD( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); break; case 'I': SetGapsID( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); break; default: Quit(""Bad cPrevType""); } ++uColIndexA; ++uColIndexOut; break; } case 'I': { assert(uPrefixLengthB > 0); SetFreqs( PA, uPrefixLengthA, 0, PB, uPrefixLengthB, wB, POut, uColIndexOut); switch (cPrevType) { case 'M': SetGapsMI( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); break; case 'D': SetGapsDI( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); break; case 'I': SetGapsII( PA, uPrefixLengthA, wA, PB, uPrefixLengthB, wB, POut, uColIndexOut); break; default: Quit(""Bad cPrevType""); } ++uColIndexB; ++uColIndexOut; break; } default: assert(false); } cPrevType = cType; } assert(uColIndexOut == uEdgeCount); ProfScoresFromFreqs(POut, uEdgeCount); ValidateProf(POut, uEdgeCount); *ptrPOut = POut; *ptruLengthOut = uEdgeCount; #if TRACE Log(""AlignTwoProfsGivenPath:\n""); ListProfile(POut, uEdgeCount, 0); #endif } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/makegraph.cpp",".cpp","662","33","#include ""pilercr.h"" #define TRACE 0 void MakeGraph(EdgeList &Edges) { #if TRACE Log(""\n""); Log(""MakeGraph()\n""); Log("" Hit PileA PileB\n""); Log(""===== ===== =====\n""); #endif for (int HitIndex = 0; HitIndex < g_HitCount; ++HitIndex) { unsigned PileIndexA = g_HitIndexToPileIndexA[HitIndex]; unsigned PileIndexB = g_HitIndexToPileIndexB[HitIndex]; EdgeData Edge; Edge.Node1 = PileIndexA; Edge.Node2 = PileIndexB; Edge.Rev = false; Edges.push_back(Edge); #if TRACE Log(""%5u %5u %5u "", HitIndex, PileIndexA, PileIndexB); LogHit(HitIndex); Log(""\n""); #endif } #if TRACE Log(""\n""); #endif } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/accepthit.cpp",".cpp","747","31","#include ""pilercr.h"" #include static bool LocalAcceptHit(const DPHit &Hit) { int Length = GetHitLength(Hit); if (Length < g_DraftMinRepeatLength || Length > g_DraftMaxRepeatLength) return false; //int StartSpace = std::min(Hit.aHi, Hit.bHi); //int EndSpace = std::max(Hit.aLo, Hit.bLo); //int Space = EndSpace - StartSpace + 1; //if (Space < g_DraftMinSpacerLength || Space > g_DraftMaxSpacerLength) // return false; if (GlobalPosToContigIndex(Hit.aLo) != GlobalPosToContigIndex(Hit.bHi)) return false; return true; } bool AcceptHit(const DPHit &Hit) { bool Accepted = LocalAcceptHit(Hit); if (Accepted) ++g_AcceptedHitCount; else ++g_NotAcceptedHitCount; return Accepted; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/saveseqs.cpp",".cpp","1775","77","#include ""pilercr.h"" #include ""sw.h"" static double CmpSeqsFwd(const Seq &s1, const Seq &s2) { unsigned Start1; unsigned Start2; std::string Path; score_t Score = SW(s1, s2, &Start1, &Start2, Path); if (Score <= 0) return 0; return GetFractId(s1, s1, Start1, Start2, Path); } static double CmpSeqsBwd(const Seq &s1, const Seq &s2) { unsigned Start1; unsigned Start2; std::string Path; Seq s1rev; s1rev.Copy(s1); s1rev.RevComp(); score_t Score = SW(s1rev, s2, &Start1, &Start2, Path); if (Score <= 0) return 0; return GetFractId(s1rev, s1, Start1, Start2, Path); } static double CmpSeqs(const Seq &s1, const Seq &s2) { double IdFwd = CmpSeqsFwd(s1, s2); if (IdFwd > 0.899) return IdFwd; return CmpSeqsBwd(s1, s2); } void SaveSeqs(FILE *f, const std::vector AAVec) { bool TrimSeqs = FlagOpt(""trimseqs""); const size_t ArrayCount = AAVec.size(); for (size_t ArrayIndex = 0; ArrayIndex < ArrayCount; ++ArrayIndex) { const ArrayAln &AA = *(AAVec[ArrayIndex]); const Seq &s = AA.ConsSeq; if (TrimSeqs) { bool Discard = false; for (size_t ArrayIndex2 = 0; ArrayIndex2 < ArrayIndex; ++ArrayIndex2) { const ArrayAln &AA2 = *(AAVec[ArrayIndex2]); const Seq &s2 = AA2.ConsSeq; if (CmpSeqs(s, s2) > 0.899) { Discard = true; break; } } if (Discard) continue; } int ArrayLength = GetArrayLength(AA); char *Label; int LocalPos = GlobalToLocal(AA.Pos, &Label); fprintf(f, "">%s[Array%d;Pos=%d]"", Label, AA.Id, LocalPos + 1); unsigned L = s.Length(); for (unsigned i = 0; i < L; ++i) { if (i%60 == 0) fprintf(f, ""\n""); fprintf(f, ""%c"", s[i]); } fprintf(f, ""\n""); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/writegff.cpp",".cpp","3544","114","#include ""pilercr.h"" void WriteGFFRecord(FILE *f, int QueryFrom, int QueryTo, int TargetFrom, int TargetTo, bool Comp, char *Feature, int Score, char *Annot) { if (Comp) { // Another lazy hack: empirically found off-by-one // complemented hits have query pos off-by-one, so // fix by this change. Should figure out what's really // going on. // QueryFrom = SeqLengthQ - Hit.bHi - 1; // QueryTo = SeqLengthQ - Hit.bLo - 1; QueryFrom = SeqLengthQ - QueryTo; QueryTo = SeqLengthQ - QueryFrom; if (QueryFrom >= QueryTo) Quit(""WriteGFFRecord: QueryFrom >= QueryTo (comp)""); } else { if (QueryFrom >= QueryTo) Quit(""WriteGFFRecord: QueryFrom >= QueryTo (not comp)""); } // DPHit coordinates sometimes over/underflow. // This is a lazy hack to work around it, should really figure // out what is going on. if (QueryFrom < 0) QueryFrom = 0; if (QueryTo >= SeqLengthQ) QueryTo = SeqLengthQ - 1; if (TargetFrom < 0) TargetFrom = 0; if (TargetTo >= SeqLengthQ) TargetTo = SeqLengthQ - 1; // Take midpoint of segment -- lazy hack again, endpoints // sometimes under / overflow const int TargetBin = (TargetFrom + TargetTo)/(2*CONTIG_MAP_BIN_SIZE); const int QueryBin = (QueryFrom + QueryTo)/(2*CONTIG_MAP_BIN_SIZE); const int BinCountT = (SeqLengthQ + CONTIG_MAP_BIN_SIZE - 1)/CONTIG_MAP_BIN_SIZE; const int BinCountQ = (SeqLengthQ + CONTIG_MAP_BIN_SIZE - 1)/CONTIG_MAP_BIN_SIZE; if (TargetBin < 0 || TargetBin >= BinCountT) { Warning(""Target bin out of range""); return; } if (QueryBin < 0 || QueryBin >= BinCountQ) { Warning(""Query bin out of range""); return; } if (ContigMapQ == 0) Quit(""ContigMap = 0""); const int TargetContigIndex = ContigMapQ[TargetBin]; const int QueryContigIndex = ContigMapQ[QueryBin]; if (TargetContigIndex < 0 || TargetContigIndex >= ContigCountQ) Quit(""WriteGFFRecord: bad target contig index""); if (QueryContigIndex < 0 || QueryContigIndex >= ContigCountQ) Quit(""WriteGFFRecord: bad query contig index""); const int TargetLength = TargetTo - TargetFrom + 1; const int QueryLength = QueryTo - QueryFrom + 1; if (TargetLength < 0 || QueryLength < 0) Warning(""WriteGFFRecord: Length < 0""); const ContigData &TargetContig = ContigsQ[TargetContigIndex]; const ContigData &QueryContig = ContigsQ[QueryContigIndex]; int TargetContigFrom = TargetFrom - TargetContig.From + 1; int QueryContigFrom = QueryFrom - QueryContig.From + 1; int TargetContigTo = TargetContigFrom + TargetLength - 1; int QueryContigTo = QueryContigFrom + QueryLength - 1; if (TargetContigFrom < 1) TargetContigFrom = 1; if (TargetContigTo > TargetContig.Length) TargetContigTo = TargetContig.Length; if (QueryContigFrom < 1) QueryContigFrom = 1; if (QueryContigTo > QueryContig.Length) QueryContigTo = QueryContig.Length; const char *TargetLabel = TargetContig.Label; const char *QueryLabel = QueryContig.Label; const char Strand = Comp ? '-' : '+'; // GFF Fields are: // [attributes] [comments] // 0 1 2 3 4 5 6 7 8 9 fprintf(f, ""%s\tcrisper\t%s\t%d\t%d\t%d\t%c\t.\tTarget %s %d %d"", QueryLabel, Feature, QueryContigFrom, QueryContigTo, Score, Strand, TargetLabel, TargetContigFrom, TargetContigTo); if (Annot != 0) fprintf(f, ""; %s"", Annot); fprintf(f, ""\n""); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/profile.h",".h","4260","121","#ifndef FastProf2_h #define FastProf2_h #include ""msa.h"" #include ""pwpath.h"" #include // for log function class DiagList; class WeightList; struct ProfPos { bool m_bAllGaps; unsigned m_uSortOrder[21]; FCOUNT m_fcCounts[20]; FCOUNT m_LL; FCOUNT m_LG; FCOUNT m_GL; FCOUNT m_GG; SCORE m_AAScores[20]; unsigned m_uResidueGroup; FCOUNT m_fOcc; FCOUNT m_fcStartOcc; FCOUNT m_fcEndOcc; SCORE m_scoreGapOpen; SCORE m_scoreGapClose; #if DOUBLE_AFFINE SCORE m_scoreGapOpen2; SCORE m_scoreGapClose2; #endif // SCORE m_scoreGapExtend; }; struct ProgNode { ProgNode() { m_Prof = 0; m_EstringL = 0; m_EstringR = 0; } MSA m_MSA; ProfPos *m_Prof; PWPath m_Path; short *m_EstringL; short *m_EstringR; unsigned m_uLength; }; const unsigned RESIDUE_GROUP_MULTIPLE = (unsigned) ~0; ProfPos *ProfileFromMSA(const MSA &a); SCORE TraceBack(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, const SCORE *DPM_, const SCORE *DPD_, const SCORE *DPI_, PWPath &Path); SCORE GlobalAlign(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); SCORE MSAPairSP(const MSA &msa1, const MSA &msa2); void AlignTwoMSAsGivenPath(const PWPath &Path, const MSA &msaA, const MSA &msaB, MSA &msaCombined); void ListProfile(const ProfPos *Prof, unsigned uLength, const MSA *ptrMSA = 0); SCORE ScoreProfPos2(const ProfPos &PPA, const ProfPos &PPB); SCORE FastScorePath2(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, const PWPath &Path); bool IsHydrophilic(const FCOUNT fcCounts[]); int PAM200_Letter(unsigned uLetter1, unsigned uLetter2); SCORE AverageMatchScore(const PWPath &Path, unsigned uEdgeIndex, unsigned uWindowLength); void WindowSmooth(const SCORE Score[], unsigned uCount, unsigned uWindowLength, SCORE SmoothScore[], double dCeil = 9e29); SCORE FastScoreMSA_LA(const MSA &msa, SCORE MatchScore[] = 0); SCORE FastScoreMSA_NS(const MSA &msa, SCORE MatchScore[] = 0); SCORE FastScoreMSA_SP(const MSA &msa, SCORE MatchScore[] = 0); bool RefineMSA(MSA &msa, const Tree &tree); SCORE MSAQScore(const MSA &msa, SCORE MatchScore[] = 0); bool RefineBiParts(MSA &msa, const Tree &tree, bool R); void FindAnchorCols(const MSA &msa, unsigned AnchorCols[], unsigned *ptruAnchorColCount); double PctIdToHeight(double dPctId); double PctIdToHeightKimura(double dPctId); double PctIdToHeightMAFFT(double dPctId); double PctIdToMAFFTDist(double dPctId); bool RefineBlocks(MSA &msa, const Tree &tree); bool RefineSubfams(MSA &msaIn, const Tree &tree, unsigned uIters); void SetMuscleTree(const Tree &tree); void RealignDiffs(const MSA &msaIn, const Tree &Diffs, const unsigned IdToDiffsTreeNodeIndex[], MSA &msaOut); void RealignDiffsE(const MSA &msaIn, const SeqVect &v, const Tree &NewTree, const Tree &OldTree, const unsigned uNewNodeIndexToOldNodeIndex[], MSA &msaOut, ProgNode *OldProgNodes); void RefineTree(MSA &msa, Tree &tree); void RefineTreeE(MSA &msa, const SeqVect &v, Tree &tree, ProgNode *ProgNodes); void SetScoreMatrix(); extern bool IsHydrophobic(const FCOUNT fcCounts[]); void Hydro(ProfPos *Prof, unsigned uLength); // Macros to simulate 2D matrices #define DPL(PLA, PLB) DPL_[(PLB)*uPrefixCountA + (PLA)] #define DPM(PLA, PLB) DPM_[(PLB)*uPrefixCountA + (PLA)] #define DPD(PLA, PLB) DPD_[(PLB)*uPrefixCountA + (PLA)] #define DPE(PLA, PLB) DPE_[(PLB)*uPrefixCountA + (PLA)] #define DPI(PLA, PLB) DPI_[(PLB)*uPrefixCountA + (PLA)] #define DPJ(PLA, PLB) DPJ_[(PLB)*uPrefixCountA + (PLA)] #define DPU(PLA, PLB) DPU_[(PLB)*uPrefixCountA + (PLA)] #define TBM(PLA, PLB) TBM_[(PLB)*uPrefixCountA + (PLA)] #define TBD(PLA, PLB) TBD_[(PLB)*uPrefixCountA + (PLA)] #define TBE(PLA, PLB) TBE_[(PLB)*uPrefixCountA + (PLA)] #define TBI(PLA, PLB) TBI_[(PLB)*uPrefixCountA + (PLA)] #define TBJ(PLA, PLB) TBJ_[(PLB)*uPrefixCountA + (PLA)] SCORE ScoreProfPos2LA(const ProfPos &PPA, const ProfPos &PPB); SCORE ScoreProfPos2NS(const ProfPos &PPA, const ProfPos &PPB); SCORE ScoreProfPos2SP(const ProfPos &PPA, const ProfPos &PPB); SCORE ScoreProfPos2SPN(const ProfPos &PPA, const ProfPos &PPB); #endif // FastProf_h ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/distfunc.h",".h","807","37","#ifndef DistFunc_h #define DistFunc_h class DistFunc { public: DistFunc(); virtual ~DistFunc(); public: virtual void SetCount(unsigned uCount); virtual void SetDist(unsigned uIndex1, unsigned uIndex2, float dDist); void SetName(unsigned uIndex, const char szName[]); void SetId(unsigned uIndex, unsigned uId); const char *GetName(unsigned uIndex) const; unsigned GetId(unsigned uIndex) const; virtual float GetDist(unsigned uIndex1, unsigned uIndex2) const; virtual unsigned GetCount() const; void LogMe() const; protected: unsigned VectorIndex(unsigned uIndex, unsigned uIndex2) const; unsigned VectorLength() const; private: unsigned m_uCount; unsigned m_uCacheCount; float *m_Dists; char **m_Names; unsigned *m_Ids; }; #endif // DistFunc_h ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/seq.h",".h","1945","92","#ifndef Seq_h #define Seq_h #include class TextFile; class MSA; typedef std::vector CharVect; class Seq : public CharVect { public: Seq() { m_ptrName = 0; // Start with moderate size to avoid // thrashing the heap. reserve(200); } ~Seq() { delete[] m_ptrName; } Seq &operator=(const Seq &rhs) { Copy(rhs); return *this; } private: // Not implemented; prevent use of copy c'tor and assignment. Seq(const Seq &); public: void Clear() { clear(); delete[] m_ptrName; m_ptrName = 0; m_uId = uInsane; } const char *GetName() const { return m_ptrName; } unsigned GetId() const { return m_uId; } void SetId(unsigned uId) { m_uId = uId; } bool FromFASTAFile(TextFile &File); void ToFASTAFile(TextFile &File) const; void ExtractUngapped(MSA &msa) const; void FromString(const char *pstrSeq, const char *pstrName); void Copy(const Seq &rhs); void CopyReversed(const Seq &rhs); void StripGaps(); void StripGapsAndWhitespace(); void ToUpper(); void SetName(const char *ptrName); unsigned GetLetter(unsigned uIndex) const; unsigned Length() const { return (unsigned) size(); } bool Eq(const Seq &s) const; bool EqIgnoreCase(const Seq &s) const; bool EqIgnoreCaseAndGaps(const Seq &s) const; bool HasGap() const; unsigned GetUngappedLength() const; void LogMe() const; void LogMeSeqOnly() const; char GetChar(unsigned uIndex) const { return operator[](uIndex); } void SetChar(unsigned uIndex, char c) { operator[](uIndex) = c; } void AppendChar(char c) { push_back(c); } void FixAlpha(); void ToString(char String[], unsigned Bytes) const; void RevComp(); #ifndef _WIN32 reference at(size_type i) { return operator[](i); } const_reference at(size_type i) const { return operator[](i); } #endif private: char *m_ptrName; unsigned m_uId; }; #endif // Seq.h ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/seqvect.cpp",".cpp","6949","329","#include ""multaln.h"" #include const size_t MAX_FASTA_LINE = 16000; const int BUFFER_BYTES = 16*1024; const int CR = '\r'; const int NL = '\n'; #define ADD(c) \ { \ if (Pos >= BufferLength) \ { \ const int NewBufferLength = BufferLength + BUFFER_BYTES; \ char *NewBuffer = new char[NewBufferLength]; \ memcpy(NewBuffer, Buffer, BufferLength); \ delete[] Buffer; \ Buffer = NewBuffer; \ BufferLength = NewBufferLength; \ } \ Buffer[Pos++] = c; \ } // Get next sequence from file. static char *GetFastaSeq(FILE *f, unsigned *ptrSeqLength, char **ptrLabel, bool DeleteGaps) { unsigned BufferLength = 0; unsigned Pos = 0; char *Buffer = 0; int c = fgetc(f); if (EOF == c) return 0; if ('>' != c) Quit(""Invalid file format, expected '>' to start FASTA label""); for (;;) { int c = fgetc(f); if (EOF == c) Quit(""End-of-file or input error in FASTA label""); // Ignore CR (discard, do not include in label) if (CR == c) continue; // NL terminates label if (NL == c) break; // All other characters added to label ADD(c) } // Nul-terminate label ADD(0) *ptrLabel = Buffer; BufferLength = 0; Pos = 0; Buffer = 0; int PreviousChar = NL; for (;;) { int c = fgetc(f); if (EOF == c) { if (feof(f)) break; else if (ferror(f)) Quit(""Error reading FASTA file, ferror=TRUE feof=FALSE errno=%d %s"", errno, strerror(errno)); else Quit(""Error reading FASTA file, fgetc=EOF feof=FALSE ferror=FALSE errno=%d %s"", errno, strerror(errno)); } if ('>' == c) { if (NL == PreviousChar) { ungetc(c, f); break; } else Quit(""Unexpected '>' in FASTA sequence data""); } else if (isspace(c)) ; else if (IsGapChar(c)) { if (!DeleteGaps) ADD(c) } else if (isalpha(c)) { c = toupper(c); ADD(c) } else if (isprint(c)) { Warning(""Invalid character '%c' in FASTA sequence data, ignored"", c); continue; } else { Warning(""Invalid byte hex %02x in FASTA sequence data, ignored"", (unsigned char) c); continue; } PreviousChar = c; } if (0 == Pos) return GetFastaSeq(f, ptrSeqLength, ptrLabel, DeleteGaps); *ptrSeqLength = Pos; return Buffer; } SeqVect::~SeqVect() { Clear(); } void SeqVect::Clear() { } void SeqVect::PadToMSA(MSA &msa) { unsigned uSeqCount = Length(); if (0 == uSeqCount) { msa.Clear(); return; } unsigned uLongestSeqLength = 0; for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { Seq *ptrSeq = at(uSeqIndex); unsigned uColCount = ptrSeq->Length(); if (uColCount > uLongestSeqLength) uLongestSeqLength = uColCount; } msa.SetSize(uSeqCount, uLongestSeqLength); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { Seq *ptrSeq = at(uSeqIndex); msa.SetSeqName(uSeqIndex, ptrSeq->GetName()); unsigned uColCount = ptrSeq->Length(); unsigned uColIndex; for (uColIndex = 0; uColIndex < uColCount; ++uColIndex) { char c = ptrSeq->at(uColIndex); msa.SetChar(uSeqIndex, uColIndex, c); } while (uColIndex < uLongestSeqLength) msa.SetChar(uSeqIndex, uColIndex++, '.'); } } void SeqVect::Copy(const SeqVect &rhs) { clear(); unsigned uSeqCount = rhs.Length(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { Seq *ptrSeq = rhs.at(uSeqIndex); Seq *ptrSeqCopy = new Seq; ptrSeqCopy->Copy(*ptrSeq); push_back(ptrSeqCopy); } } void SeqVect::StripGaps() { unsigned uSeqCount = Length(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { Seq *ptrSeq = at(uSeqIndex); ptrSeq->StripGaps(); } } void SeqVect::StripGapsAndWhitespace() { unsigned uSeqCount = Length(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { Seq *ptrSeq = at(uSeqIndex); ptrSeq->StripGapsAndWhitespace(); } } void SeqVect::ToUpper() { unsigned uSeqCount = Length(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { Seq *ptrSeq = at(uSeqIndex); ptrSeq->ToUpper(); } } bool SeqVect::FindName(const char *ptrName, unsigned *ptruIndex) const { unsigned uSeqCount = Length(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { const Seq *ptrSeq = at(uSeqIndex); if (0 == stricmp(ptrSeq->GetName(), ptrName)) { *ptruIndex = uSeqIndex; return true; } } return false; } void SeqVect::AppendSeq(const Seq &s) { Seq *ptrSeqCopy = new Seq; ptrSeqCopy->Copy(s); push_back(ptrSeqCopy); } void SeqVect::LogMe() const { unsigned uSeqCount = Length(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { const Seq *ptrSeq = at(uSeqIndex); ptrSeq->LogMe(); } } const char *SeqVect::GetSeqName(unsigned uSeqIndex) const { assert(uSeqIndex < size()); const Seq *ptrSeq = at(uSeqIndex); return ptrSeq->GetName(); } unsigned SeqVect::GetSeqId(unsigned uSeqIndex) const { assert(uSeqIndex < size()); const Seq *ptrSeq = at(uSeqIndex); return ptrSeq->GetId(); } unsigned SeqVect::GetSeqIdFromName(const char *Name) const { const unsigned uSeqCount = GetSeqCount(); for (unsigned i = 0; i < uSeqCount; ++i) { if (!strcmp(Name, GetSeqName(i))) return GetSeqId(i); } Quit(""SeqVect::GetSeqIdFromName(%s): not found"", Name); return 0; } Seq &SeqVect::GetSeqById(unsigned uId) { const unsigned uSeqCount = GetSeqCount(); for (unsigned i = 0; i < uSeqCount; ++i) { if (GetSeqId(i) == uId) return GetSeq(i); } Quit(""SeqVect::GetSeqIdByUd(%d): not found"", uId); return (Seq &) *((Seq *) 0); } unsigned SeqVect::GetSeqLength(unsigned uSeqIndex) const { assert(uSeqIndex < size()); const Seq *ptrSeq = at(uSeqIndex); return ptrSeq->Length(); } Seq &SeqVect::GetSeq(unsigned uSeqIndex) { assert(uSeqIndex < size()); return *at(uSeqIndex); } const Seq &SeqVect::GetSeq(unsigned uSeqIndex) const { assert(uSeqIndex < size()); return *at(uSeqIndex); } void SeqVect::SetSeqId(unsigned uSeqIndex, unsigned uId) { assert(uSeqIndex < size()); Seq *ptrSeq = at(uSeqIndex); return ptrSeq->SetId(uId); } void SeqVect::FromFASTAFile(FILE *f) { Clear(); for (;;) { char *Label; unsigned uLength; char *SeqData = GetFastaSeq(f, &uLength, &Label, true); if (0 == SeqData) return; Seq *ptrSeq = new Seq; for (unsigned i = 0; i < uLength; ++i) { char c = SeqData[i]; ptrSeq->push_back(c); } ptrSeq->SetName(Label); push_back(ptrSeq); delete[] SeqData; delete[] Label; } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/outlocalaln.cpp",".cpp","790","53","#include ""pilercr.h"" void OutLocalAln(const char *A, unsigned LA, const char *B, unsigned LB, unsigned StartA, unsigned StartB, const char *Path_) { Log(""A=%s\n"", A); Log(""B=%s\n"", B); Log(""Path=%s\n"", Path_); unsigned i = StartA; const char *Path = Path_; while (char c = *Path++) { switch (c) { case 'M': case 'D': assert(i < LA); Log(""%c"", A[i++]); break; case 'I': Log(""-""); break; default: assert(false); } } Log(""\n""); unsigned j = StartB; Path = Path_; while (char c = *Path++) { switch (c) { case 'M': case 'I': assert(j < LB); Log(""%c"", B[j++]); break; case 'D': Log(""-""); break; default: assert(false); } } Log(""\n""); Log(""\n""); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/seq.cpp",".cpp","5809","300","#include ""multaln.h"" const size_t MAX_FASTA_LINE = 16000; static char GetWildcardChar() { return 'N'; } void InvalidLetterWarning(char c, char w) { if (isprint(c)) Warning(""Invalid char '%c' in sequence, replaced by '%c'"", c, w); else Warning(""Invalid char 0x02x in sequence, replaced by '%c'"", c, w); } void Seq::SetName(const char *ptrName) { delete[] m_ptrName; size_t n = strlen(ptrName) + 1; m_ptrName = new char[n]; strcpy(m_ptrName, ptrName); } void Seq::ExtractUngapped(MSA &msa) const { msa.Clear(); unsigned uColCount = Length(); msa.SetSize(1, 1); unsigned uUngappedPos = 0; for (unsigned n = 0; n < uColCount; ++n) { char c = at(n); if (!IsGapChar(c)) msa.SetChar(0, uUngappedPos++, c); } msa.SetSeqName(0, m_ptrName); } void Seq::Copy(const Seq &rhs) { clear(); const unsigned uLength = rhs.Length(); for (unsigned uColIndex = 0; uColIndex < uLength; ++uColIndex) push_back(rhs.at(uColIndex)); const char *ptrName = rhs.GetName(); if (ptrName == 0) Quit(""Seq::Copy: Name=NULL""); size_t n = strlen(ptrName) + 1; m_ptrName = new char[n]; strcpy(m_ptrName, ptrName); SetId(rhs.GetId()); } void Seq::CopyReversed(const Seq &rhs) { clear(); const unsigned uLength = rhs.Length(); const unsigned uBase = rhs.Length() - 1; for (unsigned uColIndex = 0; uColIndex < uLength; ++uColIndex) push_back(rhs.at(uBase - uColIndex)); const char *ptrName = rhs.GetName(); size_t n = strlen(ptrName) + 1; m_ptrName = new char[n]; strcpy(m_ptrName, ptrName); } void Seq::StripGaps() { for (CharVect::iterator p = begin(); p != end(); ) { char c = *p; if (IsGapChar(c)) erase(p); else ++p; } } void Seq::StripGapsAndWhitespace() { for (CharVect::iterator p = begin(); p != end(); ) { char c = *p; if (isspace(c) || IsGapChar(c)) erase(p); else ++p; } } void Seq::ToUpper() { for (CharVect::iterator p = begin(); p != end(); ++p) { char c = *p; if (islower(c)) *p = toupper(c); } } unsigned Seq::GetLetter(unsigned uIndex) const { assert(uIndex < Length()); char c = operator[](uIndex); return CharToLetter(c); } bool Seq::EqIgnoreCase(const Seq &s) const { const unsigned n = Length(); if (n != s.Length()) return false; for (unsigned i = 0; i < n; ++i) { const char c1 = at(i); const char c2 = s.at(i); if (IsGapChar(c1)) { if (!IsGapChar(c2)) return false; } else { if (toupper(c1) != toupper(c2)) return false; } } return true; } bool Seq::Eq(const Seq &s) const { const unsigned n = Length(); if (n != s.Length()) return false; for (unsigned i = 0; i < n; ++i) { const char c1 = at(i); const char c2 = s.at(i); if (c1 != c2) return false; } return true; } bool Seq::EqIgnoreCaseAndGaps(const Seq &s) const { const unsigned uThisLength = Length(); const unsigned uOtherLength = s.Length(); unsigned uThisPos = 0; unsigned uOtherPos = 0; int cThis; int cOther; for (;;) { if (uThisPos == uThisLength && uOtherPos == uOtherLength) break; // Set cThis to next non-gap character in this string // or -1 if end-of-string. for (;;) { if (uThisPos == uThisLength) { cThis = -1; break; } else { cThis = at(uThisPos); ++uThisPos; if (!IsGapChar(cThis)) { cThis = toupper(cThis); break; } } } // Set cOther to next non-gap character in s // or -1 if end-of-string. for (;;) { if (uOtherPos == uOtherLength) { cOther = -1; break; } else { cOther = s.at(uOtherPos); ++uOtherPos; if (!IsGapChar(cOther)) { cOther = toupper(cOther); break; } } } // Compare characters are corresponding ungapped position if (cThis != cOther) return false; } return true; } unsigned Seq::GetUngappedLength() const { unsigned uUngappedLength = 0; for (CharVect::const_iterator p = begin(); p != end(); ++p) { char c = *p; if (!IsGapChar(c)) ++uUngappedLength; } return uUngappedLength; } void Seq::LogMe() const { Log("">%s\n"", m_ptrName); const unsigned n = Length(); for (unsigned i = 0; i < n; ++i) Log(""%c"", at(i)); Log(""\n""); } void Seq::LogMeSeqOnly() const { const unsigned n = Length(); for (unsigned i = 0; i < n; ++i) Log(""%c"", at(i)); } void Seq::FromString(const char *pstrSeq, const char *pstrName) { clear(); const unsigned uLength = (unsigned) strlen(pstrSeq); for (unsigned uColIndex = 0; uColIndex < uLength; ++uColIndex) push_back(pstrSeq[uColIndex]); size_t n = strlen(pstrName) + 1; m_ptrName = new char[n]; strcpy(m_ptrName, pstrName); } bool Seq::HasGap() const { for (CharVect::const_iterator p = begin(); p != end(); ++p) { char c = *p; if (IsGapChar(c)) return true; } return false; } void Seq::FixAlpha() { for (CharVect::iterator p = begin(); p != end(); ++p) { char c = *p; if (!IsResidueChar(c)) { char w = GetWildcardChar(); InvalidLetterWarning(c, w); *p = w; } } } void Seq::ToString(char String[], unsigned Bytes) const { const unsigned N = (unsigned) size(); if (Bytes <= N) Quit(""Seq::ToString, buffer too small""); for (unsigned i = 0; i < N; ++i) String[i] = GetChar(i); String[N] = 0; } void Seq::RevComp() { extern unsigned char CompMap[256]; iterator s = begin(); iterator t = end() - 1; while (s < t) { unsigned char c = (unsigned char) *s; *s++ = CompMap[*t]; *t-- = CompMap[c]; } if (s == t) *s = CompMap[*s]; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/fixbounds.cpp",".cpp","12348","498","#include ""pilercr.h"" #define VALIDATE_ALL 1 #if VALIDATE_ALL #define ValidateAA_All ValidateAA #else #define ValidateAA_All /* empty */ #endif static char LeftCol(ArrayAln &AA, size_t RepeatIndex) { std::string &LeftFlank = AA.LeftFlanks[RepeatIndex]; size_t Length = LeftFlank.size(); if (Length == 0) return 0; return LeftFlank[Length-1]; } static bool LeftColConserved(ArrayAln &AA) { const size_t RepeatCount = AA.LeftFlanks.size(); assert(RepeatCount == AA.Repeats.size()); assert(RepeatCount == AA.Spacers.size()); char c0 = LeftCol(AA, 0); if (c0 == 0 || c0 == '-') return false; for (size_t RepeatIndex = 1; RepeatIndex < RepeatCount; ++RepeatIndex) { char c = LeftCol(AA, RepeatIndex); if (c != c0) return false; } return true; } static char RightCol(ArrayAln &AA, size_t RepeatIndex) { std::string &Spacer = AA.Spacers[RepeatIndex]; size_t Length = Spacer.size(); if (Length == 0) return 0; return Spacer[0]; } static bool RightColConserved(ArrayAln &AA) { const size_t RepeatCount = AA.Spacers.size(); assert(RepeatCount == AA.Repeats.size()); assert(RepeatCount == AA.Spacers.size()); char c0 = RightCol(AA, 0); if (c0 == 0) return false; for (size_t RepeatIndex = 1; RepeatIndex < RepeatCount; ++RepeatIndex) { char c = RightCol(AA, RepeatIndex); if (c != c0) return false; } return true; } static bool FirstColConserved(const ArrayAln &AA) { const int *Counts = GetCountsAA(AA, 0); int MaxCount = 0; for (int i = 0; i < 4; ++i) if (Counts[i] > MaxCount) MaxCount = Counts[i]; const size_t RepeatCount = AA.LeftFlanks.size(); double Cons = (double) MaxCount / (double) RepeatCount; return RepeatCount - MaxCount <= 1 || Cons >= g_DraftMinColCons; } static bool LastColConserved(const ArrayAln &AA) { int RepeatLength = (int) AA.Repeats[0].size(); const int *Counts = GetCountsAA(AA, RepeatLength - 1); int MaxCount = 0; for (int i = 0; i < 4; ++i) if (Counts[i] > MaxCount) MaxCount = Counts[i]; const size_t RepeatCount = AA.LeftFlanks.size(); double Cons = (double) MaxCount / (double) RepeatCount; return RepeatCount - MaxCount <= 1 || Cons >= g_DraftMinColCons; } static void MoveLeftColToRepeat(ArrayAln &AA) { --(AA.Pos); const size_t RepeatCount = AA.LeftFlanks.size(); assert(RepeatCount == AA.Repeats.size()); assert(RepeatCount == AA.Spacers.size()); if (RepeatCount == 0) return; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { std::string &LeftFlank = AA.LeftFlanks[RepeatIndex]; std::string &Repeat = AA.Repeats[RepeatIndex]; std::string &Spacer = AA.Spacers[RepeatIndex]; size_t LeftFlankLength = LeftFlank.size(); size_t SpacerLength = Spacer.size(); assert(LeftFlankLength > 0); char c = LeftFlank[LeftFlankLength-1]; if (c == ' ') c = '-'; Repeat = c + Repeat; if (RepeatIndex != RepeatCount - 1) Spacer = Spacer.substr(0, SpacerLength-1); if (RepeatIndex > 0) { std::string &PrevSpacer = AA.Spacers[RepeatIndex-1]; size_t PrevSpacerLength = PrevSpacer.size(); if (PrevSpacerLength >= (size_t) g_FlankSize) { size_t StartPos = PrevSpacerLength - g_FlankSize; LeftFlank = PrevSpacer.substr(StartPos, g_FlankSize); } else { LeftFlank.clear(); size_t BlankCount = g_FlankSize - PrevSpacerLength; for (size_t i = 0; i < BlankCount; ++i) LeftFlank += ' '; LeftFlank += PrevSpacer; } } else { char *Label; int LocalPos = GlobalToLocal(AA.Pos, &Label); char c = ' '; if (LocalPos >= g_FlankSize) c = g_SeqQ[AA.Pos - g_FlankSize]; LeftFlank = c + LeftFlank.substr(0, g_FlankSize-1); } } Log(""MoveLeftColToRepeat\n""); } // Move left-most column in repeat matrix to left flank static void MoveRepeatToLeftCol(ArrayAln &AA) { if (AA.Repeats[0][0] != '-') ++(AA.Pos); const size_t RepeatCount = AA.LeftFlanks.size(); assert(RepeatCount == AA.Repeats.size()); assert(RepeatCount == AA.Spacers.size()); if (RepeatCount == 0) return; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { std::string &LeftFlank = AA.LeftFlanks[RepeatIndex]; std::string &Repeat = AA.Repeats[RepeatIndex]; size_t RepeatLength = Repeat.size(); size_t LeftFlankLength = LeftFlank.size(); char c = Repeat[0]; Repeat = Repeat.substr(1, RepeatLength - 1); if (c != '-') { LeftFlank = LeftFlank.substr(1, LeftFlankLength - 1); LeftFlank += c; } if (RepeatIndex > 0 && c != '-') { std::string &PrevSpacer = AA.Spacers[RepeatIndex - 1]; PrevSpacer += c; } assert(Repeat.size() == RepeatLength - 1); assert(LeftFlank.size() == LeftFlankLength); } Log(""MoveRepeatToLeftCol\n""); } // Move right-most column in repeat matrix to spacer static void MoveRepeatToRightCol(ArrayAln &AA) { const size_t RepeatCount = AA.LeftFlanks.size(); assert(RepeatCount == AA.Repeats.size()); assert(RepeatCount == AA.Spacers.size()); if (RepeatCount == 0) return; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { std::string &Repeat = AA.Repeats[RepeatIndex]; std::string &Spacer = AA.Spacers[RepeatIndex]; size_t RepeatLength = Repeat.size(); char c = Repeat[RepeatLength - 1]; Repeat = Repeat.substr(0, RepeatLength - 1); std::string NewSpacer; if (c != '-') NewSpacer = c; NewSpacer += Spacer; Spacer = NewSpacer; } Log(""MoveRepeatToRightCol\n""); } static void MoveRightColToRepeat(ArrayAln &AA) { const size_t RepeatCount = AA.LeftFlanks.size(); assert(RepeatCount == AA.Repeats.size()); assert(RepeatCount == AA.Spacers.size()); if (RepeatCount == 0) return; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { std::string &Spacer = AA.Spacers[RepeatIndex]; std::string &Repeat = AA.Repeats[RepeatIndex]; size_t SpacerLength = Spacer.size(); size_t RepeatLength = Repeat.size(); assert(SpacerLength > 0); char c = Spacer[0]; std::string NewRepeat; NewRepeat += AA.Repeats[RepeatIndex]; NewRepeat += c; Repeat = NewRepeat; Spacer = Spacer.substr(1, SpacerLength-1); assert(Spacer.size() == SpacerLength - 1); assert(Repeat.size() == RepeatLength + 1); } Log(""MoveRightColToRepeat\n""); } static void FixLeftTerminalGap(ArrayAln &AA, size_t RepeatIndex) { std::string &Repeat = AA.Repeats[RepeatIndex]; const size_t RepeatLength = Repeat.size(); if (RepeatLength == 0) return; size_t GapLength = 0; for (size_t i = 0; i < RepeatLength && Repeat[i] == '-'; ++i) ++GapLength; if (GapLength == 0) return; if (GapLength > 3) return; if (RepeatIndex == 0) return; std::string &PrevSpacer = AA.Spacers[RepeatIndex - 1]; size_t PrevSpacerLength = PrevSpacer.size(); if (PrevSpacerLength < (size_t) g_FlankSize) return; if (PrevSpacerLength < GapLength) return; if (PrevSpacerLength - GapLength < (size_t) g_FlankSize) return; const std::string &LeftFlank = AA.LeftFlanks[RepeatIndex]; size_t LeftFlankLength = LeftFlank.size(); if (LeftFlankLength <= GapLength) return; std::string NewRepeat; NewRepeat += LeftFlank.substr(LeftFlankLength - GapLength, GapLength); NewRepeat += Repeat.substr(GapLength, RepeatLength - GapLength); AA.Repeats[RepeatIndex] = NewRepeat; PrevSpacer = PrevSpacer.substr(0, PrevSpacerLength - GapLength); PrevSpacerLength = PrevSpacer.size(); assert(PrevSpacerLength >= (size_t) g_FlankSize); std::string TmpStr = PrevSpacer.substr(PrevSpacerLength - g_FlankSize, g_FlankSize); AA.LeftFlanks[RepeatIndex] = TmpStr; Log(""FixLeftTerminalGap %d\n"", (int) RepeatIndex); } static void FixRightTerminalGap(ArrayAln &AA, size_t RepeatIndex) { std::string &Repeat = AA.Repeats[RepeatIndex]; char *Label; int LocalPos = GlobalToLocal(AA.Pos, &Label); const size_t RepeatLength = Repeat.size(); if (RepeatLength == 0) return; size_t GapLength = 0; for (int i = (int) RepeatLength - 1; i >= 0 && Repeat[i] == '-'; --i) { ++GapLength; } if (GapLength == 0) return; if (GapLength > 2) return; std::string &Spacer = AA.Spacers[RepeatIndex]; size_t SpacerLength = Spacer.size(); const size_t RepeatCount = AA.Repeats.size(); if (SpacerLength < GapLength) { if (RepeatIndex != RepeatCount - 1) Quit(""SpacerLength < GapLength""); return; } Repeat = Repeat.substr(0, RepeatLength - GapLength); Repeat += Spacer.substr(0, GapLength); if (SpacerLength >= GapLength) Spacer = Spacer.substr(GapLength, SpacerLength - GapLength); else Spacer.clear(); Log(""FixRightTerminalGap %d\n"", (int) RepeatIndex); } static int GapCount(const std::string &s) { int Sum = 0; for (size_t i = 0; i < s.size(); ++i) if (s[i] == '-') ++Sum; return Sum; } static int AvgGapCount(const ArrayAln &AA) { const size_t RepeatCount = AA.Repeats.size(); int Sum = 0; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { const std::string &Repeat = AA.Repeats[RepeatIndex]; Sum += GapCount(Repeat); } return (int) (((double) Sum / (double) RepeatCount) + 0.5); } static bool HasInitialPartialRepeat(const ArrayAln &AA) { int Avg = AvgGapCount(AA); int Count = GapCount(AA.Repeats[0]); return Count >= 3 && Count > Avg*2; } static bool HasFinalPartialRepeat(const ArrayAln &AA) { int Avg = AvgGapCount(AA); size_t RepeatCount = AA.Repeats.size(); int Count = GapCount(AA.Repeats[RepeatCount-1]); return Count >= 3 && Count > Avg*2; } static void DeleteInitialPartialRepeat(ArrayAln &AA) { const std::string &FirstRepeat = AA.Repeats[0]; const std::string &FirstSpacer = AA.Spacers[0]; int Offset = 0; for (size_t i = 0; i < FirstRepeat.size(); ++i) if (FirstRepeat[i] != '-') ++Offset; Offset += (int) FirstSpacer.size(); AA.Pos += Offset; const size_t RepeatCount = AA.Repeats.size(); for (int i = 0; i < (int) RepeatCount - 1; ++i) { AA.LeftFlanks[i] = AA.LeftFlanks[i+1]; AA.Repeats[i] = AA.Repeats[i+1]; AA.Spacers[i] = AA.Spacers[i+1]; } AA.LeftFlanks.resize(RepeatCount-1); AA.Repeats.resize(RepeatCount-1); AA.Spacers.resize(RepeatCount-1); Log(""DeleteInitialPartialRepeat\n""); } static void DeleteFinalPartialRepeat(ArrayAln &AA) { const std::string &LastRepeat = AA.Repeats[0]; const std::string &LastSpacer = AA.Spacers[0]; size_t RepeatCount = AA.Repeats.size(); AA.LeftFlanks.resize(RepeatCount-1); AA.Repeats.resize(RepeatCount-1); AA.Spacers.resize(RepeatCount-1); Log(""DeleteFinalPartialRepeat\n""); } void FixBounds(ArrayAln &AA) { ValidateAA(AA); if (HasInitialPartialRepeat(AA)) { if (AA.Repeats.size() <= (size_t) g_DraftMinArraySize) return; DeleteInitialPartialRepeat(AA); } if (HasFinalPartialRepeat(AA)) { if (AA.Repeats.size() <= (size_t) g_DraftMinArraySize) return; DeleteFinalPartialRepeat(AA); } size_t RepeatCount = AA.Repeats.size(); assert(RepeatCount == AA.LeftFlanks.size()); assert(RepeatCount == AA.Spacers.size()); for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { ValidateAA_All(AA); FixLeftTerminalGap(AA, RepeatIndex); ValidateAA_All(AA); FixRightTerminalGap(AA, RepeatIndex); ValidateAA_All(AA); } while (LeftColConserved(AA)) { ValidateAA_All(AA); MoveLeftColToRepeat(AA); ValidateAA_All(AA); } while (RightColConserved(AA)) { ValidateAA_All(AA); MoveRightColToRepeat(AA); ValidateAA_All(AA); } while (!FirstColConserved(AA)) { ValidateAA_All(AA); MoveRepeatToLeftCol(AA); ValidateAA_All(AA); } while (!LastColConserved(AA)) { ValidateAA_All(AA); MoveRepeatToRightCol(AA); ValidateAA_All(AA); } for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { ValidateAA_All(AA); FixLeftTerminalGap(AA, RepeatIndex); ValidateAA_All(AA); FixRightTerminalGap(AA, RepeatIndex); ValidateAA_All(AA); } ValidateAA(AA); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/getgdtree.cpp",".cpp","186","13","#include ""multaln.h"" void GetGuideTree(const SeqVect &Seqs, Tree &GuideTree) { DistFunc DF; KmerDist(Seqs, DF); DistCalcDF DC; DC.Init(DF); UPGMA(DC, GuideTree); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/outdetail.cpp",".cpp","5809","251","#include ""pilercr.h"" #include ""sw.h"" static void OutputDetailHeader(const ArrayData &AD, unsigned ColCount) { char *Label; GlobalToLocal(AD.Lo, &Label); Out(""\n\n""); Out(""Array %d\n"", AD.Id); if (g_ShowHits) { Out(""Root: ""); LogHit(AD.PileIndexes.front()); Out(""\n""); } Out("">%s\n"", Label); Out(""\n""); Out("" Pos Repeat %%id Spacer Left flank Repeat""); int Blanks = (int) ColCount - 6; for (int i = 0; i < Blanks; ++i) Out("" ""); Out("" Spacer\n""); Out(""========== ====== ====== ====== ========== ""); for (unsigned i = 0; i < ColCount; ++i) Out(""=""); Out("" ======\n""); } static void OutputDetailFooter(const ArrayData &AD, unsigned ColCount) { Out(""========== ====== ====== ====== ========== ""); for (unsigned i = 0; i < ColCount; ++i) Out(""=""); Out(""\n""); } int PathALength(const char *Path) { int Length = 0; while (char c = *Path++) if (c == 'M' || c == 'D') ++Length; return Length; } double GetPctId(const char *A, const char *B, const char *Path) { int APos = 0; int BPos = 0; int Same = 0; int LA = 0; int LB = 0; while (char c = *Path++) { switch (c) { case 'M': if (toupper(A[APos++]) == toupper(B[BPos++])) ++Same; ++LA; ++LB; break; case 'D': ++APos; ++LA; break; case 'I': ++BPos; ++LB; break; } } double MaxLen = std::max(LA, LB); if (MaxLen == 0) return 0; return (double) Same * 100.0 / MaxLen; } void OutputArrayDetail(ArrayData &AD) { const IntVec &PileIndexes = AD.PileIndexes; std::vector Rows; size_t RowCount = PileIndexes.size(); Rows.reserve(RowCount); const unsigned ConsSeqLen = AD.ConsSeq.Length(); char *ConsSeqStr = all(char, ConsSeqLen+1); AD.ConsSeq.ToString(ConsSeqStr, ConsSeqLen+1); SeqVect HitSeqs; int RowIndex = 0; for_CIntVec(PileIndexes, p) { RowData &Row = Rows[RowIndex]; int PileIndex = *p; assert(PileIndex >= 0 && PileIndex < g_PileCount); Seq *PileSeq = new Seq; int Lo; int Hi; PileToSeq(g_Piles, PileIndex, *PileSeq, &Lo, &Hi); unsigned PileSeqLen = PileSeq->Length(); char *PileSeqStr = all(char, PileSeqLen+1); PileSeq->ToString(PileSeqStr, PileSeqLen+1); std::string Path; unsigned PileOffset; unsigned ConsOffset; SWSimple(PileSeqStr, PileSeqLen, ConsSeqStr, ConsSeqLen, &PileOffset, &ConsOffset, Path); Row.PctId = GetPctId(PileSeqStr+PileOffset, ConsSeqStr+ConsOffset, Path.c_str()); const PileData &Pile = g_Piles[PileIndex]; Row.RepeatLo = Lo + PileOffset; if (RowIndex == 0) AD.Lo = Row.RepeatLo; int RepeatLength = PathALength(Path.c_str()); Row.RepeatLength = RepeatLength; Seq *HitSeq = new Seq; const int ToPos = PileOffset + RepeatLength - 1; for (int Pos = PileOffset; Pos <= ToPos; ++Pos) HitSeq->push_back(PileSeqStr[Pos]); HitSeq->SetName(""hit""); HitSeq->SetId(0); HitSeqs.push_back(HitSeq); ++RowIndex; } freemem(ConsSeqStr); ConsSeqStr = 0; Seq *ConsSeq = new Seq; ConsSeq->Copy(AD.ConsSeq); HitSeqs.push_back(ConsSeq); MSA Aln; MultipleAlign(HitSeqs, Aln); const unsigned ColCount = Aln.GetColCount(); OutputDetailHeader(AD, ColCount); int SumSpacerLengths = 0; for (size_t RowIndex = 0; RowIndex < RowCount; ++RowIndex) { const RowData &Row = Rows[RowIndex]; char *Label; int LocalRepeatLo = GlobalToLocal(Row.RepeatLo, &Label); Out(""%10d %6d %6.1f%%"", LocalRepeatLo + 1, Row.RepeatLength, Row.PctId); int NextLo = -1; int Hi = -1; int SpacerLength = -1; // Spacer if (RowIndex + 1 == RowCount) Out("" ""); else { NextLo = Rows[RowIndex+1].RepeatLo; Hi = Row.RepeatLo + Row.RepeatLength - 1; SpacerLength = NextLo - Hi; Out("" %5d "", SpacerLength); SumSpacerLengths += SpacerLength; } // Left flank const ContigData &Contig = GlobalPosToContig(Row.RepeatLo); int ContigFrom = Contig.From; int ContigTo = ContigFrom + Contig.Length - 1; int LeftFlankStartPos = Row.RepeatLo - g_FlankSize; int LeftFlankBlanks = 0; if (LeftFlankStartPos < ContigFrom) { LeftFlankStartPos = ContigFrom; LeftFlankBlanks = g_FlankSize - (Row.RepeatLo - ContigFrom); } for (int i = 0; i < LeftFlankBlanks; ++i) Out("" ""); for (int Pos = LeftFlankStartPos; Pos < Row.RepeatLo; ++Pos) Out(""%c"", g_SeqQ[Pos]); Out("" ""); // Repeat for (unsigned Col = 0; Col < ColCount; ++Col) Out(""%c"", Aln.GetChar((unsigned) RowIndex, Col)); Out("" ""); // Spacer if (RowIndex + 1 == RowCount) { int RightFlankPos = Row.RepeatLo + Row.RepeatLength; int ToPos = RightFlankPos + 9; if (ToPos >= ContigTo) ToPos = ContigTo; for (int Pos = RightFlankPos; Pos <= ToPos; ++Pos) Out(""%c"", g_SeqQ[Pos]); } else { for (int Pos = Hi + 1; Pos < NextLo; ++Pos) Out(""%c"", g_SeqQ[Pos]); } if (g_ShowHits) { Out("" ""); int PileIndex = AD.PileIndexes[RowIndex]; LogPile(PileIndex); } Out(""\n""); } AD.SpacerLength = (int) ((double) SumSpacerLengths / (double) (RowCount - 1) + 0.5); OutputDetailFooter(AD, ColCount); Out(""%10d %6d %6d "", (int) AD.PileIndexes.size(), AD.RepeatLength, AD.SpacerLength); for (unsigned Col = 0; Col < ColCount; ++Col) Out(""%c"", Aln.GetChar((unsigned) RowCount, Col)); Out(""\n""); Seq ConsSymbols; GetConsSymbols(Aln, ConsSymbols); for (int i = 0; i < (10+2+6+4+28); ++i) Out("" ""); assert(ConsSymbols.Length() == ColCount); for (unsigned Col = 0; Col < ColCount; ++Col) Out(""%c"", ConsSymbols.GetChar(Col)); Out(""\n""); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/mergefilterhits.cpp",".cpp","10421","374","#include ""pilercr.h"" const int MAXIGAP = 5; static Trapezoid *free_traps = NULL; static Trapezoid eotrap; static Trapezoid *eoterm = &eotrap; static int HSORT(const void *l, const void *r) { FilterHit *x = (FilterHit *) l; FilterHit *y = (FilterHit *) r; return x->QFrom - y->QFrom; } Trapezoid *MergeFilterHits(const char *SeqT, int SeqLengthT, const char *SeqQ, int SeqLengthQ, bool Self, const FilterHit *FilterHits, int FilterHitCount, const FilterParams &FP, int *ptrTrapCount) { if (0 == FilterHitCount) { *ptrTrapCount = 0; return 0; } qsort((void *) FilterHits, FilterHitCount, sizeof(FilterHit), HSORT); #if DEBUG { // Verify sort order for (int i = 0; i < FilterHitCount-1; ++i) if (FilterHits[i+1].QFrom < FilterHits[i].QFrom) Quit(""Build_Trapezoids: not sorted""); } #endif const int TubeWidth = FP.TubeOffset + FP.SeedDiffs; const int DPADDING = 2; const int BINWIDE = TubeWidth - 1; const int BPADDING = k + 2; const int LPADDING = DPADDING + BINWIDE; free_traps = NULL; eoterm = &eotrap; Trapezoid *traporder, *traplist, *tailend; Trapezoid *b, *f, *t; int i, nd, tp; int trapcount; #ifdef REPORT_SIZES int traparea; #endif #ifdef REPORT_SIZES traparea = 0; #endif eoterm->lft = SeqLengthQ+1+LPADDING; eoterm->rgt = SeqLengthQ+1; eoterm->bot = -1; eoterm->top = SeqLengthQ+1; eoterm->next = NULL; trapcount = 0; traporder = eoterm; traplist = NULL; for (i = 0; i < FilterHitCount; i++) { nd = - FilterHits[i].DiagIndex; if (Self && nd <= FP.SeedDiffs) continue; tp = FilterHits[i].QFrom - BPADDING; #ifdef TEST_TRAP printf("" Diag %d [%d,%d]\n"", nd,FilterHits[i].QFrom,FilterHits[i].QTo); #endif f = NULL; // for b in traporder for (b = traporder; 1; b = t) { t = b->next; if (b->top < tp) { trapcount += 1; #ifdef REPORT_SIZES traparea += (b->top - b->bot + 1) * (b->rgt - b->lft + 1); #endif if (f == NULL) traporder = t; else f->next = t; b->next = traplist; traplist = b; } else if (nd > b->rgt + DPADDING) f = b; else if (nd >= b->lft - LPADDING) { if (nd+BINWIDE > b->rgt) b->rgt = nd+BINWIDE; if (nd < b->lft) b->lft = nd; if (FilterHits[i].QTo > b->top) b->top = FilterHits[i].QTo; if (f != NULL && f->rgt + DPADDING >= b->lft) { f->rgt = b->rgt; if (f->bot > b->bot) f->bot = b->bot; if (f->top < b->top) f->top = b->top; f->next = t; b->next = free_traps; free_traps = b; } else if (t != NULL && t->lft - DPADDING <= b->rgt) { b->rgt = t->rgt; if (b->bot > t->bot) b->bot = t->bot; if (b->top < t->top) b->top = t->top; b->next = t->next; t->next = free_traps; free_traps = t; t = b->next; f = b; } else f = b; break; } else { // Add to free_trap list if (free_traps == NULL) { free_traps = (Trapezoid *) malloc(sizeof(Trapezoid)); if (free_traps == NULL) Quit(""out of memory Trapezoid scan FilterHits""); free_traps->next = NULL; } if (f == NULL) f = traporder = free_traps; else f = f->next = free_traps; free_traps = f->next; f->next = b; if (f->next == 0) Log(""f->next [3] %x\n"", f); f->top = FilterHits[i].QTo; f->bot = FilterHits[i].QFrom; f->lft = nd; f->rgt = f->lft + BINWIDE; f = b; break; } } #ifdef TEST_TRAP printf("" Blist:""); for (b = traporder; b != NULL; b = b->next) printf("" [%d,%d]x[%d,%d]"", b->bot,b->top,b->lft,b->rgt); printf(""\n""); #endif } for (b = traporder; b != eoterm; b = t) { t = b->next; trapcount += 1; #ifdef REPORT_SIZES traparea += (b->top - b->bot + 1) * (b->rgt - b->lft + 1); #endif b->next = traplist; traplist = b; } #ifdef REPORT_SIZES printf(""\n %9d trapezoids of area %d (%f%% of matrix)\n"", trapcount,traparea,(100.*trapcount/SeqLengthT)/SeqLengthQ); fflush(stdout); #endif { int lag, lst, lclip; int abot, atop; #ifdef TEST_TRAPTRIM printf(""SeqQ trimming:\n""); #endif for (b = traplist; b != NULL; b = b->next) { lag = (b->bot-MAXIGAP)+1; if (lag < 0) lag = 0; lst = b->top+MAXIGAP; if (lst > SeqLengthQ) lst = SeqLengthQ; #ifdef TEST_TRAPTRIM printf("" [%d,%d]x[%d,%d] = %d\n"", b->bot,b->top,b->lft,b->rgt,b->top - b->bot + 1); #endif for (i = lag; i < lst; i++) { if (CharToLetter[(unsigned char) (SeqQ[i])] >= 0) { if (i-lag >= MAXIGAP) { if (lag - b->bot > 0) { if (free_traps == NULL) { free_traps = (Trapezoid *) malloc(sizeof(Trapezoid)); if (free_traps == NULL) Quit(""out of memory Trapezoid cutter""); free_traps->next = NULL; } t = free_traps->next; *free_traps = *b; b->next = free_traps; free_traps = t; b->top = lag; b = b->next; b->bot = i; trapcount += 1; } else b->bot = i; #ifdef TEST_TRAPTRIM printf("" Cut trap SeqQ[%d,%d]\n"",lag,i); #endif } lag = i+1; } } if (i-lag >= MAXIGAP) b->top = lag; } #ifdef TEST_TRAPTRIM printf(""SeqT trimming:\n""); #endif tailend = NULL; for (b = traplist; b != NULL; b = b->next) { if (b->top - b->bot < k) continue; abot = b->bot - b->rgt; atop = b->top - b->lft; #ifdef TEST_TRAPTRIM printf("" [%d,%d]x[%d,%d] = %d\n"", b->bot,b->top,b->lft,b->rgt,b->top - b->bot + 1); #endif lag = (abot - MAXIGAP) + 1; if (lag < 0) lag = 0; lst = atop + MAXIGAP; if (lst > SeqLengthT) lst = SeqLengthT; lclip = abot; for (i = lag; i < lst; i++) { if (CharToLetter[(unsigned char) (SeqT[i])] >= 0) { if (i-lag >= MAXIGAP) { if (lag > lclip) { if (free_traps == NULL) { free_traps = (Trapezoid *) malloc(sizeof(Trapezoid)); if (free_traps == NULL) Quit(""out of memory Trapezoid cutter""); free_traps->next = NULL; } t = free_traps->next; *free_traps = *b; b->next = free_traps; free_traps = t; #ifdef TEST_TRAPTRIM printf("" Clip to %d,%d\n"",lclip,lag); #endif { int x, m; x = lclip + b->lft; if (b->bot < x) b->bot = x; x = lag + b->rgt; if (b->top > x) b->top = x; m = (b->bot + b->top) / 2; x = m - lag; if (b->lft < x) b->lft = x; x = m - lclip; if (b->rgt > x) b->rgt = x; #ifdef TEST_TRAPTRIM printf("" [%d,%d]x[%d,%d] = %d\n"", b->bot,b->top,b->lft,b->rgt,b->top-b->bot+1); #endif } b = b->next; trapcount += 1; } lclip = i; } lag = i+1; } } if (i-lag < MAXIGAP) lag = atop; #ifdef TEST_TRAPTRIM printf("" Clip to %d,%d\n"",lclip,lag); #endif { int x, m; x = lclip + b->lft; if (b->bot < x) b->bot = x; x = lag + b->rgt; if (b->top > x) b->top = x; m = (b->bot + b->top) / 2; x = m - lag; if (b->lft < x) b->lft = x; x = m - lclip; if (b->rgt > x) b->rgt = x; #ifdef TEST_TRAPTRIM printf("" [%d,%d]x[%d,%d] = %d\n"", b->bot,b->top,b->lft,b->rgt,b->top-b->bot+1); #endif } tailend = b; } } if (tailend != NULL) { if (free_traps == NULL) { free_traps = (Trapezoid *) malloc(sizeof(Trapezoid)); if (free_traps == NULL) Quit(""out of memory Trapezoid cutter""); free_traps->next = NULL; } tailend->next = free_traps; free_traps = traplist; } #ifdef REPORT_SIZES printf("" %9d trimmed trap.s of area %d (%f%% of matrix)\n"", trapcount,traparea,(100.*trapcount/SeqLengthT)/SeqLengthQ); fflush(stdout); #endif *ptrTrapCount = trapcount; return traplist; } int SumTrapLengths(const Trapezoid *Traps) { int Sum = 0; for (const Trapezoid *T = Traps; T; T = T->next) { const int Length = T->top - T->bot; Sum += Length; } return Sum; } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/tbsw.cpp",".cpp","3472","171","#include ""pilercr.h"" #include ""multaln.h"" #include ""sw.h"" #include #include #define TRACE 0 void SWTraceBack(const unsigned char *A, unsigned LA, const unsigned char *B, unsigned LB, unsigned Topi, unsigned Topj, score_t TopScore, const score_t *DPM_, const score_t *DPD_, const score_t *DPI_, std::string &Path, unsigned *ptrStartA, unsigned *ptrStartB) { #if TRACE Log(""\n""); Log(""SWTraceBack LengthA=%u LengthB=%u\n"", LA, LB); #endif assert(LB > 0 && LA > 0); Path.clear(); unsigned i = Topi; unsigned j = Topj; const unsigned PCA = LA + 1; char cEdgeType = 'M'; #if TRACE Log(""TraceBack\n""); Log("" i j Edge\n""); Log(""--- --- ----\n""); #endif for (;;) { if (i == 0 || j == 0) goto Done; char cPrevEdgeType = cEdgeType; #if TRACE unsigned Prev_i = i; unsigned Prev_j = j; #endif /*** i is prefix length in A j is prefix length in B Current cell is DP(i,j). Determine the predecessor cell. ***/ switch (cEdgeType) { case 'M': { assert(i > 0); assert(j > 0); const unsigned char cA = A[i-1]; const unsigned char cB = B[j-1]; const score_t Score = DPM(i, j); const score_t scoreMatch = SUBST(cA, cB); score_t scoreMM = MINUS_INF; score_t scoreDM = MINUS_INF; score_t scoreIM = MINUS_INF; if (i > 0 && j > 0) scoreMM = DPM(i-1, j-1) + scoreMatch; if (i > 1) scoreDM = DPD(i-1, j-1) + scoreMatch; if (j > 1) scoreIM = DPI(i-1, j-1) + scoreMatch; if (EQ(scoreMM, Score)) cEdgeType = 'M'; else if (EQ(scoreDM, Score)) cEdgeType = 'D'; else if (EQ(scoreIM, Score)) cEdgeType = 'I'; else if (EQ(0, Score)) goto Done; else Quit(""TraceBack: failed to match M""); --i; --j; break; } case 'D': { assert(i > 0); const score_t Score = DPD(i, j); score_t scoreMD = MINUS_INF; score_t scoreDD = MINUS_INF; if (i > 1) { scoreMD = DPM(i-1, j) + GAPOPEN; scoreDD = DPD(i-1, j) + GAPEXTEND; } if (EQ(Score, scoreMD)) cEdgeType = 'M'; else if (EQ(Score, scoreDD)) cEdgeType = 'D'; else Quit(""TraceBack: failed to match D""); --i; break; } case 'I': { assert(j > 0); const score_t Score = DPI(i, j); score_t scoreMI = MINUS_INF; score_t scoreII = MINUS_INF; if (j > 1) { scoreMI = DPM(i, j-1) + GAPOPEN; scoreII = DPI(i, j-1) + GAPEXTEND; } if (EQ(Score, scoreMI)) cEdgeType = 'M'; else if (EQ(Score, scoreII)) cEdgeType = 'I'; else Quit(""TraceBack: failed to match I""); --j; break; } default: assert(false); } Path.push_back(cPrevEdgeType); #if TRACE { char cA = (cPrevEdgeType == 'M' || cPrevEdgeType == 'D') ? A[Prev_i-1] : '-'; char cB = (cPrevEdgeType == 'M' || cPrevEdgeType == 'I') ? B[Prev_j-1] : '-'; Log(""%3d %3d %4c %c%c\n"", Prev_i-1, Prev_j-1, cPrevEdgeType, cA, cB); } #endif } Done: #if TRACE Log(""StartA=%d StartB=%d\n"", i, j); #endif *ptrStartA = i; *ptrStartB = j; std::reverse(Path.begin(), Path.end()); #if TRACE { score_t sp = ScorePathLocal(A, LA, B, LB, *ptrStartA, *ptrStartB, Path.c_str()); if (!EQ(sp, TopScore)) { Log(""Path=%s\n"", Path.c_str()); Quit(""TraceBackSW: scoreMax=%d != ScorePath=%d"", TopScore, sp); } } #endif } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/seqvect.h",".h","1369","51","#ifndef SeqVect_h #define SeqVect_h #include #include #include ""seq.h"" typedef std::vector SeqVectBase; class SeqVect : public SeqVectBase { public: SeqVect() {} virtual ~SeqVect(); private: // Not implemented; prevent use of copy c'tor and assignment. SeqVect(const SeqVect &); SeqVect &operator=(const SeqVect &); public: void FromFASTAFile(FILE *f); void ToFASTAFile(FILE *f) const; void PadToMSA(MSA &msa); void Copy(const SeqVect &rhs); void StripGaps(); void StripGapsAndWhitespace(); void ToUpper(); void Clear(); unsigned Length() const { return (unsigned) size(); } unsigned GetSeqCount() const { return (unsigned) size(); } void AppendSeq(const Seq &s); bool FindName(const char *ptrName, unsigned *ptruIndex) const; void LogMe() const; const char *GetSeqName(unsigned uSeqIndex) const; unsigned GetSeqId(unsigned uSeqIndex) const; unsigned GetSeqIdFromName(const char *Name) const; unsigned GetSeqLength(unsigned uSeqIndex) const; void SetSeqId(unsigned uSeqIndex, unsigned uId); Seq &GetSeq(unsigned uIndex); Seq &GetSeqById(unsigned uId); const Seq &GetSeq(unsigned uIndex) const; #ifndef _MSC_VER reference at(size_type i) { return operator[](i); } const_reference at(size_type i) const { return operator[](i); } #endif }; #endif // SeqVect_h ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/hitstoimages.cpp",".cpp","1257","55","#include ""pilercr.h"" // Sort by Lo static bool Cmp_ImageLo(const ImageData &Image1, const ImageData &Image2) { if (Image1.Lo < Image2.Lo) return true; return false; } void HitsToImages() { g_ImageCount = 2*g_HitCount; g_Images.resize(g_ImageCount); Progress(""Converting hits to images""); for (int HitIndex = 0; HitIndex < g_HitCount; ++HitIndex) { const DPHit &Hit = g_Hits[HitIndex]; ImageData &ID1 = g_Images[2*HitIndex]; ImageData &ID2 = g_Images[2*HitIndex + 1]; ID1.Lo = Hit.aLo; ID1.Hi = Hit.aHi; ID1.HitIndex = HitIndex; ID1.IsA = true; ID2.Lo = Hit.bLo; ID2.Hi = Hit.bHi; ID2.HitIndex = HitIndex; ID2.IsA = false; } Progress(""Sorting images""); std::sort(g_Images.begin(), g_Images.end(), Cmp_ImageLo); if (!g_LogImages) return; Log(""\n""); Log(""\n""); Log(""Image Lo Hi Hit A\n""); Log(""===== ========= ========== ===== =\n""); for (int ImageIndex = 0; ImageIndex < g_ImageCount; ++ImageIndex) { const ImageData &Image = g_Images[ImageIndex]; Log(""%5d %10d %10d %5d %c"", ImageIndex, Image.Lo, Image.Hi, Image.HitIndex, Image.IsA ? 'A' : 'B'); Log("" ""); LogHit(Image.HitIndex); Log(""\n""); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/getparams.cpp",".cpp","4481","157","#include ""pilercr.h"" /*** Generate default aligner parameters given: minimum hit length. minimum fractional identity. sequence lengths. maximum memory. ***/ const int DEFAULT_LENGTH = 400; const double DEFAULT_MIN_ID = 0.94; const double RAM_FRACT = 0.80; /*** For minimum word length, choose k=4 arbitrarily. For max, k=16 definitely won't work with 32-bit ints because 4^16 = 2^32 = 4GB. k=14 might be OK, but would have to look carefully at boundary cases, which I haven't done. k=13 is definitely safe, so set this as upper bound. ***/ const int MIN_WORD_LENGTH = 4; const int MAX_WORD_LENGTH = 13; const int MAX_AVG_INDEX_LIST_LENGTH = 10; const int TUBE_OFFSET_DELTA = 32; static double FilterMemRequired(int SeqLengthQ, const FilterParams &FP) { const double Index = 2*sizeof(INDEX_ENTRY)*pow4d(FP.WordSize); const int TubeWidth = FP.TubeOffset + FP.SeedDiffs; const double MaxActiveTubes = (SeqLengthQ + TubeWidth - 1)/FP.TubeOffset + 1; const double Tubes = MaxActiveTubes*sizeof(TubeState); return Index + Tubes; } double AvgIndexListLength(int SeqLengthQ, const FilterParams &FP) { return SeqLengthQ / pow4d(FP.WordSize); } double TotalMemRequired(int SeqLengthQ, const FilterParams &FP) { const double Filter = FilterMemRequired(SeqLengthQ, FP); const double Seq = SeqLengthQ; return Filter + Seq; } static void CalcParams(int g_MinHitLength, double MinId, int SeqLengthQ, int g_Diameter, double MaxMem, FilterParams *ptrFP, DPParams *ptrDP) { if (MinId < 0 || MinId > 1.0) Quit(""CalcParams: bad MinId=%g"", MinId); if (g_MinHitLength <= 4) Quit(""CalcParams: bad g_MinHitLength=%d"", g_MinHitLength); // Lower bound on word length k by requiring manageable index. // Given kmer occurs once every 4^k positions. // Hence average number of index entries is i = N/(4^k) for random // string of length N. // Require i <= I, then k > log_4(N/i). const double dSeqLengthA = (double) SeqLengthQ; const int MinWordSize = (int) (log4(g_Diameter) - log4(MAX_AVG_INDEX_LIST_LENGTH) + 0.5); // First choice is that filter criteria are same as DP criteria, // but this may not be possible. int SeedLength = g_MinHitLength; int SeedDiffs = (int) (g_MinHitLength*(1.0 - MinId) + 0.5); // Find filter valid filter parameters, // starting from preferred case. int WordSize = -1; for (;;) { int MinWords = -1; for (WordSize = MAX_WORD_LENGTH; WordSize >= MinWordSize; --WordSize) { ptrFP->WordSize = WordSize; ptrFP->SeedLength = SeedLength; ptrFP->SeedDiffs = SeedDiffs; ptrFP->TubeOffset = ptrFP->SeedDiffs + TUBE_OFFSET_DELTA; double Mem = TotalMemRequired(SeqLengthQ, *ptrFP); if (MaxMem > 0 && Mem > MaxMem) { Log(""Parameters seedlength=%3d k=%2d seeddiffs=%2d, mem=%.0f Mb > maxmem=%.0f Mb\n"", ptrFP->SeedLength, ptrFP->WordSize, ptrFP->SeedDiffs, Mem/1e6, MaxMem/1e6); MinWords = -1; continue; } MinWords = MinWordsPerFilterHit(SeedLength, WordSize, SeedDiffs); if (MinWords <= 0) { Log(""Parameters seedlength=%3d k=%2d seeddiffs=%2d, B=%d\n"", ptrFP->SeedLength, ptrFP->WordSize, ptrFP->SeedDiffs, MinWords); MinWords = -1; continue; } const double Len = AvgIndexListLength(g_Diameter, *ptrFP); if (Len > MAX_AVG_INDEX_LIST_LENGTH) { Log(""Parameters n=%d k=%d e=%d, B=%d avgixlen=%g > max = %d\n"", ptrFP->SeedLength, ptrFP->WordSize, ptrFP->SeedDiffs, MinWords, Len, MAX_AVG_INDEX_LIST_LENGTH); MinWords = -1; continue; } break; } if (MinWords > 0) break; // Failed to find filter parameters, try // fewer errors and shorter seed. if (SeedLength >= g_MinHitLength/4) { SeedLength -= 4; continue; } if (SeedDiffs > 0) { --SeedDiffs; continue; } Quit(""Failed to find filter parameters""); } ptrDP->g_MinHitLength = g_MinHitLength; ptrDP->MinId = MinId; } // Alignment parameters are specified by length and pctid. void GetParams(int SeqLengthQ, int g_Diameter, int Length, double MinId, FilterParams *ptrFP, DPParams *ptrDP) { const char *strMaxMem = ValueOpt(""maxmem""); const double MaxMem = (0 == strMaxMem) ? GetRAMSize()*RAM_FRACT : atof(strMaxMem); CalcParams(Length, MinId, SeqLengthQ, g_Diameter, MaxMem, ptrFP, ptrDP); } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/sw.h",".h","1355","53","#ifndef SW_H #define SW_H #include typedef float score_t; const score_t MINUS_INF = -999999; #undef DPM #undef DPD #undef DPI #undef DPMb #undef DPDb #undef DPIb // Macros to simulate 2D matrices #define DPM(i, j) DPM_[(j)*PCA + (i)] #define DPD(i, j) DPD_[(j)*PCA + (i)] #define DPI(i, j) DPI_[(j)*PCA + (i)] #define DPMb(i, j) DPMb_[BandIndex((i), (j), LA, LB, r)] #define DPDb(i, j) DPDb_[BandIndex((i), (j), LA, LB, r)] #define DPIb(i, j) DPIb_[BandIndex((i), (j), LA, LB, r)] //#define SUBST(cA, cB) \ // ((*g_ptrScoreMatrix)[CharToLetter[(unsigned char) (cA)]][CharToLetter[(unsigned char) (cB)]]) static inline float SUBST(unsigned char cA, unsigned char cB) { unsigned LetA = CharToLetter[(unsigned char) cA]; unsigned LetB = CharToLetter[(unsigned char) cB]; assert(LetA < 32); assert(LetB < 32); return (*g_ptrScoreMatrix)[LetA][LetB]; } extern float g_scoreGapExtend; extern float g_scoreGapOpen; #define GAPOPEN g_scoreGapOpen #define GAPEXTEND g_scoreGapExtend #define EQ(a, b) ((a) == (b)) score_t SWSimple(const char *A_, unsigned LA, const char *B_, unsigned LB, unsigned *ptrStartA, unsigned *ptrStartB, std::string &Path); class Seq; score_t SW(const Seq &A, const Seq &B, unsigned *ptrStartA, unsigned *ptrStartB, std::string &Path); #endif // SW_H ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/validaa.cpp",".cpp","3402","129","#include ""pilercr.h"" void StripBlanksAndGaps(std::string &s) { std::string tmp; for (size_t i = 0; i < s.size(); ++i) { char c = s[i]; if (c != '-' && c != ' ') tmp += c; } s = tmp; } void StripBlanksAndGaps(Seq &s) { Seq tmp; tmp.SetName(s.GetName()); for (size_t i = 0; i < s.size(); ++i) { char c = s[i]; if (c != '-' && c != ' ') tmp.push_back(c); } s = tmp; } static void ValidateRep(const ArrayAln &AA, int RepeatIndex, int &Pos) { std::string Repeat = AA.Repeats[RepeatIndex]; std::string LeftFlank = AA.LeftFlanks[RepeatIndex]; const std::string &Spacer = AA.Spacers[RepeatIndex]; StripBlanksAndGaps(Repeat); StripBlanksAndGaps(LeftFlank); size_t LeftFlankLength = LeftFlank.size(); size_t RepeatLength = Repeat.size(); size_t SpacerLength = Spacer.size(); assert(Pos >= (int) LeftFlankLength); int LeftFlankStartPos = Pos - (int) LeftFlankLength; for (int i = 0; i < (int) LeftFlankLength; ++i) { char c1 = g_SeqQ[LeftFlankStartPos + i]; char c2 = LeftFlank[i]; if (toupper(c1) != toupper(c2)) { Log(""Repeat %d, flank[%d]=%c != Seq[%d]=%c LeftFlankStartPos=%d\n"", RepeatIndex, i, c1, LeftFlankStartPos + i, c2, LeftFlankStartPos); Log(""Flank=""); for (size_t j = 0; j < LeftFlankLength; ++j) Log(""%c"", LeftFlank[j]); Log(""\n""); Log(""Seq[%d;%d]="", LeftFlankStartPos, LeftFlankLength); for (size_t j = 0; j < LeftFlankLength; ++j) Log(""%c"", g_SeqQ[LeftFlankStartPos + j]); Log(""\n""); LogAA(AA); Quit(""ValidateRep failed""); } } for (size_t i = 0; i < RepeatLength; ++i) { char c1 = g_SeqQ[Pos + i]; char c2 = Repeat[i]; if (toupper(c1) != toupper(c2)) { Log(""Repeat %d, Repeat[%d]=%c != Seq[%d]=%c\n"", RepeatIndex, i, c1, Pos + i, c2); Log(""Repeat=""); for (size_t j = 0; j < RepeatLength; ++j) Log(""%c"", Repeat[j]); Log(""\n""); Log(""Seq[%d;%d]="", Pos, RepeatLength); for (size_t j = 0; j < RepeatLength; ++j) Log(""%c"", g_SeqQ[Pos + j]); Log(""\n""); LogAA(AA); Quit(""ValidateRep failed""); } } for (size_t i = 0; i < SpacerLength; ++i) { char c1 = g_SeqQ[Pos + RepeatLength + i]; char c2 = Spacer[i]; if (toupper(c1) != toupper(c2)) { Log(""Repeat %d, Spacer[%d]=%c != Seq[%d]=%c\n"", RepeatIndex, i, c1, Pos + RepeatLength + i, c2); Log(""Spacer=""); for (size_t j = 0; j < SpacerLength; ++j) Log(""%c"", Spacer[j]); Log(""\n""); Log(""Seq[%d;%d]="", Pos + RepeatLength, SpacerLength); for (size_t j = 0; j < SpacerLength; ++j) Log(""%c"", g_SeqQ[Pos + RepeatLength + j]); Log(""\n""); LogAA(AA); Quit(""ValidateRep failed""); } } Pos += (int) (RepeatLength + SpacerLength); } void ValidateAA(const ArrayAln &AA) { const size_t RepeatCount = AA.Spacers.size(); assert(RepeatCount == AA.Repeats.size()); assert(RepeatCount == AA.Spacers.size()); int Pos = AA.Pos; for (size_t RepeatIndex = 0; RepeatIndex < RepeatCount; ++RepeatIndex) { const std::string &LeftFlank = AA.LeftFlanks[RepeatIndex]; const std::string &Repeat = AA.Repeats[RepeatIndex]; const std::string &Spacer = AA.Spacers[RepeatIndex]; assert(Repeat.size() == AA.Repeats[0].size()); assert(LeftFlank.size() == g_FlankSize); ValidateRep(AA, (int) RepeatIndex, Pos); } } ","C++" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/multaln.h",".h","3872","154","#ifndef MULTALN_H #define MULTALN_H #ifdef _MSC_VER #pragma warning(disable: 4996) // deprecated functions #define _CRT_SECURE_NO_DEPRECATE 1 #endif #include #include #include #include #include #include ""types.h"" #include ""params.h"" #include ""myassert.h"" #ifndef _MSC_VER #define stricmp strcasecmp #define strnicmp strncasecmp #define _snprintf snprintf #define _fsopen(name, mode, share) fopen((name), (mode)) #endif enum { BIT_MM = 0x00, BIT_DM = 0x01, BIT_IM = 0x02, BIT_xM = 0x03, BIT_DD = 0x00, BIT_MD = 0x04, // ID not allowed BIT_xD = 0x04, BIT_II = 0x00, BIT_MI = 0x08, // DI not allowed BIT_xI = 0x08, }; // NX=Nucleotide alphabet enum NX { NX_A, NX_C, NX_G, NX_T, NX_U = NX_T, NX_N, NX_GAP }; const size_t MAX_ALPHA = 4; const size_t MAX_ALPHA_EX = 6; const size_t g_AlphaSize = 4; typedef float BASETYPE; typedef BASETYPE FCOUNT; typedef BASETYPE SCORE; typedef float SCOREMATRIX[32][32]; typedef SCOREMATRIX *PTR_SCOREMATRIX; extern PTR_SCOREMATRIX g_ptrScoreMatrix; static inline bool BTEq2(BASETYPE b1, BASETYPE b2) { double diff = fabs(b1 - b2); if (diff < 0.0001) return true; double sum = fabs(b1) + fabs(b2); return diff/sum < 0.005; } static inline bool BTEq(double b1, double b2) { return BTEq2((BASETYPE) b1, (BASETYPE) b2); } static inline bool ScoreEq(SCORE s1, SCORE s2) { return BTEq(s1, s2); } extern SCORE g_scoreGapOpen; extern SCORE g_scoreGapExtend; const unsigned uInsane = UINT_MAX; const double dInsane = -9e-9; const BASETYPE BTInsane = (BASETYPE) -9e-9; const SCORE MINUS_INFINITY = (SCORE) -1e37; #include ""utils.h"" #include ""seq.h"" #include ""seqvect.h"" #include ""msa.h"" #include ""tree.h"" #include ""distfunc.h"" #include ""pwpath.h"" #include ""estring.h"" #include ""profile.h"" #include ""distcalc.h"" extern unsigned g_CharToLetter[]; extern unsigned g_CharToLetterEx[]; extern char g_LetterToChar[]; extern char g_LetterExToChar[]; extern char g_UnalignChar[]; extern char g_AlignChar[]; extern bool g_IsWildcardChar[]; extern bool g_IsResidueChar[]; #define CharToLetter(c) (g_CharToLetter[(unsigned char) (c)]) #define CharToLetterEx(c) (g_CharToLetterEx[(unsigned char) (c)]) #define LetterToChar(u) (g_LetterToChar[u]) #define LetterExToChar(u) (g_LetterExToChar[u]) #define IsResidueChar(c) (g_IsResidueChar[(unsigned char) (c)]) #define IsGapChar(c) ('-' == (c) || '.' == (c)) #define IsWildcardChar(c) (g_IsWildcardChar[(unsigned char) (c)]) #define AlignChar(c) (g_AlignChar[(unsigned char) (c)]) #define UnalignChar(c) (g_UnalignChar[(unsigned char) (c)]) void GetGuideTree(const SeqVect &Seqs, Tree &GuideTree); void KmerDist(const SeqVect &Seqs, DistFunc &DF); void ProgressiveAlign(const SeqVect &Seqs, const Tree &GuideTree, MSA &Aln); SCORE GlobalAlign(const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path); void BitTraceBack(char **TraceBack, unsigned uLengthA, unsigned uLengthB, char LastEdge, PWPath &Path); SCORE AlignProfiles( const ProfPos *PA, unsigned uLengthA, const ProfPos *PB, unsigned uLengthB, PWPath &Path, ProfPos **ptrPout, unsigned *ptruLengthOut); void AlignTwoProfsGivenPath(const PWPath &Path, const ProfPos *PA, unsigned uPrefixLengthA, const ProfPos *PB, unsigned uPrefixLengthB, ProfPos **ptrPOut, unsigned *ptruLengthOut); void MakeRootMSA(const SeqVect &v, const Tree &GuideTree, ProgNode Nodes[], MSA &Aln); void MultipleAlign(SeqVect &Seqs, MSA &Aln); void UPGMA(const DistCalc &DC, Tree &tree); void GetConsSeq(const MSA &Aln, double MinCons, int *ptrStartCol, int *ptrEndCol, Seq &ConsSeq); void GetConsSymbols(const MSA &Aln, Seq &ConsSymbols); #endif // MULTALN_H ","Unknown" "CRISPR","wilkelab/Metagenomics_CAST","pilercr/msa.cpp",".cpp","19448","782","#include ""multaln.h"" const unsigned DEFAULT_SEQ_LENGTH = 500; unsigned MSA::m_uIdCount = 0; MSA::MSA() { m_uSeqCount = 0; m_uColCount = 0; m_szSeqs = 0; m_szNames = 0; m_IdToSeqIndex = 0; m_SeqIndexToId = 0; m_uCacheSeqCount = 0; m_uCacheSeqLength = 0; } MSA::~MSA() { Free(); } void MSA::Free() { for (unsigned n = 0; n < m_uSeqCount; ++n) { delete[] m_szSeqs[n]; delete[] m_szNames[n]; } delete[] m_szSeqs; delete[] m_szNames; delete[] m_IdToSeqIndex; delete[] m_SeqIndexToId; m_uSeqCount = 0; m_uColCount = 0; m_szSeqs = 0; m_szNames = 0; m_IdToSeqIndex = 0; m_SeqIndexToId = 0; } void MSA::SetSize(unsigned uSeqCount, unsigned uColCount) { Free(); m_uSeqCount = uSeqCount; m_uCacheSeqLength = uColCount; m_uColCount = 0; if (0 == uSeqCount && 0 == uColCount) return; m_szSeqs = new char *[uSeqCount]; m_szNames = new char *[uSeqCount]; for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { m_szSeqs[uSeqIndex] = new char[uColCount+1]; m_szNames[uSeqIndex] = 0; #if DEBUG memset(m_szSeqs[uSeqIndex], '?', uColCount); #endif m_szSeqs[uSeqIndex][uColCount] = 0; } if (m_uIdCount > 0) { m_IdToSeqIndex = new unsigned[m_uIdCount]; m_SeqIndexToId = new unsigned[m_uSeqCount]; #if DEBUG memset(m_IdToSeqIndex, 0xff, m_uIdCount*sizeof(unsigned)); memset(m_SeqIndexToId, 0xff, m_uSeqCount*sizeof(unsigned)); #endif } } void MSA::LogMe() const { if (0 == GetColCount()) { Log(""MSA empty\n""); return; } const unsigned uColsPerLine = 50; unsigned uLinesPerSeq = (GetColCount() - 1)/uColsPerLine + 1; for (unsigned n = 0; n < uLinesPerSeq; ++n) { unsigned i; unsigned iStart = n*uColsPerLine; unsigned iEnd = GetColCount(); if (iEnd - iStart + 1 > uColsPerLine) iEnd = iStart + uColsPerLine; Log("" ""); for (i = iStart; i < iEnd; ++i) Log(""%u"", i%10); Log(""\n""); Log("" ""); for (i = iStart; i + 9 < iEnd; i += 10) Log(""%-10u"", i); if (n == uLinesPerSeq - 1) Log("" %-10u"", GetColCount()); Log(""\n""); for (unsigned uSeqIndex = 0; uSeqIndex < m_uSeqCount; ++uSeqIndex) { Log(""%12.12s"", m_szNames[uSeqIndex]); Log("" ""); for (i = iStart; i < iEnd; ++i) Log(""%c"", GetChar(uSeqIndex, i)); if (0 != m_SeqIndexToId) Log("" [%5u]"", m_SeqIndexToId[uSeqIndex]); Log(""\n""); } Log(""\n\n""); } } char MSA::GetChar(unsigned uSeqIndex, unsigned uIndex) const { // TODO: Performance cost? if (uSeqIndex >= m_uSeqCount || uIndex >= m_uColCount) Quit(""MSA::GetChar(%u/%u,%u/%u)"", uSeqIndex, m_uSeqCount, uIndex, m_uColCount); char c = m_szSeqs[uSeqIndex][uIndex]; // assert(IsLegalChar(c)); return c; } unsigned MSA::GetLetter(unsigned uSeqIndex, unsigned uIndex) const { // TODO: Performance cost? char c = GetChar(uSeqIndex, uIndex); unsigned uLetter = CharToLetter(c); if (uLetter >= 20) return 0; return uLetter; } unsigned MSA::GetLetterEx(unsigned uSeqIndex, unsigned uIndex) const { // TODO: Performance cost? char c = GetChar(uSeqIndex, uIndex); unsigned uLetter = CharToLetterEx(c); return uLetter; } void MSA::SetSeqName(unsigned uSeqIndex, const char szName[]) { if (uSeqIndex >= m_uSeqCount) Quit(""MSA::SetSeqName(%u, %s), count=%u"", uSeqIndex, m_uSeqCount); delete[] m_szNames[uSeqIndex]; int n = (int) strlen(szName) + 1; m_szNames[uSeqIndex] = new char[n]; memcpy(m_szNames[uSeqIndex], szName, n); } const char *MSA::GetSeqName(unsigned uSeqIndex) const { if (uSeqIndex >= m_uSeqCount) Quit(""MSA::GetSeqName(%u), count=%u"", uSeqIndex, m_uSeqCount); return m_szNames[uSeqIndex]; } bool MSA::IsGap(unsigned uSeqIndex, unsigned uIndex) const { char c = GetChar(uSeqIndex, uIndex); return IsGapChar(c); } bool MSA::IsWildcard(unsigned uSeqIndex, unsigned uIndex) const { char c = GetChar(uSeqIndex, uIndex); return IsWildcardChar(c); } void MSA::SetChar(unsigned uSeqIndex, unsigned uIndex, char c) { if (uSeqIndex >= m_uSeqCount || uIndex > m_uCacheSeqLength) Quit(""MSA::SetChar(%u,%u)"", uSeqIndex, uIndex); if (uIndex == m_uCacheSeqLength) { const unsigned uNewCacheSeqLength = m_uCacheSeqLength + DEFAULT_SEQ_LENGTH; for (unsigned n = 0; n < m_uSeqCount; ++n) { char *ptrNewSeq = new char[uNewCacheSeqLength+1]; memcpy(ptrNewSeq, m_szSeqs[n], m_uCacheSeqLength); memset(ptrNewSeq + m_uCacheSeqLength, '?', DEFAULT_SEQ_LENGTH); ptrNewSeq[uNewCacheSeqLength] = 0; delete[] m_szSeqs[n]; m_szSeqs[n] = ptrNewSeq; } m_uColCount = uIndex; m_uCacheSeqLength = uNewCacheSeqLength; } if (uIndex >= m_uColCount) m_uColCount = uIndex + 1; m_szSeqs[uSeqIndex][uIndex] = c; } void MSA::GetSeq(unsigned uSeqIndex, Seq &seq) const { assert(uSeqIndex < m_uSeqCount); seq.Clear(); for (unsigned n = 0; n < m_uColCount; ++n) { char c = GetChar(uSeqIndex, n); c = toupper(c); seq.push_back(c); } const char *ptrName = GetSeqName(uSeqIndex); seq.SetName(ptrName); } bool MSA::HasGap() const { for (unsigned uSeqIndex = 0; uSeqIndex < GetSeqCount(); ++uSeqIndex) for (unsigned n = 0; n < GetColCount(); ++n) if (IsGap(uSeqIndex, n)) return true; return false; } void MSA::SetSeqCount(unsigned uSeqCount) { Free(); SetSize(uSeqCount, DEFAULT_SEQ_LENGTH); } void MSA::Copy(const MSA &msa) { Free(); const unsigned uSeqCount = msa.GetSeqCount(); const unsigned uColCount = msa.GetColCount(); SetSize(uSeqCount, uColCount); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { SetSeqName(uSeqIndex, msa.GetSeqName(uSeqIndex)); const unsigned uId = msa.GetSeqId(uSeqIndex); SetSeqId(uSeqIndex, uId); for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { const char c = msa.GetChar(uSeqIndex, uColIndex); SetChar(uSeqIndex, uColIndex, c); } } } bool MSA::IsGapColumn(unsigned uColIndex) const { assert(GetSeqCount() > 0); for (unsigned uSeqIndex = 0; uSeqIndex < GetSeqCount(); ++uSeqIndex) if (!IsGap(uSeqIndex, uColIndex)) return false; return true; } bool MSA::GetSeqIndex(const char *ptrSeqName, unsigned *ptruSeqIndex) const { for (unsigned uSeqIndex = 0; uSeqIndex < GetSeqCount(); ++uSeqIndex) if (0 == stricmp(ptrSeqName, GetSeqName(uSeqIndex))) { *ptruSeqIndex = uSeqIndex; return true; } return false; } void MSA::DeleteCol(unsigned uColIndex) { assert(uColIndex < m_uColCount); size_t n = m_uColCount - uColIndex; if (n > 0) { for (unsigned uSeqIndex = 0; uSeqIndex < GetSeqCount(); ++uSeqIndex) { char *ptrSeq = m_szSeqs[uSeqIndex]; memmove(ptrSeq + uColIndex, ptrSeq + uColIndex + 1, n); } } --m_uColCount; } void MSA::DeleteColumns(unsigned uColIndex, unsigned uColCount) { for (unsigned n = 0; n < uColCount; ++n) DeleteCol(uColIndex); } static void FmtChar(char c, unsigned uWidth) { Log(""%c"", c); for (unsigned n = 0; n < uWidth - 1; ++n) Log("" ""); } static void FmtInt(unsigned u, unsigned uWidth) { static char szStr[1024]; assert(uWidth < sizeof(szStr)); if (u > 0) sprintf(szStr, ""%u"", u); else strcpy(szStr, "".""); Log(szStr); unsigned n = (unsigned) strlen(szStr); if (n < uWidth) for (unsigned i = 0; i < uWidth - n; ++i) Log("" ""); } static void FmtInt0(unsigned u, unsigned uWidth) { static char szStr[1024]; assert(uWidth < sizeof(szStr)); sprintf(szStr, ""%u"", u); Log(szStr); unsigned n = (unsigned) strlen(szStr); if (n < uWidth) for (unsigned i = 0; i < uWidth - n; ++i) Log("" ""); } static void FmtPad(unsigned n) { for (unsigned i = 0; i < n; ++i) Log("" ""); } void MSA::FromSeq(const Seq &s) { unsigned uSeqLength = s.Length(); SetSize(1, uSeqLength); SetSeqName(0, s.GetName()); if (0 != m_SeqIndexToId) SetSeqId(0, s.GetId()); for (unsigned n = 0; n < uSeqLength; ++n) SetChar(0, n, s[n]); } unsigned MSA::GetCharCount(unsigned uSeqIndex, unsigned uColIndex) const { assert(uSeqIndex < GetSeqCount()); assert(uColIndex < GetColCount()); unsigned uCol = 0; for (unsigned n = 0; n <= uColIndex; ++n) if (!IsGap(uSeqIndex, n)) ++uCol; return uCol; } void MSA::CopySeq(unsigned uToSeqIndex, const MSA &msaFrom, unsigned uFromSeqIndex) { assert(uToSeqIndex < m_uSeqCount); const unsigned uColCount = msaFrom.GetColCount(); assert(m_uColCount == uColCount || (0 == m_uColCount && uColCount <= m_uCacheSeqLength)); memcpy(m_szSeqs[uToSeqIndex], msaFrom.GetSeqBuffer(uFromSeqIndex), uColCount); SetSeqName(uToSeqIndex, msaFrom.GetSeqName(uFromSeqIndex)); if (0 == m_uColCount) m_uColCount = uColCount; } const char *MSA::GetSeqBuffer(unsigned uSeqIndex) const { assert(uSeqIndex < m_uSeqCount); return m_szSeqs[uSeqIndex]; } void MSA::DeleteSeq(unsigned uSeqIndex) { assert(uSeqIndex < m_uSeqCount); delete m_szSeqs[uSeqIndex]; delete m_szNames[uSeqIndex]; const unsigned uBytesToMove = (m_uSeqCount - uSeqIndex)*sizeof(char *); if (uBytesToMove > 0) { memmove(m_szSeqs + uSeqIndex, m_szSeqs + uSeqIndex + 1, uBytesToMove); memmove(m_szNames + uSeqIndex, m_szNames + uSeqIndex + 1, uBytesToMove); } --m_uSeqCount; } bool MSA::IsEmptyCol(unsigned uColIndex) const { const unsigned uSeqCount = GetSeqCount(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) if (!IsGap(uSeqIndex, uColIndex)) return false; return true; } //void MSA::DeleteEmptyCols(bool bProgress) // { // unsigned uColCount = GetColCount(); // for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) // { // if (IsEmptyCol(uColIndex)) // { // if (bProgress) // { // Log(""Deleting col %u of %u\n"", uColIndex, uColCount); // printf(""Deleting col %u of %u\n"", uColIndex, uColCount); // } // DeleteCol(uColIndex); // --uColCount; // } // } // } unsigned MSA::AlignedColIndexToColIndex(unsigned uAlignedColIndex) const { Quit(""MSA::AlignedColIndexToColIndex not implemented""); return 0; } bool MSA::SeqsEq(const MSA &a1, unsigned uSeqIndex1, const MSA &a2, unsigned uSeqIndex2) { Seq s1; Seq s2; a1.GetSeq(uSeqIndex1, s1); a2.GetSeq(uSeqIndex2, s2); s1.StripGaps(); s2.StripGaps(); return s1.EqIgnoreCase(s2); } unsigned MSA::GetSeqLength(unsigned uSeqIndex) const { assert(uSeqIndex < GetSeqCount()); const unsigned uColCount = GetColCount(); unsigned uLength = 0; for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) if (!IsGap(uSeqIndex, uColIndex)) ++uLength; return uLength; } void MSA::GetPWID(unsigned uSeqIndex1, unsigned uSeqIndex2, double *ptrPWID, unsigned *ptruPosCount) const { assert(uSeqIndex1 < GetSeqCount()); assert(uSeqIndex2 < GetSeqCount()); unsigned uSameCount = 0; unsigned uPosCount = 0; const unsigned uColCount = GetColCount(); for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { char c1 = GetChar(uSeqIndex1, uColIndex); if (IsGapChar(c1)) continue; char c2 = GetChar(uSeqIndex2, uColIndex); if (IsGapChar(c2)) continue; ++uPosCount; if (c1 == c2) ++uSameCount; } *ptruPosCount = uPosCount; if (uPosCount > 0) *ptrPWID = 100.0 * (double) uSameCount / (double) uPosCount; else *ptrPWID = 0; } unsigned MSA::UniqueResidueTypes(unsigned uColIndex) const { assert(uColIndex < GetColCount()); unsigned Counts[MAX_ALPHA]; memset(Counts, 0, sizeof(Counts)); const unsigned uSeqCount = GetSeqCount(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { if (IsGap(uSeqIndex, uColIndex) || IsWildcard(uSeqIndex, uColIndex)) continue; const unsigned uLetter = GetLetter(uSeqIndex, uColIndex); ++(Counts[uLetter]); } unsigned uUniqueCount = 0; for (unsigned uLetter = 0; uLetter < g_AlphaSize; ++uLetter) if (Counts[uLetter] > 0) ++uUniqueCount; return uUniqueCount; } double MSA::GetOcc(unsigned uColIndex) const { unsigned uGapCount = 0; for (unsigned uSeqIndex = 0; uSeqIndex < GetSeqCount(); ++uSeqIndex) if (IsGap(uSeqIndex, uColIndex)) ++uGapCount; unsigned uSeqCount = GetSeqCount(); return (double) (uSeqCount - uGapCount) / (double) uSeqCount; } bool MSA::ColumnHasGap(unsigned uColIndex) const { const unsigned uSeqCount = GetSeqCount(); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) if (IsGap(uSeqIndex, uColIndex)) return true; return false; } void MSA::SetIdCount(unsigned uIdCount) { //if (m_uIdCount != 0) // Quit(""MSA::SetIdCount: may only be called once""); if (m_uIdCount > 0) { if (uIdCount > m_uIdCount) Quit(""MSA::SetIdCount: cannot increase count""); return; } m_uIdCount = uIdCount; } void MSA::SetSeqId(unsigned uSeqIndex, unsigned uId) { assert(uSeqIndex < m_uSeqCount); assert(uId < m_uIdCount); if (0 == m_SeqIndexToId) { if (0 == m_uIdCount) Quit(""MSA::SetSeqId, SetIdCount has not been called""); m_IdToSeqIndex = new unsigned[m_uIdCount]; m_SeqIndexToId = new unsigned[m_uSeqCount]; memset(m_IdToSeqIndex, 0xff, m_uIdCount*sizeof(unsigned)); memset(m_SeqIndexToId, 0xff, m_uSeqCount*sizeof(unsigned)); } m_SeqIndexToId[uSeqIndex] = uId; m_IdToSeqIndex[uId] = uSeqIndex; } unsigned MSA::GetSeqIndex(unsigned uId) const { assert(uId < m_uIdCount); assert(0 != m_IdToSeqIndex); unsigned uSeqIndex = m_IdToSeqIndex[uId]; assert(uSeqIndex < m_uSeqCount); return uSeqIndex; } bool MSA::GetSeqIndex(unsigned uId, unsigned *ptruIndex) const { for (unsigned uSeqIndex = 0; uSeqIndex < m_uSeqCount; ++uSeqIndex) { if (uId == m_SeqIndexToId[uSeqIndex]) { *ptruIndex = uSeqIndex; return true; } } return false; } unsigned MSA::GetSeqId(unsigned uSeqIndex) const { assert(uSeqIndex < m_uSeqCount); unsigned uId = m_SeqIndexToId[uSeqIndex]; assert(uId < m_uIdCount); return uId; } void MSASubsetByIds(const MSA &msaIn, const unsigned Ids[], unsigned uIdCount, MSA &msaOut) { const unsigned uColCount = msaIn.GetColCount(); msaOut.SetSize(uIdCount, uColCount); for (unsigned uSeqIndexOut = 0; uSeqIndexOut < uIdCount; ++uSeqIndexOut) { const unsigned uId = Ids[uSeqIndexOut]; const unsigned uSeqIndexIn = msaIn.GetSeqIndex(uId); const char *ptrName = msaIn.GetSeqName(uSeqIndexIn); msaOut.SetSeqId(uSeqIndexOut, uId); msaOut.SetSeqName(uSeqIndexOut, ptrName); for (unsigned uColIndex = 0; uColIndex < uColCount; ++uColIndex) { const char c = msaIn.GetChar(uSeqIndexIn, uColIndex); msaOut.SetChar(uSeqIndexOut, uColIndex, c); } } } // Caller must allocate ptrSeq and ptrLabel as new char[n]. void MSA::AppendSeq(char *ptrSeq, unsigned uSeqLength, char *ptrLabel) { if (m_uSeqCount > m_uCacheSeqCount) Quit(""Internal error MSA::AppendSeq""); if (m_uSeqCount == m_uCacheSeqCount) ExpandCache(m_uSeqCount + 4, uSeqLength); m_szSeqs[m_uSeqCount] = ptrSeq; m_szNames[m_uSeqCount] = ptrLabel; ++m_uSeqCount; } void MSA::ExpandCache(unsigned uSeqCount, unsigned uColCount) { if (m_IdToSeqIndex != 0 || m_SeqIndexToId != 0 || uSeqCount < m_uSeqCount) Quit(""Internal error MSA::ExpandCache""); if (m_uSeqCount > 0 && uColCount != m_uColCount) Quit(""Internal error MSA::ExpandCache, ColCount changed""); char **NewSeqs = new char *[uSeqCount]; char **NewNames = new char *[uSeqCount]; for (unsigned uSeqIndex = 0; uSeqIndex < m_uSeqCount; ++uSeqIndex) { NewSeqs[uSeqIndex] = m_szSeqs[uSeqIndex]; NewNames[uSeqIndex] = m_szNames[uSeqIndex]; } for (unsigned uSeqIndex = m_uSeqCount; uSeqIndex < uSeqCount; ++uSeqIndex) { char *Seq = new char[uColCount]; NewSeqs[uSeqIndex] = Seq; #if DEBUG memset(Seq, '?', uColCount); #endif } delete[] m_szSeqs; delete[] m_szNames; m_szSeqs = NewSeqs; m_szNames = NewNames; m_uCacheSeqCount = uSeqCount; m_uCacheSeqLength = uColCount; m_uColCount = uColCount; } void MSA::GetFractionalWeightedCounts(unsigned uColIndex, bool bNormalize, FCOUNT fcCounts[], FCOUNT *ptrfcGapStart, FCOUNT *ptrfcGapEnd, FCOUNT *ptrfcGapExtend, FCOUNT *ptrfOcc, FCOUNT *ptrfcLL, FCOUNT *ptrfcLG, FCOUNT *ptrfcGL, FCOUNT *ptrfcGG) const { const unsigned uSeqCount = GetSeqCount(); const unsigned uColCount = GetColCount(); memset(fcCounts, 0, g_AlphaSize*sizeof(FCOUNT)); FCOUNT fGap = 0; const FCOUNT w = (FCOUNT) (1.0 / uSeqCount); for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { if (IsGap(uSeqIndex, uColIndex)) { fGap += w; continue; } else if (IsWildcard(uSeqIndex, uColIndex)) { const unsigned uLetter = GetLetterEx(uSeqIndex, uColIndex); const FCOUNT f = w/20; for (unsigned uLetter = 0; uLetter < g_AlphaSize; ++uLetter) fcCounts[uLetter] += f; break; } else { unsigned uLetter = GetLetter(uSeqIndex, uColIndex); fcCounts[uLetter] += w; } } *ptrfOcc = (float) (1.0 - fGap); FCOUNT fcStartCount = 0; if (uColIndex == 0) { for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) if (IsGap(uSeqIndex, uColIndex)) fcStartCount += w; } else { for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) if (IsGap(uSeqIndex, uColIndex) && !IsGap(uSeqIndex, uColIndex - 1)) fcStartCount += w; } FCOUNT fcEndCount = 0; if (uColCount - 1 == uColIndex) { for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) if (IsGap(uSeqIndex, uColIndex)) fcEndCount += w; } else { for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) if (IsGap(uSeqIndex, uColIndex) && !IsGap(uSeqIndex, uColIndex + 1)) fcEndCount += w; } FCOUNT LL = 0; FCOUNT LG = 0; FCOUNT GL = 0; FCOUNT GG = 0; for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) { bool bLetterHere = !IsGap(uSeqIndex, uColIndex); bool bLetterPrev = (uColIndex == 0 || !IsGap(uSeqIndex, uColIndex - 1)); if (bLetterHere) { if (bLetterPrev) LL += w; else GL += w; } else { if (bLetterPrev) LG += w; else GG += w; } } FCOUNT fcExtendCount = 0; if (uColIndex > 0 && uColIndex < GetColCount() - 1) for (unsigned uSeqIndex = 0; uSeqIndex < uSeqCount; ++uSeqIndex) if (IsGap(uSeqIndex, uColIndex) && IsGap(uSeqIndex, uColIndex - 1) && IsGap(uSeqIndex, uColIndex + 1)) fcExtendCount += w; *ptrfcLL = LL; *ptrfcLG = LG; *ptrfcGL = GL; *ptrfcGG = GG; *ptrfcGapStart = fcStartCount; *ptrfcGapEnd = fcEndCount; *ptrfcGapExtend = fcExtendCount; } double MSA::GetPctIdentityPair(unsigned uSeqIndex1, unsigned uSeqIndex2) const { const unsigned ColCount = GetColCount(); if (ColCount == 0) return 0; double Sum = 0; for (unsigned ColIndex = 0; ColIndex < ColCount; ++ColIndex) { char c1 = GetChar(uSeqIndex1, ColIndex); char c2 = GetChar(uSeqIndex2, ColIndex); if (toupper(c1) == toupper(c2)) ++Sum; } return Sum / ColCount; } ","C++" "CRISPR","imkeller/gscreend","R/core.R",".R","1633","54","# Wrapper funtion to run complete analysis #' run gscreend #' #' @param object PoolScreenExp object #' @param quant1 lower quantile for least quantile of squares regression #' (default: 0.1) #' @param quant2 upper quantile for least quantile of squares regression #' (default: 0.9) #' @param alphacutoff alpha cutoff for alpha-RRA (default: 0.05) #' #' @return object #' @export #' #' #' @examples raw_counts <- read.table( #' system.file('extdata', 'simulated_counts.txt', #' package = 'gscreend'), #' header=TRUE) #' #'# Create the PoolScreenExp to be analyzed #'counts_matrix <- cbind(raw_counts$library0, raw_counts$R0_0, raw_counts$R1_0) #' #'rowData <- data.frame(sgRNA_id = raw_counts$sgrna_id, #'gene = raw_counts$Gene) #' #'colData <- data.frame(samplename = c('library', 'R1', 'R2'), #'timepoint = c('T0', 'T1', 'T1')) #' #'library(SummarizedExperiment) #'se <- SummarizedExperiment(assays=list(counts=counts_matrix), #'rowData=rowData, colData=colData) #' #'pse <- createPoolScreenExp(se) #' #'# Run Analysis #'pse_an <- RunGscreend(pse) #' RunGscreend <- function(object, quant1 = 0.1, quant2 = 0.9, alphacutoff = 0.05) { # normalize norm_pse <- normalizePoolScreenExp(object) # calculate fold changes lfc_pse <- calculateLFC(norm_pse) # sgRNA fitting fit_pse <- calculateIntervalFits( defineFittingIntervals(lfc_pse), quant1, quant2) # pvalues and rank sgRNAs pval_pse <- calculatePValues(fit_pse) # rank genes assignGeneData(pval_pse, alphacutoff) } ","R" "CRISPR","imkeller/gscreend","R/Normalization.R",".R","823","31","#' Normalize raw count #' #' @param object PoolScreenExp object #' #' @return object #' @keywords internal normalizePoolScreenExp <- function(object) { sgRNAse <- sgRNAData(object) sizefactors <- colSums(assays(sgRNAse)$counts) maxfact <- max(sizefactors) # want to divide each row of matrix by vector elements. only works with t() normcounts(object) <- t(t(assays(sgRNAse)$counts)/sizefactors) * maxfact message(""Size normalized count data."") object } #' Calculate log fold changes #' #' @param object PoolScreenExp object #' #' @return object #' @keywords internal calculateLFC <- function(object) { sgRNAse <- sgRNAData(object) assays(sgRNAData(object))$lfc <-log2( (normcounts(object) + 1)/(refcounts(object)[, 1] + 1) ) message(""Calculated LFC."") object } ","R" "CRISPR","imkeller/gscreend","R/QualityControl.R",".R","3553","101","#' Plot replicate correlation #' #' @param object PoolScreenExp object #' @param rep1 Name of replicate 1 #' @param rep2 Name of replicate 2 #' #' @return replicate_plot #' @export #' #' @examples #' # import a PoolScreenExp object that has been generated using RunGscreend() #' pse_an <- readRDS( #' system.file('extdata', 'gscreend_analysed_experiment.RData', #' package = 'gscreend')) #' plotReplicateCorrelation(pse_an, rep1 = 'R1', rep2 = 'R2') #' #'@importFrom graphics plot plotReplicateCorrelation <- function(object, rep1 = ""R1"", rep2 = ""R2"") { se <- sgRNAData(object) if(rep1 %in% se$samplename & rep2 %in% se$samplename) { counts1 <- assays(se[, se$samplename == rep1])$normcounts counts2 <- assays(se[, se$samplename == rep2])$normcounts plot(log2(counts1 + 1), log2(counts2 + 1), asp=1) } else { stop( ""Error: One or more of the replicate names you provide is "", ""not in the list of available replicates: "", paste(as.character(se$samplename))) } } #' Plot model parameters from the fitting #' #' @param object PoolScreenExp object #' #' @return plot #' @export #' #' @examples # import a PoolScreenExp object that has been generated using #' # RunGscreend() #' pse_an <- readRDS( #' system.file('extdata', 'gscreend_analysed_experiment.RData', #' package = 'gscreend')) #' plotModelParameters(pse_an) plotModelParameters <- function(object) { if (!is.numeric(FittingIntervals(object))) { stop(""It seems that you are tying to plot paramters from an object that "", ""has not been analysed yet. Please run RunGscreend()!"")} else { limits <- FittingIntervals(object) limits <- limits[seq_len(length(limits)) - 1] parameters <- LFCModelParameters(object) graphics::par(mfrow = c(2, 2)) plot(limits, parameters[, 1], main = ""Mean"") plot(limits, parameters[, 2], main = ""Sd"") plot(limits, parameters[, 3], main = ""Xi"") } } #' Extract a results table #' #' @param object PoolScreenExp object #' @param direction Whether the table should contain information on positive or #' negative fold changes ['negative'| 'positive'] #' #' @return plot #' @export #' #' @examples # import a PoolScreenExp object that has been generated using #' # RunGscreend() #' pse_an <- readRDS( #' system.file('extdata', 'gscreend_analysed_experiment.RData', #' package = 'gscreend')) #' ResultsTable(pse_an, direction = 'negative') #' ResultsTable <- function(object, direction = ""negative"") { if (all(dim(GeneData(object)) == 0)) { stop(""It seems that you are tying to create the ResultsTable from an object that "", ""has not been analysed yet. Please run RunGscreend()!"")} else { if (direction == ""negative"") { genedataslot <- GeneData(object) data.frame(Name = rownames(assays(genedataslot)$fdr_neg), fdr = assays(genedataslot)$fdr_neg, pval = as.numeric(assays(genedataslot)$pvalue_neg[, 1]), lfc = assays(genedataslot)$lfc) } else if (direction == ""positive"") { genedataslot <- GeneData(object) data.frame(Name = rownames(assays(genedataslot)$fdr_pos), fdr = assays(genedataslot)$fdr_pos, pval = as.numeric(assays(genedataslot)$pvalue_pos[, 1]), lfc = assays(genedataslot)$lfc) } else { stop(direction, "" is not a valid argument."", ""Select positive or negative direction for results table."") }} } ","R" "CRISPR","imkeller/gscreend","R/zzz.R",".R","244","8",".onAttach <- function(libname, pkgname) { msg <- sprintf( ""Package '%s' is deprecated and will be removed from Bioconductor version %s"", pkgname, ""3.20"") .Deprecated(msg=paste(strwrap(msg, exdent=2), collapse=""\n"")) } ","R" "CRISPR","imkeller/gscreend","R/AllGenerics.R",".R","2281","70","# sgRNA slot #' @title sgRNAData: set and retrieve sgRNAData of PoolScreenExp #' @name sgRNAData #' @param x PoolScreenExp object #' @return sgRNA slot of the object #' @export #' @examples # import a PoolScreenExp object that has been generated using #' # RunGscreend() #' pse_an <- readRDS( #' system.file('extdata', 'gscreend_analysed_experiment.RData', #' package = 'gscreend')) #' #' sgRNAData(pse_an) #' setGeneric(""sgRNAData"", function(x) standardGeneric(""sgRNAData"")) setGeneric(""sgRNAData<-"", function(x, value) standardGeneric(""sgRNAData<-"")) # Gene slot #' @title GeneData: set and retrieve GeneData of PoolScreenExp #' @name GeneData #' @param x PoolScreenExp object #' @return Gene slot of the object #' @export #' @examples # import a PoolScreenExp object that has been generated using #' # RunGscreend() #' pse_an <- readRDS( #' system.file('extdata', 'gscreend_analysed_experiment.RData', #' package = 'gscreend')) #' #' GeneData(pse_an) #' setGeneric(""GeneData"", function(x) standardGeneric(""GeneData"")) setGeneric(""GeneData<-"", function(x, value) standardGeneric(""GeneData<-"")) # FittingOptions slot setGeneric(""FittingOptions"", function(x) standardGeneric(""FittingOptions"")) setGeneric(""FittingOptions<-"", function(x, value) standardGeneric(""FittingOptions<-"")) # FittingIntervals slot setGeneric(""FittingIntervals"", function(x) standardGeneric(""FittingIntervals"")) setGeneric(""FittingIntervals<-"", function(x, value) standardGeneric(""FittingIntervals<-"")) # LFCModelParameters slot setGeneric(""LFCModelParameters"", function(x) standardGeneric(""LFCModelParameters"")) setGeneric(""LFCModelParameters<-"", function(x, value) standardGeneric(""LFCModelParameters<-"")) # set and get normalized counts setGeneric(""normcounts"", function(x) standardGeneric(""normcounts"")) setGeneric(""normcounts<-"", function(x, value) standardGeneric(""normcounts<-"")) # get reference(library) counts setGeneric(""refcounts"", function(x) standardGeneric(""refcounts"")) # get sample counts setGeneric(""samplecounts"", function(x) standardGeneric(""samplecounts"")) # get sample lfc setGeneric(""samplelfc"", function(x) standardGeneric(""samplelfc"")) # get sample pvalues setGeneric(""samplepval"", function(x) standardGeneric(""samplepval"")) ","R" "CRISPR","imkeller/gscreend","R/sgrnaRanking.R",".R","4316","125","#' Calculate interval limits for splitting data into subsets #' #' @param object PoolScreenExp object #' #' @return object #' @keywords internal defineFittingIntervals <- function(object) { # split intervals based on library counts use 10% of data # (parameter set in the object creation function # createPoolScreenExpFromSE()) quantile_lims = seq(0, 1, FittingOptions(object)$IntervalFraction) # use unique(): in case there are many 0 the first intervals are merged limits <- unique(stats::quantile(refcounts(object), quantile_lims)) FittingIntervals(object) <- as.integer(limits) object } #' Fit paramters for skew normal distribution #' #' @param LFC logarithmic fold changes of gRNA counts #' @param quant1 lower quantile for least quantile of squares regression #' (default: 0.1) #' @param quant2 upper quantile for least quantile of squares regression #' (default: 0.9) #' #' @importFrom nloptr lbfgs #' @importFrom fGarch dsnorm #' #' @return fit_skewnorm #' @keywords internal fit_least_quantile <- function(LFC, quant1, quant2) { # log likelihood function of 90% most central LFC values ll_skewnorm <- function(x) { mean = x[1] sd = x[2] xi = x[3] # left skew normal distribution used for fit because # the data is skewed towards negative LFC r = fGarch::dsnorm(LFC, mean, sd, xi) quant10 <- stats::quantile(r, quant1, na.rm = TRUE) quant90 <- stats::quantile(r, quant2, na.rm = TRUE) r_quant <- r[r >= quant10 & r <= quant90] # abs() here is ok? -sum(log(abs(r_quant))) } # non-linear optimization fit_skewnorm <- nloptr::lbfgs(c(0, 1, 0.5), ll_skewnorm, lower = c(-2, 0, -2), upper = c(2, 2, 2)) fit_skewnorm } #' Calculate fit parameters for every subset of data #' #' @param object PoolScreenExp object #' @param quant1 lower quantile for least quantile of squares regression #' (default: 0.1) #' @param quant2 upper quantile for least quantile of squares regression #' (default: 0.9) #' #' @return object #' @keywords internal calculateIntervalFits <- function(object, quant1, quant2) { # one fit is done for every intervall because the skew is more important # for perturbaions with low initial counts limits <- FittingIntervals(object) # split counts into intervals needs to be done based on reference counts ! counts_for_fit <- as.vector(refcounts(object)) lfc_for_fit <- as.vector(samplelfc(object)) ncols <- length(lfc_for_fit)/length(counts_for_fit) refcount_mask <- rep(counts_for_fit, ncols) # for every count, determine lower interval limit fits <- matrix(nrow = (length(limits) - 1), ncol = 3) for (i in seq_len(length(limits) - 1)) { lfc_subset <- lfc_for_fit[refcount_mask > limits[i] & refcount_mask < limits[i + 1]] fits[i, ] <- fit_least_quantile(lfc_subset, quant1, quant2)$par } LFCModelParameters(object) <- fits message(""Fitted null distribution."") object } #' Calculate p-values #' #' @param object PoolScreenExp object #' #' @return object #' #' @importFrom fGarch psnorm #' @keywords internal calculatePValues <- function(object) { # p value matrix needs the same dimensions as coutn data dimensions <- dim(sgRNAData(object)) # empty matrix to be filled with pvalues assays(sgRNAData(object))$pval <- matrix( nrow = dimensions[1], ncol = dimensions[2]) # previously determined fits and corresponding lower count limits fits <- LFCModelParameters(object) limits <- FittingIntervals(object) for (i in seq_len(length(limits) - 1)) { # subset data according to count at T0 mask <- refcounts(object) >= limits[i] & refcounts(object) < limits[i + 1] # data format has to be matrix mask <- matrix(mask, nrow = dimensions[1], ncol = dimensions[2]) # assign actual p values from fit assays(sgRNAData(object))$pval[mask] <- fGarch::psnorm( assays(sgRNAData(object))$lfc[mask], fits[i, 1], fits[i, 2], fits[i, 3]) } message(""Calculated p-values at gRNA level."") object } ","R" "CRISPR","imkeller/gscreend","R/DataInput.R",".R","2998","83","#' Create PoolScreenExp Experiment #' #' @param data Input data object containing gRNA level data #' (SummarizedExperiment) #' #' @return object PoolScreenExp object #' @export #' #' @examples raw_counts <- read.table( #' system.file('extdata', 'simulated_counts.txt', #' package = 'gscreend'), #' header=TRUE) #' #'counts_matrix <- cbind(raw_counts$library0, raw_counts$R0_0, raw_counts$R1_0) #' #'rowData <- data.frame(sgRNA_id = raw_counts$sgrna_id, #'gene = raw_counts$Gene) #' #'colData <- data.frame(samplename = c('library', 'R1', 'R2'), #'timepoint = c('T0', 'T1', 'T1')) #' #'library(SummarizedExperiment) #'se <- SummarizedExperiment(assays=list(counts=counts_matrix), #'rowData=rowData, colData=colData) #' #'# create a PoolScreenExp experiment #'pse <- createPoolScreenExp(se) #' #' @importFrom methods is createPoolScreenExp <- function(data) { if (is(data, ""SummarizedExperiment"")) { message( ""Creating PoolScreenExp object from a SummarizedExperiment object."" ) object <- createPoolScreenExpFromSE(data) object } else { stop( ""Error: input data is not of the suported input format: "", ""SummarizedExperiment."") } } #' Create PoolScreenExp Experiment from summarized experiment #' #' @param data SummarizedExperiment object containing gRNA level data #' #' @return object #' #' @importFrom methods new #' @keywords internal createPoolScreenExpFromSE <- function(data) { object <- new(""PoolScreenExp"") # Check whether reference and sample are named correctly checksum_ref <- sum(data$timepoint == ""T0"") checksum_sample <- sum(data$timepoint == ""T1"") if (checksum_ref != 1) { stop(""gscreend is currently only implemented"", ""for usage of one reference (T0). "", ""You are using "", checksum_ref, "" references."") } else if (checksum_sample < 1) { stop(""There is no sample T1."") } else if (checksum_sample + checksum_ref != length(data$timepoint)) { stop(""Timepoints can be named T0 or T1 only. "", ""One or more of your timepoints is names differently."") } else {message(""References and samples are named correctly."")} # Check whether rownames are correct if (!is.element(""sgRNA_id"", colnames(rowData(data)))) { stop(""The rowData of SummarizedExperiment needs to contain a column named \""sgRNA_id\"". "", ""The columns you provided are: "", paste(colnames(rowData(data)), "" "")) } else if (!is.element(""gene"", colnames(rowData(data)))) { stop(""The rowData of SummarizedExperiment needs to contain a column named \""gene\"". "", ""The columns you provided are: "", paste(colnames(rowData(data)), "" "")) } else {message(""Data concerning sgRNA and genes is provided."")} sgRNAData(object) <- data FittingOptions(object) <- list(IntervalFraction = 0.1) object } ","R" "CRISPR","imkeller/gscreend","R/GeneRanking.R",".R","4370","128","# This method is adapted from Li et al. and others. But I have # to write it from scratch because there is no available R package # on CRAN or Bioconductor # helper functions, according to definition in Li et al. # probability needs to be transformed by beta distribution alphaBeta <- function(p_test) { p_test <- sort(p_test) n <- length(p_test) min(stats::pbeta(p_test, seq_len(n), n - seq_len(n) + 1)) } # calculate rho value makeRhoNull <- function(n, p, nperm) { # if perm_genes = 10 we want to split the permutations into 5 processes n_processes <- 4 rhonull <- BiocParallel::bplapply(seq_len(n_processes), function(x) { vapply(seq_len(nperm/n_processes), function(x) {alphaBeta(sample(p, n, replace = FALSE))}, FUN.VALUE = numeric(1)) } ) unlist(rhonull) } calculateGenePval <- function(pvals, genes, alpha_cutoff, # permutations = perm_genes * genes perm_genes = 8) { cut.pvals <- pvals <= alpha_cutoff # ranking and scoring according to pvalues score_vals <- rank(pvals)/length(pvals) score_vals[!cut.pvals] <- as.numeric(1) # calculate rho for every count gene rho <- unsplit(vapply(split(score_vals, genes), FUN = alphaBeta, FUN.VALUE = numeric(1)), genes) guides_per_gene <- sort(unique(table(genes))) # store this as model parameter permutations <- perm_genes * nrow(unique(genes)) # this does not need to be parallelized because its calling # a function that is already serialized # this is the step that takes longest to complete rho_nullh <- vapply(guides_per_gene, FUN = makeRhoNull, p = score_vals, nperm = permutations, FUN.VALUE = numeric(permutations)) # Split by gene, make comparison with null model # from makeRhoNull, and unsplit by gene # this is faster than using the Bioc::Parallel option pvalue_gene <- vapply(split(rho, genes), function(x) { n_sgrnas = length(x) mean(rho_nullh[, guides_per_gene == n_sgrnas] <= x[[1]]) }, FUN.VALUE = numeric(1)) pvalue_gene } calculateGeneLFC <- function(lfcs_sgRNAs, genes) { # Gena LFC : mean LFC of sgRNAs vapply(split(lfcs_sgRNAs, genes), FUN = mean, FUN.VALUE = numeric(1)) } #' Calculate gene rank #' #' @param object PoolScreenExp object #' @param alpha_cutoff alpha cutoff for alpha-RRA (default: 0.05) #' #' @return object #' @keywords internal assignGeneData <- function(object, alpha_cutoff) { message(""Ranking genes..."") # p-values for neg LFC were calculated from model pvals_neg <- samplepval(object) # p-values for pos LFC: 1 - neg.pval pvals_pos <- 1 - samplepval(object) # genes (append gene list as many times as replicates) n_repl <- dim(pvals_neg)[2] genes <- do.call(""rbind"", replicate(n_repl, data.frame(gene = rowData(sgRNAData(object))$gene), simplify = FALSE)) # calculate pvalues message(""... for positive fold changes"") gene_pval_neg <- calculateGenePval(pvals_neg, genes, alpha_cutoff) message(""... for negative fold changes"") gene_pval_pos <- calculateGenePval(pvals_pos, genes, alpha_cutoff) # calculate fdrs from pvalues fdr_gene_neg <- stats::p.adjust(gene_pval_neg, method = ""fdr"") fdr_gene_pos <- stats::p.adjust(gene_pval_pos, method = ""fdr"") # calculate gene lfc lfcs_sgRNAs <- samplelfc(object) gene_lfc <- calculateGeneLFC(lfcs_sgRNAs, genes) # build new summarized experiment for the GeneData slot # assuming that gene order is same in neg and pos rowData <- data.frame(gene = names(gene_pval_neg)) colData <- data.frame(samplename = c(""T1""), timepoint = c(""T1"")) # build a summarized experiment that contains p values and fdrs GeneData(object) <- SummarizedExperiment( assays = list(pvalue_neg = as.matrix(gene_pval_neg), fdr_neg = as.matrix(fdr_gene_neg), pvalue_pos = as.matrix(gene_pval_pos), fdr_pos = as.matrix(fdr_gene_pos), lfc = as.matrix(gene_lfc)), rowData = rowData, colData = colData) message(""gscreend analysis has been completed."") object } ","R" "CRISPR","imkeller/gscreend","R/AllMethods.R",".R","4217","147","#' Accessor function for the sgRNA slot of the PoolScreenExp class #' #' @param x PoolScreenExp object #' #' @return sgRNA slot of the object #' @export #' #' @examples # import a PoolScreenExp object that has been generated using #' # RunGscreend() #' pse_an <- readRDS( #' system.file('extdata', 'gscreend_analysed_experiment.RData', #' package = 'gscreend')) #' #' sgRNAData(pse_an) #' setMethod(""sgRNAData"", ""PoolScreenExp"", function(x) { # I assume I am allowed to use the # direct slot access here, because there is no other way? se <- x@sgRNAData se }) # Write into the sgRNA slot setReplaceMethod(""sgRNAData"", ""PoolScreenExp"", function(x, value) { # I assume I am allowed to use the # direct slot access here, because there is no other way? x@sgRNAData <- value x }) #' Accessor function for the Gene slot of the PoolScreenExp class #' #' @param x PoolScreenExp object #' #' @return Gene slot of the object #' @export #' #' @examples # import a PoolScreenExp object that has been generated using #' # RunGscreend() #' pse_an <- readRDS( #' system.file('extdata', 'gscreend_analysed_experiment.RData', #' package = 'gscreend')) #' #' GeneData(pse_an) #' setMethod(""GeneData"", ""PoolScreenExp"", function(x) { # I assume I am allowed to use the # direct slot access here, because there is no other way? se <- x@GeneData se }) # Write into the Gene slot setReplaceMethod(""GeneData"", ""PoolScreenExp"", function(x, value) { # I assume I am allowed to use the # direct slot access here, because there is no other way? x@GeneData <- value x }) # Fitting options slot setMethod(""FittingOptions"", ""PoolScreenExp"", function(x) { # I assume I am allowed to use the # direct slot access here, because there is no other way? se <- x@FittingOptions se }) setReplaceMethod(""FittingOptions"", ""PoolScreenExp"", function(x, value) { # I assume I am allowed to use the # direct slot access here, because there is no other way? x@FittingOptions <- value x }) # Fitting intervals slot setMethod(""FittingIntervals"", ""PoolScreenExp"", function(x) { # I assume I am allowed to use the # direct slot access here, because there is no other way? se <- x@FittingIntervals se }) setReplaceMethod(""FittingIntervals"", ""PoolScreenExp"", function(x, value) { # I assume I am allowed to use the # direct slot access here, because there is no other way? x@FittingIntervals <- value x }) # slot containing fitted parameters setMethod(""LFCModelParameters"", ""PoolScreenExp"", function(x) { # I assume I am allowed to use the # direct slot access here, because there is no other way? se <- x@LFCModelParameters se }) setReplaceMethod(""LFCModelParameters"", ""PoolScreenExp"", function(x, value) { # I assume I am allowed to use the # direct slot access here, because there is no other way? x@LFCModelParameters <- value x }) setMethod(""normcounts"", ""PoolScreenExp"", function(x) assays(sgRNAData(x))$normcounts) setMethod(""normcounts<-"", ""PoolScreenExp"", function(x, value) { assays(sgRNAData(x))$normcounts <- value x }) # get the reference counts for LFC calculation setMethod(""refcounts"", ""PoolScreenExp"", function(x) { se <- sgRNAData(x) # filter to get T0 samples assays(se[, se$timepoint == ""T0""])$normcounts }) # get the reference counts for LFC calculation setMethod(""samplecounts"", ""PoolScreenExp"", function(x) { se <- sgRNAData(x) # filter to get T0 samples # names have to be checked upon input assays(se[, se$timepoint == ""T1""])$normcounts }) setMethod(""samplelfc"", ""PoolScreenExp"", function(x) { se <- sgRNAData(x) # filter to get T0 samples # names have to be checked upon input assays(se[, se$timepoint == ""T1""])$lfc }) setMethod(""samplelfc"", ""PoolScreenExp"", function(x) { se <- sgRNAData(x) # filter to get T0 samples # names have to be checked upon input assays(se[, se$timepoint == ""T1""])$lfc }) setMethod(""samplepval"", ""PoolScreenExp"", function(x) { se <- sgRNAData(x) # filter to get T0 samples # names have to be checked upon input assays(se[, se$timepoint == ""T1""])$pval }) ","R" "CRISPR","imkeller/gscreend","R/AllClasses.R",".R","1083","30","#' @title Class to store pooled CRISPR screening experiment #' @description #' The \code{poolScreenExp} class is an S4 class used to store #' sgRNA and gene related data as well as parameters necessary #' for statistical model. #' #' @import SummarizedExperiment #' #' @slot sgRNAData A SummarizedExperiment containing #' the data related to sgRNAs. #' @slot FittingIntervals A vector defining the limits of the #' intervals used for fitting of null model. #' @slot LFCModelParameters A vector of parameters estimated #' when fitting the null model. #' @slot GeneData SummarizedExperiment containing the #' data related to genes. #' @slot FittingOptions A named list with options for fitting: #' IntervalFraction - fraction of sgRNAs used in every #' fitting interval (default 0.1), #' alphaCutoff - alpha cutoff for alpha RRA algorithm (default: 0.05). #' @export #' setClass(""PoolScreenExp"", slots = c( sgRNAData = ""SummarizedExperiment"", FittingIntervals = ""vector"", LFCModelParameters = ""matrix"", GeneData = ""SummarizedExperiment"", FittingOptions = ""list"") ) ","R" "CRISPR","imkeller/gscreend","tests/testthat.R",".R","60","5","library(testthat) library(gscreend) test_check(""gscreend"") ","R" "CRISPR","imkeller/gscreend","tests/testthat/test_1_input.R",".R","1830","46","context(""1 - Data input and generate SummarizedExperiment"") test_that(""createPoolScreenExp() throws error without valid input"", { expect_error(createPoolScreenExp(1:10)) }) test_that(""createPoolScreenExpFromSE() throws error when sample names are not as correct"", { raw_counts <- read.table( system.file('extdata', 'simulated_counts.txt', package = 'gscreend'), header=TRUE) # 1 # more than one reference sample T0 counts_matrix <- cbind(raw_counts$library0, raw_counts$R0_0, raw_counts$R1_0) rowData <- data.frame(sgRNA_id = raw_counts$sgrna_id, gene = raw_counts$Gene) colData_wrong1 <- data.frame(samplename = c('library', 'R1', 'R2'), timepoint = c('T0', 'T0', 'T1')) se_wrong1 <- SummarizedExperiment(assays=list(counts=counts_matrix), rowData=rowData, colData=colData_wrong1) # create a PoolScreenExp experiment expect_error(createPoolScreenExpFromSE(se_wrong1)) # 2 # wrong name colData_wrong2 <- data.frame(samplename = c('library', 'R1', 'R2'), timepoint = c('T0', 'T1', 'Wrong')) se_wrong2 <- SummarizedExperiment(assays=list(counts=counts_matrix), rowData=rowData, colData=colData_wrong2) # create a PoolScreenExp experiment expect_error(createPoolScreenExpFromSE(se_wrong2)) # 3 # no sample T1 counts_matrix_wrong3 <- cbind(raw_counts$library0) colData_wrong3 <- data.frame(samplename = c('library'), timepoint = c('T0')) se_wrong3 <- SummarizedExperiment(assays=list(counts=counts_matrix_wrong3), rowData=rowData, colData=colData_wrong3) # create a PoolScreenExp experiment expect_error(createPoolScreenExpFromSE(se_wrong3)) }) ","R" "CRISPR","imkeller/gscreend","tests/testthat/test_3_calculations.R",".R","166","6","context(""3 - Functions used for calculating statistics"") test_that(""alphaBeta() returns a numeric value"", { expect_is(alphaBeta(c(0.1, 0.2, 0.3)), ""numeric"") }) ","R" "CRISPR","imkeller/gscreend","tests/testthat/test_2_QC.R",".R","605","17","context(""2 - Quality control functions"") test_that(""plotReplicateCorrelation() throws error when replicate names are not known"", { pse_an <- readRDS( system.file('extdata', 'gscreend_analysed_experiment.RData', package = 'gscreend')) expect_error(plotReplicateCorrelation(pse_an, rep1 = ""wrong"", rep2 = ""R2"")) }) test_that(""ResultsTable() throws error when direction is wrong"", { pse_an <- readRDS( system.file('extdata', 'gscreend_analysed_experiment.RData', package = 'gscreend')) expect_error(ResultsTable(pse_an, direction = ""wrong"")) }) ","R"