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

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

##############################################################################
# download sequence, create UCSC sequence (DONE - 2015-06-24 - Hiram)
    mkdir -p /hive/data/genomes/panRed1/genbank
    cd /hive/data/genomes/panRed1/genbank

    time rsync -L -a -P \
rsync://ftp.ncbi.nlm.nih.gov/genomes/genbank/invertebrate/Panagrellus_redivivus/all_assembly_versions/GCA_000341325.1_Pred3/ ./

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

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

    mkdir /hive/data/genomes/panRed1/ucsc
    cd /hive/data/genomes/panRed1/ucsc
    # WormBase contig names are of the pattern:
# >KB455460 1 2280433
# >KB455532 1 1000036
# >KB455127 1 861165
# >KB455382 1 814844
# >KB455536 1 783189
#   ...

    # the genbank and ws245 names are identical except the ws245 is
    # missing the .1 on each name.  Using the ws245 names to be compatible
    # with WormBase
    # no conversion of names to maintain equivalence with WormBase:
    zcat ../ws245/PRJNA186477/p_redivivus.PRJNA186477.WS245.genomic.fa.gz \
        | sed -e 's/ .*//;' | gzip -c > panRed1.fa.gz

    hgFakeAgp panRed1.fa.gz panRed1.agp

    # correct photo from WikiMedia Commons:
    mkdir /hive/data/genomes/panRed1/photo
    cd /hive/data/genomes/panRed1/photo
    wget --timestamping \
https://upload.wikimedia.org/wikipedia/en/c/cf/Panagrellus_redivivus_Otago_University_Cold_Stage.jpg
    convert -quality 80 -geometry 400x300 Panagrellus_redivivus_Otago_University_Cold_Stage.jpg \
      Panagrellus_redivivus.jpg
    identify Panagrellus_redivivus.jpg
    # Panagrellus_redivivus.jpg JPEG 400x300 400x300+0+0

    # reference: http://www.otago.ac.nz/zoology/staff/otago008939.html
    # WikiMedia Commons David Wharton, University of Otago
    # https://en.wikipedia.org/wiki/File:Panagrellus_redivivus_Otago_University_Cold_Stage.jpg

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

    cd /hive/data/genomes/panRed1
    cat << '_EOF_' > panRed1.config.ra
# Config parameters for makeGenomeDb.pl:
db panRed1
clade worm
genomeCladePriority 70
scientificName Panagrellus redivivus
commonName P. redivivus
assemblyDate Feb. 2013
assemblyShortLabel Pred3
assemblyLabel California Institute of Technology P. redivivus genome project
orderKey 16020
mitoAcc KM192364.1
fastaFiles /hive/data/genomes/panRed1/ucsc/panRed1.fa.gz
agpFiles /hive/data/genomes/panRed1/ucsc/panRed1.agp
# qualFiles none
dbDbSpeciesDir worm
photoCreditURL http://www.wormbase.org/species/p_redivivus#4--10
photoCreditName WormBase WS240
ncbiGenomeId 16242
ncbiAssemblyId 541658
ncbiAssemblyName WS240/Pred3
ncbiBioProject 186477
genBankAccessionID GCA_000341325.1
taxId 6233
'_EOF_'
    # << happy emacs

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


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

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

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

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

    cat fb.panRed1.cpgIslandExtUnmasked.txt
    # 5218407 bases of 62228262 (8.386%) in intersection

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

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

    # find accession name for chrM
    grep chrM ../../*.agp
# chrM    1       17089   2875    F       KM192364.1      1       17089   +

    # use that as second argument here:
    ~/kent/src/hg/utils/automation/ucscToINSDC.sh \
       ../../genbank/GCA_*assembly_structure/Primary_Assembly KM192364.1

    awk '{printf "%s\t0\t%d\n", $1,$2}' ../../chrom.sizes \
         | sort > name.coordinate.tab
    # eliminate the v1 from what would have been the UCSC names from genbank:
    sed -e 's/v1//;' ucscToINSDC.txt \
        | join name.coordinate.tab - | tr '[ ]' '[\t]' \
         > ucscToINSDC.bed
    # verify all names are coming through, should be same line count:
    wc -l *
    #   941 name.coordinate.tab
    #   941 ucscToINSDC.bed
    #   941 ucscToINSDC.txt

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

#########################################################################
# fixup search rule for assembly track/gold table (DONE - 2015-07-01 - Hiram)
    hgsql -N -e "select frag from gold;" panRed1 | sort | head -3
AOMH01000001_1
AOMH01000002_1
AOMH01000003_1

    hgsql -N -e "select frag from gold;" panRed1 | sort | tail -3
KB455574_8
KB455574_9
KM192364.1

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

    hgsql -N -e "select frag from gold;" panRed1 \
      | egrep -e '[AK][BMO][MH0-9]*([_\.][0-9]*)?' \
        | wc -l
    # 5978

    hgsql -N -e "select frag from gold;" panRed1 \
      | egrep -v -e '[AK][BMO][MH0-9]*([_\.][0-9]*)?' | wc -l
    # 0

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

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

    # fixed a bug in the doLoad.bash script, then continuing:
    time (doRepeatMasker.pl -buildDir=`pwd` \
        -bigClusterHub=ku -dbHost=hgwdev -workhorse=hgwdev \
        -continue=cleanup -smallClusterHub=ku panRed1) > cleanup.log 2>&1
    #  real    0m10.772s

    cat faSize.rmsk.txt
    #  65110236 bases (3020128 N's 62090108 real 61787614 upper
    #    302494 lower) in 941 sequences in 1 files
    #  Total size: mean 69192.6 sd 150304.4 min 362 (AOMH01000403)
    #    max 2280433 (KB455460) median 12743
    #  %0.46 masked total, %0.49 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 panRed1 rmsk
    # 302575 bases of 65110236 (0.465%) in intersection
    # real    0m0.395s

    # 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-07-01 - Hiram)

    mkdir /hive/data/genomes/panRed1/bed/simpleRepeat
    cd /hive/data/genomes/panRed1/bed/simpleRepeat
    time (doSimpleRepeat.pl -buildDir=`pwd` -bigClusterHub=ku \
        -dbHost=hgwdev -workhorse=hgwdev -smallClusterHub=ku \
        panRed1) > do.log 2>&1
    # real    3m1.956s
    time (doSimpleRepeat.pl -buildDir=`pwd` -bigClusterHub=ku \
        -dbHost=hgwdev -workhorse=hgwdev -smallClusterHub=ku \
        -continue=cleanup panRed1) > cleanup.log 2>&1

    cat fb.simpleRepeat
    # 756466 bases of 62228262 (1.216%) in intersection

    # using the Window Masker result as indicated below

##########################################################################
# CREATE MICROSAT TRACK (DONE - 2015-07-01 - Hiram)
     ssh hgwdev
     mkdir /cluster/data/panRed1/bed/microsat
     cd /cluster/data/panRed1/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 panRed1 microsat microsat.bed
    #	microsat.bed appears to be empty
    # there are none

##########################################################################
## WINDOWMASKER (DONE - 2015-07-01 - Hiram)

    mkdir /hive/data/genomes/panRed1/bed/windowMasker
    cd /hive/data/genomes/panRed1/bed/windowMasker
    time (doWindowMasker.pl -buildDir=`pwd` -workhorse=hgwdev \
        -dbHost=hgwdev panRed1) > do.log 2>&1
    # real    2m57.621s

    # Masking statistics
    cat faSize.panRed1.cleanWMSdust.txt
    # 65110236 bases (3020128 N's 62090108 real 53046172 upper
    #    9043936 lower) in 941 sequences in 1 files
    # Total size: mean 69192.6 sd 150304.4 min 362 (AOMH01000403)
    #    max 2280433 (KB455460) median 12743
    # %13.89 masked total, %14.57 masked real

    cat fb.panRed1.rmsk.windowmaskerSdust.txt
    # 167894 bases of 65110236 (0.258%) in intersection

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

    # measure the final masking:
    twoBitToFa panRed1.2bit stdout | faSize stdin > faSize.panRed1.2bit.txt
    cat faSize.panRed1.2bit.txt
    #  65110236 bases (3020128 N's 62090108 real 53041454 upper
    #    9048654 lower)  in 941 sequences in 1 files
    #  Total size: mean 69192.6 sd 150304.4 min 362 (AOMH01000403)
    #    max 2280433 (KB455460) median 12743
    #  %13.90 masked total, %14.57 masked real

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

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

    cat fb.panRed1.cpgIslandExt.txt
    # 3948577 bases of 62228262 (6.345%) in intersection

#########################################################################
# augustus - (DONE - 2015-07-09 - Hiram)
    mkdir /hive/data/genomes/panRed1/bed/augustus
    cd /hive/data/genomes/panRed1/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 panRed1) > do.log 2>&1
    # real    13m23.195s

    cat fb.panRed1.augustusGene.txt
    # 24225124 bases of 62228262 (38.929%) in intersection

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

    cat fb.panRed1.genscan.txt
    #   13419606 bases of 62228262 (21.565%) in intersection

    cat fb.panRed1.genscanSubopt.txt
    #  9038121 bases of 62228262 (14.524%) in intersection

########################################################################
# Create kluster run files (TBD - 2015-03-24 - Hiram)

    cd /hive/data/genomes/panRed1
    # numerator is panRed1 gapless bases "real" as reported by:
    head -1 faSize.panRed1.2bit.txt
# 2053849526 bases (76078142 N's 1977771384 real 1208345365 upper
#    76942601 lower) in 25187 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 \( 1977771384 / 2861349177 \) \* 1024
    # ( 1977771384 / 2861349177 ) * 1024 = 707.791245

    # ==> use -repMatch=700 according to size scaled down from 1024 for human.
    #   and rounded down to nearest 50
    cd /hive/data/genomes/panRed1
    time blat panRed1.2bit \
         /dev/null /dev/null -tileSize=11 -makeOoc=jkStuff/panRed1.11.ooc \
        -repMatch=700
    # Wrote 23756 overused 11-mers to jkStuff/panRed1.11.ooc
    #  real    0m32.961s

    # there are no non-bridged gaps, do not need to do this
    #   check non-bridged gaps to see what the typical size is:
#     hgsql -N -e 'select * from gap where bridge="no" order by size;' panRed1
#       | ave -tableOut -col=7 stdin
# # min Q1 median Q3 max mean N sum stddev
# 50076 58368.8 70128 100495 1.07816e+07 178173 670 1.19376e+08 672006

    # note the minimum non-bridged gap size is 50,076

#  gapToLift -verbose=2 -minGap=50000 panRed1 jkStuff/panRed1.nonBridged.lft \
#         -bedFile=jkStuff/panRed1.nonBridged.bed

#    hgsql -N \
#        -e 'select * from gap where bridge="no" order by size;' panRed1 \
#        | ave -col=7 stdin

    # not needed:
#    gapToLift -verbose=2 -minGap=100 bosTau7 jkStuff/nonBridged.lft \
#        -bedFile=jkStuff/nonBridged.bed

    # survey sizes:
    n50.pl chrom.sizes
#       reading: chrom.sizes
#       contig count: 25187, total size: 2053849526, one half size: 1026924763
# cumulative    N50 count       contig  contig size
# 1026149130      545     KN906416v1      1073586
# 1026924763 one half size
# 1027218231      546     KN906384v1      1069101

#############################################################################
# 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
    #  Nanorana parkeri	3	0	0
    #  Nanorana pleskei	3	0	0
    #  Nanorana yunnanensis	1	0	0

    # edit etc/genbank.conf to add panRed1 just before xenTro7

# panRed1 (tibetan frog)
panRed1.serverGenome = /hive/data/genomes/panRed1/panRed1.2bit
panRed1.clusterGenome = /hive/data/genomes/panRed1/panRed1.2bit
panRed1.ooc = /hive/data/genomes/panRed1/jkStuff/panRed1.11.ooc
panRed1.lift = no
panRed1.perChromTables = no
panRed1.refseq.mrna.xeno.pslCDnaFilter    = ${lowCover.refseq.mrna.xeno.pslCDnaFilter}
panRed1.genbank.mrna.native.pslCDnaFilter = ${lowCover.genbank.mrna.native.pslCDnaFilter}
panRed1.genbank.mrna.xeno.pslCDnaFilter   = ${lowCover.genbank.mrna.xeno.pslCDnaFilter}
panRed1.genbank.est.native.pslCDnaFilter  = ${lowCover.genbank.est.native.pslCDnaFilter}
panRed1.genbank.est.xeno.pslCDnaFilter    = ${lowCover.genbank.est.xeno.pslCDnaFilter}
panRed1.downloadDir = panRed1
panRed1.refseq.mrna.native.load  = no
panRed1.refseq.mrna.xeno.load = yes
panRed1.refseq.mrna.xeno.loadDesc  = yes
panRed1.genbank.mrna.native.load = no
panRed1.genbank.mrna.native.loadDesc = no
panRed1.genbank.mrna.xeno.load = yes
panRed1.genbank.mrna.xeno.loadDesc = yes
panRed1.genbank.est.native.load = no
panRed1.genbank.est.native.loadDesc = no
# panRed1.upstreamGeneTbl = ensGene

    # Edit src/lib/gbGenome.c to add new species.
    git commit -m "Added nanPar Nanorana parkeri refs #15056" \
         etc/genbank.conf src/lib/gbGenome.c
    git push
    # update /cluster/data/genbank/etc/:
    make etc-update
    # update /cluster/data/genbank/bin/:
    make install-server

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

    time ./bin/gbAlignStep -initial panRed1
    # logFile: var/build/logs/2015.05.27-15:45:35.panRed1.initalign.log
    # real    1651m57.350s

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

    # load database when finished
    ssh hgwdev
    cd /cluster/data/genbank
    time ./bin/gbDbLoadStep -drop -initialLoad panRed1
    # logFile: var/dbload/hgwdev/logs/2015.06.09-14:34:12.panRed1.dbload.log
    # real    128m32.009s

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

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

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

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

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

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

    hgsql -e 'update dbDb set organism="Microworm" where name="panRed1";' hgcentraltest

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