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

# This file describes how the browser for C. malayi WS245 version is built

##############################################################################
# download sequence, create UCSC sequence (DONE - 2015-07-07 - Hiram)
    mkdir -p /hive/data/genomes/bruMal2/ws245
    cd /hive/data/genomes/bruMal2/ws245

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

    mkdir /hive/data/genomes/bruMal2/ucsc
    cd /hive/data/genomes/bruMal2/ucsc
    # WormBase contig names are of the pattern:
# >Bmal_v3_scaffold1
# >Bmal_v3_scaffold2
# >Bmal_v3_scaffold3
#   ...

    # no conversion of names to maintain equivalence with WormBase:
    zcat ../ws245/PRJNA10729/b_malayi.PRJNA10729.WS245.genomic.fa.gz \
        | gzip -c > bruMal2.fa.gz

    hgFakeAgp bruMal2.fa.gz bruMal2.agp

    # rerun this assembly, adding in the wolbachia sequence 2015-08-11
    mkdir  /hive/data/genomes/bruMal2/wolbachia
    rsync -L -a -P \
rsync://ftp.ncbi.nlm.nih.gov/genomes/all/GCA_000008385.1_ASM838v1/ ./GCA_000008385.1/

    zcat GCA_000008385.1/GCA_000008385.1_ASM838v1_genomic.fna.gz | sed -e 's/^>.*/>wolbachia/;' | gzip -c > ../ucsc/wolbachia.fa.gz

    # find the accession from the fna.gz file:
    zcat GCA_000008385.1/GCA_000008385.1_ASM838v1_genomic.fna.gz | head -1
>AE017321.1 Wolbachia endosymbiont strain TRS of Brugia malayi, complete genome

    # and the size
    faSize ../ucsc/wolbachia.fa.gz
    # use those values in this echo statement:
    echo -e 'wolbachia\t1\t1080084\t1\tF\tAE017321.1\t1\t1080084\t+' \
       > ../ucsc/wolbachia.agp

    # obtain photo from CDC
    mkdir /hive/data/genomes/bruMal2/photo
    wget --timestamping \
http://www.cdc.gov/dpdx/images/lymphaticFilariasis/Brugia_malayi.jpg
    # already 300x300, good to go as is
    identify Brugia_malayi.jpg
Brugia_malayi.jpg JPEG 300x300 300x300+0+0 8-bit DirectClass 8.43kb

#############################################################################
#  Initial database build (DONE - 2015-07-07 - Hiram)
    # rerun build with wolbachia sequence included 2015-08-11

    cd /hive/data/genomes/bruMal2
    cat << '_EOF_' > bruMal2.config.ra
# Config parameters for makeGenomeDb.pl:
db bruMal2
clade worm
# genomeCladePriority 80
scientificName Brugia malayi
commonName Filarial worm
assemblyDate May. 2014
assemblyLabel University of Pittsburgh B. malayi genome project
assemblyShortLabel WS244/B_malayi-3.1
orderKey 2009
mitoAcc AF538716.1
fastaFiles /hive/data/genomes/bruMal2/ucsc/*.fa.gz
agpFiles /hive/data/genomes/bruMal2/ucsc/*.agp
# qualFiles none
dbDbSpeciesDir worm
photoCreditURL https://www.wormbase.org/species/b_malayi
photoCreditName no photo found
ncbiGenomeId 42
ncbiAssemblyId 176691
ncbiAssemblyName WS244/B_malayi-3.1
ncbiBioProject 10729
genBankAccessionID GCF_000002995.3
taxId 6279
'_EOF_'
    # << happy emacs

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

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

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

##############################################################################
# cpgIslands on UNMASKED sequence (DONE - 2015-08-11 - Hiram)
    mkdir /hive/data/genomes/bruMal2/bed/cpgIslandsUnmasked
    cd /hive/data/genomes/bruMal2/bed/cpgIslandsUnmasked

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

    cat fb.bruMal2.cpgIslandExtUnmasked.txt
    # 159469 bases of 87424120 (0.182%) in intersection

#############################################################################
# cytoBandIdeo - (DONE - 2015-08-11 - Hiram)
    mkdir /hive/data/genomes/bruMal2/bed/cytoBand
    cd /hive/data/genomes/bruMal2/bed/cytoBand
    makeCytoBandIdeo.csh bruMal2

#########################################################################
# ucscToINSDC table/track (TBD - 2015-03-20 - Hiram)
    # do this only on the genbank assemblies
    mkdir /hive/data/genomes/bruMal2/bed/ucscToINSDC
    cd /hive/data/genomes/bruMal2/bed/ucscToINSDC

    ~/kent/src/hg/utils/automation/ucscToINSDC.sh \
       ../../genbank/GCA_*assembly_structure/Primary_Assembly

    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 *
    # 25187 name.coordinate.tab
    # 25187 ucscToINSDC.bed
    # 25187 ucscToINSDC.txt

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

#########################################################################
# fixup search rule for assembly track/gold table (DONE - 2015-08-11 - Hiram)
    hgsql -N -e "select frag from gold;" bruMal2 | sort | head -3
AE017321.1
AF538716.1
Bmal_v3_scaffold1000_1

    hgsql -N -e "select frag from gold;" bruMal2 | sort | tail -2
Bmal_v3_scaffold9_8
Bmal_v3_scaffold9_9

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

    hgsql -N -e "select frag from gold;" bruMal2 \
      | egrep -e '(Bmal_v3_scaffold|AF538716|AE017321)[0-9]*([\._][0-9]*)?' \
        | wc -l
    # 11907

    hgsql -N -e "select frag from gold;" bruMal2 \
      | egrep -v -e '(Bmal_v3_scaffold|AF538716|AE017321)[0-9]*([\._][0-9]*)?' \
       | wc -l
    # 0

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

##########################################################################
# running repeat masker (DONE - 2015-08-11 - Hiram)
    mkdir /hive/data/genomes/bruMal2/bed/repeatMasker
    cd /hive/data/genomes/bruMal2/bed/repeatMasker
    time (doRepeatMasker.pl -buildDir=`pwd` \
        -bigClusterHub=ku -dbHost=hgwdev -workhorse=hgwdev \
        -smallClusterHub=ku bruMal2) > do.log 2>&1
    # real    78m37.643s

    cat faSize.rmsk.txt
    # 95156665 bases (7759220 N's 87397445 real 78291306 upper 9106139 lower)
    #   in 9781 sequences in 1 files
    # Total size: mean 9728.7 sd 94962.2 min 312 (Bmal_v3_scaffold9829)
    #   max 5235760 (Bmal_v3_scaffold1) median 1340
    # %9.57 masked total, %10.42 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 bruMal2 rmsk
    # 9106845 bases of 95156665 (9.570%) in intersection
    # real    0m5.110s

    # why is it different than the faSize above ?
    # because rmsk masks out some N's as well as bases, the count above
    #   separates out the N's from the bases, it doesn't show lower case N's

##########################################################################
# running simple repeat (DONE - 2015-08-11 - Hiram)
    mkdir /hive/data/genomes/bruMal2/bed/simpleRepeat
    cd /hive/data/genomes/bruMal2/bed/simpleRepeat
    time (doSimpleRepeat.pl -buildDir=`pwd` -bigClusterHub=ku \
        -dbHost=hgwdev -workhorse=hgwdev -smallClusterHub=ku \
        bruMal2) > do.log 2>&1
    # real    25m44.704s

    cat fb.simpleRepeat
    # 7317611 bases of 87424120 (8.370%) in intersection

    # using the Window Masker result as indicated below

##########################################################################
# CREATE MICROSAT TRACK (DONE - 2015-08-11 - Hiram)
     ssh hgwdev
     mkdir /cluster/data/bruMal2/bed/microsat
     cd /cluster/data/bruMal2/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 bruMal2 microsat microsat.bed
    #	Read 707 elements of size 4 from microsat.bed

##########################################################################
## WINDOWMASKER (DONE - 2015-08-11 - Hiram)
    mkdir /hive/data/genomes/bruMal2/bed/windowMasker
    cd /hive/data/genomes/bruMal2/bed/windowMasker
    time (doWindowMasker.pl -buildDir=`pwd` -workhorse=hgwdev \
        -dbHost=hgwdev bruMal2) > do.log 2>&1
    # real    6m24.960s

    # Masking statistics
    cat faSize.bruMal2.cleanWMSdust.txt
    # 95156665 bases (7759220 N's 87397445 real 54180115 upper 33217330 lower)
    #    in 9781 sequences in 1 files
    # Total size: mean 9728.7 sd 94962.2 min 312 (Bmal_v3_scaffold9829)
    #    max 5235760 (Bmal_v3_scaffold1) median 1340
    # %34.91 masked total, %38.01 masked real

    cat fb.bruMal2.rmsk.windowmaskerSdust.txt
    # 8059725 bases of 95156665 (8.470%) in intersection

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

    # measure the final masking:
    twoBitToFa bruMal2.2bit stdout | faSize stdin > faSize.bruMal2.2bit.txt
    cat faSize.bruMal2.2bit.txt
    # 95156665 bases (7759220 N's 87397445 real 54166263 upper 33231182 lower)
    #    in 9781 sequences in 1 files
    # Total size: mean 9728.7 sd 94962.2 min 312 (Bmal_v3_scaffold9829)
    #    max 5235760 (Bmal_v3_scaffold1) median 1340
    # %34.92 masked total, %38.02 masked real

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

##########################################################################
# cpgIslands - (DONE - 2015-08-11 - Hiram)
    mkdir /hive/data/genomes/bruMal2/bed/cpgIslands
    cd /hive/data/genomes/bruMal2/bed/cpgIslands
    time (doCpgIslands.pl -dbHost=hgwdev -bigClusterHub=ku \
      -workhorse=hgwdev -smallClusterHub=ku bruMal2) > do.log 2>&1 &
    # real    14m32.864s

    cat fb.bruMal2.cpgIslandExt.txt
    # 29718 bases of 87424120 (0.034%) in intersection

#########################################################################
# augustus - (DONE - 2015-08-11 - Hiram)
    mkdir /hive/data/genomes/bruMal2/bed/augustus
    cd /hive/data/genomes/bruMal2/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 bruMal2) > do.log 2>&1
    # real    64m6.834s

    cat fb.bruMal2.augustusGene.txt
    # 6111555 bases of 87424120 (6.991%) in intersection

#########################################################################
# genscan - (DONE - 2015-08-11 - Hiram)
    mkdir /hive/data/genomes/bruMal2/bed/genscan
    cd /hive/data/genomes/bruMal2/bed/genscan
    time (doGenscan.pl -buildDir=`pwd` -workhorse=hgwdev -dbHost=hgwdev \
      -bigClusterHub=ku bruMal2) > do.log 2>&1
    # real    15m30.549s
    # for some odd reason, one of the jobs failed, needed to be completed
    # on hgwdev with window size of 2,000,000 - then continuing:
    time (doGenscan.pl -buildDir=`pwd` -workhorse=hgwdev -dbHost=hgwdev \
      -continue=makeBed -bigClusterHub=ku bruMal2) > makeBed.log 2>&1
    # real    1m25.250s

    cat fb.bruMal2.genscan.txt
    #   3314831 bases of 87424120 (3.792%) in intersection

    cat fb.bruMal2.genscanSubopt.txt
    #   2620574 bases of 87424120 (2.998%) in intersection

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

    cd /hive/data/genomes/bruMal2
    # numerator is bruMal2 gapless bases "real" as reported by:
    head -1 faSize.bruMal2.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/bruMal2
    time blat bruMal2.2bit \
         /dev/null /dev/null -tileSize=11 -makeOoc=jkStuff/bruMal2.11.ooc \
        -repMatch=100
    # Wrote 8609 overused 11-mers to jkStuff/bruMal2.11.ooc
    #  real    0m1.669s

    # 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;' bruMal2 \
       | 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 bruMal2 jkStuff/bruMal2.nonBridged.lft \
         -bedFile=jkStuff/bruMal2.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 bruMal2 just before priPac1

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

    git commit -m "Added bruMal2 - 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 bruMal2
    # logFile: var/build/logs/2015.07.02-11:39:01.bruMal2.initalign.log
    # real    91m20.362s

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

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

    # enable daily alignment and update of hgwdev
    cd ~/kent/src/hg/makeDb/genbank
    git pull
    # add bruMal2 to:
    #   vi etc/align.dbs etc/hgwdev.dbs
    git commit -m "Added bruMal2 - 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=bruMal2 -tableCoverage all.joiner
    joinerCheck -database=bruMal2 -times all.joiner
    joinerCheck -database=bruMal2 -keys all.joiner

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

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

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

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

#############################################################################
# LIFTOVER TO bruMal1 (DONE - 2015-07-08 - Hiram )
    mkdir /hive/data/genomes/bruMal2/bed/blat.bruMal1.2015-08-11
    cd /hive/data/genomes/bruMal2/bed/blat.bruMal1.2015-08-11
    # -debug run to create run dir, preview scripts...
    doSameSpeciesLiftOver.pl \
	-buildDir=`pwd` \
	-bigClusterHub=ku -dbHost=hgwdev -workhorse=hgwdev \
  -ooc=/hive/data/genomes/bruMal2/jkStuff/bruMal2.11.ooc -debug bruMal2 bruMal1
    # Real run:
    time (doSameSpeciesLiftOver.pl -buildDir=`pwd` \
      -bigClusterHub=ku -dbHost=hgwdev -workhorse=hgwdev \
       -ooc=/hive/data/genomes/bruMal2/jkStuff/bruMal2.11.ooc bruMal2 bruMal1) \
		> do.log 2>&1
XXX
    #	real    3m44.490s

    # verify it works on genome-test

#############################################################################
# improve common name (DONE - 2015-07-24 - Hiram)

    hgsql -e 'update dbDb set organism="Filarial worm" where name="bruMal2";' hgcentraltest

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