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

# This file describes browser build for the oviAri4

#########################################################################
# reuse photograph from oviAri3 previous versions
#    (DONE - 2018-04-18 - ChrisL)

mkdir /hive/data/genomes/oviAri4
cd /hive/data/genomes/oviAri4
cp -p ../oviAri3/photoReference.txt .

cat photoReference.txt

photoCreditURL  http://www1.bio.ku.dk/cbp/metabolic_regulation_lab/
photoCreditName Malin P. Tygesen and Jacob B. Hansen, Univ. Copenhagen, Denmark

#########################################################################
#  Initial steps (DONE  - 2018-04-18 - ChrisL)

# To start this initialBuild.txt document, from a previous assembly document:

mkdir ~/kent/src/hg/makeDb/doc/oviAri4
cd ~/kent/src/hg/makeDb/doc/oviAri4

# best to use a most recent document since it has the latest features and
# procedures:
sed -e 's/panTro6/oviAri4/g; s/PanTro6/OviAri4/g; s/TBD/TBD/g;' ../panTro6/initialBuild.txt > initialBuild.txt

mkdir /hive/data/genomes/oviAri4/refseq
cd /hive/data/genomes/oviAri4/refseq

time rsync -L -a -P \
rsync://ftp.ncbi.nlm.nih.gov/genomes/refseq/vertebrate_mammalian/Ovis_aries/all_assembly_versions/GCF_000298735.2_Oar_v4.0/ ./

# sent 3208 bytes  received 3797403165 bytes  21887068.43 bytes/sec
# total size is 3796927865  speedup is 1.00

# real    2m53.165s

# check assembly size for later reference:

faSize G*_v4.0_genomic.fna.gz

#2615516299 bases (28008926 N's 2587507373 real 1585453251 upper 1002054122 lower) in 5466 sequences in 1 files
#Total size: mean 478506.5 sd 7917732.5 min 1001 (NW_014643138.1) max 275406953 (NC_019458.2) median 2910

# %38.31 masked total, %38.73 masked real

# this information is from the top of
#    oviAri4/refseq/GCF_002880755.1_Clint_v4.0_assembly_report.txt


# Assembly name:  Oar_v4.0
# Organism name:  Ovis aries (sheep)
# Infraspecific name:  breed=Texel
# Taxid:          9940
# BioSample:      SAMN00116405
# BioProject:     PRJNA169880
# Submitter:      International Sheep Genome Consortium
# Date:           2015-11-20
# Assembly type:  haploid
# Release type:   major
# Assembly level: Chromosome
# Genome representation: full
# WGS project:    AMGL02
# Assembly method: SOAPdenovo v. 1.03; PBJelly2 v. 14.9.9
# Genome coverage: 166.0x
# Sequencing technology: Illumina GAII; 454; PacBio RSII
# RefSeq category: Representative Genome
# GenBank assembly accession: GCA_000298735.2
# RefSeq assembly accession: GCF_000298735.2
# RefSeq assembly and GenBank assemblies identical: no
#
## Assembly-Units:
## GenBank Unit Accession       RefSeq Unit Accession   Assembly-Unit name
## GCA_000298745.2      GCF_000298745.2 Primary Assembly
##      GCF_000030495.1 non-nuclear

#############################################################################
# establish config.ra file (DONE - ChrisL - 2018-04-18)
    # arguments here are: <db> <clade> <trackDbDir> <assembly_report.txt>
    cd /hive/data/genomes/oviAri4
    $HOME/kent/src/hg/utils/automation/prepConfig.pl oviAri4 mammal \
        sheep ./refseq/*_assembly_report.txt > oviAri4.config.ra

    # compare to ../oviAri3 to see what might need to be fixed up:
    diff oviAri4.config.ra ../oviAri3/oviAri3.config.ra  | less

    cat oviAri4.config.ra
# config parameters for makeGenomeDb.pl:
db oviAri4
clade mammal
scientificName Ovis aries
commonName Sheep
assemblyDate Nov. 2015
assemblyLabel International Sheep Genome Consortium
assemblyShortLabel Oar_v4.0
orderKey 19313
# mitochondrial sequence included in refseq release
# mitoAcc NC_001941.1
mitoAcc none
fastaFiles /hive/data/genomes/oviAri4/ucsc/*.fa.gz
agpFiles /hive/data/genomes/oviAri4/ucsc/*.agp
# qualFiles none
dbDbSpeciesDir sheep
photoCreditURL  http://www1.bio.ku.dk/cbp/metabolic_regulation_lab/
photoCreditName Malin P. Tygesen and Jacob B. Hansen, Univ. Copenhagen, Denmark
ncbiGenomeId 83
ncbiAssemblyId 585171
ncbiAssemblyName Oar_v4.0
ncbiBioProject 169880
ncbiBioSample SAMN00116405
genBankAccessionID GCF_000298735.2
taxId 9940

#############################################################################
# setup UCSC named files (DONE - 2018-04-18 - ChrisL)

    mkdir /hive/data/genomes/oviAri4/ucsc
    cd /hive/data/genomes/oviAri4/ucsc

    # check for duplicate sequences:
    time faToTwoBit -noMask ../refseq/G*_v4.0_genomic.fna.gz refseq.2bit
    #  real 1m7.811s

    twoBitDup refseq.2bit
    # no output is a good result, otherwise, would have to eliminate duplicates
    # the scripts creating the fasta here will be using this refseq.2bit file

    time ~/kent/src/hg/utils/automation/ucscCompositeAgp.pl \
       ../refseq/G*_v4.0_genomic.fna.gz \
          ../refseq/G*_v4.0_assembly_structure/Primary_Assembly
# NC_019458.2 chr1
# NC_019459.2 chr2
# NC_019460.2 chr3
# NC_019461.2 chr4
# NC_019462.2 chr5
# NC_019463.2 chr6
# NC_019464.2 chr7
# NC_019465.2 chr8
# NC_019466.2 chr9
# NC_019467.2 chr10
# NC_019468.2 chr11
# NC_019469.2 chr12
# NC_019470.2 chr13
# NC_019471.2 chr14
# NC_019472.2 chr15
# NC_019473.2 chr16
# NC_019474.2 chr17
# NC_019475.2 chr18
# NC_019476.2 chr19
# NC_019477.2 chr20
# NC_019478.2 chr21
# NC_019479.2 chr22
# NC_019480.2 chr23
# NC_019481.2 chr24
# NC_019482.2 chr25
# NC_019483.2 chr26
# NC_019484.2 chrX

# real    15m1.883s
    # unplaced sequences
    time ~/kent/src/hg/utils/automation/unplacedWithChroms.pl \
       ../refseq/*_assembly_structure/Primary_Assembly
# processed 5438 sequences into chrUn.fa.gz
# real    0m37.393s

    # unlocalized sequences
    time ~/kent/src/hg/utils/automation/unlocalizedWithChroms.pl \
       ../refseq/*_assembly_structure/Primary_Assembly
# No unlocalized sequences

    # bash syntax here
    mitoAcc=`grep "^# mitoAcc" ../oviAri4.config.ra | awk '{print $NF}'`
    printf "# mitoAcc %s\n" "$mitoAcc"
# mitoAcc NC_001941.1

    zcat \
  ../refseq/*_assembly_structure/non-nuclear/assem*/AGP/chrMT.comp.agp.gz \
     | grep -v "^#" | sed -e "s/^$mitoAcc/chrM/;" > chrM.agp

    printf ">chrM\n" > chrM.fa
    twoBitToFa -noMask refseq.2bit:$mitoAcc stdout | grep -v "^>" >> chrM.fa
    gzip chrM.fa

    # verify fasta and AGPs agree
    time faToTwoBit *.fa.gz test.2bit
    #real   1m14.194s

    time cat *.agp | checkAgpAndFa stdin test.2bit 2>&1 | tail -4
    # All AGP and FASTA entries agree - both files are valid

    # real    0m10.320s

    # and no sequence lost from orginal:
    twoBitToFa test.2bit stdout | faSize stdin
    # 2615516299 bases (28008926 N's 2587507373 real 2587507373 upper 0 lower) in 5466 sequences in 1 files
    # Total size: mean 478506.5 sd 7917732.5 min 1001 (chrUn_NW_014643138v1) max 275406953 (chr1) median 2910

    # same numbers as above
    # 2615516299 bases (28008926 N's 2587507373 real 1585453251 upper 1002054122 lower) in 5466 sequences in 1 files
    # Total size: mean 478506.5 sd 7917732.5 min 1001 (NW_014643138.1) max 275406953 (NC_019458.2) median 2910

    # no longer need these temporary 2bit files
    rm refseq.2bit test.2bit

#############################################################################
#  Initial database build (DONE - 2018-04-18 - ChrisL)

    cd /hive/data/genomes/oviAri4
    # verify sequence and AGP are OK:
    time (makeGenomeDb.pl -workhorse=hgwdev -dbHost=hgwdev -fileServer=hgwdev \
         -stop=agp oviAri4.config.ra) > agp.log 2>&1
    # real   2m29.005s

    # verify there was no error in that step:
    tail agp.log
    #  *** All done!  (through the 'agp' step)

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

    # verify gaps are all there, the 2bit was created with hgFakeAgp
    # with a min gap size of 1, and so we get more gaps from the 2bit
    # than in the gap table
    twoBitInfo -nBed oviAri4.unmasked.2bit stdout | awk '{print $3-$2}' \
	| ave stdin | sed -e 's/^/# /;'
# Q1 100.000000
# median 100.000000
# Q3 685.000000
# average 628.481937
# min 1.000000
# max 24582.000000
# count 44566
# total 28008926.000000
# standard deviation 1110.525457

    hgsql -e 'select chromEnd-chromStart from gap;' oviAri4 | ave stdin | sed -e 's/^/# /;'
# Q1 100.000000
# median 100.000000
# Q3 721.000000
# average 650.935140
# min 10.000000
# max 24582.000000
# count 43016
# total 28000626.000000
# standard deviation 1123.926322


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

    # temporary symlink until masked sequence is available
    cd /hive/data/genomes/oviAri4
    ln -s `pwd`/oviAri4.unmasked.2bit /gbdb/oviAri4/oviAri4.2bit

##############################################################################
# cpgIslands on UNMASKED sequence (DONE - 2018-04-20 - ChrisL)
    mkdir /hive/data/genomes/oviAri4/bed/cpgIslandsUnmasked
    cd /hive/data/genomes/oviAri4/bed/cpgIslandsUnmasked

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

    cat fb.oviAri4.cpgIslandExtUnmasked.txt
    # 29501154 bases of 2587515673 (1.140%) in intersection

#############################################################################
# cytoBandIdeo - (DONE - 2018-04-20 - ChrisL)
    mkdir /hive/data/genomes/oviAri4/bed/cytoBand
    cd /hive/data/genomes/oviAri4/bed/cytoBand
    makeCytoBandIdeo.csh oviAri4

#############################################################################
# gapOverlap (DONE - 2018-04-20 - ChrisL)
    mkdir /hive/data/genomes/oviAri4/bed/gapOverlap
    cd /hive/data/genomes/oviAri4/bed/gapOverlap
    time (doGapOverlap.pl \
	-twoBit=/hive/data/genomes/oviAri4/oviAri4.unmasked.2bit oviAri4 ) \
	> do.log 2>&1
    # real    15m25.615s

    cat fb.oviAri4.gapOverlap.txt
    # 97216 bases of 2615516299 (0.004%) in intersection

    # 123 items, mostly on unplaced contigs:
    zcat *.bed.gz | cut -f1 | cut -d'_' -f1 | sort  | uniq -c |sort -r  | head -5
     84 chrUn
      6 chr3
      6 chr1
      4 chr25
      3 chr4

#############################################################################
# tandemDups (DONE - 2018-04-20 - ChrisL)
    mkdir /hive/data/genomes/oviAri4/bed/tandemDups
    cd /hive/data/genomes/oviAri4/bed/tandemDups
    time (~/kent/src/hg/utils/automation/doTandemDup.pl \
  -twoBit=/hive/data/genomes/oviAri4/oviAri4.unmasked.2bit oviAri4) \
	> do.log 2>&1 &
    # real    88m43.940s

    cat fb.oviAri4.tandemDups.txt
    # 70439161 bases of 2615516299 (2.693%) in intersection

    bigBedInfo oviAri4.tandemDups.bb | sed -e 's/^/#  /;'
#  version: 4
#  fieldCount: 13
#  hasHeaderExtension: yes
#  isCompressed: yes
#  isSwapped: 0
#  extraIndexCount: 0
#  itemCount: 863,625
#  primaryDataSize: 23,596,930
#  primaryIndexSize: 136,940
#  zoomLevels: 9
#  chromCount: 2406
#  basesCovered: 1,733,829,936
#  meanDepth (of bases covered): 4.431233
#  minDepth: 1.000000
#  maxDepth: 8999.000000
#  std of depth: 12.907523

#############################################################################
# run up idKeys files for chromAlias/ncbiRefSeq (DONE - 2018-04-20 - ChrisL)
    mkdir /hive/data/genomes/oviAri4/bed/idKeys
    cd /hive/data/genomes/oviAri4/bed/idKeys

    time (doIdKeys.pl \
	-twoBit=/hive/data/genomes/oviAri4/oviAri4.unmasked.2bit \
	-buildDir=`pwd` oviAri4) > do.log 2>&1 &
    # real    4m10.302s

    cat oviAri4.keySignature.txt
    #  790b46494bd4998aeb10d01d37f71791

#############################################################################
# ucscToINSDC and ucscToRefSeq table/track (DONE - 2018-04-23 - ChrisL)
    # the sequence here is working for a 'refseq' assembly
    # beware of a chrM situation may be specific depending upon what is
    # available in the assembly

    mkdir /hive/data/genomes/oviAri4/bed/ucscToINSDC
    cd /hive/data/genomes/oviAri4/bed/ucscToINSDC
    
    # missing idKey for refSeq and genbank assemblies so make them first
    # first add refSeq keys
    mkdir /hive/data/genomes/oviAri4/refSeq/idKeys
    cd /hive/data/genomes/oviAri4/refSeq/idKeys
    faToTwoBit ../GCF_000298735.2_Oar_v4.0_genomic.fna.gz oviAri4.refSeq.2bit

    time (doIdKeys.pl -buildDir=`pwd` \
        -twoBit=`pwd`/oviAri4.refSeq.2bit oviAri4)  > do.log 2>&1 &
    # real  11m55.410s

    cat oviAri4.keySignature.txt 
    # 790b46494bd4998aeb10d01d37f71791

    # now genbank
    mkdir /hive/data/genomes/oviAri4/refSeq/idKeysGenbank
    cd /hive/data/genomes/oviAri4/refSeq/idKeysGenbank
    ln -s /hive/data/outside/ncbi/genomes/genbank/vertebrate_mammalian/Ovis_aries/all_assembly_versions/GCA_000298735.2_Oar_v4.0/GCA_000298735.2_Oar_v4.0_genomic.fna.gz .
    faToTwoBit GCA_000298735.2_Oar_v4.0_genomic.fna.gz oviAri4.genbank.2bit

    time ( doIdKeys.pl -buildDir=`pwd` \
        -twoBit=`pwd`/oviAri4.genbank.2bit oviAri4 ) > do.log 2>&1 &
    # real  11m56.978s

    cat oviAri4.keySignature.txt 
    # cccd25ef9c9a8f4c210b7c32415a7ca1

    join -t$'\t' ../idKeys/oviAri4.idKeys.txt \
	../../refseq/idKeysGenbank/oviAri4.idKeys.txt | cut -f2- \
          | sort -k1,1 | join -t$'\t' <(sort -k1,1 ../../chrom.sizes) - \
            | awk '{printf "%s\t0\t%d\t%s\n", $1, $2, $3}' \
               | sort -k1,1 -k2,2n > ucscToINSDC.bed

    join -t$'\t' ../idKeys/oviAri4.idKeys.txt \
	../../refseq/idKeys/oviAri4.idKeys.txt | cut -f2- \
          | sort -k1,1 | join -t$'\t' <(sort -k1,1 ../../chrom.sizes) - \
            | awk '{printf "%s\t0\t%d\t%s\n", $1, $2, $3}' \
               | sort -k1,1 -k2,2n > ucscToRefSeq.bed

    # verify line counts are the same
    wc -l *.bed ../../chrom.sizes
    #  5465 ucscToINSDC.bed
    #  5466 ucscToRefSeq.bed
    #  5466 ../../chrom.sizes

    # need to find INSDC equivalents for chrM:
    egrep "chrM" *
ucscToRefSeq.bed:chrM   0   16616   NC_001941.1

    # lookup those accessions at NCBI Entrez
    # NC_001941.1 = AF010406.1
    printf "chrM\t0\t16616\tAF010406.1\n" >> ucscToINSDC.bed

    # resort the bed file:
    sort -k1,1 -k2,2n -o ucscToINSDC.bed ucscToINSDC.bed

    # verify chrM is correct:
    egrep "chrM|chrY" *
ucscToINSDC.bed:chrM    0   16616   AF010406.1
ucscToRefSeq.bed:chrM   0   16616   NC_001941.1

    # should be same line counts throughout:
    # wc -l *.bed ../../chrom.sizes 
    #   5466 ucscToINSDC.bed
    #   5466 ucscToRefSeq.bed
    #   5466 ../../chrom.sizes

    export chrSize=`cut -f1 ucscToINSDC.bed | awk '{print length($0)}' | sort -n | tail -1`
    echo $chrSize
    # 20
    # use the $chrSize in this sed
    sed -e "s/21/$chrSize/" $HOME/kent/src/hg/lib/ucscToINSDC.sql \
         | hgLoadSqlTab oviAri4 ucscToINSDC stdin ucscToINSDC.bed
    # should be the same for ucscToRefSeq:
    export chrSize=`cut -f1 ucscToRefSeq.bed | awk '{print length($0)}' | sort -n | tail -1`
    echo $chrSize
    #  20
    sed -e "s/21/$chrSize/" $HOME/kent/src/hg/lib/ucscToINSDC.sql \
       | sed -e 's/INSDC/RefSeq/g;' > ucscToRefSeq.sql
    hgLoadSqlTab oviAri4 ucscToRefSeq ./ucscToRefSeq.sql ucscToRefSeq.bed

    # checkTableCoords should be silent
    checkTableCoords oviAri4

    # each should cover %100 entirely:
    featureBits -countGaps oviAri4 ucscToRefSeq
    # 2615516299 bases of 2615516299 (100.000%) in intersection
    featureBits -countGaps oviAri4 ucscToINSDC 
    # 2615516299 bases of 2615516299 (100.000%) in intersection

#########################################################################
# add chromAlias table (DONE - 2018-04-23 - ChrisL)

    mkdir /hive/data/genomes/oviAri4/bed/chromAlias
    cd /hive/data/genomes/oviAri4/bed/chromAlias

    hgsql -N -e 'select chrom,name from ucscToRefSeq;' oviAri4 \
        | sort -k1,1 > ucsc.refseq.tab
    hgsql -N -e 'select chrom,name from ucscToINSDC;' oviAri4 \
        | sort -k1,1 > ucsc.genbank.tab

    ~/kent/src/hg/utils/automation/chromAlias.pl ucsc.*.tab \
	> oviAri4.chromAlias.tab

for t in refseq genbank
do
  c0=`cat ucsc.$t.tab | wc -l`
  c1=`grep $t oviAri4.chromAlias.tab | wc -l`
  ok="OK"
  if [ "$c0" -ne "$c1" ]; then
     ok="ERROR"
  fi
  printf "# checking $t: $c0 =? $c1 $ok\n"
done
# checking refseq: 5466 =? 5466 OK
# checking genbank: 5466 =? 5466 OK

    hgLoadSqlTab oviAri4 chromAlias ~/kent/src/hg/lib/chromAlias.sql \
        oviAri4.chromAlias.tab

#########################################################################
# fixup search rule for assembly track/gold table (DONE - 2018-04-23 - ChrisL)
    cd ~/kent/src/hg/makeDb/trackDb/sheep/oviAri4

    # preview prefixes and suffixes:
    hgsql -N -e "select frag from gold;" oviAri4 \
      | sed -e 's/[0-9][0-9]*//;' | sort | uniq -c | sed -e 's/^/#\t/;'
    #     48481 AMGL.1
    #         1 NC_.1
               
    # implies a rule: '[AN][MC][GL0-9_]+(\.[0-9]+)?'

    # verify this rule will find them all and eliminate them all:
    hgsql -N -e "select frag from gold;" oviAri4 | wc -l
    # 5254

    hgsql -Ne "select frag from gold" oviAri4 \
        | egrep -e '[AN][MC][GL0-9_]+(\.[0-9]+)?' | wc -l
    # 48482

    hgsql -Ne "select frag from gold" oviAri4 \
        | egrep -v -e '[AN][MC][GL0-9_]+(\.[0-9]+)?' | wc -l
    # 0

    # hence, add to trackDb/sheep/oviAri4/trackDb.ra
searchTable gold
shortCircuit 1
termRegex [ABN][ACSB][ACGZ0-9_]+(\.[0-9]+)?
query select chrom,chromStart,chromEnd,frag from %s where frag like '%s%%'
searchPriority 8

    # verify searches work in the position box

#############################################################################
# running repeat masker (DONE - 2018-04-20 - ChrisL)
    mkdir /hive/data/genomes/oviAri4/bed/repeatMasker
    cd /hive/data/genomes/oviAri4/bed/repeatMasker
    time  (doRepeatMasker.pl -buildDir=`pwd` \
        -bigClusterHub=ku -dbHost=hgwdev -workhorse=hgwdev \
        -smallClusterHub=ku oviAri4) > do.log 2>&1 &
    # real    459m57.416s

    egrep "bases|Total|masked" faSize.rmsk.txt \
	| fold -w 75 -s  | sed -e 's/^/# /;'
# 2615516299 bases (28008926 N's 2587507373 real 1402824796 upper 1184682577 
# lower) in 5466 sequences in 1 files
# Total size: mean 478506.5 sd 7917732.5 min 1001 (chrUn_NW_014643138v1) max 
# 275406953 (chr1) median 2910
# %45.29 masked total, %45.78 masked real

    egrep -i "versi|relea" do.log
    # RepeatMasker version open-4.0.7
    #    February 01 2017 (open-4-0-7) 1.331 version of RepeatMasker
    # CC    Dfam_Consensus RELEASE 20170127;                            *
    # CC    RepBase RELEASE 20170127;                                   *

    time featureBits -countGaps oviAri4 rmsk
    # 1186367593 bases of 2615516299 (45.359%) in intersection
    # real    0m47.404s

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

    # faster way to get the same result on high contig count assemblies:
    time hgsql -N -e 'select genoName,genoStart,genoEnd from rmsk;' oviAri4 \
        | bedSingleCover.pl stdin | ave -col=4 stdin | grep "^total"
    # total 1186367593.000000
    # real    0m38.423s

##########################################################################
# running simple repeat (DONE - 2018-03-23 - ChrisL)

    mkdir /hive/data/genomes/oviAri4/bed/simpleRepeat
    cd /hive/data/genomes/oviAri4/bed/simpleRepeat
    # using trf409 6 here as similar size to genome (human == 6)
    time (doSimpleRepeat.pl -buildDir=`pwd` -bigClusterHub=ku \
        -dbHost=hgwdev -workhorse=hgwdev -smallClusterHub=ku \
        -trf409 6 oviAri4) > do.log 2>&1 &
    # real    273m49.147s

    cat fb.simpleRepeat
    # 42833496 bases of 2587515673 (1.655%) in intersection

    bigBedInfo *.bb | sed -e 's/^/# /;'
# version: 4
# fieldCount: 16
# hasHeaderExtension: yes
# isCompressed: yes
# isSwapped: 0
# extraIndexCount: 0
# itemCount: 540,268
# primaryDataSize: 19,728,389
# primaryIndexSize: 120,340
# zoomLevels: 10
# chromCount: 2486
# basesCovered: 42,833,496
# meanDepth (of bases covered): 1.295128
# minDepth: 1.000000
# maxDepth: 70.000000
# std of depth: 1.175788

    # adding this trfMask to the other masking
    cd /hive/data/genomes/oviAri4

    # when using the Window Masker result:
#    twoBitMask bed/windowMasker/oviAri4.cleanWMSdust.2bit \
#       -add bed/simpleRepeat/trfMask.bed  oviAri4.2bit
    #   you can safely ignore the warning about fields >= 13

    # when using Rmsk results, add to rmsk after it is done:
    twoBitMask oviAri4.rmsk.2bit \
        -add bed/simpleRepeat/trfMask.bed oviAri4.2bit
    #   you can safely ignore the warning about fields >= 13

    twoBitToFa oviAri4.2bit stdout | faSize stdin > faSize.oviAri4.2bit.txt
    egrep "bases|Total|masked" faSize.oviAri4.2bit.txt \
	| fold -w 75 -s  | sed -e 's/^/# /;'
# 2615516299 bases (28008926 N's 2587507373 real 1402047273 upper 1185460100 
# lower) in 5466 sequences in 1 files
# Total size: mean 478506.5 sd 7917732.5 min 1001 (chrUn_NW_014643138v1) max 
# 275406953 (chr1) median 2910
# %45.32 masked total, %45.81 masked real

    # reset the symlink
    rm /gbdb/oviAri4/oviAri4.2bit
    ln -s `pwd`/oviAri4.2bit /gbdb/oviAri4/oviAri4.2bit

#########################################################################
# CREATE MICROSAT TRACK (DONE - 2018-03-24 - ChrisL)
    ssh hgwdev
    mkdir /cluster/data/oviAri4/bed/microsat
    cd /cluster/data/oviAri4/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 oviAri4 microsat microsat.bed
    # Read 27099 elements of size 4 from microsat.bed

##########################################################################
## WINDOWMASKER (DONE - 2018-04-23 - ChrisL)

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

    # Masking statistics
    egrep "bases|Total|masked" faSize.oviAri4.cleanWMSdust.txt \
	| fold -w 75 -s  | sed -e 's/^/# /;'
# 2615516299 bases (28008926 N's 2587507373 real 1571964655 upper 1015542718 
# lower) in 5466 sequences in 1 files
# Total size: mean 478506.5 sd 7917732.5 min 1001 (chrUn_NW_014643138v1) max 
# 275406953 (chr1) median 2910
# %38.83 masked total, %39.25 masked real

    cat fb.oviAri4.rmsk.windowmaskerSdust.txt
    # 769538371 bases of 2615516299 (29.422%) in intersection

#############################################################################
# ncbiRefSeq (DONE - 2018-03-24 - ChrisL)

    # can be run up after ucscToRefSeq table is constructed
    mkdir /hive/data/genomes/oviAri4/bed/ncbiRefSeq
    cd /hive/data/genomes/oviAri4/bed/ncbiRefSeq

    # adjust the name arguments
    time (~/kent/src/hg/utils/automation/doNcbiRefSeq.pl -buildDir=`pwd` \
      -bigClusterHub=ku -dbHost=hgwdev \
      -fileServer=hgwdev -smallClusterHub=ku -workhorse=hgwdev \
      refseq vertebrate_mammalian Ovis_aries \
      GCF_000298735.2_Oar_v4.0 oviAri4) > do.log 2>&1
    # real    6m15.984s

    cat fb.ncbiRefSeq.oviAri4.txt
    # 84600787 bases of 2587515673 (3.270%) in intersection

#############################################################################
# cpgIslands - (DONE - 2018-03-24 - ChrisL)
    mkdir /hive/data/genomes/oviAri4/bed/cpgIslands
    cd /hive/data/genomes/oviAri4/bed/cpgIslands
    time (doCpgIslands.pl -dbHost=hgwdev -bigClusterHub=ku \
      -workhorse=hgwdev -smallClusterHub=ku oviAri4) > do.log 2>&1 &
    # real    5m4.827s

    cat fb.oviAri4.cpgIslandExt.txt
    # 25897025 bases of 2587515673 (1.001%) in intersection

##############################################################################
# genscan - (DONE - 2018-03-24 - ChrisL)
    mkdir /hive/data/genomes/oviAri4/bed/genscan
    cd /hive/data/genomes/oviAri4/bed/genscan
    time (doGenscan.pl -buildDir=`pwd` -workhorse=hgwdev -dbHost=hgwdev \
      -bigClusterHub=ku oviAri4) > do.log 2>&1 &
    # real  128m51.713s

    cat fb.oviAri4.genscan.txt
    # 55432140 bases of 2587515673 (2.142%) in intersection

    cat fb.oviAri4.genscanSubopt.txt
    # 52806452 bases of 2587515673 (2.041%) in intersection

    bigBedInfo oviAri4.genscan.bb | sed -e 's/^/# /;'
# version: 4
# fieldCount: 12
# hasHeaderExtension: yes
# isCompressed: yes
# isSwapped: 0
# extraIndexCount: 0
# itemCount: 45,411
# primaryDataSize: 2,697,165
# primaryIndexSize: 86,740
# zoomLevels: 8
# chromCount: 2312
# basesCovered: 1,816,748,807
# meanDepth (of bases covered): 1.000000
# minDepth: 1.000000
# maxDepth: 1.000000
# std of depth: 0.000000

#############################################################################
# augustus gene track (DONE - 2018-04-24 - ChrisL)

    mkdir /hive/data/genomes/oviAri4/bed/augustus
    cd /hive/data/genomes/oviAri4/bed/augustus
    time (doAugustus.pl -buildDir=`pwd` -bigClusterHub=ku \
     -species=human -dbHost=hgwdev -workhorse=hgwdev oviAri4) > do.log 2>&1 &
    # real  73m0.609s

    cat fb.oviAri4.augustusGene.txt
    # 47691785 bases of 2587515673 (1.843%) in intersection

     bigBedInfo  oviAri4.augustus.bb | sed -e 's/^/# /;'
# version: 4
# fieldCount: 20
# hasHeaderExtension: yes
# isCompressed: yes
# isSwapped: 0
# extraIndexCount: 0
# itemCount: 28,101
# primaryDataSize: 2,075,682
# primaryIndexSize: 37,244
# zoomLevels: 8
# chromCount: 770
# basesCovered: 1,236,829,591
# meanDepth (of bases covered): 1.216583
# minDepth: 1.000000
# maxDepth: 5.000000
# std of depth: 0.579340

#############################################################################
# lastz/chain/net swap human/hg38 (DONE - 2018-04-25 - ChrisL)
    # original alignment
    cd /hive/data/genomes/hg38/bed/lastzOviAri4.2018-04-25

    cat fb.hg38.chainOviAri4Link.txt
    # 1388649593 bases of 3049335806 (45.539%) in intersection
    cat fb.hg38.chainSynOviAri4Link.txt
    # 1330693519 bases of 3049335806 (43.639%) in intersection
    cat fb.hg38.chainRBestOviAri4Link.txt
    # 1278396766 bases of 3049335806 (41.924%) in intersection

    # running the swap
    mkdir /hive/data/genomes/oviAri4/bed/blastz.hg38.swap
    cd /hive/data/genomes/oviAri4/bed/blastz.hg38.swap
    time (doBlastzChainNet.pl -verbose=2 \
        -swap /hive/data/genomes/hg38/bed/lastzOviAri4.2018-04-25/DEF \
        -chainMinScore=3000 -chainLinearGap=medium \
        -workhorse=hgwdev -smallClusterHub=ku -bigClusterHub=ku \
        -syntenicNet) > swap.log 2>&1
    # real    104m31.748s

    cat fb.oviAri4.chainHg38Link.txt
    # 1319553403 bases of 2587515673 (50.997%) in intersection
    cat fb.oviAri4.chainSynHg38Link.txt
    # 1280196824 bases of 2587515673 (49.476%) in intersection

    time (doRecipBest.pl -load -workhorse=hgwdev -buildDir=`pwd` \
        oviAri4 hg38) > rbest.log 2>&1 &
    # real    638m15.603s

    cat fb.oviAri4.chainRBestHg38Link.txt 
    # 1279077824 bases of 2587515673 (49.433%) in intersection

#############################################################################
# lastz/chain/net swap mouse/mm10 (DONE - 2018-04-25 - ChrisL)

    # alignment to mouse/mm10:
    cd /hive/data/genomes/mm10/bed/lastzOviAri4.2018-04-25

    cat fb.mm10.chainOviAri4Link.txt
    # 693504453 bases of 2652783500 (26.143%) in intersection

    cat fb.mm10.chainRBestOviAri4Link.txt
    # 657097998 bases of 2652783500 (24.770%) in intersection

    # and for the swap:
    mkdir /hive/data/genomes/oviAri4/bed/blastz.mm0.swap
    cd /hive/data/genomes/oviAri4/bed/blastz.mm10.swap

    time (doBlastzChainNet.pl -verbose=2 \
      /hive/data/genomes/mm10/bed/lastzOviAri4.2018-04-25/DEF \
        -swap -chainMinScore=3000 -chainLinearGap=medium \
          -workhorse=hgwdev -smallClusterHub=ku -bigClusterHub=ku \
            -syntenicNet) > swap.log 2>&1
    #  real    63m12.935s

    cat fb.oviAri4.chainMm10Link.txt
    # 680117358 bases of 2587515673 (26.285%) in intersection
    cat fb.oviAri4.chainSynMm10Link.txt
    # 643562837 bases of 2587515673 (24.872%) in intersection

    time (doRecipBest.pl -load -workhorse=hgwdev -buildDir=`pwd` \
	oviAri4 mm10) > rbest.log 2>&1 &
    # real    437m1.637s

    cat fb.oviAri4.chainRBestMm10Link.txt
    # 656602300 bases of 2587515673 (25.376%) in intersection

##############################################################################
# Create kluster run files (DONE - 2018-03-24 - ChrisL)

    cd /hive/data/genomes/oviAri4
    # numerator is oviAri4 gapless bases "real" as reported by:
    featureBits -noRandom -noHap oviAri4 gap
    # 24055659 bases of 2560776851 (0.939%) in intersection
    # 28994139 bases of 2803637675 (1.034%) in intersection
    #                   ^^^

    # 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 \(2560776851 / 2861349177 \) \* 1024
    # (2560776851 / 2861349177 ) * 1024 = 916.433239

    # ==> use -repMatch=900 same as was oviAri3
    cd /hive/data/genomes/oviAri4
    blat oviAri4.2bit /dev/null /dev/null -tileSize=11 \
        -makeOoc=jkStuff/oviAri4.11.ooc -repMatch=900
    #  Wrote 31423 overused 11-mers to jkStuff/oviAri4.11.ooc
    # oviAri3 at repMatch=900 was:
    #  Wrote 30413 overused 11-mers to jkStuff/oviAri3.11.ooc

    # no unbridged gaps so no need to worry about gaplift file:
    hgsql -Ne "select bridge from gap" oviAri4 | sort | uniq -c
    # 43016 yes

##############################################################################
# LIFTOVER TO oviAri3(DONE - 2018-03-24 - ChrisL)
    ssh hgwdev
    mkdir /hive/data/genomes/oviAri4/bed/blat.oviAri3.2018-04-24
    cd /hive/data/genomes/oviAri4/bed/blat.oviAri3.2018-04-24
    time (doSameSpeciesLiftOver.pl -verbose=2 -buildDir=`pwd` \
	-ooc=/hive/data/genomes/oviAri4/jkStuff/oviAri4.11.ooc \
        -bigClusterHub=ku -dbHost=hgwdev -workhorse=hgwdev \
         oviAri4 oviAri3) > do.log 2>&1 &
    # real    102m14.916s

    # verify the convert link on the test browser is now active from oviAri4 to
    # oviAri3

##############################################################################
# GENBANK AUTO UPDATE (DONE - 2018-03-25 - ChrisL)
    ssh hgwdev
    cd $HOME/kent/src/hg/makeDb/genbank
    git pull
    # /cluster/data/genbank/data/organism.lst shows:
    # #organism      mrnaCnt   estCnt  refSeqCnt
    # Ovis aries    3510    338862  915
    # Ovis aries musimon  2   0   0

    # edit etc/genbank.conf to add oviAri4 just before oviAri3
# oviAri4 (sheep - Ovis aries - refseq GCF_000298735.2 - taxId 9940)
oviAri4.serverGenome = /hive/data/genomes/oviAri4/oviAri4.2bit
oviAri4.clusterGenome = /hive/data/genomes/oviAri4/oviAri4.2bit
oviAri4.ooc = /hive/data/genomes/oviAri4/jkStuff/oviAri4.11.ooc
oviAri4.lift = no
oviAri4.perChromTables = no
oviAri4.refseq.mrna.native.pslCDnaFilter  = ${finished.refseq.mrna.native.pslCDnaFilter}
oviAri4.refseq.mrna.xeno.pslCDnaFilter    = ${finished.refseq.mrna.xeno.pslCDnaFilter}
oviAri4.genbank.mrna.native.pslCDnaFilter = ${finished.genbank.mrna.native.pslCDnaFilter}
oviAri4.genbank.mrna.xeno.pslCDnaFilter   = ${finished.genbank.mrna.xeno.pslCDnaFilter}
oviAri4.genbank.est.native.pslCDnaFilter  = ${finished.genbank.est.native.pslCDnaFilter}
oviAri4.genbank.est.xeno.pslCDnaFilter    = ${finished.genbank.est.xeno.pslCDnaFilter}
oviAri4.downloadDir = oviAri4
# defaults yes: genbank.mrna.native.load genbank.mrna.native.loadDesc
# yes: genbank.est.native.load refseq.mrna.native.load
# yes: refseq.mrna.native.loadDesc refseq.mrna.xeno.load
# yes: refseq.mrna.xeno.loadDesc
# defaults no: genbank.mrna.xeno.load genbank.mrna.xeno.loadDesc
# no: genbank.est.native.loadDesc genbank.est.xeno.load
# no: genbank.est.xeno.loadDesc
# DO NOT NEED genbank.mrna.xeno except for human, mouse
# have been doing this for chimp too:
oviAri4.genbank.mrna.xeno.load = no

    # verify stated file paths do exist:
    grep oviAri4 etc/genbank.conf | egrep "Genome|ooc|lift" \
	| awk '{print $NF}' | xargs ls -og
-rw-rw-r-- 1    146968 Mar 24 20:30 /hive/data/genomes/oviAri4/jkStuff/oviAri4.11.ooc
-rw-rw-r-- 1 795113145 Mar 24 20:22 /hive/data/genomes/oviAri4/oviAri4.2bit
-rw-rw-r-- 1 795113145 Mar 24 20:22 /hive/data/genomes/oviAri4/oviAri4.2bit

    # add oviAri4 to:
    #   etc/align.dbs etc/hgwdev.dbs
    git commit -m 'starting genbank updates for oviAri4/sheep refs #17247' \
	etc/genbank.conf etc/align.dbs etc/hgwdev.dbs
    git push
    # update /cluster/data/genbank/:
    make etc-update

#############################################################################
#  BLATSERVERS ENTRY (DONE - 2018-04-24 - ChrisL)
#	After getting a blat server assigned by the Blat Server Gods,
    ssh hgwdev

    hgsql -e 'INSERT INTO blatServers (db, host, port, isTrans, canPcr) \
    VALUES ("oviAri4", "blat1a", "17888", "1", "0"); \
    INSERT INTO blatServers (db, host, port, isTrans, canPcr) \
    VALUES ("oviAri4", "blat1a", "17889", "0", "1");' \
    hgcentraltest
    #   test it with some sequence

##############################################################################
## reset default position to same as what oviAri3 has: 
##  (DONE - 2018-04-09 - ChrisL)

    ssh hgwdev
    hgsql -e 'update dbDb set defaultPos="chr19:50698607-50712547" where name="oviAri4";' hgcentraltest

##############################################################################
# all.joiner update, downloads and in pushQ - (DONE - 2018-05-01 - ChrisL)
    cd $HOME/kent/src/hg/makeDb/schema
    ~/kent/src/hg/utils/automation/verifyBrowser.pl oviAri4
# 65 tables in database oviAri4 - Sheep, Ovis aries
# verified 65 tables in database oviAri4, 0 extra tables, 24 optional tables
# NCBI RefSeq genes 10 optional tables
# chainNetRBestHg38 3 optional tables
# chainNetRBestMm10 3 optional tables
# chainNetSynHg38   3 optional tables
# chainNetSynMm10   3 optional tables
# gapOverlap    1 optional tables
# tandemDups    1 optional tables
# 12 genbank tables found
# verified 29 required tables, 0 missing tables
# hg38 chainNet to oviAri4 found 3 required tables
# mm10 chainNet to oviAri4 found 3 required tables
# hg38 chainNet RBest and syntenic to oviAri4 found 6 optional tables
# mm10 chainNet RBest and syntenic to oviAri4 found 3 optional tables
# liftOver to previous versions: 1, from previous versions: 1

    # fixup all.joiner until this is a clean output
    joinerCheck -database=oviAri4 -tableCoverage all.joiner
    joinerCheck -database=oviAri4 -times all.joiner
    joinerCheck -database=oviAri4 -keys all.joiner

    cd /hive/data/genomes/oviAri4
    # clean up obsolete trackDb work, assuming you have already checked in
    # these trackDb files into the source tree
    rm -fr TemporaryTrackDbCheckout

    time (makeDownloads.pl -workhorse=hgwdev oviAri4) > downloads.log 2>&1
    #  real    23m39.716s

    #   now ready for pushQ entry
    mkdir /hive/data/genomes/oviAri4/pushQ
    cd /hive/data/genomes/oviAri4/pushQ
  time (makePushQSql.pl -redmineList oviAri4) > oviAri4.pushQ.sql 2> stderr.out
    # remove the tandemDups and gapOverlap from the file list:
    sed -i -e "/tandemDups/d" redmine.oviAri4.table.list
    sed -i -e "/Tandem Dups/d" redmine.oviAri4.releaseLog.txt
    sed -i -e "/gapOverlap/d" redmine.oviAri4.table.list
    sed -i -e "/Gap Overlaps/d" redmine.oviAri4.releaseLog.txt

    # also remove the genbank tables because they are built automatically
    # on beta/rr
    all_est
    all_mrna
    estOrientInfo
    intronEst
    mrnaOrientInfo
    refFlat
    refGene
    refSeqAli
    xenoRefFlat
    xenoRefGene
    xenoRefSeqAli

    #   check for errors in stderr.out, some are OK, e.g.:
    # WARNING: oviAri4 does not have seq
    # WARNING: oviAri4 does not have extFile

    # add the path names to the listing files in the redmine issue
    # in the three appropriate entry boxes:

/hive/data/genomes/oviAri4/pushQ/redmine.oviAri4.file.list
/hive/data/genomes/oviAri4/pushQ/redmine.oviAri4.releaseLog.txt
/hive/data/genomes/oviAri4/pushQ/redmine.oviAri4.table.list

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