# for emacs: -*- mode: sh; -*-

# This file describes the browser build for
#     Trichuris suis/whipworm WS245 version

##############################################################################
# download sequence, create UCSC sequence (DONE - 2015-06-24 - Hiram)
    # both the genbank and the WormBase releases are identical
    mkdir -p /hive/data/genomes/triSui1/genbank
    cd /hive/data/genomes/triSui1/genbank

    time rsync -L -a -P \
rsync://ftp.ncbi.nlm.nih.gov/genomes/genbank/invertebrate/Trichinella_spiralis/all_assembly_versions/GCA_000181795.2_Trichinella_spiralis-3.7.1/ ./
# sent 394 bytes  received 81911524 bytes  7122775.48 bytes/sec
# total size is 81899323  speedup is 1.00
# real    0m10.375s

    mkdir -p /hive/data/genomes/triSui1/ws245
    cd /hive/data/genomes/triSui1/ws245

    wget --no-parent --timestamping -m -nH --cut-dirs=6 \
ftp://ftp.sanger.ac.uk/pub/wormbase/releases/WS245/species/PRJNA208415
    wget --no-parent --timestamping -m -nH --cut-dirs=6 \
ftp://ftp.sanger.ac.uk/pub/wormbase/releases/WS245/species/PRJNA208416

    mkdir /hive/data/genomes/triSui1/ucsc
    cd /hive/data/genomes/triSui1/ucsc

    zcat ../genbank/GCA_000701005.1_Tsuis_adult_male_v1.0_assembly_structure/Primary_Assembly/unplaced_scaffolds/FASTA/unplaced.scaf.fna.gz \
        | sed -e 's/.1 Trichuris .*/v1/;' | gzip -c > triSui1.fa.gz

    zcat ../genbank/GCA_000701005.1_Tsuis_adult_male_v1.0_assembly_structure/Primary_Assembly/unplaced_scaffolds/AGP/unplaced.scaf.agp.gz \
      | sed -e 's/\.1/v1/;' > triSui1.agp

    # obtain photo, CDC public domain photo
    mkdir /hive/data/genomes/triSui1/photo
    cd /hive/data/genomes/triSui1/photo
    wget --timestamping \
http://www.cdc.gov/parasites/images/whipworm/home_page_image_whipworm.jpg
    convert -geometry 400x300 home_page_image_whipworm.jpg Trichuris_suis.jpg

    # check into source tree
    #   src/hg/htdocs/images/Trichuris_suis.jpg
    # and copy to /usr/local/apache/htdocs/images/Trichuris_suis.jpg

#############################################################################
#  Initial database build (DONE - 2015-07-10 - Hiram)

    cd /hive/data/genomes/triSui1
    cat << '_EOF_' > triSui1.config.ra
# Config parameters for makeGenomeDb.pl:
db triSui1
clade worm
genomeCladePriority 68
scientificName Trichuris suis
commonName Whipworm
assemblyDate Jul. 2014
assemblyLabel University of Melboure T. suis (male) genome project
assemblyShortLabel WS243/T. suis DCEP-RM93M male
orderKey 23200
mitoAcc GU070737.1
fastaFiles /hive/data/genomes/triSui1/ucsc/triSui1.fa.gz
agpFiles /hive/data/genomes/triSui1/ucsc/triSui1.agp
# qualFiles none
dbDbSpeciesDir worm
photoCreditURL http://www.cdc.gov/parasites/whipworm/
photoCreditName Centers for Disease Control and Prevention
ncbiGenomeId 13427
ncbiAssemblyId 205451
ncbiAssemblyName WS243/Tsuis_adult_male_v1.0
ncbiBioProject 208415
genBankAccessionID GCA_000701005.1
taxId 68888
'_EOF_'
    # << happy emacs

    # verify sequence and AGP are OK:
    time (makeGenomeDb.pl -workhorse=hgwdev -dbHost=hgwdev -fileServer=hgwdev \
         -stop=agp triSui1.config.ra) > agp.log 2>&1
    # *** All done!  (through the 'agp' step)
    # real    0m20.536s

    # then finish it off:
    time (makeGenomeDb.pl -workhorse=hgwdev -dbHost=hgwdev \
       -fileServer=hgwdev -continue=db triSui1.config.ra) > db.log 2>&1
    # real    0m53.141s

    # check in the trackDb files created and add to trackDb/makefile

##############################################################################
# cpgIslands on UNMASKED sequence (DONE - 2015-07-10 - Hiram)
    mkdir /hive/data/genomes/triSui1/bed/cpgIslandsUnmasked
    cd /hive/data/genomes/triSui1/bed/cpgIslandsUnmasked

    time (doCpgIslands.pl -dbHost=hgwdev -bigClusterHub=ku -buildDir=`pwd` \
       -tableName=cpgIslandExtUnmasked \
          -maskedSeq=/hive/data/genomes/triSui1/triSui1.unmasked.2bit \
             -workhorse=hgwdev -smallClusterHub=ku triSui1) > do.log 2>&1
    # real    4m37.436s

    cat fb.triSui1.cpgIslandExtUnmasked.txt
    # 4053516 bases of 71825323 (5.644%) in intersection

#############################################################################
# cytoBandIdeo - (DONE - 2015-07-10 - Hiram)
    mkdir /hive/data/genomes/triSui1/bed/cytoBand
    cd /hive/data/genomes/triSui1/bed/cytoBand
    makeCytoBandIdeo.csh triSui1

#########################################################################
# ucscToINSDC table/track (DONE - 2015-07-10 - Hiram)
    mkdir /hive/data/genomes/triSui1/bed/ucscToINSDC
    cd /hive/data/genomes/triSui1/bed/ucscToINSDC

    # find the chrM accession:
    grep chrM ../../*.agp
# chrM    1       14436   2       F       GU070737.1      1       14436   +

    # use that as the second argument here:
    ~/kent/src/hg/utils/automation/ucscToINSDC.sh \
       ../../genbank/GCA_000701005.1_Tsuis_adult_male_v1.0_assembly_structure/Primary_Assembly GU070737.1

    awk '{printf "%s\t0\t%d\n", $1,$2}' ../../chrom.sizes \
         | sort > name.coordinate.tab
    join name.coordinate.tab ucscToINSDC.txt | tr '[ ]' '[\t]' \
         > ucscToINSDC.bed
    # verify all names are coming through, should be same line count:
    wc -l *
    #  4293 name.coordinate.tab
    #  4293 ucscToINSDC.bed
    #  4293 ucscToINSDC.txt

    cut -f1 ucscToINSDC.bed | awk '{print length($0)}' | sort -n | tail -1
    # 10
    # use the 10 in this sed
    sed -e "s/21/10/" $HOME/kent/src/hg/lib/ucscToINSDC.sql \
         | hgLoadSqlTab triSui1 ucscToINSDC stdin ucscToINSDC.bed
    checkTableCoords triSui1
    # should cover %100 entirely:
    featureBits -countGaps triSui1 ucscToINSDC
    # 74248995 bases of 74248995 (100.000%) in intersection

#########################################################################
# fixup search rule for assembly track/gold table (DONE - 2015-07-10 - Hiram)
    hgsql -N -e "select frag from gold;" triSui1 | sort | head -3
GU070737.1
JMHY01000001.1
JMHY01000002.1

    hgsql -N -e "select frag from gold;" triSui1 | sort | tail -2
JMHY01006464.1
JMHY01006465.1

    # verify this rule will find them all or eliminate them all:
    hgsql -N -e "select frag from gold;" triSui1 | wc -l
    # 6466

    hgsql -N -e "select frag from gold;" triSui1 \
      | egrep -e '(GU070737|JMHY0100)[0-9]*(\.1)?' | wc -l
    # 6466

    hgsql -N -e "select frag from gold;" triSui1 \
      | egrep -v -e '(GU070737|JMHY0100)[0-9]*(\.1)?' | wc -l
    # 0

    # hence, add to trackDb/worm/triSui1/trackDb.ra
searchTable gold
shortCircuit 1
termRegex (GU070737|JMHY0100)[0-9]*(\.1)?
query select chrom,chromStart,chromEnd,frag from %s where frag like '%s%%'
searchPriority 8

##########################################################################
# running repeat masker (DONE - 2015-07-10 - Hiram)
    mkdir /hive/data/genomes/triSui1/bed/repeatMasker
    cd /hive/data/genomes/triSui1/bed/repeatMasker
    time (doRepeatMasker.pl -buildDir=`pwd` \
        -bigClusterHub=ku -dbHost=hgwdev -workhorse=hgwdev \
        -smallClusterHub=ku triSui1) > do.log 2>&1
    # real    153m32.056s

    cat faSize.rmsk.txt
    # 74248995 bases (2423806 N's 71825189 real 71306874 upper 518315 lower)
    #    in 4293 sequences in 1 files
    # Total size: mean 17295.4 sd 100439.5 min 201 (KL367473v1)
    #    max 1594463 (KL363182v1) median 314
    # %0.70 masked total, %0.72 masked real

    egrep -i "versi|relea" do.log
    # RepeatMasker version open-4.0.5
    #    January 31 2015 (open-4-0-5) version of RepeatMasker
    # CC   RELEASE 20140131;

    time featureBits -countGaps triSui1 rmsk
    # 518334 bases of 74248995 (0.698%) in intersection
    # real    0m1.256s

##########################################################################
# running simple repeat (DONE - 2015-07-10 - Hiram)
    mkdir /hive/data/genomes/triSui1/bed/simpleRepeat
    cd /hive/data/genomes/triSui1/bed/simpleRepeat
    time (doSimpleRepeat.pl -buildDir=`pwd` -bigClusterHub=ku \
        -dbHost=hgwdev -workhorse=hgwdev -smallClusterHub=ku \
        triSui1) > do.log 2>&1
    # real    3m56.113s

    cat fb.simpleRepeat
    # 1984238 bases of 71825323 (2.763%) in intersection

    # using the Window Masker result as indicated below

##########################################################################
# CREATE MICROSAT TRACK (DONE - 2015-07-15 - Hiram)
     ssh hgwdev
     mkdir /cluster/data/triSui1/bed/microsat
     cd /cluster/data/triSui1/bed/microsat
     awk '($5==2 || $5==3) && $6 >= 15 && $8 == 100 && $9 == 0 {printf("%s\t%s\t%s\t%dx%s\n", $1, $2, $3, $6, $16);}' \
	../simpleRepeat/simpleRepeat.bed > microsat.bed
    hgLoadBed triSui1 microsat microsat.bed
    #	Read 310 elements of size 4 from microsat.bed

##########################################################################
## WINDOWMASKER (DONE - 2015-07-15 - Hiram)
    mkdir /hive/data/genomes/triSui1/bed/windowMasker
    cd /hive/data/genomes/triSui1/bed/windowMasker
    time (doWindowMasker.pl -buildDir=`pwd` -workhorse=hgwdev \
        -dbHost=hgwdev triSui1) > do.log 2>&1
    # real    3m14.998s

    # Masking statistics
    cat faSize.triSui1.cleanWMSdust.txt
    # 74248995 bases (2423806 N's 71825189 real 62955556 upper 8869633 lower)
    #    in 4293 sequences in 1 files
    # Total size: mean 17295.4 sd 100439.5 min 201 (KL367473v1)
    #    max 1594463 (KL363182v1) median 314
    # %11.95 masked total, %12.35 masked real

    cat fb.triSui1.rmsk.windowmaskerSdust.txt
    # 410663 bases of 74248995 (0.553%) in intersection

    # using this Window Masker result for final masking::
    cd /hive/data/genomes/triSui1
    #   you can safely ignore the warning about fields >= 13
    twoBitMask bed/windowMasker/triSui1.cleanWMSdust.2bit \
       -add bed/simpleRepeat/trfMask.bed  triSui1.2bit

    # measure the final masking:
    twoBitToFa triSui1.2bit stdout | faSize stdin > faSize.triSui1.2bit.txt
    cat faSize.triSui1.2bit.txt
    # 74248995 bases (2423806 N's 71825189 real 62949616 upper 8875573 lower)
    #    in 4293 sequences in 1 files
    # Total size: mean 17295.4 sd 100439.5 min 201 (KL367473v1)
    #    max 1594463 (KL363182v1) median 314
    # %11.95 masked total, %12.36 masked real

    # and reset the symlink
    rm /gbdb/triSui1/triSui1.2bit
    ln -s /hive/data/genomes/triSui1/triSui1.2bit /gbdb/triSui1/triSui1.2bit

##########################################################################
# cpgIslands - (DONE - 2015-07-15 - Hiram)
    mkdir /hive/data/genomes/triSui1/bed/cpgIslands
    cd /hive/data/genomes/triSui1/bed/cpgIslands
    time (doCpgIslands.pl -dbHost=hgwdev -bigClusterHub=ku \
      -workhorse=hgwdev -smallClusterHub=ku triSui1) > do.log 2>&1 &
    # real    55m19.060s

    cat fb.triSui1.cpgIslandExt.txt
    # 3089138 bases of 71825323 (4.301%) in intersection

#########################################################################
# augustus - (DONE - 2015-07-15 - Hiram)
    mkdir /hive/data/genomes/triSui1/bed/augustus
    cd /hive/data/genomes/triSui1/bed/augustus
    #  XXX this is not specifically correct, the species caenorhabditis
    #      is not necessarily accurate here
    time (doAugustus.pl -buildDir=`pwd` -bigClusterHub=ku \
      -species=caenorhabditis -dbHost=hgwdev \
         -workhorse=hgwdev triSui1) > do.log 2>&1 &
    # real    39m50.787s

    cat fb.triSui1.augustusGene.txt
    # 15594049 bases of 71825323 (21.711%) in intersection

#########################################################################
# genscan - (DONE - 2015-07-15 - Hiram)
    mkdir /hive/data/genomes/triSui1/bed/genscan
    cd /hive/data/genomes/triSui1/bed/genscan
    time (doGenscan.pl -buildDir=`pwd` -workhorse=hgwdev -dbHost=hgwdev \
      -bigClusterHub=ku triSui1) > do.log 2>&1
    # real    45m29.041s

    cat fb.triSui1.genscan.txt
    #   9305968 bases of 71825323 (12.956%) in intersection

    cat fb.triSui1.genscanSubopt.txt
    #   7502974 bases of 71825323 (10.446%) in intersection

########################################################################
# Create kluster run files (TBD - 2015-07-08 - Hiram)

    cd /hive/data/genomes/triSui1
    # numerator is triSui1 gapless bases "real" as reported by:
    head -1 faSize.triSui1.2bit.txt
# 94076581 bases (7759220 N's 86317361 real 53341517 upper 32975844 lower)
#    in 9780 sequences in 1 files
    # numerator is 'real' base count
    # denominator is hg19 gapless bases as reported by:
    #   featureBits -noRandom -noHap hg19 gap
    #     234344806 bases of 2861349177 (8.190%) in intersection
    # 1024 is threshold used for human -repMatch:
    calc \( 86317361 / 2861349177 \) \* 1024
    # ( 86317361 / 2861349177 ) * 1024 = 30.890665

    # ==> use -repMatch=100 since 30 or 50 masks too much
    cd /hive/data/genomes/triSui1
    time blat triSui1.2bit \
         /dev/null /dev/null -tileSize=11 -makeOoc=jkStuff/triSui1.11.ooc \
        -repMatch=100
    # Wrote 8527 overused 11-mers to jkStuff/triSui1.11.ooc
    #  real    0m1.846s

    # there are a few non-bridged gaps
    #   check non-bridged gaps to see what the typical size is:
    hgsql -N -e 'select * from gap where bridge="no" order by size;' triSui1 \
       | ave -tableOut -col=7 stdin
# min Q1 median Q3 max mean N sum stddev
# 78831 79056 79362 79503 79503 79162.5 4 316650 320.991

    # note the minimum non-bridged gap size is 78,831
    gapToLift -verbose=2 -minGap=50000 triSui1 jkStuff/triSui1.nonBridged.lft \
         -bedFile=jkStuff/triSui1.nonBridged.bed

    # survey sizes:
    n50.pl chrom.sizes
#       reading: chrom.sizes
#       contig count: 9780, total size: 94076581, one half size: 47038290
# cumulative    N50 count       contig  contig size
# 46960459        61      Bmal_v3_scaffold61      194773
# 47038290 one half size
# 47151548        62      Bmal_v3_scaffold62      191089

#############################################################################
# GENBANK AUTO UPDATE (TBD - 2015-06-09 - Hiram)
    ssh hgwdev
    cd $HOME/kent/src/hg/makeDb/genbank
    git pull
    # /cluster/data/genbank/data/organism.lst shows:
    # #organism               mrnaCnt estCnt  refSeqCnt
    #  Pristionchus pacificus  97      37470   0

    # edit etc/genbank.conf to add triSui1 just before priPac1

# triSui1 (P. pacificus)
triSui1.serverGenome = /hive/data/genomes/triSui1/triSui1.2bit
triSui1.clusterGenome = /hive/data/genomes/triSui1/triSui1.2bit
triSui1.ooc = /hive/data/genomes/triSui1/jkStuff/triSui1.11.ooc
triSui1.lift = /hive/data/genomes/triSui1/jkStuff/triSui1.nonBridged.lft
triSui1.refseq.mrna.native.pslCDnaFilter  = ${ordered.refseq.mrna.native.pslCDnaFilter}
triSui1.refseq.mrna.xeno.pslCDnaFilter    = ${ordered.refseq.mrna.xeno.pslCDnaFilter}
triSui1.genbank.mrna.native.pslCDnaFilter = ${ordered.genbank.mrna.native.pslCDnaFilter}
triSui1.genbank.mrna.xeno.pslCDnaFilter   = ${ordered.genbank.mrna.xeno.pslCDnaFilter}
triSui1.genbank.est.native.pslCDnaFilter  = ${ordered.genbank.est.native.pslCDnaFilter}
triSui1.refseq.mrna.native.load = yes
triSui1.refseq.mrna.xeno.load  = yes
triSui1.refseq.mrna.xeno.loadDesc = yes
# DO NOT NEED genbank.mrna.xeno except for human, mouse
triSui1.genbank.mrna.xeno.load = no
triSui1.genbank.est.native.load = yes
triSui1.genbank.est.native.loadDesc = no
triSui1.downloadDir = triSui1
triSui1.perChromTables = no

    git commit -m "Added triSui1 - P. pacificus refs #15209" etc/genbank.conf
    git push
    # update /cluster/data/genbank/etc/:
    make etc-update

    screen      #  control this business with a screen since it takes a while
    cd /cluster/data/genbank

    time ./bin/gbAlignStep -initial triSui1
    # logFile: var/build/logs/2015.07.02-11:39:01.triSui1.initalign.log
    # real    91m20.362s

    #   To re-do, rm the dir first:
    #     /cluster/data/genbank/work/initial.triSui1

    # load database when finished
    ssh hgwdev
    cd /cluster/data/genbank
    time ./bin/gbDbLoadStep -drop -initialLoad triSui1
    # logFile: var/dbload/hgwdev/logs/2015.07.06-09:51:31.triSui1.dbload.log
    # real    18m34.687s

    # enable daily alignment and update of hgwdev
    cd ~/kent/src/hg/makeDb/genbank
    git pull
    # add triSui1 to:
    #   vi etc/align.dbs etc/hgwdev.dbs
    git commit -m "Added triSui1 - Pristionchus pacificus refs #15209" \
      etc/align.dbs etc/hgwdev.dbs
    git push
    make etc-update

#########################################################################
# all.joiner update, downloads and in pushQ - (TBD - 2015-06-22 - Hiram)
    cd $HOME/kent/src/hg/makeDb/schema
    # fixup all.joiner until this is a clean output
    joinerCheck -database=triSui1 -tableCoverage all.joiner
    joinerCheck -database=triSui1 -times all.joiner
    joinerCheck -database=triSui1 -keys all.joiner

    cd /hive/data/genomes/triSui1
    time makeDownloads.pl triSui1 > downloads.log 2>&1
    # real    13m42.027s

    #   now ready for pushQ entry
    mkdir /hive/data/genomes/triSui1/pushQ
    cd /hive/data/genomes/triSui1/pushQ
    makePushQSql.pl triSui1 > triSui1.pushQ.sql 2> stderr.out
    #   check for errors in stderr.out, some are OK, e.g.:
    # WARNING: hgwdev does not have /gbdb/triSui1/wib/gc5Base.wib
    # WARNING: hgwdev does not have /gbdb/triSui1/wib/quality.wib
    # WARNING: hgwdev does not have /gbdb/triSui1/bbi/qualityBw/quality.bw
    # WARNING: triSui1 does not have seq
    # WARNING: triSui1 does not have extFile
    # WARNING: triSui1 does not have estOrientInfo
    # WARNING: triSui1 does not have mrnaOrientInfo

    #   copy it to hgwbeta
    scp -p triSui1.pushQ.sql qateam@hgwbeta:/tmp
    ssh qateam@hgwbeta "./bin/x86_64/hgsql qapushq < /tmp/triSui1.pushQ.sql"

    #   in that pushQ entry walk through each entry and see if the
    #   sizes will set properly

#############################################################################
