[med-svn] [umap] 01/02: Imported Upstream version 1.0.0
Afif Elghraoui
afif at moszumanska.debian.org
Wed Jan 25 09:46:11 UTC 2017
This is an automated email from the git hooks/post-receive script.
afif pushed a commit to branch master
in repository umap.
commit a1df9226a8b11c19aacc34b6e67a005b0e934b34
Author: Afif Elghraoui <afif at ghraoui.name>
Date: Wed Jan 25 01:28:35 2017 -0800
Imported Upstream version 1.0.0
---
.hg_archival.txt | 4 +
MANIFEST.in | 1 +
README.rst | 241 +
build/lib/umap/__init__.py | 6 +
build/lib/umap/combine_umaps.py | 183 +
build/lib/umap/get_kmers.py | 265 +
build/lib/umap/handle_fasta.py | 181 +
build/lib/umap/map_bed.py | 262 +
build/lib/umap/run_bowtie.py | 136 +
build/lib/umap/ubismap.py | 636 ++
build/lib/umap/uint8_to_bed.py | 423 ++
build/lib/umap/unify_bowtie.py | 151 +
dist/umap-0.1-py2.7.egg | Bin 0 -> 58250 bytes
dist/umap-0.1.1-py2.7.egg | Bin 0 -> 58251 bytes
dist/umap-0.1.2-py2.7.egg | Bin 0 -> 66028 bytes
dist/umap-1.0.0-py2.7.egg | Bin 0 -> 65976 bytes
doc/Makefile | 230 +
doc/build/.buildinfo | 4 +
doc/build/.doctrees/documentation.doctree | Bin 0 -> 53250 bytes
doc/build/.doctrees/environment.pickle | Bin 0 -> 55022 bytes
doc/build/_modules/index.html | 86 +
doc/build/_modules/umap/combine_umaps.html | 265 +
doc/build/_modules/umap/get_kmers.html | 366 +
doc/build/_modules/umap/run_bowtie.html | 200 +
doc/build/_modules/umap/uint8_to_bed.html | 443 ++
doc/build/_modules/umap/unify_bowtie.html | 235 +
doc/build/_sources/documentation.txt | 195 +
doc/build/_static/ajax-loader.gif | Bin 0 -> 673 bytes
doc/build/_static/alabaster.css | 593 ++
doc/build/_static/basic.css | 608 ++
doc/build/_static/comment-bright.png | Bin 0 -> 3500 bytes
doc/build/_static/comment-close.png | Bin 0 -> 3578 bytes
doc/build/_static/comment.png | Bin 0 -> 3445 bytes
doc/build/_static/doctools.js | 287 +
doc/build/_static/down-pressed.png | Bin 0 -> 347 bytes
doc/build/_static/down.png | Bin 0 -> 347 bytes
doc/build/_static/file.png | Bin 0 -> 358 bytes
doc/build/_static/jquery-1.11.1.js | 10308 +++++++++++++++++++++++++++
doc/build/_static/jquery.js | 4 +
doc/build/_static/minus.png | Bin 0 -> 173 bytes
doc/build/_static/plus.png | Bin 0 -> 173 bytes
doc/build/_static/pygments.css | 65 +
doc/build/_static/searchtools.js | 651 ++
doc/build/_static/underscore-1.3.1.js | 999 +++
doc/build/_static/underscore.js | 31 +
doc/build/_static/up-pressed.png | Bin 0 -> 345 bytes
doc/build/_static/up.png | Bin 0 -> 345 bytes
doc/build/_static/websupport.js | 808 +++
doc/build/doctrees/documentation.doctree | Bin 0 -> 53250 bytes
doc/build/doctrees/environment.pickle | Bin 0 -> 55021 bytes
doc/build/documentation.html | 289 +
doc/build/genindex.html | 168 +
doc/build/latex/Makefile | 78 +
doc/build/latex/Umap.aux | 91 +
doc/build/latex/Umap.idx | 8 +
doc/build/latex/Umap.ilg | 7 +
doc/build/latex/Umap.ind | 29 +
doc/build/latex/Umap.log | 1203 ++++
doc/build/latex/Umap.out | 14 +
doc/build/latex/Umap.pdf | Bin 0 -> 163429 bytes
doc/build/latex/Umap.tex | 361 +
doc/build/latex/Umap.toc | 15 +
doc/build/latex/fncychap.sty | 683 ++
doc/build/latex/newfloat.sty | 737 ++
doc/build/latex/python.ist | 11 +
doc/build/latex/sphinx.sty | 641 ++
doc/build/latex/sphinxhowto.cls | 104 +
doc/build/latex/sphinxmanual.cls | 148 +
doc/build/latex/tabulary.sty | 452 ++
doc/build/objects.inv | 6 +
doc/build/py-modindex.html | 104 +
doc/build/search.html | 100 +
doc/build/searchindex.js | 1 +
doc/source/conf.py | 297 +
doc/source/documentation.rst | 195 +
setup.py | 37 +
umap.egg-info/PKG-INFO | 259 +
umap.egg-info/SOURCES.txt | 18 +
umap.egg-info/dependency_links.txt | 1 +
umap.egg-info/not-zip-safe | 1 +
umap.egg-info/requires.txt | 3 +
umap.egg-info/top_level.txt | 1 +
umap/__init__.py | 6 +
umap/combine_umaps.py | 183 +
umap/data/chrsize.tsv | 2 +
umap/data/genome.fa | 7 +
umap/get_kmers.py | 265 +
umap/handle_fasta.py | 181 +
umap/hg19_august.sh | 156 +
umap/map_bed.py | 262 +
umap/run_bowtie.py | 136 +
umap/ubismap.py | 636 ++
umap/uint8_to_bed.py | 423 ++
umap/unify_bowtie.py | 151 +
94 files changed, 27337 insertions(+)
diff --git a/.hg_archival.txt b/.hg_archival.txt
new file mode 100644
index 0000000..16f6075
--- /dev/null
+++ b/.hg_archival.txt
@@ -0,0 +1,4 @@
+repo: ca5823e5f2177626a38d99964306bfacb1aa72c0
+node: be5d1ea249c975b0e7b79fe09c3fa9418f608bff
+branch: default
+tag: V1.0.0
diff --git a/MANIFEST.in b/MANIFEST.in
new file mode 100644
index 0000000..9561fb1
--- /dev/null
+++ b/MANIFEST.in
@@ -0,0 +1 @@
+include README.rst
diff --git a/README.rst b/README.rst
new file mode 100644
index 0000000..ad928f5
--- /dev/null
+++ b/README.rst
@@ -0,0 +1,241 @@
+.. image:: https://readthedocs.org/projects/umap/badge/?version=latest
+
+
+Umap and Bismap: quantifying genome and methylome mappability
+=============================================================
+
+
+Introduction
+------------
+
+**The free umap software package efficiently identifies uniquely mappable regions of any genome.
+Its Bismap extension identifies mappability of the bisulfite converted genome (methylome).**
+
+the mappability of a genome for a given read length *k*.
+First, it generates all possible *k*-mers of the genome.
+Second, it maps these unique *k*-mers to the genome with `Bowtie <http://bowtie-bio.sourceforge.net/index.shtml>`_ version 1.1.0.
+Third, Umap marks the start position of each *k*-mer that aligns to only one region in the genome.
+Umap repeats these steps for a range of different *k*-mers and stores the data of each chromosome
+in a binary vector *X* with the same length as the chromosome's sequence.
+For read length *k*, :math:`X_i = 1` means that the sequence starting at :math:`X_i` and ending
+at :math:`X_{i+k}` is uniquely mappable on the forward strand.
+Since we align to both strands of the genome, the reverse complement of this same sequence
+starting at :math:`X_{i+k}` on the reverse strand is also uniquely mappable.
+:math:`X_i = 0` means that the sequence starting at :math:`X_i` and ending at
+:math:`X_{i+k}` can be mapped to at least two different regions in the genome.
+
+
+Mappability of the bisulfite-converted genome
+---------------------------------------------
+
+To identify the single-read mappability of a bisulfite-converted genome,
+we create two altered genome sequences.
+In the first sequence, we convert all cytosines to thymine (C :math:`\rightarrow` T).
+In the other sequence we convert all guanines to adenine (G :math:`\rightarrow` A).
+Our approach follows those of `Bismark <http://www.bioinformatics.babraham.ac.uk/projects/bismark/>`_
+and `BWA-meth <https://github.com/brentp/bwa-meth>`_.
+We convert the genome sequence this way because bisulfite
+treatment converts un-methylated cytosine to uracil which is read as thymine.
+Similarly the guanine that is base-pairing with the un-methylated cytosine in
+reverse strand converts to adenine. However these two conversions never occur
+at the same time on the same read. We identify the uniquely mappable regions
+of these two genomes separately, and then combine the data to represent the
+single-read mappability of the forward and reverse strands in the bisulfite-converted genome.
+
+
+Bismap requires special handling of reverse complementation of C :math:`\rightarrow` T
+or G :math:`\rightarrow` A converted genomes.
+Conversion of C :math:`\rightarrow` T on the sequence AATTCCGG produces AATT **TT** GG.
+In the Bowtie index, the reverse complement would be CCAAAATT.
+However for the purpose of identifying the mappability of the bisulfite-converted genome,
+we expect the reverse complement to be TTGGAA **TT**. The reason is that both forward and reverse
+strands undergo bisulfite treatment simultaneously. There is no DNA replication after bisulfite treatment.
+To handle this issue, Bismap creates its own reverse complemented chromosomes and suppresses Bowtie's usual reverse complement mapping.
+
+Umap and Bismap each take approximately 200 CPU hours to run for a given read length. This can be parallelized in a computing cluster over 400 cores to take only 30 minutes.
+
+
+Measures of mappability
+:::::::::::::::::::::::
+
+Umap efficiently identifies the single-read mappability of any genome for a
+range of sequencing read lengths. The single-read mappability of a genomic
+region is a fraction of that region which overlaps with at least one uniquely
+mappable *k*-mer. The Bismap extension of Umap produces the single-read mappability
+of a bisulfite-converted genome. Both Umap and Bismap produce an integer vector for
+each chromosome that efficiently defines the mappability for any region and can be
+converted to a browser extensible data (BED) file. In addition to single-read mappability,
+we can measure the mappability of a genomic region by another approach. To quantify
+the single-read mappability of a given genomic region, we measure the fraction of
+potential uniquely mappable reads in that region. A region, however, can have 100% single-read
+mappability, but in practice require a high coverage sequencing to properly identify that region.
+For example, a 1 kbp region with 100% single-read mappability can be mappable due to a
+minimum of 10 unique 100-mers that none of them overlap or a maximum of 1100 unique 100-mers
+that highly overlap. Therefore, we define the multi-read mappability, the probability that a
+randomly selected read of length k in a given region is uniquely mappable. For the genomic
+region :math:`G_{i:j}` starting at *i* and ending at *j*, there are :math:`j - i + k + 1`
+*k*-mers that overlap with :math:`G_{i:j}`.
+The multi-read mappability of :math:`G_{i:j}` is the fraction of those *k*-mers that are uniquely mappable.
+
+
+
+Quick start
+-----------
+
+We have tested Umap installation on a CentOS system using python 2.7.11.
+Bismap requires numpy and pandas and it uses other python modules such as:
+
+* gzip
+* os
+* re
+* subprocess
+
+Umap uses mercurial version control. Make sure that mercurial (hg) is installed.
+Download Umap to the directory of your python packages using::
+
+ hg clone https://bitbucket.org/hoffmanlab/umap
+ cd umap
+ python setup.py install
+
+
+Now we will run a test using a wrapper in the umap directory called ubismap.py
+and a toy genome stored under umap/data ::
+
+ cd umap
+ python ubismap.py data/genome.fa data/chrsize.tsv data/TestGenomeMappability all.q $BOWTIRDIR/bowtie-build --kmer 8 12 -write_script test_run.sh
+ sh test_run.sh
+
+The scripts that are produced by **ubismap.py** assume that you are using a Sun Grid Engine computing cluster.
+You can use parameters of this script to adjust it to your own system. You may need to manually edit this file
+because many of the SGE settings are very different than other computing clusters.
+However, all of the Umap modules accept *-job_id* which allows you to use the modules without a cluster or if
+your cluster does not support job arrays.
+
+Basically, the job array saves an environmental variable (defined by (*-var_id*) that Umap uses for paralellizing processes.
+You can run the modules in a for loop and set the *-job_id* manually.
+For example, in order to find *k*-mers of a genome with 10 million base pairs, the get_kmers
+and run_bowtie modules each need to be executed with -job_ids ranging between 1 to 10.
+
+
+Get *k*-mers
+------------
+
+.. module:: umap
+ :platform: Unix
+
+.. currentmodule:: get_kmers
+.. autoclass:: GetKmers
+
+
+The first step of finding the mappability of the genome for a given read length,
+is to create all of the possible sequences of the genome with the read length of interest.
+GetKmers requires an index reference and an index ID to do this step for one chunk of
+the genome at a time. The index ID can be specified by -job_id, or if GetKmers is
+submitted as a job array, GetKmers will use the variable name set by -var_id to obtain
+the environmental variable for the job array ID.
+
+
+
+**Important: The chromosome names in the fasta file should not contain underscore.
+Underscore is used in Bismap to differentiate reverse complement chromosomes.**
+
+
+Run Bowtie
+----------
+
+.. currentmodule:: run_bowtie
+.. autoclass:: BowtieWrapper
+
+
+When all of the possible *k*-mers of the genome are created, BowtieWrapper keeps record
+of all of the k-mers that are unique. Similar to GetKmers, the parallel process relies on
+an index reference, or -job_id.
+
+
+Merge bowtie outputs
+--------------------
+
+
+.. currentmodule:: unify_bowtie
+.. autoclass:: UnifyBowtie
+
+
+For each *k*-mer file, there will be a bowtie file with information of unique *k*-mers.
+For each chromosome, a binary vector with length of the chromosome will be created.
+If a *k*-mer starting at a given position is unique, the value will be 1.
+
+
+Merge data of various *k*-mers
+------------------------------
+
+
+.. currentmodule:: combine_umaps
+.. autoclass:: CombineUmaps
+
+If the above steps are repeated for various *k*-mers, these data can be efficiently
+stored in a numeric vector for each chromosome. For each position, the length of the smallest
+*k*-mer that uniquely maps to that position is specified.
+
+
+Convert numeric vectors to BED and Wiggle
+-----------------------------------------
+
+
+.. currentmodule:: uint8_to_bed
+.. autoclass:: Int8Handler
+.. method:: Int8Handler.write_beds
+.. method:: Int8Handler.write_as_wig
+
+To visualize binary and numeric vectors that are produced by Umap, you can use Int8Handler.
+
+
+Special instructions for Bismap
+-------------------------------
+
+For Bismap, you must create the mappability of C :math:`\rightarrow` T
+and G :math:`\rightarrow` A by specifying -Bismap, -C2T, and -G2A each time.
+After creating these two mappability, for each genome you will have a
+kmers/globalmap_k<min>tok<max> folder with normal and reverse complemented chromosome mappabilities.
+
+
+The first step is to merge the mappability of normal and reverse complemented chromosomes for each
+genome. This can be done through uint8_to_bed.py ::
+
+ python uint8_to_bed.py <MergedKmerDir> <OutDirC2T> <LabelForOutputFiles> -C2T -chrsize_path <ChromSizeFile> -WriteUnique
+ python uint8_to_bed.py <MergedKmerDir> <OutDirG2A> <LabelForOutputFiles> -G2A -chrsize_path <ChromSizeFile> -WriteUnique
+
+
+When you have created the merged mappability of each chromosome once for C :math:`\rightarrow` T genome
+and once for G :math:`\rightarrow` A genome, you should use combine_umaps.py and specify -kmer_dir_2 ::
+
+ qsub <...> -t 1-<NumberOfChromosomes> python combine_umaps.py <OutDirC2T> <ChromSizePath> -out_dir <OutDir> -kmer_dir_2 <OutDirG2A>
+
+
+Requesting Genomes
+------------------
+
+In case you need these data for other genomes and do not have access to a Sun Grid Engine computing cluster,
+we may accept to do this for you.
+Please contact the software maintainer by email and we will do our best to assist you as soon as possible.
+
+
+
+Contact, support and questions
+------------------------------
+
+For support of Umap, please user our `mailing list <https://groups.google.com/forum/#!forum/ubismap>`_.
+Specifically, if you want to report a bug or request a feature,
+please do so using
+the `Umap issue tracker <https://bitbucket.org/hoffmanlab/umap/issues>`_.
+We are interested in all comments on the package,
+and the ease of use of installation and documentation.
+
+
+Credits
+-------
+
+
+Umap was originally developed by Anshul Kundaje and was written in MATLAB.
+The original repository is available `here <https://sites.google.com/site/anshulkundaje/projects/mappability>`_.
+The version of Umap that is available in this repository, is a python reimplementation of the original Umap, and
+is initially written by Mehran Karimzadeh.
diff --git a/build/lib/umap/__init__.py b/build/lib/umap/__init__.py
new file mode 100644
index 0000000..a2ef449
--- /dev/null
+++ b/build/lib/umap/__init__.py
@@ -0,0 +1,6 @@
+from get_kmers import GetKmers
+from run_bowtie import BowtieWrapper
+from unify_bowtie import UnifyBowtie
+from combine_umaps import CombineUmaps
+from uint8_to_bed import Int8Handler
+import map_bed
diff --git a/build/lib/umap/combine_umaps.py b/build/lib/umap/combine_umaps.py
new file mode 100644
index 0000000..37a4caf
--- /dev/null
+++ b/build/lib/umap/combine_umaps.py
@@ -0,0 +1,183 @@
+from argparse import ArgumentParser
+import gzip
+import numpy as np
+import os
+
+
+def get_args():
+ parser = ArgumentParser(
+ description="Combines mappability uint8 vectors of "
+ "several kmers into 1 uint8 vector per chromosome. "
+ "It requires a directory with subfolders names as "
+ "k<read length>. This script requires a number to infer "
+ "chromosome. If not specifying -job_id, it will "
+ "identify the chromosome using -var_id environmental "
+ "varibale which by default is SGE_TASK_ID.")
+ parser.add_argument(
+ "kmer_dir",
+ help="Directory with subfolders "
+ "named as k<read length>)")
+ parser.add_argument(
+ "chrsize_path",
+ help="Path to 2 column tsv file with first column "
+ "as chromosome and second column as its size. Will "
+ "be used to identify order of the chromosomes.")
+ parser.add_argument(
+ "-out_dir",
+ default="infer",
+ help="If not specified, a subfolder "
+ "will be created in kmer_dir names as "
+ "globalmap_k<smallestkmer>tok<largestkmer>")
+ parser.add_argument(
+ "-job_id",
+ default=0,
+ type=int,
+ help="1-based index for finding chromosome from -chrsize_path. "
+ "If not specified, it will user -var_id to "
+ "infer the chromosome for combining mappabilitiy of "
+ "different kmers.")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="If -job_id is not specified, job_id will be inferred "
+ "from environmental variable -var_id.")
+ parser.add_argument(
+ "-kmer_dir_2",
+ default="NA",
+ help="Specify to merge kmers of two different directories "
+ "by logical operation AND.")
+ args = parser.parse_args()
+ job_id = args.job_id
+ out_dir = args.out_dir
+ kmers = [each_kmer for each_kmer in next(os.walk(args.kmer_dir))[1]
+ if "k" == each_kmer[0]]
+ if len(kmers) < 1:
+ raise ValueError("{} lacks kmer folders".format(args.kmer_dir))
+ if args.job_id == 0:
+ job_id = int(os.environ[args.var_id]) - 1
+ else:
+ job_id = job_id - 1
+ if args.out_dir == "infer":
+ kmer_ints = [int(each_kmer.replace("k", "")) for each_kmer in kmers]
+ out_dir = "{}/globalmap_k{}tok{}".format(
+ args.kmer_dir, min(kmer_ints), max(kmer_ints))
+ try:
+ out_list = [args.kmer_dir, args.chrsize_path,
+ out_dir, job_id, args.kmer_dir_2]
+ except:
+ raise ValueError(
+ "chrsize_path or job_id were invalid.")
+ if not os.path.exists(out_dir):
+ os.makedirs(out_dir)
+ return out_list
+
+
+class CombineUmaps:
+ def __init__(self, kmer_dir, chrsize_path,
+ out_dir, job_id, kmer_dir_2):
+ """Combine <chr>.<kmer>.uint8.unique.gz files
+
+ The kmer_dir has subfolders named as k<integer> with
+ <chr>.<kmer>.uint8.unique.gz files inside. This script
+ will use the job_id to use a particular chromosome and
+ merge the uint8.gz files across all of the different
+ kmers into one uint8.gz. Note: All methods would
+ run consequently when creating the class instance.
+
+ Args:
+ kmer_dir: Directory with k<integer> subfolders
+ chrsize_path: 2-column tsv file of <chrom>\t<size>\n...
+ out_dir: Output files will be saved to this folder
+ job_id: 0-based index to find chromosome from chrsize_path
+ kmer_dir_2: If using Bismap and want to merge C2T and G2A data
+
+ Returns
+ Saves the output to outdir/<chrom>.uint8.unique.gz files
+ """
+ self.kmer_dir = kmer_dir
+ self.kmer_dir_2 = kmer_dir_2
+ self.chrsize_path = chrsize_path
+ self.out_dir = out_dir
+ self.job_id = job_id
+ self.chrom, self.size = self.get_chrom_size()
+ self.kmers = [each_kmer for each_kmer in
+ next(os.walk(self.kmer_dir))[1]
+ if "k" == each_kmer[0]]
+ combined_ar = self.combine_uints()
+ self.write_ar(combined_ar)
+
+ def get_chrom_size(self):
+ """Finds chrom and size from self.chrsize_path"""
+ with open(self.chrsize_path, "r") as chrsize_link:
+ ind_chr = 0
+ for chrsize_line in chrsize_link:
+ if ind_chr == self.job_id:
+ chromosome = chrsize_line.rstrip().split("\t")[0]
+ size = int(chrsize_line.rstrip().split("\t")[1])
+ ind_chr = ind_chr + 1
+ return chromosome, size
+
+ def combine_uints(self):
+ """Merged different kmer arrays of one chromosome
+ """
+ MergeKmers = False
+ if os.path.exists(self.kmer_dir_2):
+ print(
+ "Limit mappability to regions {} {} and {}".format(
+ "that are unique in both",
+ kmer_dir, kmer_dir_2))
+ MergeKmers = True
+ combined_ar = np.zeros(self.size, dtype=np.uint8)
+ kmer_nums = [int(kmer.replace("k", "")) for kmer in self.kmers]
+ kmer_nums.sort()
+ for kmer_num in kmer_nums:
+ kmer = "k{}".format(kmer_num)
+ full_kmer_path = "{}/{}/{}.{}.uint8.unique.gz".format(
+ self.kmer_dir, kmer, self.chrom, kmer)
+ if not os.path.exists(full_kmer_path):
+ raise ValueError("{} does not exist".format(full_kmer_path))
+ kmer_link = gzip.open(full_kmer_path, "rb")
+ kmer_ar = np.frombuffer(kmer_link.read(), dtype=np.uint8)
+ if len(kmer_ar) != self.size:
+ kmer_ar = np.append(kmer_ar, np.zeros(kmer_num))
+ kmer_link.close()
+ index_comb_0 = combined_ar == 0
+ index_kmer = kmer_ar != 0
+ index_adkmer = np.logical_and(index_comb_0, index_kmer)
+ if MergeKmers:
+ full_kmer_path_2 = "{}/{}/{}.{}.uint8.unique.gz".format(
+ self.kmer_dir_2, kmer, self.chrom, kmer)
+ kmer_link_2 = gzip.open(full_kmer_path_2, "rb")
+ kmer_ar_2 = np.frombuffer(kmer_link_2.read(), dtype=np.uint8)
+ if len(kmer_ar_2) != self.size:
+ kmer_ar_2 = np.append(kmer_ar_2, np.zeros(kmer_num))
+ kmer_link_2.close()
+ index_kmer_2 = kmer_ar_2 != 0
+ index_adkmer_2 = np.logical_and(index_comb_0, index_kmer_2)
+ index_adkmer = np.logical_and(index_adkmer, index_adkmer_2)
+ combined_ar[index_adkmer] = kmer_num
+ print(
+ "Added information of {} for {}".format(
+ kmer, self.chrom))
+ return combined_ar
+
+ def write_ar(self, combined_ar):
+ """Writes merged array to unsigned 8bit integer file.
+
+ Used self.out_dir and self.chrom.
+
+ Args:
+ combined_ar: Can be any numpy array
+ """
+ if not os.path.exists(self.out_dir):
+ os.makedirs(self.out_dir)
+ out_path = "{}/{}.uint8.unique.gz".format(
+ self.out_dir, self.chrom)
+ out_link = gzip.open(out_path, "wb")
+ out_link.write(combined_ar.tobytes())
+ out_link.close()
+
+
+if __name__ == "__main__":
+ kmer_dir, chrsize_path, out_dir, job_id, kmer_dir_2 = get_args()
+ CombineUmaps(kmer_dir, chrsize_path, out_dir, job_id, kmer_dir_2)
diff --git a/build/lib/umap/get_kmers.py b/build/lib/umap/get_kmers.py
new file mode 100644
index 0000000..a4fb0d4
--- /dev/null
+++ b/build/lib/umap/get_kmers.py
@@ -0,0 +1,265 @@
+from argparse import ArgumentParser
+import gzip
+import numpy as np
+import os
+import pandas as pd
+
+
+def get_args():
+ parser = ArgumentParser(
+ description="Creates list of unique Kmers "
+ "for each 1Mb of the genome. Relies on an environmental "
+ "variable such as SGE_TASK_ID to identify the correct "
+ "megabase of the genome for this purpose. "
+ "If not using job arrays, specify -job_id manually.")
+ parser.add_argument(
+ "chromsize_path",
+ help="Path to 2 column tsv file where first column is "
+ "chromosome name and second column is chromosome size")
+ parser.add_argument(
+ "out_dir",
+ help="Path to the directory for creating "
+ "<chromosome>.<Megabase>.<kmer>.kmer.gz files")
+ parser.add_argument(
+ "chr_dir",
+ help="Path to directory with <chromosome>.fasta files.")
+ parser.add_argument(
+ "idx_path",
+ help="Path to the 4 column file with the following columns: "
+ "Index | Chromosome | Start | End. This file will be used "
+ "for identifying the chunk of the chromosome.")
+ parser.add_argument(
+ "--kmer",
+ default="infer",
+ help="The software would infer it based on the "
+ "name of the 'out_dir'. If it is set and "
+ "contradicts the 'out_dir', a subfolder "
+ "under out_dir will be created named 'kmer' and "
+ "out_dir will be changed to that.")
+ parser.add_argument(
+ "--job_id",
+ default=0,
+ type=int,
+ help="If not submitted in job array, would require this "
+ "parameter to be set. (1-based index)")
+ parser.add_argument(
+ "--var_id",
+ default="SGE_TASK_ID",
+ help="The variable name that the script would use "
+ "for identifying the job id. By default: SGE_TASK_ID.")
+ args = parser.parse_args()
+ out_dir = args.out_dir
+ inferred_kmer = args.out_dir.split("/")[-1]
+ kmer = args.kmer
+ job_id = args.job_id
+ if args.kmer == "infer":
+ kmer = inferred_kmer
+ elif args.kmer != inferred_kmer:
+ kmer = args.kmer
+ out_dir = "{}/{}".format(out_dir, kmer)
+ if job_id == 0:
+ job_id = int(os.environ[args.var_id]) - 1
+ out_list = [args.chromsize_path, out_dir,
+ kmer, job_id, args.chr_dir,
+ args.idx_path]
+ return out_list
+
+
+class GetKmers:
+ def __init__(self, out_dir, kmer, job_id,
+ chr_dir, chromsize_path, idx_path):
+ """Creates all the possible k-mers for part of the genome.
+
+ Used a referece file to find the appropriate chromosome,
+ start and end position. Passes through the fasta file
+ of the chromosome and generates all of the possible k-mers.
+
+ Args:
+ :param out_dir: Directory for saving <chrom>.<jobid>.kmer.gz files
+ :param str kmer: k-mer string such as 'k24'
+ :param int job_id: Reference ID used for finding chrom, start and end
+ :param chr_dir: Path to directory with chromosome fasta files
+ :param chromsize_path: Path to 2 column file of chrom\tsize\n
+ :param idx_path: Path to 4 column file of index\tchrom\t\st\tend\n
+
+ :returns: An object with methods such as get_step_fasta(),
+ get_seq_ar(), write_kmers() and write_regions().
+
+ :raises ValueError: if expected chromosome path does not exist
+ """
+ self.out_dir = out_dir
+ self.kmer = kmer
+ self.job_id = job_id
+ self.chromsize_path = chromsize_path
+ self.chr_dir = chr_dir
+ self.idx_path = idx_path
+ self.chrom, self.start, self.end = self.get_region()
+ self.chrom_path = "{}/{}.fasta".format(
+ self.chr_dir, self.chrom)
+ if not os.path.exists(self.chrom_path):
+ raise ValueError(
+ "{} does not exist".format(self.chrom_path))
+ elif not os.path.exists(self.idx_path):
+ raise ValueError(
+ "{} does not exist".format(self.idx_path))
+
+ def get_region(self):
+ """Find chromosomal chunk
+
+ Using job_id and chromsize_path, finds chromosome,
+ start and end. Looks if chrsize_index.tsv exists.
+ If it doesn't, it will create chrsize_index.tsv.
+ Otherwise will use it for finding that information.
+
+ :returns: chrom, start, end
+
+ :raises ValueError: If job_id is out of expected range
+ """
+ job_id = self.job_id
+ idx_path = self.idx_path
+ idx_df = pd.read_csv(idx_path, sep="\t", index_col=0)
+ dict_idx = idx_df.to_dict()
+ try:
+ chrom, start, end = [
+ dict_idx[each_line][job_id] for
+ each_line in ["Chromosome", "Start", "End"]]
+ except:
+ raise ValueError(
+ "{} Job id is larger than available indices".format(
+ job_id))
+ return chrom, int(start), int(end)
+
+ def get_step_fasta(self):
+ """Finds number of nucleotides at each line of FASTA
+
+
+ :raises ValueError: If top 10 FASTA lines have
+ sequences of varying length
+ """
+ chrom_path = self.chrom_path
+ line_nums = 10
+ len_lines = []
+ with open(chrom_path, "r") as chr_link:
+ for line_num in range(line_nums):
+ chr_line = chr_link.readline().rstrip()
+ if ">" not in chr_line:
+ len_line = len(chr_line)
+ if len_line not in len_lines:
+ if chr_line != "":
+ len_lines.append(len_line)
+ if len(len_lines) == 1:
+ return(len_lines[0])
+ else:
+ raise ValueError(
+ "Top 10 FASTA lines have sequences of varying length")
+
+ def get_seq_ar(self, fasta_fix):
+ """Gets sequence as numpy array
+
+ get_seq_ar creates a numpy array matching sequence
+ of the region specified by chromosome, start and
+ end. However it starts the sequence with kmer - 1
+ less than the specified start to account for the
+ missing kmers from the previous chunk of chromosome.
+ Each element is one line of a fasta file that may be
+ cut to match the exact start/end positions.
+
+ Args:
+ :param int fasta_fix: Number of nucleotides per fasta line.
+
+ :returns: Numpy array with each member being one line of FASTA
+ """
+ start = self.start
+ end, chrom_path = self.end, self.chrom_path
+ kmer = int(self.kmer.replace("k", ""))
+ start = start - kmer
+ if start < 0:
+ start = 0
+ st_line = int(np.floor(start / fasta_fix))
+ st_line_pos = start % fasta_fix
+ end_line = int(np.floor(end / fasta_fix))
+ end_line_pos = (end % fasta_fix) + 1
+ seq_ar = np.empty(int(end_line - st_line + 1),
+ dtype="|S{}".format(fasta_fix + 1))
+ ind_seq = 0
+ STORE_LINE = False
+ with open(chrom_path, "r") as chr_link:
+ line_ind = 0
+ for each_line in chr_link:
+ if line_ind == st_line:
+ STORE_LINE = True
+ each_line = each_line.rstrip()[st_line_pos:]
+ if STORE_LINE:
+ if line_ind == end_line:
+ STORE_LINE = False
+ each_line = each_line.rstrip()[:end_line_pos]
+ seq_ar[ind_seq] = each_line.rstrip()
+ ind_seq = ind_seq + 1
+ line_ind = line_ind + 1
+ if "chr" in seq_ar[0]:
+ seq_ar = seq_ar[1:]
+ return seq_ar
+
+ def write_kmers(self, cur_seq, kmer_int, out_link):
+ """Creates k-mers and saves them to the file
+
+ Using a numpy array of sequences, generates and
+ saves all of the possible k-mers.
+
+ Args:
+ :param cur_seq: A string of sequences
+ :param kmer_int: An integer denoting the k-mer size
+ :param out_link: File link for writing k-mers
+
+ :returns: May modify cur_seq by deducing the k-mers that
+ are written to the out_link file object.
+ """
+ if len(cur_seq) < kmer_int:
+ return cur_seq
+ elif len(cur_seq) == kmer_int:
+ out_link.write(cur_seq + "\n")
+ cur_seq = cur_seq[1:]
+ return cur_seq
+ else:
+ for i in range(len(cur_seq) - kmer_int):
+ j = i + kmer_int
+ if j > len(cur_seq):
+ j = len(cur_seq)
+ seq_out = cur_seq[i:j]
+ if "N" not in seq_out:
+ out_link.write(seq_out + "\n")
+ cur_seq = cur_seq[(i + 1):]
+ return cur_seq
+
+ def write_region(self):
+ """Wrapper of GetKmers to get and write k-mers
+
+ write_region method executes all the other methods
+ of the GetKmers class for writing out all of the
+ possible k-mers from chunk of a FASTA file.
+ """
+ out_dir, kmer, job_id = self.out_dir, self.kmer, self.job_id
+ chrom = self.chrom
+ start, end = self.start, self.end
+ out_path = "{}/{}.{}.{}.kmer.gz".format(
+ out_dir, chrom, job_id, kmer.replace("k", ""))
+ out_link = gzip.open(out_path, "wb")
+ fasta_fix = self.get_step_fasta()
+ kmer_int = int(kmer.replace("k", ""))
+ seq_ar = self.get_seq_ar(fasta_fix)
+ cur_seq = ""
+ for each_seq in seq_ar:
+ cur_seq = cur_seq + each_seq
+ cur_seq = self.write_kmers(cur_seq, kmer_int, out_link)
+ print("Created all sequences for {}:{}-{}".format(
+ chrom, start, end))
+ out_link.close()
+
+
+if __name__ == "__main__":
+ chromsize_path, out_dir, kmer, job_id, chr_dir, idx_path = get_args()
+ GetKmerObj = GetKmers(
+ out_dir, kmer, job_id,
+ chr_dir, chromsize_path,
+ idx_path)
+ GetKmerObj.write_region()
diff --git a/build/lib/umap/handle_fasta.py b/build/lib/umap/handle_fasta.py
new file mode 100644
index 0000000..e1b8288
--- /dev/null
+++ b/build/lib/umap/handle_fasta.py
@@ -0,0 +1,181 @@
+from argparse import ArgumentParser
+from datetime import datetime
+import numpy as np
+import os
+from subprocess import call
+
+
+class FastaHandler:
+ def __init__(self, in_path, out_path, chrsize_path,
+ chr_dir, complement=True, conversion="None"):
+ """Reverse complement the genome for Bismap
+
+ This class generates the necessary FASTA files
+ for running Umap or Bismap. If using Bismap,
+ a reverse complemented set of chromosomes for
+ the specified conversion will be produced.
+
+ :param in_path: Path to genome .fasta file
+ :param out_path: Path to output .fasta file
+ :param chrsize_path: Path to 2-column chrom\tsize\n file
+ :param chr_dir: Path to directory for
+ writing chromosome fasta files
+ :param complement: If reverse complemented chromosomes
+ must be created
+ :param conversion: One of 'None', 'C2T' or 'G2A'
+ """
+ self.in_path = in_path
+ self.out_path = out_path
+ self.chrsize_path = chrsize_path
+ self.chr_dir = chr_dir
+ self.complement = complement
+ self.conversion = conversion
+
+ def handle_fasta(self):
+ """Wrapper function of FastaHandler
+
+ Writes individual fasta files for each chromosome
+ and converts nucleotides or reverse complements
+ sequences if necessary (for Bismap feature)
+ """
+ chrsize_dict = self.get_chrsize_dict()
+ print("Reverse complementation: {}".format(self.complement))
+ print("Nucleotide conversion: {}".format(self.conversion))
+ if not os.path.exists(self.chr_dir):
+ os.makedirs(self.chr_dir)
+ chr_path = self.chr_dir + "/chr1.fasta"
+ chr_link = open(chr_path, "w")
+ if self.complement:
+ chr_path_rc = chr_path.replace(".fasta", "_RC.fasta")
+ chr_link_rc = open(chr_path_rc, "w")
+ out_link_rc = open(self.out_path.replace(
+ ".fasta", "_RC.fasta"), "w")
+ out_link = open(self.out_path, "w")
+ ad_fin = ""
+ chr_len = 0
+ if self.complement:
+ complement_ar = np.zeros(10)
+ with open(self.in_path, "r") as fas_link:
+ for each_line in fas_link:
+ ad_line = each_line.rstrip()
+ if ">chr" in ad_line:
+ if " " in ad_line:
+ ad_line = ad_line.split(" ")[0]
+ if "\t" in ad_line:
+ ad_line = ad_line.split("\t")[0]
+ chr_link.close()
+ print ad_fin
+ chrom = ad_line[1:]
+ chr_path = "{}/{}.fasta".format(
+ self.chr_dir, chrom)
+ chr_link = open(chr_path, "w")
+ if self.complement:
+ if complement_ar[0] != 0:
+ self.write_reverse(complement_ar, chr_link_rc,
+ out_link_rc, chr_len, chrom)
+ chr_len = chrsize_dict[chrom]
+ complement_ar = np.empty((chr_len), dtype="|S8")
+ start = 0
+ ad_line_rc = ad_line + "_RC"
+ chr_link_rc.close()
+ chr_link_rc = open(
+ chr_path.replace(".fasta", "_RC.fasta"), "w")
+ out_link_rc.write(ad_line_rc + "\n")
+ chr_link_rc.write(ad_line_rc + "\n")
+ print "%s started at %s" % (ad_line, str(datetime.now()))
+ else:
+ ad_line = ad_line.upper()
+ if self.complement:
+ ad_line_rc = ad_line.replace("A", "1")
+ ad_line_rc = ad_line_rc.replace("T", "A")
+ ad_line_rc = ad_line_rc.replace("C", "2")
+ ad_line_rc = ad_line_rc.replace("G", "C")
+ ad_line_rc = ad_line_rc.replace("1", "T")
+ ad_line_rc = ad_line_rc.replace("2", "G")
+ # ad_line_rc = ad_line_rc[::-1]
+ if self.conversion == "C2T":
+ ad_line = ad_line.replace("C", "T")
+ ad_line_rc = ad_line_rc.replace("C", "T")
+ elif self.conversion == "G2A":
+ ad_line = ad_line.replace("G", "A")
+ ad_line_rc = ad_line_rc.replace("G", "A")
+ ad_fin = ad_line + "\n"
+ out_link.write(ad_fin)
+ chr_link.write(ad_fin)
+ if self.complement:
+ ad_fin_rc = ad_line_rc + "\n"
+ if "chr" not in ad_fin_rc:
+ end_pos = start + len(ad_line_rc)
+ try:
+ complement_ar[start:end_pos] = list(ad_line_rc)
+ except:
+ print(
+ "{} to {} with length of {}".format(
+ start, end_pos,
+ len(range(start, end_pos))))
+ print(ad_line_rc)
+ raise ValueError("Failed to add sequences")
+ start = start + len(ad_line_rc)
+ out_link.close()
+ chr_link.close()
+ if self.complement:
+ self.write_reverse(complement_ar, chr_link_rc,
+ out_link_rc, chr_len, chrom)
+ out_link_rc.close()
+ chr_link_rc.close()
+ call(" ".join(["cat", self.out_path.replace(".fasta", "_RC.fasta"),
+ ">>", self.out_path]), shell=True)
+ call(["mv", self.out_path.replace(".fasta", "_RC.fasta"),
+ self.out_path.replace(".fasta", "_Deprecated_RC.fasta")])
+
+ def write_reverse(complement_ar, chr_link_rc,
+ out_link_rc, chr_len, chrom):
+ complement_ar = complement_ar[::-1]
+ print("Length of {} was {}".format(chrom, chr_len))
+ for start in range(0, chr_len, 50):
+ end = start + 50
+ if end > chr_len:
+ end = chr_len
+ ad_seq = "".join(complement_ar[start:end])
+ out_link_rc.write(ad_seq + "\n")
+ chr_link_rc.write(ad_seq + "\n")
+
+ def get_chrsize_dict(self):
+ chrsize_dict = {}
+ with open(self.chrsize_path, "r") as chrsize_link:
+ for chrsize_line in chrsize_link:
+ chrom, size = chrsize_line.rstrip().split("\t")
+ chrsize_dict[chrom] = int(size)
+ return chrsize_dict
+
+
+if __name__ == "__main__":
+ parser = ArgumentParser(
+ description="Reverse complements a fasta genome")
+ parser.add_argument(
+ "in_fasta",
+ help="FASTA format genome")
+ parser.add_argument(
+ "out_fasta",
+ help="Output FASTA full path")
+ parser.add_argument(
+ "chrsize_path",
+ help="Path to 2 column file with first column "
+ "being the chromosome name and the second "
+ "column being the chromosome size")
+ parser.add_argument(
+ "chr_dir",
+ help="Path to directory for writing individual "
+ "fasta files for each chromosome")
+ parser.add_argument(
+ "--Complement",
+ action="store_true",
+ help="Create a double genome with both "
+ "+ and - strand information")
+ parser.add_argument(
+ "-Conversion",
+ help="Specify C2T or G2A")
+ args = parser.parse_args()
+ FastaObj = FastaHandler(args.in_fasta, args.out_fasta, args.chrsize_path,
+ args.chr_dir, args.Complement, args.Conversion)
+ FastaObj.handle_fasta()
diff --git a/build/lib/umap/map_bed.py b/build/lib/umap/map_bed.py
new file mode 100644
index 0000000..23e5dc1
--- /dev/null
+++ b/build/lib/umap/map_bed.py
@@ -0,0 +1,262 @@
+from argparse import ArgumentParser
+import gzip
+import numpy as np
+import os
+import pandas as pd
+import re
+
+
+def get_args():
+ parser = ArgumentParser(
+ description="This script expects an input "
+ "gzipped BED file, a directory with umap/bismap "
+ "produced files names as <chr>.uint8."
+ "unique.gz. It will add one column to the bed "
+ "file which would determine the fraction of "
+ "uniquely mappable reads that passover this "
+ "region. The first column added to input is "
+ "single-read mappability, which is the percent "
+ "of the region that is uniquely mappable. "
+ "The second added column is the multi-read"
+ " mappability; the probability that a randonly "
+ "selected read overlapping with that region "
+ "is uniquely mappable. If the input BED file "
+ "has 1 bp intervals, you can specify -SingleNucleotide "
+ "and -wigdir to use a faster algorithm.")
+ parser.add_argument(
+ "bed_path",
+ help="Path to gzipped bed file")
+ parser.add_argument(
+ "out_path",
+ help="Path to gzipped output file")
+ parser.add_argument(
+ "umap_dir",
+ help="Path to directory with uint8 binary "
+ "files produced by Umap/Bismap.")
+ parser.add_argument(
+ "kmer",
+ type=int,
+ help="The read length for defining single-read "
+ "and multi-read mappability.")
+ parser.add_argument(
+ "-SingleNucleotide",
+ action="store_true",
+ help="If specified, assumes each region is only one "
+ "nucleotide. You must specify -wig as well.")
+ parser.add_argument(
+ "-wigdir",
+ default="",
+ help="Path to directory with <kmer>_<chrom>."
+ "MultiTrackMappability.wg.gz files.")
+ args = parser.parse_args()
+ if args.SingleNucleotide:
+ if not os.path.exists(args.wigdir):
+ raise ValueError("-wigdir didn't exist!")
+ out_list = [args.bed_path, args.out_path,
+ args.umap_dir, args.kmer,
+ args.wigdir]
+ return out_list
+
+
+def load_wig(wig_path, chrom_size):
+ '''
+ Translated a fixed step wig file of a chromosome
+ with step size 1 to a numpy array.
+ Will be used internally by BedMappability.
+ Unexpected behaviour if wig file has multiple
+ chromosomes.
+ '''
+ wig_ar = np.zeros(chrom_size, dtype=float)
+ pos = 0
+ with gzip.open(wig_path, "rb") as wig_link:
+ for wig_line in wig_link:
+ if "start" in wig_line:
+ pos_str = wig_line.rstrip().split(" ")[2]
+ pos = int(pos_str.replace("start=", "")) - 1
+ else:
+ value = float(wig_line.rstrip())
+ wig_ar[pos] = value
+ pos = pos + 1
+ print("Loaded {}".format(wig_path))
+ return wig_ar
+
+
+def bed_handler(bed_path):
+ '''
+ Saves a gzipped BED file to a pandas
+ dataframe.
+ '''
+ no_header = True
+ with gzip.open(bed_path, "rb") as bed_link:
+ header_line = bed_link.readline()
+ header_list = header_line.rstrip().split("\t")
+ if len(header_list) < 3:
+ no_header = False
+ elif "chr" not in header_list[0]:
+ no_header = False
+ if no_header:
+ bed_df = pd.read_csv(
+ bed_path,
+ sep="\t",
+ header=None,
+ compression="gzip")
+ else:
+ bed_df = pd.read_csv(
+ bed_path,
+ skiprows=1,
+ sep="\t",
+ header=None,
+ compression="gzip")
+ column_names = list(bed_df.columns)
+ column_names[:3] = ["Chromosome", "Start", "End"]
+ bed_df.columns = column_names
+ return bed_df
+
+
+def subsetter(my_list, regex):
+ '''
+ Finds elements of a list matching a regex
+ '''
+ out_list = []
+ for each in my_list:
+ RE = re.search(regex, each)
+ if RE:
+ out_list.append(each)
+ return out_list
+
+
+class BedMappability:
+ '''
+ This class provides methods for identifying
+ single-read and multi-read mappability of
+ an input BED file. it uses local functions
+ such as bed_handler and get_wig if necessary.
+ '''
+ def __init__(self, bed_path, umap_dir,
+ out_path, kmer, wigdir="NA"):
+ '''
+
+ :param bed_path: Input gzipped BED path
+ :param umap_dir: Umap/Bismap unique uint directory
+ :param out_path: Path to output gzipped BED
+ :param kmer: Integer kmer size
+ :param wigdir: Directory of multi-read mappability
+ files of different chromosomes. Optional.
+ '''
+ self.bed_path = bed_path
+ self.umap_dir = umap_dir
+ self.out_path = out_path
+ self.kmer = kmer
+ self.kmer_str = "k{}".format(kmer)
+ self.wigdir = wigdir
+
+ def annotate_bed(self):
+ '''
+ Main motor method for getting single-read
+ and multi-read mappability of BedMappability object.
+
+ Returns:
+ Pandas dataframe BED file with mappability info
+ '''
+ bed_df = bed_handler(self.bed_path)
+ all_chrs = list(pd.unique(bed_df["Chromosome"]))
+ all_chrs.sort()
+ bed_out_list = []
+ for each_chr in all_chrs:
+ print("Started working on {}".format(each_chr))
+ temp_df = bed_df[bed_df["Chromosome"] == each_chr]
+ mapped_df = self.get_df_mappability(temp_df, each_chr)
+ if len(mapped_df) > 0:
+ bed_out_list.append(mapped_df)
+ out_df = pd.concat(bed_out_list)
+ return out_df
+
+ def get_df_mappability(self, temp_df, cur_chr):
+ '''
+ Internally used method for finding the single-read
+ and multi-read mappability of a bed file for a given
+ chromosome.
+ '''
+ dists = pd.unique(temp_df.iloc[2] - temp_df.iloc[1])
+ FIXED_DIST_1 = False
+ if len(dists) < 2:
+ if 1 in dists or 0 in dists:
+ FIXED_DIST_1 = True
+ temp_df["SingleRead.Mappability"] = 0
+ temp_df["MultiRead.Mappability"] = 0
+ umap_paths = subsetter(os.listdir(self.umap_dir),
+ "uint8.unique.gz")
+ umap_path = subsetter(umap_paths, "{}.uint".format(cur_chr))
+ if len(umap_path) == 0:
+ temp_df = []
+ else:
+ umap_path = umap_path[0]
+ uint_path = "{}/{}".format(
+ self.umap_dir, umap_path)
+ uint_link = gzip.open(uint_path, "rb")
+ uint_ar = np.frombuffer(uint_link.read(), dtype=np.uint8)
+ uint_link.close()
+ print("Using {}".format(umap_path))
+ kmer = self.kmer
+ wig_path = "{}/{}_{}.MultiTrackMappability.wg.gz".format(
+ self.wigdir, self.kmer_str, cur_chr)
+ if os.path.exists(wig_path) and FIXED_DIST_1:
+ wig_ar = load_wig(wig_path, len(uint_ar))
+ temp_df["MultiRead.Mappability"] = \
+ wig_ar[temp_df.iloc[:, 1] - 1]
+ temp_df["SingleRead.Mappability"] = \
+ temp_df["MultiRead.Mappability"]
+ ind_unique, = np.where(temp_df["SingleRead.Mappability"] > 0)
+ temp_df["SingleRead.Mappability"].iloc[ind_unique] = 1
+ else:
+ less_than_kmer = uint_ar <= kmer
+ not_zero = uint_ar != 0
+ uniquely_mappable = np.array(
+ np.logical_and(less_than_kmer, not_zero),
+ dtype=int)
+ for i in range(temp_df.shape[0]):
+ chr, start, end = temp_df.iloc[i, :3]
+ st_vec = start - kmer
+ if st_vec < 0:
+ st_vec = 0
+ region_vec = np.zeros(
+ len(range(st_vec, end + 1)),
+ dtype=float)
+ single_vec = np.zeros(
+ len(range(st_vec, end + 1)),
+ dtype=float)
+ idxs_unique, = np.where(
+ [each_idx == 1 for each_idx in
+ uniquely_mappable[st_vec:(end + 1)]])
+ for idx_unique in idxs_unique:
+ end_idx = idx_unique + kmer
+ if end_idx > len(region_vec):
+ end_idx = len(region_vec)
+ region_vec[idx_unique:end_idx] = 1
+ single_vec[idx_unique:end_idx] = \
+ single_vec[idx_unique:end_idx] + 1
+ unique_map_percent = float(
+ sum(single_vec[kmer:(kmer + end - start + 1)] > 0)) /\
+ float(len(single_vec[kmer:(kmer + end - start + 1)]))
+ map_prob = float(len(idxs_unique)) / float(len(region_vec))
+ temp_df.iloc[i, -1] = map_prob
+ temp_df.iloc[i, -2] = unique_map_percent
+ return temp_df
+
+ def write_bed(self, mapped_df):
+ '''
+ Use this method to write the output of
+ BedMappability.annotate_bed() to a gzipped file,
+ '''
+ out_link = gzip.open(self.out_path, "wb")
+ mapped_df.to_csv(out_link, sep="\t", index=False, header=False)
+ out_link.close()
+ print("Successfully created {}".format(self.out_path))
+
+
+if __name__ == "__main__":
+ bed_path, out_path, umap_dir, kmer, wigdir = get_args()
+ BedMapObj = BedMappability(bed_path, umap_dir,
+ out_path, kmer, wigdir)
+ mapped_df = BedMapObj.annotate_bed()
+ BedMapObj.write_bed(mapped_df)
diff --git a/build/lib/umap/run_bowtie.py b/build/lib/umap/run_bowtie.py
new file mode 100644
index 0000000..59db64c
--- /dev/null
+++ b/build/lib/umap/run_bowtie.py
@@ -0,0 +1,136 @@
+from argparse import ArgumentParser
+from datetime import datetime
+import os
+import re
+import subprocess
+
+
+def subset_list(list_items, regex):
+ out_list = []
+ for each_item in list_items:
+ RE = re.search(regex, each_item)
+ if RE:
+ out_list.append(each_item)
+ return out_list
+
+
+class BowtieWrapper:
+ def __init__(self, kmer_dir, bowtie_dir,
+ index_dir, index_name,
+ job_id, Bismap):
+ """Runs Bowtie one <chrom>.<kmer>.<jobid>.kmer.gz
+
+ Using the job_id, this function identifies
+ one kmer.gz file and runs bowtie on that and saves
+ the output to <chrom>.<kmer>.<jobid>.bowtie.gz.
+
+ :param kmer_dir: Directory with <chrom>.<kmer>.<jobid>.kmer.gz files
+ :param bowtie_dir: Directory with Bowtie 1.1.0 executable files.
+ :param index_dir: Directory with Bowtie index
+ :param index_name: Name used for generating Bowtie index files
+ :param int job_id: will be used for finding kmer.gz file
+ :param bool Bismap: Run bowtie with --norc
+
+ :returns: Saves the output to a file in the same directory as kmer_dir
+ """
+ self.kmer_dir = kmer_dir
+ self.bowtie_dir = bowtie_dir
+ self.index_dir = index_dir
+ self.index_name = index_name
+ self.job_id = job_id
+ self.Bismap = Bismap
+ self.execute_bowtie_command()
+
+ def execute_bowtie_command(self):
+ """The only method of BowtieWrapper
+
+ Will be executed automatically by BowtieWrapper
+
+ :raises ValueError: If job_id is out of expected range
+ """
+ if self.Bismap:
+ rev_comp = " --norc "
+ else:
+ rev_comp = ""
+ kmer_names = ["{}/{}".format(self.kmer_dir, each_kmer) for each_kmer
+ in subset_list(os.listdir(self.kmer_dir), ".kmer.gz$")]
+ kmer_names.sort()
+ LongIndex = False
+ short_ind_path = "{}/{}.1.ebwtl".format(
+ self.index_dir, self.index_name)
+ if os.path.exists(short_ind_path):
+ LongIndex = True
+ print("Switching to use of long index")
+ if job_id <= len(kmer_names):
+ try:
+ kmer_file = kmer_names[job_id]
+ except:
+ raise ValueError(
+ "{} does not exist. Time: {}".format(
+ job_id, str(datetime.now())))
+ print("processing Kmer File {}".format(kmer_file))
+ # kmer_name = kmer_dir.split("/")[-1]
+ kmer_path = "{}/{}".format(self.kmer_dir, kmer_file.split("/")[-1])
+ bowtie_out_path = kmer_path.replace(".kmer.gz", ".bowtie.gz")
+ first_part_of_command = "gunzip -c {} | {}/bowtie ".format(
+ kmer_path, self.bowtie_dir)
+ if LongIndex:
+ first_part_of_command = first_part_of_command +\
+ "--large-index "
+ bowtiecmd = first_part_of_command +\
+ "{}/{} ".format(self.index_dir, self.index_name) +\
+ "-v 0 -k 1 -m 1 {}--mm ".format(rev_comp) +\
+ "-r --refidx --suppress 5,6,7,8 - " +\
+ "| gzip -c > {}".format(bowtie_out_path)
+ subprocess.call(bowtiecmd, shell=True)
+ print("Executing {}".format(bowtiecmd))
+ else:
+ print("The length of files was {} but the index was {}".format(
+ len(kmer_names), job_id))
+
+
+def check_genome(index_dir, index_name):
+ all_idx_paths = [
+ each_path for each_path in
+ os.listdir(index_dir) if index_name in each_path]
+ if len(all_idx_paths) < 6:
+ raise ValueError("Index does not exist")
+
+
+if __name__ == "__main__":
+ parser = ArgumentParser(
+ description="Umap wrapper for running bowtie "
+ "on individual k-mer files.")
+ parser.add_argument(
+ "kmer_dir",
+ help="Directory containing the .kmer files")
+ parser.add_argument(
+ "bowtie_dir",
+ help="Directory containing bowtie executable")
+ parser.add_argument(
+ "index_dir",
+ help="Directory containing bowtie index")
+ parser.add_argument(
+ "index_name",
+ help="prefix name of bowtie index")
+ parser.add_argument(
+ "-Bismap",
+ action="store_true",
+ help="Run bowtie with --norc")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="HPC environmental variable for JOB ID")
+ parser.add_argument(
+ "-job_id",
+ type=int,
+ default=0,
+ help="1-based index for selecting a k-mer file")
+ args = parser.parse_args()
+ check_genome(args.index_dir, args.index_name)
+ job_id = args.job_id
+ if job_id == 0:
+ job_id = int(os.environ[args.var_id]) - 1
+ BowtieWrapper(args.kmer_dir, args.bowtie_dir,
+ args.index_dir, args.index_name, job_id,
+ args.Bismap)
diff --git a/build/lib/umap/ubismap.py b/build/lib/umap/ubismap.py
new file mode 100644
index 0000000..65fdf67
--- /dev/null
+++ b/build/lib/umap/ubismap.py
@@ -0,0 +1,636 @@
+from argparse import ArgumentParser
+from datetime import datetime
+import os
+import pandas as pd
+import re
+import subprocess
+from handle_fasta import FastaHandler
+
+
+class ArgHandler:
+ def __init__(self):
+ """Makes an argument class
+
+ Uses ArgumentParser and generates some local arguments as well
+ for direct use by other classes and functions.
+ """
+ parser = ArgumentParser(
+ description="This scripts is a wrapper that writes qsub "
+ "job submission commands for executing other scripts of the "
+ "software in order to identify mappability of a given genome "
+ "for a range of various read lengths. This script assumes "
+ "that you are using a cluster system that accepts the following "
+ "parameters: -N, -e, -o, -t, -tc, -cwd, "
+ "-b y, -terse. If these options do not exist in your "
+ "cluster, specify -write so you can modify the "
+ "qsub job submissions manually.")
+ parser.add_argument(
+ "fasta_path",
+ help="Path to the genome fasta file.")
+ parser.add_argument(
+ "chrsize_path",
+ help="Path to a 2-column file where the first column "
+ "is the chromosome name and the second column is its size")
+ parser.add_argument(
+ "out_dir",
+ help="Path to directory to create output files/folders")
+ parser.add_argument(
+ "queue_name",
+ help="Queue name for qsub job submission.")
+ parser.add_argument(
+ "bowtie_path",
+ help="Path to bowtie-build executable")
+ parser.add_argument(
+ "--kmers",
+ default=[24, 36, 50, 100],
+ nargs="*",
+ help="Kmer length for mappability. e.g. 24 36 50 100")
+ parser.add_argument(
+ "-GenomeReady",
+ action="store_true",
+ help="If in the 'out_dir' "
+ "there already exists a /chrs and /genome subdirectory "
+ "where genome directory has a genome.fasta "
+ "with bowtie index suffix as 'BisMap_bowtie.ind' or "
+ "'Umap_bowtie.ind' if --Bismap is not specified and "
+ "the ./chrs directory has indivudal chromosome "
+ "FASTA files, specify this option")
+ parser.add_argument(
+ "-Bismap",
+ action="store_true",
+ help="Specify --Bismap if double genome indexing is expected. "
+ "This would create a genome that is concatenation of forward "
+ "and reverse complement. If -C2T or -G2A is expected, "
+ "this must be specified")
+ parser.add_argument(
+ "-C2T",
+ action="store_true",
+ help="If --Bismap is provided, specify --C2T or --G2A")
+ parser.add_argument(
+ "-G2A",
+ action="store_true",
+ help="If --Bismap is provided, specify --C2T or --G2A")
+ parser.add_argument(
+ "-ExitAfterIndexing",
+ action="store_true",
+ help="If you only want the index, specify this option")
+ parser.add_argument(
+ "-SimultaneousJobs",
+ default=120,
+ type=int,
+ help="Number of jobs to run simultaneously")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="Environmental variable for accessing job IDs. "
+ "By default is set to SGE_TASK_ID assuming a sungrid "
+ "engine environment.")
+ parser.add_argument(
+ "-write_script",
+ default="False",
+ help="Specify -write <Path to output job submission file> "
+ "if instead of direct execution, "
+ "you want to save the job submission file.")
+ parser.add_argument(
+ "-pipe",
+ action="store_true",
+ help="If -pipe is specified, the software command "
+ "will be piped into the qsub command. For example "
+ "instead of: 'qsub -q <queuename> -N <jobname> "
+ "python <script>.py <arg1> <arg2>', 'echo python "
+ "<script>.py <arg1> <arg2> | qsub -q <queuename> "
+ "-N <jobname>' will be written/executed.")
+ parser.add_argument(
+ "-chunk",
+ default=1000000,
+ type=int,
+ help="Length of chromosomal chunks")
+ args = parser.parse_args()
+ out_dir = args.out_dir
+ chrom_dir, dir_kmers, index_dir = make_dir_structure(out_dir)
+ print("{} Jobs will be run simultaneously at each step".format(
+ args.SimultaneousJobs))
+ # Create paths and key parameters
+ chrsize_path = "{}/chrsize.tsv".format(out_dir)
+ if args.chrsize_path != chrsize_path:
+ subprocess.call(["cp", args.chrsize_path, chrsize_path])
+ chrsize_df = pd.read_csv(chrsize_path, sep="\t", names=["Chr", "Size"])
+ LenChrs = len(pd.unique(chrsize_df["Chr"]))
+ conversion = "None"
+ genome_path = "{}/genome.fa".format(index_dir)
+ # Make sure write is a new file
+ if args.write_script != "False":
+ with open(args.write_script, "w") as out_link:
+ out_link.write(
+ "# Bismap/Umap job submission commands follow.\n")
+ source_dir = os.getcwd()
+ if args.C2T:
+ if args.G2A:
+ raise ValueError("Cannot specify both -C2T and -G2A")
+ conversion = "C2T"
+ elif args.G2A:
+ conversion = "G2A"
+ if args.Bismap:
+ # It is possible that chrx_RC information does not exist
+ # in the chrsize.tsv file. The function below would check
+ # and add this information if necessary and would update
+ # chromosome length
+ len_chrs_after_complement = complement_chrsize_file(chrsize_path)
+ if len_chrs_after_complement != LenChrs:
+ LenChrs = len_chrs_after_complement
+ print "Length of chromosomes changed to %d to account for\
+ reverse complements" % LenChrs
+ idx_path = index_unique_kmer_jobids(chrsize_path, args.chunk)
+ self.genome_path = genome_path
+ self.chrom_dir = chrom_dir
+ self.dir_kmers = dir_kmers
+ self.chrsize_path = chrsize_path
+ self.out_dir = out_dir
+ self.idx_path = idx_path
+ self.conversion = conversion
+ self.Bismap = args.Bismap
+ self.queue_name = args.queue_name
+ self.kmers = args.kmers
+ self.SimultaneousJobs = args.SimultaneousJobs
+ self.ExitAfterIndexing = args.ExitAfterIndexing
+ self.var_id = args.var_id
+ self.write_script = args.write_script
+ self.source_dir = source_dir
+ self.GenomeReady = args.GenomeReady
+ self.fasta_path = args.fasta_path
+ self.bowtie_path = args.bowtie_path
+ self.LenChrs = LenChrs
+ self.pipe = args.pipe
+
+
+def pipe_job(job_list):
+ '''Assumes the qsub command has the
+ qsub ... -cwd -b y <executing command>.
+ It will change it to: echo <executing command>
+ | qsub ...'''
+ for ind_job in range(len(job_list)):
+ if job_list[ind_job] == "-cwd":
+ if job_list[ind_job + 1] == "-b":
+ if job_list[ind_job + 2] == "y":
+ ind_cwd = ind_job
+ try:
+ qsub_list = job_list[:ind_cwd]
+ exec_list = job_list[(ind_cwd + 3):]
+ piped_list = [
+ ['echo "'] + exec_list + ['" | '] + qsub_list]
+ return piped_list
+ except:
+ raise ValueError(
+ "The submitted command to pipe_job must "
+ "include -cwd -b y.")
+
+
+def index_genome(queue_name, converted_path,
+ bowtie_build_path, Bismap, write_path, pipe):
+ path_genome = "{}/genome.fa".format(converted_path)
+ if Bismap:
+ index_suffix = "BisMap_bowtie.ind"
+ else:
+ index_suffix = "Umap_bowtie.ind"
+ index_job_line = ["qsub", "-q", queue_name, "-terse",
+ "-N", "Index-Bowtie", "-o",
+ "{}/index_genome.LOG".format(converted_path),
+ "-e", "{}/index_genome.ERR".format(converted_path),
+ "-cwd", "-b", "y",
+ bowtie_build_path, path_genome,
+ "{}/{}".format(converted_path, index_suffix)]
+ if pipe:
+ index_job_line = pipe_job(index_job_line)
+ if write_path != "False":
+ job_num = write_job(index_job_line, write_path)
+ else:
+ try:
+ job_line = subprocess.Popen(index_job_line, stdout=subprocess.PIPE)
+ job_num = job_line.stdout.read().rstrip()
+ except:
+ raise ValueError(
+ "Your system is incompatible with direct job "
+ "submission. Please specify -write and manually "
+ "modify the job submission options.")
+ print "job id %s from indexing genome" % job_num
+ return index_suffix, job_num
+
+
+def get_unique_kmer_jobnums(idx_path):
+ ind_df = pd.read_csv(idx_path, sep="\t")
+ last_ind = ind_df.shape[0] + 1
+ return last_ind
+
+
+def write_job(list_out, write_path):
+ write_link = open(write_path, "a")
+ out_str = "\nJOBID=$({})\n".format(
+ " ".join(list_out))
+ write_link.write(out_str)
+ write_link.write(
+ 'IDPARTS=($(echo $JOBID | tr "." "\\n"))\n')
+ write_link.write(
+ 'WAITID=${IDPARTS[0]}\n')
+ write_link.write(
+ 'echo "Submitted JOB ID $WAITID"\n')
+ write_link.close()
+ return "$WAITID"
+
+
+def make_unique_kmers(chrom_dir, dir_kmers,
+ kmer_size, queue_name,
+ source_dir, conversion_job_id,
+ idx_path, chrsize_path,
+ write_path, var_id,
+ job_lim, pipe):
+ """Generates kmer.gz files of the genome
+ """
+ # chr_files = os.listdir(chrom_dir)
+ # chr_fas = sublist_by_reg(".fa$", chr_files)
+ out_dir = "{}/k{}".format(dir_kmers, kmer_size)
+ ind_jobs = get_unique_kmer_jobnums(idx_path)
+ array_param = "1-{}".format(ind_jobs)
+ get_kmers = ["qsub", "-q",
+ queue_name, "-t",
+ array_param, "-N",
+ "Bismap.UniqueKmers",
+ "-terse",
+ "-tc", str(job_lim),
+ "-hold_jid", conversion_job_id,
+ "-cwd", "-b", "y",
+ "-o", "{}/Bismap.UniqueKmers.LOG".format(dir_kmers),
+ "-e", "{}/Bismap.UniqueKmers.ERR".format(dir_kmers),
+ "python", "get_kmers.py",
+ chrsize_path, out_dir,
+ chrom_dir, idx_path,
+ "--var_id", var_id, "--kmer", "k{}".format(kmer_size)]
+ if pipe:
+ get_kmers = pipe_job(get_kmers)
+ if write_path != "False":
+ job_num = write_job(get_kmers, write_path)
+ else:
+ try:
+ job_line = subprocess.Popen(get_kmers, stdout=subprocess.PIPE)
+ except:
+ raise ValueError("Incompatible system? Try -write.")
+ job_num = job_line.stdout.read().rstrip()
+ print "job id %s from creating unique kmers" % job_num
+ job_num = job_num.split(".")[0]
+ return job_num, ind_jobs
+
+
+def run_bowtie(queue_name, dir_kmers, bowtie_path, index_dir,
+ index_suffix, kmer_job_id,
+ index_job_id, kmer, source_dir,
+ Bismap, num_jobs, write_path, var_id,
+ job_lim, pipe):
+ """Calls bowtie on kmer.gz files
+ """
+ bowtie_dir = "/".join(bowtie_path.split("/")[:-1])
+ kmer_folder = "{}/k{}".format(dir_kmers, kmer)
+ array_param = "1-{}".format(num_jobs)
+ wait_param = "%s,%s" % (index_job_id, kmer_job_id)
+ run_bowtie = ["qsub", "-q",
+ queue_name, "-t",
+ array_param, "-N",
+ "Bismap.RunBowtie",
+ "-terse",
+ "-tc", str(job_lim),
+ "-hold_jid", wait_param,
+ "-cwd", "-b", "y",
+ # "-l", "\"mem_requested={%s}G\"" % (mem_GB),
+ "-o", "{}/Bismap.RunBowtie.LOG".format(dir_kmers),
+ "-e", "{}/Bismap.RunBowtie.ERR".format(dir_kmers),
+ "python", "run_bowtie.py", kmer_folder,
+ bowtie_dir, index_dir, index_suffix,
+ "-var_id", var_id]
+ if Bismap:
+ run_bowtie.append("-Bismap")
+ if pipe:
+ run_bowtie = pipe_job(run_bowtie)
+ if write_path != "False":
+ job_num = write_job(run_bowtie, write_path)
+ else:
+ try:
+ job_line = subprocess.Popen(run_bowtie, stdout=subprocess.PIPE)
+ except:
+ raise ValueError("Incompatible system? Try -write")
+ job_num = job_line.stdout.read()
+ print "job id %s from mapping with bowtie" % job_num
+ job_num = job_num.split(".")[0]
+ return job_num
+
+
+def unify_bowtie(queue_name, bowtie_job_id, dir_kmers,
+ kmer, chrom_dir, source_dir,
+ LenChrs, write_path, var_id,
+ chrsize_path, job_lim, pipe):
+ """Generates qsub command for interpreting bowtie outputs
+
+ Saves collectinve bowtie.gz files of each chromosome into
+ a binary unsigned 8-bit integer file for each chromosome
+ which is an array with the same length as the chromosome
+ """
+ kmer_folder = "{}/k{}".format(dir_kmers, kmer)
+ len_chrs = LenChrs
+ array_param = "1-%d:1" % (len_chrs)
+ chr_order_path = chrsize_path
+ wait_param = bowtie_job_id
+ unify_bw_lst = ["qsub", "-q",
+ queue_name,
+ "-t", array_param,
+ "-N",
+ "Bismap.UnifyBowtie",
+ "-terse",
+ "-tc", str(job_lim),
+ "-hold_jid", wait_param,
+ "-cwd", "-b", "y",
+ "-o", "{}/Bismap.UnifyBowtie.LOG".format(dir_kmers),
+ "-e", "{}/Bismap.UnifyBowtie.ERR".format(dir_kmers),
+ "python", "unify_bowtie.py",
+ kmer_folder, chr_order_path, "-var_id", var_id]
+ if pipe:
+ unify_bw_lst = pipe_job(unify_bw_lst)
+ if write_path != "False":
+ job_num = write_job(unify_bw_lst, write_path)
+ else:
+ try:
+ job_line = subprocess.Popen(unify_bw_lst, stdout=subprocess.PIPE)
+ except:
+ raise ValueError("Incompatible system? try -write")
+ job_num = job_line.stdout.read()
+ job_num = job_num.split(".")[0]
+ TempDir = "%s/TEMPs" % kmer_folder
+ make_dir(TempDir)
+ move_intermediary_files = ["qsub", "-q",
+ queue_name, "-N",
+ "Moving.Intermediary.Files",
+ "-hold_jid", job_num,
+ "-terse",
+ "-cwd", "-b", "y",
+ "-o", "Bismap.FileMov.LOG",
+ "-e", "Bismap.FileMov.ERR",
+ "mv",
+ "%s/*kmer*" % (kmer_folder),
+ TempDir]
+ if write_path != "False":
+ job_num = write_job(move_intermediary_files, write_path)
+ else:
+ job_line = subprocess.Popen(
+ move_intermediary_files, stdout=subprocess.PIPE)
+ move_intermediary_files_2 = move_intermediary_files[:-2] +\
+ ["%s/*bowtie*" % (kmer_folder), TempDir]
+ if write_path != "False":
+ job_num = write_job(move_intermediary_files_2, write_path)
+ else:
+ job_line = subprocess.Popen(
+ move_intermediary_files_2,
+ stdout=subprocess.PIPE)
+ job_num = job_line.stdout.read()
+ return job_num
+
+
+def sublist_by_reg(regex, my_list):
+ subsetted_list = []
+ for item in my_list:
+ RE = re.search(regex, item)
+ if RE:
+ subsetted_list.append(item)
+ return subsetted_list
+
+
+def make_dir(dir_name):
+ if not os.path.exists(dir_name):
+ os.makedirs(dir_name)
+
+
+def make_dir_structure(out_dir):
+ """Generates subfolders needed for Umap in out_dir
+ """
+ chrom_dir = "{}/chrs".format(out_dir)
+ path_genome = "{}/genome".format(out_dir)
+ dir_kmers = "{}/kmers".format(out_dir)
+ make_dir(chrom_dir)
+ make_dir(path_genome)
+ make_dir(dir_kmers)
+ return chrom_dir, dir_kmers, path_genome
+
+
+def combine_files(bowtie_unify_id, source_dir, dir_kmers, queue_name,
+ chrsize_path, write_path, var_id, LenChrs, pipe):
+ """Creates the qsub command for merging data of several k-mers
+ """
+ combine_job_line = ["qsub", "-q",
+ queue_name, "-N",
+ "CombineUmappedFiles",
+ "-terse",
+ "-t", "1-{}".format(LenChrs),
+ "-hold_jid", bowtie_unify_id,
+ "-cwd", "-b", "y",
+ "-o", "{}/Bismap.combine.LOG".format(dir_kmers),
+ "-e", "{}/Bismap.combine.ERR".format(dir_kmers),
+ "python", "combine_umaps.py", dir_kmers,
+ chrsize_path, "-var_id", var_id]
+ if pipe:
+ combine_job_line = pipe_job(combine_job_line)
+ if write_path != "False":
+ write_job(combine_job_line, write_path)
+ else:
+ subprocess.call(combine_job_line)
+
+
+def complement_chrsize_file(chrsize_path):
+ """Complement chromosome size file
+
+ If using Bismap, an extra set of chromosomes
+ will be generated with the _RC suffix.
+ These need to be added to the chromosome size
+ file as well.
+
+ :param chrsize_path: Path to 2-column file of chrom\tsize\n
+
+ :returns: The actual number of chromosomes
+ """
+ if not os.path.exists(chrsize_path):
+ print "%s didn't exist!" % chrsize_path
+ ad_lines = []
+ len_chrs = 0
+ NO_RC = True
+ with open(chrsize_path, "r") as chrsize_link:
+ for each_line in chrsize_link:
+ len_chrs = len_chrs + 1
+ if "_RC" in each_line:
+ NO_RC = False
+ chrsize_list = each_line.rstrip().split("\t")
+ chrsize_list[0] = chrsize_list[0] + "_RC"
+ ad_lines.append("\t".join(chrsize_list) + "\n")
+ if len(ad_lines) > 0 and NO_RC:
+ with open(chrsize_path, "a") as chrsize_link:
+ for each_line in ad_lines:
+ len_chrs = len_chrs + 1
+ print "adding %s" % each_line
+ chrsize_link.write(each_line)
+ print "Added reverse complemented chromosomes"
+ else:
+ "Reverse complemented chromosomes existed"
+ return len_chrs
+
+
+def process_genome(GenomeReady, genome_path,
+ Bismap, fasta_path,
+ conversion, out_dir, chr_dir,
+ queue_name, bowtie_path,
+ chrsize_path, write_script, pipe):
+ """Generates necessary fasta files for Umap and Bismap
+
+ Umap and Bismap require fasta files for each chromosome.
+ Bismap requires the fasta files to have a C>T or G>A
+ conversion as well. Additionally, Bismap requires a
+ reverse complemented set of chromosome where the
+ C>T or G>A conversion occurs after reverse complementation.
+
+ :param GenomeRead: Boolean indicating if index of genome exists
+ :param genome_path: Path to the output fasta file of the genome
+ :param Bismap: Boolean indicating if Bismap option is selected
+ :param fasta_path: Path to the already existing input fasta file
+ :param conversion: One of None, C2T or G2A
+ :param out_dir: Directory for Umap output
+ :param chr_dir: Directory for making individual chromosome fastas
+ :param bowtie_path: Path to executable bowtie-build binary
+ :param chrsize_path: Path to 2-column file of chromosome\tsize\n
+ :param write_script: File path for writing the qsub command
+ or the string 'False'
+ :param pipe: Boolean indicating if the qsub command should be piped
+
+ :returns: index_suffix, index_job_id (qsub wait IDs)
+ """
+ if GenomeReady:
+ print("Assuming the genome and index files exist")
+ index_suffix = "BisMap_bowtie.ind"
+ index_job_id = "1"
+ else:
+ print "Started copying/reverse complementing/converting"
+ if not os.path.exists(genome_path):
+ if Bismap:
+ print "Bismap reverse complementation started\
+ at %s" % str(datetime.now())
+ FastaObj = FastaHandler(fasta_path, genome_path, chrsize_path,
+ chr_dir, True, conversion)
+ else:
+ print "Umap genome is being processed"
+ FastaObj = FastaHandler(fasta_path, genome_path, chrsize_path,
+ chr_dir, False, "None")
+ FastaObj.handle_fasta()
+ elif Bismap:
+ print "Assuming that %s/genome/genome.fa includes reverse\
+ complemented chromosomes." % out_dir
+ print "Indexing the genome started at %s" % str(datetime.now())
+ index_suffix, index_job_id = index_genome(
+ queue_name,
+ "{}/genome".format(out_dir),
+ bowtie_path, Bismap, write_script, pipe)
+ print "Done with indexing at %s" % str(datetime.now())
+ return index_suffix, index_job_id
+
+
+def index_unique_kmer_jobids(chrsize_path, CHUNK_SIZE=1e6):
+ """Generate index file mapping job_ids to chromosomal chunks
+
+ Umap (or Bismap) requires around 200 hours of computation.
+ All of the scripts accept -job_id arguments to perform the
+ embarrassingly parallel process on different chromosomal
+ chunks using a 0-based index that refers to part of the
+ genome. This script creates a 4-column index file with
+ the following columns:
+ Index\tChromosome\tStart\tend\n
+
+ :param chrsize_path: Path to 2-column file of chrom\tsize\n
+ :param CHUNK_SIZE: The maximum length of each chromosomal chunk
+ :type CHUNK_SIZE: Integer
+
+ :returns: Path to index file
+ """
+ CHUNK_SIZE = int(CHUNK_SIZE)
+ ind_path = "{}/chrsize_index.tsv".format(
+ "/".join(chrsize_path.split("/")[:-1]))
+ if not os.path.exists(ind_path):
+ ind_link = open(ind_path, "w")
+ ind_link.write("Index\tChromosome\tStart\tEnd\n")
+ start = 1
+ ind = 0
+ # Identifying chromosome, start, end for job_id
+ with open(chrsize_path, "r") as chrsize_link:
+ for chrsize_line in chrsize_link:
+ chr, len_chr = chrsize_line.rstrip().split("\t")
+ end = int(len_chr) + start
+ for pos in range(start, end, CHUNK_SIZE):
+ if pos < end:
+ if pos + CHUNK_SIZE - 1 > end:
+ pos_end = end
+ else:
+ pos_end = pos + CHUNK_SIZE - 1
+ ind_link.write(
+ "\t".join(
+ [str(ind), chr, str(pos), str(int(pos_end))]) +
+ "\n")
+ ind = ind + 1
+ ind_link.close()
+ return ind_path
+
+
+if __name__ == "__main__":
+ args = ArgHandler()
+ # genome_path, chrom_dir, dir_kmers, chrsize_path, out_dir = args_list[:5]
+ # idx_path, conversion, Bismap, queue_name = args_list[5:9]
+ # kmers, SimultaneousJobs, ExitAfterIndexing = args_list[9:12]
+ # var_id, write_script, source_dir, GenomeReady = args_list[12:16]
+ # fasta_path, bowtie_path, LenChrs, pipe = args_list[16:]
+ index_dir = os.path.dirname(args.genome_path)
+ conversion_job_id = "1" # initiate job dependency with an invalid ID
+ index_suffix, index_job_id = process_genome(
+ args.GenomeReady, args.genome_path,
+ args.Bismap, args.fasta_path,
+ args.conversion, args.out_dir,
+ args.chrom_dir, args.queue_name,
+ args.bowtie_path, args.chrsize_path,
+ args.write_script, args.pipe)
+ if args.ExitAfterIndexing:
+ pass
+ print "Exiting because -ExitAfterIndexing is specified"
+ else:
+ for kmer in args.kmers:
+ kmer = int(kmer)
+ make_dir("{}/k{}".format(args.dir_kmers, kmer))
+ kmer_job_id, num_jobs = make_unique_kmers(
+ args.chrom_dir, args.dir_kmers, kmer,
+ args.queue_name, args.source_dir,
+ conversion_job_id,
+ args.idx_path, args.chrsize_path,
+ args.write_script, args.var_id,
+ args.SimultaneousJobs, args.pipe)
+ bowtie_job_id = run_bowtie(
+ args.queue_name, args.dir_kmers,
+ args.bowtie_path,
+ index_dir, index_suffix,
+ kmer_job_id, index_job_id, kmer,
+ args.source_dir, args.Bismap,
+ num_jobs, args.write_script, args.var_id,
+ args.SimultaneousJobs, args.pipe)
+ bowtie_unify_id = unify_bowtie(
+ args.queue_name, bowtie_job_id,
+ args.dir_kmers,
+ kmer, args.chrom_dir,
+ args.source_dir, args.LenChrs,
+ args.write_script,
+ args.var_id, args.chrsize_path,
+ args.SimultaneousJobs, args.pipe)
+ conversion_job_id = kmer_job_id
+ print "Jobs submitted for k%d" % kmer
+ combine_files(bowtie_unify_id, args.source_dir,
+ args.dir_kmers,
+ args.queue_name,
+ args.chrsize_path, args.write_script,
+ args.var_id,
+ args.LenChrs, args.pipe)
+ conversion_job_id = bowtie_unify_id
+ print("Successfully done with creating all jobs")
diff --git a/build/lib/umap/uint8_to_bed.py b/build/lib/umap/uint8_to_bed.py
new file mode 100644
index 0000000..d5b21d7
--- /dev/null
+++ b/build/lib/umap/uint8_to_bed.py
@@ -0,0 +1,423 @@
+import argparse
+from datetime import datetime
+import gzip
+import numpy as np
+import os
+import re
+import warnings
+
+
+def subset_list(my_list, regex, reg_neg=False):
+ out_list = []
+ for item in my_list:
+ RE = re.search(regex, item)
+ if RE and not reg_neg:
+ out_list.append(item)
+ elif not RE and reg_neg:
+ out_list.append(item)
+ return out_list
+
+
+class Int8Handler:
+ def __init__(self, in_dir, out_dir, C2T, G2A, chrsize_path):
+ """Infers important directory structure from in_dir
+
+ The Int8Handler class requires in_dir argument which
+ is a directory with subfolders named as k<integer>
+ that have <chrom>.<kmer>.uint8.unique.gz files.
+ The Int8Handler.write_beds method creates one
+ browser extensible data (BED) file for each of the
+ k<integer> subfolders.
+
+ :param in_dir: Directory with <chrom>.uint8.unique.gz files
+ :param out_dir: Directory for saving output BED files
+ """
+ self.in_dir = in_dir
+ self.C2T = C2T
+ self.G2A = G2A
+ self.chrsize_path = chrsize_path
+ self.in_prev_dir = "/".join(in_dir.split("/")[:-1])
+ self.fix = ".uint8.unique.gz"
+ self.uint8s = subset_list(os.listdir(in_dir), self.fix)
+ self.prev_dir = "/".join(self.in_dir.split("/")[:-1])
+ self.kmers = subset_list(next(os.walk(self.in_prev_dir))[1],
+ "^k")
+ self.out_dir = out_dir
+ self.type = self.find_type()
+ self.chrsize_dict = self.make_chrsize_dict()
+ self.chroms = [each_chr for each_chr in
+ self.chrsize_dict.keys() if
+ "RC" not in each_chr]
+ self.chroms.sort()
+
+ def find_type(self):
+ if self.C2T:
+ self.type = "Bismap.Forward"
+ elif self.G2A:
+ self.type = "Bismap.Reverse"
+ else:
+ self.type = "Umap"
+ return self.type
+
+ def write_beds(self, out_label, kmer_cur,
+ WriteUnique=False):
+ """Convert uint8 files to BED
+
+ A method of class Int8Handler, it reads uint8 files of
+ different chromosomes and saves them into a BED file.
+ This is the only method in this class that needs
+ to be called manually by the user.
+
+ Args:
+ out_label: Will be used in output names: <kmer>.<out_label>.bed.gz
+ kmer_cur: k-mer size in format of k<integer>
+ WriteUnique: Defaults to False. Will merge and save uint files.
+ Use if working with -Bismap and have reverse
+ complemented chromosomes.
+
+ Returns:
+ Saved ths output to a gzipped BED file
+
+ Raises:
+ Warning: If no uniquely mappable read is found in
+ any of the uint8 arrays.
+ """
+ kmer = int(kmer_cur.replace("k", ""))
+ STRAND = "+"
+ if self.G2A:
+ STRAND = "-"
+ in_dir = self.in_dir
+ all_chrs = self.chroms
+ all_chrs.sort()
+ for cur_chr in self.chroms:
+ other_chr = cur_chr + "_RC"
+ uint_path = "{}/{}{}".format(
+ in_dir, cur_chr, self.fix)
+ uniquely_mappable = self.load_uint_ar(
+ uint_path, kmer, cur_chr)
+ if self.type != "Umap":
+ uint_path_other = in_dir +\
+ "/" + uint_path.split("/")[-1].replace(cur_chr, other_chr)
+ uniquely_mappable_other = self.load_uint_ar(
+ uint_path_other, kmer, other_chr)
+
+ # Remove the last k nucleotides of the reverse chromosome
+ uniquely_mappable_other = uniquely_mappable_other[:-kmer]
+
+ # Reverse the chromosome (Hence it's a reverse complement)
+ uniquely_mappable_other = uniquely_mappable_other[::-1]
+
+ # Remove the last k nucleotides of the forward chromosome
+ uniquely_mappable = uniquely_mappable[:-kmer]
+
+ # Merge to find uniquely mappable reads in both strands
+ uniquely_mappable = np.array(
+ np.logical_and(
+ uniquely_mappable_other, uniquely_mappable),
+ dtype=int)
+ if WriteUnique:
+ unique_ar = np.array(uniquely_mappable, dtype=np.uint8)
+ out_dir_uint = "{}/k{}".format(self.out_dir, kmer)
+ if not os.path.exists(out_dir_uint):
+ os.makedirs(out_dir_uint)
+ out_path_uint = "{}/{}.k{}.uint8.unique.gz".format(
+ out_dir_uint, cur_chr, kmer)
+ out_link_uint = gzip.open(out_path_uint, "wb")
+ out_link_uint.write(unique_ar.tobytes())
+ out_link_uint.close()
+
+ bed_kmer_pos = self.get_bed6(
+ uniquely_mappable, kmer, STRAND, uint_path, cur_chr)
+
+ # Write the BED6 to a gzipped tsv file
+ out_name = "{}/{}.{}.bed.gz".format(
+ self.out_dir, kmer_cur, out_label)
+ if cur_chr == all_chrs[0]:
+ header = self.make_header(kmer_cur, type)
+ out_link = gzip.open(out_name, "wb")
+ out_link.write(header)
+ else:
+ out_link = gzip.open(out_name, "ab")
+ if len(bed_kmer_pos) > 0:
+ print "Found %d regions in %s" %\
+ (bed_kmer_pos.shape[0], cur_chr)
+ for bed_line in bed_kmer_pos:
+ line_out = [str(val) for val in bed_line]
+ line_out = "\t".join(line_out) + "\n"
+ out_link.write(line_out)
+ print "Created data of %s at %s" %\
+ (cur_chr, str(datetime.now()))
+ out_link.close()
+
+ def get_bed6(self, uniquely_mappable, kmer,
+ STRAND, uint_path, cur_chr):
+ """Make BED6 from a binary vector
+
+ Converts a binary vector with the same length
+ as the chromosome to a BED6 file. Each 1
+ entry in the binary file indicates that the
+ k-mer starting at that position and ending at
+ k nucleotides downstream is uniquely mappable.
+ Thus the BED6 would show any region in the genome
+ that is uniquely mappable by at least one k-mer.
+
+ :param uniquely_mappable: numpy binary array (0 or 1 values)
+ :param kmer: Integer scalar showing read length (k-mer)
+ :param STRAND: Strand that will be saved to the BED6
+ :param uint_path: Path of the uint8 array that was used
+ :param cur_chr: Chromosome name the the data is from
+
+ :returns: A numpy string array with BED6 information
+ """
+ unimap_diff = np.diff(uniquely_mappable)
+ poses_start, = np.where(unimap_diff == 1)
+ poses_end, = np.where(unimap_diff == -1)
+ if len(poses_start) != len(poses_end):
+ if len(poses_start) > len(poses_end):
+ poses_end = np.append(poses_end, [len(uniquely_mappable)])
+ else:
+ poses_start = np.append([0], poses_start)
+ elif uniquely_mappable[0] == 1:
+ poses_start = np.append([0], poses_start)
+ poses_end = np.append(poses_end, [len(uniquely_mappable)])
+ if len(poses_start) == 0:
+ warnings.warn(
+ "Found no uniquely mappable reads for {}!".format(
+ uint_path))
+ bed_kmer_pos = []
+ else:
+ chr_length = self.chrsize_dict[cur_chr]
+ bed_kmer_pos = np.empty(shape=(len(poses_start), 6),
+ dtype="S16")
+ ind_high = []
+ for ind_st in range(len(poses_start)):
+ if poses_end[ind_st] + kmer - 1 > chr_length:
+ ind_high.append(ind_st)
+ bed_kmer_pos = np.array(
+ [[cur_chr, str(poses_start[i] + 1),
+ str(poses_end[i] + kmer - 1),
+ "k" + str(kmer),
+ 1, STRAND] for i in range(len(poses_start))],
+ dtype="S64")
+ for each_ind in ind_high:
+ if int(bed_kmer_pos[each_ind][2]) > chr_length:
+ bed_kmer_pos[each_ind][2] = str(chr_length)
+ return bed_kmer_pos
+
+ def load_uint_ar(self, uint_path, kmer, cur_chr):
+ """Loads a gzipped unsigned 8-bit integer as a numpy array
+ """
+ uint_link = gzip.open(uint_path, "rb")
+ uint_ar = np.frombuffer(uint_link.read(), dtype=np.uint8)
+ uint_link.close()
+ print "Processing {} for {} {}".format(
+ uint_path, kmer, cur_chr)
+ less_than_kmer = uint_ar <= kmer
+ not_zero = uint_ar != 0
+ uniquely_mappable = np.array(
+ np.logical_and(less_than_kmer, not_zero), dtype=int)
+ return uniquely_mappable
+
+ def make_header(self, kmer, type):
+ """Created BED6 header
+
+ :param str kmer: k<integer>
+ :param type: One of Bismap.Forward, Bismap.Reverse or Umap
+ """
+ dict_col = {"Bisulfite.Converted": "240,40,80",
+ "Umap": "80,40,240",
+ "Bismap.Forward": "220,20,80",
+ "Bismap.Reverse": "80,20,220"}
+ header = 'track name="{} {}"'.format(type, kmer) +\
+ 'description="Single-read mappability with {}-mers'.format(
+ kmer) +\
+ 'color=%s \n'.format(dict_col.get(type, "40,40,240"))
+ return header
+
+ def make_chrsize_dict(self):
+ """Creates dictionary from 2-column chromosome size file
+ """
+ chrsize_dict = {}
+ with open(self.chrsize_path, "r") as chrsize_link:
+ for each_line in chrsize_link:
+ chr = each_line.rstrip("\n").split("\t")[0]
+ length = int(each_line.rstrip("\n").split("\t")[1])
+ chrsize_dict[chr] = length
+ return chrsize_dict
+
+ def bin_arr_to_wig(self, uniquely_mappable, kmer):
+ """Converts a uniquely a binary array to mult-read mappability
+
+ Unique mappability array is a binary array where each
+ value of 1 indicates that the k-mer starting at that
+ position is uniquely mappable. This function generates
+ an array of the same length and saves the multi-read mappability
+ of each position in that array. Multi-read mappability is the
+ probability of finding a uniquely mappable k-mer among all of
+ the k-mers that overlap with a given position.
+
+ :param uniquely_mappable: A binary numpy array
+ :param kmer: An integer defining read length
+
+ :returns: Multi-read mappability array.
+ """
+ LEN_AR = len(uniquely_mappable)
+ poses_start, = np.where(uniquely_mappable == 1)
+ ar_quant = np.zeros(len(uniquely_mappable), dtype=float)
+ for ind_st in poses_start:
+ ind_end = ind_st + kmer
+ if ind_end > LEN_AR:
+ ind_end = LEN_AR
+ ar_quant[ind_st:ind_end] = ar_quant[ind_st:ind_end] + 1.0
+ print("Finished generating multi-read mappability date at {}".format(
+ str(datetime.now())))
+ del poses_start
+ ar_quant = ar_quant / float(kmer)
+ return ar_quant
+
+ def write_as_wig(self, uint_path, out_path, kmer, chrom):
+ """unsigned 8-bit integer array file to wiggle
+
+ For a given numeric unsigned 8-bit integer vector that
+ is generated by Umap, this method save the wiggle file
+ which is specific for one chromosome over one read length.
+
+ :param uint_path: Path to a gzipped numeric unsigned 8-bit array
+ :param out_path: Gzipped path for saving wiggle
+ :param kmer: Integer defining read length
+ :param chrom: Chromosome that the uint_path is specific to
+ """
+ uniquely_mappable = self.load_uint_ar(uint_path, kmer, chrom)
+ ar_quant = self.bin_arr_to_wig(uniquely_mappable, kmer)
+ out_link = gzip.open(out_path, "wb")
+ unimap_diff = np.diff(np.array(ar_quant > 0, dtype=int))
+ poses_start, = np.where(unimap_diff == 1)
+ poses_end, = np.where(unimap_diff == -1)
+ if len(poses_start) != len(poses_end):
+ if len(poses_start) > len(poses_end):
+ poses_end = np.append(poses_end, [len(uniquely_mappable)])
+ else:
+ poses_start = np.append([0], poses_start)
+ elif uniquely_mappable[0] == 1:
+ poses_start = np.append([0], poses_start)
+ poses_end = np.append(poses_end, [len(uniquely_mappable)])
+ for ind_st in range(len(poses_start)):
+ pos_st = poses_start[ind_st] + 1
+ pos_end = poses_end[ind_st] + 1
+ start_line = "fixedStep chrom={} start={} step=1 span=1\n".format(
+ chrom, pos_st)
+ out_link.write(start_line)
+ for each_pos in range(pos_st, pos_end):
+ out_link.write(str(ar_quant[each_pos]) + "\n")
+ print(
+ "Finished saving the data to {} at {}".format(
+ out_path, str(datetime.now())))
+ out_link.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Converts\
+ unionized uint8 outputs of umap/ubismap to bed files")
+ parser.add_argument(
+ "in_dir",
+ help="folder with <chrom>.uint8.unique.gz files")
+ parser.add_argument(
+ "out_dir",
+ help="Folder for writing the output files")
+ parser.add_argument(
+ "out_label",
+ help="File names would be kmer.<out_label>.bed.gz")
+ parser.add_argument(
+ "-C2T",
+ action="store_true",
+ help="If using converted genomes specify -C2T or -G2A")
+ parser.add_argument(
+ "-G2A",
+ action="store_true",
+ help="If using converted genomes specify -C2T or -G2A")
+ parser.add_argument(
+ "-chrsize_path",
+ default="../../chrsize.tsv",
+ help="Path to a 2 column file of chromosome and length. "
+ "By default it goes to ../../chrsize.tsv from out_dir")
+ parser.add_argument(
+ "-WriteUnique",
+ action="store_true",
+ help="If -Bismap is true and want to store the merged "
+ "uint file, specify this option")
+ parser.add_argument(
+ "-wiggle",
+ action="store_true",
+ help="If specified, will generate wiggle files "
+ "for each chromosome. Make sure to specify -job_id "
+ "or run in job array for parallel computation.")
+ parser.add_argument(
+ "-bed",
+ action="store_true",
+ help="If specified, will generate bed files that specify "
+ "all of the regions in the genome that are uniquely mappable "
+ "by each of the k-mers")
+ parser.add_argument(
+ "-kmers",
+ default=["k0"],
+ nargs="*",
+ help="Specify kmers separated by space such as: -kmers k10 k20")
+ parser.add_argument(
+ "-job_id",
+ type=int,
+ default=0,
+ help="If not using job array, specify this index "
+ "which will be used for selecting the chromosomes")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="Environmental variable for finding chromosome indices")
+ args = parser.parse_args()
+ if not args.bed and not args.wiggle:
+ raise ValueError("Please specify only one of -bed or -wiggle")
+ if args.bed and args.wiggle:
+ raise ValueError("Please specify at least one of -bed or -wiggle")
+ if not os.path.exists(args.out_dir):
+ os.makedirs(args.out_dir)
+ FileHandler = Int8Handler(args.in_dir,
+ args.out_dir, args.C2T, args.G2A,
+ args.chrsize_path)
+ job_id = args.job_id
+ PARALLEL = True
+ if job_id == 0:
+ job_id = os.environ[args.var_id]
+ if job_id == "":
+ PARALLEL = False
+ kmers = FileHandler.kmers
+ if args.kmers[0] != "k0":
+ kmers = args.kmers
+ # for kmer in kmers:
+ for kmer in kmers:
+ if args.bed:
+ print("Creating BED file")
+ FileHandler.write_beds(args.out_label,
+ kmer, args.WriteUnique)
+ elif PARALLEL and args.wiggle:
+ chrom = FileHandler.chroms[int(job_id) - 1]
+ print(
+ "Saving Wiggle using job id {}, selected {}".format(
+ job_id, chrom))
+ out_path = "{}/{}.{}.{}.MultiReadMappability.wg.gz".format(
+ args.out_dir, args.out_label, chrom, kmer)
+ uint_path = "{}/{}.uint8.unique.gz".format(
+ args.in_dir, chrom)
+ kmer_num = int(kmer.replace("k", ""))
+ FileHandler.write_as_wig(uint_path, out_path, kmer_num, chrom)
+ elif args.wiggle:
+ print("Creating wiggles for all chromosomes consequently")
+ print("This may take long...")
+ for chrom in FileHandler.chroms:
+ out_path = "{}/{}.{}.{}.MultiReadMappability.wg.gz".format(
+ args.out_dir, args.out_label, chrom, kmer)
+ uint_path = "{}/{}.uint8.unique.gz".format(
+ args.in_dir, chrom)
+ kmer_num = int(kmer.replace("k", ""))
+ FileHandler.write_as_wig(uint_path, out_path, kmer_num, chrom)
+ print(
+ "Tired of waiting? Try parallel processing "
+ "by specifying -job_id")
diff --git a/build/lib/umap/unify_bowtie.py b/build/lib/umap/unify_bowtie.py
new file mode 100644
index 0000000..9f7f80e
--- /dev/null
+++ b/build/lib/umap/unify_bowtie.py
@@ -0,0 +1,151 @@
+from argparse import ArgumentParser
+import gzip
+import numpy as np
+import os
+import pandas as pd
+import re
+
+
+def subset_list(list_items, regex):
+ out_list = []
+ for each_item in list_items:
+ RE = re.search(regex, each_item)
+ if RE:
+ out_list.append(each_item)
+ return out_list
+
+
+class UnifyBowtie:
+ def __init__(self, bowtie_outdir, chrsize_path, job_id):
+ """Merges bowtie.gz outputs of run_bowtie
+
+ Based on outputs of run_bowtie that are saved in format
+ of <chr>.<kmer>.<job_id>.bowtie.gz, this class uses
+ a variable ID to select a particular chromosome and
+ merge the data in all of the different bowtie.gz files
+ of that chromosome.
+
+ :param bowtie_outdir: Directory with <chr>.<kmer>.<job_id>.bowtie.gz
+ :param chrsize_path: Path to 2-column file: <chr>\t<size>\n...
+ :param int job_id: A 0-based index to select chromosome
+ based on chrsize_path
+
+ :returns: Saves the output to bowtie_outdir/
+ <chr>.<kmer>.uint8.unique.gz file
+ """
+ self.bowtie_outdir = bowtie_outdir
+ self.chrsize_path = chrsize_path
+ self.ind_chr = job_id
+ self.chr_dict = self.make_chr_dict()
+ self.bowtie_to_unique()
+
+ def make_chr_dict(self):
+ """Makes a dictionary using self.chrsize_path"""
+ chr_dict = {}
+ with open(self.chrsize_path, "r") as chrsize_link:
+ for chrsize_line in chrsize_link:
+ chrom, size = chrsize_line.rstrip().split("\t")
+ chr_dict[chrom] = int(size)
+ return chr_dict
+
+ def get_mapped_positions(self, bowtie_path):
+ """Finds mapped regions in bowtie output
+
+ In a gzipped bowtie output with perfect matches,
+ filters the results to those in the forward strand
+ and saves them to an array.
+
+ Why results filtered for forward strand?
+ The results uniquely mapped
+ to the reverse strand are rare and a mistake of the
+ aligning algorithm because all of the k-mers are
+ generated from the forward strand. If match happens
+ on reverse strand, it means that the match is not the
+ only unique match (reads were generated from forward
+ strand).
+ """
+ bowtie_df = pd.read_csv(
+ bowtie_path, sep="\t",
+ compression="gzip",
+ names=["Ind", "Strand", "Chr", "Start"])
+ bowtie_df = bowtie_df[bowtie_df["Strand"] == "+"]
+ ind_ar = bowtie_df.iloc[:, 3]
+ return ind_ar
+
+ def get_other_chr_name(self, chr_name):
+ """Finds name of the reverse complement chromosome
+
+ In Bismap, we generate a set of reverse complemented
+ chromosomes to account for bisulfite conversion before
+ reverse complementation. This function finds those
+ chromosomes"""
+ new_name = chr_name
+ if "RC" in chr_name:
+ len_paths = len(
+ subset_list(
+ os.listdir(self.bowtie_outdir), chr_name))
+ if len_paths == 0:
+ new_name = chr_name + "_RC"
+ return new_name
+
+ def bowtie_to_unique(self):
+ """Wrapper method of UnifyBowtie
+
+ Uses information of bowtie.gz files to find mappability
+ of a given chromosome. Is automatically called by
+ UnifyBowtie."""
+ KMER = int(self.bowtie_outdir.split("/")[-1].split("k")[-1])
+ all_chrs = self.chr_dict.keys()
+ all_chrs.sort()
+ chrom = all_chrs[self.ind_chr]
+ size = self.chr_dict[chrom]
+ new_chr_name = self.get_other_chr_name(chrom)
+ chr_paths = ["{}/{}".format(self.bowtie_outdir, bowtie_path)
+ for bowtie_path in subset_list(
+ os.listdir(self.bowtie_outdir),
+ "{}\.".format(new_chr_name))]
+ bowtie_paths = subset_list(chr_paths, ".bowtie.gz")
+ unique_ar = np.zeros(size, dtype=np.uint8)
+ for bowtie_path in bowtie_paths:
+ mapped_indices = self.get_mapped_positions(bowtie_path)
+ for st_index in mapped_indices:
+ end_index = st_index + KMER
+ unique_ar[st_index:end_index] = 1
+ print("Done with {}".format(bowtie_path))
+ out_path = "{}/{}.k{}.uint8.unique.gz".format(
+ self.bowtie_outdir, chrom, KMER)
+ out_link = gzip.open(out_path, "wb")
+ # np.save(out_link, unique_ar)
+ out_link.write(unique_ar.tobytes())
+ # unique_ar.tofile(out_link)
+ out_link.close()
+ print("Saved {}".format(out_path))
+ print("Exiting successfully")
+
+
+if __name__ == "__main__":
+ parser = ArgumentParser(
+ description="")
+ parser.add_argument(
+ "bowtie_outdir",
+ help="Directory containing bowtie output files")
+ parser.add_argument(
+ "chrsize_path",
+ help="A file containing the order of chromosome names\
+ to consider (one chromosome name per line)")
+ parser.add_argument(
+ "-job_id",
+ default=0,
+ type=int,
+ help="If not using a cluster for submitting jobs, "
+ "specify the job_id by integer ranging from 1 to "
+ "total number of chromosomes in chrsize_path")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="HPC variable name for job ID (1-based index)")
+ args = parser.parse_args()
+ job_id = args.job_id
+ if job_id == 0:
+ job_id = int(os.environ[args.var_id]) - 1
+ UnifyBowtie(args.bowtie_outdir, args.chrsize_path, job_id)
diff --git a/dist/umap-0.1-py2.7.egg b/dist/umap-0.1-py2.7.egg
new file mode 100644
index 0000000..b929c30
Binary files /dev/null and b/dist/umap-0.1-py2.7.egg differ
diff --git a/dist/umap-0.1.1-py2.7.egg b/dist/umap-0.1.1-py2.7.egg
new file mode 100644
index 0000000..15deead
Binary files /dev/null and b/dist/umap-0.1.1-py2.7.egg differ
diff --git a/dist/umap-0.1.2-py2.7.egg b/dist/umap-0.1.2-py2.7.egg
new file mode 100644
index 0000000..b0a1747
Binary files /dev/null and b/dist/umap-0.1.2-py2.7.egg differ
diff --git a/dist/umap-1.0.0-py2.7.egg b/dist/umap-1.0.0-py2.7.egg
new file mode 100644
index 0000000..a3cfd24
Binary files /dev/null and b/dist/umap-1.0.0-py2.7.egg differ
diff --git a/doc/Makefile b/doc/Makefile
new file mode 100644
index 0000000..981ad2d
--- /dev/null
+++ b/doc/Makefile
@@ -0,0 +1,230 @@
+# Makefile for Sphinx documentation
+#
+
+# You can set these variables from the command line.
+SPHINXOPTS =
+SPHINXBUILD = sphinx-build
+PAPER =
+BUILDDIR = build
+
+# User-friendly check for sphinx-build
+ifeq ($(shell which $(SPHINXBUILD) >/dev/null 2>&1; echo $$?), 1)
+ $(error The '$(SPHINXBUILD)' command was not found. Make sure you have Sphinx installed, then set the SPHINXBUILD environment variable to point to the full path of the '$(SPHINXBUILD)' executable. Alternatively you can add the directory with the executable to your PATH. If you don\'t have Sphinx installed, grab it from http://sphinx-doc.org/)
+endif
+
+# Internal variables.
+PAPEROPT_a4 = -D latex_paper_size=a4
+PAPEROPT_letter = -D latex_paper_size=letter
+ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
+# the i18n builder cannot share the environment and doctrees with the others
+I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) source
+
+.PHONY: help
+help:
+ @echo "Please use \`make <target>' where <target> is one of"
+ @echo " html to make standalone HTML files"
+ @echo " dirhtml to make HTML files named index.html in directories"
+ @echo " singlehtml to make a single large HTML file"
+ @echo " pickle to make pickle files"
+ @echo " json to make JSON files"
+ @echo " htmlhelp to make HTML files and a HTML help project"
+ @echo " qthelp to make HTML files and a qthelp project"
+ @echo " applehelp to make an Apple Help Book"
+ @echo " devhelp to make HTML files and a Devhelp project"
+ @echo " epub to make an epub"
+ @echo " epub3 to make an epub3"
+ @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter"
+ @echo " latexpdf to make LaTeX files and run them through pdflatex"
+ @echo " latexpdfja to make LaTeX files and run them through platex/dvipdfmx"
+ @echo " text to make text files"
+ @echo " man to make manual pages"
+ @echo " texinfo to make Texinfo files"
+ @echo " info to make Texinfo files and run them through makeinfo"
+ @echo " gettext to make PO message catalogs"
+ @echo " changes to make an overview of all changed/added/deprecated items"
+ @echo " xml to make Docutils-native XML files"
+ @echo " pseudoxml to make pseudoxml-XML files for display purposes"
+ @echo " linkcheck to check all external links for integrity"
+ @echo " doctest to run all doctests embedded in the documentation (if enabled)"
+ @echo " coverage to run coverage check of the documentation (if enabled)"
+ @echo " dummy to check syntax errors of document sources"
+
+.PHONY: clean
+clean:
+ rm -rf $(BUILDDIR)/*
+
+.PHONY: html
+html:
+ $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/html."
+
+.PHONY: dirhtml
+dirhtml:
+ $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml
+ @echo
+ @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml."
+
+.PHONY: singlehtml
+singlehtml:
+ $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml
+ @echo
+ @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml."
+
+.PHONY: pickle
+pickle:
+ $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle
+ @echo
+ @echo "Build finished; now you can process the pickle files."
+
+.PHONY: json
+json:
+ $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json
+ @echo
+ @echo "Build finished; now you can process the JSON files."
+
+.PHONY: htmlhelp
+htmlhelp:
+ $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp
+ @echo
+ @echo "Build finished; now you can run HTML Help Workshop with the" \
+ ".hhp project file in $(BUILDDIR)/htmlhelp."
+
+.PHONY: qthelp
+qthelp:
+ $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp
+ @echo
+ @echo "Build finished; now you can run "qcollectiongenerator" with the" \
+ ".qhcp project file in $(BUILDDIR)/qthelp, like this:"
+ @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Umap.qhcp"
+ @echo "To view the help file:"
+ @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Umap.qhc"
+
+.PHONY: applehelp
+applehelp:
+ $(SPHINXBUILD) -b applehelp $(ALLSPHINXOPTS) $(BUILDDIR)/applehelp
+ @echo
+ @echo "Build finished. The help book is in $(BUILDDIR)/applehelp."
+ @echo "N.B. You won't be able to view it unless you put it in" \
+ "~/Library/Documentation/Help or install it in your application" \
+ "bundle."
+
+.PHONY: devhelp
+devhelp:
+ $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp
+ @echo
+ @echo "Build finished."
+ @echo "To view the help file:"
+ @echo "# mkdir -p $$HOME/.local/share/devhelp/Umap"
+ @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Umap"
+ @echo "# devhelp"
+
+.PHONY: epub
+epub:
+ $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub
+ @echo
+ @echo "Build finished. The epub file is in $(BUILDDIR)/epub."
+
+.PHONY: epub3
+epub3:
+ $(SPHINXBUILD) -b epub3 $(ALLSPHINXOPTS) $(BUILDDIR)/epub3
+ @echo
+ @echo "Build finished. The epub3 file is in $(BUILDDIR)/epub3."
+
+.PHONY: latex
+latex:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo
+ @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex."
+ @echo "Run \`make' in that directory to run these through (pdf)latex" \
+ "(use \`make latexpdf' here to do that automatically)."
+
+.PHONY: latexpdf
+latexpdf:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo "Running LaTeX files through pdflatex..."
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+.PHONY: latexpdfja
+latexpdfja:
+ $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex
+ @echo "Running LaTeX files through platex and dvipdfmx..."
+ $(MAKE) -C $(BUILDDIR)/latex all-pdf-ja
+ @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex."
+
+.PHONY: text
+text:
+ $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text
+ @echo
+ @echo "Build finished. The text files are in $(BUILDDIR)/text."
+
+.PHONY: man
+man:
+ $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man
+ @echo
+ @echo "Build finished. The manual pages are in $(BUILDDIR)/man."
+
+.PHONY: texinfo
+texinfo:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo
+ @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo."
+ @echo "Run \`make' in that directory to run these through makeinfo" \
+ "(use \`make info' here to do that automatically)."
+
+.PHONY: info
+info:
+ $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo
+ @echo "Running Texinfo files through makeinfo..."
+ make -C $(BUILDDIR)/texinfo info
+ @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo."
+
+.PHONY: gettext
+gettext:
+ $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale
+ @echo
+ @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale."
+
+.PHONY: changes
+changes:
+ $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes
+ @echo
+ @echo "The overview file is in $(BUILDDIR)/changes."
+
+.PHONY: linkcheck
+linkcheck:
+ $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck
+ @echo
+ @echo "Link check complete; look for any errors in the above output " \
+ "or in $(BUILDDIR)/linkcheck/output.txt."
+
+.PHONY: doctest
+doctest:
+ $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest
+ @echo "Testing of doctests in the sources finished, look at the " \
+ "results in $(BUILDDIR)/doctest/output.txt."
+
+.PHONY: coverage
+coverage:
+ $(SPHINXBUILD) -b coverage $(ALLSPHINXOPTS) $(BUILDDIR)/coverage
+ @echo "Testing of coverage in the sources finished, look at the " \
+ "results in $(BUILDDIR)/coverage/python.txt."
+
+.PHONY: xml
+xml:
+ $(SPHINXBUILD) -b xml $(ALLSPHINXOPTS) $(BUILDDIR)/xml
+ @echo
+ @echo "Build finished. The XML files are in $(BUILDDIR)/xml."
+
+.PHONY: pseudoxml
+pseudoxml:
+ $(SPHINXBUILD) -b pseudoxml $(ALLSPHINXOPTS) $(BUILDDIR)/pseudoxml
+ @echo
+ @echo "Build finished. The pseudo-XML files are in $(BUILDDIR)/pseudoxml."
+
+.PHONY: dummy
+dummy:
+ $(SPHINXBUILD) -b dummy $(ALLSPHINXOPTS) $(BUILDDIR)/dummy
+ @echo
+ @echo "Build finished. Dummy builder generates no files."
diff --git a/doc/build/.buildinfo b/doc/build/.buildinfo
new file mode 100644
index 0000000..9d7bb7a
--- /dev/null
+++ b/doc/build/.buildinfo
@@ -0,0 +1,4 @@
+# Sphinx build info version 1
+# This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done.
+config: 56c11847db12f185f46d1ce76393616e
+tags: 645f666f9bcd5a90fca523b33c5a78b7
diff --git a/doc/build/.doctrees/documentation.doctree b/doc/build/.doctrees/documentation.doctree
new file mode 100644
index 0000000..cea3e4e
Binary files /dev/null and b/doc/build/.doctrees/documentation.doctree differ
diff --git a/doc/build/.doctrees/environment.pickle b/doc/build/.doctrees/environment.pickle
new file mode 100644
index 0000000..138628d
Binary files /dev/null and b/doc/build/.doctrees/environment.pickle differ
diff --git a/doc/build/_modules/index.html b/doc/build/_modules/index.html
new file mode 100644
index 0000000..aa09c98
--- /dev/null
+++ b/doc/build/_modules/index.html
@@ -0,0 +1,86 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>Overview: module code — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="../_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="../_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: '../',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="../_static/jquery.js"></script>
+ <script type="text/javascript" src="../_static/underscore.js"></script>
+ <script type="text/javascript" src="../_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="../documentation.html" />
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+ <h1>All modules for which code is available</h1>
+<ul><li><a href="umap/combine_umaps.html">umap.combine_umaps</a></li>
+<li><a href="umap/get_kmers.html">umap.get_kmers</a></li>
+<li><a href="umap/run_bowtie.html">umap.run_bowtie</a></li>
+<li><a href="umap/uint8_to_bed.html">umap.uint8_to_bed</a></li>
+<li><a href="umap/unify_bowtie.html">umap.unify_bowtie</a></li>
+</ul>
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper"><div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="../documentation.html">Documentation overview</a><ul>
+ </ul></li>
+</ul>
+</div>
+<div id="searchbox" style="display: none" role="search">
+ <h3>Quick search</h3>
+ <form class="search" action="../search.html" method="get">
+ <input type="text" name="q" />
+ <input type="submit" value="Go" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+ </form>
+</div>
+<script type="text/javascript">$('#searchbox').show(0);</script>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/_modules/umap/combine_umaps.html b/doc/build/_modules/umap/combine_umaps.html
new file mode 100644
index 0000000..798502a
--- /dev/null
+++ b/doc/build/_modules/umap/combine_umaps.html
@@ -0,0 +1,265 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>umap.combine_umaps — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="../../_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: '../../',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="../../_static/jquery.js"></script>
+ <script type="text/javascript" src="../../_static/underscore.js"></script>
+ <script type="text/javascript" src="../../_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="../../documentation.html" />
+ <link rel="up" title="Module code" href="../index.html" />
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+ <h1>Source code for umap.combine_umaps</h1><div class="highlight"><pre>
+<span class="kn">from</span> <span class="nn">argparse</span> <span class="kn">import</span> <span class="n">ArgumentParser</span>
+<span class="kn">import</span> <span class="nn">gzip</span>
+<span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
+<span class="kn">import</span> <span class="nn">os</span>
+
+
+<span class="k">def</span> <span class="nf">get_args</span><span class="p">():</span>
+ <span class="n">parser</span> <span class="o">=</span> <span class="n">ArgumentParser</span><span class="p">(</span>
+ <span class="n">description</span><span class="o">=</span><span class="s2">"Combines mappability uint8 vectors of "</span>
+ <span class="s2">"several kmers into 1 uint8 vector per chromosome. "</span>
+ <span class="s2">"It requires a directory with subfolders names as "</span>
+ <span class="s2">"k<read length>. This script requires a number to infer "</span>
+ <span class="s2">"chromosome. If not specifying -job_id, it will "</span>
+ <span class="s2">"identify the chromosome using -var_id environmental "</span>
+ <span class="s2">"varibale which by default is SGE_TASK_ID."</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"kmer_dir"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Directory with subfolders "</span>
+ <span class="s2">"named as k<read length>)"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"chrsize_path"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Path to 2 column tsv file with first column "</span>
+ <span class="s2">"as chromosome and second column as its size. Will "</span>
+ <span class="s2">"be used to identify order of the chromosomes."</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-out_dir"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="s2">"infer"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"If not specified, a subfolder "</span>
+ <span class="s2">"will be created in kmer_dir names as "</span>
+ <span class="s2">"globalmap_k<smallestkmer>tok<largestkmer>"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-job_id"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
+ <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"1-based index for finding chromosome from -chrsize_path. "</span>
+ <span class="s2">"If not specified, it will user -var_id to "</span>
+ <span class="s2">"infer the chromosome for combining mappabilitiy of "</span>
+ <span class="s2">"different kmers."</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-var_id"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="s2">"SGE_TASK_ID"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"If -job_id is not specified, job_id will be inferred "</span>
+ <span class="s2">"from environmental variable -var_id."</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-kmer_dir_2"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="s2">"NA"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Specify to merge kmers of two different directories "</span>
+ <span class="s2">"by logical operation AND."</span><span class="p">)</span>
+ <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">job_id</span>
+ <span class="n">out_dir</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">out_dir</span>
+ <span class="n">kmers</span> <span class="o">=</span> <span class="p">[</span><span class="n">each_kmer</span> <span class="k">for</span> <span class="n">each_kmer</span> <span class="ow">in</span> <span class="nb">next</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">walk</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">kmer_dir</span><span class="p">))[</span><span class="mi">1</span><span [...]
+ <span class="k">if</span> <span class="s2">"k"</span> <span class="o">==</span> <span class="n">each_kmer</span><span class="p">[</span><span class="mi">0</span><span class="p">]]</span>
+ <span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">job_id</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="n">args</span><span class="o">.</span><span class="n">var_id</span><span class="p">])</span> <span class="o">-</span> <span class="mi">1</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="n">job_id</span> <span class="o">-</span> <span class="mi">1</span>
+ <span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">out_dir</span> <span class="o">==</span> <span class="s2">"infer"</span><span class="p">:</span>
+ <span class="n">kmer_ints</span> <span class="o">=</span> <span class="p">[</span><span class="nb">int</span><span class="p">(</span><span class="n">each_kmer</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">"k"</span><span class="p">,</span> <span class="s2">""</span><span class="p">))</span> <span class="k">for</span> <span class="n">each_kmer</span> <span class="ow">in</span> <span class="n">kmers</span><s [...]
+ <span class="n">out_dir</span> <span class="o">=</span> <span class="s2">"{}/globalmap_k{}tok{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">args</span><span class="o">.</span><span class="n">kmer_dir</span><span class="p">,</span> <span class="nb">min</span><span class="p">(</span><span class="n">kmer_ints</span><span class="p">),</span> <span class="nb">max</span><span class="p">(</span><span class="n">kmer_ints</span><span class="p">))</span>
+ <span class="k">try</span><span class="p">:</span>
+ <span class="n">out_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">args</span><span class="o">.</span><span class="n">kmer_dir</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">chrsize_path</span><span class="p">,</span>
+ <span class="n">out_dir</span><span class="p">,</span> <span class="n">job_id</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">kmer_dir_2</span><span class="p">]</span>
+ <span class="k">except</span><span class="p">:</span>
+ <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
+ <span class="s2">"chrsize_path or job_id were invalid."</span><span class="p">)</span>
+ <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">out_dir</span><span class="p">):</span>
+ <span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">out_dir</span><span class="p">)</span>
+ <span class="k">return</span> <span class="n">out_list</span>
+
+
+<div class="viewcode-block" id="CombineUmaps"><a class="viewcode-back" href="../../documentation.html#umap.CombineUmaps">[docs]</a><span class="k">class</span> <span class="nc">CombineUmaps</span><span class="p">:</span>
+ <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">kmer_dir</span><span class="p">,</span> <span class="n">chrsize_path</span><span class="p">,</span>
+ <span class="n">out_dir</span><span class="p">,</span> <span class="n">job_id</span><span class="p">,</span> <span class="n">kmer_dir_2</span><span class="p">):</span>
+ <span class="sd">"""Combine <chr>.<kmer>.uint8.unique.gz files</span>
+
+<span class="sd"> The kmer_dir has subfolders named as k<integer> with</span>
+<span class="sd"> <chr>.<kmer>.uint8.unique.gz files inside. This script</span>
+<span class="sd"> will use the job_id to use a particular chromosome and</span>
+<span class="sd"> merge the uint8.gz files across all of the different</span>
+<span class="sd"> kmers into one uint8.gz. Note: All methods would</span>
+<span class="sd"> run consequently when creating the class instance.</span>
+
+<span class="sd"> Args:</span>
+<span class="sd"> kmer_dir: Directory with k<integer> subfolders</span>
+<span class="sd"> chrsize_path: 2-column tsv file of <chrom>\t<size>\n...</span>
+<span class="sd"> out_dir: Output files will be saved to this folder</span>
+<span class="sd"> job_id: 0-based index to find chromosome from chrsize_path</span>
+<span class="sd"> kmer_dir_2: If using Bismap and want to merge C2T and G2A data</span>
+
+<span class="sd"> Returns</span>
+<span class="sd"> Saves the output to outdir/<chrom>.uint8.unique.gz files</span>
+<span class="sd"> """</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir</span> <span class="o">=</span> <span class="n">kmer_dir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir_2</span> <span class="o">=</span> <span class="n">kmer_dir_2</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chrsize_path</span> <span class="o">=</span> <span class="n">chrsize_path</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">out_dir</span> <span class="o">=</span> <span class="n">out_dir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">job_id</span> <span class="o">=</span> <span class="n">job_id</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chrom</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">size</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_chrom_size</span><span class="p">()</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">kmers</span> <span class="o">=</span> <span class="p">[</span><span class="n">each_kmer</span> <span class="k">for</span> <span class="n">each_kmer</span> <span class="ow">in</span>
+ <span class="nb">next</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">walk</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir</span><span class="p">))[</span><span class="mi">1</span><span class="p">]</span>
+ <span class="k">if</span> <span class="s2">"k"</span> <span class="o">==</span> <span class="n">each_kmer</span><span class="p">[</span><span class="mi">0</span><span class="p">]]</span>
+ <span class="n">combined_ar</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">combine_uints</span><span class="p">()</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">write_ar</span><span class="p">(</span><span class="n">combined_ar</span><span class="p">)</span>
+
+ <span class="k">def</span> <span class="nf">get_chrom_size</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="sd">"""Finds chrom and size from self.chrsize_path"""</span>
+ <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chrsize_path</span><span class="p">,</span> <span class="s2">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">chrsize_link</span><span class="p">:</span>
+ <span class="n">ind_chr</span> <span class="o">=</span> <span class="mi">0</span>
+ <span class="k">for</span> <span class="n">chrsize_line</span> <span class="ow">in</span> <span class="n">chrsize_link</span><span class="p">:</span>
+ <span class="k">if</span> <span class="n">ind_chr</span> <span class="o">==</span> <span class="bp">self</span><span class="o">.</span><span class="n">job_id</span><span class="p">:</span>
+ <span class="n">chromosome</span> <span class="o">=</span> <span class="n">chrsize_line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="p">)[</span><span class="mi">0</span><span class="p">]</span>
+ <span class="n">size</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">chrsize_line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="p">)[</span><span class="mi">1</span><span class="p">])</span>
+ <span class="n">ind_chr</span> <span class="o">=</span> <span class="n">ind_chr</span> <span class="o">+</span> <span class="mi">1</span>
+ <span class="k">return</span> <span class="n">chromosome</span><span class="p">,</span> <span class="n">size</span>
+
+ <span class="k">def</span> <span class="nf">combine_uints</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="sd">"""Merged different kmer arrays of one chromosome</span>
+<span class="sd"> """</span>
+ <span class="n">MergeKmers</span> <span class="o">=</span> <span class="bp">False</span>
+ <span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir_2</span><span class="p">):</span>
+ <span class="k">print</span><span class="p">(</span>
+ <span class="s2">"Limit mappability to regions {} {} and {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="s2">"that are unique in both"</span><span class="p">,</span>
+ <span class="n">kmer_dir</span><span class="p">,</span> <span class="n">kmer_dir_2</span><span class="p">))</span>
+ <span class="n">MergeKmers</span> <span class="o">=</span> <span class="bp">True</span>
+ <span class="n">combined_ar</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">size</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>
+ <span class="n">kmer_nums</span> <span class="o">=</span> <span class="p">[</span><span class="nb">int</span><span class="p">(</span><span class="n">kmer</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">"k"</span><span class="p">,</span> <span class="s2">""</span><span class="p">))</span> <span class="k">for</span> <span class="n">kmer</span> <span class="ow">in</span> <span class="bp">self</span><span class= [...]
+ <span class="n">kmer_nums</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
+ <span class="k">for</span> <span class="n">kmer_num</span> <span class="ow">in</span> <span class="n">kmer_nums</span><span class="p">:</span>
+ <span class="n">kmer</span> <span class="o">=</span> <span class="s2">"k{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">kmer_num</span><span class="p">)</span>
+ <span class="n">full_kmer_path</span> <span class="o">=</span> <span class="s2">"{}/{}/{}.{}.uint8.unique.gz"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">chrom</span><span class="p">,</span> <span class="n">kmer</span><span class="p">)</span>
+ <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">full_kmer_path</span><span class="p">):</span>
+ <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">"{} does not exist"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">full_kmer_path</span><span class="p">))</span>
+ <span class="n">kmer_link</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">full_kmer_path</span><span class="p">,</span> <span class="s2">"rb"</span><span class="p">)</span>
+ <span class="n">kmer_ar</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">frombuffer</span><span class="p">(</span><span class="n">kmer_link</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">kmer_ar</span><span class="p">)</span> <span class="o">!=</span> <span class="bp">self</span><span class="o">.</span><span class="n">size</span><span class="p">:</span>
+ <span class="n">kmer_ar</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">kmer_ar</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">kmer_num</span><span class="p">))</span>
+ <span class="n">kmer_link</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
+ <span class="n">index_comb_0</span> <span class="o">=</span> <span class="n">combined_ar</span> <span class="o">==</span> <span class="mi">0</span>
+ <span class="n">index_kmer</span> <span class="o">=</span> <span class="n">kmer_ar</span> <span class="o">!=</span> <span class="mi">0</span>
+ <span class="n">index_adkmer</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">logical_and</span><span class="p">(</span><span class="n">index_comb_0</span><span class="p">,</span> <span class="n">index_kmer</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">MergeKmers</span><span class="p">:</span>
+ <span class="n">full_kmer_path_2</span> <span class="o">=</span> <span class="s2">"{}/{}/{}.{}.uint8.unique.gz"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir_2</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">chrom</span><span class="p">,</span> <span class="n">kmer</span><span class="p">)</span>
+ <span class="n">kmer_link_2</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">full_kmer_path_2</span><span class="p">,</span> <span class="s2">"rb"</span><span class="p">)</span>
+ <span class="n">kmer_ar_2</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">frombuffer</span><span class="p">(</span><span class="n">kmer_link_2</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">kmer_ar_2</span><span class="p">)</span> <span class="o">!=</span> <span class="bp">self</span><span class="o">.</span><span class="n">size</span><span class="p">:</span>
+ <span class="n">kmer_ar_2</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">kmer_ar_2</span><span class="p">,</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">kmer_num</span><span class="p">))</span>
+ <span class="n">kmer_link_2</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
+ <span class="n">index_kmer_2</span> <span class="o">=</span> <span class="n">kmer_ar_2</span> <span class="o">!=</span> <span class="mi">0</span>
+ <span class="n">index_adkmer_2</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">logical_and</span><span class="p">(</span><span class="n">index_comb_0</span><span class="p">,</span> <span class="n">index_kmer_2</span><span class="p">)</span>
+ <span class="n">index_adkmer</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">logical_and</span><span class="p">(</span><span class="n">index_adkmer</span><span class="p">,</span> <span class="n">index_adkmer_2</span><span class="p">)</span>
+ <span class="n">combined_ar</span><span class="p">[</span><span class="n">index_adkmer</span><span class="p">]</span> <span class="o">=</span> <span class="n">kmer_num</span>
+ <span class="k">print</span><span class="p">(</span>
+ <span class="s2">"Added information of {} for {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">kmer</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">chrom</span><span class="p">))</span>
+ <span class="k">return</span> <span class="n">combined_ar</span>
+
+ <span class="k">def</span> <span class="nf">write_ar</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">combined_ar</span><span class="p">):</span>
+ <span class="sd">"""Writes merged array to unsigned 8bit integer file.</span>
+
+<span class="sd"> Used self.out_dir and self.chrom.</span>
+
+<span class="sd"> Args:</span>
+<span class="sd"> combined_ar: Can be any numpy array</span>
+<span class="sd"> """</span>
+ <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">out_dir</span><span class="p">):</span>
+ <span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">out_dir</span><span class="p">)</span>
+ <span class="n">out_path</span> <span class="o">=</span> <span class="s2">"{}/{}.uint8.unique.gz"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">out_dir</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">chrom</span><span class="p">)</span>
+ <span class="n">out_link</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">out_path</span><span class="p">,</span> <span class="s2">"wb"</span><span class="p">)</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">combined_ar</span><span class="o">.</span><span class="n">tobytes</span><span class="p">())</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></div>
+
+
+<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span>
+ <span class="n">kmer_dir</span><span class="p">,</span> <span class="n">chrsize_path</span><span class="p">,</span> <span class="n">out_dir</span><span class="p">,</span> <span class="n">job_id</span><span class="p">,</span> <span class="n">kmer_dir_2</span> <span class="o">=</span> <span class="n">get_args</span><span class="p">()</span>
+ <span class="n">CombineUmaps</span><span class="p">(</span><span class="n">kmer_dir</span><span class="p">,</span> <span class="n">chrsize_path</span><span class="p">,</span> <span class="n">out_dir</span><span class="p">,</span> <span class="n">job_id</span><span class="p">,</span> <span class="n">kmer_dir_2</span><span class="p">)</span>
+</pre></div>
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper"><div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="../../documentation.html">Documentation overview</a><ul>
+ <li><a href="../index.html">Module code</a><ul>
+ </ul></li>
+ </ul></li>
+</ul>
+</div>
+<div id="searchbox" style="display: none" role="search">
+ <h3>Quick search</h3>
+ <form class="search" action="../../search.html" method="get">
+ <input type="text" name="q" />
+ <input type="submit" value="Go" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+ </form>
+</div>
+<script type="text/javascript">$('#searchbox').show(0);</script>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/_modules/umap/get_kmers.html b/doc/build/_modules/umap/get_kmers.html
new file mode 100644
index 0000000..842b25b
--- /dev/null
+++ b/doc/build/_modules/umap/get_kmers.html
@@ -0,0 +1,366 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>umap.get_kmers — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="../../_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: '../../',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="../../_static/jquery.js"></script>
+ <script type="text/javascript" src="../../_static/underscore.js"></script>
+ <script type="text/javascript" src="../../_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="../../documentation.html" />
+ <link rel="up" title="Module code" href="../index.html" />
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+ <h1>Source code for umap.get_kmers</h1><div class="highlight"><pre>
+<span class="kn">from</span> <span class="nn">argparse</span> <span class="kn">import</span> <span class="n">ArgumentParser</span>
+<span class="kn">import</span> <span class="nn">gzip</span>
+<span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
+<span class="kn">import</span> <span class="nn">os</span>
+<span class="kn">import</span> <span class="nn">pandas</span> <span class="kn">as</span> <span class="nn">pd</span>
+
+
+<span class="k">def</span> <span class="nf">get_args</span><span class="p">():</span>
+ <span class="n">parser</span> <span class="o">=</span> <span class="n">ArgumentParser</span><span class="p">(</span>
+ <span class="n">description</span><span class="o">=</span><span class="s2">"Creates list of unique Kmers "</span>
+ <span class="s2">"for each 1Mb of the genome. Relies on an environmental "</span>
+ <span class="s2">"variable such as SGE_TASK_ID to identify the correct "</span>
+ <span class="s2">"megabase of the genome for this purpose. "</span>
+ <span class="s2">"If not using job arrays, specify -job_id manually."</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"chrsize_path"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Path to 2 column tsv file where first column is "</span>
+ <span class="s2">"chromosome name and second column is chromosome size"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"out_dir"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Path to the directory for creating "</span>
+ <span class="s2">"<chromosome>.<Megabase>.<kmer>.kmer.gz files"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"kmer"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="s2">"infer"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"The software would infer it based on the "</span>
+ <span class="s2">"name of the 'out_dir'. If it is set and "</span>
+ <span class="s2">"contradicts the 'out_dir', a subfolder "</span>
+ <span class="s2">"under out_dir will be created named 'kmer' and "</span>
+ <span class="s2">"out_dir will be changed to that."</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"chr_dir"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Path to directory with <chromosome>.fasta files."</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-job_id"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
+ <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"If not submitted in job array, would require this "</span>
+ <span class="s2">"parameter to be set. (1-based index)"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-var_id"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="s2">"SGE_TASK_ID"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"The variable name that the script would use "</span>
+ <span class="s2">"for identifying the job id. By default: SGE_TASK_ID."</span><span class="p">)</span>
+ <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
+ <span class="n">out_dir</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">out_dir</span>
+ <span class="n">inferred_kmer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">out_dir</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"/"</span><span class="p">)[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
+ <span class="n">kmer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">kmer</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">job_id</span>
+ <span class="k">if</span> <span class="n">args</span><span class="o">.</span><span class="n">kmer</span> <span class="o">==</span> <span class="s2">"infer"</span><span class="p">:</span>
+ <span class="n">kmer</span> <span class="o">=</span> <span class="n">inferred_kmer</span>
+ <span class="k">elif</span> <span class="n">args</span><span class="o">.</span><span class="n">kmer</span> <span class="o">!=</span> <span class="n">inferred_kmer</span><span class="p">:</span>
+ <span class="n">kmer</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">kmer</span>
+ <span class="n">out_dir</span> <span class="o">=</span> <span class="s2">"{}/{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">out_dir</span><span class="p">,</span> <span class="n">kmer</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">job_id</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="n">args</span><span class="o">.</span><span class="n">var_id</span><span class="p">])</span> <span class="o">-</span> <span class="mi">1</span>
+ <span class="n">out_list</span> <span class="o">=</span> <span class="p">[</span><span class="n">args</span><span class="o">.</span><span class="n">chrsize_path</span><span class="p">,</span> <span class="n">out_dir</span><span class="p">,</span>
+ <span class="n">kmer</span><span class="p">,</span> <span class="n">job_id</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">chr_dir</span><span class="p">]</span>
+ <span class="k">return</span> <span class="n">out_list</span>
+
+
+<div class="viewcode-block" id="GetKmers"><a class="viewcode-back" href="../../documentation.html#umap.GetKmers">[docs]</a><span class="k">class</span> <span class="nc">GetKmers</span><span class="p">:</span>
+ <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">out_dir</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">job_id</span><span class="p">,</span>
+ <span class="n">chr_dir</span><span class="p">,</span> <span class="n">chrsize_path</span><span class="p">):</span>
+ <span class="sd">"""Creates all the possible k-mers for part of the genome.</span>
+
+<span class="sd"> Used a referece file to find the appropriate chromosome,</span>
+<span class="sd"> start and end position. Passes through the fasta file</span>
+<span class="sd"> of the chromosome and generates all of the possible k-mers.</span>
+
+<span class="sd"> Args:</span>
+<span class="sd"> :param out_dir: Directory for saving <chrom>.<jobid>.kmer.gz files</span>
+<span class="sd"> :param str kmer: k-mer string such as 'k24'</span>
+<span class="sd"> :param int job_id: Reference ID used for finding chrom, start and end</span>
+<span class="sd"> :param chr_dir: Path to directory with chromosome fasta files</span>
+<span class="sd"> :param chrsize_path: Path to 2 column file of chrom\tsize\n</span>
+
+<span class="sd"> :returns: An object with methods such as get_step_fasta(),</span>
+<span class="sd"> get_seq_ar(), write_kmers() and write_regions().</span>
+
+<span class="sd"> :raises ValueError: if expected chromosome path does not exist</span>
+<span class="sd"> """</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">out_dir</span> <span class="o">=</span> <span class="n">out_dir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">kmer</span> <span class="o">=</span> <span class="n">kmer</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">job_id</span> <span class="o">=</span> <span class="n">job_id</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chrsize_path</span> <span class="o">=</span> <span class="n">chrsize_path</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chr_dir</span> <span class="o">=</span> <span class="n">chr_dir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chrom</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">start</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">end</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_region</span><span class="p">()</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chr_path</span> <span class="o">=</span> <span class="s2">"{}/{}.fasta"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chr_dir</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">chrom</span><span class="p">)</span>
+ <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chr_path</span><span class="p">):</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chr_path</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">chr_path</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">".fasta"</span><span class="p">,</span> <span class="s2">".fa"</span><span class="p">)</span>
+ <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chr_path</span><span class="p">):</span>
+ <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span><span class="s2">"{} does not exist"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chr_path</span><span class="p">))</span>
+
+ <span class="k">def</span> <span class="nf">get_region</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="sd">"""Find chromosomal chunk</span>
+
+<span class="sd"> Using job_id and chrsize_path, finds chromosome,</span>
+<span class="sd"> start and end. Looks if chrsize_index.tsv exists.</span>
+<span class="sd"> If it doesn't, it will create chrsize_index.tsv.</span>
+<span class="sd"> Otherwise will use it for finding that information.</span>
+
+<span class="sd"> :returns: chrom, start, end</span>
+
+<span class="sd"> :raises ValueError: If job_id is out of expected range</span>
+<span class="sd"> """</span>
+ <span class="n">chrsize_path</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">chrsize_path</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">job_id</span>
+ <span class="n">CHUNK_SIZE</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="mf">1e6</span><span class="p">)</span>
+ <span class="n">ind_path</span> <span class="o">=</span> <span class="s2">"{}/chrsize_index.tsv"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="s2">"/"</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">chrsize_path</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"/"</span><span class="p">)[:</span><span class="o">-</span><span class="mi">1</span><span class="p">]))</span>
+ <span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">ind_path</span><span class="p">):</span>
+ <span class="n">ind_df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span><span class="n">ind_path</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="p">,</span> <span class="n">index_col</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
+ <span class="n">dict_inds</span> <span class="o">=</span> <span class="n">ind_df</span><span class="o">.</span><span class="n">to_dict</span><span class="p">()</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="n">ind_link</span> <span class="o">=</span> <span class="nb">open</span><span class="p">(</span><span class="n">ind_path</span><span class="p">,</span> <span class="s2">"w"</span><span class="p">)</span>
+ <span class="n">ind_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="s2">"Index</span><span class="se">\t</span><span class="s2">Chromosome</span><span class="se">\t</span><span class="s2">Start</span><span class="se">\t</span><span class="s2">End</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span>
+ <span class="n">start</span> <span class="o">=</span> <span class="mi">1</span>
+ <span class="n">ind</span> <span class="o">=</span> <span class="mi">0</span>
+ <span class="c1"># Identifying chromosome, start, end for job_id</span>
+ <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">chrsize_path</span><span class="p">,</span> <span class="s2">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">chrsize_link</span><span class="p">:</span>
+ <span class="k">for</span> <span class="n">chrsize_line</span> <span class="ow">in</span> <span class="n">chrsize_link</span><span class="p">:</span>
+ <span class="n">chrom</span><span class="p">,</span> <span class="n">len_chr</span> <span class="o">=</span> <span class="n">chrsize_line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="p">)</span>
+ <span class="n">end</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">len_chr</span><span class="p">)</span> <span class="o">+</span> <span class="n">start</span>
+ <span class="k">for</span> <span class="n">pos</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">start</span><span class="p">,</span> <span class="n">end</span><span class="p">,</span> <span class="n">CHUNK_SIZE</span><span class="p">):</span>
+ <span class="k">if</span> <span class="n">pos</span> <span class="o"><</span> <span class="n">end</span><span class="p">:</span>
+ <span class="k">if</span> <span class="n">pos</span> <span class="o">+</span> <span class="n">CHUNK_SIZE</span> <span class="o">-</span> <span class="mi">1</span> <span class="o">></span> <span class="n">end</span><span class="p">:</span>
+ <span class="n">pos_end</span> <span class="o">=</span> <span class="n">end</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="n">pos_end</span> <span class="o">=</span> <span class="n">pos</span> <span class="o">+</span> <span class="n">CHUNK_SIZE</span> <span class="o">-</span> <span class="mi">1</span>
+ <span class="n">ind_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span>
+ <span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="o">.</span><span class="n">join</span><span class="p">([</span><span class="nb">str</span><span class="p">(</span><span class="n">ind</span><span class="p">),</span> <span class="n">chrom</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">pos</span><span class="p">),</span>
+ <span class="nb">str</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">pos_end</span><span class="p">))])</span> <span class="o">+</span>
+ <span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span>
+ <span class="n">ind</span> <span class="o">=</span> <span class="n">ind</span> <span class="o">+</span> <span class="mi">1</span>
+ <span class="n">ind_link</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
+ <span class="n">ind_df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span><span class="n">ind_path</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="p">,</span> <span class="n">index_col</span><span class="o">=</span><span class="mi">0</span><span class="p">)</span>
+ <span class="n">dict_inds</span> <span class="o">=</span> <span class="n">ind_df</span><span class="o">.</span><span class="n">to_dict</span><span class="p">()</span>
+ <span class="k">try</span><span class="p">:</span>
+ <span class="n">chrom</span><span class="p">,</span> <span class="n">start</span><span class="p">,</span> <span class="n">end</span> <span class="o">=</span> <span class="p">[</span>
+ <span class="n">dict_inds</span><span class="p">[</span><span class="n">qry</span><span class="p">][</span><span class="n">job_id</span><span class="p">]</span> <span class="k">for</span>
+ <span class="n">qry</span> <span class="ow">in</span> <span class="p">[</span><span class="s2">"Chromosome"</span><span class="p">,</span> <span class="s2">"Start"</span><span class="p">,</span> <span class="s2">"End"</span><span class="p">]]</span>
+ <span class="k">except</span><span class="p">:</span>
+ <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
+ <span class="s2">"{} Job id is larger than available indices"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">job_id</span><span class="p">))</span>
+ <span class="k">return</span> <span class="n">chrom</span><span class="p">,</span> <span class="nb">int</span><span class="p">(</span><span class="n">start</span><span class="p">),</span> <span class="nb">int</span><span class="p">(</span><span class="n">end</span><span class="p">)</span>
+
+ <span class="k">def</span> <span class="nf">get_step_fasta</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="sd">"""Finds number of nucleotides at each line of FASTA</span>
+
+
+<span class="sd"> :raises ValueError: If top 10 FASTA lines have</span>
+<span class="sd"> sequences of varying length</span>
+<span class="sd"> """</span>
+ <span class="n">chr_path</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">chr_path</span>
+ <span class="n">line_nums</span> <span class="o">=</span> <span class="mi">10</span>
+ <span class="n">len_lines</span> <span class="o">=</span> <span class="p">[]</span>
+ <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">chr_path</span><span class="p">,</span> <span class="s2">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">chr_link</span><span class="p">:</span>
+ <span class="k">for</span> <span class="n">line_num</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">line_nums</span><span class="p">):</span>
+ <span class="n">chr_line</span> <span class="o">=</span> <span class="n">chr_link</span><span class="o">.</span><span class="n">readline</span><span class="p">()</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span>
+ <span class="k">if</span> <span class="s2">">"</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">chr_line</span><span class="p">:</span>
+ <span class="n">len_line</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">chr_line</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">len_line</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">len_lines</span><span class="p">:</span>
+ <span class="k">if</span> <span class="n">chr_line</span> <span class="o">!=</span> <span class="s2">""</span><span class="p">:</span>
+ <span class="n">len_lines</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">len_line</span><span class="p">)</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">len_lines</span><span class="p">)</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
+ <span class="k">return</span><span class="p">(</span><span class="n">len_lines</span><span class="p">[</span><span class="mi">0</span><span class="p">])</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
+ <span class="s2">"Top 10 FASTA lines have sequences of varying length"</span><span class="p">)</span>
+
+ <span class="k">def</span> <span class="nf">get_seq_ar</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">fasta_fix</span><span class="p">):</span>
+ <span class="sd">"""Gets sequence as numpy array</span>
+
+<span class="sd"> get_seq_ar creates a numpy array matching sequence</span>
+<span class="sd"> of the region specified by chromosome, start and</span>
+<span class="sd"> end. However it starts the sequence with kmer - 1</span>
+<span class="sd"> less than the specified start to account for the</span>
+<span class="sd"> missing kmers from the previous chunk of chromosome.</span>
+<span class="sd"> Each element is one line of a fasta file that may be</span>
+<span class="sd"> cut to match the exact start/end positions.</span>
+
+<span class="sd"> Args:</span>
+<span class="sd"> :param int fasta_fix: Number of nucleotides per fasta line.</span>
+
+<span class="sd"> :returns: Numpy array with each member being one line of FASTA</span>
+<span class="sd"> """</span>
+ <span class="n">start</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">start</span>
+ <span class="n">end</span><span class="p">,</span> <span class="n">chr_path</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">end</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">chr_path</span>
+ <span class="n">kmer</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kmer</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">"k"</span><span class="p">,</span> <span class="s2">""</span><span class="p">))</span>
+ <span class="n">start</span> <span class="o">=</span> <span class="n">start</span> <span class="o">-</span> <span class="n">kmer</span>
+ <span class="k">if</span> <span class="n">start</span> <span class="o"><</span> <span class="mi">0</span><span class="p">:</span>
+ <span class="n">start</span> <span class="o">=</span> <span class="mi">0</span>
+ <span class="n">st_line</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">floor</span><span class="p">(</span><span class="n">start</span> <span class="o">/</span> <span class="n">fasta_fix</span><span class="p">))</span>
+ <span class="n">st_line_pos</span> <span class="o">=</span> <span class="n">start</span> <span class="o">%</span> <span class="n">fasta_fix</span>
+ <span class="n">end_line</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">floor</span><span class="p">(</span><span class="n">end</span> <span class="o">/</span> <span class="n">fasta_fix</span><span class="p">))</span>
+ <span class="n">end_line_pos</span> <span class="o">=</span> <span class="p">(</span><span class="n">end</span> <span class="o">%</span> <span class="n">fasta_fix</span><span class="p">)</span> <span class="o">+</span> <span class="mi">1</span>
+ <span class="n">seq_ar</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">empty</span><span class="p">(</span><span class="nb">int</span><span class="p">(</span><span class="n">end_line</span> <span class="o">-</span> <span class="n">st_line</span> <span class="o">+</span> <span class="mi">1</span><span class="p">),</span>
+ <span class="n">dtype</span><span class="o">=</span><span class="s2">"|S{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">fasta_fix</span> <span class="o">+</span> <span class="mi">1</span><span class="p">))</span>
+ <span class="n">ind_seq</span> <span class="o">=</span> <span class="mi">0</span>
+ <span class="n">STORE_LINE</span> <span class="o">=</span> <span class="bp">False</span>
+ <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="n">chr_path</span><span class="p">,</span> <span class="s2">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">chr_link</span><span class="p">:</span>
+ <span class="n">line_ind</span> <span class="o">=</span> <span class="mi">0</span>
+ <span class="k">for</span> <span class="n">each_line</span> <span class="ow">in</span> <span class="n">chr_link</span><span class="p">:</span>
+ <span class="k">if</span> <span class="n">line_ind</span> <span class="o">==</span> <span class="n">st_line</span><span class="p">:</span>
+ <span class="n">STORE_LINE</span> <span class="o">=</span> <span class="bp">True</span>
+ <span class="n">each_line</span> <span class="o">=</span> <span class="n">each_line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()[</span><span class="n">st_line_pos</span><span class="p">:]</span>
+ <span class="k">if</span> <span class="n">STORE_LINE</span><span class="p">:</span>
+ <span class="k">if</span> <span class="n">line_ind</span> <span class="o">==</span> <span class="n">end_line</span><span class="p">:</span>
+ <span class="n">STORE_LINE</span> <span class="o">=</span> <span class="bp">False</span>
+ <span class="n">each_line</span> <span class="o">=</span> <span class="n">each_line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()[:</span><span class="n">end_line_pos</span><span class="p">]</span>
+ <span class="n">seq_ar</span><span class="p">[</span><span class="n">ind_seq</span><span class="p">]</span> <span class="o">=</span> <span class="n">each_line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span>
+ <span class="n">ind_seq</span> <span class="o">=</span> <span class="n">ind_seq</span> <span class="o">+</span> <span class="mi">1</span>
+ <span class="n">line_ind</span> <span class="o">=</span> <span class="n">line_ind</span> <span class="o">+</span> <span class="mi">1</span>
+ <span class="k">if</span> <span class="s2">"chr"</span> <span class="ow">in</span> <span class="n">seq_ar</span><span class="p">[</span><span class="mi">0</span><span class="p">]:</span>
+ <span class="n">seq_ar</span> <span class="o">=</span> <span class="n">seq_ar</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
+ <span class="k">return</span> <span class="n">seq_ar</span>
+
+ <span class="k">def</span> <span class="nf">write_kmers</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">cur_seq</span><span class="p">,</span> <span class="n">kmer_int</span><span class="p">,</span> <span class="n">out_link</span><span class="p">):</span>
+ <span class="sd">"""Creates k-mers and saves them to the file</span>
+
+<span class="sd"> Using a numpy array of sequences, generates and</span>
+<span class="sd"> saves all of the possible k-mers.</span>
+
+<span class="sd"> Args:</span>
+<span class="sd"> :param cur_seq: A string of sequences</span>
+<span class="sd"> :param kmer_int: An integer denoting the k-mer size</span>
+<span class="sd"> :param out_link: File link for writing k-mers</span>
+
+<span class="sd"> :returns: May modify cur_seq by deducing the k-mers that</span>
+<span class="sd"> are written to the out_link file object.</span>
+<span class="sd"> """</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">cur_seq</span><span class="p">)</span> <span class="o"><</span> <span class="n">kmer_int</span><span class="p">:</span>
+ <span class="k">return</span> <span class="n">cur_seq</span>
+ <span class="k">elif</span> <span class="nb">len</span><span class="p">(</span><span class="n">cur_seq</span><span class="p">)</span> <span class="o">==</span> <span class="n">kmer_int</span><span class="p">:</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">cur_seq</span> <span class="o">+</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span>
+ <span class="n">cur_seq</span> <span class="o">=</span> <span class="n">cur_seq</span><span class="p">[</span><span class="mi">1</span><span class="p">:]</span>
+ <span class="k">return</span> <span class="n">cur_seq</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">cur_seq</span><span class="p">)</span> <span class="o">-</span> <span class="n">kmer_int</span><span class="p">):</span>
+ <span class="n">j</span> <span class="o">=</span> <span class="n">i</span> <span class="o">+</span> <span class="n">kmer_int</span>
+ <span class="k">if</span> <span class="n">j</span> <span class="o">></span> <span class="nb">len</span><span class="p">(</span><span class="n">cur_seq</span><span class="p">):</span>
+ <span class="n">j</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">cur_seq</span><span class="p">)</span>
+ <span class="n">seq_out</span> <span class="o">=</span> <span class="n">cur_seq</span><span class="p">[</span><span class="n">i</span><span class="p">:</span><span class="n">j</span><span class="p">]</span>
+ <span class="k">if</span> <span class="s2">"N"</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">seq_out</span><span class="p">:</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">seq_out</span> <span class="o">+</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span>
+ <span class="n">cur_seq</span> <span class="o">=</span> <span class="n">cur_seq</span><span class="p">[(</span><span class="n">i</span> <span class="o">+</span> <span class="mi">1</span><span class="p">):]</span>
+ <span class="k">return</span> <span class="n">cur_seq</span>
+
+ <span class="k">def</span> <span class="nf">write_region</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="sd">"""Wrapper of GetKmers to get and write k-mers</span>
+
+<span class="sd"> write_region method executes all the other methods</span>
+<span class="sd"> of the GetKmers class for writing out all of the</span>
+<span class="sd"> possible k-mers from chunk of a FASTA file.</span>
+<span class="sd"> """</span>
+ <span class="n">out_dir</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">job_id</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">out_dir</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">kmer</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">job_id</span>
+ <span class="n">chrom</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">chrom</span>
+ <span class="n">start</span><span class="p">,</span> <span class="n">end</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">start</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">end</span>
+ <span class="n">out_path</span> <span class="o">=</span> <span class="s2">"{}/{}.{}.{}.kmer.gz"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">out_dir</span><span class="p">,</span> <span class="n">chrom</span><span class="p">,</span> <span class="n">job_id</span><span class="p">,</span> <span class="n">kmer</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">"k"</span><span class="p">,</span> <span class="s2">""</span><span class="p">))</span>
+ <span class="n">out_link</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">out_path</span><span class="p">,</span> <span class="s2">"wb"</span><span class="p">)</span>
+ <span class="n">fasta_fix</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_step_fasta</span><span class="p">()</span>
+ <span class="n">kmer_int</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">kmer</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">"k"</span><span class="p">,</span> <span class="s2">""</span><span class="p">))</span>
+ <span class="n">seq_ar</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_seq_ar</span><span class="p">(</span><span class="n">fasta_fix</span><span class="p">)</span>
+ <span class="n">cur_seq</span> <span class="o">=</span> <span class="s2">""</span>
+ <span class="k">for</span> <span class="n">each_seq</span> <span class="ow">in</span> <span class="n">seq_ar</span><span class="p">:</span>
+ <span class="n">cur_seq</span> <span class="o">=</span> <span class="n">cur_seq</span> <span class="o">+</span> <span class="n">each_seq</span>
+ <span class="n">cur_seq</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">write_kmers</span><span class="p">(</span><span class="n">cur_seq</span><span class="p">,</span> <span class="n">kmer_int</span><span class="p">,</span> <span class="n">out_link</span><span class="p">)</span>
+ <span class="k">print</span><span class="p">(</span><span class="s2">"Created all sequences for {}:{}-{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">chrom</span><span class="p">,</span> <span class="n">start</span><span class="p">,</span> <span class="n">end</span><span class="p">))</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></div>
+
+
+<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span>
+ <span class="n">chrsize_path</span><span class="p">,</span> <span class="n">out_dir</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">job_id</span><span class="p">,</span> <span class="n">chr_dir</span> <span class="o">=</span> <span class="n">get_args</span><span class="p">()</span>
+ <span class="n">GetKmerObj</span> <span class="o">=</span> <span class="n">GetKmers</span><span class="p">(</span>
+ <span class="n">out_dir</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">job_id</span><span class="p">,</span>
+ <span class="n">chr_dir</span><span class="p">,</span> <span class="n">chrsize_path</span><span class="p">)</span>
+ <span class="n">GetKmerObj</span><span class="o">.</span><span class="n">write_region</span><span class="p">()</span>
+</pre></div>
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper"><div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="../../documentation.html">Documentation overview</a><ul>
+ <li><a href="../index.html">Module code</a><ul>
+ </ul></li>
+ </ul></li>
+</ul>
+</div>
+<div id="searchbox" style="display: none" role="search">
+ <h3>Quick search</h3>
+ <form class="search" action="../../search.html" method="get">
+ <input type="text" name="q" />
+ <input type="submit" value="Go" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+ </form>
+</div>
+<script type="text/javascript">$('#searchbox').show(0);</script>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/_modules/umap/run_bowtie.html b/doc/build/_modules/umap/run_bowtie.html
new file mode 100644
index 0000000..fc6ebc1
--- /dev/null
+++ b/doc/build/_modules/umap/run_bowtie.html
@@ -0,0 +1,200 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>umap.run_bowtie — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="../../_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: '../../',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="../../_static/jquery.js"></script>
+ <script type="text/javascript" src="../../_static/underscore.js"></script>
+ <script type="text/javascript" src="../../_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="../../documentation.html" />
+ <link rel="up" title="Module code" href="../index.html" />
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+ <h1>Source code for umap.run_bowtie</h1><div class="highlight"><pre>
+<span class="kn">from</span> <span class="nn">argparse</span> <span class="kn">import</span> <span class="n">ArgumentParser</span>
+<span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">datetime</span>
+<span class="kn">import</span> <span class="nn">os</span>
+<span class="kn">import</span> <span class="nn">re</span>
+<span class="kn">import</span> <span class="nn">subprocess</span>
+
+
+<span class="k">def</span> <span class="nf">subset_list</span><span class="p">(</span><span class="n">list_items</span><span class="p">,</span> <span class="n">regex</span><span class="p">):</span>
+ <span class="n">out_list</span> <span class="o">=</span> <span class="p">[]</span>
+ <span class="k">for</span> <span class="n">each_item</span> <span class="ow">in</span> <span class="n">list_items</span><span class="p">:</span>
+ <span class="n">RE</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">regex</span><span class="p">,</span> <span class="n">each_item</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">RE</span><span class="p">:</span>
+ <span class="n">out_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">each_item</span><span class="p">)</span>
+ <span class="k">return</span> <span class="n">out_list</span>
+
+
+<div class="viewcode-block" id="BowtieWrapper"><a class="viewcode-back" href="../../documentation.html#umap.BowtieWrapper">[docs]</a><span class="k">class</span> <span class="nc">BowtieWrapper</span><span class="p">:</span>
+ <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">kmer_dir</span><span class="p">,</span> <span class="n">bowtie_dir</span><span class="p">,</span>
+ <span class="n">index_dir</span><span class="p">,</span> <span class="n">index_name</span><span class="p">,</span>
+ <span class="n">job_id</span><span class="p">):</span>
+ <span class="sd">"""Runs Bowtie one <chrom>.<kmer>.<jobid>.kmer.gz</span>
+
+<span class="sd"> Using the job_id, this function identifies</span>
+<span class="sd"> one kmer.gz file and runs bowtie on that and saves</span>
+<span class="sd"> the output to <chrom>.<kmer>.<jobid>.bowtie.gz.</span>
+
+<span class="sd"> :param kmer_dir: Directory with <chrom>.<kmer>.<jobid>.kmer.gz files</span>
+<span class="sd"> :param bowtie_dir: Directory with Bowtie 1.1.0 executable files.</span>
+<span class="sd"> :param index_dir: Directory with Bowtie index</span>
+<span class="sd"> :param index_name: Name used for generating Bowtie index files</span>
+<span class="sd"> :param int job_id: will be used for finding kmer.gz file</span>
+
+<span class="sd"> :returns: Saves the output to a file in the same directory as kmer_dir</span>
+<span class="sd"> """</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir</span> <span class="o">=</span> <span class="n">kmer_dir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">bowtie_dir</span> <span class="o">=</span> <span class="n">bowtie_dir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">index_dir</span> <span class="o">=</span> <span class="n">index_dir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">index_name</span> <span class="o">=</span> <span class="n">index_name</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">job_id</span> <span class="o">=</span> <span class="n">job_id</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">execute_bowtie_command</span><span class="p">()</span>
+
+ <span class="k">def</span> <span class="nf">execute_bowtie_command</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="sd">"""The only method of BowtieWrapper</span>
+
+<span class="sd"> Will be executed automatically by BowtieWrapper</span>
+
+<span class="sd"> :raises ValueError: If job_id is out of expected range</span>
+<span class="sd"> """</span>
+ <span class="n">kmer_names</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"{}/{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir</span><span class="p">,</span> <span class="n">each_kmer</span><span class="p">)</span> <span class="k">for</span> <span class="n">each_kmer</span>
+ <span class="ow">in</span> <span class="n">subset_list</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir</span><span class="p">),</span> <span class="s2">".kmer.gz$"</span><span class="p">)]</span>
+ <span class="n">kmer_names</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
+ <span class="n">LongIndex</span> <span class="o">=</span> <span class="bp">False</span>
+ <span class="n">short_ind_path</span> <span class="o">=</span> <span class="s2">"{}/{}.1.ebwtl"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">index_dir</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">index_name</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">short_ind_path</span><span class="p">):</span>
+ <span class="n">LongIndex</span> <span class="o">=</span> <span class="bp">True</span>
+ <span class="k">print</span><span class="p">(</span><span class="s2">"Switching to use of long index"</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">job_id</span> <span class="o"><=</span> <span class="nb">len</span><span class="p">(</span><span class="n">kmer_names</span><span class="p">):</span>
+ <span class="k">try</span><span class="p">:</span>
+ <span class="n">kmer_file</span> <span class="o">=</span> <span class="n">kmer_names</span><span class="p">[</span><span class="n">job_id</span><span class="p">]</span>
+ <span class="k">except</span><span class="p">:</span>
+ <span class="k">raise</span> <span class="ne">ValueError</span><span class="p">(</span>
+ <span class="s2">"{} does not exist. Time: {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">job_id</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())))</span>
+ <span class="k">print</span><span class="p">(</span><span class="s2">"processing Kmer File {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">kmer_file</span><span class="p">))</span>
+ <span class="c1"># kmer_name = kmer_dir.split("/")[-1]</span>
+ <span class="n">kmer_path</span> <span class="o">=</span> <span class="s2">"{}/{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">kmer_dir</span><span class="p">,</span> <span class="n">kmer_file</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"/"</span><span class="p">)[</span><span class="o">-</span><s [...]
+ <span class="n">bowtie_out_path</span> <span class="o">=</span> <span class="n">kmer_path</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">".kmer.gz"</span><span class="p">,</span> <span class="s2">".bowtie.gz"</span><span class="p">)</span>
+ <span class="n">first_part_of_command</span> <span class="o">=</span> <span class="s2">"gunzip -c {} | {}/bowtie "</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">kmer_path</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">bowtie_dir</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">LongIndex</span><span class="p">:</span>
+ <span class="n">first_part_of_command</span> <span class="o">=</span> <span class="n">first_part_of_command</span> <span class="o">+</span>\
+ <span class="s2">"--large-index "</span>
+ <span class="n">bowtiecmd</span> <span class="o">=</span> <span class="n">first_part_of_command</span> <span class="o">+</span>\
+ <span class="s2">"{}/{} "</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">index_dir</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">index_name</span><span class="p">)</span> <span class="o">+</span>\
+ <span class="s2">"-v 0 -k 1 -m 1 --norc --mm "</span> <span class="o">+</span>\
+ <span class="s2">"-r --refidx --suppress 5,6,7,8 - "</span> <span class="o">+</span>\
+ <span class="s2">"| gzip -c > {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">bowtie_out_path</span><span class="p">)</span>
+ <span class="n">subprocess</span><span class="o">.</span><span class="n">call</span><span class="p">(</span><span class="n">bowtiecmd</span><span class="p">,</span> <span class="n">shell</span><span class="o">=</span><span class="bp">True</span><span class="p">)</span>
+ <span class="k">print</span><span class="p">(</span><span class="s2">"Executing {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">bowtiecmd</span><span class="p">))</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="k">print</span><span class="p">(</span><span class="s2">"The length of files was {} but the index was {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="nb">len</span><span class="p">(</span><span class="n">kmer_names</span><span class="p">),</span> <span class="n">job_id</span><span class="p">))</span></div>
+
+
+<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span>
+ <span class="n">parser</span> <span class="o">=</span> <span class="n">ArgumentParser</span><span class="p">(</span>
+ <span class="n">description</span><span class="o">=</span><span class="s2">"Umap wrapper for running bowtie "</span>
+ <span class="s2">"on individual k-mer files."</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"kmer_dir"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Directory containing the .kmer files"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"bowtie_dir"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Directory containing bowtie executable"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"index_dir"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Directory containing bowtie index"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"index_name"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"prefix name of bowtie index"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-var_id"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="s2">"SGE_TASK_ID"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"HPC environmental variable for JOB ID"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-job_id"</span><span class="p">,</span>
+ <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"1-based index for selecting a k-mer file"</span><span class="p">)</span>
+ <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">job_id</span>
+ <span class="k">if</span> <span class="n">job_id</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="n">args</span><span class="o">.</span><span class="n">var_id</span><span class="p">])</span> <span class="o">-</span> <span class="mi">1</span>
+ <span class="n">BowtieWrapper</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">kmer_dir</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">bowtie_dir</span><span class="p">,</span>
+ <span class="n">args</span><span class="o">.</span><span class="n">index_dir</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">index_name</span><span class="p">,</span> <span class="n">job_id</span><span class="p">)</span>
+</pre></div>
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper"><div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="../../documentation.html">Documentation overview</a><ul>
+ <li><a href="../index.html">Module code</a><ul>
+ </ul></li>
+ </ul></li>
+</ul>
+</div>
+<div id="searchbox" style="display: none" role="search">
+ <h3>Quick search</h3>
+ <form class="search" action="../../search.html" method="get">
+ <input type="text" name="q" />
+ <input type="submit" value="Go" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+ </form>
+</div>
+<script type="text/javascript">$('#searchbox').show(0);</script>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/_modules/umap/uint8_to_bed.html b/doc/build/_modules/umap/uint8_to_bed.html
new file mode 100644
index 0000000..98b0525
--- /dev/null
+++ b/doc/build/_modules/umap/uint8_to_bed.html
@@ -0,0 +1,443 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>umap.uint8_to_bed — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="../../_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: '../../',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="../../_static/jquery.js"></script>
+ <script type="text/javascript" src="../../_static/underscore.js"></script>
+ <script type="text/javascript" src="../../_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="../../documentation.html" />
+ <link rel="up" title="Module code" href="../index.html" />
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+ <h1>Source code for umap.uint8_to_bed</h1><div class="highlight"><pre>
+<span class="kn">import</span> <span class="nn">argparse</span>
+<span class="kn">from</span> <span class="nn">datetime</span> <span class="kn">import</span> <span class="n">datetime</span>
+<span class="kn">import</span> <span class="nn">gzip</span>
+<span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
+<span class="kn">import</span> <span class="nn">os</span>
+<span class="kn">import</span> <span class="nn">re</span>
+<span class="kn">import</span> <span class="nn">warnings</span>
+
+
+<span class="k">def</span> <span class="nf">subset_list</span><span class="p">(</span><span class="n">my_list</span><span class="p">,</span> <span class="n">regex</span><span class="p">,</span> <span class="n">reg_neg</span><span class="o">=</span><span class="bp">False</span><span class="p">):</span>
+ <span class="n">out_list</span> <span class="o">=</span> <span class="p">[]</span>
+ <span class="k">for</span> <span class="n">item</span> <span class="ow">in</span> <span class="n">my_list</span><span class="p">:</span>
+ <span class="n">RE</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">regex</span><span class="p">,</span> <span class="n">item</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">RE</span> <span class="ow">and</span> <span class="ow">not</span> <span class="n">reg_neg</span><span class="p">:</span>
+ <span class="n">out_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
+ <span class="k">elif</span> <span class="ow">not</span> <span class="n">RE</span> <span class="ow">and</span> <span class="n">reg_neg</span><span class="p">:</span>
+ <span class="n">out_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">item</span><span class="p">)</span>
+ <span class="k">return</span> <span class="n">out_list</span>
+
+
+<div class="viewcode-block" id="Int8Handler"><a class="viewcode-back" href="../../documentation.html#umap.Int8Handler">[docs]</a><span class="k">class</span> <span class="nc">Int8Handler</span><span class="p">:</span>
+ <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">in_dir</span><span class="p">,</span> <span class="n">out_dir</span><span class="p">,</span> <span class="n">C2T</span><span class="p">,</span> <span class="n">G2A</span><span class="p">,</span> <span class="n">chrsize_path</span><span class="p">):</span>
+ <span class="sd">"""Infers important directory structure from in_dir</span>
+
+<span class="sd"> The Int8Handler class requires in_dir argument which</span>
+<span class="sd"> is a directory with subfolders named as k<integer></span>
+<span class="sd"> that have <chrom>.<kmer>.uint8.unique.gz files.</span>
+<span class="sd"> The Int8Handler.write_beds method creates one</span>
+<span class="sd"> browser extensible data (BED) file for each of the</span>
+<span class="sd"> k<integer> subfolders.</span>
+
+<span class="sd"> :param in_dir: Directory with <chrom>.uint8.unique.gz files</span>
+<span class="sd"> :param out_dir: Directory for saving output BED files</span>
+<span class="sd"> """</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">in_dir</span> <span class="o">=</span> <span class="n">in_dir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">C2T</span> <span class="o">=</span> <span class="n">C2T</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">G2A</span> <span class="o">=</span> <span class="n">G2A</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chrsize_path</span> <span class="o">=</span> <span class="n">chrsize_path</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">in_prev_dir</span> <span class="o">=</span> <span class="s2">"/"</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">in_dir</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"/"</span><span class="p">)[:</span><span class="o">-</span><span class="mi">1</span><span class="p">])</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">fix</span> <span class="o">=</span> <span class="s2">".uint8.unique.gz"</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">uint8s</span> <span class="o">=</span> <span class="n">subset_list</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="n">in_dir</span><span class="p">),</span> <span class="bp">self</span><span class="o">.</span><span class="n">fix</span><span class="p">)</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">prev_dir</span> <span class="o">=</span> <span class="s2">"/"</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">in_dir</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"/"</span><span class="p">)[:</span><span class="o">-</span><span class="mi">1< [...]
+ <span class="bp">self</span><span class="o">.</span><span class="n">kmers</span> <span class="o">=</span> <span class="n">subset_list</span><span class="p">(</span><span class="nb">next</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">walk</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">in_prev_dir</span><span class="p">))[</span><span class="mi">1</span><span class="p">],</span>
+ <span class="s2">"^k"</span><span class="p">)</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">out_dir</span> <span class="o">=</span> <span class="n">out_dir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">type</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">find_type</span><span class="p">()</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chrsize_dict</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">make_chrsize_dict</span><span class="p">()</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chroms</span> <span class="o">=</span> <span class="p">[</span><span class="n">each_chr</span> <span class="k">for</span> <span class="n">each_chr</span> <span class="ow">in</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chrsize_dict</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span> <span class="k">if</span>
+ <span class="s2">"RC"</span> <span class="ow">not</span> <span class="ow">in</span> <span class="n">each_chr</span><span class="p">]</span>
+
+ <span class="k">def</span> <span class="nf">find_type</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">C2T</span><span class="p">:</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">type</span> <span class="o">=</span> <span class="s2">"Bismap.Forward"</span>
+ <span class="k">elif</span> <span class="bp">self</span><span class="o">.</span><span class="n">G2A</span><span class="p">:</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">type</span> <span class="o">=</span> <span class="s2">"Bismap.Reverse"</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">type</span> <span class="o">=</span> <span class="s2">"Umap"</span>
+ <span class="k">return</span> <span class="bp">self</span><span class="o">.</span><span class="n">type</span>
+
+<div class="viewcode-block" id="Int8Handler.write_beds"><a class="viewcode-back" href="../../documentation.html#umap.Int8Handler.write_beds">[docs]</a> <span class="k">def</span> <span class="nf">write_beds</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">out_label</span><span class="p">,</span> <span class="n">kmer_cur</span><span class="p">,</span>
+ <span class="n">WriteUnique</span><span class="o">=</span><span class="bp">False</span><span class="p">):</span>
+ <span class="sd">"""Convert uint8 files to BED</span>
+
+<span class="sd"> A method of class Int8Handler, it reads uint8 files of</span>
+<span class="sd"> different chromosomes and saves them into a BED file.</span>
+<span class="sd"> This is the only method in this class that needs</span>
+<span class="sd"> to be called manually by the user.</span>
+
+<span class="sd"> Args:</span>
+<span class="sd"> out_label: Will be used in output names: <kmer>.<out_label>.bed.gz</span>
+<span class="sd"> kmer_cur: k-mer size in format of k<integer></span>
+<span class="sd"> WriteUnique: Defaults to False. Will merge and save uint files.</span>
+<span class="sd"> Use if working with -Bismap and have reverse</span>
+<span class="sd"> complemented chromosomes.</span>
+
+<span class="sd"> Returns:</span>
+<span class="sd"> Saved ths output to a gzipped BED file</span>
+
+<span class="sd"> Raises:</span>
+<span class="sd"> Warning: If no uniquely mappable read is found in</span>
+<span class="sd"> any of the uint8 arrays.</span>
+<span class="sd"> """</span>
+ <span class="n">kmer</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">kmer_cur</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">"k"</span><span class="p">,</span> <span class="s2">""</span><span class="p">))</span>
+ <span class="n">STRAND</span> <span class="o">=</span> <span class="s2">"+"</span>
+ <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">G2A</span><span class="p">:</span>
+ <span class="n">STRAND</span> <span class="o">=</span> <span class="s2">"-"</span>
+ <span class="n">in_dir</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">in_dir</span>
+ <span class="n">all_chrs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">chroms</span>
+ <span class="n">all_chrs</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
+ <span class="k">for</span> <span class="n">cur_chr</span> <span class="ow">in</span> <span class="bp">self</span><span class="o">.</span><span class="n">chroms</span><span class="p">:</span>
+ <span class="n">other_chr</span> <span class="o">=</span> <span class="n">cur_chr</span> <span class="o">+</span> <span class="s2">"_RC"</span>
+ <span class="n">uint_path</span> <span class="o">=</span> <span class="s2">"{}/{}{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">in_dir</span><span class="p">,</span> <span class="n">cur_chr</span><span class="p">,</span> <span class="bp">self</span><span class="o">.</span><span class="n">fix</span><span class="p">)</span>
+ <span class="n">uniquely_mappable</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">load_uint_ar</span><span class="p">(</span>
+ <span class="n">uint_path</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">cur_chr</span><span class="p">)</span>
+ <span class="k">if</span> <span class="bp">self</span><span class="o">.</span><span class="n">type</span> <span class="o">!=</span> <span class="s2">"Umap"</span><span class="p">:</span>
+ <span class="n">uint_path_other</span> <span class="o">=</span> <span class="n">in_dir</span> <span class="o">+</span>\
+ <span class="s2">"/"</span> <span class="o">+</span> <span class="n">uint_path</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="n">cur_chr</span><span class="p">,</span> <span class="n">other_chr</span><span class="p">)</span>
+ <span class="n">uniquely_mappable_other</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">load_uint_ar</span><span class="p">(</span>
+ <span class="n">uint_path_other</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">other_chr</span><span class="p">)</span>
+
+ <span class="c1"># Remove the last k nucleotides of the reverse chromosome</span>
+ <span class="n">uniquely_mappable_other</span> <span class="o">=</span> <span class="n">uniquely_mappable_other</span><span class="p">[:</span><span class="o">-</span><span class="n">kmer</span><span class="p">]</span>
+
+ <span class="c1"># Reverse the chromosome (Hence it's a reverse complement)</span>
+ <span class="n">uniquely_mappable_other</span> <span class="o">=</span> <span class="n">uniquely_mappable_other</span><span class="p">[::</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span>
+
+ <span class="c1"># Remove the last k nucleotides of the forward chromosome</span>
+ <span class="n">uniquely_mappable</span> <span class="o">=</span> <span class="n">uniquely_mappable</span><span class="p">[:</span><span class="o">-</span><span class="n">kmer</span><span class="p">]</span>
+
+ <span class="c1"># Merge to find uniquely mappable reads in both strands</span>
+ <span class="n">uniquely_mappable</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span>
+ <span class="n">np</span><span class="o">.</span><span class="n">logical_and</span><span class="p">(</span>
+ <span class="n">uniquely_mappable_other</span><span class="p">,</span> <span class="n">uniquely_mappable</span><span class="p">),</span>
+ <span class="n">dtype</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">WriteUnique</span><span class="p">:</span>
+ <span class="n">unique_ar</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">uniquely_mappable</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>
+ <span class="n">out_dir_uint</span> <span class="o">=</span> <span class="s2">"{}/k{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">out_dir</span><span class="p">,</span> <span class="n">kmer</span><span class="p">)</span>
+ <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">out_dir_uint</span><span class="p">):</span>
+ <span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">out_dir_uint</span><span class="p">)</span>
+ <span class="n">out_path_uint</span> <span class="o">=</span> <span class="s2">"{}/{}.k{}.uint8.unique.gz"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="p">(</span><span class="n">out_dir_uint</span><span class="p">,</span> <span class="n">cur_chr</span><span class="p">,</span> <span class="n">kmer</span><span class="p">))</span>
+ <span class="n">out_link_uint</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">out_path_uint</span><span class="p">,</span> <span class="s2">"wb"</span><span class="p">)</span>
+ <span class="n">out_link_uint</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">unique_ar</span><span class="o">.</span><span class="n">tobytes</span><span class="p">())</span>
+ <span class="n">out_link_uint</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
+
+ <span class="n">bed_kmer_pos</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_bed6</span><span class="p">(</span>
+ <span class="n">uniquely_mappable</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">STRAND</span><span class="p">,</span> <span class="n">uint_path</span><span class="p">,</span> <span class="n">cur_chr</span><span class="p">)</span>
+
+ <span class="c1"># Write the BED6 to a gzipped tsv file</span>
+ <span class="n">out_name</span> <span class="o">=</span> <span class="s2">"{}/{}.{}.bed.gz"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">out_dir</span><span class="p">,</span> <span class="n">kmer_cur</span><span class="p">,</span> <span class="n">out_label</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">cur_chr</span> <span class="o">==</span> <span class="n">all_chrs</span><span class="p">[</span><span class="mi">0</span><span class="p">]:</span>
+ <span class="n">header</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">make_header</span><span class="p">(</span><span class="n">kmer_cur</span><span class="p">,</span> <span class="nb">type</span><span class="p">)</span>
+ <span class="n">out_link</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">out_name</span><span class="p">,</span> <span class="s2">"wb"</span><span class="p">)</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">header</span><span class="p">)</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="n">out_link</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">out_name</span><span class="p">,</span> <span class="s2">"ab"</span><span class="p">)</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">bed_kmer_pos</span><span class="p">)</span> <span class="o">></span> <span class="mi">0</span><span class="p">:</span>
+ <span class="k">print</span> <span class="s2">"Found </span><span class="si">%d</span><span class="s2"> regions in </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span>\
+ <span class="p">(</span><span class="n">bed_kmer_pos</span><span class="o">.</span><span class="n">shape</span><span class="p">[</span><span class="mi">0</span><span class="p">],</span> <span class="n">cur_chr</span><span class="p">)</span>
+ <span class="k">for</span> <span class="n">bed_line</span> <span class="ow">in</span> <span class="n">bed_kmer_pos</span><span class="p">:</span>
+ <span class="n">line_out</span> <span class="o">=</span> <span class="p">[</span><span class="nb">str</span><span class="p">(</span><span class="n">val</span><span class="p">)</span> <span class="k">for</span> <span class="n">val</span> <span class="ow">in</span> <span class="n">bed_line</span><span class="p">]</span>
+ <span class="n">line_out</span> <span class="o">=</span> <span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="o">.</span><span class="n">join</span><span class="p">(</span><span class="n">line_out</span><span class="p">)</span> <span class="o">+</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">"</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">line_out</span><span class="p">)</span>
+ <span class="k">print</span> <span class="s2">"Created data of </span><span class="si">%s</span><span class="s2"> at </span><span class="si">%s</span><span class="s2">"</span> <span class="o">%</span>\
+ <span class="p">(</span><span class="n">cur_chr</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">()))</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></div>
+
+ <span class="k">def</span> <span class="nf">get_bed6</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">uniquely_mappable</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span>
+ <span class="n">STRAND</span><span class="p">,</span> <span class="n">uint_path</span><span class="p">,</span> <span class="n">cur_chr</span><span class="p">):</span>
+ <span class="sd">"""Make BED6 from a binary vector</span>
+
+<span class="sd"> Converts a binary vector with the same length</span>
+<span class="sd"> as the chromosome to a BED6 file. Each 1</span>
+<span class="sd"> entry in the binary file indicates that the</span>
+<span class="sd"> k-mer starting at that position and ending at</span>
+<span class="sd"> k nucleotides downstream is uniquely mappable.</span>
+<span class="sd"> Thus the BED6 would show any region in the genome</span>
+<span class="sd"> that is uniquely mappable by at least one k-mer.</span>
+
+<span class="sd"> :param uniquely_mappable: numpy binary array (0 or 1 values)</span>
+<span class="sd"> :param kmer: Integer scalar showing read length (k-mer)</span>
+<span class="sd"> :param STRAND: Strand that will be saved to the BED6</span>
+<span class="sd"> :param uint_path: Path of the uint8 array that was used</span>
+<span class="sd"> :param cur_chr: Chromosome name the the data is from</span>
+
+<span class="sd"> :returns: A numpy string array with BED6 information</span>
+<span class="sd"> """</span>
+ <span class="n">unimap_diff</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">diff</span><span class="p">(</span><span class="n">uniquely_mappable</span><span class="p">)</span>
+ <span class="n">poses_start</span><span class="p">,</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">unimap_diff</span> <span class="o">==</span> <span class="mi">1</span><span class="p">)</span>
+ <span class="n">poses_end</span><span class="p">,</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">unimap_diff</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">poses_start</span><span class="p">)</span> <span class="o">!=</span> <span class="nb">len</span><span class="p">(</span><span class="n">poses_end</span><span class="p">):</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">poses_start</span><span class="p">)</span> <span class="o">></span> <span class="nb">len</span><span class="p">(</span><span class="n">poses_end</span><span class="p">):</span>
+ <span class="n">poses_end</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">poses_end</span><span class="p">,</span> <span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">uniquely_mappable</span><span class="p">)])</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="n">poses_start</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">([</span><span class="mi">0</span><span class="p">],</span> <span class="n">poses_start</span><span class="p">)</span>
+ <span class="k">elif</span> <span class="n">uniquely_mappable</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
+ <span class="n">poses_start</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">([</span><span class="mi">0</span><span class="p">],</span> <span class="n">poses_start</span><span class="p">)</span>
+ <span class="n">poses_end</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">poses_end</span><span class="p">,</span> <span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">uniquely_mappable</span><span class="p">)])</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">poses_start</span><span class="p">)</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
+ <span class="n">warnings</span><span class="o">.</span><span class="n">warn</span><span class="p">(</span>
+ <span class="s2">"Found no uniquely mappable reads for {}!"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">uint_path</span><span class="p">))</span>
+ <span class="n">bed_kmer_pos</span> <span class="o">=</span> <span class="p">[]</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="n">chr_length</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">chrsize_dict</span><span class="p">[</span><span class="n">cur_chr</span><span class="p">]</span>
+ <span class="n">bed_kmer_pos</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">empty</span><span class="p">(</span><span class="n">shape</span><span class="o">=</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">poses_start</span><span class="p">),</span> <span class="mi">6</span><span class="p">),</span>
+ <span class="n">dtype</span><span class="o">=</span><span class="s2">"S16"</span><span class="p">)</span>
+ <span class="k">for</span> <span class="n">ind_st</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">poses_start</span><span class="p">)):</span>
+ <span class="n">ad_ar</span> <span class="o">=</span> <span class="p">[</span><span class="n">cur_chr</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">poses_start</span><span class="p">[</span><span class="n">ind_st</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span><span class="p">),</span>
+ <span class="nb">str</span><span class="p">(</span><span class="n">poses_end</span><span class="p">[</span><span class="n">ind_st</span><span class="p">]</span> <span class="o">+</span> <span class="n">kmer</span> <span class="o">-</span> <span class="mi">1</span><span class="p">),</span>
+ <span class="s2">"k"</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">kmer</span><span class="p">),</span> <span class="mi">1</span><span class="p">,</span> <span class="n">STRAND</span><span class="p">]</span>
+ <span class="k">if</span> <span class="n">poses_end</span><span class="p">[</span><span class="n">ind_st</span><span class="p">]</span> <span class="o">+</span> <span class="n">kmer</span> <span class="o">-</span> <span class="mi">1</span> <span class="o">></span> <span class="n">chr_length</span><span class="p">:</span>
+ <span class="n">ad_ar</span><span class="p">[</span><span class="mi">2</span><span class="p">]</span> <span class="o">=</span> <span class="n">chr_length</span>
+ <span class="n">bed_kmer_pos</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span>
+ <span class="p">[[</span><span class="n">cur_chr</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">poses_start</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span><span class="p">),</span>
+ <span class="nb">str</span><span class="p">(</span><span class="n">poses_end</span><span class="p">[</span><span class="n">i</span><span class="p">]</span> <span class="o">+</span> <span class="n">kmer</span> <span class="o">-</span> <span class="mi">1</span><span class="p">),</span>
+ <span class="s2">"k"</span> <span class="o">+</span> <span class="nb">str</span><span class="p">(</span><span class="n">kmer</span><span class="p">),</span>
+ <span class="mi">1</span><span class="p">,</span> <span class="n">STRAND</span><span class="p">]</span> <span class="k">for</span> <span class="n">i</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">poses_start</span><span class="p">))],</span>
+ <span class="n">dtype</span><span class="o">=</span><span class="s2">"S64"</span><span class="p">)</span>
+ <span class="k">return</span> <span class="n">bed_kmer_pos</span>
+
+ <span class="k">def</span> <span class="nf">load_uint_ar</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">uint_path</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">cur_chr</span><span class="p">):</span>
+ <span class="sd">"""Loads a gzipped unsigned 8-bit integer as a numpy array</span>
+<span class="sd"> """</span>
+ <span class="n">uint_link</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">uint_path</span><span class="p">,</span> <span class="s2">"rb"</span><span class="p">)</span>
+ <span class="n">uint_ar</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">frombuffer</span><span class="p">(</span><span class="n">uint_link</span><span class="o">.</span><span class="n">read</span><span class="p">(),</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>
+ <span class="n">uint_link</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
+ <span class="k">print</span> <span class="s2">"Processing {} for {} {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">uint_path</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">cur_chr</span><span class="p">)</span>
+ <span class="n">less_than_kmer</span> <span class="o">=</span> <span class="n">uint_ar</span> <span class="o"><=</span> <span class="n">kmer</span>
+ <span class="n">not_zero</span> <span class="o">=</span> <span class="n">uint_ar</span> <span class="o">!=</span> <span class="mi">0</span>
+ <span class="n">uniquely_mappable</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span>
+ <span class="n">np</span><span class="o">.</span><span class="n">logical_and</span><span class="p">(</span><span class="n">less_than_kmer</span><span class="p">,</span> <span class="n">not_zero</span><span class="p">),</span> <span class="n">dtype</span><span class="o">=</span><span class="nb">int</span><span class="p">)</span>
+ <span class="k">return</span> <span class="n">uniquely_mappable</span>
+
+ <span class="k">def</span> <span class="nf">make_header</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="nb">type</span><span class="p">):</span>
+ <span class="sd">"""Created BED6 header</span>
+
+<span class="sd"> :param str kmer: k<integer></span>
+<span class="sd"> :param type: One of Bismap.Forward, Bismap.Reverse or Umap</span>
+<span class="sd"> """</span>
+ <span class="n">dict_col</span> <span class="o">=</span> <span class="p">{</span><span class="s2">"Bisulfite.Converted"</span><span class="p">:</span> <span class="s2">"240,40,80"</span><span class="p">,</span>
+ <span class="s2">"Umap"</span><span class="p">:</span> <span class="s2">"80,40,240"</span><span class="p">,</span>
+ <span class="s2">"Bismap.Forward"</span><span class="p">:</span> <span class="s2">"220,20,80"</span><span class="p">,</span>
+ <span class="s2">"Bismap.Reverse"</span><span class="p">:</span> <span class="s2">"80,20,220"</span><span class="p">}</span>
+ <span class="n">header</span> <span class="o">=</span> <span class="s1">'track name="{} {}"'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="nb">type</span><span class="p">,</span> <span class="n">kmer</span><span class="p">)</span> <span class="o">+</span>\
+ <span class="s1">'description="Single-read mappability with {}-mers'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">kmer</span><span class="p">)</span> <span class="o">+</span>\
+ <span class="s1">'color=</span><span class="si">%s</span><span class="s1"> </span><span class="se">\n</span><span class="s1">'</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">dict_col</span><span class="o">.</span><span class="n">get</span><span class="p">(</span><span class="nb">type</span><span class="p">,</span> <span class="s2">"40,40,240"</span><span class="p">))</span>
+ <span class="k">return</span> <span class="n">header</span>
+
+ <span class="k">def</span> <span class="nf">make_chrsize_dict</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="sd">"""Creates dictionary from 2-column chromosome size file</span>
+<span class="sd"> """</span>
+ <span class="n">chrsize_dict</span> <span class="o">=</span> <span class="p">{}</span>
+ <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chrsize_path</span><span class="p">,</span> <span class="s2">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">chrsize_link</span><span class="p">:</span>
+ <span class="k">for</span> <span class="n">each_line</span> <span class="ow">in</span> <span class="n">chrsize_link</span><span class="p">:</span>
+ <span class="nb">chr</span> <span class="o">=</span> <span class="n">each_line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="p">)[</span><span class="mi"> [...]
+ <span class="n">length</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">each_line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">(</span><span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">&q [...]
+ <span class="n">chrsize_dict</span><span class="p">[</span><span class="nb">chr</span><span class="p">]</span> <span class="o">=</span> <span class="n">length</span>
+ <span class="k">return</span> <span class="n">chrsize_dict</span>
+
+ <span class="k">def</span> <span class="nf">bin_arr_to_wig</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">uniquely_mappable</span><span class="p">,</span> <span class="n">kmer</span><span class="p">):</span>
+ <span class="sd">"""Converts a uniquely a binary array to mult-read mappability</span>
+
+<span class="sd"> Unique mappability array is a binary array where each</span>
+<span class="sd"> value of 1 indicates that the k-mer starting at that</span>
+<span class="sd"> position is uniquely mappable. This function generates</span>
+<span class="sd"> an array of the same length and saves the multi-read mappability</span>
+<span class="sd"> of each position in that array. Multi-read mappability is the</span>
+<span class="sd"> probability of finding a uniquely mappable k-mer among all of</span>
+<span class="sd"> the k-mers that overlap with a given position.</span>
+
+<span class="sd"> :param uniquely_mappable: A binary numpy array</span>
+<span class="sd"> :param kmer: An integer defining read length</span>
+
+<span class="sd"> :returns: Multi-read mappability array.</span>
+<span class="sd"> """</span>
+ <span class="n">LEN_AR</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span><span class="n">uniquely_mappable</span><span class="p">)</span>
+ <span class="n">poses_start</span><span class="p">,</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">uniquely_mappable</span> <span class="o">==</span> <span class="mi">1</span><span class="p">)</span>
+ <span class="n">ar_quant</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">uniquely_mappable</span><span class="p">),</span> <span class="n">dtype</span><span class="o">=</span><span class="nb">float</span><span class="p">)</span>
+ <span class="k">for</span> <span class="n">ind_st</span> <span class="ow">in</span> <span class="n">poses_start</span><span class="p">:</span>
+ <span class="n">ind_end</span> <span class="o">=</span> <span class="n">ind_st</span> <span class="o">+</span> <span class="n">kmer</span>
+ <span class="k">if</span> <span class="n">ind_end</span> <span class="o">></span> <span class="n">LEN_AR</span><span class="p">:</span>
+ <span class="n">ind_end</span> <span class="o">=</span> <span class="n">LEN_AR</span>
+ <span class="n">ar_quant</span><span class="p">[</span><span class="n">ind_st</span><span class="p">:</span><span class="n">ind_end</span><span class="p">]</span> <span class="o">=</span> <span class="n">ar_quant</span><span class="p">[</span><span class="n">ind_st</span><span class="p">:</span><span class="n">ind_end</span><span class="p">]</span> <span class="o">+</span> <span class="mf">1.0</span>
+ <span class="k">print</span><span class="p">(</span><span class="s2">"Finished generating multi-read mappability date at {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="nb">str</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())))</span>
+ <span class="k">del</span> <span class="n">poses_start</span>
+ <span class="n">ar_quant</span> <span class="o">=</span> <span class="n">ar_quant</span> <span class="o">/</span> <span class="nb">float</span><span class="p">(</span><span class="n">kmer</span><span class="p">)</span>
+ <span class="k">return</span> <span class="n">ar_quant</span>
+
+<div class="viewcode-block" id="Int8Handler.write_as_wig"><a class="viewcode-back" href="../../documentation.html#umap.Int8Handler.write_as_wig">[docs]</a> <span class="k">def</span> <span class="nf">write_as_wig</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">uint_path</span><span class="p">,</span> <span class="n">out_path</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">chrom</span> [...]
+ <span class="sd">"""unsigned 8-bit integer array file to wiggle</span>
+
+<span class="sd"> For a given numeric unsigned 8-bit integer vector that</span>
+<span class="sd"> is generated by Umap, this method save the wiggle file</span>
+<span class="sd"> which is specific for one chromosome over one read length.</span>
+
+<span class="sd"> :param uint_path: Path to a gzipped numeric unsigned 8-bit array</span>
+<span class="sd"> :param out_path: Gzipped path for saving wiggle</span>
+<span class="sd"> :param kmer: Integer defining read length</span>
+<span class="sd"> :param chrom: Chromosome that the uint_path is specific to</span>
+<span class="sd"> """</span>
+ <span class="n">uniquely_mappable</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">load_uint_ar</span><span class="p">(</span><span class="n">uint_path</span><span class="p">,</span> <span class="n">kmer</span><span class="p">,</span> <span class="n">chrom</span><span class="p">)</span>
+ <span class="n">ar_quant</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">bin_arr_to_wig</span><span class="p">(</span><span class="n">uniquely_mappable</span><span class="p">,</span> <span class="n">kmer</span><span class="p">)</span>
+ <span class="n">out_link</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">out_path</span><span class="p">,</span> <span class="s2">"wb"</span><span class="p">)</span>
+ <span class="n">unimap_diff</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">diff</span><span class="p">(</span><span class="n">np</span><span class="o">.</span><span class="n">array</span><span class="p">(</span><span class="n">ar_quant</span> <span class="o">></span> <span class="mi">0</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="nb">int</span><span class="p">))</span>
+ <span class="n">poses_start</span><span class="p">,</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">unimap_diff</span> <span class="o">==</span> <span class="mi">1</span><span class="p">)</span>
+ <span class="n">poses_end</span><span class="p">,</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">where</span><span class="p">(</span><span class="n">unimap_diff</span> <span class="o">==</span> <span class="o">-</span><span class="mi">1</span><span class="p">)</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">poses_start</span><span class="p">)</span> <span class="o">!=</span> <span class="nb">len</span><span class="p">(</span><span class="n">poses_end</span><span class="p">):</span>
+ <span class="k">if</span> <span class="nb">len</span><span class="p">(</span><span class="n">poses_start</span><span class="p">)</span> <span class="o">></span> <span class="nb">len</span><span class="p">(</span><span class="n">poses_end</span><span class="p">):</span>
+ <span class="n">poses_end</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">poses_end</span><span class="p">,</span> <span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">uniquely_mappable</span><span class="p">)])</span>
+ <span class="k">else</span><span class="p">:</span>
+ <span class="n">poses_start</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">([</span><span class="mi">0</span><span class="p">],</span> <span class="n">poses_start</span><span class="p">)</span>
+ <span class="k">elif</span> <span class="n">uniquely_mappable</span><span class="p">[</span><span class="mi">0</span><span class="p">]</span> <span class="o">==</span> <span class="mi">1</span><span class="p">:</span>
+ <span class="n">poses_start</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">([</span><span class="mi">0</span><span class="p">],</span> <span class="n">poses_start</span><span class="p">)</span>
+ <span class="n">poses_end</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">poses_end</span><span class="p">,</span> <span class="p">[</span><span class="nb">len</span><span class="p">(</span><span class="n">uniquely_mappable</span><span class="p">)])</span>
+ <span class="k">for</span> <span class="n">ind_st</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="nb">len</span><span class="p">(</span><span class="n">poses_start</span><span class="p">)):</span>
+ <span class="n">pos_st</span> <span class="o">=</span> <span class="n">poses_start</span><span class="p">[</span><span class="n">ind_st</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>
+ <span class="n">pos_end</span> <span class="o">=</span> <span class="n">poses_end</span><span class="p">[</span><span class="n">ind_st</span><span class="p">]</span> <span class="o">+</span> <span class="mi">1</span>
+ <span class="n">start_line</span> <span class="o">=</span> <span class="s2">"fixedStep chrom={} start={} step=1 span=1</span><span class="se">\n</span><span class="s2">"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">chrom</span><span class="p">,</span> <span class="n">pos_st</span><span class="p">)</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">start_line</span><span class="p">)</span>
+ <span class="k">for</span> <span class="n">each_pos</span> <span class="ow">in</span> <span class="nb">range</span><span class="p">(</span><span class="n">pos_st</span><span class="p">,</span> <span class="n">pos_end</span><span class="p">):</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="nb">str</span><span class="p">(</span><span class="n">ar_quant</span><span class="p">[</span><span class="n">each_pos</span><span class="p">])</span> <span class="o">+</span> <span class="s2">"</span><span class="se">\n</span><span class="s2">"</span><span class="p">)</span>
+ <span class="k">print</span><span class="p">(</span>
+ <span class="s2">"Finished saving the data to {} at {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">out_path</span><span class="p">,</span> <span class="nb">str</span><span class="p">(</span><span class="n">datetime</span><span class="o">.</span><span class="n">now</span><span class="p">())))</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">close</span><span class="p">()</span></div></div>
+
+
+<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span>
+ <span class="n">parser</span> <span class="o">=</span> <span class="n">argparse</span><span class="o">.</span><span class="n">ArgumentParser</span><span class="p">(</span><span class="n">description</span><span class="o">=</span><span class="s2">"Converts</span><span class="se">\</span>
+<span class="s2"> unionized uint8 outputs of umap/ubismap to bed files"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">"in_dir"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"folder with <chrom>.uint8.unique.gz files"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">"out_dir"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Folder for writing the output files"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">"out_label"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"File names would be kmer.<out_label>.bed.gz"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">"-C2T"</span><span class="p">,</span>
+ <span class="n">action</span><span class="o">=</span><span class="s2">"store_true"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"If using converted genomes specify</span><span class="se">\</span>
+<span class="s2"> -C2T or -G2A"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">"-G2A"</span><span class="p">,</span>
+ <span class="n">action</span><span class="o">=</span><span class="s2">"store_true"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"If using converted genomes specify</span><span class="se">\</span>
+<span class="s2"> -C2T or -G2A"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">"-chrsize_path"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="s2">"../../chrsize.tsv"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Path to a 2 column file of chromosome and length.</span><span class="se">\</span>
+<span class="s2"> By default it goes to ../../chrsize.tsv from</span><span class="se">\</span>
+<span class="s2"> out_dir"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span><span class="s2">"-WriteUnique"</span><span class="p">,</span>
+ <span class="n">action</span><span class="o">=</span><span class="s2">"store_true"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"If -Bismap is true and want to store the merged</span><span class="se">\</span>
+<span class="s2"> uint file, specify this option"</span><span class="p">)</span>
+ <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
+ <span class="k">if</span> <span class="ow">not</span> <span class="n">os</span><span class="o">.</span><span class="n">path</span><span class="o">.</span><span class="n">exists</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">out_dir</span><span class="p">):</span>
+ <span class="n">os</span><span class="o">.</span><span class="n">makedirs</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">out_dir</span><span class="p">)</span>
+ <span class="n">FileHandler</span> <span class="o">=</span> <span class="n">Int8Handler</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">in_dir</span><span class="p">,</span>
+ <span class="n">args</span><span class="o">.</span><span class="n">out_dir</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">C2T</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">G2A</span><span class="p">,</span>
+ <span class="n">args</span><span class="o">.</span><span class="n">chrsize_path</span><span class="p">)</span>
+ <span class="n">kmers</span> <span class="o">=</span> <span class="n">FileHandler</span><span class="o">.</span><span class="n">kmers</span>
+ <span class="c1"># for kmer in kmers:</span>
+ <span class="k">for</span> <span class="n">kmer</span> <span class="ow">in</span> <span class="n">kmers</span><span class="p">:</span>
+ <span class="n">FileHandler</span><span class="o">.</span><span class="n">write_beds</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">out_label</span><span class="p">,</span>
+ <span class="n">kmer</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">WriteUnique</span><span class="p">)</span>
+ <span class="k">for</span> <span class="n">chrom</span> <span class="ow">in</span> <span class="n">FileHandler</span><span class="o">.</span><span class="n">chroms</span><span class="p">:</span>
+ <span class="n">out_path</span> <span class="o">=</span> <span class="s2">"{}/{}.{}.{}.MultiReadMappability.wg.gz"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">args</span><span class="o">.</span><span class="n">out_dir</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">out_label</span><span class="p">,</span> <span class="n">chrom</span><span class="p">,</span> <span class="n">kmer</span><span class="p">)</span>
+ <span class="n">uint_path</span> <span class="o">=</span> <span class="s2">"{}/{}.uint8.unique.gz"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="n">args</span><span class="o">.</span><span class="n">in_dir</span><span class="p">,</span> <span class="n">chrom</span><span class="p">)</span>
+ <span class="n">kmer_num</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">kmer</span><span class="o">.</span><span class="n">replace</span><span class="p">(</span><span class="s2">"k"</span><span class="p">,</span> <span class="s2">""</span><span class="p">))</span>
+ <span class="n">FileHandler</span><span class="o">.</span><span class="n">write_as_wig</span><span class="p">(</span><span class="n">uint_path</span><span class="p">,</span> <span class="n">out_path</span><span class="p">,</span> <span class="n">kmer_num</span><span class="p">,</span> <span class="n">chrom</span><span class="p">)</span>
+</pre></div>
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper"><div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="../../documentation.html">Documentation overview</a><ul>
+ <li><a href="../index.html">Module code</a><ul>
+ </ul></li>
+ </ul></li>
+</ul>
+</div>
+<div id="searchbox" style="display: none" role="search">
+ <h3>Quick search</h3>
+ <form class="search" action="../../search.html" method="get">
+ <input type="text" name="q" />
+ <input type="submit" value="Go" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+ </form>
+</div>
+<script type="text/javascript">$('#searchbox').show(0);</script>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/_modules/umap/unify_bowtie.html b/doc/build/_modules/umap/unify_bowtie.html
new file mode 100644
index 0000000..3d8c564
--- /dev/null
+++ b/doc/build/_modules/umap/unify_bowtie.html
@@ -0,0 +1,235 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>umap.unify_bowtie — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="../../_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="../../_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: '../../',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="../../_static/jquery.js"></script>
+ <script type="text/javascript" src="../../_static/underscore.js"></script>
+ <script type="text/javascript" src="../../_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="../../documentation.html" />
+ <link rel="up" title="Module code" href="../index.html" />
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+ <h1>Source code for umap.unify_bowtie</h1><div class="highlight"><pre>
+<span class="kn">from</span> <span class="nn">argparse</span> <span class="kn">import</span> <span class="n">ArgumentParser</span>
+<span class="kn">import</span> <span class="nn">gzip</span>
+<span class="kn">import</span> <span class="nn">numpy</span> <span class="kn">as</span> <span class="nn">np</span>
+<span class="kn">import</span> <span class="nn">os</span>
+<span class="kn">import</span> <span class="nn">pandas</span> <span class="kn">as</span> <span class="nn">pd</span>
+<span class="kn">import</span> <span class="nn">re</span>
+
+
+<span class="k">def</span> <span class="nf">subset_list</span><span class="p">(</span><span class="n">list_items</span><span class="p">,</span> <span class="n">regex</span><span class="p">):</span>
+ <span class="n">out_list</span> <span class="o">=</span> <span class="p">[]</span>
+ <span class="k">for</span> <span class="n">each_item</span> <span class="ow">in</span> <span class="n">list_items</span><span class="p">:</span>
+ <span class="n">RE</span> <span class="o">=</span> <span class="n">re</span><span class="o">.</span><span class="n">search</span><span class="p">(</span><span class="n">regex</span><span class="p">,</span> <span class="n">each_item</span><span class="p">)</span>
+ <span class="k">if</span> <span class="n">RE</span><span class="p">:</span>
+ <span class="n">out_list</span><span class="o">.</span><span class="n">append</span><span class="p">(</span><span class="n">each_item</span><span class="p">)</span>
+ <span class="k">return</span> <span class="n">out_list</span>
+
+
+<div class="viewcode-block" id="UnifyBowtie"><a class="viewcode-back" href="../../documentation.html#umap.UnifyBowtie">[docs]</a><span class="k">class</span> <span class="nc">UnifyBowtie</span><span class="p">:</span>
+ <span class="k">def</span> <span class="nf">__init__</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bowtie_outdir</span><span class="p">,</span> <span class="n">chrsize_path</span><span class="p">,</span> <span class="n">job_id</span><span class="p">):</span>
+ <span class="sd">"""Merges bowtie.gz outputs of run_bowtie</span>
+
+<span class="sd"> Based on outputs of run_bowtie that are saved in format</span>
+<span class="sd"> of <chr>.<kmer>.<job_id>.bowtie.gz, this class uses</span>
+<span class="sd"> a variable ID to select a particular chromosome and</span>
+<span class="sd"> merge the data in all of the different bowtie.gz files</span>
+<span class="sd"> of that chromosome.</span>
+
+<span class="sd"> :param bowtie_outdir: Directory with <chr>.<kmer>.<job_id>.bowtie.gz</span>
+<span class="sd"> :param chrsize_path: Path to 2-column file: <chr>\t<size>\n...</span>
+<span class="sd"> :param int job_id: A 0-based index to select chromosome</span>
+<span class="sd"> based on chrsize_path</span>
+
+<span class="sd"> :returns: Saves the output to bowtie_outdir/</span>
+<span class="sd"> <chr>.<kmer>.uint8.unique.gz file</span>
+<span class="sd"> """</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">bowtie_outdir</span> <span class="o">=</span> <span class="n">bowtie_outdir</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chrsize_path</span> <span class="o">=</span> <span class="n">chrsize_path</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">ind_chr</span> <span class="o">=</span> <span class="n">job_id</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">chr_dict</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">make_chr_dict</span><span class="p">()</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">bowtie_to_unique</span><span class="p">()</span>
+
+ <span class="k">def</span> <span class="nf">make_chr_dict</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="sd">"""Makes a dictionary using self.chrsize_path"""</span>
+ <span class="n">chr_dict</span> <span class="o">=</span> <span class="p">{}</span>
+ <span class="k">with</span> <span class="nb">open</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">chrsize_path</span><span class="p">,</span> <span class="s2">"r"</span><span class="p">)</span> <span class="k">as</span> <span class="n">chrsize_link</span><span class="p">:</span>
+ <span class="k">for</span> <span class="n">chrsize_line</span> <span class="ow">in</span> <span class="n">chrsize_link</span><span class="p">:</span>
+ <span class="n">chrom</span><span class="p">,</span> <span class="n">size</span> <span class="o">=</span> <span class="n">chrsize_line</span><span class="o">.</span><span class="n">rstrip</span><span class="p">()</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="p">)</span>
+ <span class="n">chr_dict</span><span class="p">[</span><span class="n">chrom</span><span class="p">]</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">size</span><span class="p">)</span>
+ <span class="k">return</span> <span class="n">chr_dict</span>
+
+ <span class="k">def</span> <span class="nf">get_mapped_positions</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">bowtie_path</span><span class="p">):</span>
+ <span class="sd">"""Finds mapped regions in bowtie output</span>
+
+<span class="sd"> In a gzipped bowtie output with perfect matches,</span>
+<span class="sd"> filters the results to those in the forward strand</span>
+<span class="sd"> and saves them to an array.</span>
+
+<span class="sd"> Why results filtered for forward strand?</span>
+<span class="sd"> The results uniquely mapped</span>
+<span class="sd"> to the reverse strand are rare and a mistake of the</span>
+<span class="sd"> aligning algorithm because all of the k-mers are</span>
+<span class="sd"> generated from the forward strand. If match happens</span>
+<span class="sd"> on reverse strand, it means that the match is not the</span>
+<span class="sd"> only unique match (reads were generated from forward</span>
+<span class="sd"> strand).</span>
+<span class="sd"> """</span>
+ <span class="n">bowtie_df</span> <span class="o">=</span> <span class="n">pd</span><span class="o">.</span><span class="n">read_csv</span><span class="p">(</span>
+ <span class="n">bowtie_path</span><span class="p">,</span> <span class="n">sep</span><span class="o">=</span><span class="s2">"</span><span class="se">\t</span><span class="s2">"</span><span class="p">,</span>
+ <span class="n">compression</span><span class="o">=</span><span class="s2">"gzip"</span><span class="p">,</span>
+ <span class="n">names</span><span class="o">=</span><span class="p">[</span><span class="s2">"Ind"</span><span class="p">,</span> <span class="s2">"Strand"</span><span class="p">,</span> <span class="s2">"Chr"</span><span class="p">,</span> <span class="s2">"Start"</span><span class="p">])</span>
+ <span class="n">bowtie_df</span> <span class="o">=</span> <span class="n">bowtie_df</span><span class="p">[</span><span class="n">bowtie_df</span><span class="p">[</span><span class="s2">"Strand"</span><span class="p">]</span> <span class="o">==</span> <span class="s2">"+"</span><span class="p">]</span>
+ <span class="n">ind_ar</span> <span class="o">=</span> <span class="n">bowtie_df</span><span class="o">.</span><span class="n">iloc</span><span class="p">[:,</span> <span class="mi">3</span><span class="p">]</span>
+ <span class="k">return</span> <span class="n">ind_ar</span>
+
+ <span class="k">def</span> <span class="nf">get_other_chr_name</span><span class="p">(</span><span class="bp">self</span><span class="p">,</span> <span class="n">chr_name</span><span class="p">):</span>
+ <span class="sd">"""Finds name of the reverse complement chromosome</span>
+
+<span class="sd"> In Bismap, we generate a set of reverse complemented</span>
+<span class="sd"> chromosomes to account for bisulfite conversion before</span>
+<span class="sd"> reverse complementation. This function finds those</span>
+<span class="sd"> chromosomes"""</span>
+ <span class="n">new_name</span> <span class="o">=</span> <span class="n">chr_name</span>
+ <span class="k">if</span> <span class="s2">"RC"</span> <span class="ow">in</span> <span class="n">chr_name</span><span class="p">:</span>
+ <span class="n">len_paths</span> <span class="o">=</span> <span class="nb">len</span><span class="p">(</span>
+ <span class="n">subset_list</span><span class="p">(</span>
+ <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">bowtie_outdir</span><span class="p">),</span> <span class="n">chr_name</span><span class="p">))</span>
+ <span class="k">if</span> <span class="n">len_paths</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
+ <span class="n">new_name</span> <span class="o">=</span> <span class="n">chr_name</span> <span class="o">+</span> <span class="s2">"_RC"</span>
+ <span class="k">return</span> <span class="n">new_name</span>
+
+ <span class="k">def</span> <span class="nf">bowtie_to_unique</span><span class="p">(</span><span class="bp">self</span><span class="p">):</span>
+ <span class="sd">"""Wrapper method of UnifyBowtie</span>
+
+<span class="sd"> Uses information of bowtie.gz files to find mappability</span>
+<span class="sd"> of a given chromosome. Is automatically called by</span>
+<span class="sd"> UnifyBowtie."""</span>
+ <span class="n">KMER</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">bowtie_outdir</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span class="s2">"/"</span><span class="p">)[</span><span class="o">-</span><span class="mi">1</span><span class="p">]</span><span class="o">.</span><span class="n">split</span><span class="p">(</span><span [...]
+ <span class="n">all_chrs</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">chr_dict</span><span class="o">.</span><span class="n">keys</span><span class="p">()</span>
+ <span class="n">all_chrs</span><span class="o">.</span><span class="n">sort</span><span class="p">()</span>
+ <span class="n">chrom</span> <span class="o">=</span> <span class="n">all_chrs</span><span class="p">[</span><span class="bp">self</span><span class="o">.</span><span class="n">ind_chr</span><span class="p">]</span>
+ <span class="n">size</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">chr_dict</span><span class="p">[</span><span class="n">chrom</span><span class="p">]</span>
+ <span class="n">new_chr_name</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_other_chr_name</span><span class="p">(</span><span class="n">chrom</span><span class="p">)</span>
+ <span class="n">chr_paths</span> <span class="o">=</span> <span class="p">[</span><span class="s2">"{}/{}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">bowtie_outdir</span><span class="p">,</span> <span class="n">bowtie_path</span><span class="p">)</span>
+ <span class="k">for</span> <span class="n">bowtie_path</span> <span class="ow">in</span> <span class="n">subset_list</span><span class="p">(</span>
+ <span class="n">os</span><span class="o">.</span><span class="n">listdir</span><span class="p">(</span><span class="bp">self</span><span class="o">.</span><span class="n">bowtie_outdir</span><span class="p">),</span>
+ <span class="s2">"{}\."</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">new_chr_name</span><span class="p">))]</span>
+ <span class="n">bowtie_paths</span> <span class="o">=</span> <span class="n">subset_list</span><span class="p">(</span><span class="n">chr_paths</span><span class="p">,</span> <span class="s2">".bowtie.gz"</span><span class="p">)</span>
+ <span class="n">unique_ar</span> <span class="o">=</span> <span class="n">np</span><span class="o">.</span><span class="n">zeros</span><span class="p">(</span><span class="n">size</span><span class="p">,</span> <span class="n">dtype</span><span class="o">=</span><span class="n">np</span><span class="o">.</span><span class="n">uint8</span><span class="p">)</span>
+ <span class="k">for</span> <span class="n">bowtie_path</span> <span class="ow">in</span> <span class="n">bowtie_paths</span><span class="p">:</span>
+ <span class="n">mapped_indices</span> <span class="o">=</span> <span class="bp">self</span><span class="o">.</span><span class="n">get_mapped_positions</span><span class="p">(</span><span class="n">bowtie_path</span><span class="p">)</span>
+ <span class="k">for</span> <span class="n">st_index</span> <span class="ow">in</span> <span class="n">mapped_indices</span><span class="p">:</span>
+ <span class="n">end_index</span> <span class="o">=</span> <span class="n">st_index</span> <span class="o">+</span> <span class="n">KMER</span>
+ <span class="n">unique_ar</span><span class="p">[</span><span class="n">st_index</span><span class="p">:</span><span class="n">end_index</span><span class="p">]</span> <span class="o">=</span> <span class="mi">1</span>
+ <span class="k">print</span><span class="p">(</span><span class="s2">"Done with {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">bowtie_path</span><span class="p">))</span>
+ <span class="n">out_path</span> <span class="o">=</span> <span class="s2">"{}/{}.k{}.uint8.unique.gz"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span>
+ <span class="bp">self</span><span class="o">.</span><span class="n">bowtie_outdir</span><span class="p">,</span> <span class="n">chrom</span><span class="p">,</span> <span class="n">KMER</span><span class="p">)</span>
+ <span class="n">out_link</span> <span class="o">=</span> <span class="n">gzip</span><span class="o">.</span><span class="n">open</span><span class="p">(</span><span class="n">out_path</span><span class="p">,</span> <span class="s2">"wb"</span><span class="p">)</span>
+ <span class="c1"># np.save(out_link, unique_ar)</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">write</span><span class="p">(</span><span class="n">unique_ar</span><span class="o">.</span><span class="n">tobytes</span><span class="p">())</span>
+ <span class="c1"># unique_ar.tofile(out_link)</span>
+ <span class="n">out_link</span><span class="o">.</span><span class="n">close</span><span class="p">()</span>
+ <span class="k">print</span><span class="p">(</span><span class="s2">"Saved {}"</span><span class="o">.</span><span class="n">format</span><span class="p">(</span><span class="n">out_path</span><span class="p">))</span>
+ <span class="k">print</span><span class="p">(</span><span class="s2">"Exiting successfully"</span><span class="p">)</span></div>
+
+
+<span class="k">if</span> <span class="n">__name__</span> <span class="o">==</span> <span class="s2">"__main__"</span><span class="p">:</span>
+ <span class="n">parser</span> <span class="o">=</span> <span class="n">ArgumentParser</span><span class="p">(</span>
+ <span class="n">description</span><span class="o">=</span><span class="s2">""</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"bowtie_outdir"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"Directory containing bowtie output files"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"chrsize_path"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"A file containing the order of chromosome names</span><span class="se">\</span>
+<span class="s2"> to consider (one chromosome name per line)"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-job_id"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="mi">0</span><span class="p">,</span>
+ <span class="nb">type</span><span class="o">=</span><span class="nb">int</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"If not using a cluster for submitting jobs, "</span>
+ <span class="s2">"specify the job_id by integer ranging from 1 to "</span>
+ <span class="s2">"total number of chromosomes in chrsize_path"</span><span class="p">)</span>
+ <span class="n">parser</span><span class="o">.</span><span class="n">add_argument</span><span class="p">(</span>
+ <span class="s2">"-var_id"</span><span class="p">,</span>
+ <span class="n">default</span><span class="o">=</span><span class="s2">"SGE_TASK_ID"</span><span class="p">,</span>
+ <span class="n">help</span><span class="o">=</span><span class="s2">"HPC variable name for job ID (1-based index)"</span><span class="p">)</span>
+ <span class="n">args</span> <span class="o">=</span> <span class="n">parser</span><span class="o">.</span><span class="n">parse_args</span><span class="p">()</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="n">args</span><span class="o">.</span><span class="n">job_id</span>
+ <span class="k">if</span> <span class="n">job_id</span> <span class="o">==</span> <span class="mi">0</span><span class="p">:</span>
+ <span class="n">job_id</span> <span class="o">=</span> <span class="nb">int</span><span class="p">(</span><span class="n">os</span><span class="o">.</span><span class="n">environ</span><span class="p">[</span><span class="n">args</span><span class="o">.</span><span class="n">var_id</span><span class="p">])</span> <span class="o">-</span> <span class="mi">1</span>
+ <span class="n">UnifyBowtie</span><span class="p">(</span><span class="n">args</span><span class="o">.</span><span class="n">bowtie_outdir</span><span class="p">,</span> <span class="n">args</span><span class="o">.</span><span class="n">chrsize_path</span><span class="p">,</span> <span class="n">job_id</span><span class="p">)</span>
+</pre></div>
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper"><div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="../../documentation.html">Documentation overview</a><ul>
+ <li><a href="../index.html">Module code</a><ul>
+ </ul></li>
+ </ul></li>
+</ul>
+</div>
+<div id="searchbox" style="display: none" role="search">
+ <h3>Quick search</h3>
+ <form class="search" action="../../search.html" method="get">
+ <input type="text" name="q" />
+ <input type="submit" value="Go" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+ </form>
+</div>
+<script type="text/javascript">$('#searchbox').show(0);</script>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/_sources/documentation.txt b/doc/build/_sources/documentation.txt
new file mode 100644
index 0000000..51ccce1
--- /dev/null
+++ b/doc/build/_sources/documentation.txt
@@ -0,0 +1,195 @@
+.. Umap documentation master file, created by
+ sphinx-quickstart on Mon Jun 20 14:29:08 2016.
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+Welcome to Umap's documentation!
+================================
+
+Contents:
+
+.. toctree::
+ :maxdepth: 2
+
+
+Introduction
+------------
+
+**The free umap software package efficiently identifies uniquely mappable regions of any genome.
+Its Bismap extension identifies mappability of the bisulfite converted genome (methylome).**
+
+the mappability of a genome for a given read length *k*.
+First, it generates all possible *k*-mers of the genome.
+Second, it maps these unique *k*-mers to the genome with `Bowtie <http://bowtie-bio.sourceforge.net/index.shtml>`_ version 1.1.0.
+Third, Umap marks the start position of each *k*-mer that aligns to only one region in the genome.
+Umap repeats these steps for a range of different *k*-mers and stores the data of each chromosome
+in a binary vector *X* with the same length as the chromosome's sequence.
+For read length *k*, :math:`X_i = 1` means that the sequence starting at :math:`X_i` and ending
+at :math:`X_{i+k}` is uniquely mappable on the forward strand.
+Since we align to both strands of the genome, the reverse complement of this same sequence
+starting at :math:`X_{i+k}` on the reverse strand is also uniquely mappable.
+:math:`X_i = 0` means that the sequence starting at :math:`X_i` and ending at
+:math:`X_{i+k}` can be mapped to at least two different regions in the genome.
+
+
+Mappability of the bisulfite-converted genome
+---------------------------------------------
+
+To identify the single-read mappability of a bisulfite-converted genome,
+we create two altered genome sequences.
+In the first sequence, we convert all cytosines to thymine (C :math:`\rightarrow` T).
+In the other sequence we convert all guanines to adenine (G :math:`\rightarrow` A).
+Our approach follows those of `Bismark <http://www.bioinformatics.babraham.ac.uk/projects/bismark/>`_
+and `BWA-meth <https://github.com/brentp/bwa-meth>`_.
+We convert the genome sequence this way because bisulfite
+treatment converts un-methylated cytosine to uracil which is read as thymine.
+Similarly the guanine that is base-pairing with the un-methylated cytosine in
+reverse strand converts to adenine. However these two conversions never occur
+at the same time on the same read. We identify the uniquely mappable regions
+of these two genomes separately, and then combine the data to represent the
+single-read mappability of the forward and reverse strands in the bisulfite-converted genome.
+
+
+Bismap requires special handling of reverse complementation of C :math:`\rightarrow` T
+or G :math:`\rightarrow` A converted genomes.
+Conversion of C :math:`\rightarrow` T on the sequence AATTCCGG produces AATT **TT** GG.
+In the Bowtie index, the reverse complement would be CCAAAATT.
+However for the purpose of identifying the mappability of the bisulfite-converted genome,
+we expect the reverse complement to be TTGGAA **TT**. The reason is that both forward and reverse
+strands undergo bisulfite treatment simultaneously. There is no DNA replication after bisulfite treatment.
+To handle this issue, Bismap creates its own reverse complemented chromosomes and suppresses Bowtie's usual reverse complement mapping.
+
+Umap and Bismap each take approximately 200 CPU hours to run for a given read length. This can be parallelized in a computing cluster over 400 cores to take only 30 minutes.
+
+
+
+Measures of mappability
+:::::::::::::::::::::::
+
+Umap efficiently identifies the single-read mappability of any genome for a
+range of sequencing read lengths. The single-read mappability of a genomic
+region is a fraction of that region which overlaps with at least one uniquely
+mappable *k*-mer. The Bismap extension of Umap produces the single-read mappability
+of a bisulfite-converted genome. Both Umap and Bismap produce an integer vector for
+each chromosome that efficiently defines the mappability for any region and can be
+converted to a browser extensible data (BED) file. In addition to single-read mappability,
+we can measure the mappability of a genomic region by another approach. To quantify
+the single-read mappability of a given genomic region, we measure the fraction of
+potential uniquely mappable reads in that region. A region, however, can have 100% single-read
+mappability, but in practice require a high coverage sequencing to properly identify that region.
+For example, a 1 kbp region with 100% single-read mappability can be mappable due to a
+minimum of 10 unique 100-mers that none of them overlap or a maximum of 1100 unique 100-mers
+that highly overlap. Therefore, we define the multi-read mappability, the probability that a
+randomly selected read of length k in a given region is uniquely mappable. For the genomic
+region :math:`G_{i:j}` starting at *i* and ending at *j*, there are :math:`j - i + k + 1`
+*k*-mers that overlap with :math:`G_{i:j}`.
+The multi-read mappability of :math:`G_{i:j}` is the fraction of those *k*-mers that are uniquely mappable.
+
+
+
+Quick start
+-----------
+
+We have tested Umap installation on a CentOS system using python 2.7.11.
+Bismap requires numpy and pandas and it uses other python modules such as:
+
+* gzip
+* os
+* re
+* subprocess
+
+Umap uses mercurial version control. Make sure that mercurial (hg) is installed.
+Download Umap to the directory of your python packages using::
+
+ hg clone https://bitbucket.org/hoffmanlab/umap
+ cd umap
+ python setup.py install
+
+
+Now we will run a test using a wrapper in the umap directory called ubismap.py
+and a toy genome stored under umap/data ::
+
+ cd umap
+ python ubismap.py data/genome.fa data/chrsize.tsv data/TestGenomeMappability all.q $BOWTIRDIR/bowtie-build --kmer 8 12 -write_script test_run.sh
+ sh test_run.sh
+
+The scripts that are produced by **ubismap.py** assume that you are using a Sun Grid Engine computing cluster.
+You can use parameters of this script to adjust it to your own system. You may need to manually edit this file
+because many of the SGE settings are very different than other computing clusters.
+However, all of the Umap modules accept *-job_id* which allows you to use the modules without a cluster or if
+your cluster does not support job arrays.
+
+Basically, the job array saves an environmental variable (defined by (*-var_id*) that Umap uses for paralellizing processes.
+You can run the modules in a for loop and set the *-job_id* manually.
+For example, in order to find *k*-mers of a genome with 10 million base pairs, the get_kmers
+and run_bowtie modules each need to be executed with -job_ids ranging between 1 to 10.
+
+Get *k*-mers
+------------
+
+.. module:: umap
+ :platform: Unix
+
+.. currentmodule:: umap
+.. autoclass:: GetKmers
+
+
+Run Bowtie
+----------
+
+.. currentmodule:: umap
+.. autoclass:: BowtieWrapper
+
+
+Merge bowtie outputs
+--------------------
+
+
+.. currentmodule:: umap
+.. autoclass:: UnifyBowtie
+
+
+Merge data of various *k*-mers
+------------------------------
+
+
+.. currentmodule:: umap
+.. autoclass:: CombineUmaps
+
+
+Convert numeric vectors to BED and Wiggle
+-----------------------------------------
+
+
+.. currentmodule:: umap
+.. autoclass:: Int8Handler
+.. method:: Int8Handler.write_beds
+.. method:: Int8Handler.write_as_wig
+
+Requesting Genomes
+------------------
+
+In case you need these data for other genomes and do not have access to a Sun Grid Engine computing cluster,
+we may accept to do this for you.
+Please contact the software maintainer by email and we will do our best to assist you as soon as possible.
+
+
+
+Contact, support and questions
+------------------------------
+
+For support of Umap, please user our `mailing list <https://groups.google.com/forum/#!forum/ubismap>`_.
+Specifically, if you want to report a bug or request a feature,
+please do so using
+the `Umap issue tracker <https://bitbucket.org/hoffmanlab/umap/issues>`_.
+We are interested in all comments on the package,
+and the ease of use of installation and documentation.
+
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
diff --git a/doc/build/_static/ajax-loader.gif b/doc/build/_static/ajax-loader.gif
new file mode 100644
index 0000000..61faf8c
Binary files /dev/null and b/doc/build/_static/ajax-loader.gif differ
diff --git a/doc/build/_static/alabaster.css b/doc/build/_static/alabaster.css
new file mode 100644
index 0000000..bc420a4
--- /dev/null
+++ b/doc/build/_static/alabaster.css
@@ -0,0 +1,593 @@
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+ at import url("basic.css");
+
+/* -- page layout ----------------------------------------------------------- */
+
+body {
+ font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro', serif;
+ font-size: 17px;
+ background-color: white;
+ color: #000;
+ margin: 0;
+ padding: 0;
+}
+
+div.document {
+ width: 940px;
+ margin: 30px auto 0 auto;
+}
+
+div.documentwrapper {
+ float: left;
+ width: 100%;
+}
+
+div.bodywrapper {
+ margin: 0 0 0 220px;
+}
+
+div.sphinxsidebar {
+ width: 220px;
+}
+
+hr {
+ border: 1px solid #B1B4B6;
+}
+
+div.body {
+ background-color: #ffffff;
+ color: #3E4349;
+ padding: 0 30px 0 30px;
+}
+
+div.body > .section {
+ text-align: left;
+}
+
+div.footer {
+ width: 940px;
+ margin: 20px auto 30px auto;
+ font-size: 14px;
+ color: #888;
+ text-align: right;
+}
+
+div.footer a {
+ color: #888;
+}
+
+
+div.relations {
+ display: none;
+}
+
+
+div.sphinxsidebar a {
+ color: #444;
+ text-decoration: none;
+ border-bottom: 1px dotted #999;
+}
+
+div.sphinxsidebar a:hover {
+ border-bottom: 1px solid #999;
+}
+
+div.sphinxsidebar {
+ font-size: 14px;
+ line-height: 1.5;
+}
+
+div.sphinxsidebarwrapper {
+ padding: 18px 10px;
+}
+
+div.sphinxsidebarwrapper p.logo {
+ padding: 0;
+ margin: -10px 0 0 0px;
+ text-align: center;
+}
+
+div.sphinxsidebarwrapper h1.logo {
+ margin-top: -10px;
+ text-align: center;
+ margin-bottom: 5px;
+ text-align: left;
+}
+
+div.sphinxsidebarwrapper h1.logo-name {
+ margin-top: 0px;
+}
+
+div.sphinxsidebarwrapper p.blurb {
+ margin-top: 0;
+ font-style: normal;
+}
+
+div.sphinxsidebar h3,
+div.sphinxsidebar h4 {
+ font-family: 'Garamond', 'Georgia', serif;
+ color: #444;
+ font-size: 24px;
+ font-weight: normal;
+ margin: 0 0 5px 0;
+ padding: 0;
+}
+
+div.sphinxsidebar h4 {
+ font-size: 20px;
+}
+
+div.sphinxsidebar h3 a {
+ color: #444;
+}
+
+div.sphinxsidebar p.logo a,
+div.sphinxsidebar h3 a,
+div.sphinxsidebar p.logo a:hover,
+div.sphinxsidebar h3 a:hover {
+ border: none;
+}
+
+div.sphinxsidebar p {
+ color: #555;
+ margin: 10px 0;
+}
+
+div.sphinxsidebar ul {
+ margin: 10px 0;
+ padding: 0;
+ color: #000;
+}
+
+div.sphinxsidebar ul li.toctree-l1 > a {
+ font-size: 120%;
+}
+
+div.sphinxsidebar ul li.toctree-l2 > a {
+ font-size: 110%;
+}
+
+div.sphinxsidebar input {
+ border: 1px solid #CCC;
+ font-family: 'goudy old style', 'minion pro', 'bell mt', Georgia, 'Hiragino Mincho Pro', serif;
+ font-size: 1em;
+}
+
+div.sphinxsidebar hr {
+ border: none;
+ height: 1px;
+ color: #AAA;
+ background: #AAA;
+
+ text-align: left;
+ margin-left: 0;
+ width: 50%;
+}
+
+/* -- body styles ----------------------------------------------------------- */
+
+a {
+ color: #004B6B;
+ text-decoration: underline;
+}
+
+a:hover {
+ color: #6D4100;
+ text-decoration: underline;
+}
+
+div.body h1,
+div.body h2,
+div.body h3,
+div.body h4,
+div.body h5,
+div.body h6 {
+ font-family: 'Garamond', 'Georgia', serif;
+ font-weight: normal;
+ margin: 30px 0px 10px 0px;
+ padding: 0;
+}
+
+div.body h1 { margin-top: 0; padding-top: 0; font-size: 240%; }
+div.body h2 { font-size: 180%; }
+div.body h3 { font-size: 150%; }
+div.body h4 { font-size: 130%; }
+div.body h5 { font-size: 100%; }
+div.body h6 { font-size: 100%; }
+
+a.headerlink {
+ color: #DDD;
+ padding: 0 4px;
+ text-decoration: none;
+}
+
+a.headerlink:hover {
+ color: #444;
+ background: #EAEAEA;
+}
+
+div.body p, div.body dd, div.body li {
+ line-height: 1.4em;
+}
+
+div.admonition {
+ margin: 20px 0px;
+ padding: 10px 30px;
+ background-color: #FCC;
+ border: 1px solid #FAA;
+}
+
+div.admonition tt.xref, div.admonition a tt {
+ border-bottom: 1px solid #fafafa;
+}
+
+dd div.admonition {
+ margin-left: -60px;
+ padding-left: 60px;
+}
+
+div.admonition p.admonition-title {
+ font-family: 'Garamond', 'Georgia', serif;
+ font-weight: normal;
+ font-size: 24px;
+ margin: 0 0 10px 0;
+ padding: 0;
+ line-height: 1;
+}
+
+div.admonition p.last {
+ margin-bottom: 0;
+}
+
+div.highlight {
+ background-color: white;
+}
+
+dt:target, .highlight {
+ background: #FAF3E8;
+}
+
+div.note {
+ background-color: #EEE;
+ border: 1px solid #CCC;
+}
+
+div.seealso {
+ background-color: #EEE;
+ border: 1px solid #CCC;
+}
+
+div.topic {
+ background-color: #eee;
+}
+
+p.admonition-title {
+ display: inline;
+}
+
+p.admonition-title:after {
+ content: ":";
+}
+
+pre, tt, code {
+ font-family: 'Consolas', 'Menlo', 'Deja Vu Sans Mono', 'Bitstream Vera Sans Mono', monospace;
+ font-size: 0.9em;
+}
+
+.hll {
+ background-color: #FFC;
+ margin: 0 -12px;
+ padding: 0 12px;
+ display: block;
+}
+
+img.screenshot {
+}
+
+tt.descname, tt.descclassname, code.descname, code.descclassname {
+ font-size: 0.95em;
+}
+
+tt.descname, code.descname {
+ padding-right: 0.08em;
+}
+
+img.screenshot {
+ -moz-box-shadow: 2px 2px 4px #eee;
+ -webkit-box-shadow: 2px 2px 4px #eee;
+ box-shadow: 2px 2px 4px #eee;
+}
+
+table.docutils {
+ border: 1px solid #888;
+ -moz-box-shadow: 2px 2px 4px #eee;
+ -webkit-box-shadow: 2px 2px 4px #eee;
+ box-shadow: 2px 2px 4px #eee;
+}
+
+table.docutils td, table.docutils th {
+ border: 1px solid #888;
+ padding: 0.25em 0.7em;
+}
+
+table.field-list, table.footnote {
+ border: none;
+ -moz-box-shadow: none;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
+
+table.footnote {
+ margin: 15px 0;
+ width: 100%;
+ border: 1px solid #EEE;
+ background: #FDFDFD;
+ font-size: 0.9em;
+}
+
+table.footnote + table.footnote {
+ margin-top: -15px;
+ border-top: none;
+}
+
+table.field-list th {
+ padding: 0 0.8em 0 0;
+}
+
+table.field-list td {
+ padding: 0;
+}
+
+table.field-list p {
+ margin-bottom: 0.8em;
+}
+
+table.footnote td.label {
+ width: 0px;
+ padding: 0.3em 0 0.3em 0.5em;
+}
+
+table.footnote td {
+ padding: 0.3em 0.5em;
+}
+
+dl {
+ margin: 0;
+ padding: 0;
+}
+
+dl dd {
+ margin-left: 30px;
+}
+
+blockquote {
+ margin: 0 0 0 30px;
+ padding: 0;
+}
+
+ul, ol {
+ margin: 10px 0 10px 30px;
+ padding: 0;
+}
+
+pre {
+ background: #EEE;
+ padding: 7px 30px;
+ margin: 15px 0px;
+ line-height: 1.3em;
+}
+
+dl pre, blockquote pre, li pre {
+ margin-left: 0;
+ padding-left: 30px;
+}
+
+dl dl pre {
+ margin-left: -90px;
+ padding-left: 90px;
+}
+
+tt, code {
+ background-color: #ecf0f3;
+ color: #222;
+ /* padding: 1px 2px; */
+}
+
+tt.xref, code.xref, a tt {
+ background-color: #FBFBFB;
+ border-bottom: 1px solid white;
+}
+
+a.reference {
+ text-decoration: none;
+ border-bottom: 1px dotted #004B6B;
+}
+
+a.reference:hover {
+ border-bottom: 1px solid #6D4100;
+}
+
+a.footnote-reference {
+ text-decoration: none;
+ font-size: 0.7em;
+ vertical-align: top;
+ border-bottom: 1px dotted #004B6B;
+}
+
+a.footnote-reference:hover {
+ border-bottom: 1px solid #6D4100;
+}
+
+a:hover tt, a:hover code {
+ background: #EEE;
+}
+
+
+ at media screen and (max-width: 870px) {
+
+ div.sphinxsidebar {
+ display: none;
+ }
+
+ div.document {
+ width: 100%;
+
+ }
+
+ div.documentwrapper {
+ margin-left: 0;
+ margin-top: 0;
+ margin-right: 0;
+ margin-bottom: 0;
+ }
+
+ div.bodywrapper {
+ margin-top: 0;
+ margin-right: 0;
+ margin-bottom: 0;
+ margin-left: 0;
+ }
+
+ ul {
+ margin-left: 0;
+ }
+
+ .document {
+ width: auto;
+ }
+
+ .footer {
+ width: auto;
+ }
+
+ .bodywrapper {
+ margin: 0;
+ }
+
+ .footer {
+ width: auto;
+ }
+
+ .github {
+ display: none;
+ }
+
+
+
+}
+
+
+
+ at media screen and (max-width: 875px) {
+
+ body {
+ margin: 0;
+ padding: 20px 30px;
+ }
+
+ div.documentwrapper {
+ float: none;
+ background: white;
+ }
+
+ div.sphinxsidebar {
+ display: block;
+ float: none;
+ width: 102.5%;
+ margin: 50px -30px -20px -30px;
+ padding: 10px 20px;
+ background: #333;
+ color: #FFF;
+ }
+
+ div.sphinxsidebar h3, div.sphinxsidebar h4, div.sphinxsidebar p,
+ div.sphinxsidebar h3 a {
+ color: white;
+ }
+
+ div.sphinxsidebar a {
+ color: #AAA;
+ }
+
+ div.sphinxsidebar p.logo {
+ display: none;
+ }
+
+ div.document {
+ width: 100%;
+ margin: 0;
+ }
+
+ div.footer {
+ display: none;
+ }
+
+ div.bodywrapper {
+ margin: 0;
+ }
+
+ div.body {
+ min-height: 0;
+ padding: 0;
+ }
+
+ .rtd_doc_footer {
+ display: none;
+ }
+
+ .document {
+ width: auto;
+ }
+
+ .footer {
+ width: auto;
+ }
+
+ .footer {
+ width: auto;
+ }
+
+ .github {
+ display: none;
+ }
+}
+
+
+/* misc. */
+
+.revsys-inline {
+ display: none!important;
+}
+
+/* Make nested-list/multi-paragraph items look better in Releases changelog
+ * pages. Without this, docutils' magical list fuckery causes inconsistent
+ * formatting between different release sub-lists.
+ */
+div#changelog > div.section > ul > li > p:only-child {
+ margin-bottom: 0;
+}
+
+/* Hide fugly table cell borders in ..bibliography:: directive output */
+table.docutils.citation, table.docutils.citation td, table.docutils.citation th {
+ border: none;
+ /* Below needed in some edge cases; if not applied, bottom shadows appear */
+ -moz-box-shadow: none;
+ -webkit-box-shadow: none;
+ box-shadow: none;
+}
\ No newline at end of file
diff --git a/doc/build/_static/basic.css b/doc/build/_static/basic.css
new file mode 100644
index 0000000..65dfd7d
--- /dev/null
+++ b/doc/build/_static/basic.css
@@ -0,0 +1,608 @@
+/*
+ * basic.css
+ * ~~~~~~~~~
+ *
+ * Sphinx stylesheet -- basic theme.
+ *
+ * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ * :license: BSD, see LICENSE for details.
+ *
+ */
+
+/* -- main layout ----------------------------------------------------------- */
+
+div.clearer {
+ clear: both;
+}
+
+/* -- relbar ---------------------------------------------------------------- */
+
+div.related {
+ width: 100%;
+ font-size: 90%;
+}
+
+div.related h3 {
+ display: none;
+}
+
+div.related ul {
+ margin: 0;
+ padding: 0 0 0 10px;
+ list-style: none;
+}
+
+div.related li {
+ display: inline;
+}
+
+div.related li.right {
+ float: right;
+ margin-right: 5px;
+}
+
+/* -- sidebar --------------------------------------------------------------- */
+
+div.sphinxsidebarwrapper {
+ padding: 10px 5px 0 10px;
+}
+
+div.sphinxsidebar {
+ float: left;
+ width: 230px;
+ margin-left: -100%;
+ font-size: 90%;
+ word-wrap: break-word;
+ overflow-wrap : break-word;
+}
+
+div.sphinxsidebar ul {
+ list-style: none;
+}
+
+div.sphinxsidebar ul ul,
+div.sphinxsidebar ul.want-points {
+ margin-left: 20px;
+ list-style: square;
+}
+
+div.sphinxsidebar ul ul {
+ margin-top: 0;
+ margin-bottom: 0;
+}
+
+div.sphinxsidebar form {
+ margin-top: 10px;
+}
+
+div.sphinxsidebar input {
+ border: 1px solid #98dbcc;
+ font-family: sans-serif;
+ font-size: 1em;
+}
+
+div.sphinxsidebar #searchbox input[type="text"] {
+ width: 170px;
+}
+
+div.sphinxsidebar #searchbox input[type="submit"] {
+ width: 30px;
+}
+
+img {
+ border: 0;
+ max-width: 100%;
+}
+
+/* -- search page ----------------------------------------------------------- */
+
+ul.search {
+ margin: 10px 0 0 20px;
+ padding: 0;
+}
+
+ul.search li {
+ padding: 5px 0 5px 20px;
+ background-image: url(file.png);
+ background-repeat: no-repeat;
+ background-position: 0 7px;
+}
+
+ul.search li a {
+ font-weight: bold;
+}
+
+ul.search li div.context {
+ color: #888;
+ margin: 2px 0 0 30px;
+ text-align: left;
+}
+
+ul.keywordmatches li.goodmatch a {
+ font-weight: bold;
+}
+
+/* -- index page ------------------------------------------------------------ */
+
+table.contentstable {
+ width: 90%;
+}
+
+table.contentstable p.biglink {
+ line-height: 150%;
+}
+
+a.biglink {
+ font-size: 1.3em;
+}
+
+span.linkdescr {
+ font-style: italic;
+ padding-top: 5px;
+ font-size: 90%;
+}
+
+/* -- general index --------------------------------------------------------- */
+
+table.indextable {
+ width: 100%;
+}
+
+table.indextable td {
+ text-align: left;
+ vertical-align: top;
+}
+
+table.indextable dl, table.indextable dd {
+ margin-top: 0;
+ margin-bottom: 0;
+}
+
+table.indextable tr.pcap {
+ height: 10px;
+}
+
+table.indextable tr.cap {
+ margin-top: 10px;
+ background-color: #f2f2f2;
+}
+
+img.toggler {
+ margin-right: 3px;
+ margin-top: 3px;
+ cursor: pointer;
+}
+
+div.modindex-jumpbox {
+ border-top: 1px solid #ddd;
+ border-bottom: 1px solid #ddd;
+ margin: 1em 0 1em 0;
+ padding: 0.4em;
+}
+
+div.genindex-jumpbox {
+ border-top: 1px solid #ddd;
+ border-bottom: 1px solid #ddd;
+ margin: 1em 0 1em 0;
+ padding: 0.4em;
+}
+
+/* -- general body styles --------------------------------------------------- */
+
+div.body p, div.body dd, div.body li, div.body blockquote {
+ -moz-hyphens: auto;
+ -ms-hyphens: auto;
+ -webkit-hyphens: auto;
+ hyphens: auto;
+}
+
+a.headerlink {
+ visibility: hidden;
+}
+
+h1:hover > a.headerlink,
+h2:hover > a.headerlink,
+h3:hover > a.headerlink,
+h4:hover > a.headerlink,
+h5:hover > a.headerlink,
+h6:hover > a.headerlink,
+dt:hover > a.headerlink,
+caption:hover > a.headerlink,
+p.caption:hover > a.headerlink,
+div.code-block-caption:hover > a.headerlink {
+ visibility: visible;
+}
+
+div.body p.caption {
+ text-align: inherit;
+}
+
+div.body td {
+ text-align: left;
+}
+
+.field-list ul {
+ padding-left: 1em;
+}
+
+.first {
+ margin-top: 0 !important;
+}
+
+p.rubric {
+ margin-top: 30px;
+ font-weight: bold;
+}
+
+img.align-left, .figure.align-left, object.align-left {
+ clear: left;
+ float: left;
+ margin-right: 1em;
+}
+
+img.align-right, .figure.align-right, object.align-right {
+ clear: right;
+ float: right;
+ margin-left: 1em;
+}
+
+img.align-center, .figure.align-center, object.align-center {
+ display: block;
+ margin-left: auto;
+ margin-right: auto;
+}
+
+.align-left {
+ text-align: left;
+}
+
+.align-center {
+ text-align: center;
+}
+
+.align-right {
+ text-align: right;
+}
+
+/* -- sidebars -------------------------------------------------------------- */
+
+div.sidebar {
+ margin: 0 0 0.5em 1em;
+ border: 1px solid #ddb;
+ padding: 7px 7px 0 7px;
+ background-color: #ffe;
+ width: 40%;
+ float: right;
+}
+
+p.sidebar-title {
+ font-weight: bold;
+}
+
+/* -- topics ---------------------------------------------------------------- */
+
+div.topic {
+ border: 1px solid #ccc;
+ padding: 7px 7px 0 7px;
+ margin: 10px 0 10px 0;
+}
+
+p.topic-title {
+ font-size: 1.1em;
+ font-weight: bold;
+ margin-top: 10px;
+}
+
+/* -- admonitions ----------------------------------------------------------- */
+
+div.admonition {
+ margin-top: 10px;
+ margin-bottom: 10px;
+ padding: 7px;
+}
+
+div.admonition dt {
+ font-weight: bold;
+}
+
+div.admonition dl {
+ margin-bottom: 0;
+}
+
+p.admonition-title {
+ margin: 0px 10px 5px 0px;
+ font-weight: bold;
+}
+
+div.body p.centered {
+ text-align: center;
+ margin-top: 25px;
+}
+
+/* -- tables ---------------------------------------------------------------- */
+
+table.docutils {
+ border: 0;
+ border-collapse: collapse;
+}
+
+table caption span.caption-number {
+ font-style: italic;
+}
+
+table caption span.caption-text {
+}
+
+table.docutils td, table.docutils th {
+ padding: 1px 8px 1px 5px;
+ border-top: 0;
+ border-left: 0;
+ border-right: 0;
+ border-bottom: 1px solid #aaa;
+}
+
+table.field-list td, table.field-list th {
+ border: 0 !important;
+}
+
+table.footnote td, table.footnote th {
+ border: 0 !important;
+}
+
+th {
+ text-align: left;
+ padding-right: 5px;
+}
+
+table.citation {
+ border-left: solid 1px gray;
+ margin-left: 1px;
+}
+
+table.citation td {
+ border-bottom: none;
+}
+
+/* -- figures --------------------------------------------------------------- */
+
+div.figure {
+ margin: 0.5em;
+ padding: 0.5em;
+}
+
+div.figure p.caption {
+ padding: 0.3em;
+}
+
+div.figure p.caption span.caption-number {
+ font-style: italic;
+}
+
+div.figure p.caption span.caption-text {
+}
+
+
+/* -- other body styles ----------------------------------------------------- */
+
+ol.arabic {
+ list-style: decimal;
+}
+
+ol.loweralpha {
+ list-style: lower-alpha;
+}
+
+ol.upperalpha {
+ list-style: upper-alpha;
+}
+
+ol.lowerroman {
+ list-style: lower-roman;
+}
+
+ol.upperroman {
+ list-style: upper-roman;
+}
+
+dl {
+ margin-bottom: 15px;
+}
+
+dd p {
+ margin-top: 0px;
+}
+
+dd ul, dd table {
+ margin-bottom: 10px;
+}
+
+dd {
+ margin-top: 3px;
+ margin-bottom: 10px;
+ margin-left: 30px;
+}
+
+dt:target, .highlighted {
+ background-color: #fbe54e;
+}
+
+dl.glossary dt {
+ font-weight: bold;
+ font-size: 1.1em;
+}
+
+.field-list ul {
+ margin: 0;
+ padding-left: 1em;
+}
+
+.field-list p {
+ margin: 0;
+}
+
+.optional {
+ font-size: 1.3em;
+}
+
+.sig-paren {
+ font-size: larger;
+}
+
+.versionmodified {
+ font-style: italic;
+}
+
+.system-message {
+ background-color: #fda;
+ padding: 5px;
+ border: 3px solid red;
+}
+
+.footnote:target {
+ background-color: #ffa;
+}
+
+.line-block {
+ display: block;
+ margin-top: 1em;
+ margin-bottom: 1em;
+}
+
+.line-block .line-block {
+ margin-top: 0;
+ margin-bottom: 0;
+ margin-left: 1.5em;
+}
+
+.guilabel, .menuselection {
+ font-family: sans-serif;
+}
+
+.accelerator {
+ text-decoration: underline;
+}
+
+.classifier {
+ font-style: oblique;
+}
+
+abbr, acronym {
+ border-bottom: dotted 1px;
+ cursor: help;
+}
+
+/* -- code displays --------------------------------------------------------- */
+
+pre {
+ overflow: auto;
+ overflow-y: hidden; /* fixes display issues on Chrome browsers */
+}
+
+td.linenos pre {
+ padding: 5px 0px;
+ border: 0;
+ background-color: transparent;
+ color: #aaa;
+}
+
+table.highlighttable {
+ margin-left: 0.5em;
+}
+
+table.highlighttable td {
+ padding: 0 0.5em 0 0.5em;
+}
+
+div.code-block-caption {
+ padding: 2px 5px;
+ font-size: small;
+}
+
+div.code-block-caption code {
+ background-color: transparent;
+}
+
+div.code-block-caption + div > div.highlight > pre {
+ margin-top: 0;
+}
+
+div.code-block-caption span.caption-number {
+ padding: 0.1em 0.3em;
+ font-style: italic;
+}
+
+div.code-block-caption span.caption-text {
+}
+
+div.literal-block-wrapper {
+ padding: 1em 1em 0;
+}
+
+div.literal-block-wrapper div.highlight {
+ margin: 0;
+}
+
+code.descname {
+ background-color: transparent;
+ font-weight: bold;
+ font-size: 1.2em;
+}
+
+code.descclassname {
+ background-color: transparent;
+}
+
+code.xref, a code {
+ background-color: transparent;
+ font-weight: bold;
+}
+
+h1 code, h2 code, h3 code, h4 code, h5 code, h6 code {
+ background-color: transparent;
+}
+
+.viewcode-link {
+ float: right;
+}
+
+.viewcode-back {
+ float: right;
+ font-family: sans-serif;
+}
+
+div.viewcode-block:target {
+ margin: -1px -10px;
+ padding: 0 10px;
+}
+
+/* -- math display ---------------------------------------------------------- */
+
+img.math {
+ vertical-align: middle;
+}
+
+div.body div.math p {
+ text-align: center;
+}
+
+span.eqno {
+ float: right;
+}
+
+/* -- printout stylesheet --------------------------------------------------- */
+
+ at media print {
+ div.document,
+ div.documentwrapper,
+ div.bodywrapper {
+ margin: 0 !important;
+ width: 100%;
+ }
+
+ div.sphinxsidebar,
+ div.related,
+ div.footer,
+ #top-link {
+ display: none;
+ }
+}
\ No newline at end of file
diff --git a/doc/build/_static/comment-bright.png b/doc/build/_static/comment-bright.png
new file mode 100644
index 0000000..551517b
Binary files /dev/null and b/doc/build/_static/comment-bright.png differ
diff --git a/doc/build/_static/comment-close.png b/doc/build/_static/comment-close.png
new file mode 100644
index 0000000..09b54be
Binary files /dev/null and b/doc/build/_static/comment-close.png differ
diff --git a/doc/build/_static/comment.png b/doc/build/_static/comment.png
new file mode 100644
index 0000000..92feb52
Binary files /dev/null and b/doc/build/_static/comment.png differ
diff --git a/doc/build/_static/doctools.js b/doc/build/_static/doctools.js
new file mode 100644
index 0000000..8163495
--- /dev/null
+++ b/doc/build/_static/doctools.js
@@ -0,0 +1,287 @@
+/*
+ * doctools.js
+ * ~~~~~~~~~~~
+ *
+ * Sphinx JavaScript utilities for all documentation.
+ *
+ * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ * :license: BSD, see LICENSE for details.
+ *
+ */
+
+/**
+ * select a different prefix for underscore
+ */
+$u = _.noConflict();
+
+/**
+ * make the code below compatible with browsers without
+ * an installed firebug like debugger
+if (!window.console || !console.firebug) {
+ var names = ["log", "debug", "info", "warn", "error", "assert", "dir",
+ "dirxml", "group", "groupEnd", "time", "timeEnd", "count", "trace",
+ "profile", "profileEnd"];
+ window.console = {};
+ for (var i = 0; i < names.length; ++i)
+ window.console[names[i]] = function() {};
+}
+ */
+
+/**
+ * small helper function to urldecode strings
+ */
+jQuery.urldecode = function(x) {
+ return decodeURIComponent(x).replace(/\+/g, ' ');
+};
+
+/**
+ * small helper function to urlencode strings
+ */
+jQuery.urlencode = encodeURIComponent;
+
+/**
+ * This function returns the parsed url parameters of the
+ * current request. Multiple values per key are supported,
+ * it will always return arrays of strings for the value parts.
+ */
+jQuery.getQueryParameters = function(s) {
+ if (typeof s == 'undefined')
+ s = document.location.search;
+ var parts = s.substr(s.indexOf('?') + 1).split('&');
+ var result = {};
+ for (var i = 0; i < parts.length; i++) {
+ var tmp = parts[i].split('=', 2);
+ var key = jQuery.urldecode(tmp[0]);
+ var value = jQuery.urldecode(tmp[1]);
+ if (key in result)
+ result[key].push(value);
+ else
+ result[key] = [value];
+ }
+ return result;
+};
+
+/**
+ * highlight a given string on a jquery object by wrapping it in
+ * span elements with the given class name.
+ */
+jQuery.fn.highlightText = function(text, className) {
+ function highlight(node) {
+ if (node.nodeType == 3) {
+ var val = node.nodeValue;
+ var pos = val.toLowerCase().indexOf(text);
+ if (pos >= 0 && !jQuery(node.parentNode).hasClass(className)) {
+ var span = document.createElement("span");
+ span.className = className;
+ span.appendChild(document.createTextNode(val.substr(pos, text.length)));
+ node.parentNode.insertBefore(span, node.parentNode.insertBefore(
+ document.createTextNode(val.substr(pos + text.length)),
+ node.nextSibling));
+ node.nodeValue = val.substr(0, pos);
+ }
+ }
+ else if (!jQuery(node).is("button, select, textarea")) {
+ jQuery.each(node.childNodes, function() {
+ highlight(this);
+ });
+ }
+ }
+ return this.each(function() {
+ highlight(this);
+ });
+};
+
+/*
+ * backward compatibility for jQuery.browser
+ * This will be supported until firefox bug is fixed.
+ */
+if (!jQuery.browser) {
+ jQuery.uaMatch = function(ua) {
+ ua = ua.toLowerCase();
+
+ var match = /(chrome)[ \/]([\w.]+)/.exec(ua) ||
+ /(webkit)[ \/]([\w.]+)/.exec(ua) ||
+ /(opera)(?:.*version|)[ \/]([\w.]+)/.exec(ua) ||
+ /(msie) ([\w.]+)/.exec(ua) ||
+ ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec(ua) ||
+ [];
+
+ return {
+ browser: match[ 1 ] || "",
+ version: match[ 2 ] || "0"
+ };
+ };
+ jQuery.browser = {};
+ jQuery.browser[jQuery.uaMatch(navigator.userAgent).browser] = true;
+}
+
+/**
+ * Small JavaScript module for the documentation.
+ */
+var Documentation = {
+
+ init : function() {
+ this.fixFirefoxAnchorBug();
+ this.highlightSearchWords();
+ this.initIndexTable();
+
+ },
+
+ /**
+ * i18n support
+ */
+ TRANSLATIONS : {},
+ PLURAL_EXPR : function(n) { return n == 1 ? 0 : 1; },
+ LOCALE : 'unknown',
+
+ // gettext and ngettext don't access this so that the functions
+ // can safely bound to a different name (_ = Documentation.gettext)
+ gettext : function(string) {
+ var translated = Documentation.TRANSLATIONS[string];
+ if (typeof translated == 'undefined')
+ return string;
+ return (typeof translated == 'string') ? translated : translated[0];
+ },
+
+ ngettext : function(singular, plural, n) {
+ var translated = Documentation.TRANSLATIONS[singular];
+ if (typeof translated == 'undefined')
+ return (n == 1) ? singular : plural;
+ return translated[Documentation.PLURALEXPR(n)];
+ },
+
+ addTranslations : function(catalog) {
+ for (var key in catalog.messages)
+ this.TRANSLATIONS[key] = catalog.messages[key];
+ this.PLURAL_EXPR = new Function('n', 'return +(' + catalog.plural_expr + ')');
+ this.LOCALE = catalog.locale;
+ },
+
+ /**
+ * add context elements like header anchor links
+ */
+ addContextElements : function() {
+ $('div[id] > :header:first').each(function() {
+ $('<a class="headerlink">\u00B6</a>').
+ attr('href', '#' + this.id).
+ attr('title', _('Permalink to this headline')).
+ appendTo(this);
+ });
+ $('dt[id]').each(function() {
+ $('<a class="headerlink">\u00B6</a>').
+ attr('href', '#' + this.id).
+ attr('title', _('Permalink to this definition')).
+ appendTo(this);
+ });
+ },
+
+ /**
+ * workaround a firefox stupidity
+ * see: https://bugzilla.mozilla.org/show_bug.cgi?id=645075
+ */
+ fixFirefoxAnchorBug : function() {
+ if (document.location.hash)
+ window.setTimeout(function() {
+ document.location.href += '';
+ }, 10);
+ },
+
+ /**
+ * highlight the search words provided in the url in the text
+ */
+ highlightSearchWords : function() {
+ var params = $.getQueryParameters();
+ var terms = (params.highlight) ? params.highlight[0].split(/\s+/) : [];
+ if (terms.length) {
+ var body = $('div.body');
+ if (!body.length) {
+ body = $('body');
+ }
+ window.setTimeout(function() {
+ $.each(terms, function() {
+ body.highlightText(this.toLowerCase(), 'highlighted');
+ });
+ }, 10);
+ $('<p class="highlight-link"><a href="javascript:Documentation.' +
+ 'hideSearchWords()">' + _('Hide Search Matches') + '</a></p>')
+ .appendTo($('#searchbox'));
+ }
+ },
+
+ /**
+ * init the domain index toggle buttons
+ */
+ initIndexTable : function() {
+ var togglers = $('img.toggler').click(function() {
+ var src = $(this).attr('src');
+ var idnum = $(this).attr('id').substr(7);
+ $('tr.cg-' + idnum).toggle();
+ if (src.substr(-9) == 'minus.png')
+ $(this).attr('src', src.substr(0, src.length-9) + 'plus.png');
+ else
+ $(this).attr('src', src.substr(0, src.length-8) + 'minus.png');
+ }).css('display', '');
+ if (DOCUMENTATION_OPTIONS.COLLAPSE_INDEX) {
+ togglers.click();
+ }
+ },
+
+ /**
+ * helper function to hide the search marks again
+ */
+ hideSearchWords : function() {
+ $('#searchbox .highlight-link').fadeOut(300);
+ $('span.highlighted').removeClass('highlighted');
+ },
+
+ /**
+ * make the url absolute
+ */
+ makeURL : function(relativeURL) {
+ return DOCUMENTATION_OPTIONS.URL_ROOT + '/' + relativeURL;
+ },
+
+ /**
+ * get the current relative url
+ */
+ getCurrentURL : function() {
+ var path = document.location.pathname;
+ var parts = path.split(/\//);
+ $.each(DOCUMENTATION_OPTIONS.URL_ROOT.split(/\//), function() {
+ if (this == '..')
+ parts.pop();
+ });
+ var url = parts.join('/');
+ return path.substring(url.lastIndexOf('/') + 1, path.length - 1);
+ },
+
+ initOnKeyListeners: function() {
+ $(document).keyup(function(event) {
+ var activeElementType = document.activeElement.tagName;
+ // don't navigate when in search box or textarea
+ if (activeElementType !== 'TEXTAREA' && activeElementType !== 'INPUT' && activeElementType !== 'SELECT') {
+ switch (event.keyCode) {
+ case 37: // left
+ var prevHref = $('link[rel="prev"]').prop('href');
+ if (prevHref) {
+ window.location.href = prevHref;
+ return false;
+ }
+ case 39: // right
+ var nextHref = $('link[rel="next"]').prop('href');
+ if (nextHref) {
+ window.location.href = nextHref;
+ return false;
+ }
+ }
+ }
+ });
+ }
+};
+
+// quick alias for translations
+_ = Documentation.gettext;
+
+$(document).ready(function() {
+ Documentation.init();
+});
\ No newline at end of file
diff --git a/doc/build/_static/down-pressed.png b/doc/build/_static/down-pressed.png
new file mode 100644
index 0000000..7c30d00
Binary files /dev/null and b/doc/build/_static/down-pressed.png differ
diff --git a/doc/build/_static/down.png b/doc/build/_static/down.png
new file mode 100644
index 0000000..f48098a
Binary files /dev/null and b/doc/build/_static/down.png differ
diff --git a/doc/build/_static/file.png b/doc/build/_static/file.png
new file mode 100644
index 0000000..254c60b
Binary files /dev/null and b/doc/build/_static/file.png differ
diff --git a/doc/build/_static/jquery-1.11.1.js b/doc/build/_static/jquery-1.11.1.js
new file mode 100644
index 0000000..d4b67f7
--- /dev/null
+++ b/doc/build/_static/jquery-1.11.1.js
@@ -0,0 +1,10308 @@
+/*!
+ * jQuery JavaScript Library v1.11.1
+ * http://jquery.com/
+ *
+ * Includes Sizzle.js
+ * http://sizzlejs.com/
+ *
+ * Copyright 2005, 2014 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2014-05-01T17:42Z
+ */
+
+(function( global, factory ) {
+
+ if ( typeof module === "object" && typeof module.exports === "object" ) {
+ // For CommonJS and CommonJS-like environments where a proper window is present,
+ // execute the factory and get jQuery
+ // For environments that do not inherently posses a window with a document
+ // (such as Node.js), expose a jQuery-making factory as module.exports
+ // This accentuates the need for the creation of a real window
+ // e.g. var jQuery = require("jquery")(window);
+ // See ticket #14549 for more info
+ module.exports = global.document ?
+ factory( global, true ) :
+ function( w ) {
+ if ( !w.document ) {
+ throw new Error( "jQuery requires a window with a document" );
+ }
+ return factory( w );
+ };
+ } else {
+ factory( global );
+ }
+
+// Pass this if window is not defined yet
+}(typeof window !== "undefined" ? window : this, function( window, noGlobal ) {
+
+// Can't do this because several apps including ASP.NET trace
+// the stack via arguments.caller.callee and Firefox dies if
+// you try to trace through "use strict" call chains. (#13335)
+// Support: Firefox 18+
+//
+
+var deletedIds = [];
+
+var slice = deletedIds.slice;
+
+var concat = deletedIds.concat;
+
+var push = deletedIds.push;
+
+var indexOf = deletedIds.indexOf;
+
+var class2type = {};
+
+var toString = class2type.toString;
+
+var hasOwn = class2type.hasOwnProperty;
+
+var support = {};
+
+
+
+var
+ version = "1.11.1",
+
+ // Define a local copy of jQuery
+ jQuery = function( selector, context ) {
+ // The jQuery object is actually just the init constructor 'enhanced'
+ // Need init if jQuery is called (just allow error to be thrown if not included)
+ return new jQuery.fn.init( selector, context );
+ },
+
+ // Support: Android<4.1, IE<9
+ // Make sure we trim BOM and NBSP
+ rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,
+
+ // Matches dashed string for camelizing
+ rmsPrefix = /^-ms-/,
+ rdashAlpha = /-([\da-z])/gi,
+
+ // Used by jQuery.camelCase as callback to replace()
+ fcamelCase = function( all, letter ) {
+ return letter.toUpperCase();
+ };
+
+jQuery.fn = jQuery.prototype = {
+ // The current version of jQuery being used
+ jquery: version,
+
+ constructor: jQuery,
+
+ // Start with an empty selector
+ selector: "",
+
+ // The default length of a jQuery object is 0
+ length: 0,
+
+ toArray: function() {
+ return slice.call( this );
+ },
+
+ // Get the Nth element in the matched element set OR
+ // Get the whole matched element set as a clean array
+ get: function( num ) {
+ return num != null ?
+
+ // Return just the one element from the set
+ ( num < 0 ? this[ num + this.length ] : this[ num ] ) :
+
+ // Return all the elements in a clean array
+ slice.call( this );
+ },
+
+ // Take an array of elements and push it onto the stack
+ // (returning the new matched element set)
+ pushStack: function( elems ) {
+
+ // Build a new jQuery matched element set
+ var ret = jQuery.merge( this.constructor(), elems );
+
+ // Add the old object onto the stack (as a reference)
+ ret.prevObject = this;
+ ret.context = this.context;
+
+ // Return the newly-formed element set
+ return ret;
+ },
+
+ // Execute a callback for every element in the matched set.
+ // (You can seed the arguments with an array of args, but this is
+ // only used internally.)
+ each: function( callback, args ) {
+ return jQuery.each( this, callback, args );
+ },
+
+ map: function( callback ) {
+ return this.pushStack( jQuery.map(this, function( elem, i ) {
+ return callback.call( elem, i, elem );
+ }));
+ },
+
+ slice: function() {
+ return this.pushStack( slice.apply( this, arguments ) );
+ },
+
+ first: function() {
+ return this.eq( 0 );
+ },
+
+ last: function() {
+ return this.eq( -1 );
+ },
+
+ eq: function( i ) {
+ var len = this.length,
+ j = +i + ( i < 0 ? len : 0 );
+ return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] );
+ },
+
+ end: function() {
+ return this.prevObject || this.constructor(null);
+ },
+
+ // For internal use only.
+ // Behaves like an Array's method, not like a jQuery method.
+ push: push,
+ sort: deletedIds.sort,
+ splice: deletedIds.splice
+};
+
+jQuery.extend = jQuery.fn.extend = function() {
+ var src, copyIsArray, copy, name, options, clone,
+ target = arguments[0] || {},
+ i = 1,
+ length = arguments.length,
+ deep = false;
+
+ // Handle a deep copy situation
+ if ( typeof target === "boolean" ) {
+ deep = target;
+
+ // skip the boolean and the target
+ target = arguments[ i ] || {};
+ i++;
+ }
+
+ // Handle case when target is a string or something (possible in deep copy)
+ if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
+ target = {};
+ }
+
+ // extend jQuery itself if only one argument is passed
+ if ( i === length ) {
+ target = this;
+ i--;
+ }
+
+ for ( ; i < length; i++ ) {
+ // Only deal with non-null/undefined values
+ if ( (options = arguments[ i ]) != null ) {
+ // Extend the base object
+ for ( name in options ) {
+ src = target[ name ];
+ copy = options[ name ];
+
+ // Prevent never-ending loop
+ if ( target === copy ) {
+ continue;
+ }
+
+ // Recurse if we're merging plain objects or arrays
+ if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
+ if ( copyIsArray ) {
+ copyIsArray = false;
+ clone = src && jQuery.isArray(src) ? src : [];
+
+ } else {
+ clone = src && jQuery.isPlainObject(src) ? src : {};
+ }
+
+ // Never move original objects, clone them
+ target[ name ] = jQuery.extend( deep, clone, copy );
+
+ // Don't bring in undefined values
+ } else if ( copy !== undefined ) {
+ target[ name ] = copy;
+ }
+ }
+ }
+ }
+
+ // Return the modified object
+ return target;
+};
+
+jQuery.extend({
+ // Unique for each copy of jQuery on the page
+ expando: "jQuery" + ( version + Math.random() ).replace( /\D/g, "" ),
+
+ // Assume jQuery is ready without the ready module
+ isReady: true,
+
+ error: function( msg ) {
+ throw new Error( msg );
+ },
+
+ noop: function() {},
+
+ // See test/unit/core.js for details concerning isFunction.
+ // Since version 1.3, DOM methods and functions like alert
+ // aren't supported. They return false on IE (#2968).
+ isFunction: function( obj ) {
+ return jQuery.type(obj) === "function";
+ },
+
+ isArray: Array.isArray || function( obj ) {
+ return jQuery.type(obj) === "array";
+ },
+
+ isWindow: function( obj ) {
+ /* jshint eqeqeq: false */
+ return obj != null && obj == obj.window;
+ },
+
+ isNumeric: function( obj ) {
+ // parseFloat NaNs numeric-cast false positives (null|true|false|"")
+ // ...but misinterprets leading-number strings, particularly hex literals ("0x...")
+ // subtraction forces infinities to NaN
+ return !jQuery.isArray( obj ) && obj - parseFloat( obj ) >= 0;
+ },
+
+ isEmptyObject: function( obj ) {
+ var name;
+ for ( name in obj ) {
+ return false;
+ }
+ return true;
+ },
+
+ isPlainObject: function( obj ) {
+ var key;
+
+ // Must be an Object.
+ // Because of IE, we also have to check the presence of the constructor property.
+ // Make sure that DOM nodes and window objects don't pass through, as well
+ if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
+ return false;
+ }
+
+ try {
+ // Not own constructor property must be Object
+ if ( obj.constructor &&
+ !hasOwn.call(obj, "constructor") &&
+ !hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
+ return false;
+ }
+ } catch ( e ) {
+ // IE8,9 Will throw exceptions on certain host objects #9897
+ return false;
+ }
+
+ // Support: IE<9
+ // Handle iteration over inherited properties before own properties.
+ if ( support.ownLast ) {
+ for ( key in obj ) {
+ return hasOwn.call( obj, key );
+ }
+ }
+
+ // Own properties are enumerated firstly, so to speed up,
+ // if last one is own, then all properties are own.
+ for ( key in obj ) {}
+
+ return key === undefined || hasOwn.call( obj, key );
+ },
+
+ type: function( obj ) {
+ if ( obj == null ) {
+ return obj + "";
+ }
+ return typeof obj === "object" || typeof obj === "function" ?
+ class2type[ toString.call(obj) ] || "object" :
+ typeof obj;
+ },
+
+ // Evaluates a script in a global context
+ // Workarounds based on findings by Jim Driscoll
+ // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
+ globalEval: function( data ) {
+ if ( data && jQuery.trim( data ) ) {
+ // We use execScript on Internet Explorer
+ // We use an anonymous function so that context is window
+ // rather than jQuery in Firefox
+ ( window.execScript || function( data ) {
+ window[ "eval" ].call( window, data );
+ } )( data );
+ }
+ },
+
+ // Convert dashed to camelCase; used by the css and data modules
+ // Microsoft forgot to hump their vendor prefix (#9572)
+ camelCase: function( string ) {
+ return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
+ },
+
+ nodeName: function( elem, name ) {
+ return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase();
+ },
+
+ // args is for internal usage only
+ each: function( obj, callback, args ) {
+ var value,
+ i = 0,
+ length = obj.length,
+ isArray = isArraylike( obj );
+
+ if ( args ) {
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback.apply( obj[ i ], args );
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( i in obj ) {
+ value = callback.apply( obj[ i ], args );
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ }
+
+ // A special, fast, case for the most common use of each
+ } else {
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback.call( obj[ i ], i, obj[ i ] );
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ } else {
+ for ( i in obj ) {
+ value = callback.call( obj[ i ], i, obj[ i ] );
+
+ if ( value === false ) {
+ break;
+ }
+ }
+ }
+ }
+
+ return obj;
+ },
+
+ // Support: Android<4.1, IE<9
+ trim: function( text ) {
+ return text == null ?
+ "" :
+ ( text + "" ).replace( rtrim, "" );
+ },
+
+ // results is for internal usage only
+ makeArray: function( arr, results ) {
+ var ret = results || [];
+
+ if ( arr != null ) {
+ if ( isArraylike( Object(arr) ) ) {
+ jQuery.merge( ret,
+ typeof arr === "string" ?
+ [ arr ] : arr
+ );
+ } else {
+ push.call( ret, arr );
+ }
+ }
+
+ return ret;
+ },
+
+ inArray: function( elem, arr, i ) {
+ var len;
+
+ if ( arr ) {
+ if ( indexOf ) {
+ return indexOf.call( arr, elem, i );
+ }
+
+ len = arr.length;
+ i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
+
+ for ( ; i < len; i++ ) {
+ // Skip accessing in sparse arrays
+ if ( i in arr && arr[ i ] === elem ) {
+ return i;
+ }
+ }
+ }
+
+ return -1;
+ },
+
+ merge: function( first, second ) {
+ var len = +second.length,
+ j = 0,
+ i = first.length;
+
+ while ( j < len ) {
+ first[ i++ ] = second[ j++ ];
+ }
+
+ // Support: IE<9
+ // Workaround casting of .length to NaN on otherwise arraylike objects (e.g., NodeLists)
+ if ( len !== len ) {
+ while ( second[j] !== undefined ) {
+ first[ i++ ] = second[ j++ ];
+ }
+ }
+
+ first.length = i;
+
+ return first;
+ },
+
+ grep: function( elems, callback, invert ) {
+ var callbackInverse,
+ matches = [],
+ i = 0,
+ length = elems.length,
+ callbackExpect = !invert;
+
+ // Go through the array, only saving the items
+ // that pass the validator function
+ for ( ; i < length; i++ ) {
+ callbackInverse = !callback( elems[ i ], i );
+ if ( callbackInverse !== callbackExpect ) {
+ matches.push( elems[ i ] );
+ }
+ }
+
+ return matches;
+ },
+
+ // arg is for internal usage only
+ map: function( elems, callback, arg ) {
+ var value,
+ i = 0,
+ length = elems.length,
+ isArray = isArraylike( elems ),
+ ret = [];
+
+ // Go through the array, translating each of the items to their new values
+ if ( isArray ) {
+ for ( ; i < length; i++ ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret.push( value );
+ }
+ }
+
+ // Go through every key on the object,
+ } else {
+ for ( i in elems ) {
+ value = callback( elems[ i ], i, arg );
+
+ if ( value != null ) {
+ ret.push( value );
+ }
+ }
+ }
+
+ // Flatten any nested arrays
+ return concat.apply( [], ret );
+ },
+
+ // A global GUID counter for objects
+ guid: 1,
+
+ // Bind a function to a context, optionally partially applying any
+ // arguments.
+ proxy: function( fn, context ) {
+ var args, proxy, tmp;
+
+ if ( typeof context === "string" ) {
+ tmp = fn[ context ];
+ context = fn;
+ fn = tmp;
+ }
+
+ // Quick check to determine if target is callable, in the spec
+ // this throws a TypeError, but we will just return undefined.
+ if ( !jQuery.isFunction( fn ) ) {
+ return undefined;
+ }
+
+ // Simulated bind
+ args = slice.call( arguments, 2 );
+ proxy = function() {
+ return fn.apply( context || this, args.concat( slice.call( arguments ) ) );
+ };
+
+ // Set the guid of unique handler to the same of original handler, so it can be removed
+ proxy.guid = fn.guid = fn.guid || jQuery.guid++;
+
+ return proxy;
+ },
+
+ now: function() {
+ return +( new Date() );
+ },
+
+ // jQuery.support is not used in Core but other projects attach their
+ // properties to it so it needs to exist.
+ support: support
+});
+
+// Populate the class2type map
+jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) {
+ class2type[ "[object " + name + "]" ] = name.toLowerCase();
+});
+
+function isArraylike( obj ) {
+ var length = obj.length,
+ type = jQuery.type( obj );
+
+ if ( type === "function" || jQuery.isWindow( obj ) ) {
+ return false;
+ }
+
+ if ( obj.nodeType === 1 && length ) {
+ return true;
+ }
+
+ return type === "array" || length === 0 ||
+ typeof length === "number" && length > 0 && ( length - 1 ) in obj;
+}
+var Sizzle =
+/*!
+ * Sizzle CSS Selector Engine v1.10.19
+ * http://sizzlejs.com/
+ *
+ * Copyright 2013 jQuery Foundation, Inc. and other contributors
+ * Released under the MIT license
+ * http://jquery.org/license
+ *
+ * Date: 2014-04-18
+ */
+(function( window ) {
+
+var i,
+ support,
+ Expr,
+ getText,
+ isXML,
+ tokenize,
+ compile,
+ select,
+ outermostContext,
+ sortInput,
+ hasDuplicate,
+
+ // Local document vars
+ setDocument,
+ document,
+ docElem,
+ documentIsHTML,
+ rbuggyQSA,
+ rbuggyMatches,
+ matches,
+ contains,
+
+ // Instance-specific data
+ expando = "sizzle" + -(new Date()),
+ preferredDoc = window.document,
+ dirruns = 0,
+ done = 0,
+ classCache = createCache(),
+ tokenCache = createCache(),
+ compilerCache = createCache(),
+ sortOrder = function( a, b ) {
+ if ( a === b ) {
+ hasDuplicate = true;
+ }
+ return 0;
+ },
+
+ // General-purpose constants
+ strundefined = typeof undefined,
+ MAX_NEGATIVE = 1 << 31,
+
+ // Instance methods
+ hasOwn = ({}).hasOwnProperty,
+ arr = [],
+ pop = arr.pop,
+ push_native = arr.push,
+ push = arr.push,
+ slice = arr.slice,
+ // Use a stripped-down indexOf if we can't use a native one
+ indexOf = arr.indexOf || function( elem ) {
+ var i = 0,
+ len = this.length;
+ for ( ; i < len; i++ ) {
+ if ( this[i] === elem ) {
+ return i;
+ }
+ }
+ return -1;
+ },
+
+ booleans = "checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",
+
+ // Regular expressions
+
+ // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace
+ whitespace = "[\\x20\\t\\r\\n\\f]",
+ // http://www.w3.org/TR/css3-syntax/#characters
+ characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",
+
+ // Loosely modeled on CSS identifier characters
+ // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors
+ // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier
+ identifier = characterEncoding.replace( "w", "w#" ),
+
+ // Attribute selectors: http://www.w3.org/TR/selectors/#attribute-selectors
+ attributes = "\\[" + whitespace + "*(" + characterEncoding + ")(?:" + whitespace +
+ // Operator (capture 2)
+ "*([*^$|!~]?=)" + whitespace +
+ // "Attribute values must be CSS identifiers [capture 5] or strings [capture 3 or capture 4]"
+ "*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|(" + identifier + "))|)" + whitespace +
+ "*\\]",
+
+ pseudos = ":(" + characterEncoding + ")(?:\\((" +
+ // To reduce the number of selectors needing tokenize in the preFilter, prefer arguments:
+ // 1. quoted (capture 3; capture 4 or capture 5)
+ "('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|" +
+ // 2. simple (capture 6)
+ "((?:\\\\.|[^\\\\()[\\]]|" + attributes + ")*)|" +
+ // 3. anything else (capture 2)
+ ".*" +
+ ")\\)|)",
+
+ // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter
+ rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ),
+
+ rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ),
+ rcombinators = new RegExp( "^" + whitespace + "*([>+~]|" + whitespace + ")" + whitespace + "*" ),
+
+ rattributeQuotes = new RegExp( "=" + whitespace + "*([^\\]'\"]*?)" + whitespace + "*\\]", "g" ),
+
+ rpseudo = new RegExp( pseudos ),
+ ridentifier = new RegExp( "^" + identifier + "$" ),
+
+ matchExpr = {
+ "ID": new RegExp( "^#(" + characterEncoding + ")" ),
+ "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ),
+ "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ),
+ "ATTR": new RegExp( "^" + attributes ),
+ "PSEUDO": new RegExp( "^" + pseudos ),
+ "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace +
+ "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace +
+ "*(\\d+)|))" + whitespace + "*\\)|)", "i" ),
+ "bool": new RegExp( "^(?:" + booleans + ")$", "i" ),
+ // For use in libraries implementing .is()
+ // We use this for POS matching in `select`
+ "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" +
+ whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" )
+ },
+
+ rinputs = /^(?:input|select|textarea|button)$/i,
+ rheader = /^h\d$/i,
+
+ rnative = /^[^{]+\{\s*\[native \w/,
+
+ // Easily-parseable/retrievable ID or TAG or CLASS selectors
+ rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,
+
+ rsibling = /[+~]/,
+ rescape = /'|\\/g,
+
+ // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters
+ runescape = new RegExp( "\\\\([\\da-f]{1,6}" + whitespace + "?|(" + whitespace + ")|.)", "ig" ),
+ funescape = function( _, escaped, escapedWhitespace ) {
+ var high = "0x" + escaped - 0x10000;
+ // NaN means non-codepoint
+ // Support: Firefox<24
+ // Workaround erroneous numeric interpretation of +"0x"
+ return high !== high || escapedWhitespace ?
+ escaped :
+ high < 0 ?
+ // BMP codepoint
+ String.fromCharCode( high + 0x10000 ) :
+ // Supplemental Plane codepoint (surrogate pair)
+ String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 );
+ };
+
+// Optimize for push.apply( _, NodeList )
+try {
+ push.apply(
+ (arr = slice.call( preferredDoc.childNodes )),
+ preferredDoc.childNodes
+ );
+ // Support: Android<4.0
+ // Detect silently failing push.apply
+ arr[ preferredDoc.childNodes.length ].nodeType;
+} catch ( e ) {
+ push = { apply: arr.length ?
+
+ // Leverage slice if possible
+ function( target, els ) {
+ push_native.apply( target, slice.call(els) );
+ } :
+
+ // Support: IE<9
+ // Otherwise append directly
+ function( target, els ) {
+ var j = target.length,
+ i = 0;
+ // Can't trust NodeList.length
+ while ( (target[j++] = els[i++]) ) {}
+ target.length = j - 1;
+ }
+ };
+}
+
+function Sizzle( selector, context, results, seed ) {
+ var match, elem, m, nodeType,
+ // QSA vars
+ i, groups, old, nid, newContext, newSelector;
+
+ if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) {
+ setDocument( context );
+ }
+
+ context = context || document;
+ results = results || [];
+
+ if ( !selector || typeof selector !== "string" ) {
+ return results;
+ }
+
+ if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) {
+ return [];
+ }
+
+ if ( documentIsHTML && !seed ) {
+
+ // Shortcuts
+ if ( (match = rquickExpr.exec( selector )) ) {
+ // Speed-up: Sizzle("#ID")
+ if ( (m = match[1]) ) {
+ if ( nodeType === 9 ) {
+ elem = context.getElementById( m );
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document (jQuery #6963)
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE, Opera, and Webkit return items
+ // by name instead of ID
+ if ( elem.id === m ) {
+ results.push( elem );
+ return results;
+ }
+ } else {
+ return results;
+ }
+ } else {
+ // Context is not a document
+ if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) &&
+ contains( context, elem ) && elem.id === m ) {
+ results.push( elem );
+ return results;
+ }
+ }
+
+ // Speed-up: Sizzle("TAG")
+ } else if ( match[2] ) {
+ push.apply( results, context.getElementsByTagName( selector ) );
+ return results;
+
+ // Speed-up: Sizzle(".CLASS")
+ } else if ( (m = match[3]) && support.getElementsByClassName && context.getElementsByClassName ) {
+ push.apply( results, context.getElementsByClassName( m ) );
+ return results;
+ }
+ }
+
+ // QSA path
+ if ( support.qsa && (!rbuggyQSA || !rbuggyQSA.test( selector )) ) {
+ nid = old = expando;
+ newContext = context;
+ newSelector = nodeType === 9 && selector;
+
+ // qSA works strangely on Element-rooted queries
+ // We can work around this by specifying an extra ID on the root
+ // and working up from there (Thanks to Andrew Dupont for the technique)
+ // IE 8 doesn't work on object elements
+ if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
+ groups = tokenize( selector );
+
+ if ( (old = context.getAttribute("id")) ) {
+ nid = old.replace( rescape, "\\$&" );
+ } else {
+ context.setAttribute( "id", nid );
+ }
+ nid = "[id='" + nid + "'] ";
+
+ i = groups.length;
+ while ( i-- ) {
+ groups[i] = nid + toSelector( groups[i] );
+ }
+ newContext = rsibling.test( selector ) && testContext( context.parentNode ) || context;
+ newSelector = groups.join(",");
+ }
+
+ if ( newSelector ) {
+ try {
+ push.apply( results,
+ newContext.querySelectorAll( newSelector )
+ );
+ return results;
+ } catch(qsaError) {
+ } finally {
+ if ( !old ) {
+ context.removeAttribute("id");
+ }
+ }
+ }
+ }
+ }
+
+ // All others
+ return select( selector.replace( rtrim, "$1" ), context, results, seed );
+}
+
+/**
+ * Create key-value caches of limited size
+ * @returns {Function(string, Object)} Returns the Object data after storing it on itself with
+ * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength)
+ * deleting the oldest entry
+ */
+function createCache() {
+ var keys = [];
+
+ function cache( key, value ) {
+ // Use (key + " ") to avoid collision with native prototype properties (see Issue #157)
+ if ( keys.push( key + " " ) > Expr.cacheLength ) {
+ // Only keep the most recent entries
+ delete cache[ keys.shift() ];
+ }
+ return (cache[ key + " " ] = value);
+ }
+ return cache;
+}
+
+/**
+ * Mark a function for special use by Sizzle
+ * @param {Function} fn The function to mark
+ */
+function markFunction( fn ) {
+ fn[ expando ] = true;
+ return fn;
+}
+
+/**
+ * Support testing using an element
+ * @param {Function} fn Passed the created div and expects a boolean result
+ */
+function assert( fn ) {
+ var div = document.createElement("div");
+
+ try {
+ return !!fn( div );
+ } catch (e) {
+ return false;
+ } finally {
+ // Remove from its parent by default
+ if ( div.parentNode ) {
+ div.parentNode.removeChild( div );
+ }
+ // release memory in IE
+ div = null;
+ }
+}
+
+/**
+ * Adds the same handler for all of the specified attrs
+ * @param {String} attrs Pipe-separated list of attributes
+ * @param {Function} handler The method that will be applied
+ */
+function addHandle( attrs, handler ) {
+ var arr = attrs.split("|"),
+ i = attrs.length;
+
+ while ( i-- ) {
+ Expr.attrHandle[ arr[i] ] = handler;
+ }
+}
+
+/**
+ * Checks document order of two siblings
+ * @param {Element} a
+ * @param {Element} b
+ * @returns {Number} Returns less than 0 if a precedes b, greater than 0 if a follows b
+ */
+function siblingCheck( a, b ) {
+ var cur = b && a,
+ diff = cur && a.nodeType === 1 && b.nodeType === 1 &&
+ ( ~b.sourceIndex || MAX_NEGATIVE ) -
+ ( ~a.sourceIndex || MAX_NEGATIVE );
+
+ // Use IE sourceIndex if available on both nodes
+ if ( diff ) {
+ return diff;
+ }
+
+ // Check if b follows a
+ if ( cur ) {
+ while ( (cur = cur.nextSibling) ) {
+ if ( cur === b ) {
+ return -1;
+ }
+ }
+ }
+
+ return a ? 1 : -1;
+}
+
+/**
+ * Returns a function to use in pseudos for input types
+ * @param {String} type
+ */
+function createInputPseudo( type ) {
+ return function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return name === "input" && elem.type === type;
+ };
+}
+
+/**
+ * Returns a function to use in pseudos for buttons
+ * @param {String} type
+ */
+function createButtonPseudo( type ) {
+ return function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return (name === "input" || name === "button") && elem.type === type;
+ };
+}
+
+/**
+ * Returns a function to use in pseudos for positionals
+ * @param {Function} fn
+ */
+function createPositionalPseudo( fn ) {
+ return markFunction(function( argument ) {
+ argument = +argument;
+ return markFunction(function( seed, matches ) {
+ var j,
+ matchIndexes = fn( [], seed.length, argument ),
+ i = matchIndexes.length;
+
+ // Match elements found at the specified indexes
+ while ( i-- ) {
+ if ( seed[ (j = matchIndexes[i]) ] ) {
+ seed[j] = !(matches[j] = seed[j]);
+ }
+ }
+ });
+ });
+}
+
+/**
+ * Checks a node for validity as a Sizzle context
+ * @param {Element|Object=} context
+ * @returns {Element|Object|Boolean} The input node if acceptable, otherwise a falsy value
+ */
+function testContext( context ) {
+ return context && typeof context.getElementsByTagName !== strundefined && context;
+}
+
+// Expose support vars for convenience
+support = Sizzle.support = {};
+
+/**
+ * Detects XML nodes
+ * @param {Element|Object} elem An element or a document
+ * @returns {Boolean} True iff elem is a non-HTML XML node
+ */
+isXML = Sizzle.isXML = function( elem ) {
+ // documentElement is verified for cases where it doesn't yet exist
+ // (such as loading iframes in IE - #4833)
+ var documentElement = elem && (elem.ownerDocument || elem).documentElement;
+ return documentElement ? documentElement.nodeName !== "HTML" : false;
+};
+
+/**
+ * Sets document-related variables once based on the current document
+ * @param {Element|Object} [doc] An element or document object to use to set the document
+ * @returns {Object} Returns the current document
+ */
+setDocument = Sizzle.setDocument = function( node ) {
+ var hasCompare,
+ doc = node ? node.ownerDocument || node : preferredDoc,
+ parent = doc.defaultView;
+
+ // If no document and documentElement is available, return
+ if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) {
+ return document;
+ }
+
+ // Set our document
+ document = doc;
+ docElem = doc.documentElement;
+
+ // Support tests
+ documentIsHTML = !isXML( doc );
+
+ // Support: IE>8
+ // If iframe document is assigned to "document" variable and if iframe has been reloaded,
+ // IE will throw "permission denied" error when accessing "document" variable, see jQuery #13936
+ // IE6-8 do not support the defaultView property so parent will be undefined
+ if ( parent && parent !== parent.top ) {
+ // IE11 does not have attachEvent, so all must suffer
+ if ( parent.addEventListener ) {
+ parent.addEventListener( "unload", function() {
+ setDocument();
+ }, false );
+ } else if ( parent.attachEvent ) {
+ parent.attachEvent( "onunload", function() {
+ setDocument();
+ });
+ }
+ }
+
+ /* Attributes
+ ---------------------------------------------------------------------- */
+
+ // Support: IE<8
+ // Verify that getAttribute really returns attributes and not properties (excepting IE8 booleans)
+ support.attributes = assert(function( div ) {
+ div.className = "i";
+ return !div.getAttribute("className");
+ });
+
+ /* getElement(s)By*
+ ---------------------------------------------------------------------- */
+
+ // Check if getElementsByTagName("*") returns only elements
+ support.getElementsByTagName = assert(function( div ) {
+ div.appendChild( doc.createComment("") );
+ return !div.getElementsByTagName("*").length;
+ });
+
+ // Check if getElementsByClassName can be trusted
+ support.getElementsByClassName = rnative.test( doc.getElementsByClassName ) && assert(function( div ) {
+ div.innerHTML = "<div class='a'></div><div class='a i'></div>";
+
+ // Support: Safari<4
+ // Catch class over-caching
+ div.firstChild.className = "i";
+ // Support: Opera<10
+ // Catch gEBCN failure to find non-leading classes
+ return div.getElementsByClassName("i").length === 2;
+ });
+
+ // Support: IE<10
+ // Check if getElementById returns elements by name
+ // The broken getElementById methods don't pick up programatically-set names,
+ // so use a roundabout getElementsByName test
+ support.getById = assert(function( div ) {
+ docElem.appendChild( div ).id = expando;
+ return !doc.getElementsByName || !doc.getElementsByName( expando ).length;
+ });
+
+ // ID find and filter
+ if ( support.getById ) {
+ Expr.find["ID"] = function( id, context ) {
+ if ( typeof context.getElementById !== strundefined && documentIsHTML ) {
+ var m = context.getElementById( id );
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ return m && m.parentNode ? [ m ] : [];
+ }
+ };
+ Expr.filter["ID"] = function( id ) {
+ var attrId = id.replace( runescape, funescape );
+ return function( elem ) {
+ return elem.getAttribute("id") === attrId;
+ };
+ };
+ } else {
+ // Support: IE6/7
+ // getElementById is not reliable as a find shortcut
+ delete Expr.find["ID"];
+
+ Expr.filter["ID"] = function( id ) {
+ var attrId = id.replace( runescape, funescape );
+ return function( elem ) {
+ var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id");
+ return node && node.value === attrId;
+ };
+ };
+ }
+
+ // Tag
+ Expr.find["TAG"] = support.getElementsByTagName ?
+ function( tag, context ) {
+ if ( typeof context.getElementsByTagName !== strundefined ) {
+ return context.getElementsByTagName( tag );
+ }
+ } :
+ function( tag, context ) {
+ var elem,
+ tmp = [],
+ i = 0,
+ results = context.getElementsByTagName( tag );
+
+ // Filter out possible comments
+ if ( tag === "*" ) {
+ while ( (elem = results[i++]) ) {
+ if ( elem.nodeType === 1 ) {
+ tmp.push( elem );
+ }
+ }
+
+ return tmp;
+ }
+ return results;
+ };
+
+ // Class
+ Expr.find["CLASS"] = support.getElementsByClassName && function( className, context ) {
+ if ( typeof context.getElementsByClassName !== strundefined && documentIsHTML ) {
+ return context.getElementsByClassName( className );
+ }
+ };
+
+ /* QSA/matchesSelector
+ ---------------------------------------------------------------------- */
+
+ // QSA and matchesSelector support
+
+ // matchesSelector(:active) reports false when true (IE9/Opera 11.5)
+ rbuggyMatches = [];
+
+ // qSa(:focus) reports false when true (Chrome 21)
+ // We allow this because of a bug in IE8/9 that throws an error
+ // whenever `document.activeElement` is accessed on an iframe
+ // So, we allow :focus to pass through QSA all the time to avoid the IE error
+ // See http://bugs.jquery.com/ticket/13378
+ rbuggyQSA = [];
+
+ if ( (support.qsa = rnative.test( doc.querySelectorAll )) ) {
+ // Build QSA regex
+ // Regex strategy adopted from Diego Perini
+ assert(function( div ) {
+ // Select is set to empty string on purpose
+ // This is to test IE's treatment of not explicitly
+ // setting a boolean content attribute,
+ // since its presence should be enough
+ // http://bugs.jquery.com/ticket/12359
+ div.innerHTML = "<select msallowclip=''><option selected=''></option></select>";
+
+ // Support: IE8, Opera 11-12.16
+ // Nothing should be selected when empty strings follow ^= or $= or *=
+ // The test attribute must be unknown in Opera but "safe" for WinRT
+ // http://msdn.microsoft.com/en-us/library/ie/hh465388.aspx#attribute_section
+ if ( div.querySelectorAll("[msallowclip^='']").length ) {
+ rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:''|\"\")" );
+ }
+
+ // Support: IE8
+ // Boolean attributes and "value" are not treated correctly
+ if ( !div.querySelectorAll("[selected]").length ) {
+ rbuggyQSA.push( "\\[" + whitespace + "*(?:value|" + booleans + ")" );
+ }
+
+ // Webkit/Opera - :checked should return selected option elements
+ // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+ // IE8 throws error here and will not see later tests
+ if ( !div.querySelectorAll(":checked").length ) {
+ rbuggyQSA.push(":checked");
+ }
+ });
+
+ assert(function( div ) {
+ // Support: Windows 8 Native Apps
+ // The type and name attributes are restricted during .innerHTML assignment
+ var input = doc.createElement("input");
+ input.setAttribute( "type", "hidden" );
+ div.appendChild( input ).setAttribute( "name", "D" );
+
+ // Support: IE8
+ // Enforce case-sensitivity of name attribute
+ if ( div.querySelectorAll("[name=d]").length ) {
+ rbuggyQSA.push( "name" + whitespace + "*[*^$|!~]?=" );
+ }
+
+ // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled)
+ // IE8 throws error here and will not see later tests
+ if ( !div.querySelectorAll(":enabled").length ) {
+ rbuggyQSA.push( ":enabled", ":disabled" );
+ }
+
+ // Opera 10-11 does not throw on post-comma invalid pseudos
+ div.querySelectorAll("*,:x");
+ rbuggyQSA.push(",.*:");
+ });
+ }
+
+ if ( (support.matchesSelector = rnative.test( (matches = docElem.matches ||
+ docElem.webkitMatchesSelector ||
+ docElem.mozMatchesSelector ||
+ docElem.oMatchesSelector ||
+ docElem.msMatchesSelector) )) ) {
+
+ assert(function( div ) {
+ // Check to see if it's possible to do matchesSelector
+ // on a disconnected node (IE 9)
+ support.disconnectedMatch = matches.call( div, "div" );
+
+ // This should fail with an exception
+ // Gecko does not error, returns false instead
+ matches.call( div, "[s!='']:x" );
+ rbuggyMatches.push( "!=", pseudos );
+ });
+ }
+
+ rbuggyQSA = rbuggyQSA.length && new RegExp( rbuggyQSA.join("|") );
+ rbuggyMatches = rbuggyMatches.length && new RegExp( rbuggyMatches.join("|") );
+
+ /* Contains
+ ---------------------------------------------------------------------- */
+ hasCompare = rnative.test( docElem.compareDocumentPosition );
+
+ // Element contains another
+ // Purposefully does not implement inclusive descendent
+ // As in, an element does not contain itself
+ contains = hasCompare || rnative.test( docElem.contains ) ?
+ function( a, b ) {
+ var adown = a.nodeType === 9 ? a.documentElement : a,
+ bup = b && b.parentNode;
+ return a === bup || !!( bup && bup.nodeType === 1 && (
+ adown.contains ?
+ adown.contains( bup ) :
+ a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16
+ ));
+ } :
+ function( a, b ) {
+ if ( b ) {
+ while ( (b = b.parentNode) ) {
+ if ( b === a ) {
+ return true;
+ }
+ }
+ }
+ return false;
+ };
+
+ /* Sorting
+ ---------------------------------------------------------------------- */
+
+ // Document order sorting
+ sortOrder = hasCompare ?
+ function( a, b ) {
+
+ // Flag for duplicate removal
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ // Sort on method existence if only one input has compareDocumentPosition
+ var compare = !a.compareDocumentPosition - !b.compareDocumentPosition;
+ if ( compare ) {
+ return compare;
+ }
+
+ // Calculate position if both inputs belong to the same document
+ compare = ( a.ownerDocument || a ) === ( b.ownerDocument || b ) ?
+ a.compareDocumentPosition( b ) :
+
+ // Otherwise we know they are disconnected
+ 1;
+
+ // Disconnected nodes
+ if ( compare & 1 ||
+ (!support.sortDetached && b.compareDocumentPosition( a ) === compare) ) {
+
+ // Choose the first element that is related to our preferred document
+ if ( a === doc || a.ownerDocument === preferredDoc && contains(preferredDoc, a) ) {
+ return -1;
+ }
+ if ( b === doc || b.ownerDocument === preferredDoc && contains(preferredDoc, b) ) {
+ return 1;
+ }
+
+ // Maintain original order
+ return sortInput ?
+ ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
+ 0;
+ }
+
+ return compare & 4 ? -1 : 1;
+ } :
+ function( a, b ) {
+ // Exit early if the nodes are identical
+ if ( a === b ) {
+ hasDuplicate = true;
+ return 0;
+ }
+
+ var cur,
+ i = 0,
+ aup = a.parentNode,
+ bup = b.parentNode,
+ ap = [ a ],
+ bp = [ b ];
+
+ // Parentless nodes are either documents or disconnected
+ if ( !aup || !bup ) {
+ return a === doc ? -1 :
+ b === doc ? 1 :
+ aup ? -1 :
+ bup ? 1 :
+ sortInput ?
+ ( indexOf.call( sortInput, a ) - indexOf.call( sortInput, b ) ) :
+ 0;
+
+ // If the nodes are siblings, we can do a quick check
+ } else if ( aup === bup ) {
+ return siblingCheck( a, b );
+ }
+
+ // Otherwise we need full lists of their ancestors for comparison
+ cur = a;
+ while ( (cur = cur.parentNode) ) {
+ ap.unshift( cur );
+ }
+ cur = b;
+ while ( (cur = cur.parentNode) ) {
+ bp.unshift( cur );
+ }
+
+ // Walk down the tree looking for a discrepancy
+ while ( ap[i] === bp[i] ) {
+ i++;
+ }
+
+ return i ?
+ // Do a sibling check if the nodes have a common ancestor
+ siblingCheck( ap[i], bp[i] ) :
+
+ // Otherwise nodes in our document sort first
+ ap[i] === preferredDoc ? -1 :
+ bp[i] === preferredDoc ? 1 :
+ 0;
+ };
+
+ return doc;
+};
+
+Sizzle.matches = function( expr, elements ) {
+ return Sizzle( expr, null, null, elements );
+};
+
+Sizzle.matchesSelector = function( elem, expr ) {
+ // Set document vars if needed
+ if ( ( elem.ownerDocument || elem ) !== document ) {
+ setDocument( elem );
+ }
+
+ // Make sure that attribute selectors are quoted
+ expr = expr.replace( rattributeQuotes, "='$1']" );
+
+ if ( support.matchesSelector && documentIsHTML &&
+ ( !rbuggyMatches || !rbuggyMatches.test( expr ) ) &&
+ ( !rbuggyQSA || !rbuggyQSA.test( expr ) ) ) {
+
+ try {
+ var ret = matches.call( elem, expr );
+
+ // IE 9's matchesSelector returns false on disconnected nodes
+ if ( ret || support.disconnectedMatch ||
+ // As well, disconnected nodes are said to be in a document
+ // fragment in IE 9
+ elem.document && elem.document.nodeType !== 11 ) {
+ return ret;
+ }
+ } catch(e) {}
+ }
+
+ return Sizzle( expr, document, null, [ elem ] ).length > 0;
+};
+
+Sizzle.contains = function( context, elem ) {
+ // Set document vars if needed
+ if ( ( context.ownerDocument || context ) !== document ) {
+ setDocument( context );
+ }
+ return contains( context, elem );
+};
+
+Sizzle.attr = function( elem, name ) {
+ // Set document vars if needed
+ if ( ( elem.ownerDocument || elem ) !== document ) {
+ setDocument( elem );
+ }
+
+ var fn = Expr.attrHandle[ name.toLowerCase() ],
+ // Don't get fooled by Object.prototype properties (jQuery #13807)
+ val = fn && hasOwn.call( Expr.attrHandle, name.toLowerCase() ) ?
+ fn( elem, name, !documentIsHTML ) :
+ undefined;
+
+ return val !== undefined ?
+ val :
+ support.attributes || !documentIsHTML ?
+ elem.getAttribute( name ) :
+ (val = elem.getAttributeNode(name)) && val.specified ?
+ val.value :
+ null;
+};
+
+Sizzle.error = function( msg ) {
+ throw new Error( "Syntax error, unrecognized expression: " + msg );
+};
+
+/**
+ * Document sorting and removing duplicates
+ * @param {ArrayLike} results
+ */
+Sizzle.uniqueSort = function( results ) {
+ var elem,
+ duplicates = [],
+ j = 0,
+ i = 0;
+
+ // Unless we *know* we can detect duplicates, assume their presence
+ hasDuplicate = !support.detectDuplicates;
+ sortInput = !support.sortStable && results.slice( 0 );
+ results.sort( sortOrder );
+
+ if ( hasDuplicate ) {
+ while ( (elem = results[i++]) ) {
+ if ( elem === results[ i ] ) {
+ j = duplicates.push( i );
+ }
+ }
+ while ( j-- ) {
+ results.splice( duplicates[ j ], 1 );
+ }
+ }
+
+ // Clear input after sorting to release objects
+ // See https://github.com/jquery/sizzle/pull/225
+ sortInput = null;
+
+ return results;
+};
+
+/**
+ * Utility function for retrieving the text value of an array of DOM nodes
+ * @param {Array|Element} elem
+ */
+getText = Sizzle.getText = function( elem ) {
+ var node,
+ ret = "",
+ i = 0,
+ nodeType = elem.nodeType;
+
+ if ( !nodeType ) {
+ // If no nodeType, this is expected to be an array
+ while ( (node = elem[i++]) ) {
+ // Do not traverse comment nodes
+ ret += getText( node );
+ }
+ } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
+ // Use textContent for elements
+ // innerText usage removed for consistency of new lines (jQuery #11153)
+ if ( typeof elem.textContent === "string" ) {
+ return elem.textContent;
+ } else {
+ // Traverse its children
+ for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+ ret += getText( elem );
+ }
+ }
+ } else if ( nodeType === 3 || nodeType === 4 ) {
+ return elem.nodeValue;
+ }
+ // Do not include comment or processing instruction nodes
+
+ return ret;
+};
+
+Expr = Sizzle.selectors = {
+
+ // Can be adjusted by the user
+ cacheLength: 50,
+
+ createPseudo: markFunction,
+
+ match: matchExpr,
+
+ attrHandle: {},
+
+ find: {},
+
+ relative: {
+ ">": { dir: "parentNode", first: true },
+ " ": { dir: "parentNode" },
+ "+": { dir: "previousSibling", first: true },
+ "~": { dir: "previousSibling" }
+ },
+
+ preFilter: {
+ "ATTR": function( match ) {
+ match[1] = match[1].replace( runescape, funescape );
+
+ // Move the given value to match[3] whether quoted or unquoted
+ match[3] = ( match[3] || match[4] || match[5] || "" ).replace( runescape, funescape );
+
+ if ( match[2] === "~=" ) {
+ match[3] = " " + match[3] + " ";
+ }
+
+ return match.slice( 0, 4 );
+ },
+
+ "CHILD": function( match ) {
+ /* matches from matchExpr["CHILD"]
+ 1 type (only|nth|...)
+ 2 what (child|of-type)
+ 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...)
+ 4 xn-component of xn+y argument ([+-]?\d*n|)
+ 5 sign of xn-component
+ 6 x of xn-component
+ 7 sign of y-component
+ 8 y of y-component
+ */
+ match[1] = match[1].toLowerCase();
+
+ if ( match[1].slice( 0, 3 ) === "nth" ) {
+ // nth-* requires argument
+ if ( !match[3] ) {
+ Sizzle.error( match[0] );
+ }
+
+ // numeric x and y parameters for Expr.filter.CHILD
+ // remember that false/true cast respectively to 0/1
+ match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) );
+ match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" );
+
+ // other types prohibit arguments
+ } else if ( match[3] ) {
+ Sizzle.error( match[0] );
+ }
+
+ return match;
+ },
+
+ "PSEUDO": function( match ) {
+ var excess,
+ unquoted = !match[6] && match[2];
+
+ if ( matchExpr["CHILD"].test( match[0] ) ) {
+ return null;
+ }
+
+ // Accept quoted arguments as-is
+ if ( match[3] ) {
+ match[2] = match[4] || match[5] || "";
+
+ // Strip excess characters from unquoted arguments
+ } else if ( unquoted && rpseudo.test( unquoted ) &&
+ // Get excess from tokenize (recursively)
+ (excess = tokenize( unquoted, true )) &&
+ // advance to the next closing parenthesis
+ (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) {
+
+ // excess is a negative index
+ match[0] = match[0].slice( 0, excess );
+ match[2] = unquoted.slice( 0, excess );
+ }
+
+ // Return only captures needed by the pseudo filter method (type and argument)
+ return match.slice( 0, 3 );
+ }
+ },
+
+ filter: {
+
+ "TAG": function( nodeNameSelector ) {
+ var nodeName = nodeNameSelector.replace( runescape, funescape ).toLowerCase();
+ return nodeNameSelector === "*" ?
+ function() { return true; } :
+ function( elem ) {
+ return elem.nodeName && elem.nodeName.toLowerCase() === nodeName;
+ };
+ },
+
+ "CLASS": function( className ) {
+ var pattern = classCache[ className + " " ];
+
+ return pattern ||
+ (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) &&
+ classCache( className, function( elem ) {
+ return pattern.test( typeof elem.className === "string" && elem.className || typeof elem.getAttribute !== strundefined && elem.getAttribute("class") || "" );
+ });
+ },
+
+ "ATTR": function( name, operator, check ) {
+ return function( elem ) {
+ var result = Sizzle.attr( elem, name );
+
+ if ( result == null ) {
+ return operator === "!=";
+ }
+ if ( !operator ) {
+ return true;
+ }
+
+ result += "";
+
+ return operator === "=" ? result === check :
+ operator === "!=" ? result !== check :
+ operator === "^=" ? check && result.indexOf( check ) === 0 :
+ operator === "*=" ? check && result.indexOf( check ) > -1 :
+ operator === "$=" ? check && result.slice( -check.length ) === check :
+ operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 :
+ operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" :
+ false;
+ };
+ },
+
+ "CHILD": function( type, what, argument, first, last ) {
+ var simple = type.slice( 0, 3 ) !== "nth",
+ forward = type.slice( -4 ) !== "last",
+ ofType = what === "of-type";
+
+ return first === 1 && last === 0 ?
+
+ // Shortcut for :nth-*(n)
+ function( elem ) {
+ return !!elem.parentNode;
+ } :
+
+ function( elem, context, xml ) {
+ var cache, outerCache, node, diff, nodeIndex, start,
+ dir = simple !== forward ? "nextSibling" : "previousSibling",
+ parent = elem.parentNode,
+ name = ofType && elem.nodeName.toLowerCase(),
+ useCache = !xml && !ofType;
+
+ if ( parent ) {
+
+ // :(first|last|only)-(child|of-type)
+ if ( simple ) {
+ while ( dir ) {
+ node = elem;
+ while ( (node = node[ dir ]) ) {
+ if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) {
+ return false;
+ }
+ }
+ // Reverse direction for :only-* (if we haven't yet done so)
+ start = dir = type === "only" && !start && "nextSibling";
+ }
+ return true;
+ }
+
+ start = [ forward ? parent.firstChild : parent.lastChild ];
+
+ // non-xml :nth-child(...) stores cache data on `parent`
+ if ( forward && useCache ) {
+ // Seek `elem` from a previously-cached index
+ outerCache = parent[ expando ] || (parent[ expando ] = {});
+ cache = outerCache[ type ] || [];
+ nodeIndex = cache[0] === dirruns && cache[1];
+ diff = cache[0] === dirruns && cache[2];
+ node = nodeIndex && parent.childNodes[ nodeIndex ];
+
+ while ( (node = ++nodeIndex && node && node[ dir ] ||
+
+ // Fallback to seeking `elem` from the start
+ (diff = nodeIndex = 0) || start.pop()) ) {
+
+ // When found, cache indexes on `parent` and break
+ if ( node.nodeType === 1 && ++diff && node === elem ) {
+ outerCache[ type ] = [ dirruns, nodeIndex, diff ];
+ break;
+ }
+ }
+
+ // Use previously-cached element index if available
+ } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) {
+ diff = cache[1];
+
+ // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...)
+ } else {
+ // Use the same loop as above to seek `elem` from the start
+ while ( (node = ++nodeIndex && node && node[ dir ] ||
+ (diff = nodeIndex = 0) || start.pop()) ) {
+
+ if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) {
+ // Cache the index of each encountered element
+ if ( useCache ) {
+ (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ];
+ }
+
+ if ( node === elem ) {
+ break;
+ }
+ }
+ }
+ }
+
+ // Incorporate the offset, then check against cycle size
+ diff -= last;
+ return diff === first || ( diff % first === 0 && diff / first >= 0 );
+ }
+ };
+ },
+
+ "PSEUDO": function( pseudo, argument ) {
+ // pseudo-class names are case-insensitive
+ // http://www.w3.org/TR/selectors/#pseudo-classes
+ // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters
+ // Remember that setFilters inherits from pseudos
+ var args,
+ fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] ||
+ Sizzle.error( "unsupported pseudo: " + pseudo );
+
+ // The user may use createPseudo to indicate that
+ // arguments are needed to create the filter function
+ // just as Sizzle does
+ if ( fn[ expando ] ) {
+ return fn( argument );
+ }
+
+ // But maintain support for old signatures
+ if ( fn.length > 1 ) {
+ args = [ pseudo, pseudo, "", argument ];
+ return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ?
+ markFunction(function( seed, matches ) {
+ var idx,
+ matched = fn( seed, argument ),
+ i = matched.length;
+ while ( i-- ) {
+ idx = indexOf.call( seed, matched[i] );
+ seed[ idx ] = !( matches[ idx ] = matched[i] );
+ }
+ }) :
+ function( elem ) {
+ return fn( elem, 0, args );
+ };
+ }
+
+ return fn;
+ }
+ },
+
+ pseudos: {
+ // Potentially complex pseudos
+ "not": markFunction(function( selector ) {
+ // Trim the selector passed to compile
+ // to avoid treating leading and trailing
+ // spaces as combinators
+ var input = [],
+ results = [],
+ matcher = compile( selector.replace( rtrim, "$1" ) );
+
+ return matcher[ expando ] ?
+ markFunction(function( seed, matches, context, xml ) {
+ var elem,
+ unmatched = matcher( seed, null, xml, [] ),
+ i = seed.length;
+
+ // Match elements unmatched by `matcher`
+ while ( i-- ) {
+ if ( (elem = unmatched[i]) ) {
+ seed[i] = !(matches[i] = elem);
+ }
+ }
+ }) :
+ function( elem, context, xml ) {
+ input[0] = elem;
+ matcher( input, null, xml, results );
+ return !results.pop();
+ };
+ }),
+
+ "has": markFunction(function( selector ) {
+ return function( elem ) {
+ return Sizzle( selector, elem ).length > 0;
+ };
+ }),
+
+ "contains": markFunction(function( text ) {
+ return function( elem ) {
+ return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1;
+ };
+ }),
+
+ // "Whether an element is represented by a :lang() selector
+ // is based solely on the element's language value
+ // being equal to the identifier C,
+ // or beginning with the identifier C immediately followed by "-".
+ // The matching of C against the element's language value is performed case-insensitively.
+ // The identifier C does not have to be a valid language name."
+ // http://www.w3.org/TR/selectors/#lang-pseudo
+ "lang": markFunction( function( lang ) {
+ // lang value must be a valid identifier
+ if ( !ridentifier.test(lang || "") ) {
+ Sizzle.error( "unsupported lang: " + lang );
+ }
+ lang = lang.replace( runescape, funescape ).toLowerCase();
+ return function( elem ) {
+ var elemLang;
+ do {
+ if ( (elemLang = documentIsHTML ?
+ elem.lang :
+ elem.getAttribute("xml:lang") || elem.getAttribute("lang")) ) {
+
+ elemLang = elemLang.toLowerCase();
+ return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0;
+ }
+ } while ( (elem = elem.parentNode) && elem.nodeType === 1 );
+ return false;
+ };
+ }),
+
+ // Miscellaneous
+ "target": function( elem ) {
+ var hash = window.location && window.location.hash;
+ return hash && hash.slice( 1 ) === elem.id;
+ },
+
+ "root": function( elem ) {
+ return elem === docElem;
+ },
+
+ "focus": function( elem ) {
+ return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex);
+ },
+
+ // Boolean properties
+ "enabled": function( elem ) {
+ return elem.disabled === false;
+ },
+
+ "disabled": function( elem ) {
+ return elem.disabled === true;
+ },
+
+ "checked": function( elem ) {
+ // In CSS3, :checked should return both checked and selected elements
+ // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked
+ var nodeName = elem.nodeName.toLowerCase();
+ return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected);
+ },
+
+ "selected": function( elem ) {
+ // Accessing this property makes selected-by-default
+ // options in Safari work properly
+ if ( elem.parentNode ) {
+ elem.parentNode.selectedIndex;
+ }
+
+ return elem.selected === true;
+ },
+
+ // Contents
+ "empty": function( elem ) {
+ // http://www.w3.org/TR/selectors/#empty-pseudo
+ // :empty is negated by element (1) or content nodes (text: 3; cdata: 4; entity ref: 5),
+ // but not by others (comment: 8; processing instruction: 7; etc.)
+ // nodeType < 6 works because attributes (2) do not appear as children
+ for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) {
+ if ( elem.nodeType < 6 ) {
+ return false;
+ }
+ }
+ return true;
+ },
+
+ "parent": function( elem ) {
+ return !Expr.pseudos["empty"]( elem );
+ },
+
+ // Element/input types
+ "header": function( elem ) {
+ return rheader.test( elem.nodeName );
+ },
+
+ "input": function( elem ) {
+ return rinputs.test( elem.nodeName );
+ },
+
+ "button": function( elem ) {
+ var name = elem.nodeName.toLowerCase();
+ return name === "input" && elem.type === "button" || name === "button";
+ },
+
+ "text": function( elem ) {
+ var attr;
+ return elem.nodeName.toLowerCase() === "input" &&
+ elem.type === "text" &&
+
+ // Support: IE<8
+ // New HTML5 attribute values (e.g., "search") appear with elem.type === "text"
+ ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === "text" );
+ },
+
+ // Position-in-collection
+ "first": createPositionalPseudo(function() {
+ return [ 0 ];
+ }),
+
+ "last": createPositionalPseudo(function( matchIndexes, length ) {
+ return [ length - 1 ];
+ }),
+
+ "eq": createPositionalPseudo(function( matchIndexes, length, argument ) {
+ return [ argument < 0 ? argument + length : argument ];
+ }),
+
+ "even": createPositionalPseudo(function( matchIndexes, length ) {
+ var i = 0;
+ for ( ; i < length; i += 2 ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ }),
+
+ "odd": createPositionalPseudo(function( matchIndexes, length ) {
+ var i = 1;
+ for ( ; i < length; i += 2 ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ }),
+
+ "lt": createPositionalPseudo(function( matchIndexes, length, argument ) {
+ var i = argument < 0 ? argument + length : argument;
+ for ( ; --i >= 0; ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ }),
+
+ "gt": createPositionalPseudo(function( matchIndexes, length, argument ) {
+ var i = argument < 0 ? argument + length : argument;
+ for ( ; ++i < length; ) {
+ matchIndexes.push( i );
+ }
+ return matchIndexes;
+ })
+ }
+};
+
+Expr.pseudos["nth"] = Expr.pseudos["eq"];
+
+// Add button/input type pseudos
+for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) {
+ Expr.pseudos[ i ] = createInputPseudo( i );
+}
+for ( i in { submit: true, reset: true } ) {
+ Expr.pseudos[ i ] = createButtonPseudo( i );
+}
+
+// Easy API for creating new setFilters
+function setFilters() {}
+setFilters.prototype = Expr.filters = Expr.pseudos;
+Expr.setFilters = new setFilters();
+
+tokenize = Sizzle.tokenize = function( selector, parseOnly ) {
+ var matched, match, tokens, type,
+ soFar, groups, preFilters,
+ cached = tokenCache[ selector + " " ];
+
+ if ( cached ) {
+ return parseOnly ? 0 : cached.slice( 0 );
+ }
+
+ soFar = selector;
+ groups = [];
+ preFilters = Expr.preFilter;
+
+ while ( soFar ) {
+
+ // Comma and first run
+ if ( !matched || (match = rcomma.exec( soFar )) ) {
+ if ( match ) {
+ // Don't consume trailing commas as valid
+ soFar = soFar.slice( match[0].length ) || soFar;
+ }
+ groups.push( (tokens = []) );
+ }
+
+ matched = false;
+
+ // Combinators
+ if ( (match = rcombinators.exec( soFar )) ) {
+ matched = match.shift();
+ tokens.push({
+ value: matched,
+ // Cast descendant combinators to space
+ type: match[0].replace( rtrim, " " )
+ });
+ soFar = soFar.slice( matched.length );
+ }
+
+ // Filters
+ for ( type in Expr.filter ) {
+ if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] ||
+ (match = preFilters[ type ]( match ))) ) {
+ matched = match.shift();
+ tokens.push({
+ value: matched,
+ type: type,
+ matches: match
+ });
+ soFar = soFar.slice( matched.length );
+ }
+ }
+
+ if ( !matched ) {
+ break;
+ }
+ }
+
+ // Return the length of the invalid excess
+ // if we're just parsing
+ // Otherwise, throw an error or return tokens
+ return parseOnly ?
+ soFar.length :
+ soFar ?
+ Sizzle.error( selector ) :
+ // Cache the tokens
+ tokenCache( selector, groups ).slice( 0 );
+};
+
+function toSelector( tokens ) {
+ var i = 0,
+ len = tokens.length,
+ selector = "";
+ for ( ; i < len; i++ ) {
+ selector += tokens[i].value;
+ }
+ return selector;
+}
+
+function addCombinator( matcher, combinator, base ) {
+ var dir = combinator.dir,
+ checkNonElements = base && dir === "parentNode",
+ doneName = done++;
+
+ return combinator.first ?
+ // Check against closest ancestor/preceding element
+ function( elem, context, xml ) {
+ while ( (elem = elem[ dir ]) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ return matcher( elem, context, xml );
+ }
+ }
+ } :
+
+ // Check against all ancestor/preceding elements
+ function( elem, context, xml ) {
+ var oldCache, outerCache,
+ newCache = [ dirruns, doneName ];
+
+ // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching
+ if ( xml ) {
+ while ( (elem = elem[ dir ]) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ if ( matcher( elem, context, xml ) ) {
+ return true;
+ }
+ }
+ }
+ } else {
+ while ( (elem = elem[ dir ]) ) {
+ if ( elem.nodeType === 1 || checkNonElements ) {
+ outerCache = elem[ expando ] || (elem[ expando ] = {});
+ if ( (oldCache = outerCache[ dir ]) &&
+ oldCache[ 0 ] === dirruns && oldCache[ 1 ] === doneName ) {
+
+ // Assign to newCache so results back-propagate to previous elements
+ return (newCache[ 2 ] = oldCache[ 2 ]);
+ } else {
+ // Reuse newcache so results back-propagate to previous elements
+ outerCache[ dir ] = newCache;
+
+ // A match means we're done; a fail means we have to keep checking
+ if ( (newCache[ 2 ] = matcher( elem, context, xml )) ) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+ };
+}
+
+function elementMatcher( matchers ) {
+ return matchers.length > 1 ?
+ function( elem, context, xml ) {
+ var i = matchers.length;
+ while ( i-- ) {
+ if ( !matchers[i]( elem, context, xml ) ) {
+ return false;
+ }
+ }
+ return true;
+ } :
+ matchers[0];
+}
+
+function multipleContexts( selector, contexts, results ) {
+ var i = 0,
+ len = contexts.length;
+ for ( ; i < len; i++ ) {
+ Sizzle( selector, contexts[i], results );
+ }
+ return results;
+}
+
+function condense( unmatched, map, filter, context, xml ) {
+ var elem,
+ newUnmatched = [],
+ i = 0,
+ len = unmatched.length,
+ mapped = map != null;
+
+ for ( ; i < len; i++ ) {
+ if ( (elem = unmatched[i]) ) {
+ if ( !filter || filter( elem, context, xml ) ) {
+ newUnmatched.push( elem );
+ if ( mapped ) {
+ map.push( i );
+ }
+ }
+ }
+ }
+
+ return newUnmatched;
+}
+
+function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) {
+ if ( postFilter && !postFilter[ expando ] ) {
+ postFilter = setMatcher( postFilter );
+ }
+ if ( postFinder && !postFinder[ expando ] ) {
+ postFinder = setMatcher( postFinder, postSelector );
+ }
+ return markFunction(function( seed, results, context, xml ) {
+ var temp, i, elem,
+ preMap = [],
+ postMap = [],
+ preexisting = results.length,
+
+ // Get initial elements from seed or context
+ elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ),
+
+ // Prefilter to get matcher input, preserving a map for seed-results synchronization
+ matcherIn = preFilter && ( seed || !selector ) ?
+ condense( elems, preMap, preFilter, context, xml ) :
+ elems,
+
+ matcherOut = matcher ?
+ // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results,
+ postFinder || ( seed ? preFilter : preexisting || postFilter ) ?
+
+ // ...intermediate processing is necessary
+ [] :
+
+ // ...otherwise use results directly
+ results :
+ matcherIn;
+
+ // Find primary matches
+ if ( matcher ) {
+ matcher( matcherIn, matcherOut, context, xml );
+ }
+
+ // Apply postFilter
+ if ( postFilter ) {
+ temp = condense( matcherOut, postMap );
+ postFilter( temp, [], context, xml );
+
+ // Un-match failing elements by moving them back to matcherIn
+ i = temp.length;
+ while ( i-- ) {
+ if ( (elem = temp[i]) ) {
+ matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem);
+ }
+ }
+ }
+
+ if ( seed ) {
+ if ( postFinder || preFilter ) {
+ if ( postFinder ) {
+ // Get the final matcherOut by condensing this intermediate into postFinder contexts
+ temp = [];
+ i = matcherOut.length;
+ while ( i-- ) {
+ if ( (elem = matcherOut[i]) ) {
+ // Restore matcherIn since elem is not yet a final match
+ temp.push( (matcherIn[i] = elem) );
+ }
+ }
+ postFinder( null, (matcherOut = []), temp, xml );
+ }
+
+ // Move matched elements from seed to results to keep them synchronized
+ i = matcherOut.length;
+ while ( i-- ) {
+ if ( (elem = matcherOut[i]) &&
+ (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) {
+
+ seed[temp] = !(results[temp] = elem);
+ }
+ }
+ }
+
+ // Add elements to results, through postFinder if defined
+ } else {
+ matcherOut = condense(
+ matcherOut === results ?
+ matcherOut.splice( preexisting, matcherOut.length ) :
+ matcherOut
+ );
+ if ( postFinder ) {
+ postFinder( null, results, matcherOut, xml );
+ } else {
+ push.apply( results, matcherOut );
+ }
+ }
+ });
+}
+
+function matcherFromTokens( tokens ) {
+ var checkContext, matcher, j,
+ len = tokens.length,
+ leadingRelative = Expr.relative[ tokens[0].type ],
+ implicitRelative = leadingRelative || Expr.relative[" "],
+ i = leadingRelative ? 1 : 0,
+
+ // The foundational matcher ensures that elements are reachable from top-level context(s)
+ matchContext = addCombinator( function( elem ) {
+ return elem === checkContext;
+ }, implicitRelative, true ),
+ matchAnyContext = addCombinator( function( elem ) {
+ return indexOf.call( checkContext, elem ) > -1;
+ }, implicitRelative, true ),
+ matchers = [ function( elem, context, xml ) {
+ return ( !leadingRelative && ( xml || context !== outermostContext ) ) || (
+ (checkContext = context).nodeType ?
+ matchContext( elem, context, xml ) :
+ matchAnyContext( elem, context, xml ) );
+ } ];
+
+ for ( ; i < len; i++ ) {
+ if ( (matcher = Expr.relative[ tokens[i].type ]) ) {
+ matchers = [ addCombinator(elementMatcher( matchers ), matcher) ];
+ } else {
+ matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches );
+
+ // Return special upon seeing a positional matcher
+ if ( matcher[ expando ] ) {
+ // Find the next relative operator (if any) for proper handling
+ j = ++i;
+ for ( ; j < len; j++ ) {
+ if ( Expr.relative[ tokens[j].type ] ) {
+ break;
+ }
+ }
+ return setMatcher(
+ i > 1 && elementMatcher( matchers ),
+ i > 1 && toSelector(
+ // If the preceding token was a descendant combinator, insert an implicit any-element `*`
+ tokens.slice( 0, i - 1 ).concat({ value: tokens[ i - 2 ].type === " " ? "*" : "" })
+ ).replace( rtrim, "$1" ),
+ matcher,
+ i < j && matcherFromTokens( tokens.slice( i, j ) ),
+ j < len && matcherFromTokens( (tokens = tokens.slice( j )) ),
+ j < len && toSelector( tokens )
+ );
+ }
+ matchers.push( matcher );
+ }
+ }
+
+ return elementMatcher( matchers );
+}
+
+function matcherFromGroupMatchers( elementMatchers, setMatchers ) {
+ var bySet = setMatchers.length > 0,
+ byElement = elementMatchers.length > 0,
+ superMatcher = function( seed, context, xml, results, outermost ) {
+ var elem, j, matcher,
+ matchedCount = 0,
+ i = "0",
+ unmatched = seed && [],
+ setMatched = [],
+ contextBackup = outermostContext,
+ // We must always have either seed elements or outermost context
+ elems = seed || byElement && Expr.find["TAG"]( "*", outermost ),
+ // Use integer dirruns iff this is the outermost matcher
+ dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1),
+ len = elems.length;
+
+ if ( outermost ) {
+ outermostContext = context !== document && context;
+ }
+
+ // Add elements passing elementMatchers directly to results
+ // Keep `i` a string if there are no elements so `matchedCount` will be "00" below
+ // Support: IE<9, Safari
+ // Tolerate NodeList properties (IE: "length"; Safari: <number>) matching elements by id
+ for ( ; i !== len && (elem = elems[i]) != null; i++ ) {
+ if ( byElement && elem ) {
+ j = 0;
+ while ( (matcher = elementMatchers[j++]) ) {
+ if ( matcher( elem, context, xml ) ) {
+ results.push( elem );
+ break;
+ }
+ }
+ if ( outermost ) {
+ dirruns = dirrunsUnique;
+ }
+ }
+
+ // Track unmatched elements for set filters
+ if ( bySet ) {
+ // They will have gone through all possible matchers
+ if ( (elem = !matcher && elem) ) {
+ matchedCount--;
+ }
+
+ // Lengthen the array for every element, matched or not
+ if ( seed ) {
+ unmatched.push( elem );
+ }
+ }
+ }
+
+ // Apply set filters to unmatched elements
+ matchedCount += i;
+ if ( bySet && i !== matchedCount ) {
+ j = 0;
+ while ( (matcher = setMatchers[j++]) ) {
+ matcher( unmatched, setMatched, context, xml );
+ }
+
+ if ( seed ) {
+ // Reintegrate element matches to eliminate the need for sorting
+ if ( matchedCount > 0 ) {
+ while ( i-- ) {
+ if ( !(unmatched[i] || setMatched[i]) ) {
+ setMatched[i] = pop.call( results );
+ }
+ }
+ }
+
+ // Discard index placeholder values to get only actual matches
+ setMatched = condense( setMatched );
+ }
+
+ // Add matches to results
+ push.apply( results, setMatched );
+
+ // Seedless set matches succeeding multiple successful matchers stipulate sorting
+ if ( outermost && !seed && setMatched.length > 0 &&
+ ( matchedCount + setMatchers.length ) > 1 ) {
+
+ Sizzle.uniqueSort( results );
+ }
+ }
+
+ // Override manipulation of globals by nested matchers
+ if ( outermost ) {
+ dirruns = dirrunsUnique;
+ outermostContext = contextBackup;
+ }
+
+ return unmatched;
+ };
+
+ return bySet ?
+ markFunction( superMatcher ) :
+ superMatcher;
+}
+
+compile = Sizzle.compile = function( selector, match /* Internal Use Only */ ) {
+ var i,
+ setMatchers = [],
+ elementMatchers = [],
+ cached = compilerCache[ selector + " " ];
+
+ if ( !cached ) {
+ // Generate a function of recursive functions that can be used to check each element
+ if ( !match ) {
+ match = tokenize( selector );
+ }
+ i = match.length;
+ while ( i-- ) {
+ cached = matcherFromTokens( match[i] );
+ if ( cached[ expando ] ) {
+ setMatchers.push( cached );
+ } else {
+ elementMatchers.push( cached );
+ }
+ }
+
+ // Cache the compiled function
+ cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) );
+
+ // Save selector and tokenization
+ cached.selector = selector;
+ }
+ return cached;
+};
+
+/**
+ * A low-level selection function that works with Sizzle's compiled
+ * selector functions
+ * @param {String|Function} selector A selector or a pre-compiled
+ * selector function built with Sizzle.compile
+ * @param {Element} context
+ * @param {Array} [results]
+ * @param {Array} [seed] A set of elements to match against
+ */
+select = Sizzle.select = function( selector, context, results, seed ) {
+ var i, tokens, token, type, find,
+ compiled = typeof selector === "function" && selector,
+ match = !seed && tokenize( (selector = compiled.selector || selector) );
+
+ results = results || [];
+
+ // Try to minimize operations if there is no seed and only one group
+ if ( match.length === 1 ) {
+
+ // Take a shortcut and set the context if the root selector is an ID
+ tokens = match[0] = match[0].slice( 0 );
+ if ( tokens.length > 2 && (token = tokens[0]).type === "ID" &&
+ support.getById && context.nodeType === 9 && documentIsHTML &&
+ Expr.relative[ tokens[1].type ] ) {
+
+ context = ( Expr.find["ID"]( token.matches[0].replace(runescape, funescape), context ) || [] )[0];
+ if ( !context ) {
+ return results;
+
+ // Precompiled matchers will still verify ancestry, so step up a level
+ } else if ( compiled ) {
+ context = context.parentNode;
+ }
+
+ selector = selector.slice( tokens.shift().value.length );
+ }
+
+ // Fetch a seed set for right-to-left matching
+ i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length;
+ while ( i-- ) {
+ token = tokens[i];
+
+ // Abort if we hit a combinator
+ if ( Expr.relative[ (type = token.type) ] ) {
+ break;
+ }
+ if ( (find = Expr.find[ type ]) ) {
+ // Search, expanding context for leading sibling combinators
+ if ( (seed = find(
+ token.matches[0].replace( runescape, funescape ),
+ rsibling.test( tokens[0].type ) && testContext( context.parentNode ) || context
+ )) ) {
+
+ // If seed is empty or no tokens remain, we can return early
+ tokens.splice( i, 1 );
+ selector = seed.length && toSelector( tokens );
+ if ( !selector ) {
+ push.apply( results, seed );
+ return results;
+ }
+
+ break;
+ }
+ }
+ }
+ }
+
+ // Compile and execute a filtering function if one is not provided
+ // Provide `match` to avoid retokenization if we modified the selector above
+ ( compiled || compile( selector, match ) )(
+ seed,
+ context,
+ !documentIsHTML,
+ results,
+ rsibling.test( selector ) && testContext( context.parentNode ) || context
+ );
+ return results;
+};
+
+// One-time assignments
+
+// Sort stability
+support.sortStable = expando.split("").sort( sortOrder ).join("") === expando;
+
+// Support: Chrome<14
+// Always assume duplicates if they aren't passed to the comparison function
+support.detectDuplicates = !!hasDuplicate;
+
+// Initialize against the default document
+setDocument();
+
+// Support: Webkit<537.32 - Safari 6.0.3/Chrome 25 (fixed in Chrome 27)
+// Detached nodes confoundingly follow *each other*
+support.sortDetached = assert(function( div1 ) {
+ // Should return 1, but returns 4 (following)
+ return div1.compareDocumentPosition( document.createElement("div") ) & 1;
+});
+
+// Support: IE<8
+// Prevent attribute/property "interpolation"
+// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
+if ( !assert(function( div ) {
+ div.innerHTML = "<a href='#'></a>";
+ return div.firstChild.getAttribute("href") === "#" ;
+}) ) {
+ addHandle( "type|href|height|width", function( elem, name, isXML ) {
+ if ( !isXML ) {
+ return elem.getAttribute( name, name.toLowerCase() === "type" ? 1 : 2 );
+ }
+ });
+}
+
+// Support: IE<9
+// Use defaultValue in place of getAttribute("value")
+if ( !support.attributes || !assert(function( div ) {
+ div.innerHTML = "<input/>";
+ div.firstChild.setAttribute( "value", "" );
+ return div.firstChild.getAttribute( "value" ) === "";
+}) ) {
+ addHandle( "value", function( elem, name, isXML ) {
+ if ( !isXML && elem.nodeName.toLowerCase() === "input" ) {
+ return elem.defaultValue;
+ }
+ });
+}
+
+// Support: IE<9
+// Use getAttributeNode to fetch booleans when getAttribute lies
+if ( !assert(function( div ) {
+ return div.getAttribute("disabled") == null;
+}) ) {
+ addHandle( booleans, function( elem, name, isXML ) {
+ var val;
+ if ( !isXML ) {
+ return elem[ name ] === true ? name.toLowerCase() :
+ (val = elem.getAttributeNode( name )) && val.specified ?
+ val.value :
+ null;
+ }
+ });
+}
+
+return Sizzle;
+
+})( window );
+
+
+
+jQuery.find = Sizzle;
+jQuery.expr = Sizzle.selectors;
+jQuery.expr[":"] = jQuery.expr.pseudos;
+jQuery.unique = Sizzle.uniqueSort;
+jQuery.text = Sizzle.getText;
+jQuery.isXMLDoc = Sizzle.isXML;
+jQuery.contains = Sizzle.contains;
+
+
+
+var rneedsContext = jQuery.expr.match.needsContext;
+
+var rsingleTag = (/^<(\w+)\s*\/?>(?:<\/\1>|)$/);
+
+
+
+var risSimple = /^.[^:#\[\.,]*$/;
+
+// Implement the identical functionality for filter and not
+function winnow( elements, qualifier, not ) {
+ if ( jQuery.isFunction( qualifier ) ) {
+ return jQuery.grep( elements, function( elem, i ) {
+ /* jshint -W018 */
+ return !!qualifier.call( elem, i, elem ) !== not;
+ });
+
+ }
+
+ if ( qualifier.nodeType ) {
+ return jQuery.grep( elements, function( elem ) {
+ return ( elem === qualifier ) !== not;
+ });
+
+ }
+
+ if ( typeof qualifier === "string" ) {
+ if ( risSimple.test( qualifier ) ) {
+ return jQuery.filter( qualifier, elements, not );
+ }
+
+ qualifier = jQuery.filter( qualifier, elements );
+ }
+
+ return jQuery.grep( elements, function( elem ) {
+ return ( jQuery.inArray( elem, qualifier ) >= 0 ) !== not;
+ });
+}
+
+jQuery.filter = function( expr, elems, not ) {
+ var elem = elems[ 0 ];
+
+ if ( not ) {
+ expr = ":not(" + expr + ")";
+ }
+
+ return elems.length === 1 && elem.nodeType === 1 ?
+ jQuery.find.matchesSelector( elem, expr ) ? [ elem ] : [] :
+ jQuery.find.matches( expr, jQuery.grep( elems, function( elem ) {
+ return elem.nodeType === 1;
+ }));
+};
+
+jQuery.fn.extend({
+ find: function( selector ) {
+ var i,
+ ret = [],
+ self = this,
+ len = self.length;
+
+ if ( typeof selector !== "string" ) {
+ return this.pushStack( jQuery( selector ).filter(function() {
+ for ( i = 0; i < len; i++ ) {
+ if ( jQuery.contains( self[ i ], this ) ) {
+ return true;
+ }
+ }
+ }) );
+ }
+
+ for ( i = 0; i < len; i++ ) {
+ jQuery.find( selector, self[ i ], ret );
+ }
+
+ // Needed because $( selector, context ) becomes $( context ).find( selector )
+ ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret );
+ ret.selector = this.selector ? this.selector + " " + selector : selector;
+ return ret;
+ },
+ filter: function( selector ) {
+ return this.pushStack( winnow(this, selector || [], false) );
+ },
+ not: function( selector ) {
+ return this.pushStack( winnow(this, selector || [], true) );
+ },
+ is: function( selector ) {
+ return !!winnow(
+ this,
+
+ // If this is a positional/relative selector, check membership in the returned set
+ // so $("p:first").is("p:last") won't return true for a doc with two "p".
+ typeof selector === "string" && rneedsContext.test( selector ) ?
+ jQuery( selector ) :
+ selector || [],
+ false
+ ).length;
+ }
+});
+
+
+// Initialize a jQuery object
+
+
+// A central reference to the root jQuery(document)
+var rootjQuery,
+
+ // Use the correct document accordingly with window argument (sandbox)
+ document = window.document,
+
+ // A simple way to check for HTML strings
+ // Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
+ // Strict HTML recognition (#11290: must start with <)
+ rquickExpr = /^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,
+
+ init = jQuery.fn.init = function( selector, context ) {
+ var match, elem;
+
+ // HANDLE: $(""), $(null), $(undefined), $(false)
+ if ( !selector ) {
+ return this;
+ }
+
+ // Handle HTML strings
+ if ( typeof selector === "string" ) {
+ if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
+ // Assume that strings that start and end with <> are HTML and skip the regex check
+ match = [ null, selector, null ];
+
+ } else {
+ match = rquickExpr.exec( selector );
+ }
+
+ // Match html or make sure no context is specified for #id
+ if ( match && (match[1] || !context) ) {
+
+ // HANDLE: $(html) -> $(array)
+ if ( match[1] ) {
+ context = context instanceof jQuery ? context[0] : context;
+
+ // scripts is true for back-compat
+ // Intentionally let the error be thrown if parseHTML is not present
+ jQuery.merge( this, jQuery.parseHTML(
+ match[1],
+ context && context.nodeType ? context.ownerDocument || context : document,
+ true
+ ) );
+
+ // HANDLE: $(html, props)
+ if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) {
+ for ( match in context ) {
+ // Properties of context are called as methods if possible
+ if ( jQuery.isFunction( this[ match ] ) ) {
+ this[ match ]( context[ match ] );
+
+ // ...and otherwise set as attributes
+ } else {
+ this.attr( match, context[ match ] );
+ }
+ }
+ }
+
+ return this;
+
+ // HANDLE: $(#id)
+ } else {
+ elem = document.getElementById( match[2] );
+
+ // Check parentNode to catch when Blackberry 4.6 returns
+ // nodes that are no longer in the document #6963
+ if ( elem && elem.parentNode ) {
+ // Handle the case where IE and Opera return items
+ // by name instead of ID
+ if ( elem.id !== match[2] ) {
+ return rootjQuery.find( selector );
+ }
+
+ // Otherwise, we inject the element directly into the jQuery object
+ this.length = 1;
+ this[0] = elem;
+ }
+
+ this.context = document;
+ this.selector = selector;
+ return this;
+ }
+
+ // HANDLE: $(expr, $(...))
+ } else if ( !context || context.jquery ) {
+ return ( context || rootjQuery ).find( selector );
+
+ // HANDLE: $(expr, context)
+ // (which is just equivalent to: $(context).find(expr)
+ } else {
+ return this.constructor( context ).find( selector );
+ }
+
+ // HANDLE: $(DOMElement)
+ } else if ( selector.nodeType ) {
+ this.context = this[0] = selector;
+ this.length = 1;
+ return this;
+
+ // HANDLE: $(function)
+ // Shortcut for document ready
+ } else if ( jQuery.isFunction( selector ) ) {
+ return typeof rootjQuery.ready !== "undefined" ?
+ rootjQuery.ready( selector ) :
+ // Execute immediately if ready is not present
+ selector( jQuery );
+ }
+
+ if ( selector.selector !== undefined ) {
+ this.selector = selector.selector;
+ this.context = selector.context;
+ }
+
+ return jQuery.makeArray( selector, this );
+ };
+
+// Give the init function the jQuery prototype for later instantiation
+init.prototype = jQuery.fn;
+
+// Initialize central reference
+rootjQuery = jQuery( document );
+
+
+var rparentsprev = /^(?:parents|prev(?:Until|All))/,
+ // methods guaranteed to produce a unique set when starting from a unique set
+ guaranteedUnique = {
+ children: true,
+ contents: true,
+ next: true,
+ prev: true
+ };
+
+jQuery.extend({
+ dir: function( elem, dir, until ) {
+ var matched = [],
+ cur = elem[ dir ];
+
+ while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
+ if ( cur.nodeType === 1 ) {
+ matched.push( cur );
+ }
+ cur = cur[dir];
+ }
+ return matched;
+ },
+
+ sibling: function( n, elem ) {
+ var r = [];
+
+ for ( ; n; n = n.nextSibling ) {
+ if ( n.nodeType === 1 && n !== elem ) {
+ r.push( n );
+ }
+ }
+
+ return r;
+ }
+});
+
+jQuery.fn.extend({
+ has: function( target ) {
+ var i,
+ targets = jQuery( target, this ),
+ len = targets.length;
+
+ return this.filter(function() {
+ for ( i = 0; i < len; i++ ) {
+ if ( jQuery.contains( this, targets[i] ) ) {
+ return true;
+ }
+ }
+ });
+ },
+
+ closest: function( selectors, context ) {
+ var cur,
+ i = 0,
+ l = this.length,
+ matched = [],
+ pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ?
+ jQuery( selectors, context || this.context ) :
+ 0;
+
+ for ( ; i < l; i++ ) {
+ for ( cur = this[i]; cur && cur !== context; cur = cur.parentNode ) {
+ // Always skip document fragments
+ if ( cur.nodeType < 11 && (pos ?
+ pos.index(cur) > -1 :
+
+ // Don't pass non-elements to Sizzle
+ cur.nodeType === 1 &&
+ jQuery.find.matchesSelector(cur, selectors)) ) {
+
+ matched.push( cur );
+ break;
+ }
+ }
+ }
+
+ return this.pushStack( matched.length > 1 ? jQuery.unique( matched ) : matched );
+ },
+
+ // Determine the position of an element within
+ // the matched set of elements
+ index: function( elem ) {
+
+ // No argument, return index in parent
+ if ( !elem ) {
+ return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1;
+ }
+
+ // index in selector
+ if ( typeof elem === "string" ) {
+ return jQuery.inArray( this[0], jQuery( elem ) );
+ }
+
+ // Locate the position of the desired element
+ return jQuery.inArray(
+ // If it receives a jQuery object, the first element is used
+ elem.jquery ? elem[0] : elem, this );
+ },
+
+ add: function( selector, context ) {
+ return this.pushStack(
+ jQuery.unique(
+ jQuery.merge( this.get(), jQuery( selector, context ) )
+ )
+ );
+ },
+
+ addBack: function( selector ) {
+ return this.add( selector == null ?
+ this.prevObject : this.prevObject.filter(selector)
+ );
+ }
+});
+
+function sibling( cur, dir ) {
+ do {
+ cur = cur[ dir ];
+ } while ( cur && cur.nodeType !== 1 );
+
+ return cur;
+}
+
+jQuery.each({
+ parent: function( elem ) {
+ var parent = elem.parentNode;
+ return parent && parent.nodeType !== 11 ? parent : null;
+ },
+ parents: function( elem ) {
+ return jQuery.dir( elem, "parentNode" );
+ },
+ parentsUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "parentNode", until );
+ },
+ next: function( elem ) {
+ return sibling( elem, "nextSibling" );
+ },
+ prev: function( elem ) {
+ return sibling( elem, "previousSibling" );
+ },
+ nextAll: function( elem ) {
+ return jQuery.dir( elem, "nextSibling" );
+ },
+ prevAll: function( elem ) {
+ return jQuery.dir( elem, "previousSibling" );
+ },
+ nextUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "nextSibling", until );
+ },
+ prevUntil: function( elem, i, until ) {
+ return jQuery.dir( elem, "previousSibling", until );
+ },
+ siblings: function( elem ) {
+ return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
+ },
+ children: function( elem ) {
+ return jQuery.sibling( elem.firstChild );
+ },
+ contents: function( elem ) {
+ return jQuery.nodeName( elem, "iframe" ) ?
+ elem.contentDocument || elem.contentWindow.document :
+ jQuery.merge( [], elem.childNodes );
+ }
+}, function( name, fn ) {
+ jQuery.fn[ name ] = function( until, selector ) {
+ var ret = jQuery.map( this, fn, until );
+
+ if ( name.slice( -5 ) !== "Until" ) {
+ selector = until;
+ }
+
+ if ( selector && typeof selector === "string" ) {
+ ret = jQuery.filter( selector, ret );
+ }
+
+ if ( this.length > 1 ) {
+ // Remove duplicates
+ if ( !guaranteedUnique[ name ] ) {
+ ret = jQuery.unique( ret );
+ }
+
+ // Reverse order for parents* and prev-derivatives
+ if ( rparentsprev.test( name ) ) {
+ ret = ret.reverse();
+ }
+ }
+
+ return this.pushStack( ret );
+ };
+});
+var rnotwhite = (/\S+/g);
+
+
+
+// String to Object options format cache
+var optionsCache = {};
+
+// Convert String-formatted options into Object-formatted ones and store in cache
+function createOptions( options ) {
+ var object = optionsCache[ options ] = {};
+ jQuery.each( options.match( rnotwhite ) || [], function( _, flag ) {
+ object[ flag ] = true;
+ });
+ return object;
+}
+
+/*
+ * Create a callback list using the following parameters:
+ *
+ * options: an optional list of space-separated options that will change how
+ * the callback list behaves or a more traditional option object
+ *
+ * By default a callback list will act like an event callback list and can be
+ * "fired" multiple times.
+ *
+ * Possible options:
+ *
+ * once: will ensure the callback list can only be fired once (like a Deferred)
+ *
+ * memory: will keep track of previous values and will call any callback added
+ * after the list has been fired right away with the latest "memorized"
+ * values (like a Deferred)
+ *
+ * unique: will ensure a callback can only be added once (no duplicate in the list)
+ *
+ * stopOnFalse: interrupt callings when a callback returns false
+ *
+ */
+jQuery.Callbacks = function( options ) {
+
+ // Convert options from String-formatted to Object-formatted if needed
+ // (we check in cache first)
+ options = typeof options === "string" ?
+ ( optionsCache[ options ] || createOptions( options ) ) :
+ jQuery.extend( {}, options );
+
+ var // Flag to know if list is currently firing
+ firing,
+ // Last fire value (for non-forgettable lists)
+ memory,
+ // Flag to know if list was already fired
+ fired,
+ // End of the loop when firing
+ firingLength,
+ // Index of currently firing callback (modified by remove if needed)
+ firingIndex,
+ // First callback to fire (used internally by add and fireWith)
+ firingStart,
+ // Actual callback list
+ list = [],
+ // Stack of fire calls for repeatable lists
+ stack = !options.once && [],
+ // Fire callbacks
+ fire = function( data ) {
+ memory = options.memory && data;
+ fired = true;
+ firingIndex = firingStart || 0;
+ firingStart = 0;
+ firingLength = list.length;
+ firing = true;
+ for ( ; list && firingIndex < firingLength; firingIndex++ ) {
+ if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) {
+ memory = false; // To prevent further calls using add
+ break;
+ }
+ }
+ firing = false;
+ if ( list ) {
+ if ( stack ) {
+ if ( stack.length ) {
+ fire( stack.shift() );
+ }
+ } else if ( memory ) {
+ list = [];
+ } else {
+ self.disable();
+ }
+ }
+ },
+ // Actual Callbacks object
+ self = {
+ // Add a callback or a collection of callbacks to the list
+ add: function() {
+ if ( list ) {
+ // First, we save the current length
+ var start = list.length;
+ (function add( args ) {
+ jQuery.each( args, function( _, arg ) {
+ var type = jQuery.type( arg );
+ if ( type === "function" ) {
+ if ( !options.unique || !self.has( arg ) ) {
+ list.push( arg );
+ }
+ } else if ( arg && arg.length && type !== "string" ) {
+ // Inspect recursively
+ add( arg );
+ }
+ });
+ })( arguments );
+ // Do we need to add the callbacks to the
+ // current firing batch?
+ if ( firing ) {
+ firingLength = list.length;
+ // With memory, if we're not firing then
+ // we should call right away
+ } else if ( memory ) {
+ firingStart = start;
+ fire( memory );
+ }
+ }
+ return this;
+ },
+ // Remove a callback from the list
+ remove: function() {
+ if ( list ) {
+ jQuery.each( arguments, function( _, arg ) {
+ var index;
+ while ( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) {
+ list.splice( index, 1 );
+ // Handle firing indexes
+ if ( firing ) {
+ if ( index <= firingLength ) {
+ firingLength--;
+ }
+ if ( index <= firingIndex ) {
+ firingIndex--;
+ }
+ }
+ }
+ });
+ }
+ return this;
+ },
+ // Check if a given callback is in the list.
+ // If no argument is given, return whether or not list has callbacks attached.
+ has: function( fn ) {
+ return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length );
+ },
+ // Remove all callbacks from the list
+ empty: function() {
+ list = [];
+ firingLength = 0;
+ return this;
+ },
+ // Have the list do nothing anymore
+ disable: function() {
+ list = stack = memory = undefined;
+ return this;
+ },
+ // Is it disabled?
+ disabled: function() {
+ return !list;
+ },
+ // Lock the list in its current state
+ lock: function() {
+ stack = undefined;
+ if ( !memory ) {
+ self.disable();
+ }
+ return this;
+ },
+ // Is it locked?
+ locked: function() {
+ return !stack;
+ },
+ // Call all callbacks with the given context and arguments
+ fireWith: function( context, args ) {
+ if ( list && ( !fired || stack ) ) {
+ args = args || [];
+ args = [ context, args.slice ? args.slice() : args ];
+ if ( firing ) {
+ stack.push( args );
+ } else {
+ fire( args );
+ }
+ }
+ return this;
+ },
+ // Call all the callbacks with the given arguments
+ fire: function() {
+ self.fireWith( this, arguments );
+ return this;
+ },
+ // To know if the callbacks have already been called at least once
+ fired: function() {
+ return !!fired;
+ }
+ };
+
+ return self;
+};
+
+
+jQuery.extend({
+
+ Deferred: function( func ) {
+ var tuples = [
+ // action, add listener, listener list, final state
+ [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ],
+ [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ],
+ [ "notify", "progress", jQuery.Callbacks("memory") ]
+ ],
+ state = "pending",
+ promise = {
+ state: function() {
+ return state;
+ },
+ always: function() {
+ deferred.done( arguments ).fail( arguments );
+ return this;
+ },
+ then: function( /* fnDone, fnFail, fnProgress */ ) {
+ var fns = arguments;
+ return jQuery.Deferred(function( newDefer ) {
+ jQuery.each( tuples, function( i, tuple ) {
+ var fn = jQuery.isFunction( fns[ i ] ) && fns[ i ];
+ // deferred[ done | fail | progress ] for forwarding actions to newDefer
+ deferred[ tuple[1] ](function() {
+ var returned = fn && fn.apply( this, arguments );
+ if ( returned && jQuery.isFunction( returned.promise ) ) {
+ returned.promise()
+ .done( newDefer.resolve )
+ .fail( newDefer.reject )
+ .progress( newDefer.notify );
+ } else {
+ newDefer[ tuple[ 0 ] + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments );
+ }
+ });
+ });
+ fns = null;
+ }).promise();
+ },
+ // Get a promise for this deferred
+ // If obj is provided, the promise aspect is added to the object
+ promise: function( obj ) {
+ return obj != null ? jQuery.extend( obj, promise ) : promise;
+ }
+ },
+ deferred = {};
+
+ // Keep pipe for back-compat
+ promise.pipe = promise.then;
+
+ // Add list-specific methods
+ jQuery.each( tuples, function( i, tuple ) {
+ var list = tuple[ 2 ],
+ stateString = tuple[ 3 ];
+
+ // promise[ done | fail | progress ] = list.add
+ promise[ tuple[1] ] = list.add;
+
+ // Handle state
+ if ( stateString ) {
+ list.add(function() {
+ // state = [ resolved | rejected ]
+ state = stateString;
+
+ // [ reject_list | resolve_list ].disable; progress_list.lock
+ }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock );
+ }
+
+ // deferred[ resolve | reject | notify ]
+ deferred[ tuple[0] ] = function() {
+ deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments );
+ return this;
+ };
+ deferred[ tuple[0] + "With" ] = list.fireWith;
+ });
+
+ // Make the deferred a promise
+ promise.promise( deferred );
+
+ // Call given func if any
+ if ( func ) {
+ func.call( deferred, deferred );
+ }
+
+ // All done!
+ return deferred;
+ },
+
+ // Deferred helper
+ when: function( subordinate /* , ..., subordinateN */ ) {
+ var i = 0,
+ resolveValues = slice.call( arguments ),
+ length = resolveValues.length,
+
+ // the count of uncompleted subordinates
+ remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0,
+
+ // the master Deferred. If resolveValues consist of only a single Deferred, just use that.
+ deferred = remaining === 1 ? subordinate : jQuery.Deferred(),
+
+ // Update function for both resolve and progress values
+ updateFunc = function( i, contexts, values ) {
+ return function( value ) {
+ contexts[ i ] = this;
+ values[ i ] = arguments.length > 1 ? slice.call( arguments ) : value;
+ if ( values === progressValues ) {
+ deferred.notifyWith( contexts, values );
+
+ } else if ( !(--remaining) ) {
+ deferred.resolveWith( contexts, values );
+ }
+ };
+ },
+
+ progressValues, progressContexts, resolveContexts;
+
+ // add listeners to Deferred subordinates; treat others as resolved
+ if ( length > 1 ) {
+ progressValues = new Array( length );
+ progressContexts = new Array( length );
+ resolveContexts = new Array( length );
+ for ( ; i < length; i++ ) {
+ if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) {
+ resolveValues[ i ].promise()
+ .done( updateFunc( i, resolveContexts, resolveValues ) )
+ .fail( deferred.reject )
+ .progress( updateFunc( i, progressContexts, progressValues ) );
+ } else {
+ --remaining;
+ }
+ }
+ }
+
+ // if we're not waiting on anything, resolve the master
+ if ( !remaining ) {
+ deferred.resolveWith( resolveContexts, resolveValues );
+ }
+
+ return deferred.promise();
+ }
+});
+
+
+// The deferred used on DOM ready
+var readyList;
+
+jQuery.fn.ready = function( fn ) {
+ // Add the callback
+ jQuery.ready.promise().done( fn );
+
+ return this;
+};
+
+jQuery.extend({
+ // Is the DOM ready to be used? Set to true once it occurs.
+ isReady: false,
+
+ // A counter to track how many items to wait for before
+ // the ready event fires. See #6781
+ readyWait: 1,
+
+ // Hold (or release) the ready event
+ holdReady: function( hold ) {
+ if ( hold ) {
+ jQuery.readyWait++;
+ } else {
+ jQuery.ready( true );
+ }
+ },
+
+ // Handle when the DOM is ready
+ ready: function( wait ) {
+
+ // Abort if there are pending holds or we're already ready
+ if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) {
+ return;
+ }
+
+ // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
+ if ( !document.body ) {
+ return setTimeout( jQuery.ready );
+ }
+
+ // Remember that the DOM is ready
+ jQuery.isReady = true;
+
+ // If a normal DOM Ready event fired, decrement, and wait if need be
+ if ( wait !== true && --jQuery.readyWait > 0 ) {
+ return;
+ }
+
+ // If there are functions bound, to execute
+ readyList.resolveWith( document, [ jQuery ] );
+
+ // Trigger any bound ready events
+ if ( jQuery.fn.triggerHandler ) {
+ jQuery( document ).triggerHandler( "ready" );
+ jQuery( document ).off( "ready" );
+ }
+ }
+});
+
+/**
+ * Clean-up method for dom ready events
+ */
+function detach() {
+ if ( document.addEventListener ) {
+ document.removeEventListener( "DOMContentLoaded", completed, false );
+ window.removeEventListener( "load", completed, false );
+
+ } else {
+ document.detachEvent( "onreadystatechange", completed );
+ window.detachEvent( "onload", completed );
+ }
+}
+
+/**
+ * The ready event handler and self cleanup method
+ */
+function completed() {
+ // readyState === "complete" is good enough for us to call the dom ready in oldIE
+ if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) {
+ detach();
+ jQuery.ready();
+ }
+}
+
+jQuery.ready.promise = function( obj ) {
+ if ( !readyList ) {
+
+ readyList = jQuery.Deferred();
+
+ // Catch cases where $(document).ready() is called after the browser event has already occurred.
+ // we once tried to use readyState "interactive" here, but it caused issues like the one
+ // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15
+ if ( document.readyState === "complete" ) {
+ // Handle it asynchronously to allow scripts the opportunity to delay ready
+ setTimeout( jQuery.ready );
+
+ // Standards-based browsers support DOMContentLoaded
+ } else if ( document.addEventListener ) {
+ // Use the handy event callback
+ document.addEventListener( "DOMContentLoaded", completed, false );
+
+ // A fallback to window.onload, that will always work
+ window.addEventListener( "load", completed, false );
+
+ // If IE event model is used
+ } else {
+ // Ensure firing before onload, maybe late but safe also for iframes
+ document.attachEvent( "onreadystatechange", completed );
+
+ // A fallback to window.onload, that will always work
+ window.attachEvent( "onload", completed );
+
+ // If IE and not a frame
+ // continually check to see if the document is ready
+ var top = false;
+
+ try {
+ top = window.frameElement == null && document.documentElement;
+ } catch(e) {}
+
+ if ( top && top.doScroll ) {
+ (function doScrollCheck() {
+ if ( !jQuery.isReady ) {
+
+ try {
+ // Use the trick by Diego Perini
+ // http://javascript.nwbox.com/IEContentLoaded/
+ top.doScroll("left");
+ } catch(e) {
+ return setTimeout( doScrollCheck, 50 );
+ }
+
+ // detach all dom ready events
+ detach();
+
+ // and execute any waiting functions
+ jQuery.ready();
+ }
+ })();
+ }
+ }
+ }
+ return readyList.promise( obj );
+};
+
+
+var strundefined = typeof undefined;
+
+
+
+// Support: IE<9
+// Iteration over object's inherited properties before its own
+var i;
+for ( i in jQuery( support ) ) {
+ break;
+}
+support.ownLast = i !== "0";
+
+// Note: most support tests are defined in their respective modules.
+// false until the test is run
+support.inlineBlockNeedsLayout = false;
+
+// Execute ASAP in case we need to set body.style.zoom
+jQuery(function() {
+ // Minified: var a,b,c,d
+ var val, div, body, container;
+
+ body = document.getElementsByTagName( "body" )[ 0 ];
+ if ( !body || !body.style ) {
+ // Return for frameset docs that don't have a body
+ return;
+ }
+
+ // Setup
+ div = document.createElement( "div" );
+ container = document.createElement( "div" );
+ container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
+ body.appendChild( container ).appendChild( div );
+
+ if ( typeof div.style.zoom !== strundefined ) {
+ // Support: IE<8
+ // Check if natively block-level elements act like inline-block
+ // elements when setting their display to 'inline' and giving
+ // them layout
+ div.style.cssText = "display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";
+
+ support.inlineBlockNeedsLayout = val = div.offsetWidth === 3;
+ if ( val ) {
+ // Prevent IE 6 from affecting layout for positioned elements #11048
+ // Prevent IE from shrinking the body in IE 7 mode #12869
+ // Support: IE<8
+ body.style.zoom = 1;
+ }
+ }
+
+ body.removeChild( container );
+});
+
+
+
+
+(function() {
+ var div = document.createElement( "div" );
+
+ // Execute the test only if not already executed in another module.
+ if (support.deleteExpando == null) {
+ // Support: IE<9
+ support.deleteExpando = true;
+ try {
+ delete div.test;
+ } catch( e ) {
+ support.deleteExpando = false;
+ }
+ }
+
+ // Null elements to avoid leaks in IE.
+ div = null;
+})();
+
+
+/**
+ * Determines whether an object can have data
+ */
+jQuery.acceptData = function( elem ) {
+ var noData = jQuery.noData[ (elem.nodeName + " ").toLowerCase() ],
+ nodeType = +elem.nodeType || 1;
+
+ // Do not set data on non-element DOM nodes because it will not be cleared (#8335).
+ return nodeType !== 1 && nodeType !== 9 ?
+ false :
+
+ // Nodes accept data unless otherwise specified; rejection can be conditional
+ !noData || noData !== true && elem.getAttribute("classid") === noData;
+};
+
+
+var rbrace = /^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,
+ rmultiDash = /([A-Z])/g;
+
+function dataAttr( elem, key, data ) {
+ // If nothing was found internally, try to fetch any
+ // data from the HTML5 data-* attribute
+ if ( data === undefined && elem.nodeType === 1 ) {
+
+ var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase();
+
+ data = elem.getAttribute( name );
+
+ if ( typeof data === "string" ) {
+ try {
+ data = data === "true" ? true :
+ data === "false" ? false :
+ data === "null" ? null :
+ // Only convert to a number if it doesn't change the string
+ +data + "" === data ? +data :
+ rbrace.test( data ) ? jQuery.parseJSON( data ) :
+ data;
+ } catch( e ) {}
+
+ // Make sure we set the data so it isn't changed later
+ jQuery.data( elem, key, data );
+
+ } else {
+ data = undefined;
+ }
+ }
+
+ return data;
+}
+
+// checks a cache object for emptiness
+function isEmptyDataObject( obj ) {
+ var name;
+ for ( name in obj ) {
+
+ // if the public data object is empty, the private is still empty
+ if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
+ continue;
+ }
+ if ( name !== "toJSON" ) {
+ return false;
+ }
+ }
+
+ return true;
+}
+
+function internalData( elem, name, data, pvt /* Internal Use Only */ ) {
+ if ( !jQuery.acceptData( elem ) ) {
+ return;
+ }
+
+ var ret, thisCache,
+ internalKey = jQuery.expando,
+
+ // We have to handle DOM nodes and JS objects differently because IE6-7
+ // can't GC object references properly across the DOM-JS boundary
+ isNode = elem.nodeType,
+
+ // Only DOM nodes need the global jQuery cache; JS object data is
+ // attached directly to the object so GC can occur automatically
+ cache = isNode ? jQuery.cache : elem,
+
+ // Only defining an ID for JS objects if its cache already exists allows
+ // the code to shortcut on the same path as a DOM node with no cache
+ id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey;
+
+ // Avoid doing any more work than we need to when trying to get data on an
+ // object that has no data at all
+ if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && data === undefined && typeof name === "string" ) {
+ return;
+ }
+
+ if ( !id ) {
+ // Only DOM nodes need a new unique ID for each element since their data
+ // ends up in the global cache
+ if ( isNode ) {
+ id = elem[ internalKey ] = deletedIds.pop() || jQuery.guid++;
+ } else {
+ id = internalKey;
+ }
+ }
+
+ if ( !cache[ id ] ) {
+ // Avoid exposing jQuery metadata on plain JS objects when the object
+ // is serialized using JSON.stringify
+ cache[ id ] = isNode ? {} : { toJSON: jQuery.noop };
+ }
+
+ // An object can be passed to jQuery.data instead of a key/value pair; this gets
+ // shallow copied over onto the existing cache
+ if ( typeof name === "object" || typeof name === "function" ) {
+ if ( pvt ) {
+ cache[ id ] = jQuery.extend( cache[ id ], name );
+ } else {
+ cache[ id ].data = jQuery.extend( cache[ id ].data, name );
+ }
+ }
+
+ thisCache = cache[ id ];
+
+ // jQuery data() is stored in a separate object inside the object's internal data
+ // cache in order to avoid key collisions between internal data and user-defined
+ // data.
+ if ( !pvt ) {
+ if ( !thisCache.data ) {
+ thisCache.data = {};
+ }
+
+ thisCache = thisCache.data;
+ }
+
+ if ( data !== undefined ) {
+ thisCache[ jQuery.camelCase( name ) ] = data;
+ }
+
+ // Check for both converted-to-camel and non-converted data property names
+ // If a data property was specified
+ if ( typeof name === "string" ) {
+
+ // First Try to find as-is property data
+ ret = thisCache[ name ];
+
+ // Test for null|undefined property data
+ if ( ret == null ) {
+
+ // Try to find the camelCased property
+ ret = thisCache[ jQuery.camelCase( name ) ];
+ }
+ } else {
+ ret = thisCache;
+ }
+
+ return ret;
+}
+
+function internalRemoveData( elem, name, pvt ) {
+ if ( !jQuery.acceptData( elem ) ) {
+ return;
+ }
+
+ var thisCache, i,
+ isNode = elem.nodeType,
+
+ // See jQuery.data for more information
+ cache = isNode ? jQuery.cache : elem,
+ id = isNode ? elem[ jQuery.expando ] : jQuery.expando;
+
+ // If there is already no cache entry for this object, there is no
+ // purpose in continuing
+ if ( !cache[ id ] ) {
+ return;
+ }
+
+ if ( name ) {
+
+ thisCache = pvt ? cache[ id ] : cache[ id ].data;
+
+ if ( thisCache ) {
+
+ // Support array or space separated string names for data keys
+ if ( !jQuery.isArray( name ) ) {
+
+ // try the string as a key before any manipulation
+ if ( name in thisCache ) {
+ name = [ name ];
+ } else {
+
+ // split the camel cased version by spaces unless a key with the spaces exists
+ name = jQuery.camelCase( name );
+ if ( name in thisCache ) {
+ name = [ name ];
+ } else {
+ name = name.split(" ");
+ }
+ }
+ } else {
+ // If "name" is an array of keys...
+ // When data is initially created, via ("key", "val") signature,
+ // keys will be converted to camelCase.
+ // Since there is no way to tell _how_ a key was added, remove
+ // both plain key and camelCase key. #12786
+ // This will only penalize the array argument path.
+ name = name.concat( jQuery.map( name, jQuery.camelCase ) );
+ }
+
+ i = name.length;
+ while ( i-- ) {
+ delete thisCache[ name[i] ];
+ }
+
+ // If there is no data left in the cache, we want to continue
+ // and let the cache object itself get destroyed
+ if ( pvt ? !isEmptyDataObject(thisCache) : !jQuery.isEmptyObject(thisCache) ) {
+ return;
+ }
+ }
+ }
+
+ // See jQuery.data for more information
+ if ( !pvt ) {
+ delete cache[ id ].data;
+
+ // Don't destroy the parent cache unless the internal data object
+ // had been the only thing left in it
+ if ( !isEmptyDataObject( cache[ id ] ) ) {
+ return;
+ }
+ }
+
+ // Destroy the cache
+ if ( isNode ) {
+ jQuery.cleanData( [ elem ], true );
+
+ // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080)
+ /* jshint eqeqeq: false */
+ } else if ( support.deleteExpando || cache != cache.window ) {
+ /* jshint eqeqeq: true */
+ delete cache[ id ];
+
+ // When all else fails, null
+ } else {
+ cache[ id ] = null;
+ }
+}
+
+jQuery.extend({
+ cache: {},
+
+ // The following elements (space-suffixed to avoid Object.prototype collisions)
+ // throw uncatchable exceptions if you attempt to set expando properties
+ noData: {
+ "applet ": true,
+ "embed ": true,
+ // ...but Flash objects (which have this classid) *can* handle expandos
+ "object ": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"
+ },
+
+ hasData: function( elem ) {
+ elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
+ return !!elem && !isEmptyDataObject( elem );
+ },
+
+ data: function( elem, name, data ) {
+ return internalData( elem, name, data );
+ },
+
+ removeData: function( elem, name ) {
+ return internalRemoveData( elem, name );
+ },
+
+ // For internal use only.
+ _data: function( elem, name, data ) {
+ return internalData( elem, name, data, true );
+ },
+
+ _removeData: function( elem, name ) {
+ return internalRemoveData( elem, name, true );
+ }
+});
+
+jQuery.fn.extend({
+ data: function( key, value ) {
+ var i, name, data,
+ elem = this[0],
+ attrs = elem && elem.attributes;
+
+ // Special expections of .data basically thwart jQuery.access,
+ // so implement the relevant behavior ourselves
+
+ // Gets all values
+ if ( key === undefined ) {
+ if ( this.length ) {
+ data = jQuery.data( elem );
+
+ if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) {
+ i = attrs.length;
+ while ( i-- ) {
+
+ // Support: IE11+
+ // The attrs elements can be null (#14894)
+ if ( attrs[ i ] ) {
+ name = attrs[ i ].name;
+ if ( name.indexOf( "data-" ) === 0 ) {
+ name = jQuery.camelCase( name.slice(5) );
+ dataAttr( elem, name, data[ name ] );
+ }
+ }
+ }
+ jQuery._data( elem, "parsedAttrs", true );
+ }
+ }
+
+ return data;
+ }
+
+ // Sets multiple values
+ if ( typeof key === "object" ) {
+ return this.each(function() {
+ jQuery.data( this, key );
+ });
+ }
+
+ return arguments.length > 1 ?
+
+ // Sets one value
+ this.each(function() {
+ jQuery.data( this, key, value );
+ }) :
+
+ // Gets one value
+ // Try to fetch any internally stored data first
+ elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : undefined;
+ },
+
+ removeData: function( key ) {
+ return this.each(function() {
+ jQuery.removeData( this, key );
+ });
+ }
+});
+
+
+jQuery.extend({
+ queue: function( elem, type, data ) {
+ var queue;
+
+ if ( elem ) {
+ type = ( type || "fx" ) + "queue";
+ queue = jQuery._data( elem, type );
+
+ // Speed up dequeue by getting out quickly if this is just a lookup
+ if ( data ) {
+ if ( !queue || jQuery.isArray(data) ) {
+ queue = jQuery._data( elem, type, jQuery.makeArray(data) );
+ } else {
+ queue.push( data );
+ }
+ }
+ return queue || [];
+ }
+ },
+
+ dequeue: function( elem, type ) {
+ type = type || "fx";
+
+ var queue = jQuery.queue( elem, type ),
+ startLength = queue.length,
+ fn = queue.shift(),
+ hooks = jQuery._queueHooks( elem, type ),
+ next = function() {
+ jQuery.dequeue( elem, type );
+ };
+
+ // If the fx queue is dequeued, always remove the progress sentinel
+ if ( fn === "inprogress" ) {
+ fn = queue.shift();
+ startLength--;
+ }
+
+ if ( fn ) {
+
+ // Add a progress sentinel to prevent the fx queue from being
+ // automatically dequeued
+ if ( type === "fx" ) {
+ queue.unshift( "inprogress" );
+ }
+
+ // clear up the last queue stop function
+ delete hooks.stop;
+ fn.call( elem, next, hooks );
+ }
+
+ if ( !startLength && hooks ) {
+ hooks.empty.fire();
+ }
+ },
+
+ // not intended for public consumption - generates a queueHooks object, or returns the current one
+ _queueHooks: function( elem, type ) {
+ var key = type + "queueHooks";
+ return jQuery._data( elem, key ) || jQuery._data( elem, key, {
+ empty: jQuery.Callbacks("once memory").add(function() {
+ jQuery._removeData( elem, type + "queue" );
+ jQuery._removeData( elem, key );
+ })
+ });
+ }
+});
+
+jQuery.fn.extend({
+ queue: function( type, data ) {
+ var setter = 2;
+
+ if ( typeof type !== "string" ) {
+ data = type;
+ type = "fx";
+ setter--;
+ }
+
+ if ( arguments.length < setter ) {
+ return jQuery.queue( this[0], type );
+ }
+
+ return data === undefined ?
+ this :
+ this.each(function() {
+ var queue = jQuery.queue( this, type, data );
+
+ // ensure a hooks for this queue
+ jQuery._queueHooks( this, type );
+
+ if ( type === "fx" && queue[0] !== "inprogress" ) {
+ jQuery.dequeue( this, type );
+ }
+ });
+ },
+ dequeue: function( type ) {
+ return this.each(function() {
+ jQuery.dequeue( this, type );
+ });
+ },
+ clearQueue: function( type ) {
+ return this.queue( type || "fx", [] );
+ },
+ // Get a promise resolved when queues of a certain type
+ // are emptied (fx is the type by default)
+ promise: function( type, obj ) {
+ var tmp,
+ count = 1,
+ defer = jQuery.Deferred(),
+ elements = this,
+ i = this.length,
+ resolve = function() {
+ if ( !( --count ) ) {
+ defer.resolveWith( elements, [ elements ] );
+ }
+ };
+
+ if ( typeof type !== "string" ) {
+ obj = type;
+ type = undefined;
+ }
+ type = type || "fx";
+
+ while ( i-- ) {
+ tmp = jQuery._data( elements[ i ], type + "queueHooks" );
+ if ( tmp && tmp.empty ) {
+ count++;
+ tmp.empty.add( resolve );
+ }
+ }
+ resolve();
+ return defer.promise( obj );
+ }
+});
+var pnum = (/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/).source;
+
+var cssExpand = [ "Top", "Right", "Bottom", "Left" ];
+
+var isHidden = function( elem, el ) {
+ // isHidden might be called from jQuery#filter function;
+ // in that case, element will be second argument
+ elem = el || elem;
+ return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem );
+ };
+
+
+
+// Multifunctional method to get and set values of a collection
+// The value/s can optionally be executed if it's a function
+var access = jQuery.access = function( elems, fn, key, value, chainable, emptyGet, raw ) {
+ var i = 0,
+ length = elems.length,
+ bulk = key == null;
+
+ // Sets many values
+ if ( jQuery.type( key ) === "object" ) {
+ chainable = true;
+ for ( i in key ) {
+ jQuery.access( elems, fn, i, key[i], true, emptyGet, raw );
+ }
+
+ // Sets one value
+ } else if ( value !== undefined ) {
+ chainable = true;
+
+ if ( !jQuery.isFunction( value ) ) {
+ raw = true;
+ }
+
+ if ( bulk ) {
+ // Bulk operations run against the entire set
+ if ( raw ) {
+ fn.call( elems, value );
+ fn = null;
+
+ // ...except when executing function values
+ } else {
+ bulk = fn;
+ fn = function( elem, key, value ) {
+ return bulk.call( jQuery( elem ), value );
+ };
+ }
+ }
+
+ if ( fn ) {
+ for ( ; i < length; i++ ) {
+ fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) );
+ }
+ }
+ }
+
+ return chainable ?
+ elems :
+
+ // Gets
+ bulk ?
+ fn.call( elems ) :
+ length ? fn( elems[0], key ) : emptyGet;
+};
+var rcheckableType = (/^(?:checkbox|radio)$/i);
+
+
+
+(function() {
+ // Minified: var a,b,c
+ var input = document.createElement( "input" ),
+ div = document.createElement( "div" ),
+ fragment = document.createDocumentFragment();
+
+ // Setup
+ div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
+
+ // IE strips leading whitespace when .innerHTML is used
+ support.leadingWhitespace = div.firstChild.nodeType === 3;
+
+ // Make sure that tbody elements aren't automatically inserted
+ // IE will insert them into empty tables
+ support.tbody = !div.getElementsByTagName( "tbody" ).length;
+
+ // Make sure that link elements get serialized correctly by innerHTML
+ // This requires a wrapper element in IE
+ support.htmlSerialize = !!div.getElementsByTagName( "link" ).length;
+
+ // Makes sure cloning an html5 element does not cause problems
+ // Where outerHTML is undefined, this still works
+ support.html5Clone =
+ document.createElement( "nav" ).cloneNode( true ).outerHTML !== "<:nav></:nav>";
+
+ // Check if a disconnected checkbox will retain its checked
+ // value of true after appended to the DOM (IE6/7)
+ input.type = "checkbox";
+ input.checked = true;
+ fragment.appendChild( input );
+ support.appendChecked = input.checked;
+
+ // Make sure textarea (and checkbox) defaultValue is properly cloned
+ // Support: IE6-IE11+
+ div.innerHTML = "<textarea>x</textarea>";
+ support.noCloneChecked = !!div.cloneNode( true ).lastChild.defaultValue;
+
+ // #11217 - WebKit loses check when the name is after the checked attribute
+ fragment.appendChild( div );
+ div.innerHTML = "<input type='radio' checked='checked' name='t'/>";
+
+ // Support: Safari 5.1, iOS 5.1, Android 4.x, Android 2.3
+ // old WebKit doesn't clone checked state correctly in fragments
+ support.checkClone = div.cloneNode( true ).cloneNode( true ).lastChild.checked;
+
+ // Support: IE<9
+ // Opera does not clone events (and typeof div.attachEvent === undefined).
+ // IE9-10 clones events bound via attachEvent, but they don't trigger with .click()
+ support.noCloneEvent = true;
+ if ( div.attachEvent ) {
+ div.attachEvent( "onclick", function() {
+ support.noCloneEvent = false;
+ });
+
+ div.cloneNode( true ).click();
+ }
+
+ // Execute the test only if not already executed in another module.
+ if (support.deleteExpando == null) {
+ // Support: IE<9
+ support.deleteExpando = true;
+ try {
+ delete div.test;
+ } catch( e ) {
+ support.deleteExpando = false;
+ }
+ }
+})();
+
+
+(function() {
+ var i, eventName,
+ div = document.createElement( "div" );
+
+ // Support: IE<9 (lack submit/change bubble), Firefox 23+ (lack focusin event)
+ for ( i in { submit: true, change: true, focusin: true }) {
+ eventName = "on" + i;
+
+ if ( !(support[ i + "Bubbles" ] = eventName in window) ) {
+ // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP)
+ div.setAttribute( eventName, "t" );
+ support[ i + "Bubbles" ] = div.attributes[ eventName ].expando === false;
+ }
+ }
+
+ // Null elements to avoid leaks in IE.
+ div = null;
+})();
+
+
+var rformElems = /^(?:input|select|textarea)$/i,
+ rkeyEvent = /^key/,
+ rmouseEvent = /^(?:mouse|pointer|contextmenu)|click/,
+ rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
+ rtypenamespace = /^([^.]*)(?:\.(.+)|)$/;
+
+function returnTrue() {
+ return true;
+}
+
+function returnFalse() {
+ return false;
+}
+
+function safeActiveElement() {
+ try {
+ return document.activeElement;
+ } catch ( err ) { }
+}
+
+/*
+ * Helper functions for managing events -- not part of the public interface.
+ * Props to Dean Edwards' addEvent library for many of the ideas.
+ */
+jQuery.event = {
+
+ global: {},
+
+ add: function( elem, types, handler, data, selector ) {
+ var tmp, events, t, handleObjIn,
+ special, eventHandle, handleObj,
+ handlers, type, namespaces, origType,
+ elemData = jQuery._data( elem );
+
+ // Don't attach events to noData or text/comment nodes (but allow plain objects)
+ if ( !elemData ) {
+ return;
+ }
+
+ // Caller can pass in an object of custom data in lieu of the handler
+ if ( handler.handler ) {
+ handleObjIn = handler;
+ handler = handleObjIn.handler;
+ selector = handleObjIn.selector;
+ }
+
+ // Make sure that the handler has a unique ID, used to find/remove it later
+ if ( !handler.guid ) {
+ handler.guid = jQuery.guid++;
+ }
+
+ // Init the element's event structure and main handler, if this is the first
+ if ( !(events = elemData.events) ) {
+ events = elemData.events = {};
+ }
+ if ( !(eventHandle = elemData.handle) ) {
+ eventHandle = elemData.handle = function( e ) {
+ // Discard the second event of a jQuery.event.trigger() and
+ // when an event is called after a page has unloaded
+ return typeof jQuery !== strundefined && (!e || jQuery.event.triggered !== e.type) ?
+ jQuery.event.dispatch.apply( eventHandle.elem, arguments ) :
+ undefined;
+ };
+ // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events
+ eventHandle.elem = elem;
+ }
+
+ // Handle multiple events separated by a space
+ types = ( types || "" ).match( rnotwhite ) || [ "" ];
+ t = types.length;
+ while ( t-- ) {
+ tmp = rtypenamespace.exec( types[t] ) || [];
+ type = origType = tmp[1];
+ namespaces = ( tmp[2] || "" ).split( "." ).sort();
+
+ // There *must* be a type, no attaching namespace-only handlers
+ if ( !type ) {
+ continue;
+ }
+
+ // If event changes its type, use the special event handlers for the changed type
+ special = jQuery.event.special[ type ] || {};
+
+ // If selector defined, determine special event api type, otherwise given type
+ type = ( selector ? special.delegateType : special.bindType ) || type;
+
+ // Update special based on newly reset type
+ special = jQuery.event.special[ type ] || {};
+
+ // handleObj is passed to all event handlers
+ handleObj = jQuery.extend({
+ type: type,
+ origType: origType,
+ data: data,
+ handler: handler,
+ guid: handler.guid,
+ selector: selector,
+ needsContext: selector && jQuery.expr.match.needsContext.test( selector ),
+ namespace: namespaces.join(".")
+ }, handleObjIn );
+
+ // Init the event handler queue if we're the first
+ if ( !(handlers = events[ type ]) ) {
+ handlers = events[ type ] = [];
+ handlers.delegateCount = 0;
+
+ // Only use addEventListener/attachEvent if the special events handler returns false
+ if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
+ // Bind the global event handler to the element
+ if ( elem.addEventListener ) {
+ elem.addEventListener( type, eventHandle, false );
+
+ } else if ( elem.attachEvent ) {
+ elem.attachEvent( "on" + type, eventHandle );
+ }
+ }
+ }
+
+ if ( special.add ) {
+ special.add.call( elem, handleObj );
+
+ if ( !handleObj.handler.guid ) {
+ handleObj.handler.guid = handler.guid;
+ }
+ }
+
+ // Add to the element's handler list, delegates in front
+ if ( selector ) {
+ handlers.splice( handlers.delegateCount++, 0, handleObj );
+ } else {
+ handlers.push( handleObj );
+ }
+
+ // Keep track of which events have ever been used, for event optimization
+ jQuery.event.global[ type ] = true;
+ }
+
+ // Nullify elem to prevent memory leaks in IE
+ elem = null;
+ },
+
+ // Detach an event or set of events from an element
+ remove: function( elem, types, handler, selector, mappedTypes ) {
+ var j, handleObj, tmp,
+ origCount, t, events,
+ special, handlers, type,
+ namespaces, origType,
+ elemData = jQuery.hasData( elem ) && jQuery._data( elem );
+
+ if ( !elemData || !(events = elemData.events) ) {
+ return;
+ }
+
+ // Once for each type.namespace in types; type may be omitted
+ types = ( types || "" ).match( rnotwhite ) || [ "" ];
+ t = types.length;
+ while ( t-- ) {
+ tmp = rtypenamespace.exec( types[t] ) || [];
+ type = origType = tmp[1];
+ namespaces = ( tmp[2] || "" ).split( "." ).sort();
+
+ // Unbind all events (on this namespace, if provided) for the element
+ if ( !type ) {
+ for ( type in events ) {
+ jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
+ }
+ continue;
+ }
+
+ special = jQuery.event.special[ type ] || {};
+ type = ( selector ? special.delegateType : special.bindType ) || type;
+ handlers = events[ type ] || [];
+ tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" );
+
+ // Remove matching events
+ origCount = j = handlers.length;
+ while ( j-- ) {
+ handleObj = handlers[ j ];
+
+ if ( ( mappedTypes || origType === handleObj.origType ) &&
+ ( !handler || handler.guid === handleObj.guid ) &&
+ ( !tmp || tmp.test( handleObj.namespace ) ) &&
+ ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
+ handlers.splice( j, 1 );
+
+ if ( handleObj.selector ) {
+ handlers.delegateCount--;
+ }
+ if ( special.remove ) {
+ special.remove.call( elem, handleObj );
+ }
+ }
+ }
+
+ // Remove generic event handler if we removed something and no more handlers exist
+ // (avoids potential for endless recursion during removal of special event handlers)
+ if ( origCount && !handlers.length ) {
+ if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) {
+ jQuery.removeEvent( elem, type, elemData.handle );
+ }
+
+ delete events[ type ];
+ }
+ }
+
+ // Remove the expando if it's no longer used
+ if ( jQuery.isEmptyObject( events ) ) {
+ delete elemData.handle;
+
+ // removeData also checks for emptiness and clears the expando if empty
+ // so use it instead of delete
+ jQuery._removeData( elem, "events" );
+ }
+ },
+
+ trigger: function( event, data, elem, onlyHandlers ) {
+ var handle, ontype, cur,
+ bubbleType, special, tmp, i,
+ eventPath = [ elem || document ],
+ type = hasOwn.call( event, "type" ) ? event.type : event,
+ namespaces = hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : [];
+
+ cur = tmp = elem = elem || document;
+
+ // Don't do events on text and comment nodes
+ if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
+ return;
+ }
+
+ // focus/blur morphs to focusin/out; ensure we're not firing them right now
+ if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
+ return;
+ }
+
+ if ( type.indexOf(".") >= 0 ) {
+ // Namespaced trigger; create a regexp to match event type in handle()
+ namespaces = type.split(".");
+ type = namespaces.shift();
+ namespaces.sort();
+ }
+ ontype = type.indexOf(":") < 0 && "on" + type;
+
+ // Caller can pass in a jQuery.Event object, Object, or just an event type string
+ event = event[ jQuery.expando ] ?
+ event :
+ new jQuery.Event( type, typeof event === "object" && event );
+
+ // Trigger bitmask: & 1 for native handlers; & 2 for jQuery (always true)
+ event.isTrigger = onlyHandlers ? 2 : 3;
+ event.namespace = namespaces.join(".");
+ event.namespace_re = event.namespace ?
+ new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) :
+ null;
+
+ // Clean up the event in case it is being reused
+ event.result = undefined;
+ if ( !event.target ) {
+ event.target = elem;
+ }
+
+ // Clone any incoming data and prepend the event, creating the handler arg list
+ data = data == null ?
+ [ event ] :
+ jQuery.makeArray( data, [ event ] );
+
+ // Allow special events to draw outside the lines
+ special = jQuery.event.special[ type ] || {};
+ if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) {
+ return;
+ }
+
+ // Determine event propagation path in advance, per W3C events spec (#9951)
+ // Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
+ if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
+
+ bubbleType = special.delegateType || type;
+ if ( !rfocusMorph.test( bubbleType + type ) ) {
+ cur = cur.parentNode;
+ }
+ for ( ; cur; cur = cur.parentNode ) {
+ eventPath.push( cur );
+ tmp = cur;
+ }
+
+ // Only add window if we got to document (e.g., not plain obj or detached DOM)
+ if ( tmp === (elem.ownerDocument || document) ) {
+ eventPath.push( tmp.defaultView || tmp.parentWindow || window );
+ }
+ }
+
+ // Fire handlers on the event path
+ i = 0;
+ while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) {
+
+ event.type = i > 1 ?
+ bubbleType :
+ special.bindType || type;
+
+ // jQuery handler
+ handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
+ if ( handle ) {
+ handle.apply( cur, data );
+ }
+
+ // Native handler
+ handle = ontype && cur[ ontype ];
+ if ( handle && handle.apply && jQuery.acceptData( cur ) ) {
+ event.result = handle.apply( cur, data );
+ if ( event.result === false ) {
+ event.preventDefault();
+ }
+ }
+ }
+ event.type = type;
+
+ // If nobody prevented the default action, do it now
+ if ( !onlyHandlers && !event.isDefaultPrevented() ) {
+
+ if ( (!special._default || special._default.apply( eventPath.pop(), data ) === false) &&
+ jQuery.acceptData( elem ) ) {
+
+ // Call a native DOM method on the target with the same name name as the event.
+ // Can't use an .isFunction() check here because IE6/7 fails that test.
+ // Don't do default actions on window, that's where global variables be (#6170)
+ if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) {
+
+ // Don't re-trigger an onFOO event when we call its FOO() method
+ tmp = elem[ ontype ];
+
+ if ( tmp ) {
+ elem[ ontype ] = null;
+ }
+
+ // Prevent re-triggering of the same event, since we already bubbled it above
+ jQuery.event.triggered = type;
+ try {
+ elem[ type ]();
+ } catch ( e ) {
+ // IE<9 dies on focus/blur to hidden element (#1486,#12518)
+ // only reproducible on winXP IE8 native, not IE9 in IE8 mode
+ }
+ jQuery.event.triggered = undefined;
+
+ if ( tmp ) {
+ elem[ ontype ] = tmp;
+ }
+ }
+ }
+ }
+
+ return event.result;
+ },
+
+ dispatch: function( event ) {
+
+ // Make a writable jQuery.Event from the native event object
+ event = jQuery.event.fix( event );
+
+ var i, ret, handleObj, matched, j,
+ handlerQueue = [],
+ args = slice.call( arguments ),
+ handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [],
+ special = jQuery.event.special[ event.type ] || {};
+
+ // Use the fix-ed jQuery.Event rather than the (read-only) native event
+ args[0] = event;
+ event.delegateTarget = this;
+
+ // Call the preDispatch hook for the mapped type, and let it bail if desired
+ if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) {
+ return;
+ }
+
+ // Determine handlers
+ handlerQueue = jQuery.event.handlers.call( this, event, handlers );
+
+ // Run delegates first; they may want to stop propagation beneath us
+ i = 0;
+ while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) {
+ event.currentTarget = matched.elem;
+
+ j = 0;
+ while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) {
+
+ // Triggered event must either 1) have no namespace, or
+ // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
+ if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) {
+
+ event.handleObj = handleObj;
+ event.data = handleObj.data;
+
+ ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
+ .apply( matched.elem, args );
+
+ if ( ret !== undefined ) {
+ if ( (event.result = ret) === false ) {
+ event.preventDefault();
+ event.stopPropagation();
+ }
+ }
+ }
+ }
+ }
+
+ // Call the postDispatch hook for the mapped type
+ if ( special.postDispatch ) {
+ special.postDispatch.call( this, event );
+ }
+
+ return event.result;
+ },
+
+ handlers: function( event, handlers ) {
+ var sel, handleObj, matches, i,
+ handlerQueue = [],
+ delegateCount = handlers.delegateCount,
+ cur = event.target;
+
+ // Find delegate handlers
+ // Black-hole SVG <use> instance trees (#13180)
+ // Avoid non-left-click bubbling in Firefox (#3861)
+ if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) {
+
+ /* jshint eqeqeq: false */
+ for ( ; cur != this; cur = cur.parentNode || this ) {
+ /* jshint eqeqeq: true */
+
+ // Don't check non-elements (#13208)
+ // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764)
+ if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) {
+ matches = [];
+ for ( i = 0; i < delegateCount; i++ ) {
+ handleObj = handlers[ i ];
+
+ // Don't conflict with Object.prototype properties (#13203)
+ sel = handleObj.selector + " ";
+
+ if ( matches[ sel ] === undefined ) {
+ matches[ sel ] = handleObj.needsContext ?
+ jQuery( sel, this ).index( cur ) >= 0 :
+ jQuery.find( sel, this, null, [ cur ] ).length;
+ }
+ if ( matches[ sel ] ) {
+ matches.push( handleObj );
+ }
+ }
+ if ( matches.length ) {
+ handlerQueue.push({ elem: cur, handlers: matches });
+ }
+ }
+ }
+ }
+
+ // Add the remaining (directly-bound) handlers
+ if ( delegateCount < handlers.length ) {
+ handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) });
+ }
+
+ return handlerQueue;
+ },
+
+ fix: function( event ) {
+ if ( event[ jQuery.expando ] ) {
+ return event;
+ }
+
+ // Create a writable copy of the event object and normalize some properties
+ var i, prop, copy,
+ type = event.type,
+ originalEvent = event,
+ fixHook = this.fixHooks[ type ];
+
+ if ( !fixHook ) {
+ this.fixHooks[ type ] = fixHook =
+ rmouseEvent.test( type ) ? this.mouseHooks :
+ rkeyEvent.test( type ) ? this.keyHooks :
+ {};
+ }
+ copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props;
+
+ event = new jQuery.Event( originalEvent );
+
+ i = copy.length;
+ while ( i-- ) {
+ prop = copy[ i ];
+ event[ prop ] = originalEvent[ prop ];
+ }
+
+ // Support: IE<9
+ // Fix target property (#1925)
+ if ( !event.target ) {
+ event.target = originalEvent.srcElement || document;
+ }
+
+ // Support: Chrome 23+, Safari?
+ // Target should not be a text node (#504, #13143)
+ if ( event.target.nodeType === 3 ) {
+ event.target = event.target.parentNode;
+ }
+
+ // Support: IE<9
+ // For mouse/key events, metaKey==false if it's undefined (#3368, #11328)
+ event.metaKey = !!event.metaKey;
+
+ return fixHook.filter ? fixHook.filter( event, originalEvent ) : event;
+ },
+
+ // Includes some event props shared by KeyEvent and MouseEvent
+ props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),
+
+ fixHooks: {},
+
+ keyHooks: {
+ props: "char charCode key keyCode".split(" "),
+ filter: function( event, original ) {
+
+ // Add which for key events
+ if ( event.which == null ) {
+ event.which = original.charCode != null ? original.charCode : original.keyCode;
+ }
+
+ return event;
+ }
+ },
+
+ mouseHooks: {
+ props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),
+ filter: function( event, original ) {
+ var body, eventDoc, doc,
+ button = original.button,
+ fromElement = original.fromElement;
+
+ // Calculate pageX/Y if missing and clientX/Y available
+ if ( event.pageX == null && original.clientX != null ) {
+ eventDoc = event.target.ownerDocument || document;
+ doc = eventDoc.documentElement;
+ body = eventDoc.body;
+
+ event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 );
+ event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 );
+ }
+
+ // Add relatedTarget, if necessary
+ if ( !event.relatedTarget && fromElement ) {
+ event.relatedTarget = fromElement === event.target ? original.toElement : fromElement;
+ }
+
+ // Add which for click: 1 === left; 2 === middle; 3 === right
+ // Note: button is not normalized, so don't use it
+ if ( !event.which && button !== undefined ) {
+ event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) );
+ }
+
+ return event;
+ }
+ },
+
+ special: {
+ load: {
+ // Prevent triggered image.load events from bubbling to window.load
+ noBubble: true
+ },
+ focus: {
+ // Fire native event if possible so blur/focus sequence is correct
+ trigger: function() {
+ if ( this !== safeActiveElement() && this.focus ) {
+ try {
+ this.focus();
+ return false;
+ } catch ( e ) {
+ // Support: IE<9
+ // If we error on focus to hidden element (#1486, #12518),
+ // let .trigger() run the handlers
+ }
+ }
+ },
+ delegateType: "focusin"
+ },
+ blur: {
+ trigger: function() {
+ if ( this === safeActiveElement() && this.blur ) {
+ this.blur();
+ return false;
+ }
+ },
+ delegateType: "focusout"
+ },
+ click: {
+ // For checkbox, fire native event so checked state will be right
+ trigger: function() {
+ if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) {
+ this.click();
+ return false;
+ }
+ },
+
+ // For cross-browser consistency, don't fire native .click() on links
+ _default: function( event ) {
+ return jQuery.nodeName( event.target, "a" );
+ }
+ },
+
+ beforeunload: {
+ postDispatch: function( event ) {
+
+ // Support: Firefox 20+
+ // Firefox doesn't alert if the returnValue field is not set.
+ if ( event.result !== undefined && event.originalEvent ) {
+ event.originalEvent.returnValue = event.result;
+ }
+ }
+ }
+ },
+
+ simulate: function( type, elem, event, bubble ) {
+ // Piggyback on a donor event to simulate a different one.
+ // Fake originalEvent to avoid donor's stopPropagation, but if the
+ // simulated event prevents default then we do the same on the donor.
+ var e = jQuery.extend(
+ new jQuery.Event(),
+ event,
+ {
+ type: type,
+ isSimulated: true,
+ originalEvent: {}
+ }
+ );
+ if ( bubble ) {
+ jQuery.event.trigger( e, null, elem );
+ } else {
+ jQuery.event.dispatch.call( elem, e );
+ }
+ if ( e.isDefaultPrevented() ) {
+ event.preventDefault();
+ }
+ }
+};
+
+jQuery.removeEvent = document.removeEventListener ?
+ function( elem, type, handle ) {
+ if ( elem.removeEventListener ) {
+ elem.removeEventListener( type, handle, false );
+ }
+ } :
+ function( elem, type, handle ) {
+ var name = "on" + type;
+
+ if ( elem.detachEvent ) {
+
+ // #8545, #7054, preventing memory leaks for custom events in IE6-8
+ // detachEvent needed property on element, by name of that event, to properly expose it to GC
+ if ( typeof elem[ name ] === strundefined ) {
+ elem[ name ] = null;
+ }
+
+ elem.detachEvent( name, handle );
+ }
+ };
+
+jQuery.Event = function( src, props ) {
+ // Allow instantiation without the 'new' keyword
+ if ( !(this instanceof jQuery.Event) ) {
+ return new jQuery.Event( src, props );
+ }
+
+ // Event object
+ if ( src && src.type ) {
+ this.originalEvent = src;
+ this.type = src.type;
+
+ // Events bubbling up the document may have been marked as prevented
+ // by a handler lower down the tree; reflect the correct value.
+ this.isDefaultPrevented = src.defaultPrevented ||
+ src.defaultPrevented === undefined &&
+ // Support: IE < 9, Android < 4.0
+ src.returnValue === false ?
+ returnTrue :
+ returnFalse;
+
+ // Event type
+ } else {
+ this.type = src;
+ }
+
+ // Put explicitly provided properties onto the event object
+ if ( props ) {
+ jQuery.extend( this, props );
+ }
+
+ // Create a timestamp if incoming event doesn't have one
+ this.timeStamp = src && src.timeStamp || jQuery.now();
+
+ // Mark it as fixed
+ this[ jQuery.expando ] = true;
+};
+
+// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
+// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
+jQuery.Event.prototype = {
+ isDefaultPrevented: returnFalse,
+ isPropagationStopped: returnFalse,
+ isImmediatePropagationStopped: returnFalse,
+
+ preventDefault: function() {
+ var e = this.originalEvent;
+
+ this.isDefaultPrevented = returnTrue;
+ if ( !e ) {
+ return;
+ }
+
+ // If preventDefault exists, run it on the original event
+ if ( e.preventDefault ) {
+ e.preventDefault();
+
+ // Support: IE
+ // Otherwise set the returnValue property of the original event to false
+ } else {
+ e.returnValue = false;
+ }
+ },
+ stopPropagation: function() {
+ var e = this.originalEvent;
+
+ this.isPropagationStopped = returnTrue;
+ if ( !e ) {
+ return;
+ }
+ // If stopPropagation exists, run it on the original event
+ if ( e.stopPropagation ) {
+ e.stopPropagation();
+ }
+
+ // Support: IE
+ // Set the cancelBubble property of the original event to true
+ e.cancelBubble = true;
+ },
+ stopImmediatePropagation: function() {
+ var e = this.originalEvent;
+
+ this.isImmediatePropagationStopped = returnTrue;
+
+ if ( e && e.stopImmediatePropagation ) {
+ e.stopImmediatePropagation();
+ }
+
+ this.stopPropagation();
+ }
+};
+
+// Create mouseenter/leave events using mouseover/out and event-time checks
+jQuery.each({
+ mouseenter: "mouseover",
+ mouseleave: "mouseout",
+ pointerenter: "pointerover",
+ pointerleave: "pointerout"
+}, function( orig, fix ) {
+ jQuery.event.special[ orig ] = {
+ delegateType: fix,
+ bindType: fix,
+
+ handle: function( event ) {
+ var ret,
+ target = this,
+ related = event.relatedTarget,
+ handleObj = event.handleObj;
+
+ // For mousenter/leave call the handler if related is outside the target.
+ // NB: No relatedTarget if the mouse left/entered the browser window
+ if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
+ event.type = handleObj.origType;
+ ret = handleObj.handler.apply( this, arguments );
+ event.type = fix;
+ }
+ return ret;
+ }
+ };
+});
+
+// IE submit delegation
+if ( !support.submitBubbles ) {
+
+ jQuery.event.special.submit = {
+ setup: function() {
+ // Only need this for delegated form submit events
+ if ( jQuery.nodeName( this, "form" ) ) {
+ return false;
+ }
+
+ // Lazy-add a submit handler when a descendant form may potentially be submitted
+ jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
+ // Node name check avoids a VML-related crash in IE (#9807)
+ var elem = e.target,
+ form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
+ if ( form && !jQuery._data( form, "submitBubbles" ) ) {
+ jQuery.event.add( form, "submit._submit", function( event ) {
+ event._submit_bubble = true;
+ });
+ jQuery._data( form, "submitBubbles", true );
+ }
+ });
+ // return undefined since we don't need an event listener
+ },
+
+ postDispatch: function( event ) {
+ // If form was submitted by the user, bubble the event up the tree
+ if ( event._submit_bubble ) {
+ delete event._submit_bubble;
+ if ( this.parentNode && !event.isTrigger ) {
+ jQuery.event.simulate( "submit", this.parentNode, event, true );
+ }
+ }
+ },
+
+ teardown: function() {
+ // Only need this for delegated form submit events
+ if ( jQuery.nodeName( this, "form" ) ) {
+ return false;
+ }
+
+ // Remove delegated handlers; cleanData eventually reaps submit handlers attached above
+ jQuery.event.remove( this, "._submit" );
+ }
+ };
+}
+
+// IE change delegation and checkbox/radio fix
+if ( !support.changeBubbles ) {
+
+ jQuery.event.special.change = {
+
+ setup: function() {
+
+ if ( rformElems.test( this.nodeName ) ) {
+ // IE doesn't fire change on a check/radio until blur; trigger it on click
+ // after a propertychange. Eat the blur-change in special.change.handle.
+ // This still fires onchange a second time for check/radio after blur.
+ if ( this.type === "checkbox" || this.type === "radio" ) {
+ jQuery.event.add( this, "propertychange._change", function( event ) {
+ if ( event.originalEvent.propertyName === "checked" ) {
+ this._just_changed = true;
+ }
+ });
+ jQuery.event.add( this, "click._change", function( event ) {
+ if ( this._just_changed && !event.isTrigger ) {
+ this._just_changed = false;
+ }
+ // Allow triggered, simulated change events (#11500)
+ jQuery.event.simulate( "change", this, event, true );
+ });
+ }
+ return false;
+ }
+ // Delegated event; lazy-add a change handler on descendant inputs
+ jQuery.event.add( this, "beforeactivate._change", function( e ) {
+ var elem = e.target;
+
+ if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) {
+ jQuery.event.add( elem, "change._change", function( event ) {
+ if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
+ jQuery.event.simulate( "change", this.parentNode, event, true );
+ }
+ });
+ jQuery._data( elem, "changeBubbles", true );
+ }
+ });
+ },
+
+ handle: function( event ) {
+ var elem = event.target;
+
+ // Swallow native change events from checkbox/radio, we already triggered them above
+ if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
+ return event.handleObj.handler.apply( this, arguments );
+ }
+ },
+
+ teardown: function() {
+ jQuery.event.remove( this, "._change" );
+
+ return !rformElems.test( this.nodeName );
+ }
+ };
+}
+
+// Create "bubbling" focus and blur events
+if ( !support.focusinBubbles ) {
+ jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
+
+ // Attach a single capturing handler on the document while someone wants focusin/focusout
+ var handler = function( event ) {
+ jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
+ };
+
+ jQuery.event.special[ fix ] = {
+ setup: function() {
+ var doc = this.ownerDocument || this,
+ attaches = jQuery._data( doc, fix );
+
+ if ( !attaches ) {
+ doc.addEventListener( orig, handler, true );
+ }
+ jQuery._data( doc, fix, ( attaches || 0 ) + 1 );
+ },
+ teardown: function() {
+ var doc = this.ownerDocument || this,
+ attaches = jQuery._data( doc, fix ) - 1;
+
+ if ( !attaches ) {
+ doc.removeEventListener( orig, handler, true );
+ jQuery._removeData( doc, fix );
+ } else {
+ jQuery._data( doc, fix, attaches );
+ }
+ }
+ };
+ });
+}
+
+jQuery.fn.extend({
+
+ on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
+ var type, origFn;
+
+ // Types can be a map of types/handlers
+ if ( typeof types === "object" ) {
+ // ( types-Object, selector, data )
+ if ( typeof selector !== "string" ) {
+ // ( types-Object, data )
+ data = data || selector;
+ selector = undefined;
+ }
+ for ( type in types ) {
+ this.on( type, selector, data, types[ type ], one );
+ }
+ return this;
+ }
+
+ if ( data == null && fn == null ) {
+ // ( types, fn )
+ fn = selector;
+ data = selector = undefined;
+ } else if ( fn == null ) {
+ if ( typeof selector === "string" ) {
+ // ( types, selector, fn )
+ fn = data;
+ data = undefined;
+ } else {
+ // ( types, data, fn )
+ fn = data;
+ data = selector;
+ selector = undefined;
+ }
+ }
+ if ( fn === false ) {
+ fn = returnFalse;
+ } else if ( !fn ) {
+ return this;
+ }
+
+ if ( one === 1 ) {
+ origFn = fn;
+ fn = function( event ) {
+ // Can use an empty set, since event contains the info
+ jQuery().off( event );
+ return origFn.apply( this, arguments );
+ };
+ // Use same guid so caller can remove using origFn
+ fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ );
+ }
+ return this.each( function() {
+ jQuery.event.add( this, types, fn, data, selector );
+ });
+ },
+ one: function( types, selector, data, fn ) {
+ return this.on( types, selector, data, fn, 1 );
+ },
+ off: function( types, selector, fn ) {
+ var handleObj, type;
+ if ( types && types.preventDefault && types.handleObj ) {
+ // ( event ) dispatched jQuery.Event
+ handleObj = types.handleObj;
+ jQuery( types.delegateTarget ).off(
+ handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType,
+ handleObj.selector,
+ handleObj.handler
+ );
+ return this;
+ }
+ if ( typeof types === "object" ) {
+ // ( types-object [, selector] )
+ for ( type in types ) {
+ this.off( type, selector, types[ type ] );
+ }
+ return this;
+ }
+ if ( selector === false || typeof selector === "function" ) {
+ // ( types [, fn] )
+ fn = selector;
+ selector = undefined;
+ }
+ if ( fn === false ) {
+ fn = returnFalse;
+ }
+ return this.each(function() {
+ jQuery.event.remove( this, types, fn, selector );
+ });
+ },
+
+ trigger: function( type, data ) {
+ return this.each(function() {
+ jQuery.event.trigger( type, data, this );
+ });
+ },
+ triggerHandler: function( type, data ) {
+ var elem = this[0];
+ if ( elem ) {
+ return jQuery.event.trigger( type, data, elem, true );
+ }
+ }
+});
+
+
+function createSafeFragment( document ) {
+ var list = nodeNames.split( "|" ),
+ safeFrag = document.createDocumentFragment();
+
+ if ( safeFrag.createElement ) {
+ while ( list.length ) {
+ safeFrag.createElement(
+ list.pop()
+ );
+ }
+ }
+ return safeFrag;
+}
+
+var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
+ "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
+ rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g,
+ rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
+ rleadingWhitespace = /^\s+/,
+ rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,
+ rtagName = /<([\w:]+)/,
+ rtbody = /<tbody/i,
+ rhtml = /<|&#?\w+;/,
+ rnoInnerhtml = /<(?:script|style|link)/i,
+ // checked="checked" or checked
+ rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
+ rscriptType = /^$|\/(?:java|ecma)script/i,
+ rscriptTypeMasked = /^true\/(.*)/,
+ rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,
+
+ // We have to close these tags to support XHTML (#13200)
+ wrapMap = {
+ option: [ 1, "<select multiple='multiple'>", "</select>" ],
+ legend: [ 1, "<fieldset>", "</fieldset>" ],
+ area: [ 1, "<map>", "</map>" ],
+ param: [ 1, "<object>", "</object>" ],
+ thead: [ 1, "<table>", "</table>" ],
+ tr: [ 2, "<table><tbody>", "</tbody></table>" ],
+ col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
+ td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
+
+ // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags,
+ // unless wrapped in a div with non-breaking characters in front of it.
+ _default: support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ]
+ },
+ safeFragment = createSafeFragment( document ),
+ fragmentDiv = safeFragment.appendChild( document.createElement("div") );
+
+wrapMap.optgroup = wrapMap.option;
+wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
+wrapMap.th = wrapMap.td;
+
+function getAll( context, tag ) {
+ var elems, elem,
+ i = 0,
+ found = typeof context.getElementsByTagName !== strundefined ? context.getElementsByTagName( tag || "*" ) :
+ typeof context.querySelectorAll !== strundefined ? context.querySelectorAll( tag || "*" ) :
+ undefined;
+
+ if ( !found ) {
+ for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) {
+ if ( !tag || jQuery.nodeName( elem, tag ) ) {
+ found.push( elem );
+ } else {
+ jQuery.merge( found, getAll( elem, tag ) );
+ }
+ }
+ }
+
+ return tag === undefined || tag && jQuery.nodeName( context, tag ) ?
+ jQuery.merge( [ context ], found ) :
+ found;
+}
+
+// Used in buildFragment, fixes the defaultChecked property
+function fixDefaultChecked( elem ) {
+ if ( rcheckableType.test( elem.type ) ) {
+ elem.defaultChecked = elem.checked;
+ }
+}
+
+// Support: IE<8
+// Manipulating tables requires a tbody
+function manipulationTarget( elem, content ) {
+ return jQuery.nodeName( elem, "table" ) &&
+ jQuery.nodeName( content.nodeType !== 11 ? content : content.firstChild, "tr" ) ?
+
+ elem.getElementsByTagName("tbody")[0] ||
+ elem.appendChild( elem.ownerDocument.createElement("tbody") ) :
+ elem;
+}
+
+// Replace/restore the type attribute of script elements for safe DOM manipulation
+function disableScript( elem ) {
+ elem.type = (jQuery.find.attr( elem, "type" ) !== null) + "/" + elem.type;
+ return elem;
+}
+function restoreScript( elem ) {
+ var match = rscriptTypeMasked.exec( elem.type );
+ if ( match ) {
+ elem.type = match[1];
+ } else {
+ elem.removeAttribute("type");
+ }
+ return elem;
+}
+
+// Mark scripts as having already been evaluated
+function setGlobalEval( elems, refElements ) {
+ var elem,
+ i = 0;
+ for ( ; (elem = elems[i]) != null; i++ ) {
+ jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) );
+ }
+}
+
+function cloneCopyEvent( src, dest ) {
+
+ if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
+ return;
+ }
+
+ var type, i, l,
+ oldData = jQuery._data( src ),
+ curData = jQuery._data( dest, oldData ),
+ events = oldData.events;
+
+ if ( events ) {
+ delete curData.handle;
+ curData.events = {};
+
+ for ( type in events ) {
+ for ( i = 0, l = events[ type ].length; i < l; i++ ) {
+ jQuery.event.add( dest, type, events[ type ][ i ] );
+ }
+ }
+ }
+
+ // make the cloned public data object a copy from the original
+ if ( curData.data ) {
+ curData.data = jQuery.extend( {}, curData.data );
+ }
+}
+
+function fixCloneNodeIssues( src, dest ) {
+ var nodeName, e, data;
+
+ // We do not need to do anything for non-Elements
+ if ( dest.nodeType !== 1 ) {
+ return;
+ }
+
+ nodeName = dest.nodeName.toLowerCase();
+
+ // IE6-8 copies events bound via attachEvent when using cloneNode.
+ if ( !support.noCloneEvent && dest[ jQuery.expando ] ) {
+ data = jQuery._data( dest );
+
+ for ( e in data.events ) {
+ jQuery.removeEvent( dest, e, data.handle );
+ }
+
+ // Event data gets referenced instead of copied if the expando gets copied too
+ dest.removeAttribute( jQuery.expando );
+ }
+
+ // IE blanks contents when cloning scripts, and tries to evaluate newly-set text
+ if ( nodeName === "script" && dest.text !== src.text ) {
+ disableScript( dest ).text = src.text;
+ restoreScript( dest );
+
+ // IE6-10 improperly clones children of object elements using classid.
+ // IE10 throws NoModificationAllowedError if parent is null, #12132.
+ } else if ( nodeName === "object" ) {
+ if ( dest.parentNode ) {
+ dest.outerHTML = src.outerHTML;
+ }
+
+ // This path appears unavoidable for IE9. When cloning an object
+ // element in IE9, the outerHTML strategy above is not sufficient.
+ // If the src has innerHTML and the destination does not,
+ // copy the src.innerHTML into the dest.innerHTML. #10324
+ if ( support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) {
+ dest.innerHTML = src.innerHTML;
+ }
+
+ } else if ( nodeName === "input" && rcheckableType.test( src.type ) ) {
+ // IE6-8 fails to persist the checked state of a cloned checkbox
+ // or radio button. Worse, IE6-7 fail to give the cloned element
+ // a checked appearance if the defaultChecked value isn't also set
+
+ dest.defaultChecked = dest.checked = src.checked;
+
+ // IE6-7 get confused and end up setting the value of a cloned
+ // checkbox/radio button to an empty string instead of "on"
+ if ( dest.value !== src.value ) {
+ dest.value = src.value;
+ }
+
+ // IE6-8 fails to return the selected option to the default selected
+ // state when cloning options
+ } else if ( nodeName === "option" ) {
+ dest.defaultSelected = dest.selected = src.defaultSelected;
+
+ // IE6-8 fails to set the defaultValue to the correct value when
+ // cloning other types of input fields
+ } else if ( nodeName === "input" || nodeName === "textarea" ) {
+ dest.defaultValue = src.defaultValue;
+ }
+}
+
+jQuery.extend({
+ clone: function( elem, dataAndEvents, deepDataAndEvents ) {
+ var destElements, node, clone, i, srcElements,
+ inPage = jQuery.contains( elem.ownerDocument, elem );
+
+ if ( support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) {
+ clone = elem.cloneNode( true );
+
+ // IE<=8 does not properly clone detached, unknown element nodes
+ } else {
+ fragmentDiv.innerHTML = elem.outerHTML;
+ fragmentDiv.removeChild( clone = fragmentDiv.firstChild );
+ }
+
+ if ( (!support.noCloneEvent || !support.noCloneChecked) &&
+ (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
+
+ // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2
+ destElements = getAll( clone );
+ srcElements = getAll( elem );
+
+ // Fix all IE cloning issues
+ for ( i = 0; (node = srcElements[i]) != null; ++i ) {
+ // Ensure that the destination node is not null; Fixes #9587
+ if ( destElements[i] ) {
+ fixCloneNodeIssues( node, destElements[i] );
+ }
+ }
+ }
+
+ // Copy the events from the original to the clone
+ if ( dataAndEvents ) {
+ if ( deepDataAndEvents ) {
+ srcElements = srcElements || getAll( elem );
+ destElements = destElements || getAll( clone );
+
+ for ( i = 0; (node = srcElements[i]) != null; i++ ) {
+ cloneCopyEvent( node, destElements[i] );
+ }
+ } else {
+ cloneCopyEvent( elem, clone );
+ }
+ }
+
+ // Preserve script evaluation history
+ destElements = getAll( clone, "script" );
+ if ( destElements.length > 0 ) {
+ setGlobalEval( destElements, !inPage && getAll( elem, "script" ) );
+ }
+
+ destElements = srcElements = node = null;
+
+ // Return the cloned set
+ return clone;
+ },
+
+ buildFragment: function( elems, context, scripts, selection ) {
+ var j, elem, contains,
+ tmp, tag, tbody, wrap,
+ l = elems.length,
+
+ // Ensure a safe fragment
+ safe = createSafeFragment( context ),
+
+ nodes = [],
+ i = 0;
+
+ for ( ; i < l; i++ ) {
+ elem = elems[ i ];
+
+ if ( elem || elem === 0 ) {
+
+ // Add nodes directly
+ if ( jQuery.type( elem ) === "object" ) {
+ jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem );
+
+ // Convert non-html into a text node
+ } else if ( !rhtml.test( elem ) ) {
+ nodes.push( context.createTextNode( elem ) );
+
+ // Convert html into DOM nodes
+ } else {
+ tmp = tmp || safe.appendChild( context.createElement("div") );
+
+ // Deserialize a standard representation
+ tag = (rtagName.exec( elem ) || [ "", "" ])[ 1 ].toLowerCase();
+ wrap = wrapMap[ tag ] || wrapMap._default;
+
+ tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2];
+
+ // Descend through wrappers to the right content
+ j = wrap[0];
+ while ( j-- ) {
+ tmp = tmp.lastChild;
+ }
+
+ // Manually add leading whitespace removed by IE
+ if ( !support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
+ nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) );
+ }
+
+ // Remove IE's autoinserted <tbody> from table fragments
+ if ( !support.tbody ) {
+
+ // String was a <table>, *may* have spurious <tbody>
+ elem = tag === "table" && !rtbody.test( elem ) ?
+ tmp.firstChild :
+
+ // String was a bare <thead> or <tfoot>
+ wrap[1] === "<table>" && !rtbody.test( elem ) ?
+ tmp :
+ 0;
+
+ j = elem && elem.childNodes.length;
+ while ( j-- ) {
+ if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) {
+ elem.removeChild( tbody );
+ }
+ }
+ }
+
+ jQuery.merge( nodes, tmp.childNodes );
+
+ // Fix #12392 for WebKit and IE > 9
+ tmp.textContent = "";
+
+ // Fix #12392 for oldIE
+ while ( tmp.firstChild ) {
+ tmp.removeChild( tmp.firstChild );
+ }
+
+ // Remember the top-level container for proper cleanup
+ tmp = safe.lastChild;
+ }
+ }
+ }
+
+ // Fix #11356: Clear elements from fragment
+ if ( tmp ) {
+ safe.removeChild( tmp );
+ }
+
+ // Reset defaultChecked for any radios and checkboxes
+ // about to be appended to the DOM in IE 6/7 (#8060)
+ if ( !support.appendChecked ) {
+ jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked );
+ }
+
+ i = 0;
+ while ( (elem = nodes[ i++ ]) ) {
+
+ // #4087 - If origin and destination elements are the same, and this is
+ // that element, do not do anything
+ if ( selection && jQuery.inArray( elem, selection ) !== -1 ) {
+ continue;
+ }
+
+ contains = jQuery.contains( elem.ownerDocument, elem );
+
+ // Append to fragment
+ tmp = getAll( safe.appendChild( elem ), "script" );
+
+ // Preserve script evaluation history
+ if ( contains ) {
+ setGlobalEval( tmp );
+ }
+
+ // Capture executables
+ if ( scripts ) {
+ j = 0;
+ while ( (elem = tmp[ j++ ]) ) {
+ if ( rscriptType.test( elem.type || "" ) ) {
+ scripts.push( elem );
+ }
+ }
+ }
+ }
+
+ tmp = null;
+
+ return safe;
+ },
+
+ cleanData: function( elems, /* internal */ acceptData ) {
+ var elem, type, id, data,
+ i = 0,
+ internalKey = jQuery.expando,
+ cache = jQuery.cache,
+ deleteExpando = support.deleteExpando,
+ special = jQuery.event.special;
+
+ for ( ; (elem = elems[i]) != null; i++ ) {
+ if ( acceptData || jQuery.acceptData( elem ) ) {
+
+ id = elem[ internalKey ];
+ data = id && cache[ id ];
+
+ if ( data ) {
+ if ( data.events ) {
+ for ( type in data.events ) {
+ if ( special[ type ] ) {
+ jQuery.event.remove( elem, type );
+
+ // This is a shortcut to avoid jQuery.event.remove's overhead
+ } else {
+ jQuery.removeEvent( elem, type, data.handle );
+ }
+ }
+ }
+
+ // Remove cache only if it was not already removed by jQuery.event.remove
+ if ( cache[ id ] ) {
+
+ delete cache[ id ];
+
+ // IE does not allow us to delete expando properties from nodes,
+ // nor does it have a removeAttribute function on Document nodes;
+ // we must handle all of these cases
+ if ( deleteExpando ) {
+ delete elem[ internalKey ];
+
+ } else if ( typeof elem.removeAttribute !== strundefined ) {
+ elem.removeAttribute( internalKey );
+
+ } else {
+ elem[ internalKey ] = null;
+ }
+
+ deletedIds.push( id );
+ }
+ }
+ }
+ }
+ }
+});
+
+jQuery.fn.extend({
+ text: function( value ) {
+ return access( this, function( value ) {
+ return value === undefined ?
+ jQuery.text( this ) :
+ this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) );
+ }, null, value, arguments.length );
+ },
+
+ append: function() {
+ return this.domManip( arguments, function( elem ) {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ var target = manipulationTarget( this, elem );
+ target.appendChild( elem );
+ }
+ });
+ },
+
+ prepend: function() {
+ return this.domManip( arguments, function( elem ) {
+ if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) {
+ var target = manipulationTarget( this, elem );
+ target.insertBefore( elem, target.firstChild );
+ }
+ });
+ },
+
+ before: function() {
+ return this.domManip( arguments, function( elem ) {
+ if ( this.parentNode ) {
+ this.parentNode.insertBefore( elem, this );
+ }
+ });
+ },
+
+ after: function() {
+ return this.domManip( arguments, function( elem ) {
+ if ( this.parentNode ) {
+ this.parentNode.insertBefore( elem, this.nextSibling );
+ }
+ });
+ },
+
+ remove: function( selector, keepData /* Internal Use Only */ ) {
+ var elem,
+ elems = selector ? jQuery.filter( selector, this ) : this,
+ i = 0;
+
+ for ( ; (elem = elems[i]) != null; i++ ) {
+
+ if ( !keepData && elem.nodeType === 1 ) {
+ jQuery.cleanData( getAll( elem ) );
+ }
+
+ if ( elem.parentNode ) {
+ if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) {
+ setGlobalEval( getAll( elem, "script" ) );
+ }
+ elem.parentNode.removeChild( elem );
+ }
+ }
+
+ return this;
+ },
+
+ empty: function() {
+ var elem,
+ i = 0;
+
+ for ( ; (elem = this[i]) != null; i++ ) {
+ // Remove element nodes and prevent memory leaks
+ if ( elem.nodeType === 1 ) {
+ jQuery.cleanData( getAll( elem, false ) );
+ }
+
+ // Remove any remaining nodes
+ while ( elem.firstChild ) {
+ elem.removeChild( elem.firstChild );
+ }
+
+ // If this is a select, ensure that it displays empty (#12336)
+ // Support: IE<9
+ if ( elem.options && jQuery.nodeName( elem, "select" ) ) {
+ elem.options.length = 0;
+ }
+ }
+
+ return this;
+ },
+
+ clone: function( dataAndEvents, deepDataAndEvents ) {
+ dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
+ deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
+
+ return this.map(function() {
+ return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
+ });
+ },
+
+ html: function( value ) {
+ return access( this, function( value ) {
+ var elem = this[ 0 ] || {},
+ i = 0,
+ l = this.length;
+
+ if ( value === undefined ) {
+ return elem.nodeType === 1 ?
+ elem.innerHTML.replace( rinlinejQuery, "" ) :
+ undefined;
+ }
+
+ // See if we can take a shortcut and just use innerHTML
+ if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
+ ( support.htmlSerialize || !rnoshimcache.test( value ) ) &&
+ ( support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
+ !wrapMap[ (rtagName.exec( value ) || [ "", "" ])[ 1 ].toLowerCase() ] ) {
+
+ value = value.replace( rxhtmlTag, "<$1></$2>" );
+
+ try {
+ for (; i < l; i++ ) {
+ // Remove element nodes and prevent memory leaks
+ elem = this[i] || {};
+ if ( elem.nodeType === 1 ) {
+ jQuery.cleanData( getAll( elem, false ) );
+ elem.innerHTML = value;
+ }
+ }
+
+ elem = 0;
+
+ // If using innerHTML throws an exception, use the fallback method
+ } catch(e) {}
+ }
+
+ if ( elem ) {
+ this.empty().append( value );
+ }
+ }, null, value, arguments.length );
+ },
+
+ replaceWith: function() {
+ var arg = arguments[ 0 ];
+
+ // Make the changes, replacing each context element with the new content
+ this.domManip( arguments, function( elem ) {
+ arg = this.parentNode;
+
+ jQuery.cleanData( getAll( this ) );
+
+ if ( arg ) {
+ arg.replaceChild( elem, this );
+ }
+ });
+
+ // Force removal if there was no new content (e.g., from empty arguments)
+ return arg && (arg.length || arg.nodeType) ? this : this.remove();
+ },
+
+ detach: function( selector ) {
+ return this.remove( selector, true );
+ },
+
+ domManip: function( args, callback ) {
+
+ // Flatten any nested arrays
+ args = concat.apply( [], args );
+
+ var first, node, hasScripts,
+ scripts, doc, fragment,
+ i = 0,
+ l = this.length,
+ set = this,
+ iNoClone = l - 1,
+ value = args[0],
+ isFunction = jQuery.isFunction( value );
+
+ // We can't cloneNode fragments that contain checked, in WebKit
+ if ( isFunction ||
+ ( l > 1 && typeof value === "string" &&
+ !support.checkClone && rchecked.test( value ) ) ) {
+ return this.each(function( index ) {
+ var self = set.eq( index );
+ if ( isFunction ) {
+ args[0] = value.call( this, index, self.html() );
+ }
+ self.domManip( args, callback );
+ });
+ }
+
+ if ( l ) {
+ fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this );
+ first = fragment.firstChild;
+
+ if ( fragment.childNodes.length === 1 ) {
+ fragment = first;
+ }
+
+ if ( first ) {
+ scripts = jQuery.map( getAll( fragment, "script" ), disableScript );
+ hasScripts = scripts.length;
+
+ // Use the original fragment for the last item instead of the first because it can end up
+ // being emptied incorrectly in certain situations (#8070).
+ for ( ; i < l; i++ ) {
+ node = fragment;
+
+ if ( i !== iNoClone ) {
+ node = jQuery.clone( node, true, true );
+
+ // Keep references to cloned scripts for later restoration
+ if ( hasScripts ) {
+ jQuery.merge( scripts, getAll( node, "script" ) );
+ }
+ }
+
+ callback.call( this[i], node, i );
+ }
+
+ if ( hasScripts ) {
+ doc = scripts[ scripts.length - 1 ].ownerDocument;
+
+ // Reenable scripts
+ jQuery.map( scripts, restoreScript );
+
+ // Evaluate executable scripts on first document insertion
+ for ( i = 0; i < hasScripts; i++ ) {
+ node = scripts[ i ];
+ if ( rscriptType.test( node.type || "" ) &&
+ !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) {
+
+ if ( node.src ) {
+ // Optional AJAX dependency, but won't run scripts if not present
+ if ( jQuery._evalUrl ) {
+ jQuery._evalUrl( node.src );
+ }
+ } else {
+ jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) );
+ }
+ }
+ }
+ }
+
+ // Fix #11809: Avoid leaking memory
+ fragment = first = null;
+ }
+ }
+
+ return this;
+ }
+});
+
+jQuery.each({
+ appendTo: "append",
+ prependTo: "prepend",
+ insertBefore: "before",
+ insertAfter: "after",
+ replaceAll: "replaceWith"
+}, function( name, original ) {
+ jQuery.fn[ name ] = function( selector ) {
+ var elems,
+ i = 0,
+ ret = [],
+ insert = jQuery( selector ),
+ last = insert.length - 1;
+
+ for ( ; i <= last; i++ ) {
+ elems = i === last ? this : this.clone(true);
+ jQuery( insert[i] )[ original ]( elems );
+
+ // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get()
+ push.apply( ret, elems.get() );
+ }
+
+ return this.pushStack( ret );
+ };
+});
+
+
+var iframe,
+ elemdisplay = {};
+
+/**
+ * Retrieve the actual display of a element
+ * @param {String} name nodeName of the element
+ * @param {Object} doc Document object
+ */
+// Called only from within defaultDisplay
+function actualDisplay( name, doc ) {
+ var style,
+ elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ),
+
+ // getDefaultComputedStyle might be reliably used only on attached element
+ display = window.getDefaultComputedStyle && ( style = window.getDefaultComputedStyle( elem[ 0 ] ) ) ?
+
+ // Use of this method is a temporary fix (more like optmization) until something better comes along,
+ // since it was removed from specification and supported only in FF
+ style.display : jQuery.css( elem[ 0 ], "display" );
+
+ // We don't have any data stored on the element,
+ // so use "detach" method as fast way to get rid of the element
+ elem.detach();
+
+ return display;
+}
+
+/**
+ * Try to determine the default display value of an element
+ * @param {String} nodeName
+ */
+function defaultDisplay( nodeName ) {
+ var doc = document,
+ display = elemdisplay[ nodeName ];
+
+ if ( !display ) {
+ display = actualDisplay( nodeName, doc );
+
+ // If the simple way fails, read from inside an iframe
+ if ( display === "none" || !display ) {
+
+ // Use the already-created iframe if possible
+ iframe = (iframe || jQuery( "<iframe frameborder='0' width='0' height='0'/>" )).appendTo( doc.documentElement );
+
+ // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse
+ doc = ( iframe[ 0 ].contentWindow || iframe[ 0 ].contentDocument ).document;
+
+ // Support: IE
+ doc.write();
+ doc.close();
+
+ display = actualDisplay( nodeName, doc );
+ iframe.detach();
+ }
+
+ // Store the correct default display
+ elemdisplay[ nodeName ] = display;
+ }
+
+ return display;
+}
+
+
+(function() {
+ var shrinkWrapBlocksVal;
+
+ support.shrinkWrapBlocks = function() {
+ if ( shrinkWrapBlocksVal != null ) {
+ return shrinkWrapBlocksVal;
+ }
+
+ // Will be changed later if needed.
+ shrinkWrapBlocksVal = false;
+
+ // Minified: var b,c,d
+ var div, body, container;
+
+ body = document.getElementsByTagName( "body" )[ 0 ];
+ if ( !body || !body.style ) {
+ // Test fired too early or in an unsupported environment, exit.
+ return;
+ }
+
+ // Setup
+ div = document.createElement( "div" );
+ container = document.createElement( "div" );
+ container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
+ body.appendChild( container ).appendChild( div );
+
+ // Support: IE6
+ // Check if elements with layout shrink-wrap their children
+ if ( typeof div.style.zoom !== strundefined ) {
+ // Reset CSS: box-sizing; display; margin; border
+ div.style.cssText =
+ // Support: Firefox<29, Android 2.3
+ // Vendor-prefix box-sizing
+ "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
+ "box-sizing:content-box;display:block;margin:0;border:0;" +
+ "padding:1px;width:1px;zoom:1";
+ div.appendChild( document.createElement( "div" ) ).style.width = "5px";
+ shrinkWrapBlocksVal = div.offsetWidth !== 3;
+ }
+
+ body.removeChild( container );
+
+ return shrinkWrapBlocksVal;
+ };
+
+})();
+var rmargin = (/^margin/);
+
+var rnumnonpx = new RegExp( "^(" + pnum + ")(?!px)[a-z%]+$", "i" );
+
+
+
+var getStyles, curCSS,
+ rposition = /^(top|right|bottom|left)$/;
+
+if ( window.getComputedStyle ) {
+ getStyles = function( elem ) {
+ return elem.ownerDocument.defaultView.getComputedStyle( elem, null );
+ };
+
+ curCSS = function( elem, name, computed ) {
+ var width, minWidth, maxWidth, ret,
+ style = elem.style;
+
+ computed = computed || getStyles( elem );
+
+ // getPropertyValue is only needed for .css('filter') in IE9, see #12537
+ ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined;
+
+ if ( computed ) {
+
+ if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) {
+ ret = jQuery.style( elem, name );
+ }
+
+ // A tribute to the "awesome hack by Dean Edwards"
+ // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right
+ // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels
+ // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
+ if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) {
+
+ // Remember the original values
+ width = style.width;
+ minWidth = style.minWidth;
+ maxWidth = style.maxWidth;
+
+ // Put in the new values to get a computed value out
+ style.minWidth = style.maxWidth = style.width = ret;
+ ret = computed.width;
+
+ // Revert the changed values
+ style.width = width;
+ style.minWidth = minWidth;
+ style.maxWidth = maxWidth;
+ }
+ }
+
+ // Support: IE
+ // IE returns zIndex value as an integer.
+ return ret === undefined ?
+ ret :
+ ret + "";
+ };
+} else if ( document.documentElement.currentStyle ) {
+ getStyles = function( elem ) {
+ return elem.currentStyle;
+ };
+
+ curCSS = function( elem, name, computed ) {
+ var left, rs, rsLeft, ret,
+ style = elem.style;
+
+ computed = computed || getStyles( elem );
+ ret = computed ? computed[ name ] : undefined;
+
+ // Avoid setting ret to empty string here
+ // so we don't default to auto
+ if ( ret == null && style && style[ name ] ) {
+ ret = style[ name ];
+ }
+
+ // From the awesome hack by Dean Edwards
+ // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
+
+ // If we're not dealing with a regular pixel number
+ // but a number that has a weird ending, we need to convert it to pixels
+ // but not position css attributes, as those are proportional to the parent element instead
+ // and we can't measure the parent instead because it might trigger a "stacking dolls" problem
+ if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {
+
+ // Remember the original values
+ left = style.left;
+ rs = elem.runtimeStyle;
+ rsLeft = rs && rs.left;
+
+ // Put in the new values to get a computed value out
+ if ( rsLeft ) {
+ rs.left = elem.currentStyle.left;
+ }
+ style.left = name === "fontSize" ? "1em" : ret;
+ ret = style.pixelLeft + "px";
+
+ // Revert the changed values
+ style.left = left;
+ if ( rsLeft ) {
+ rs.left = rsLeft;
+ }
+ }
+
+ // Support: IE
+ // IE returns zIndex value as an integer.
+ return ret === undefined ?
+ ret :
+ ret + "" || "auto";
+ };
+}
+
+
+
+
+function addGetHookIf( conditionFn, hookFn ) {
+ // Define the hook, we'll check on the first run if it's really needed.
+ return {
+ get: function() {
+ var condition = conditionFn();
+
+ if ( condition == null ) {
+ // The test was not ready at this point; screw the hook this time
+ // but check again when needed next time.
+ return;
+ }
+
+ if ( condition ) {
+ // Hook not needed (or it's not possible to use it due to missing dependency),
+ // remove it.
+ // Since there are no other hooks for marginRight, remove the whole object.
+ delete this.get;
+ return;
+ }
+
+ // Hook needed; redefine it so that the support test is not executed again.
+
+ return (this.get = hookFn).apply( this, arguments );
+ }
+ };
+}
+
+
+(function() {
+ // Minified: var b,c,d,e,f,g, h,i
+ var div, style, a, pixelPositionVal, boxSizingReliableVal,
+ reliableHiddenOffsetsVal, reliableMarginRightVal;
+
+ // Setup
+ div = document.createElement( "div" );
+ div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
+ a = div.getElementsByTagName( "a" )[ 0 ];
+ style = a && a.style;
+
+ // Finish early in limited (non-browser) environments
+ if ( !style ) {
+ return;
+ }
+
+ style.cssText = "float:left;opacity:.5";
+
+ // Support: IE<9
+ // Make sure that element opacity exists (as opposed to filter)
+ support.opacity = style.opacity === "0.5";
+
+ // Verify style float existence
+ // (IE uses styleFloat instead of cssFloat)
+ support.cssFloat = !!style.cssFloat;
+
+ div.style.backgroundClip = "content-box";
+ div.cloneNode( true ).style.backgroundClip = "";
+ support.clearCloneStyle = div.style.backgroundClip === "content-box";
+
+ // Support: Firefox<29, Android 2.3
+ // Vendor-prefix box-sizing
+ support.boxSizing = style.boxSizing === "" || style.MozBoxSizing === "" ||
+ style.WebkitBoxSizing === "";
+
+ jQuery.extend(support, {
+ reliableHiddenOffsets: function() {
+ if ( reliableHiddenOffsetsVal == null ) {
+ computeStyleTests();
+ }
+ return reliableHiddenOffsetsVal;
+ },
+
+ boxSizingReliable: function() {
+ if ( boxSizingReliableVal == null ) {
+ computeStyleTests();
+ }
+ return boxSizingReliableVal;
+ },
+
+ pixelPosition: function() {
+ if ( pixelPositionVal == null ) {
+ computeStyleTests();
+ }
+ return pixelPositionVal;
+ },
+
+ // Support: Android 2.3
+ reliableMarginRight: function() {
+ if ( reliableMarginRightVal == null ) {
+ computeStyleTests();
+ }
+ return reliableMarginRightVal;
+ }
+ });
+
+ function computeStyleTests() {
+ // Minified: var b,c,d,j
+ var div, body, container, contents;
+
+ body = document.getElementsByTagName( "body" )[ 0 ];
+ if ( !body || !body.style ) {
+ // Test fired too early or in an unsupported environment, exit.
+ return;
+ }
+
+ // Setup
+ div = document.createElement( "div" );
+ container = document.createElement( "div" );
+ container.style.cssText = "position:absolute;border:0;width:0;height:0;top:0;left:-9999px";
+ body.appendChild( container ).appendChild( div );
+
+ div.style.cssText =
+ // Support: Firefox<29, Android 2.3
+ // Vendor-prefix box-sizing
+ "-webkit-box-sizing:border-box;-moz-box-sizing:border-box;" +
+ "box-sizing:border-box;display:block;margin-top:1%;top:1%;" +
+ "border:1px;padding:1px;width:4px;position:absolute";
+
+ // Support: IE<9
+ // Assume reasonable values in the absence of getComputedStyle
+ pixelPositionVal = boxSizingReliableVal = false;
+ reliableMarginRightVal = true;
+
+ // Check for getComputedStyle so that this code is not run in IE<9.
+ if ( window.getComputedStyle ) {
+ pixelPositionVal = ( window.getComputedStyle( div, null ) || {} ).top !== "1%";
+ boxSizingReliableVal =
+ ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px";
+
+ // Support: Android 2.3
+ // Div with explicit width and no margin-right incorrectly
+ // gets computed margin-right based on width of container (#3333)
+ // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+ contents = div.appendChild( document.createElement( "div" ) );
+
+ // Reset CSS: box-sizing; display; margin; border; padding
+ contents.style.cssText = div.style.cssText =
+ // Support: Firefox<29, Android 2.3
+ // Vendor-prefix box-sizing
+ "-webkit-box-sizing:content-box;-moz-box-sizing:content-box;" +
+ "box-sizing:content-box;display:block;margin:0;border:0;padding:0";
+ contents.style.marginRight = contents.style.width = "0";
+ div.style.width = "1px";
+
+ reliableMarginRightVal =
+ !parseFloat( ( window.getComputedStyle( contents, null ) || {} ).marginRight );
+ }
+
+ // Support: IE8
+ // Check if table cells still have offsetWidth/Height when they are set
+ // to display:none and there are still other visible table cells in a
+ // table row; if so, offsetWidth/Height are not reliable for use when
+ // determining if an element has been hidden directly using
+ // display:none (it is still safe to use offsets if a parent element is
+ // hidden; don safety goggles and see bug #4512 for more information).
+ div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>";
+ contents = div.getElementsByTagName( "td" );
+ contents[ 0 ].style.cssText = "margin:0;border:0;padding:0;display:none";
+ reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
+ if ( reliableHiddenOffsetsVal ) {
+ contents[ 0 ].style.display = "";
+ contents[ 1 ].style.display = "none";
+ reliableHiddenOffsetsVal = contents[ 0 ].offsetHeight === 0;
+ }
+
+ body.removeChild( container );
+ }
+
+})();
+
+
+// A method for quickly swapping in/out CSS properties to get correct calculations.
+jQuery.swap = function( elem, options, callback, args ) {
+ var ret, name,
+ old = {};
+
+ // Remember the old values, and insert the new ones
+ for ( name in options ) {
+ old[ name ] = elem.style[ name ];
+ elem.style[ name ] = options[ name ];
+ }
+
+ ret = callback.apply( elem, args || [] );
+
+ // Revert the old values
+ for ( name in options ) {
+ elem.style[ name ] = old[ name ];
+ }
+
+ return ret;
+};
+
+
+var
+ ralpha = /alpha\([^)]*\)/i,
+ ropacity = /opacity\s*=\s*([^)]*)/,
+
+ // swappable if display is none or starts with table except "table", "table-cell", or "table-caption"
+ // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display
+ rdisplayswap = /^(none|table(?!-c[ea]).+)/,
+ rnumsplit = new RegExp( "^(" + pnum + ")(.*)$", "i" ),
+ rrelNum = new RegExp( "^([+-])=(" + pnum + ")", "i" ),
+
+ cssShow = { position: "absolute", visibility: "hidden", display: "block" },
+ cssNormalTransform = {
+ letterSpacing: "0",
+ fontWeight: "400"
+ },
+
+ cssPrefixes = [ "Webkit", "O", "Moz", "ms" ];
+
+
+// return a css property mapped to a potentially vendor prefixed property
+function vendorPropName( style, name ) {
+
+ // shortcut for names that are not vendor prefixed
+ if ( name in style ) {
+ return name;
+ }
+
+ // check for vendor prefixed names
+ var capName = name.charAt(0).toUpperCase() + name.slice(1),
+ origName = name,
+ i = cssPrefixes.length;
+
+ while ( i-- ) {
+ name = cssPrefixes[ i ] + capName;
+ if ( name in style ) {
+ return name;
+ }
+ }
+
+ return origName;
+}
+
+function showHide( elements, show ) {
+ var display, elem, hidden,
+ values = [],
+ index = 0,
+ length = elements.length;
+
+ for ( ; index < length; index++ ) {
+ elem = elements[ index ];
+ if ( !elem.style ) {
+ continue;
+ }
+
+ values[ index ] = jQuery._data( elem, "olddisplay" );
+ display = elem.style.display;
+ if ( show ) {
+ // Reset the inline display of this element to learn if it is
+ // being hidden by cascaded rules or not
+ if ( !values[ index ] && display === "none" ) {
+ elem.style.display = "";
+ }
+
+ // Set elements which have been overridden with display: none
+ // in a stylesheet to whatever the default browser style is
+ // for such an element
+ if ( elem.style.display === "" && isHidden( elem ) ) {
+ values[ index ] = jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
+ }
+ } else {
+ hidden = isHidden( elem );
+
+ if ( display && display !== "none" || !hidden ) {
+ jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) );
+ }
+ }
+ }
+
+ // Set the display of most of the elements in a second loop
+ // to avoid the constant reflow
+ for ( index = 0; index < length; index++ ) {
+ elem = elements[ index ];
+ if ( !elem.style ) {
+ continue;
+ }
+ if ( !show || elem.style.display === "none" || elem.style.display === "" ) {
+ elem.style.display = show ? values[ index ] || "" : "none";
+ }
+ }
+
+ return elements;
+}
+
+function setPositiveNumber( elem, value, subtract ) {
+ var matches = rnumsplit.exec( value );
+ return matches ?
+ // Guard against undefined "subtract", e.g., when used as in cssHooks
+ Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) :
+ value;
+}
+
+function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) {
+ var i = extra === ( isBorderBox ? "border" : "content" ) ?
+ // If we already have the right measurement, avoid augmentation
+ 4 :
+ // Otherwise initialize for horizontal or vertical properties
+ name === "width" ? 1 : 0,
+
+ val = 0;
+
+ for ( ; i < 4; i += 2 ) {
+ // both box models exclude margin, so add it if we want it
+ if ( extra === "margin" ) {
+ val += jQuery.css( elem, extra + cssExpand[ i ], true, styles );
+ }
+
+ if ( isBorderBox ) {
+ // border-box includes padding, so remove it if we want content
+ if ( extra === "content" ) {
+ val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
+ }
+
+ // at this point, extra isn't border nor margin, so remove border
+ if ( extra !== "margin" ) {
+ val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
+ }
+ } else {
+ // at this point, extra isn't content, so add padding
+ val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles );
+
+ // at this point, extra isn't content nor padding, so add border
+ if ( extra !== "padding" ) {
+ val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles );
+ }
+ }
+ }
+
+ return val;
+}
+
+function getWidthOrHeight( elem, name, extra ) {
+
+ // Start with offset property, which is equivalent to the border-box value
+ var valueIsBorderBox = true,
+ val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
+ styles = getStyles( elem ),
+ isBorderBox = support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box";
+
+ // some non-html elements return undefined for offsetWidth, so check for null/undefined
+ // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285
+ // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668
+ if ( val <= 0 || val == null ) {
+ // Fall back to computed then uncomputed css if necessary
+ val = curCSS( elem, name, styles );
+ if ( val < 0 || val == null ) {
+ val = elem.style[ name ];
+ }
+
+ // Computed unit is not pixels. Stop here and return.
+ if ( rnumnonpx.test(val) ) {
+ return val;
+ }
+
+ // we need the check for style in case a browser which returns unreliable values
+ // for getComputedStyle silently falls back to the reliable elem.style
+ valueIsBorderBox = isBorderBox && ( support.boxSizingReliable() || val === elem.style[ name ] );
+
+ // Normalize "", auto, and prepare for extra
+ val = parseFloat( val ) || 0;
+ }
+
+ // use the active box-sizing model to add/subtract irrelevant styles
+ return ( val +
+ augmentWidthOrHeight(
+ elem,
+ name,
+ extra || ( isBorderBox ? "border" : "content" ),
+ valueIsBorderBox,
+ styles
+ )
+ ) + "px";
+}
+
+jQuery.extend({
+ // Add in style property hooks for overriding the default
+ // behavior of getting and setting a style property
+ cssHooks: {
+ opacity: {
+ get: function( elem, computed ) {
+ if ( computed ) {
+ // We should always get a number back from opacity
+ var ret = curCSS( elem, "opacity" );
+ return ret === "" ? "1" : ret;
+ }
+ }
+ }
+ },
+
+ // Don't automatically add "px" to these possibly-unitless properties
+ cssNumber: {
+ "columnCount": true,
+ "fillOpacity": true,
+ "flexGrow": true,
+ "flexShrink": true,
+ "fontWeight": true,
+ "lineHeight": true,
+ "opacity": true,
+ "order": true,
+ "orphans": true,
+ "widows": true,
+ "zIndex": true,
+ "zoom": true
+ },
+
+ // Add in properties whose names you wish to fix before
+ // setting or getting the value
+ cssProps: {
+ // normalize float css property
+ "float": support.cssFloat ? "cssFloat" : "styleFloat"
+ },
+
+ // Get and set the style property on a DOM Node
+ style: function( elem, name, value, extra ) {
+ // Don't set styles on text and comment nodes
+ if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
+ return;
+ }
+
+ // Make sure that we're working with the right name
+ var ret, type, hooks,
+ origName = jQuery.camelCase( name ),
+ style = elem.style;
+
+ name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) );
+
+ // gets hook for the prefixed version
+ // followed by the unprefixed version
+ hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
+
+ // Check if we're setting a value
+ if ( value !== undefined ) {
+ type = typeof value;
+
+ // convert relative number strings (+= or -=) to relative numbers. #7345
+ if ( type === "string" && (ret = rrelNum.exec( value )) ) {
+ value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) );
+ // Fixes bug #9237
+ type = "number";
+ }
+
+ // Make sure that null and NaN values aren't set. See: #7116
+ if ( value == null || value !== value ) {
+ return;
+ }
+
+ // If a number was passed in, add 'px' to the (except for certain CSS properties)
+ if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
+ value += "px";
+ }
+
+ // Fixes #8908, it can be done more correctly by specifing setters in cssHooks,
+ // but it would mean to define eight (for every problematic property) identical functions
+ if ( !support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) {
+ style[ name ] = "inherit";
+ }
+
+ // If a hook was provided, use that value, otherwise just set the specified value
+ if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) {
+
+ // Support: IE
+ // Swallow errors from 'invalid' CSS values (#5509)
+ try {
+ style[ name ] = value;
+ } catch(e) {}
+ }
+
+ } else {
+ // If a hook was provided get the non-computed value from there
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
+ return ret;
+ }
+
+ // Otherwise just get the value from the style object
+ return style[ name ];
+ }
+ },
+
+ css: function( elem, name, extra, styles ) {
+ var num, val, hooks,
+ origName = jQuery.camelCase( name );
+
+ // Make sure that we're working with the right name
+ name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) );
+
+ // gets hook for the prefixed version
+ // followed by the unprefixed version
+ hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ];
+
+ // If a hook was provided get the computed value from there
+ if ( hooks && "get" in hooks ) {
+ val = hooks.get( elem, true, extra );
+ }
+
+ // Otherwise, if a way to get the computed value exists, use that
+ if ( val === undefined ) {
+ val = curCSS( elem, name, styles );
+ }
+
+ //convert "normal" to computed value
+ if ( val === "normal" && name in cssNormalTransform ) {
+ val = cssNormalTransform[ name ];
+ }
+
+ // Return, converting to number if forced or a qualifier was provided and val looks numeric
+ if ( extra === "" || extra ) {
+ num = parseFloat( val );
+ return extra === true || jQuery.isNumeric( num ) ? num || 0 : val;
+ }
+ return val;
+ }
+});
+
+jQuery.each([ "height", "width" ], function( i, name ) {
+ jQuery.cssHooks[ name ] = {
+ get: function( elem, computed, extra ) {
+ if ( computed ) {
+ // certain elements can have dimension info if we invisibly show them
+ // however, it must have a current display style that would benefit from this
+ return rdisplayswap.test( jQuery.css( elem, "display" ) ) && elem.offsetWidth === 0 ?
+ jQuery.swap( elem, cssShow, function() {
+ return getWidthOrHeight( elem, name, extra );
+ }) :
+ getWidthOrHeight( elem, name, extra );
+ }
+ },
+
+ set: function( elem, value, extra ) {
+ var styles = extra && getStyles( elem );
+ return setPositiveNumber( elem, value, extra ?
+ augmentWidthOrHeight(
+ elem,
+ name,
+ extra,
+ support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box",
+ styles
+ ) : 0
+ );
+ }
+ };
+});
+
+if ( !support.opacity ) {
+ jQuery.cssHooks.opacity = {
+ get: function( elem, computed ) {
+ // IE uses filters for opacity
+ return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
+ ( 0.01 * parseFloat( RegExp.$1 ) ) + "" :
+ computed ? "1" : "";
+ },
+
+ set: function( elem, value ) {
+ var style = elem.style,
+ currentStyle = elem.currentStyle,
+ opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
+ filter = currentStyle && currentStyle.filter || style.filter || "";
+
+ // IE has trouble with opacity if it does not have layout
+ // Force it by setting the zoom level
+ style.zoom = 1;
+
+ // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
+ // if value === "", then remove inline opacity #12685
+ if ( ( value >= 1 || value === "" ) &&
+ jQuery.trim( filter.replace( ralpha, "" ) ) === "" &&
+ style.removeAttribute ) {
+
+ // Setting style.filter to null, "" & " " still leave "filter:" in the cssText
+ // if "filter:" is present at all, clearType is disabled, we want to avoid this
+ // style.removeAttribute is IE Only, but so apparently is this code path...
+ style.removeAttribute( "filter" );
+
+ // if there is no filter style applied in a css rule or unset inline opacity, we are done
+ if ( value === "" || currentStyle && !currentStyle.filter ) {
+ return;
+ }
+ }
+
+ // otherwise, set new filter values
+ style.filter = ralpha.test( filter ) ?
+ filter.replace( ralpha, opacity ) :
+ filter + " " + opacity;
+ }
+ };
+}
+
+jQuery.cssHooks.marginRight = addGetHookIf( support.reliableMarginRight,
+ function( elem, computed ) {
+ if ( computed ) {
+ // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
+ // Work around by temporarily setting element display to inline-block
+ return jQuery.swap( elem, { "display": "inline-block" },
+ curCSS, [ elem, "marginRight" ] );
+ }
+ }
+);
+
+// These hooks are used by animate to expand properties
+jQuery.each({
+ margin: "",
+ padding: "",
+ border: "Width"
+}, function( prefix, suffix ) {
+ jQuery.cssHooks[ prefix + suffix ] = {
+ expand: function( value ) {
+ var i = 0,
+ expanded = {},
+
+ // assumes a single number if not a string
+ parts = typeof value === "string" ? value.split(" ") : [ value ];
+
+ for ( ; i < 4; i++ ) {
+ expanded[ prefix + cssExpand[ i ] + suffix ] =
+ parts[ i ] || parts[ i - 2 ] || parts[ 0 ];
+ }
+
+ return expanded;
+ }
+ };
+
+ if ( !rmargin.test( prefix ) ) {
+ jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber;
+ }
+});
+
+jQuery.fn.extend({
+ css: function( name, value ) {
+ return access( this, function( elem, name, value ) {
+ var styles, len,
+ map = {},
+ i = 0;
+
+ if ( jQuery.isArray( name ) ) {
+ styles = getStyles( elem );
+ len = name.length;
+
+ for ( ; i < len; i++ ) {
+ map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles );
+ }
+
+ return map;
+ }
+
+ return value !== undefined ?
+ jQuery.style( elem, name, value ) :
+ jQuery.css( elem, name );
+ }, name, value, arguments.length > 1 );
+ },
+ show: function() {
+ return showHide( this, true );
+ },
+ hide: function() {
+ return showHide( this );
+ },
+ toggle: function( state ) {
+ if ( typeof state === "boolean" ) {
+ return state ? this.show() : this.hide();
+ }
+
+ return this.each(function() {
+ if ( isHidden( this ) ) {
+ jQuery( this ).show();
+ } else {
+ jQuery( this ).hide();
+ }
+ });
+ }
+});
+
+
+function Tween( elem, options, prop, end, easing ) {
+ return new Tween.prototype.init( elem, options, prop, end, easing );
+}
+jQuery.Tween = Tween;
+
+Tween.prototype = {
+ constructor: Tween,
+ init: function( elem, options, prop, end, easing, unit ) {
+ this.elem = elem;
+ this.prop = prop;
+ this.easing = easing || "swing";
+ this.options = options;
+ this.start = this.now = this.cur();
+ this.end = end;
+ this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" );
+ },
+ cur: function() {
+ var hooks = Tween.propHooks[ this.prop ];
+
+ return hooks && hooks.get ?
+ hooks.get( this ) :
+ Tween.propHooks._default.get( this );
+ },
+ run: function( percent ) {
+ var eased,
+ hooks = Tween.propHooks[ this.prop ];
+
+ if ( this.options.duration ) {
+ this.pos = eased = jQuery.easing[ this.easing ](
+ percent, this.options.duration * percent, 0, 1, this.options.duration
+ );
+ } else {
+ this.pos = eased = percent;
+ }
+ this.now = ( this.end - this.start ) * eased + this.start;
+
+ if ( this.options.step ) {
+ this.options.step.call( this.elem, this.now, this );
+ }
+
+ if ( hooks && hooks.set ) {
+ hooks.set( this );
+ } else {
+ Tween.propHooks._default.set( this );
+ }
+ return this;
+ }
+};
+
+Tween.prototype.init.prototype = Tween.prototype;
+
+Tween.propHooks = {
+ _default: {
+ get: function( tween ) {
+ var result;
+
+ if ( tween.elem[ tween.prop ] != null &&
+ (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) {
+ return tween.elem[ tween.prop ];
+ }
+
+ // passing an empty string as a 3rd parameter to .css will automatically
+ // attempt a parseFloat and fallback to a string if the parse fails
+ // so, simple values such as "10px" are parsed to Float.
+ // complex values such as "rotate(1rad)" are returned as is.
+ result = jQuery.css( tween.elem, tween.prop, "" );
+ // Empty strings, null, undefined and "auto" are converted to 0.
+ return !result || result === "auto" ? 0 : result;
+ },
+ set: function( tween ) {
+ // use step hook for back compat - use cssHook if its there - use .style if its
+ // available and use plain properties where available
+ if ( jQuery.fx.step[ tween.prop ] ) {
+ jQuery.fx.step[ tween.prop ]( tween );
+ } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) {
+ jQuery.style( tween.elem, tween.prop, tween.now + tween.unit );
+ } else {
+ tween.elem[ tween.prop ] = tween.now;
+ }
+ }
+ }
+};
+
+// Support: IE <=9
+// Panic based approach to setting things on disconnected nodes
+
+Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = {
+ set: function( tween ) {
+ if ( tween.elem.nodeType && tween.elem.parentNode ) {
+ tween.elem[ tween.prop ] = tween.now;
+ }
+ }
+};
+
+jQuery.easing = {
+ linear: function( p ) {
+ return p;
+ },
+ swing: function( p ) {
+ return 0.5 - Math.cos( p * Math.PI ) / 2;
+ }
+};
+
+jQuery.fx = Tween.prototype.init;
+
+// Back Compat <1.8 extension point
+jQuery.fx.step = {};
+
+
+
+
+var
+ fxNow, timerId,
+ rfxtypes = /^(?:toggle|show|hide)$/,
+ rfxnum = new RegExp( "^(?:([+-])=|)(" + pnum + ")([a-z%]*)$", "i" ),
+ rrun = /queueHooks$/,
+ animationPrefilters = [ defaultPrefilter ],
+ tweeners = {
+ "*": [ function( prop, value ) {
+ var tween = this.createTween( prop, value ),
+ target = tween.cur(),
+ parts = rfxnum.exec( value ),
+ unit = parts && parts[ 3 ] || ( jQuery.cssNumber[ prop ] ? "" : "px" ),
+
+ // Starting value computation is required for potential unit mismatches
+ start = ( jQuery.cssNumber[ prop ] || unit !== "px" && +target ) &&
+ rfxnum.exec( jQuery.css( tween.elem, prop ) ),
+ scale = 1,
+ maxIterations = 20;
+
+ if ( start && start[ 3 ] !== unit ) {
+ // Trust units reported by jQuery.css
+ unit = unit || start[ 3 ];
+
+ // Make sure we update the tween properties later on
+ parts = parts || [];
+
+ // Iteratively approximate from a nonzero starting point
+ start = +target || 1;
+
+ do {
+ // If previous iteration zeroed out, double until we get *something*
+ // Use a string for doubling factor so we don't accidentally see scale as unchanged below
+ scale = scale || ".5";
+
+ // Adjust and apply
+ start = start / scale;
+ jQuery.style( tween.elem, prop, start + unit );
+
+ // Update scale, tolerating zero or NaN from tween.cur()
+ // And breaking the loop if scale is unchanged or perfect, or if we've just had enough
+ } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations );
+ }
+
+ // Update tween properties
+ if ( parts ) {
+ start = tween.start = +start || +target || 0;
+ tween.unit = unit;
+ // If a +=/-= token was provided, we're doing a relative animation
+ tween.end = parts[ 1 ] ?
+ start + ( parts[ 1 ] + 1 ) * parts[ 2 ] :
+ +parts[ 2 ];
+ }
+
+ return tween;
+ } ]
+ };
+
+// Animations created synchronously will run synchronously
+function createFxNow() {
+ setTimeout(function() {
+ fxNow = undefined;
+ });
+ return ( fxNow = jQuery.now() );
+}
+
+// Generate parameters to create a standard animation
+function genFx( type, includeWidth ) {
+ var which,
+ attrs = { height: type },
+ i = 0;
+
+ // if we include width, step value is 1 to do all cssExpand values,
+ // if we don't include width, step value is 2 to skip over Left and Right
+ includeWidth = includeWidth ? 1 : 0;
+ for ( ; i < 4 ; i += 2 - includeWidth ) {
+ which = cssExpand[ i ];
+ attrs[ "margin" + which ] = attrs[ "padding" + which ] = type;
+ }
+
+ if ( includeWidth ) {
+ attrs.opacity = attrs.width = type;
+ }
+
+ return attrs;
+}
+
+function createTween( value, prop, animation ) {
+ var tween,
+ collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ),
+ index = 0,
+ length = collection.length;
+ for ( ; index < length; index++ ) {
+ if ( (tween = collection[ index ].call( animation, prop, value )) ) {
+
+ // we're done with this property
+ return tween;
+ }
+ }
+}
+
+function defaultPrefilter( elem, props, opts ) {
+ /* jshint validthis: true */
+ var prop, value, toggle, tween, hooks, oldfire, display, checkDisplay,
+ anim = this,
+ orig = {},
+ style = elem.style,
+ hidden = elem.nodeType && isHidden( elem ),
+ dataShow = jQuery._data( elem, "fxshow" );
+
+ // handle queue: false promises
+ if ( !opts.queue ) {
+ hooks = jQuery._queueHooks( elem, "fx" );
+ if ( hooks.unqueued == null ) {
+ hooks.unqueued = 0;
+ oldfire = hooks.empty.fire;
+ hooks.empty.fire = function() {
+ if ( !hooks.unqueued ) {
+ oldfire();
+ }
+ };
+ }
+ hooks.unqueued++;
+
+ anim.always(function() {
+ // doing this makes sure that the complete handler will be called
+ // before this completes
+ anim.always(function() {
+ hooks.unqueued--;
+ if ( !jQuery.queue( elem, "fx" ).length ) {
+ hooks.empty.fire();
+ }
+ });
+ });
+ }
+
+ // height/width overflow pass
+ if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) {
+ // Make sure that nothing sneaks out
+ // Record all 3 overflow attributes because IE does not
+ // change the overflow attribute when overflowX and
+ // overflowY are set to the same value
+ opts.overflow = [ style.overflow, style.overflowX, style.overflowY ];
+
+ // Set display property to inline-block for height/width
+ // animations on inline elements that are having width/height animated
+ display = jQuery.css( elem, "display" );
+
+ // Test default display if display is currently "none"
+ checkDisplay = display === "none" ?
+ jQuery._data( elem, "olddisplay" ) || defaultDisplay( elem.nodeName ) : display;
+
+ if ( checkDisplay === "inline" && jQuery.css( elem, "float" ) === "none" ) {
+
+ // inline-level elements accept inline-block;
+ // block-level elements need to be inline with layout
+ if ( !support.inlineBlockNeedsLayout || defaultDisplay( elem.nodeName ) === "inline" ) {
+ style.display = "inline-block";
+ } else {
+ style.zoom = 1;
+ }
+ }
+ }
+
+ if ( opts.overflow ) {
+ style.overflow = "hidden";
+ if ( !support.shrinkWrapBlocks() ) {
+ anim.always(function() {
+ style.overflow = opts.overflow[ 0 ];
+ style.overflowX = opts.overflow[ 1 ];
+ style.overflowY = opts.overflow[ 2 ];
+ });
+ }
+ }
+
+ // show/hide pass
+ for ( prop in props ) {
+ value = props[ prop ];
+ if ( rfxtypes.exec( value ) ) {
+ delete props[ prop ];
+ toggle = toggle || value === "toggle";
+ if ( value === ( hidden ? "hide" : "show" ) ) {
+
+ // If there is dataShow left over from a stopped hide or show and we are going to proceed with show, we should pretend to be hidden
+ if ( value === "show" && dataShow && dataShow[ prop ] !== undefined ) {
+ hidden = true;
+ } else {
+ continue;
+ }
+ }
+ orig[ prop ] = dataShow && dataShow[ prop ] || jQuery.style( elem, prop );
+
+ // Any non-fx value stops us from restoring the original display value
+ } else {
+ display = undefined;
+ }
+ }
+
+ if ( !jQuery.isEmptyObject( orig ) ) {
+ if ( dataShow ) {
+ if ( "hidden" in dataShow ) {
+ hidden = dataShow.hidden;
+ }
+ } else {
+ dataShow = jQuery._data( elem, "fxshow", {} );
+ }
+
+ // store state if its toggle - enables .stop().toggle() to "reverse"
+ if ( toggle ) {
+ dataShow.hidden = !hidden;
+ }
+ if ( hidden ) {
+ jQuery( elem ).show();
+ } else {
+ anim.done(function() {
+ jQuery( elem ).hide();
+ });
+ }
+ anim.done(function() {
+ var prop;
+ jQuery._removeData( elem, "fxshow" );
+ for ( prop in orig ) {
+ jQuery.style( elem, prop, orig[ prop ] );
+ }
+ });
+ for ( prop in orig ) {
+ tween = createTween( hidden ? dataShow[ prop ] : 0, prop, anim );
+
+ if ( !( prop in dataShow ) ) {
+ dataShow[ prop ] = tween.start;
+ if ( hidden ) {
+ tween.end = tween.start;
+ tween.start = prop === "width" || prop === "height" ? 1 : 0;
+ }
+ }
+ }
+
+ // If this is a noop like .hide().hide(), restore an overwritten display value
+ } else if ( (display === "none" ? defaultDisplay( elem.nodeName ) : display) === "inline" ) {
+ style.display = display;
+ }
+}
+
+function propFilter( props, specialEasing ) {
+ var index, name, easing, value, hooks;
+
+ // camelCase, specialEasing and expand cssHook pass
+ for ( index in props ) {
+ name = jQuery.camelCase( index );
+ easing = specialEasing[ name ];
+ value = props[ index ];
+ if ( jQuery.isArray( value ) ) {
+ easing = value[ 1 ];
+ value = props[ index ] = value[ 0 ];
+ }
+
+ if ( index !== name ) {
+ props[ name ] = value;
+ delete props[ index ];
+ }
+
+ hooks = jQuery.cssHooks[ name ];
+ if ( hooks && "expand" in hooks ) {
+ value = hooks.expand( value );
+ delete props[ name ];
+
+ // not quite $.extend, this wont overwrite keys already present.
+ // also - reusing 'index' from above because we have the correct "name"
+ for ( index in value ) {
+ if ( !( index in props ) ) {
+ props[ index ] = value[ index ];
+ specialEasing[ index ] = easing;
+ }
+ }
+ } else {
+ specialEasing[ name ] = easing;
+ }
+ }
+}
+
+function Animation( elem, properties, options ) {
+ var result,
+ stopped,
+ index = 0,
+ length = animationPrefilters.length,
+ deferred = jQuery.Deferred().always( function() {
+ // don't match elem in the :animated selector
+ delete tick.elem;
+ }),
+ tick = function() {
+ if ( stopped ) {
+ return false;
+ }
+ var currentTime = fxNow || createFxNow(),
+ remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ),
+ // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497)
+ temp = remaining / animation.duration || 0,
+ percent = 1 - temp,
+ index = 0,
+ length = animation.tweens.length;
+
+ for ( ; index < length ; index++ ) {
+ animation.tweens[ index ].run( percent );
+ }
+
+ deferred.notifyWith( elem, [ animation, percent, remaining ]);
+
+ if ( percent < 1 && length ) {
+ return remaining;
+ } else {
+ deferred.resolveWith( elem, [ animation ] );
+ return false;
+ }
+ },
+ animation = deferred.promise({
+ elem: elem,
+ props: jQuery.extend( {}, properties ),
+ opts: jQuery.extend( true, { specialEasing: {} }, options ),
+ originalProperties: properties,
+ originalOptions: options,
+ startTime: fxNow || createFxNow(),
+ duration: options.duration,
+ tweens: [],
+ createTween: function( prop, end ) {
+ var tween = jQuery.Tween( elem, animation.opts, prop, end,
+ animation.opts.specialEasing[ prop ] || animation.opts.easing );
+ animation.tweens.push( tween );
+ return tween;
+ },
+ stop: function( gotoEnd ) {
+ var index = 0,
+ // if we are going to the end, we want to run all the tweens
+ // otherwise we skip this part
+ length = gotoEnd ? animation.tweens.length : 0;
+ if ( stopped ) {
+ return this;
+ }
+ stopped = true;
+ for ( ; index < length ; index++ ) {
+ animation.tweens[ index ].run( 1 );
+ }
+
+ // resolve when we played the last frame
+ // otherwise, reject
+ if ( gotoEnd ) {
+ deferred.resolveWith( elem, [ animation, gotoEnd ] );
+ } else {
+ deferred.rejectWith( elem, [ animation, gotoEnd ] );
+ }
+ return this;
+ }
+ }),
+ props = animation.props;
+
+ propFilter( props, animation.opts.specialEasing );
+
+ for ( ; index < length ; index++ ) {
+ result = animationPrefilters[ index ].call( animation, elem, props, animation.opts );
+ if ( result ) {
+ return result;
+ }
+ }
+
+ jQuery.map( props, createTween, animation );
+
+ if ( jQuery.isFunction( animation.opts.start ) ) {
+ animation.opts.start.call( elem, animation );
+ }
+
+ jQuery.fx.timer(
+ jQuery.extend( tick, {
+ elem: elem,
+ anim: animation,
+ queue: animation.opts.queue
+ })
+ );
+
+ // attach callbacks from options
+ return animation.progress( animation.opts.progress )
+ .done( animation.opts.done, animation.opts.complete )
+ .fail( animation.opts.fail )
+ .always( animation.opts.always );
+}
+
+jQuery.Animation = jQuery.extend( Animation, {
+ tweener: function( props, callback ) {
+ if ( jQuery.isFunction( props ) ) {
+ callback = props;
+ props = [ "*" ];
+ } else {
+ props = props.split(" ");
+ }
+
+ var prop,
+ index = 0,
+ length = props.length;
+
+ for ( ; index < length ; index++ ) {
+ prop = props[ index ];
+ tweeners[ prop ] = tweeners[ prop ] || [];
+ tweeners[ prop ].unshift( callback );
+ }
+ },
+
+ prefilter: function( callback, prepend ) {
+ if ( prepend ) {
+ animationPrefilters.unshift( callback );
+ } else {
+ animationPrefilters.push( callback );
+ }
+ }
+});
+
+jQuery.speed = function( speed, easing, fn ) {
+ var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
+ complete: fn || !fn && easing ||
+ jQuery.isFunction( speed ) && speed,
+ duration: speed,
+ easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
+ };
+
+ opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
+ opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
+
+ // normalize opt.queue - true/undefined/null -> "fx"
+ if ( opt.queue == null || opt.queue === true ) {
+ opt.queue = "fx";
+ }
+
+ // Queueing
+ opt.old = opt.complete;
+
+ opt.complete = function() {
+ if ( jQuery.isFunction( opt.old ) ) {
+ opt.old.call( this );
+ }
+
+ if ( opt.queue ) {
+ jQuery.dequeue( this, opt.queue );
+ }
+ };
+
+ return opt;
+};
+
+jQuery.fn.extend({
+ fadeTo: function( speed, to, easing, callback ) {
+
+ // show any hidden elements after setting opacity to 0
+ return this.filter( isHidden ).css( "opacity", 0 ).show()
+
+ // animate to the value specified
+ .end().animate({ opacity: to }, speed, easing, callback );
+ },
+ animate: function( prop, speed, easing, callback ) {
+ var empty = jQuery.isEmptyObject( prop ),
+ optall = jQuery.speed( speed, easing, callback ),
+ doAnimation = function() {
+ // Operate on a copy of prop so per-property easing won't be lost
+ var anim = Animation( this, jQuery.extend( {}, prop ), optall );
+
+ // Empty animations, or finishing resolves immediately
+ if ( empty || jQuery._data( this, "finish" ) ) {
+ anim.stop( true );
+ }
+ };
+ doAnimation.finish = doAnimation;
+
+ return empty || optall.queue === false ?
+ this.each( doAnimation ) :
+ this.queue( optall.queue, doAnimation );
+ },
+ stop: function( type, clearQueue, gotoEnd ) {
+ var stopQueue = function( hooks ) {
+ var stop = hooks.stop;
+ delete hooks.stop;
+ stop( gotoEnd );
+ };
+
+ if ( typeof type !== "string" ) {
+ gotoEnd = clearQueue;
+ clearQueue = type;
+ type = undefined;
+ }
+ if ( clearQueue && type !== false ) {
+ this.queue( type || "fx", [] );
+ }
+
+ return this.each(function() {
+ var dequeue = true,
+ index = type != null && type + "queueHooks",
+ timers = jQuery.timers,
+ data = jQuery._data( this );
+
+ if ( index ) {
+ if ( data[ index ] && data[ index ].stop ) {
+ stopQueue( data[ index ] );
+ }
+ } else {
+ for ( index in data ) {
+ if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) {
+ stopQueue( data[ index ] );
+ }
+ }
+ }
+
+ for ( index = timers.length; index--; ) {
+ if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
+ timers[ index ].anim.stop( gotoEnd );
+ dequeue = false;
+ timers.splice( index, 1 );
+ }
+ }
+
+ // start the next in the queue if the last step wasn't forced
+ // timers currently will call their complete callbacks, which will dequeue
+ // but only if they were gotoEnd
+ if ( dequeue || !gotoEnd ) {
+ jQuery.dequeue( this, type );
+ }
+ });
+ },
+ finish: function( type ) {
+ if ( type !== false ) {
+ type = type || "fx";
+ }
+ return this.each(function() {
+ var index,
+ data = jQuery._data( this ),
+ queue = data[ type + "queue" ],
+ hooks = data[ type + "queueHooks" ],
+ timers = jQuery.timers,
+ length = queue ? queue.length : 0;
+
+ // enable finishing flag on private data
+ data.finish = true;
+
+ // empty the queue first
+ jQuery.queue( this, type, [] );
+
+ if ( hooks && hooks.stop ) {
+ hooks.stop.call( this, true );
+ }
+
+ // look for any active animations, and finish them
+ for ( index = timers.length; index--; ) {
+ if ( timers[ index ].elem === this && timers[ index ].queue === type ) {
+ timers[ index ].anim.stop( true );
+ timers.splice( index, 1 );
+ }
+ }
+
+ // look for any animations in the old queue and finish them
+ for ( index = 0; index < length; index++ ) {
+ if ( queue[ index ] && queue[ index ].finish ) {
+ queue[ index ].finish.call( this );
+ }
+ }
+
+ // turn off finishing flag
+ delete data.finish;
+ });
+ }
+});
+
+jQuery.each([ "toggle", "show", "hide" ], function( i, name ) {
+ var cssFn = jQuery.fn[ name ];
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return speed == null || typeof speed === "boolean" ?
+ cssFn.apply( this, arguments ) :
+ this.animate( genFx( name, true ), speed, easing, callback );
+ };
+});
+
+// Generate shortcuts for custom animations
+jQuery.each({
+ slideDown: genFx("show"),
+ slideUp: genFx("hide"),
+ slideToggle: genFx("toggle"),
+ fadeIn: { opacity: "show" },
+ fadeOut: { opacity: "hide" },
+ fadeToggle: { opacity: "toggle" }
+}, function( name, props ) {
+ jQuery.fn[ name ] = function( speed, easing, callback ) {
+ return this.animate( props, speed, easing, callback );
+ };
+});
+
+jQuery.timers = [];
+jQuery.fx.tick = function() {
+ var timer,
+ timers = jQuery.timers,
+ i = 0;
+
+ fxNow = jQuery.now();
+
+ for ( ; i < timers.length; i++ ) {
+ timer = timers[ i ];
+ // Checks the timer has not already been removed
+ if ( !timer() && timers[ i ] === timer ) {
+ timers.splice( i--, 1 );
+ }
+ }
+
+ if ( !timers.length ) {
+ jQuery.fx.stop();
+ }
+ fxNow = undefined;
+};
+
+jQuery.fx.timer = function( timer ) {
+ jQuery.timers.push( timer );
+ if ( timer() ) {
+ jQuery.fx.start();
+ } else {
+ jQuery.timers.pop();
+ }
+};
+
+jQuery.fx.interval = 13;
+
+jQuery.fx.start = function() {
+ if ( !timerId ) {
+ timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval );
+ }
+};
+
+jQuery.fx.stop = function() {
+ clearInterval( timerId );
+ timerId = null;
+};
+
+jQuery.fx.speeds = {
+ slow: 600,
+ fast: 200,
+ // Default speed
+ _default: 400
+};
+
+
+// Based off of the plugin by Clint Helfers, with permission.
+// http://blindsignals.com/index.php/2009/07/jquery-delay/
+jQuery.fn.delay = function( time, type ) {
+ time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
+ type = type || "fx";
+
+ return this.queue( type, function( next, hooks ) {
+ var timeout = setTimeout( next, time );
+ hooks.stop = function() {
+ clearTimeout( timeout );
+ };
+ });
+};
+
+
+(function() {
+ // Minified: var a,b,c,d,e
+ var input, div, select, a, opt;
+
+ // Setup
+ div = document.createElement( "div" );
+ div.setAttribute( "className", "t" );
+ div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";
+ a = div.getElementsByTagName("a")[ 0 ];
+
+ // First batch of tests.
+ select = document.createElement("select");
+ opt = select.appendChild( document.createElement("option") );
+ input = div.getElementsByTagName("input")[ 0 ];
+
+ a.style.cssText = "top:1px";
+
+ // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
+ support.getSetAttribute = div.className !== "t";
+
+ // Get the style information from getAttribute
+ // (IE uses .cssText instead)
+ support.style = /top/.test( a.getAttribute("style") );
+
+ // Make sure that URLs aren't manipulated
+ // (IE normalizes it by default)
+ support.hrefNormalized = a.getAttribute("href") === "/a";
+
+ // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere)
+ support.checkOn = !!input.value;
+
+ // Make sure that a selected-by-default option has a working selected property.
+ // (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
+ support.optSelected = opt.selected;
+
+ // Tests for enctype support on a form (#6743)
+ support.enctype = !!document.createElement("form").enctype;
+
+ // Make sure that the options inside disabled selects aren't marked as disabled
+ // (WebKit marks them as disabled)
+ select.disabled = true;
+ support.optDisabled = !opt.disabled;
+
+ // Support: IE8 only
+ // Check if we can trust getAttribute("value")
+ input = document.createElement( "input" );
+ input.setAttribute( "value", "" );
+ support.input = input.getAttribute( "value" ) === "";
+
+ // Check if an input maintains its value after becoming a radio
+ input.value = "t";
+ input.setAttribute( "type", "radio" );
+ support.radioValue = input.value === "t";
+})();
+
+
+var rreturn = /\r/g;
+
+jQuery.fn.extend({
+ val: function( value ) {
+ var hooks, ret, isFunction,
+ elem = this[0];
+
+ if ( !arguments.length ) {
+ if ( elem ) {
+ hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ];
+
+ if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) {
+ return ret;
+ }
+
+ ret = elem.value;
+
+ return typeof ret === "string" ?
+ // handle most common string cases
+ ret.replace(rreturn, "") :
+ // handle cases where value is null/undef or number
+ ret == null ? "" : ret;
+ }
+
+ return;
+ }
+
+ isFunction = jQuery.isFunction( value );
+
+ return this.each(function( i ) {
+ var val;
+
+ if ( this.nodeType !== 1 ) {
+ return;
+ }
+
+ if ( isFunction ) {
+ val = value.call( this, i, jQuery( this ).val() );
+ } else {
+ val = value;
+ }
+
+ // Treat null/undefined as ""; convert numbers to string
+ if ( val == null ) {
+ val = "";
+ } else if ( typeof val === "number" ) {
+ val += "";
+ } else if ( jQuery.isArray( val ) ) {
+ val = jQuery.map( val, function( value ) {
+ return value == null ? "" : value + "";
+ });
+ }
+
+ hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ];
+
+ // If set returns undefined, fall back to normal setting
+ if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) {
+ this.value = val;
+ }
+ });
+ }
+});
+
+jQuery.extend({
+ valHooks: {
+ option: {
+ get: function( elem ) {
+ var val = jQuery.find.attr( elem, "value" );
+ return val != null ?
+ val :
+ // Support: IE10-11+
+ // option.text throws exceptions (#14686, #14858)
+ jQuery.trim( jQuery.text( elem ) );
+ }
+ },
+ select: {
+ get: function( elem ) {
+ var value, option,
+ options = elem.options,
+ index = elem.selectedIndex,
+ one = elem.type === "select-one" || index < 0,
+ values = one ? null : [],
+ max = one ? index + 1 : options.length,
+ i = index < 0 ?
+ max :
+ one ? index : 0;
+
+ // Loop through all the selected options
+ for ( ; i < max; i++ ) {
+ option = options[ i ];
+
+ // oldIE doesn't update selected after form reset (#2551)
+ if ( ( option.selected || i === index ) &&
+ // Don't return options that are disabled or in a disabled optgroup
+ ( support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) &&
+ ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) {
+
+ // Get the specific value for the option
+ value = jQuery( option ).val();
+
+ // We don't need an array for one selects
+ if ( one ) {
+ return value;
+ }
+
+ // Multi-Selects return an array
+ values.push( value );
+ }
+ }
+
+ return values;
+ },
+
+ set: function( elem, value ) {
+ var optionSet, option,
+ options = elem.options,
+ values = jQuery.makeArray( value ),
+ i = options.length;
+
+ while ( i-- ) {
+ option = options[ i ];
+
+ if ( jQuery.inArray( jQuery.valHooks.option.get( option ), values ) >= 0 ) {
+
+ // Support: IE6
+ // When new option element is added to select box we need to
+ // force reflow of newly added node in order to workaround delay
+ // of initialization properties
+ try {
+ option.selected = optionSet = true;
+
+ } catch ( _ ) {
+
+ // Will be executed only in IE6
+ option.scrollHeight;
+ }
+
+ } else {
+ option.selected = false;
+ }
+ }
+
+ // Force browsers to behave consistently when non-matching value is set
+ if ( !optionSet ) {
+ elem.selectedIndex = -1;
+ }
+
+ return options;
+ }
+ }
+ }
+});
+
+// Radios and checkboxes getter/setter
+jQuery.each([ "radio", "checkbox" ], function() {
+ jQuery.valHooks[ this ] = {
+ set: function( elem, value ) {
+ if ( jQuery.isArray( value ) ) {
+ return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
+ }
+ }
+ };
+ if ( !support.checkOn ) {
+ jQuery.valHooks[ this ].get = function( elem ) {
+ // Support: Webkit
+ // "" is returned instead of "on" if a value isn't specified
+ return elem.getAttribute("value") === null ? "on" : elem.value;
+ };
+ }
+});
+
+
+
+
+var nodeHook, boolHook,
+ attrHandle = jQuery.expr.attrHandle,
+ ruseDefault = /^(?:checked|selected)$/i,
+ getSetAttribute = support.getSetAttribute,
+ getSetInput = support.input;
+
+jQuery.fn.extend({
+ attr: function( name, value ) {
+ return access( this, jQuery.attr, name, value, arguments.length > 1 );
+ },
+
+ removeAttr: function( name ) {
+ return this.each(function() {
+ jQuery.removeAttr( this, name );
+ });
+ }
+});
+
+jQuery.extend({
+ attr: function( elem, name, value ) {
+ var hooks, ret,
+ nType = elem.nodeType;
+
+ // don't get/set attributes on text, comment and attribute nodes
+ if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+ return;
+ }
+
+ // Fallback to prop when attributes are not supported
+ if ( typeof elem.getAttribute === strundefined ) {
+ return jQuery.prop( elem, name, value );
+ }
+
+ // All attributes are lowercase
+ // Grab necessary hook if one is defined
+ if ( nType !== 1 || !jQuery.isXMLDoc( elem ) ) {
+ name = name.toLowerCase();
+ hooks = jQuery.attrHooks[ name ] ||
+ ( jQuery.expr.match.bool.test( name ) ? boolHook : nodeHook );
+ }
+
+ if ( value !== undefined ) {
+
+ if ( value === null ) {
+ jQuery.removeAttr( elem, name );
+
+ } else if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) {
+ return ret;
+
+ } else {
+ elem.setAttribute( name, value + "" );
+ return value;
+ }
+
+ } else if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) {
+ return ret;
+
+ } else {
+ ret = jQuery.find.attr( elem, name );
+
+ // Non-existent attributes return null, we normalize to undefined
+ return ret == null ?
+ undefined :
+ ret;
+ }
+ },
+
+ removeAttr: function( elem, value ) {
+ var name, propName,
+ i = 0,
+ attrNames = value && value.match( rnotwhite );
+
+ if ( attrNames && elem.nodeType === 1 ) {
+ while ( (name = attrNames[i++]) ) {
+ propName = jQuery.propFix[ name ] || name;
+
+ // Boolean attributes get special treatment (#10870)
+ if ( jQuery.expr.match.bool.test( name ) ) {
+ // Set corresponding property to false
+ if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
+ elem[ propName ] = false;
+ // Support: IE<9
+ // Also clear defaultChecked/defaultSelected (if appropriate)
+ } else {
+ elem[ jQuery.camelCase( "default-" + name ) ] =
+ elem[ propName ] = false;
+ }
+
+ // See #9699 for explanation of this approach (setting first, then removal)
+ } else {
+ jQuery.attr( elem, name, "" );
+ }
+
+ elem.removeAttribute( getSetAttribute ? name : propName );
+ }
+ }
+ },
+
+ attrHooks: {
+ type: {
+ set: function( elem, value ) {
+ if ( !support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) {
+ // Setting the type on a radio button after the value resets the value in IE6-9
+ // Reset value to default in case type is set after value during creation
+ var val = elem.value;
+ elem.setAttribute( "type", value );
+ if ( val ) {
+ elem.value = val;
+ }
+ return value;
+ }
+ }
+ }
+ }
+});
+
+// Hook for boolean attributes
+boolHook = {
+ set: function( elem, value, name ) {
+ if ( value === false ) {
+ // Remove boolean attributes when set to false
+ jQuery.removeAttr( elem, name );
+ } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) {
+ // IE<8 needs the *property* name
+ elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name );
+
+ // Use defaultChecked and defaultSelected for oldIE
+ } else {
+ elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true;
+ }
+
+ return name;
+ }
+};
+
+// Retrieve booleans specially
+jQuery.each( jQuery.expr.match.bool.source.match( /\w+/g ), function( i, name ) {
+
+ var getter = attrHandle[ name ] || jQuery.find.attr;
+
+ attrHandle[ name ] = getSetInput && getSetAttribute || !ruseDefault.test( name ) ?
+ function( elem, name, isXML ) {
+ var ret, handle;
+ if ( !isXML ) {
+ // Avoid an infinite loop by temporarily removing this function from the getter
+ handle = attrHandle[ name ];
+ attrHandle[ name ] = ret;
+ ret = getter( elem, name, isXML ) != null ?
+ name.toLowerCase() :
+ null;
+ attrHandle[ name ] = handle;
+ }
+ return ret;
+ } :
+ function( elem, name, isXML ) {
+ if ( !isXML ) {
+ return elem[ jQuery.camelCase( "default-" + name ) ] ?
+ name.toLowerCase() :
+ null;
+ }
+ };
+});
+
+// fix oldIE attroperties
+if ( !getSetInput || !getSetAttribute ) {
+ jQuery.attrHooks.value = {
+ set: function( elem, value, name ) {
+ if ( jQuery.nodeName( elem, "input" ) ) {
+ // Does not return so that setAttribute is also used
+ elem.defaultValue = value;
+ } else {
+ // Use nodeHook if defined (#1954); otherwise setAttribute is fine
+ return nodeHook && nodeHook.set( elem, value, name );
+ }
+ }
+ };
+}
+
+// IE6/7 do not support getting/setting some attributes with get/setAttribute
+if ( !getSetAttribute ) {
+
+ // Use this for any attribute in IE6/7
+ // This fixes almost every IE6/7 issue
+ nodeHook = {
+ set: function( elem, value, name ) {
+ // Set the existing or create a new attribute node
+ var ret = elem.getAttributeNode( name );
+ if ( !ret ) {
+ elem.setAttributeNode(
+ (ret = elem.ownerDocument.createAttribute( name ))
+ );
+ }
+
+ ret.value = value += "";
+
+ // Break association with cloned elements by also using setAttribute (#9646)
+ if ( name === "value" || value === elem.getAttribute( name ) ) {
+ return value;
+ }
+ }
+ };
+
+ // Some attributes are constructed with empty-string values when not defined
+ attrHandle.id = attrHandle.name = attrHandle.coords =
+ function( elem, name, isXML ) {
+ var ret;
+ if ( !isXML ) {
+ return (ret = elem.getAttributeNode( name )) && ret.value !== "" ?
+ ret.value :
+ null;
+ }
+ };
+
+ // Fixing value retrieval on a button requires this module
+ jQuery.valHooks.button = {
+ get: function( elem, name ) {
+ var ret = elem.getAttributeNode( name );
+ if ( ret && ret.specified ) {
+ return ret.value;
+ }
+ },
+ set: nodeHook.set
+ };
+
+ // Set contenteditable to false on removals(#10429)
+ // Setting to empty string throws an error as an invalid value
+ jQuery.attrHooks.contenteditable = {
+ set: function( elem, value, name ) {
+ nodeHook.set( elem, value === "" ? false : value, name );
+ }
+ };
+
+ // Set width and height to auto instead of 0 on empty string( Bug #8150 )
+ // This is for removals
+ jQuery.each([ "width", "height" ], function( i, name ) {
+ jQuery.attrHooks[ name ] = {
+ set: function( elem, value ) {
+ if ( value === "" ) {
+ elem.setAttribute( name, "auto" );
+ return value;
+ }
+ }
+ };
+ });
+}
+
+if ( !support.style ) {
+ jQuery.attrHooks.style = {
+ get: function( elem ) {
+ // Return undefined in the case of empty string
+ // Note: IE uppercases css property names, but if we were to .toLowerCase()
+ // .cssText, that would destroy case senstitivity in URL's, like in "background"
+ return elem.style.cssText || undefined;
+ },
+ set: function( elem, value ) {
+ return ( elem.style.cssText = value + "" );
+ }
+ };
+}
+
+
+
+
+var rfocusable = /^(?:input|select|textarea|button|object)$/i,
+ rclickable = /^(?:a|area)$/i;
+
+jQuery.fn.extend({
+ prop: function( name, value ) {
+ return access( this, jQuery.prop, name, value, arguments.length > 1 );
+ },
+
+ removeProp: function( name ) {
+ name = jQuery.propFix[ name ] || name;
+ return this.each(function() {
+ // try/catch handles cases where IE balks (such as removing a property on window)
+ try {
+ this[ name ] = undefined;
+ delete this[ name ];
+ } catch( e ) {}
+ });
+ }
+});
+
+jQuery.extend({
+ propFix: {
+ "for": "htmlFor",
+ "class": "className"
+ },
+
+ prop: function( elem, name, value ) {
+ var ret, hooks, notxml,
+ nType = elem.nodeType;
+
+ // don't get/set properties on text, comment and attribute nodes
+ if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
+ return;
+ }
+
+ notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
+
+ if ( notxml ) {
+ // Fix name and attach hooks
+ name = jQuery.propFix[ name ] || name;
+ hooks = jQuery.propHooks[ name ];
+ }
+
+ if ( value !== undefined ) {
+ return hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ?
+ ret :
+ ( elem[ name ] = value );
+
+ } else {
+ return hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ?
+ ret :
+ elem[ name ];
+ }
+ },
+
+ propHooks: {
+ tabIndex: {
+ get: function( elem ) {
+ // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set
+ // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/
+ // Use proper attribute retrieval(#12072)
+ var tabindex = jQuery.find.attr( elem, "tabindex" );
+
+ return tabindex ?
+ parseInt( tabindex, 10 ) :
+ rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ?
+ 0 :
+ -1;
+ }
+ }
+ }
+});
+
+// Some attributes require a special call on IE
+// http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx
+if ( !support.hrefNormalized ) {
+ // href/src property should get the full normalized URL (#10299/#12915)
+ jQuery.each([ "href", "src" ], function( i, name ) {
+ jQuery.propHooks[ name ] = {
+ get: function( elem ) {
+ return elem.getAttribute( name, 4 );
+ }
+ };
+ });
+}
+
+// Support: Safari, IE9+
+// mis-reports the default selected property of an option
+// Accessing the parent's selectedIndex property fixes it
+if ( !support.optSelected ) {
+ jQuery.propHooks.selected = {
+ get: function( elem ) {
+ var parent = elem.parentNode;
+
+ if ( parent ) {
+ parent.selectedIndex;
+
+ // Make sure that it also works with optgroups, see #5701
+ if ( parent.parentNode ) {
+ parent.parentNode.selectedIndex;
+ }
+ }
+ return null;
+ }
+ };
+}
+
+jQuery.each([
+ "tabIndex",
+ "readOnly",
+ "maxLength",
+ "cellSpacing",
+ "cellPadding",
+ "rowSpan",
+ "colSpan",
+ "useMap",
+ "frameBorder",
+ "contentEditable"
+], function() {
+ jQuery.propFix[ this.toLowerCase() ] = this;
+});
+
+// IE6/7 call enctype encoding
+if ( !support.enctype ) {
+ jQuery.propFix.enctype = "encoding";
+}
+
+
+
+
+var rclass = /[\t\r\n\f]/g;
+
+jQuery.fn.extend({
+ addClass: function( value ) {
+ var classes, elem, cur, clazz, j, finalValue,
+ i = 0,
+ len = this.length,
+ proceed = typeof value === "string" && value;
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( j ) {
+ jQuery( this ).addClass( value.call( this, j, this.className ) );
+ });
+ }
+
+ if ( proceed ) {
+ // The disjunction here is for better compressibility (see removeClass)
+ classes = ( value || "" ).match( rnotwhite ) || [];
+
+ for ( ; i < len; i++ ) {
+ elem = this[ i ];
+ cur = elem.nodeType === 1 && ( elem.className ?
+ ( " " + elem.className + " " ).replace( rclass, " " ) :
+ " "
+ );
+
+ if ( cur ) {
+ j = 0;
+ while ( (clazz = classes[j++]) ) {
+ if ( cur.indexOf( " " + clazz + " " ) < 0 ) {
+ cur += clazz + " ";
+ }
+ }
+
+ // only assign if different to avoid unneeded rendering.
+ finalValue = jQuery.trim( cur );
+ if ( elem.className !== finalValue ) {
+ elem.className = finalValue;
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ removeClass: function( value ) {
+ var classes, elem, cur, clazz, j, finalValue,
+ i = 0,
+ len = this.length,
+ proceed = arguments.length === 0 || typeof value === "string" && value;
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( j ) {
+ jQuery( this ).removeClass( value.call( this, j, this.className ) );
+ });
+ }
+ if ( proceed ) {
+ classes = ( value || "" ).match( rnotwhite ) || [];
+
+ for ( ; i < len; i++ ) {
+ elem = this[ i ];
+ // This expression is here for better compressibility (see addClass)
+ cur = elem.nodeType === 1 && ( elem.className ?
+ ( " " + elem.className + " " ).replace( rclass, " " ) :
+ ""
+ );
+
+ if ( cur ) {
+ j = 0;
+ while ( (clazz = classes[j++]) ) {
+ // Remove *all* instances
+ while ( cur.indexOf( " " + clazz + " " ) >= 0 ) {
+ cur = cur.replace( " " + clazz + " ", " " );
+ }
+ }
+
+ // only assign if different to avoid unneeded rendering.
+ finalValue = value ? jQuery.trim( cur ) : "";
+ if ( elem.className !== finalValue ) {
+ elem.className = finalValue;
+ }
+ }
+ }
+ }
+
+ return this;
+ },
+
+ toggleClass: function( value, stateVal ) {
+ var type = typeof value;
+
+ if ( typeof stateVal === "boolean" && type === "string" ) {
+ return stateVal ? this.addClass( value ) : this.removeClass( value );
+ }
+
+ if ( jQuery.isFunction( value ) ) {
+ return this.each(function( i ) {
+ jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
+ });
+ }
+
+ return this.each(function() {
+ if ( type === "string" ) {
+ // toggle individual class names
+ var className,
+ i = 0,
+ self = jQuery( this ),
+ classNames = value.match( rnotwhite ) || [];
+
+ while ( (className = classNames[ i++ ]) ) {
+ // check each className given, space separated list
+ if ( self.hasClass( className ) ) {
+ self.removeClass( className );
+ } else {
+ self.addClass( className );
+ }
+ }
+
+ // Toggle whole class name
+ } else if ( type === strundefined || type === "boolean" ) {
+ if ( this.className ) {
+ // store className if set
+ jQuery._data( this, "__className__", this.className );
+ }
+
+ // If the element has a class name or if we're passed "false",
+ // then remove the whole classname (if there was one, the above saved it).
+ // Otherwise bring back whatever was previously saved (if anything),
+ // falling back to the empty string if nothing was stored.
+ this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
+ }
+ });
+ },
+
+ hasClass: function( selector ) {
+ var className = " " + selector + " ",
+ i = 0,
+ l = this.length;
+ for ( ; i < l; i++ ) {
+ if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) {
+ return true;
+ }
+ }
+
+ return false;
+ }
+});
+
+
+
+
+// Return jQuery for attributes-only inclusion
+
+
+jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
+ "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
+ "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
+
+ // Handle event binding
+ jQuery.fn[ name ] = function( data, fn ) {
+ return arguments.length > 0 ?
+ this.on( name, null, data, fn ) :
+ this.trigger( name );
+ };
+});
+
+jQuery.fn.extend({
+ hover: function( fnOver, fnOut ) {
+ return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
+ },
+
+ bind: function( types, data, fn ) {
+ return this.on( types, null, data, fn );
+ },
+ unbind: function( types, fn ) {
+ return this.off( types, null, fn );
+ },
+
+ delegate: function( selector, types, data, fn ) {
+ return this.on( types, selector, data, fn );
+ },
+ undelegate: function( selector, types, fn ) {
+ // ( namespace ) or ( selector, types [, fn] )
+ return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn );
+ }
+});
+
+
+var nonce = jQuery.now();
+
+var rquery = (/\?/);
+
+
+
+var rvalidtokens = /(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;
+
+jQuery.parseJSON = function( data ) {
+ // Attempt to parse using the native JSON parser first
+ if ( window.JSON && window.JSON.parse ) {
+ // Support: Android 2.3
+ // Workaround failure to string-cast null input
+ return window.JSON.parse( data + "" );
+ }
+
+ var requireNonComma,
+ depth = null,
+ str = jQuery.trim( data + "" );
+
+ // Guard against invalid (and possibly dangerous) input by ensuring that nothing remains
+ // after removing valid tokens
+ return str && !jQuery.trim( str.replace( rvalidtokens, function( token, comma, open, close ) {
+
+ // Force termination if we see a misplaced comma
+ if ( requireNonComma && comma ) {
+ depth = 0;
+ }
+
+ // Perform no more replacements after returning to outermost depth
+ if ( depth === 0 ) {
+ return token;
+ }
+
+ // Commas must not follow "[", "{", or ","
+ requireNonComma = open || comma;
+
+ // Determine new depth
+ // array/object open ("[" or "{"): depth += true - false (increment)
+ // array/object close ("]" or "}"): depth += false - true (decrement)
+ // other cases ("," or primitive): depth += true - true (numeric cast)
+ depth += !close - !open;
+
+ // Remove this token
+ return "";
+ }) ) ?
+ ( Function( "return " + str ) )() :
+ jQuery.error( "Invalid JSON: " + data );
+};
+
+
+// Cross-browser xml parsing
+jQuery.parseXML = function( data ) {
+ var xml, tmp;
+ if ( !data || typeof data !== "string" ) {
+ return null;
+ }
+ try {
+ if ( window.DOMParser ) { // Standard
+ tmp = new DOMParser();
+ xml = tmp.parseFromString( data, "text/xml" );
+ } else { // IE
+ xml = new ActiveXObject( "Microsoft.XMLDOM" );
+ xml.async = "false";
+ xml.loadXML( data );
+ }
+ } catch( e ) {
+ xml = undefined;
+ }
+ if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
+ jQuery.error( "Invalid XML: " + data );
+ }
+ return xml;
+};
+
+
+var
+ // Document location
+ ajaxLocParts,
+ ajaxLocation,
+
+ rhash = /#.*$/,
+ rts = /([?&])_=[^&]*/,
+ rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
+ // #7653, #8125, #8152: local protocol detection
+ rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/,
+ rnoContent = /^(?:GET|HEAD)$/,
+ rprotocol = /^\/\//,
+ rurl = /^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,
+
+ /* Prefilters
+ * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
+ * 2) These are called:
+ * - BEFORE asking for a transport
+ * - AFTER param serialization (s.data is a string if s.processData is true)
+ * 3) key is the dataType
+ * 4) the catchall symbol "*" can be used
+ * 5) execution will start with transport dataType and THEN continue down to "*" if needed
+ */
+ prefilters = {},
+
+ /* Transports bindings
+ * 1) key is the dataType
+ * 2) the catchall symbol "*" can be used
+ * 3) selection will start with transport dataType and THEN go to "*" if needed
+ */
+ transports = {},
+
+ // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
+ allTypes = "*/".concat("*");
+
+// #8138, IE may throw an exception when accessing
+// a field from window.location if document.domain has been set
+try {
+ ajaxLocation = location.href;
+} catch( e ) {
+ // Use the href attribute of an A element
+ // since IE will modify it given document.location
+ ajaxLocation = document.createElement( "a" );
+ ajaxLocation.href = "";
+ ajaxLocation = ajaxLocation.href;
+}
+
+// Segment location into parts
+ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
+
+// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
+function addToPrefiltersOrTransports( structure ) {
+
+ // dataTypeExpression is optional and defaults to "*"
+ return function( dataTypeExpression, func ) {
+
+ if ( typeof dataTypeExpression !== "string" ) {
+ func = dataTypeExpression;
+ dataTypeExpression = "*";
+ }
+
+ var dataType,
+ i = 0,
+ dataTypes = dataTypeExpression.toLowerCase().match( rnotwhite ) || [];
+
+ if ( jQuery.isFunction( func ) ) {
+ // For each dataType in the dataTypeExpression
+ while ( (dataType = dataTypes[i++]) ) {
+ // Prepend if requested
+ if ( dataType.charAt( 0 ) === "+" ) {
+ dataType = dataType.slice( 1 ) || "*";
+ (structure[ dataType ] = structure[ dataType ] || []).unshift( func );
+
+ // Otherwise append
+ } else {
+ (structure[ dataType ] = structure[ dataType ] || []).push( func );
+ }
+ }
+ }
+ };
+}
+
+// Base inspection function for prefilters and transports
+function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) {
+
+ var inspected = {},
+ seekingTransport = ( structure === transports );
+
+ function inspect( dataType ) {
+ var selected;
+ inspected[ dataType ] = true;
+ jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) {
+ var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR );
+ if ( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) {
+ options.dataTypes.unshift( dataTypeOrTransport );
+ inspect( dataTypeOrTransport );
+ return false;
+ } else if ( seekingTransport ) {
+ return !( selected = dataTypeOrTransport );
+ }
+ });
+ return selected;
+ }
+
+ return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" );
+}
+
+// A special extend for ajax options
+// that takes "flat" options (not to be deep extended)
+// Fixes #9887
+function ajaxExtend( target, src ) {
+ var deep, key,
+ flatOptions = jQuery.ajaxSettings.flatOptions || {};
+
+ for ( key in src ) {
+ if ( src[ key ] !== undefined ) {
+ ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ];
+ }
+ }
+ if ( deep ) {
+ jQuery.extend( true, target, deep );
+ }
+
+ return target;
+}
+
+/* Handles responses to an ajax request:
+ * - finds the right dataType (mediates between content-type and expected dataType)
+ * - returns the corresponding response
+ */
+function ajaxHandleResponses( s, jqXHR, responses ) {
+ var firstDataType, ct, finalDataType, type,
+ contents = s.contents,
+ dataTypes = s.dataTypes;
+
+ // Remove auto dataType and get content-type in the process
+ while ( dataTypes[ 0 ] === "*" ) {
+ dataTypes.shift();
+ if ( ct === undefined ) {
+ ct = s.mimeType || jqXHR.getResponseHeader("Content-Type");
+ }
+ }
+
+ // Check if we're dealing with a known content-type
+ if ( ct ) {
+ for ( type in contents ) {
+ if ( contents[ type ] && contents[ type ].test( ct ) ) {
+ dataTypes.unshift( type );
+ break;
+ }
+ }
+ }
+
+ // Check to see if we have a response for the expected dataType
+ if ( dataTypes[ 0 ] in responses ) {
+ finalDataType = dataTypes[ 0 ];
+ } else {
+ // Try convertible dataTypes
+ for ( type in responses ) {
+ if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
+ finalDataType = type;
+ break;
+ }
+ if ( !firstDataType ) {
+ firstDataType = type;
+ }
+ }
+ // Or just use first one
+ finalDataType = finalDataType || firstDataType;
+ }
+
+ // If we found a dataType
+ // We add the dataType to the list if needed
+ // and return the corresponding response
+ if ( finalDataType ) {
+ if ( finalDataType !== dataTypes[ 0 ] ) {
+ dataTypes.unshift( finalDataType );
+ }
+ return responses[ finalDataType ];
+ }
+}
+
+/* Chain conversions given the request and the original response
+ * Also sets the responseXXX fields on the jqXHR instance
+ */
+function ajaxConvert( s, response, jqXHR, isSuccess ) {
+ var conv2, current, conv, tmp, prev,
+ converters = {},
+ // Work with a copy of dataTypes in case we need to modify it for conversion
+ dataTypes = s.dataTypes.slice();
+
+ // Create converters map with lowercased keys
+ if ( dataTypes[ 1 ] ) {
+ for ( conv in s.converters ) {
+ converters[ conv.toLowerCase() ] = s.converters[ conv ];
+ }
+ }
+
+ current = dataTypes.shift();
+
+ // Convert to each sequential dataType
+ while ( current ) {
+
+ if ( s.responseFields[ current ] ) {
+ jqXHR[ s.responseFields[ current ] ] = response;
+ }
+
+ // Apply the dataFilter if provided
+ if ( !prev && isSuccess && s.dataFilter ) {
+ response = s.dataFilter( response, s.dataType );
+ }
+
+ prev = current;
+ current = dataTypes.shift();
+
+ if ( current ) {
+
+ // There's only work to do if current dataType is non-auto
+ if ( current === "*" ) {
+
+ current = prev;
+
+ // Convert response if prev dataType is non-auto and differs from current
+ } else if ( prev !== "*" && prev !== current ) {
+
+ // Seek a direct converter
+ conv = converters[ prev + " " + current ] || converters[ "* " + current ];
+
+ // If none found, seek a pair
+ if ( !conv ) {
+ for ( conv2 in converters ) {
+
+ // If conv2 outputs current
+ tmp = conv2.split( " " );
+ if ( tmp[ 1 ] === current ) {
+
+ // If prev can be converted to accepted input
+ conv = converters[ prev + " " + tmp[ 0 ] ] ||
+ converters[ "* " + tmp[ 0 ] ];
+ if ( conv ) {
+ // Condense equivalence converters
+ if ( conv === true ) {
+ conv = converters[ conv2 ];
+
+ // Otherwise, insert the intermediate dataType
+ } else if ( converters[ conv2 ] !== true ) {
+ current = tmp[ 0 ];
+ dataTypes.unshift( tmp[ 1 ] );
+ }
+ break;
+ }
+ }
+ }
+ }
+
+ // Apply converter (if not an equivalence)
+ if ( conv !== true ) {
+
+ // Unless errors are allowed to bubble, catch and return them
+ if ( conv && s[ "throws" ] ) {
+ response = conv( response );
+ } else {
+ try {
+ response = conv( response );
+ } catch ( e ) {
+ return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current };
+ }
+ }
+ }
+ }
+ }
+ }
+
+ return { state: "success", data: response };
+}
+
+jQuery.extend({
+
+ // Counter for holding the number of active queries
+ active: 0,
+
+ // Last-Modified header cache for next request
+ lastModified: {},
+ etag: {},
+
+ ajaxSettings: {
+ url: ajaxLocation,
+ type: "GET",
+ isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
+ global: true,
+ processData: true,
+ async: true,
+ contentType: "application/x-www-form-urlencoded; charset=UTF-8",
+ /*
+ timeout: 0,
+ data: null,
+ dataType: null,
+ username: null,
+ password: null,
+ cache: null,
+ throws: false,
+ traditional: false,
+ headers: {},
+ */
+
+ accepts: {
+ "*": allTypes,
+ text: "text/plain",
+ html: "text/html",
+ xml: "application/xml, text/xml",
+ json: "application/json, text/javascript"
+ },
+
+ contents: {
+ xml: /xml/,
+ html: /html/,
+ json: /json/
+ },
+
+ responseFields: {
+ xml: "responseXML",
+ text: "responseText",
+ json: "responseJSON"
+ },
+
+ // Data converters
+ // Keys separate source (or catchall "*") and destination types with a single space
+ converters: {
+
+ // Convert anything to text
+ "* text": String,
+
+ // Text to html (true = no transformation)
+ "text html": true,
+
+ // Evaluate text as a json expression
+ "text json": jQuery.parseJSON,
+
+ // Parse text as xml
+ "text xml": jQuery.parseXML
+ },
+
+ // For options that shouldn't be deep extended:
+ // you can add your own custom options here if
+ // and when you create one that shouldn't be
+ // deep extended (see ajaxExtend)
+ flatOptions: {
+ url: true,
+ context: true
+ }
+ },
+
+ // Creates a full fledged settings object into target
+ // with both ajaxSettings and settings fields.
+ // If target is omitted, writes into ajaxSettings.
+ ajaxSetup: function( target, settings ) {
+ return settings ?
+
+ // Building a settings object
+ ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) :
+
+ // Extending ajaxSettings
+ ajaxExtend( jQuery.ajaxSettings, target );
+ },
+
+ ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
+ ajaxTransport: addToPrefiltersOrTransports( transports ),
+
+ // Main method
+ ajax: function( url, options ) {
+
+ // If url is an object, simulate pre-1.5 signature
+ if ( typeof url === "object" ) {
+ options = url;
+ url = undefined;
+ }
+
+ // Force options to be an object
+ options = options || {};
+
+ var // Cross-domain detection vars
+ parts,
+ // Loop variable
+ i,
+ // URL without anti-cache param
+ cacheURL,
+ // Response headers as string
+ responseHeadersString,
+ // timeout handle
+ timeoutTimer,
+
+ // To know if global events are to be dispatched
+ fireGlobals,
+
+ transport,
+ // Response headers
+ responseHeaders,
+ // Create the final options object
+ s = jQuery.ajaxSetup( {}, options ),
+ // Callbacks context
+ callbackContext = s.context || s,
+ // Context for global events is callbackContext if it is a DOM node or jQuery collection
+ globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ?
+ jQuery( callbackContext ) :
+ jQuery.event,
+ // Deferreds
+ deferred = jQuery.Deferred(),
+ completeDeferred = jQuery.Callbacks("once memory"),
+ // Status-dependent callbacks
+ statusCode = s.statusCode || {},
+ // Headers (they are sent all at once)
+ requestHeaders = {},
+ requestHeadersNames = {},
+ // The jqXHR state
+ state = 0,
+ // Default abort message
+ strAbort = "canceled",
+ // Fake xhr
+ jqXHR = {
+ readyState: 0,
+
+ // Builds headers hashtable if needed
+ getResponseHeader: function( key ) {
+ var match;
+ if ( state === 2 ) {
+ if ( !responseHeaders ) {
+ responseHeaders = {};
+ while ( (match = rheaders.exec( responseHeadersString )) ) {
+ responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
+ }
+ }
+ match = responseHeaders[ key.toLowerCase() ];
+ }
+ return match == null ? null : match;
+ },
+
+ // Raw string
+ getAllResponseHeaders: function() {
+ return state === 2 ? responseHeadersString : null;
+ },
+
+ // Caches the header
+ setRequestHeader: function( name, value ) {
+ var lname = name.toLowerCase();
+ if ( !state ) {
+ name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
+ requestHeaders[ name ] = value;
+ }
+ return this;
+ },
+
+ // Overrides response content-type header
+ overrideMimeType: function( type ) {
+ if ( !state ) {
+ s.mimeType = type;
+ }
+ return this;
+ },
+
+ // Status-dependent callbacks
+ statusCode: function( map ) {
+ var code;
+ if ( map ) {
+ if ( state < 2 ) {
+ for ( code in map ) {
+ // Lazy-add the new callback in a way that preserves old ones
+ statusCode[ code ] = [ statusCode[ code ], map[ code ] ];
+ }
+ } else {
+ // Execute the appropriate callbacks
+ jqXHR.always( map[ jqXHR.status ] );
+ }
+ }
+ return this;
+ },
+
+ // Cancel the request
+ abort: function( statusText ) {
+ var finalText = statusText || strAbort;
+ if ( transport ) {
+ transport.abort( finalText );
+ }
+ done( 0, finalText );
+ return this;
+ }
+ };
+
+ // Attach deferreds
+ deferred.promise( jqXHR ).complete = completeDeferred.add;
+ jqXHR.success = jqXHR.done;
+ jqXHR.error = jqXHR.fail;
+
+ // Remove hash character (#7531: and string promotion)
+ // Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
+ // Handle falsy url in the settings object (#10093: consistency with old signature)
+ // We also use the url parameter if available
+ s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
+
+ // Alias method option to type as per ticket #12004
+ s.type = options.method || options.type || s.method || s.type;
+
+ // Extract dataTypes list
+ s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( rnotwhite ) || [ "" ];
+
+ // A cross-domain request is in order when we have a protocol:host:port mismatch
+ if ( s.crossDomain == null ) {
+ parts = rurl.exec( s.url.toLowerCase() );
+ s.crossDomain = !!( parts &&
+ ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] ||
+ ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? "80" : "443" ) ) !==
+ ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? "80" : "443" ) ) )
+ );
+ }
+
+ // Convert data if not already a string
+ if ( s.data && s.processData && typeof s.data !== "string" ) {
+ s.data = jQuery.param( s.data, s.traditional );
+ }
+
+ // Apply prefilters
+ inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
+
+ // If request was aborted inside a prefilter, stop there
+ if ( state === 2 ) {
+ return jqXHR;
+ }
+
+ // We can fire global events as of now if asked to
+ fireGlobals = s.global;
+
+ // Watch for a new set of requests
+ if ( fireGlobals && jQuery.active++ === 0 ) {
+ jQuery.event.trigger("ajaxStart");
+ }
+
+ // Uppercase the type
+ s.type = s.type.toUpperCase();
+
+ // Determine if request has content
+ s.hasContent = !rnoContent.test( s.type );
+
+ // Save the URL in case we're toying with the If-Modified-Since
+ // and/or If-None-Match header later on
+ cacheURL = s.url;
+
+ // More options handling for requests with no content
+ if ( !s.hasContent ) {
+
+ // If data is available, append data to url
+ if ( s.data ) {
+ cacheURL = ( s.url += ( rquery.test( cacheURL ) ? "&" : "?" ) + s.data );
+ // #9682: remove data so that it's not used in an eventual retry
+ delete s.data;
+ }
+
+ // Add anti-cache in url if needed
+ if ( s.cache === false ) {
+ s.url = rts.test( cacheURL ) ?
+
+ // If there is already a '_' parameter, set its value
+ cacheURL.replace( rts, "$1_=" + nonce++ ) :
+
+ // Otherwise add one to the end
+ cacheURL + ( rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + nonce++;
+ }
+ }
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ if ( jQuery.lastModified[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] );
+ }
+ if ( jQuery.etag[ cacheURL ] ) {
+ jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] );
+ }
+ }
+
+ // Set the correct header, if data is being sent
+ if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
+ jqXHR.setRequestHeader( "Content-Type", s.contentType );
+ }
+
+ // Set the Accepts header for the server, depending on the dataType
+ jqXHR.setRequestHeader(
+ "Accept",
+ s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
+ s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
+ s.accepts[ "*" ]
+ );
+
+ // Check for headers option
+ for ( i in s.headers ) {
+ jqXHR.setRequestHeader( i, s.headers[ i ] );
+ }
+
+ // Allow custom headers/mimetypes and early abort
+ if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
+ // Abort if not done already and return
+ return jqXHR.abort();
+ }
+
+ // aborting is no longer a cancellation
+ strAbort = "abort";
+
+ // Install callbacks on deferreds
+ for ( i in { success: 1, error: 1, complete: 1 } ) {
+ jqXHR[ i ]( s[ i ] );
+ }
+
+ // Get transport
+ transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
+
+ // If no transport, we auto-abort
+ if ( !transport ) {
+ done( -1, "No Transport" );
+ } else {
+ jqXHR.readyState = 1;
+
+ // Send global event
+ if ( fireGlobals ) {
+ globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
+ }
+ // Timeout
+ if ( s.async && s.timeout > 0 ) {
+ timeoutTimer = setTimeout(function() {
+ jqXHR.abort("timeout");
+ }, s.timeout );
+ }
+
+ try {
+ state = 1;
+ transport.send( requestHeaders, done );
+ } catch ( e ) {
+ // Propagate exception as error if not done
+ if ( state < 2 ) {
+ done( -1, e );
+ // Simply rethrow otherwise
+ } else {
+ throw e;
+ }
+ }
+ }
+
+ // Callback for when everything is done
+ function done( status, nativeStatusText, responses, headers ) {
+ var isSuccess, success, error, response, modified,
+ statusText = nativeStatusText;
+
+ // Called once
+ if ( state === 2 ) {
+ return;
+ }
+
+ // State is "done" now
+ state = 2;
+
+ // Clear timeout if it exists
+ if ( timeoutTimer ) {
+ clearTimeout( timeoutTimer );
+ }
+
+ // Dereference transport for early garbage collection
+ // (no matter how long the jqXHR object will be used)
+ transport = undefined;
+
+ // Cache response headers
+ responseHeadersString = headers || "";
+
+ // Set readyState
+ jqXHR.readyState = status > 0 ? 4 : 0;
+
+ // Determine if successful
+ isSuccess = status >= 200 && status < 300 || status === 304;
+
+ // Get response data
+ if ( responses ) {
+ response = ajaxHandleResponses( s, jqXHR, responses );
+ }
+
+ // Convert no matter what (that way responseXXX fields are always set)
+ response = ajaxConvert( s, response, jqXHR, isSuccess );
+
+ // If successful, handle type chaining
+ if ( isSuccess ) {
+
+ // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
+ if ( s.ifModified ) {
+ modified = jqXHR.getResponseHeader("Last-Modified");
+ if ( modified ) {
+ jQuery.lastModified[ cacheURL ] = modified;
+ }
+ modified = jqXHR.getResponseHeader("etag");
+ if ( modified ) {
+ jQuery.etag[ cacheURL ] = modified;
+ }
+ }
+
+ // if no content
+ if ( status === 204 || s.type === "HEAD" ) {
+ statusText = "nocontent";
+
+ // if not modified
+ } else if ( status === 304 ) {
+ statusText = "notmodified";
+
+ // If we have data, let's convert it
+ } else {
+ statusText = response.state;
+ success = response.data;
+ error = response.error;
+ isSuccess = !error;
+ }
+ } else {
+ // We extract error from statusText
+ // then normalize statusText and status for non-aborts
+ error = statusText;
+ if ( status || !statusText ) {
+ statusText = "error";
+ if ( status < 0 ) {
+ status = 0;
+ }
+ }
+ }
+
+ // Set data for the fake xhr object
+ jqXHR.status = status;
+ jqXHR.statusText = ( nativeStatusText || statusText ) + "";
+
+ // Success/Error
+ if ( isSuccess ) {
+ deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
+ } else {
+ deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
+ }
+
+ // Status-dependent callbacks
+ jqXHR.statusCode( statusCode );
+ statusCode = undefined;
+
+ if ( fireGlobals ) {
+ globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError",
+ [ jqXHR, s, isSuccess ? success : error ] );
+ }
+
+ // Complete
+ completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
+
+ if ( fireGlobals ) {
+ globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
+ // Handle the global AJAX counter
+ if ( !( --jQuery.active ) ) {
+ jQuery.event.trigger("ajaxStop");
+ }
+ }
+ }
+
+ return jqXHR;
+ },
+
+ getJSON: function( url, data, callback ) {
+ return jQuery.get( url, data, callback, "json" );
+ },
+
+ getScript: function( url, callback ) {
+ return jQuery.get( url, undefined, callback, "script" );
+ }
+});
+
+jQuery.each( [ "get", "post" ], function( i, method ) {
+ jQuery[ method ] = function( url, data, callback, type ) {
+ // shift arguments if data argument was omitted
+ if ( jQuery.isFunction( data ) ) {
+ type = type || callback;
+ callback = data;
+ data = undefined;
+ }
+
+ return jQuery.ajax({
+ url: url,
+ type: method,
+ dataType: type,
+ data: data,
+ success: callback
+ });
+ };
+});
+
+// Attach a bunch of functions for handling common AJAX events
+jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ) {
+ jQuery.fn[ type ] = function( fn ) {
+ return this.on( type, fn );
+ };
+});
+
+
+jQuery._evalUrl = function( url ) {
+ return jQuery.ajax({
+ url: url,
+ type: "GET",
+ dataType: "script",
+ async: false,
+ global: false,
+ "throws": true
+ });
+};
+
+
+jQuery.fn.extend({
+ wrapAll: function( html ) {
+ if ( jQuery.isFunction( html ) ) {
+ return this.each(function(i) {
+ jQuery(this).wrapAll( html.call(this, i) );
+ });
+ }
+
+ if ( this[0] ) {
+ // The elements to wrap the target around
+ var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
+
+ if ( this[0].parentNode ) {
+ wrap.insertBefore( this[0] );
+ }
+
+ wrap.map(function() {
+ var elem = this;
+
+ while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
+ elem = elem.firstChild;
+ }
+
+ return elem;
+ }).append( this );
+ }
+
+ return this;
+ },
+
+ wrapInner: function( html ) {
+ if ( jQuery.isFunction( html ) ) {
+ return this.each(function(i) {
+ jQuery(this).wrapInner( html.call(this, i) );
+ });
+ }
+
+ return this.each(function() {
+ var self = jQuery( this ),
+ contents = self.contents();
+
+ if ( contents.length ) {
+ contents.wrapAll( html );
+
+ } else {
+ self.append( html );
+ }
+ });
+ },
+
+ wrap: function( html ) {
+ var isFunction = jQuery.isFunction( html );
+
+ return this.each(function(i) {
+ jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html );
+ });
+ },
+
+ unwrap: function() {
+ return this.parent().each(function() {
+ if ( !jQuery.nodeName( this, "body" ) ) {
+ jQuery( this ).replaceWith( this.childNodes );
+ }
+ }).end();
+ }
+});
+
+
+jQuery.expr.filters.hidden = function( elem ) {
+ // Support: Opera <= 12.12
+ // Opera reports offsetWidths and offsetHeights less than zero on some elements
+ return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 ||
+ (!support.reliableHiddenOffsets() &&
+ ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
+};
+
+jQuery.expr.filters.visible = function( elem ) {
+ return !jQuery.expr.filters.hidden( elem );
+};
+
+
+
+
+var r20 = /%20/g,
+ rbracket = /\[\]$/,
+ rCRLF = /\r?\n/g,
+ rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i,
+ rsubmittable = /^(?:input|select|textarea|keygen)/i;
+
+function buildParams( prefix, obj, traditional, add ) {
+ var name;
+
+ if ( jQuery.isArray( obj ) ) {
+ // Serialize array item.
+ jQuery.each( obj, function( i, v ) {
+ if ( traditional || rbracket.test( prefix ) ) {
+ // Treat each array item as a scalar.
+ add( prefix, v );
+
+ } else {
+ // Item is non-scalar (array or object), encode its numeric index.
+ buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
+ }
+ });
+
+ } else if ( !traditional && jQuery.type( obj ) === "object" ) {
+ // Serialize object item.
+ for ( name in obj ) {
+ buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
+ }
+
+ } else {
+ // Serialize scalar item.
+ add( prefix, obj );
+ }
+}
+
+// Serialize an array of form elements or a set of
+// key/values into a query string
+jQuery.param = function( a, traditional ) {
+ var prefix,
+ s = [],
+ add = function( key, value ) {
+ // If value is a function, invoke it and return its value
+ value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value );
+ s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
+ };
+
+ // Set traditional to true for jQuery <= 1.3.2 behavior.
+ if ( traditional === undefined ) {
+ traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional;
+ }
+
+ // If an array was passed in, assume that it is an array of form elements.
+ if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
+ // Serialize the form elements
+ jQuery.each( a, function() {
+ add( this.name, this.value );
+ });
+
+ } else {
+ // If traditional, encode the "old" way (the way 1.3.2 or older
+ // did it), otherwise encode params recursively.
+ for ( prefix in a ) {
+ buildParams( prefix, a[ prefix ], traditional, add );
+ }
+ }
+
+ // Return the resulting serialization
+ return s.join( "&" ).replace( r20, "+" );
+};
+
+jQuery.fn.extend({
+ serialize: function() {
+ return jQuery.param( this.serializeArray() );
+ },
+ serializeArray: function() {
+ return this.map(function() {
+ // Can add propHook for "elements" to filter or add form elements
+ var elements = jQuery.prop( this, "elements" );
+ return elements ? jQuery.makeArray( elements ) : this;
+ })
+ .filter(function() {
+ var type = this.type;
+ // Use .is(":disabled") so that fieldset[disabled] works
+ return this.name && !jQuery( this ).is( ":disabled" ) &&
+ rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) &&
+ ( this.checked || !rcheckableType.test( type ) );
+ })
+ .map(function( i, elem ) {
+ var val = jQuery( this ).val();
+
+ return val == null ?
+ null :
+ jQuery.isArray( val ) ?
+ jQuery.map( val, function( val ) {
+ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ }) :
+ { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
+ }).get();
+ }
+});
+
+
+// Create the request object
+// (This is still attached to ajaxSettings for backward compatibility)
+jQuery.ajaxSettings.xhr = window.ActiveXObject !== undefined ?
+ // Support: IE6+
+ function() {
+
+ // XHR cannot access local files, always use ActiveX for that case
+ return !this.isLocal &&
+
+ // Support: IE7-8
+ // oldIE XHR does not support non-RFC2616 methods (#13240)
+ // See http://msdn.microsoft.com/en-us/library/ie/ms536648(v=vs.85).aspx
+ // and http://www.w3.org/Protocols/rfc2616/rfc2616-sec9.html#sec9
+ // Although this check for six methods instead of eight
+ // since IE also does not support "trace" and "connect"
+ /^(get|post|head|put|delete|options)$/i.test( this.type ) &&
+
+ createStandardXHR() || createActiveXHR();
+ } :
+ // For all other browsers, use the standard XMLHttpRequest object
+ createStandardXHR;
+
+var xhrId = 0,
+ xhrCallbacks = {},
+ xhrSupported = jQuery.ajaxSettings.xhr();
+
+// Support: IE<10
+// Open requests must be manually aborted on unload (#5280)
+if ( window.ActiveXObject ) {
+ jQuery( window ).on( "unload", function() {
+ for ( var key in xhrCallbacks ) {
+ xhrCallbacks[ key ]( undefined, true );
+ }
+ });
+}
+
+// Determine support properties
+support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
+xhrSupported = support.ajax = !!xhrSupported;
+
+// Create transport if the browser can provide an xhr
+if ( xhrSupported ) {
+
+ jQuery.ajaxTransport(function( options ) {
+ // Cross domain only allowed if supported through XMLHttpRequest
+ if ( !options.crossDomain || support.cors ) {
+
+ var callback;
+
+ return {
+ send: function( headers, complete ) {
+ var i,
+ xhr = options.xhr(),
+ id = ++xhrId;
+
+ // Open the socket
+ xhr.open( options.type, options.url, options.async, options.username, options.password );
+
+ // Apply custom fields if provided
+ if ( options.xhrFields ) {
+ for ( i in options.xhrFields ) {
+ xhr[ i ] = options.xhrFields[ i ];
+ }
+ }
+
+ // Override mime type if needed
+ if ( options.mimeType && xhr.overrideMimeType ) {
+ xhr.overrideMimeType( options.mimeType );
+ }
+
+ // X-Requested-With header
+ // For cross-domain requests, seeing as conditions for a preflight are
+ // akin to a jigsaw puzzle, we simply never set it to be sure.
+ // (it can always be set on a per-request basis or even using ajaxSetup)
+ // For same-domain requests, won't change header if already provided.
+ if ( !options.crossDomain && !headers["X-Requested-With"] ) {
+ headers["X-Requested-With"] = "XMLHttpRequest";
+ }
+
+ // Set headers
+ for ( i in headers ) {
+ // Support: IE<9
+ // IE's ActiveXObject throws a 'Type Mismatch' exception when setting
+ // request header to a null-value.
+ //
+ // To keep consistent with other XHR implementations, cast the value
+ // to string and ignore `undefined`.
+ if ( headers[ i ] !== undefined ) {
+ xhr.setRequestHeader( i, headers[ i ] + "" );
+ }
+ }
+
+ // Do send the request
+ // This may raise an exception which is actually
+ // handled in jQuery.ajax (so no try/catch here)
+ xhr.send( ( options.hasContent && options.data ) || null );
+
+ // Listener
+ callback = function( _, isAbort ) {
+ var status, statusText, responses;
+
+ // Was never called and is aborted or complete
+ if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
+ // Clean up
+ delete xhrCallbacks[ id ];
+ callback = undefined;
+ xhr.onreadystatechange = jQuery.noop;
+
+ // Abort manually if needed
+ if ( isAbort ) {
+ if ( xhr.readyState !== 4 ) {
+ xhr.abort();
+ }
+ } else {
+ responses = {};
+ status = xhr.status;
+
+ // Support: IE<10
+ // Accessing binary-data responseText throws an exception
+ // (#11426)
+ if ( typeof xhr.responseText === "string" ) {
+ responses.text = xhr.responseText;
+ }
+
+ // Firefox throws an exception when accessing
+ // statusText for faulty cross-domain requests
+ try {
+ statusText = xhr.statusText;
+ } catch( e ) {
+ // We normalize with Webkit giving an empty statusText
+ statusText = "";
+ }
+
+ // Filter status for non standard behaviors
+
+ // If the request is local and we have data: assume a success
+ // (success with no data won't get notified, that's the best we
+ // can do given current implementations)
+ if ( !status && options.isLocal && !options.crossDomain ) {
+ status = responses.text ? 200 : 404;
+ // IE - #1450: sometimes returns 1223 when it should be 204
+ } else if ( status === 1223 ) {
+ status = 204;
+ }
+ }
+ }
+
+ // Call complete if needed
+ if ( responses ) {
+ complete( status, statusText, responses, xhr.getAllResponseHeaders() );
+ }
+ };
+
+ if ( !options.async ) {
+ // if we're in sync mode we fire the callback
+ callback();
+ } else if ( xhr.readyState === 4 ) {
+ // (IE6 & IE7) if it's in cache and has been
+ // retrieved directly we need to fire the callback
+ setTimeout( callback );
+ } else {
+ // Add to the list of active xhr callbacks
+ xhr.onreadystatechange = xhrCallbacks[ id ] = callback;
+ }
+ },
+
+ abort: function() {
+ if ( callback ) {
+ callback( undefined, true );
+ }
+ }
+ };
+ }
+ });
+}
+
+// Functions to create xhrs
+function createStandardXHR() {
+ try {
+ return new window.XMLHttpRequest();
+ } catch( e ) {}
+}
+
+function createActiveXHR() {
+ try {
+ return new window.ActiveXObject( "Microsoft.XMLHTTP" );
+ } catch( e ) {}
+}
+
+
+
+
+// Install script dataType
+jQuery.ajaxSetup({
+ accepts: {
+ script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
+ },
+ contents: {
+ script: /(?:java|ecma)script/
+ },
+ converters: {
+ "text script": function( text ) {
+ jQuery.globalEval( text );
+ return text;
+ }
+ }
+});
+
+// Handle cache's special case and global
+jQuery.ajaxPrefilter( "script", function( s ) {
+ if ( s.cache === undefined ) {
+ s.cache = false;
+ }
+ if ( s.crossDomain ) {
+ s.type = "GET";
+ s.global = false;
+ }
+});
+
+// Bind script tag hack transport
+jQuery.ajaxTransport( "script", function(s) {
+
+ // This transport only deals with cross domain requests
+ if ( s.crossDomain ) {
+
+ var script,
+ head = document.head || jQuery("head")[0] || document.documentElement;
+
+ return {
+
+ send: function( _, callback ) {
+
+ script = document.createElement("script");
+
+ script.async = true;
+
+ if ( s.scriptCharset ) {
+ script.charset = s.scriptCharset;
+ }
+
+ script.src = s.url;
+
+ // Attach handlers for all browsers
+ script.onload = script.onreadystatechange = function( _, isAbort ) {
+
+ if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
+
+ // Handle memory leak in IE
+ script.onload = script.onreadystatechange = null;
+
+ // Remove the script
+ if ( script.parentNode ) {
+ script.parentNode.removeChild( script );
+ }
+
+ // Dereference the script
+ script = null;
+
+ // Callback if not abort
+ if ( !isAbort ) {
+ callback( 200, "success" );
+ }
+ }
+ };
+
+ // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending
+ // Use native DOM manipulation to avoid our domManip AJAX trickery
+ head.insertBefore( script, head.firstChild );
+ },
+
+ abort: function() {
+ if ( script ) {
+ script.onload( undefined, true );
+ }
+ }
+ };
+ }
+});
+
+
+
+
+var oldCallbacks = [],
+ rjsonp = /(=)\?(?=&|$)|\?\?/;
+
+// Default jsonp settings
+jQuery.ajaxSetup({
+ jsonp: "callback",
+ jsonpCallback: function() {
+ var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( nonce++ ) );
+ this[ callback ] = true;
+ return callback;
+ }
+});
+
+// Detect, normalize options and install callbacks for jsonp requests
+jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
+
+ var callbackName, overwritten, responseContainer,
+ jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ?
+ "url" :
+ typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data"
+ );
+
+ // Handle iff the expected data type is "jsonp" or we have a parameter to set
+ if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) {
+
+ // Get callback name, remembering preexisting value associated with it
+ callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ?
+ s.jsonpCallback() :
+ s.jsonpCallback;
+
+ // Insert callback into url or form data
+ if ( jsonProp ) {
+ s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName );
+ } else if ( s.jsonp !== false ) {
+ s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName;
+ }
+
+ // Use data converter to retrieve json after script execution
+ s.converters["script json"] = function() {
+ if ( !responseContainer ) {
+ jQuery.error( callbackName + " was not called" );
+ }
+ return responseContainer[ 0 ];
+ };
+
+ // force json dataType
+ s.dataTypes[ 0 ] = "json";
+
+ // Install callback
+ overwritten = window[ callbackName ];
+ window[ callbackName ] = function() {
+ responseContainer = arguments;
+ };
+
+ // Clean-up function (fires after converters)
+ jqXHR.always(function() {
+ // Restore preexisting value
+ window[ callbackName ] = overwritten;
+
+ // Save back as free
+ if ( s[ callbackName ] ) {
+ // make sure that re-using the options doesn't screw things around
+ s.jsonpCallback = originalSettings.jsonpCallback;
+
+ // save the callback name for future use
+ oldCallbacks.push( callbackName );
+ }
+
+ // Call if it was a function and we have a response
+ if ( responseContainer && jQuery.isFunction( overwritten ) ) {
+ overwritten( responseContainer[ 0 ] );
+ }
+
+ responseContainer = overwritten = undefined;
+ });
+
+ // Delegate to script
+ return "script";
+ }
+});
+
+
+
+
+// data: string of html
+// context (optional): If specified, the fragment will be created in this context, defaults to document
+// keepScripts (optional): If true, will include scripts passed in the html string
+jQuery.parseHTML = function( data, context, keepScripts ) {
+ if ( !data || typeof data !== "string" ) {
+ return null;
+ }
+ if ( typeof context === "boolean" ) {
+ keepScripts = context;
+ context = false;
+ }
+ context = context || document;
+
+ var parsed = rsingleTag.exec( data ),
+ scripts = !keepScripts && [];
+
+ // Single tag
+ if ( parsed ) {
+ return [ context.createElement( parsed[1] ) ];
+ }
+
+ parsed = jQuery.buildFragment( [ data ], context, scripts );
+
+ if ( scripts && scripts.length ) {
+ jQuery( scripts ).remove();
+ }
+
+ return jQuery.merge( [], parsed.childNodes );
+};
+
+
+// Keep a copy of the old load method
+var _load = jQuery.fn.load;
+
+/**
+ * Load a url into a page
+ */
+jQuery.fn.load = function( url, params, callback ) {
+ if ( typeof url !== "string" && _load ) {
+ return _load.apply( this, arguments );
+ }
+
+ var selector, response, type,
+ self = this,
+ off = url.indexOf(" ");
+
+ if ( off >= 0 ) {
+ selector = jQuery.trim( url.slice( off, url.length ) );
+ url = url.slice( 0, off );
+ }
+
+ // If it's a function
+ if ( jQuery.isFunction( params ) ) {
+
+ // We assume that it's the callback
+ callback = params;
+ params = undefined;
+
+ // Otherwise, build a param string
+ } else if ( params && typeof params === "object" ) {
+ type = "POST";
+ }
+
+ // If we have elements to modify, make the request
+ if ( self.length > 0 ) {
+ jQuery.ajax({
+ url: url,
+
+ // if "type" variable is undefined, then "GET" method will be used
+ type: type,
+ dataType: "html",
+ data: params
+ }).done(function( responseText ) {
+
+ // Save response for use in complete callback
+ response = arguments;
+
+ self.html( selector ?
+
+ // If a selector was specified, locate the right elements in a dummy div
+ // Exclude scripts to avoid IE 'Permission Denied' errors
+ jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) :
+
+ // Otherwise use the full result
+ responseText );
+
+ }).complete( callback && function( jqXHR, status ) {
+ self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] );
+ });
+ }
+
+ return this;
+};
+
+
+
+
+jQuery.expr.filters.animated = function( elem ) {
+ return jQuery.grep(jQuery.timers, function( fn ) {
+ return elem === fn.elem;
+ }).length;
+};
+
+
+
+
+
+var docElem = window.document.documentElement;
+
+/**
+ * Gets a window from an element
+ */
+function getWindow( elem ) {
+ return jQuery.isWindow( elem ) ?
+ elem :
+ elem.nodeType === 9 ?
+ elem.defaultView || elem.parentWindow :
+ false;
+}
+
+jQuery.offset = {
+ setOffset: function( elem, options, i ) {
+ var curPosition, curLeft, curCSSTop, curTop, curOffset, curCSSLeft, calculatePosition,
+ position = jQuery.css( elem, "position" ),
+ curElem = jQuery( elem ),
+ props = {};
+
+ // set position first, in-case top/left are set even on static elem
+ if ( position === "static" ) {
+ elem.style.position = "relative";
+ }
+
+ curOffset = curElem.offset();
+ curCSSTop = jQuery.css( elem, "top" );
+ curCSSLeft = jQuery.css( elem, "left" );
+ calculatePosition = ( position === "absolute" || position === "fixed" ) &&
+ jQuery.inArray("auto", [ curCSSTop, curCSSLeft ] ) > -1;
+
+ // need to be able to calculate position if either top or left is auto and position is either absolute or fixed
+ if ( calculatePosition ) {
+ curPosition = curElem.position();
+ curTop = curPosition.top;
+ curLeft = curPosition.left;
+ } else {
+ curTop = parseFloat( curCSSTop ) || 0;
+ curLeft = parseFloat( curCSSLeft ) || 0;
+ }
+
+ if ( jQuery.isFunction( options ) ) {
+ options = options.call( elem, i, curOffset );
+ }
+
+ if ( options.top != null ) {
+ props.top = ( options.top - curOffset.top ) + curTop;
+ }
+ if ( options.left != null ) {
+ props.left = ( options.left - curOffset.left ) + curLeft;
+ }
+
+ if ( "using" in options ) {
+ options.using.call( elem, props );
+ } else {
+ curElem.css( props );
+ }
+ }
+};
+
+jQuery.fn.extend({
+ offset: function( options ) {
+ if ( arguments.length ) {
+ return options === undefined ?
+ this :
+ this.each(function( i ) {
+ jQuery.offset.setOffset( this, options, i );
+ });
+ }
+
+ var docElem, win,
+ box = { top: 0, left: 0 },
+ elem = this[ 0 ],
+ doc = elem && elem.ownerDocument;
+
+ if ( !doc ) {
+ return;
+ }
+
+ docElem = doc.documentElement;
+
+ // Make sure it's not a disconnected DOM node
+ if ( !jQuery.contains( docElem, elem ) ) {
+ return box;
+ }
+
+ // If we don't have gBCR, just use 0,0 rather than error
+ // BlackBerry 5, iOS 3 (original iPhone)
+ if ( typeof elem.getBoundingClientRect !== strundefined ) {
+ box = elem.getBoundingClientRect();
+ }
+ win = getWindow( doc );
+ return {
+ top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ),
+ left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 )
+ };
+ },
+
+ position: function() {
+ if ( !this[ 0 ] ) {
+ return;
+ }
+
+ var offsetParent, offset,
+ parentOffset = { top: 0, left: 0 },
+ elem = this[ 0 ];
+
+ // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is its only offset parent
+ if ( jQuery.css( elem, "position" ) === "fixed" ) {
+ // we assume that getBoundingClientRect is available when computed position is fixed
+ offset = elem.getBoundingClientRect();
+ } else {
+ // Get *real* offsetParent
+ offsetParent = this.offsetParent();
+
+ // Get correct offsets
+ offset = this.offset();
+ if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) {
+ parentOffset = offsetParent.offset();
+ }
+
+ // Add offsetParent borders
+ parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true );
+ parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true );
+ }
+
+ // Subtract parent offsets and element margins
+ // note: when an element has margin: auto the offsetLeft and marginLeft
+ // are the same in Safari causing offset.left to incorrectly be 0
+ return {
+ top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ),
+ left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true)
+ };
+ },
+
+ offsetParent: function() {
+ return this.map(function() {
+ var offsetParent = this.offsetParent || docElem;
+
+ while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position" ) === "static" ) ) {
+ offsetParent = offsetParent.offsetParent;
+ }
+ return offsetParent || docElem;
+ });
+ }
+});
+
+// Create scrollLeft and scrollTop methods
+jQuery.each( { scrollLeft: "pageXOffset", scrollTop: "pageYOffset" }, function( method, prop ) {
+ var top = /Y/.test( prop );
+
+ jQuery.fn[ method ] = function( val ) {
+ return access( this, function( elem, method, val ) {
+ var win = getWindow( elem );
+
+ if ( val === undefined ) {
+ return win ? (prop in win) ? win[ prop ] :
+ win.document.documentElement[ method ] :
+ elem[ method ];
+ }
+
+ if ( win ) {
+ win.scrollTo(
+ !top ? val : jQuery( win ).scrollLeft(),
+ top ? val : jQuery( win ).scrollTop()
+ );
+
+ } else {
+ elem[ method ] = val;
+ }
+ }, method, val, arguments.length, null );
+ };
+});
+
+// Add the top/left cssHooks using jQuery.fn.position
+// Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084
+// getComputedStyle returns percent when specified for top/left/bottom/right
+// rather than make the css module depend on the offset module, we just check for it here
+jQuery.each( [ "top", "left" ], function( i, prop ) {
+ jQuery.cssHooks[ prop ] = addGetHookIf( support.pixelPosition,
+ function( elem, computed ) {
+ if ( computed ) {
+ computed = curCSS( elem, prop );
+ // if curCSS returns percentage, fallback to offset
+ return rnumnonpx.test( computed ) ?
+ jQuery( elem ).position()[ prop ] + "px" :
+ computed;
+ }
+ }
+ );
+});
+
+
+// Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods
+jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
+ jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) {
+ // margin is only for outerHeight, outerWidth
+ jQuery.fn[ funcName ] = function( margin, value ) {
+ var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ),
+ extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" );
+
+ return access( this, function( elem, type, value ) {
+ var doc;
+
+ if ( jQuery.isWindow( elem ) ) {
+ // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there
+ // isn't a whole lot we can do. See pull request at this URL for discussion:
+ // https://github.com/jquery/jquery/pull/764
+ return elem.document.documentElement[ "client" + name ];
+ }
+
+ // Get document width or height
+ if ( elem.nodeType === 9 ) {
+ doc = elem.documentElement;
+
+ // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest
+ // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it.
+ return Math.max(
+ elem.body[ "scroll" + name ], doc[ "scroll" + name ],
+ elem.body[ "offset" + name ], doc[ "offset" + name ],
+ doc[ "client" + name ]
+ );
+ }
+
+ return value === undefined ?
+ // Get width or height on the element, requesting but not forcing parseFloat
+ jQuery.css( elem, type, extra ) :
+
+ // Set width or height on the element
+ jQuery.style( elem, type, value, extra );
+ }, type, chainable ? margin : undefined, chainable, null );
+ };
+ });
+});
+
+
+// The number of elements contained in the matched element set
+jQuery.fn.size = function() {
+ return this.length;
+};
+
+jQuery.fn.andSelf = jQuery.fn.addBack;
+
+
+
+
+// Register as a named AMD module, since jQuery can be concatenated with other
+// files that may use define, but not via a proper concatenation script that
+// understands anonymous AMD modules. A named AMD is safest and most robust
+// way to register. Lowercase jquery is used because AMD module names are
+// derived from file names, and jQuery is normally delivered in a lowercase
+// file name. Do this after creating the global so that if an AMD module wants
+// to call noConflict to hide this version of jQuery, it will work.
+
+// Note that for maximum portability, libraries that are not jQuery should
+// declare themselves as anonymous modules, and avoid setting a global if an
+// AMD loader is present. jQuery is a special case. For more information, see
+// https://github.com/jrburke/requirejs/wiki/Updating-existing-libraries#wiki-anon
+
+if ( typeof define === "function" && define.amd ) {
+ define( "jquery", [], function() {
+ return jQuery;
+ });
+}
+
+
+
+
+var
+ // Map over jQuery in case of overwrite
+ _jQuery = window.jQuery,
+
+ // Map over the $ in case of overwrite
+ _$ = window.$;
+
+jQuery.noConflict = function( deep ) {
+ if ( window.$ === jQuery ) {
+ window.$ = _$;
+ }
+
+ if ( deep && window.jQuery === jQuery ) {
+ window.jQuery = _jQuery;
+ }
+
+ return jQuery;
+};
+
+// Expose jQuery and $ identifiers, even in
+// AMD (#7102#comment:10, https://github.com/jquery/jquery/pull/557)
+// and CommonJS for browser emulators (#13566)
+if ( typeof noGlobal === strundefined ) {
+ window.jQuery = window.$ = jQuery;
+}
+
+
+
+
+return jQuery;
+
+}));
diff --git a/doc/build/_static/jquery.js b/doc/build/_static/jquery.js
new file mode 100644
index 0000000..ab28a24
--- /dev/null
+++ b/doc/build/_static/jquery.js
@@ -0,0 +1,4 @@
+/*! jQuery v1.11.1 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
+!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k={},l="1.11.1",m=function(a,b){return new m.fn.init(a,b)},n=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,o=/^-ms-/,p=/-([\da-z])/gi,q=function(a,b [...]
+if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||m.guid++:h),j[k]||(j[k]=i?{}:{toJSON:m.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=m.extend(j[k],b):j[k].data=m.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[m.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[m.camelCase(b)])):f=g,f}}function R(a,b,c){if(m.acceptData(a)){var d,e,f=a.nodeType,g=f?m.cache:a,h=f?a[m.expando]:m.expando;if(g[h]){if(b&& [...]
+},cur:function(){var a=Zb.propHooks[this.prop];return a&&a.get?a.get(this):Zb.propHooks._default.get(this)},run:function(a){var b,c=Zb.propHooks[this.prop];return this.pos=b=this.options.duration?m.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):Zb.propHooks._default.set(this),this}},Zb.prototype.init.prototype=Zb.prototype,Zb.prop [...]
diff --git a/doc/build/_static/minus.png b/doc/build/_static/minus.png
new file mode 100644
index 0000000..0f22b16
Binary files /dev/null and b/doc/build/_static/minus.png differ
diff --git a/doc/build/_static/plus.png b/doc/build/_static/plus.png
new file mode 100644
index 0000000..0cfe084
Binary files /dev/null and b/doc/build/_static/plus.png differ
diff --git a/doc/build/_static/pygments.css b/doc/build/_static/pygments.css
new file mode 100644
index 0000000..8213e90
--- /dev/null
+++ b/doc/build/_static/pygments.css
@@ -0,0 +1,65 @@
+.highlight .hll { background-color: #ffffcc }
+.highlight { background: #eeffcc; }
+.highlight .c { color: #408090; font-style: italic } /* Comment */
+.highlight .err { border: 1px solid #FF0000 } /* Error */
+.highlight .k { color: #007020; font-weight: bold } /* Keyword */
+.highlight .o { color: #666666 } /* Operator */
+.highlight .ch { color: #408090; font-style: italic } /* Comment.Hashbang */
+.highlight .cm { color: #408090; font-style: italic } /* Comment.Multiline */
+.highlight .cp { color: #007020 } /* Comment.Preproc */
+.highlight .cpf { color: #408090; font-style: italic } /* Comment.PreprocFile */
+.highlight .c1 { color: #408090; font-style: italic } /* Comment.Single */
+.highlight .cs { color: #408090; background-color: #fff0f0 } /* Comment.Special */
+.highlight .gd { color: #A00000 } /* Generic.Deleted */
+.highlight .ge { font-style: italic } /* Generic.Emph */
+.highlight .gr { color: #FF0000 } /* Generic.Error */
+.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */
+.highlight .gi { color: #00A000 } /* Generic.Inserted */
+.highlight .go { color: #333333 } /* Generic.Output */
+.highlight .gp { color: #c65d09; font-weight: bold } /* Generic.Prompt */
+.highlight .gs { font-weight: bold } /* Generic.Strong */
+.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */
+.highlight .gt { color: #0044DD } /* Generic.Traceback */
+.highlight .kc { color: #007020; font-weight: bold } /* Keyword.Constant */
+.highlight .kd { color: #007020; font-weight: bold } /* Keyword.Declaration */
+.highlight .kn { color: #007020; font-weight: bold } /* Keyword.Namespace */
+.highlight .kp { color: #007020 } /* Keyword.Pseudo */
+.highlight .kr { color: #007020; font-weight: bold } /* Keyword.Reserved */
+.highlight .kt { color: #902000 } /* Keyword.Type */
+.highlight .m { color: #208050 } /* Literal.Number */
+.highlight .s { color: #4070a0 } /* Literal.String */
+.highlight .na { color: #4070a0 } /* Name.Attribute */
+.highlight .nb { color: #007020 } /* Name.Builtin */
+.highlight .nc { color: #0e84b5; font-weight: bold } /* Name.Class */
+.highlight .no { color: #60add5 } /* Name.Constant */
+.highlight .nd { color: #555555; font-weight: bold } /* Name.Decorator */
+.highlight .ni { color: #d55537; font-weight: bold } /* Name.Entity */
+.highlight .ne { color: #007020 } /* Name.Exception */
+.highlight .nf { color: #06287e } /* Name.Function */
+.highlight .nl { color: #002070; font-weight: bold } /* Name.Label */
+.highlight .nn { color: #0e84b5; font-weight: bold } /* Name.Namespace */
+.highlight .nt { color: #062873; font-weight: bold } /* Name.Tag */
+.highlight .nv { color: #bb60d5 } /* Name.Variable */
+.highlight .ow { color: #007020; font-weight: bold } /* Operator.Word */
+.highlight .w { color: #bbbbbb } /* Text.Whitespace */
+.highlight .mb { color: #208050 } /* Literal.Number.Bin */
+.highlight .mf { color: #208050 } /* Literal.Number.Float */
+.highlight .mh { color: #208050 } /* Literal.Number.Hex */
+.highlight .mi { color: #208050 } /* Literal.Number.Integer */
+.highlight .mo { color: #208050 } /* Literal.Number.Oct */
+.highlight .sb { color: #4070a0 } /* Literal.String.Backtick */
+.highlight .sc { color: #4070a0 } /* Literal.String.Char */
+.highlight .sd { color: #4070a0; font-style: italic } /* Literal.String.Doc */
+.highlight .s2 { color: #4070a0 } /* Literal.String.Double */
+.highlight .se { color: #4070a0; font-weight: bold } /* Literal.String.Escape */
+.highlight .sh { color: #4070a0 } /* Literal.String.Heredoc */
+.highlight .si { color: #70a0d0; font-style: italic } /* Literal.String.Interpol */
+.highlight .sx { color: #c65d09 } /* Literal.String.Other */
+.highlight .sr { color: #235388 } /* Literal.String.Regex */
+.highlight .s1 { color: #4070a0 } /* Literal.String.Single */
+.highlight .ss { color: #517918 } /* Literal.String.Symbol */
+.highlight .bp { color: #007020 } /* Name.Builtin.Pseudo */
+.highlight .vc { color: #bb60d5 } /* Name.Variable.Class */
+.highlight .vg { color: #bb60d5 } /* Name.Variable.Global */
+.highlight .vi { color: #bb60d5 } /* Name.Variable.Instance */
+.highlight .il { color: #208050 } /* Literal.Number.Integer.Long */
\ No newline at end of file
diff --git a/doc/build/_static/searchtools.js b/doc/build/_static/searchtools.js
new file mode 100644
index 0000000..066857c
--- /dev/null
+++ b/doc/build/_static/searchtools.js
@@ -0,0 +1,651 @@
+/*
+ * searchtools.js_t
+ * ~~~~~~~~~~~~~~~~
+ *
+ * Sphinx JavaScript utilities for the full-text search.
+ *
+ * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ * :license: BSD, see LICENSE for details.
+ *
+ */
+
+
+/* Non-minified version JS is _stemmer.js if file is provided */
+/**
+ * Porter Stemmer
+ */
+var Stemmer = function() {
+
+ var step2list = {
+ ational: 'ate',
+ tional: 'tion',
+ enci: 'ence',
+ anci: 'ance',
+ izer: 'ize',
+ bli: 'ble',
+ alli: 'al',
+ entli: 'ent',
+ eli: 'e',
+ ousli: 'ous',
+ ization: 'ize',
+ ation: 'ate',
+ ator: 'ate',
+ alism: 'al',
+ iveness: 'ive',
+ fulness: 'ful',
+ ousness: 'ous',
+ aliti: 'al',
+ iviti: 'ive',
+ biliti: 'ble',
+ logi: 'log'
+ };
+
+ var step3list = {
+ icate: 'ic',
+ ative: '',
+ alize: 'al',
+ iciti: 'ic',
+ ical: 'ic',
+ ful: '',
+ ness: ''
+ };
+
+ var c = "[^aeiou]"; // consonant
+ var v = "[aeiouy]"; // vowel
+ var C = c + "[^aeiouy]*"; // consonant sequence
+ var V = v + "[aeiou]*"; // vowel sequence
+
+ var mgr0 = "^(" + C + ")?" + V + C; // [C]VC... is m>0
+ var meq1 = "^(" + C + ")?" + V + C + "(" + V + ")?$"; // [C]VC[V] is m=1
+ var mgr1 = "^(" + C + ")?" + V + C + V + C; // [C]VCVC... is m>1
+ var s_v = "^(" + C + ")?" + v; // vowel in stem
+
+ this.stemWord = function (w) {
+ var stem;
+ var suffix;
+ var firstch;
+ var origword = w;
+
+ if (w.length < 3)
+ return w;
+
+ var re;
+ var re2;
+ var re3;
+ var re4;
+
+ firstch = w.substr(0,1);
+ if (firstch == "y")
+ w = firstch.toUpperCase() + w.substr(1);
+
+ // Step 1a
+ re = /^(.+?)(ss|i)es$/;
+ re2 = /^(.+?)([^s])s$/;
+
+ if (re.test(w))
+ w = w.replace(re,"$1$2");
+ else if (re2.test(w))
+ w = w.replace(re2,"$1$2");
+
+ // Step 1b
+ re = /^(.+?)eed$/;
+ re2 = /^(.+?)(ed|ing)$/;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ re = new RegExp(mgr0);
+ if (re.test(fp[1])) {
+ re = /.$/;
+ w = w.replace(re,"");
+ }
+ }
+ else if (re2.test(w)) {
+ var fp = re2.exec(w);
+ stem = fp[1];
+ re2 = new RegExp(s_v);
+ if (re2.test(stem)) {
+ w = stem;
+ re2 = /(at|bl|iz)$/;
+ re3 = new RegExp("([^aeiouylsz])\\1$");
+ re4 = new RegExp("^" + C + v + "[^aeiouwxy]$");
+ if (re2.test(w))
+ w = w + "e";
+ else if (re3.test(w)) {
+ re = /.$/;
+ w = w.replace(re,"");
+ }
+ else if (re4.test(w))
+ w = w + "e";
+ }
+ }
+
+ // Step 1c
+ re = /^(.+?)y$/;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ re = new RegExp(s_v);
+ if (re.test(stem))
+ w = stem + "i";
+ }
+
+ // Step 2
+ re = /^(.+?)(ational|tional|enci|anci|izer|bli|alli|entli|eli|ousli|ization|ation|ator|alism|iveness|fulness|ousness|aliti|iviti|biliti|logi)$/;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ suffix = fp[2];
+ re = new RegExp(mgr0);
+ if (re.test(stem))
+ w = stem + step2list[suffix];
+ }
+
+ // Step 3
+ re = /^(.+?)(icate|ative|alize|iciti|ical|ful|ness)$/;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ suffix = fp[2];
+ re = new RegExp(mgr0);
+ if (re.test(stem))
+ w = stem + step3list[suffix];
+ }
+
+ // Step 4
+ re = /^(.+?)(al|ance|ence|er|ic|able|ible|ant|ement|ment|ent|ou|ism|ate|iti|ous|ive|ize)$/;
+ re2 = /^(.+?)(s|t)(ion)$/;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ re = new RegExp(mgr1);
+ if (re.test(stem))
+ w = stem;
+ }
+ else if (re2.test(w)) {
+ var fp = re2.exec(w);
+ stem = fp[1] + fp[2];
+ re2 = new RegExp(mgr1);
+ if (re2.test(stem))
+ w = stem;
+ }
+
+ // Step 5
+ re = /^(.+?)e$/;
+ if (re.test(w)) {
+ var fp = re.exec(w);
+ stem = fp[1];
+ re = new RegExp(mgr1);
+ re2 = new RegExp(meq1);
+ re3 = new RegExp("^" + C + v + "[^aeiouwxy]$");
+ if (re.test(stem) || (re2.test(stem) && !(re3.test(stem))))
+ w = stem;
+ }
+ re = /ll$/;
+ re2 = new RegExp(mgr1);
+ if (re.test(w) && re2.test(w)) {
+ re = /.$/;
+ w = w.replace(re,"");
+ }
+
+ // and turn initial Y back to y
+ if (firstch == "y")
+ w = firstch.toLowerCase() + w.substr(1);
+ return w;
+ }
+}
+
+
+
+/**
+ * Simple result scoring code.
+ */
+var Scorer = {
+ // Implement the following function to further tweak the score for each result
+ // The function takes a result array [filename, title, anchor, descr, score]
+ // and returns the new score.
+ /*
+ score: function(result) {
+ return result[4];
+ },
+ */
+
+ // query matches the full name of an object
+ objNameMatch: 11,
+ // or matches in the last dotted part of the object name
+ objPartialMatch: 6,
+ // Additive scores depending on the priority of the object
+ objPrio: {0: 15, // used to be importantResults
+ 1: 5, // used to be objectResults
+ 2: -5}, // used to be unimportantResults
+ // Used when the priority is not in the mapping.
+ objPrioDefault: 0,
+
+ // query found in title
+ title: 15,
+ // query found in terms
+ term: 5
+};
+
+
+/**
+ * Search Module
+ */
+var Search = {
+
+ _index : null,
+ _queued_query : null,
+ _pulse_status : -1,
+
+ init : function() {
+ var params = $.getQueryParameters();
+ if (params.q) {
+ var query = params.q[0];
+ $('input[name="q"]')[0].value = query;
+ this.performSearch(query);
+ }
+ },
+
+ loadIndex : function(url) {
+ $.ajax({type: "GET", url: url, data: null,
+ dataType: "script", cache: true,
+ complete: function(jqxhr, textstatus) {
+ if (textstatus != "success") {
+ document.getElementById("searchindexloader").src = url;
+ }
+ }});
+ },
+
+ setIndex : function(index) {
+ var q;
+ this._index = index;
+ if ((q = this._queued_query) !== null) {
+ this._queued_query = null;
+ Search.query(q);
+ }
+ },
+
+ hasIndex : function() {
+ return this._index !== null;
+ },
+
+ deferQuery : function(query) {
+ this._queued_query = query;
+ },
+
+ stopPulse : function() {
+ this._pulse_status = 0;
+ },
+
+ startPulse : function() {
+ if (this._pulse_status >= 0)
+ return;
+ function pulse() {
+ var i;
+ Search._pulse_status = (Search._pulse_status + 1) % 4;
+ var dotString = '';
+ for (i = 0; i < Search._pulse_status; i++)
+ dotString += '.';
+ Search.dots.text(dotString);
+ if (Search._pulse_status > -1)
+ window.setTimeout(pulse, 500);
+ }
+ pulse();
+ },
+
+ /**
+ * perform a search for something (or wait until index is loaded)
+ */
+ performSearch : function(query) {
+ // create the required interface elements
+ this.out = $('#search-results');
+ this.title = $('<h2>' + _('Searching') + '</h2>').appendTo(this.out);
+ this.dots = $('<span></span>').appendTo(this.title);
+ this.status = $('<p style="display: none"></p>').appendTo(this.out);
+ this.output = $('<ul class="search"/>').appendTo(this.out);
+
+ $('#search-progress').text(_('Preparing search...'));
+ this.startPulse();
+
+ // index already loaded, the browser was quick!
+ if (this.hasIndex())
+ this.query(query);
+ else
+ this.deferQuery(query);
+ },
+
+ /**
+ * execute search (requires search index to be loaded)
+ */
+ query : function(query) {
+ var i;
+ var stopwords = ["a","and","are","as","at","be","but","by","for","if","in","into","is","it","near","no","not","of","on","or","such","that","the","their","then","there","these","they","this","to","was","will","with"];
+
+ // stem the searchterms and add them to the correct list
+ var stemmer = new Stemmer();
+ var searchterms = [];
+ var excluded = [];
+ var hlterms = [];
+ var tmp = query.split(/\s+/);
+ var objectterms = [];
+ for (i = 0; i < tmp.length; i++) {
+ if (tmp[i] !== "") {
+ objectterms.push(tmp[i].toLowerCase());
+ }
+
+ if ($u.indexOf(stopwords, tmp[i].toLowerCase()) != -1 || tmp[i].match(/^\d+$/) ||
+ tmp[i] === "") {
+ // skip this "word"
+ continue;
+ }
+ // stem the word
+ var word = stemmer.stemWord(tmp[i].toLowerCase());
+ var toAppend;
+ // select the correct list
+ if (word[0] == '-') {
+ toAppend = excluded;
+ word = word.substr(1);
+ }
+ else {
+ toAppend = searchterms;
+ hlterms.push(tmp[i].toLowerCase());
+ }
+ // only add if not already in the list
+ if (!$u.contains(toAppend, word))
+ toAppend.push(word);
+ }
+ var highlightstring = '?highlight=' + $.urlencode(hlterms.join(" "));
+
+ // console.debug('SEARCH: searching for:');
+ // console.info('required: ', searchterms);
+ // console.info('excluded: ', excluded);
+
+ // prepare search
+ var terms = this._index.terms;
+ var titleterms = this._index.titleterms;
+
+ // array of [filename, title, anchor, descr, score]
+ var results = [];
+ $('#search-progress').empty();
+
+ // lookup as object
+ for (i = 0; i < objectterms.length; i++) {
+ var others = [].concat(objectterms.slice(0, i),
+ objectterms.slice(i+1, objectterms.length));
+ results = results.concat(this.performObjectSearch(objectterms[i], others));
+ }
+
+ // lookup as search terms in fulltext
+ results = results.concat(this.performTermsSearch(searchterms, excluded, terms, titleterms));
+
+ // let the scorer override scores with a custom scoring function
+ if (Scorer.score) {
+ for (i = 0; i < results.length; i++)
+ results[i][4] = Scorer.score(results[i]);
+ }
+
+ // now sort the results by score (in opposite order of appearance, since the
+ // display function below uses pop() to retrieve items) and then
+ // alphabetically
+ results.sort(function(a, b) {
+ var left = a[4];
+ var right = b[4];
+ if (left > right) {
+ return 1;
+ } else if (left < right) {
+ return -1;
+ } else {
+ // same score: sort alphabetically
+ left = a[1].toLowerCase();
+ right = b[1].toLowerCase();
+ return (left > right) ? -1 : ((left < right) ? 1 : 0);
+ }
+ });
+
+ // for debugging
+ //Search.lastresults = results.slice(); // a copy
+ //console.info('search results:', Search.lastresults);
+
+ // print the results
+ var resultCount = results.length;
+ function displayNextItem() {
+ // results left, load the summary and display it
+ if (results.length) {
+ var item = results.pop();
+ var listItem = $('<li style="display:none"></li>');
+ if (DOCUMENTATION_OPTIONS.FILE_SUFFIX === '') {
+ // dirhtml builder
+ var dirname = item[0] + '/';
+ if (dirname.match(/\/index\/$/)) {
+ dirname = dirname.substring(0, dirname.length-6);
+ } else if (dirname == 'index/') {
+ dirname = '';
+ }
+ listItem.append($('<a/>').attr('href',
+ DOCUMENTATION_OPTIONS.URL_ROOT + dirname +
+ highlightstring + item[2]).html(item[1]));
+ } else {
+ // normal html builders
+ listItem.append($('<a/>').attr('href',
+ item[0] + DOCUMENTATION_OPTIONS.FILE_SUFFIX +
+ highlightstring + item[2]).html(item[1]));
+ }
+ if (item[3]) {
+ listItem.append($('<span> (' + item[3] + ')</span>'));
+ Search.output.append(listItem);
+ listItem.slideDown(5, function() {
+ displayNextItem();
+ });
+ } else if (DOCUMENTATION_OPTIONS.HAS_SOURCE) {
+ $.ajax({url: DOCUMENTATION_OPTIONS.URL_ROOT + '_sources/' + item[0] + '.txt',
+ dataType: "text",
+ complete: function(jqxhr, textstatus) {
+ var data = jqxhr.responseText;
+ if (data !== '' && data !== undefined) {
+ listItem.append(Search.makeSearchSummary(data, searchterms, hlterms));
+ }
+ Search.output.append(listItem);
+ listItem.slideDown(5, function() {
+ displayNextItem();
+ });
+ }});
+ } else {
+ // no source available, just display title
+ Search.output.append(listItem);
+ listItem.slideDown(5, function() {
+ displayNextItem();
+ });
+ }
+ }
+ // search finished, update title and status message
+ else {
+ Search.stopPulse();
+ Search.title.text(_('Search Results'));
+ if (!resultCount)
+ Search.status.text(_('Your search did not match any documents. Please make sure that all words are spelled correctly and that you\'ve selected enough categories.'));
+ else
+ Search.status.text(_('Search finished, found %s page(s) matching the search query.').replace('%s', resultCount));
+ Search.status.fadeIn(500);
+ }
+ }
+ displayNextItem();
+ },
+
+ /**
+ * search for object names
+ */
+ performObjectSearch : function(object, otherterms) {
+ var filenames = this._index.filenames;
+ var objects = this._index.objects;
+ var objnames = this._index.objnames;
+ var titles = this._index.titles;
+
+ var i;
+ var results = [];
+
+ for (var prefix in objects) {
+ for (var name in objects[prefix]) {
+ var fullname = (prefix ? prefix + '.' : '') + name;
+ if (fullname.toLowerCase().indexOf(object) > -1) {
+ var score = 0;
+ var parts = fullname.split('.');
+ // check for different match types: exact matches of full name or
+ // "last name" (i.e. last dotted part)
+ if (fullname == object || parts[parts.length - 1] == object) {
+ score += Scorer.objNameMatch;
+ // matches in last name
+ } else if (parts[parts.length - 1].indexOf(object) > -1) {
+ score += Scorer.objPartialMatch;
+ }
+ var match = objects[prefix][name];
+ var objname = objnames[match[1]][2];
+ var title = titles[match[0]];
+ // If more than one term searched for, we require other words to be
+ // found in the name/title/description
+ if (otherterms.length > 0) {
+ var haystack = (prefix + ' ' + name + ' ' +
+ objname + ' ' + title).toLowerCase();
+ var allfound = true;
+ for (i = 0; i < otherterms.length; i++) {
+ if (haystack.indexOf(otherterms[i]) == -1) {
+ allfound = false;
+ break;
+ }
+ }
+ if (!allfound) {
+ continue;
+ }
+ }
+ var descr = objname + _(', in ') + title;
+
+ var anchor = match[3];
+ if (anchor === '')
+ anchor = fullname;
+ else if (anchor == '-')
+ anchor = objnames[match[1]][1] + '-' + fullname;
+ // add custom score for some objects according to scorer
+ if (Scorer.objPrio.hasOwnProperty(match[2])) {
+ score += Scorer.objPrio[match[2]];
+ } else {
+ score += Scorer.objPrioDefault;
+ }
+ results.push([filenames[match[0]], fullname, '#'+anchor, descr, score]);
+ }
+ }
+ }
+
+ return results;
+ },
+
+ /**
+ * search for full-text terms in the index
+ */
+ performTermsSearch : function(searchterms, excluded, terms, titleterms) {
+ var filenames = this._index.filenames;
+ var titles = this._index.titles;
+
+ var i, j, file;
+ var fileMap = {};
+ var scoreMap = {};
+ var results = [];
+
+ // perform the search on the required terms
+ for (i = 0; i < searchterms.length; i++) {
+ var word = searchterms[i];
+ var files = [];
+ var _o = [
+ {files: terms[word], score: Scorer.term},
+ {files: titleterms[word], score: Scorer.title}
+ ];
+
+ // no match but word was a required one
+ if ($u.every(_o, function(o){return o.files === undefined;})) {
+ break;
+ }
+ // found search word in contents
+ $u.each(_o, function(o) {
+ var _files = o.files;
+ if (_files === undefined)
+ return
+
+ if (_files.length === undefined)
+ _files = [_files];
+ files = files.concat(_files);
+
+ // set score for the word in each file to Scorer.term
+ for (j = 0; j < _files.length; j++) {
+ file = _files[j];
+ if (!(file in scoreMap))
+ scoreMap[file] = {}
+ scoreMap[file][word] = o.score;
+ }
+ });
+
+ // create the mapping
+ for (j = 0; j < files.length; j++) {
+ file = files[j];
+ if (file in fileMap)
+ fileMap[file].push(word);
+ else
+ fileMap[file] = [word];
+ }
+ }
+
+ // now check if the files don't contain excluded terms
+ for (file in fileMap) {
+ var valid = true;
+
+ // check if all requirements are matched
+ if (fileMap[file].length != searchterms.length)
+ continue;
+
+ // ensure that none of the excluded terms is in the search result
+ for (i = 0; i < excluded.length; i++) {
+ if (terms[excluded[i]] == file ||
+ titleterms[excluded[i]] == file ||
+ $u.contains(terms[excluded[i]] || [], file) ||
+ $u.contains(titleterms[excluded[i]] || [], file)) {
+ valid = false;
+ break;
+ }
+ }
+
+ // if we have still a valid result we can add it to the result list
+ if (valid) {
+ // select one (max) score for the file.
+ // for better ranking, we should calculate ranking by using words statistics like basic tf-idf...
+ var score = $u.max($u.map(fileMap[file], function(w){return scoreMap[file][w]}));
+ results.push([filenames[file], titles[file], '', null, score]);
+ }
+ }
+ return results;
+ },
+
+ /**
+ * helper function to return a node containing the
+ * search summary for a given text. keywords is a list
+ * of stemmed words, hlwords is the list of normal, unstemmed
+ * words. the first one is used to find the occurrence, the
+ * latter for highlighting it.
+ */
+ makeSearchSummary : function(text, keywords, hlwords) {
+ var textLower = text.toLowerCase();
+ var start = 0;
+ $.each(keywords, function() {
+ var i = textLower.indexOf(this.toLowerCase());
+ if (i > -1)
+ start = i;
+ });
+ start = Math.max(start - 120, 0);
+ var excerpt = ((start > 0) ? '...' : '') +
+ $.trim(text.substr(start, 240)) +
+ ((start + 240 - text.length) ? '...' : '');
+ var rv = $('<div class="context"></div>').text(excerpt);
+ $.each(hlwords, function() {
+ rv = rv.highlightText(this, 'highlighted');
+ });
+ return rv;
+ }
+};
+
+$(document).ready(function() {
+ Search.init();
+});
\ No newline at end of file
diff --git a/doc/build/_static/underscore-1.3.1.js b/doc/build/_static/underscore-1.3.1.js
new file mode 100644
index 0000000..208d4cd
--- /dev/null
+++ b/doc/build/_static/underscore-1.3.1.js
@@ -0,0 +1,999 @@
+// Underscore.js 1.3.1
+// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
+// Underscore is freely distributable under the MIT license.
+// Portions of Underscore are inspired or borrowed from Prototype,
+// Oliver Steele's Functional, and John Resig's Micro-Templating.
+// For all details and documentation:
+// http://documentcloud.github.com/underscore
+
+(function() {
+
+ // Baseline setup
+ // --------------
+
+ // Establish the root object, `window` in the browser, or `global` on the server.
+ var root = this;
+
+ // Save the previous value of the `_` variable.
+ var previousUnderscore = root._;
+
+ // Establish the object that gets returned to break out of a loop iteration.
+ var breaker = {};
+
+ // Save bytes in the minified (but not gzipped) version:
+ var ArrayProto = Array.prototype, ObjProto = Object.prototype, FuncProto = Function.prototype;
+
+ // Create quick reference variables for speed access to core prototypes.
+ var slice = ArrayProto.slice,
+ unshift = ArrayProto.unshift,
+ toString = ObjProto.toString,
+ hasOwnProperty = ObjProto.hasOwnProperty;
+
+ // All **ECMAScript 5** native function implementations that we hope to use
+ // are declared here.
+ var
+ nativeForEach = ArrayProto.forEach,
+ nativeMap = ArrayProto.map,
+ nativeReduce = ArrayProto.reduce,
+ nativeReduceRight = ArrayProto.reduceRight,
+ nativeFilter = ArrayProto.filter,
+ nativeEvery = ArrayProto.every,
+ nativeSome = ArrayProto.some,
+ nativeIndexOf = ArrayProto.indexOf,
+ nativeLastIndexOf = ArrayProto.lastIndexOf,
+ nativeIsArray = Array.isArray,
+ nativeKeys = Object.keys,
+ nativeBind = FuncProto.bind;
+
+ // Create a safe reference to the Underscore object for use below.
+ var _ = function(obj) { return new wrapper(obj); };
+
+ // Export the Underscore object for **Node.js**, with
+ // backwards-compatibility for the old `require()` API. If we're in
+ // the browser, add `_` as a global object via a string identifier,
+ // for Closure Compiler "advanced" mode.
+ if (typeof exports !== 'undefined') {
+ if (typeof module !== 'undefined' && module.exports) {
+ exports = module.exports = _;
+ }
+ exports._ = _;
+ } else {
+ root['_'] = _;
+ }
+
+ // Current version.
+ _.VERSION = '1.3.1';
+
+ // Collection Functions
+ // --------------------
+
+ // The cornerstone, an `each` implementation, aka `forEach`.
+ // Handles objects with the built-in `forEach`, arrays, and raw objects.
+ // Delegates to **ECMAScript 5**'s native `forEach` if available.
+ var each = _.each = _.forEach = function(obj, iterator, context) {
+ if (obj == null) return;
+ if (nativeForEach && obj.forEach === nativeForEach) {
+ obj.forEach(iterator, context);
+ } else if (obj.length === +obj.length) {
+ for (var i = 0, l = obj.length; i < l; i++) {
+ if (i in obj && iterator.call(context, obj[i], i, obj) === breaker) return;
+ }
+ } else {
+ for (var key in obj) {
+ if (_.has(obj, key)) {
+ if (iterator.call(context, obj[key], key, obj) === breaker) return;
+ }
+ }
+ }
+ };
+
+ // Return the results of applying the iterator to each element.
+ // Delegates to **ECMAScript 5**'s native `map` if available.
+ _.map = _.collect = function(obj, iterator, context) {
+ var results = [];
+ if (obj == null) return results;
+ if (nativeMap && obj.map === nativeMap) return obj.map(iterator, context);
+ each(obj, function(value, index, list) {
+ results[results.length] = iterator.call(context, value, index, list);
+ });
+ if (obj.length === +obj.length) results.length = obj.length;
+ return results;
+ };
+
+ // **Reduce** builds up a single result from a list of values, aka `inject`,
+ // or `foldl`. Delegates to **ECMAScript 5**'s native `reduce` if available.
+ _.reduce = _.foldl = _.inject = function(obj, iterator, memo, context) {
+ var initial = arguments.length > 2;
+ if (obj == null) obj = [];
+ if (nativeReduce && obj.reduce === nativeReduce) {
+ if (context) iterator = _.bind(iterator, context);
+ return initial ? obj.reduce(iterator, memo) : obj.reduce(iterator);
+ }
+ each(obj, function(value, index, list) {
+ if (!initial) {
+ memo = value;
+ initial = true;
+ } else {
+ memo = iterator.call(context, memo, value, index, list);
+ }
+ });
+ if (!initial) throw new TypeError('Reduce of empty array with no initial value');
+ return memo;
+ };
+
+ // The right-associative version of reduce, also known as `foldr`.
+ // Delegates to **ECMAScript 5**'s native `reduceRight` if available.
+ _.reduceRight = _.foldr = function(obj, iterator, memo, context) {
+ var initial = arguments.length > 2;
+ if (obj == null) obj = [];
+ if (nativeReduceRight && obj.reduceRight === nativeReduceRight) {
+ if (context) iterator = _.bind(iterator, context);
+ return initial ? obj.reduceRight(iterator, memo) : obj.reduceRight(iterator);
+ }
+ var reversed = _.toArray(obj).reverse();
+ if (context && !initial) iterator = _.bind(iterator, context);
+ return initial ? _.reduce(reversed, iterator, memo, context) : _.reduce(reversed, iterator);
+ };
+
+ // Return the first value which passes a truth test. Aliased as `detect`.
+ _.find = _.detect = function(obj, iterator, context) {
+ var result;
+ any(obj, function(value, index, list) {
+ if (iterator.call(context, value, index, list)) {
+ result = value;
+ return true;
+ }
+ });
+ return result;
+ };
+
+ // Return all the elements that pass a truth test.
+ // Delegates to **ECMAScript 5**'s native `filter` if available.
+ // Aliased as `select`.
+ _.filter = _.select = function(obj, iterator, context) {
+ var results = [];
+ if (obj == null) return results;
+ if (nativeFilter && obj.filter === nativeFilter) return obj.filter(iterator, context);
+ each(obj, function(value, index, list) {
+ if (iterator.call(context, value, index, list)) results[results.length] = value;
+ });
+ return results;
+ };
+
+ // Return all the elements for which a truth test fails.
+ _.reject = function(obj, iterator, context) {
+ var results = [];
+ if (obj == null) return results;
+ each(obj, function(value, index, list) {
+ if (!iterator.call(context, value, index, list)) results[results.length] = value;
+ });
+ return results;
+ };
+
+ // Determine whether all of the elements match a truth test.
+ // Delegates to **ECMAScript 5**'s native `every` if available.
+ // Aliased as `all`.
+ _.every = _.all = function(obj, iterator, context) {
+ var result = true;
+ if (obj == null) return result;
+ if (nativeEvery && obj.every === nativeEvery) return obj.every(iterator, context);
+ each(obj, function(value, index, list) {
+ if (!(result = result && iterator.call(context, value, index, list))) return breaker;
+ });
+ return result;
+ };
+
+ // Determine if at least one element in the object matches a truth test.
+ // Delegates to **ECMAScript 5**'s native `some` if available.
+ // Aliased as `any`.
+ var any = _.some = _.any = function(obj, iterator, context) {
+ iterator || (iterator = _.identity);
+ var result = false;
+ if (obj == null) return result;
+ if (nativeSome && obj.some === nativeSome) return obj.some(iterator, context);
+ each(obj, function(value, index, list) {
+ if (result || (result = iterator.call(context, value, index, list))) return breaker;
+ });
+ return !!result;
+ };
+
+ // Determine if a given value is included in the array or object using `===`.
+ // Aliased as `contains`.
+ _.include = _.contains = function(obj, target) {
+ var found = false;
+ if (obj == null) return found;
+ if (nativeIndexOf && obj.indexOf === nativeIndexOf) return obj.indexOf(target) != -1;
+ found = any(obj, function(value) {
+ return value === target;
+ });
+ return found;
+ };
+
+ // Invoke a method (with arguments) on every item in a collection.
+ _.invoke = function(obj, method) {
+ var args = slice.call(arguments, 2);
+ return _.map(obj, function(value) {
+ return (_.isFunction(method) ? method || value : value[method]).apply(value, args);
+ });
+ };
+
+ // Convenience version of a common use case of `map`: fetching a property.
+ _.pluck = function(obj, key) {
+ return _.map(obj, function(value){ return value[key]; });
+ };
+
+ // Return the maximum element or (element-based computation).
+ _.max = function(obj, iterator, context) {
+ if (!iterator && _.isArray(obj)) return Math.max.apply(Math, obj);
+ if (!iterator && _.isEmpty(obj)) return -Infinity;
+ var result = {computed : -Infinity};
+ each(obj, function(value, index, list) {
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
+ computed >= result.computed && (result = {value : value, computed : computed});
+ });
+ return result.value;
+ };
+
+ // Return the minimum element (or element-based computation).
+ _.min = function(obj, iterator, context) {
+ if (!iterator && _.isArray(obj)) return Math.min.apply(Math, obj);
+ if (!iterator && _.isEmpty(obj)) return Infinity;
+ var result = {computed : Infinity};
+ each(obj, function(value, index, list) {
+ var computed = iterator ? iterator.call(context, value, index, list) : value;
+ computed < result.computed && (result = {value : value, computed : computed});
+ });
+ return result.value;
+ };
+
+ // Shuffle an array.
+ _.shuffle = function(obj) {
+ var shuffled = [], rand;
+ each(obj, function(value, index, list) {
+ if (index == 0) {
+ shuffled[0] = value;
+ } else {
+ rand = Math.floor(Math.random() * (index + 1));
+ shuffled[index] = shuffled[rand];
+ shuffled[rand] = value;
+ }
+ });
+ return shuffled;
+ };
+
+ // Sort the object's values by a criterion produced by an iterator.
+ _.sortBy = function(obj, iterator, context) {
+ return _.pluck(_.map(obj, function(value, index, list) {
+ return {
+ value : value,
+ criteria : iterator.call(context, value, index, list)
+ };
+ }).sort(function(left, right) {
+ var a = left.criteria, b = right.criteria;
+ return a < b ? -1 : a > b ? 1 : 0;
+ }), 'value');
+ };
+
+ // Groups the object's values by a criterion. Pass either a string attribute
+ // to group by, or a function that returns the criterion.
+ _.groupBy = function(obj, val) {
+ var result = {};
+ var iterator = _.isFunction(val) ? val : function(obj) { return obj[val]; };
+ each(obj, function(value, index) {
+ var key = iterator(value, index);
+ (result[key] || (result[key] = [])).push(value);
+ });
+ return result;
+ };
+
+ // Use a comparator function to figure out at what index an object should
+ // be inserted so as to maintain order. Uses binary search.
+ _.sortedIndex = function(array, obj, iterator) {
+ iterator || (iterator = _.identity);
+ var low = 0, high = array.length;
+ while (low < high) {
+ var mid = (low + high) >> 1;
+ iterator(array[mid]) < iterator(obj) ? low = mid + 1 : high = mid;
+ }
+ return low;
+ };
+
+ // Safely convert anything iterable into a real, live array.
+ _.toArray = function(iterable) {
+ if (!iterable) return [];
+ if (iterable.toArray) return iterable.toArray();
+ if (_.isArray(iterable)) return slice.call(iterable);
+ if (_.isArguments(iterable)) return slice.call(iterable);
+ return _.values(iterable);
+ };
+
+ // Return the number of elements in an object.
+ _.size = function(obj) {
+ return _.toArray(obj).length;
+ };
+
+ // Array Functions
+ // ---------------
+
+ // Get the first element of an array. Passing **n** will return the first N
+ // values in the array. Aliased as `head`. The **guard** check allows it to work
+ // with `_.map`.
+ _.first = _.head = function(array, n, guard) {
+ return (n != null) && !guard ? slice.call(array, 0, n) : array[0];
+ };
+
+ // Returns everything but the last entry of the array. Especcialy useful on
+ // the arguments object. Passing **n** will return all the values in
+ // the array, excluding the last N. The **guard** check allows it to work with
+ // `_.map`.
+ _.initial = function(array, n, guard) {
+ return slice.call(array, 0, array.length - ((n == null) || guard ? 1 : n));
+ };
+
+ // Get the last element of an array. Passing **n** will return the last N
+ // values in the array. The **guard** check allows it to work with `_.map`.
+ _.last = function(array, n, guard) {
+ if ((n != null) && !guard) {
+ return slice.call(array, Math.max(array.length - n, 0));
+ } else {
+ return array[array.length - 1];
+ }
+ };
+
+ // Returns everything but the first entry of the array. Aliased as `tail`.
+ // Especially useful on the arguments object. Passing an **index** will return
+ // the rest of the values in the array from that index onward. The **guard**
+ // check allows it to work with `_.map`.
+ _.rest = _.tail = function(array, index, guard) {
+ return slice.call(array, (index == null) || guard ? 1 : index);
+ };
+
+ // Trim out all falsy values from an array.
+ _.compact = function(array) {
+ return _.filter(array, function(value){ return !!value; });
+ };
+
+ // Return a completely flattened version of an array.
+ _.flatten = function(array, shallow) {
+ return _.reduce(array, function(memo, value) {
+ if (_.isArray(value)) return memo.concat(shallow ? value : _.flatten(value));
+ memo[memo.length] = value;
+ return memo;
+ }, []);
+ };
+
+ // Return a version of the array that does not contain the specified value(s).
+ _.without = function(array) {
+ return _.difference(array, slice.call(arguments, 1));
+ };
+
+ // Produce a duplicate-free version of the array. If the array has already
+ // been sorted, you have the option of using a faster algorithm.
+ // Aliased as `unique`.
+ _.uniq = _.unique = function(array, isSorted, iterator) {
+ var initial = iterator ? _.map(array, iterator) : array;
+ var result = [];
+ _.reduce(initial, function(memo, el, i) {
+ if (0 == i || (isSorted === true ? _.last(memo) != el : !_.include(memo, el))) {
+ memo[memo.length] = el;
+ result[result.length] = array[i];
+ }
+ return memo;
+ }, []);
+ return result;
+ };
+
+ // Produce an array that contains the union: each distinct element from all of
+ // the passed-in arrays.
+ _.union = function() {
+ return _.uniq(_.flatten(arguments, true));
+ };
+
+ // Produce an array that contains every item shared between all the
+ // passed-in arrays. (Aliased as "intersect" for back-compat.)
+ _.intersection = _.intersect = function(array) {
+ var rest = slice.call(arguments, 1);
+ return _.filter(_.uniq(array), function(item) {
+ return _.every(rest, function(other) {
+ return _.indexOf(other, item) >= 0;
+ });
+ });
+ };
+
+ // Take the difference between one array and a number of other arrays.
+ // Only the elements present in just the first array will remain.
+ _.difference = function(array) {
+ var rest = _.flatten(slice.call(arguments, 1));
+ return _.filter(array, function(value){ return !_.include(rest, value); });
+ };
+
+ // Zip together multiple lists into a single array -- elements that share
+ // an index go together.
+ _.zip = function() {
+ var args = slice.call(arguments);
+ var length = _.max(_.pluck(args, 'length'));
+ var results = new Array(length);
+ for (var i = 0; i < length; i++) results[i] = _.pluck(args, "" + i);
+ return results;
+ };
+
+ // If the browser doesn't supply us with indexOf (I'm looking at you, **MSIE**),
+ // we need this function. Return the position of the first occurrence of an
+ // item in an array, or -1 if the item is not included in the array.
+ // Delegates to **ECMAScript 5**'s native `indexOf` if available.
+ // If the array is large and already in sort order, pass `true`
+ // for **isSorted** to use binary search.
+ _.indexOf = function(array, item, isSorted) {
+ if (array == null) return -1;
+ var i, l;
+ if (isSorted) {
+ i = _.sortedIndex(array, item);
+ return array[i] === item ? i : -1;
+ }
+ if (nativeIndexOf && array.indexOf === nativeIndexOf) return array.indexOf(item);
+ for (i = 0, l = array.length; i < l; i++) if (i in array && array[i] === item) return i;
+ return -1;
+ };
+
+ // Delegates to **ECMAScript 5**'s native `lastIndexOf` if available.
+ _.lastIndexOf = function(array, item) {
+ if (array == null) return -1;
+ if (nativeLastIndexOf && array.lastIndexOf === nativeLastIndexOf) return array.lastIndexOf(item);
+ var i = array.length;
+ while (i--) if (i in array && array[i] === item) return i;
+ return -1;
+ };
+
+ // Generate an integer Array containing an arithmetic progression. A port of
+ // the native Python `range()` function. See
+ // [the Python documentation](http://docs.python.org/library/functions.html#range).
+ _.range = function(start, stop, step) {
+ if (arguments.length <= 1) {
+ stop = start || 0;
+ start = 0;
+ }
+ step = arguments[2] || 1;
+
+ var len = Math.max(Math.ceil((stop - start) / step), 0);
+ var idx = 0;
+ var range = new Array(len);
+
+ while(idx < len) {
+ range[idx++] = start;
+ start += step;
+ }
+
+ return range;
+ };
+
+ // Function (ahem) Functions
+ // ------------------
+
+ // Reusable constructor function for prototype setting.
+ var ctor = function(){};
+
+ // Create a function bound to a given object (assigning `this`, and arguments,
+ // optionally). Binding with arguments is also known as `curry`.
+ // Delegates to **ECMAScript 5**'s native `Function.bind` if available.
+ // We check for `func.bind` first, to fail fast when `func` is undefined.
+ _.bind = function bind(func, context) {
+ var bound, args;
+ if (func.bind === nativeBind && nativeBind) return nativeBind.apply(func, slice.call(arguments, 1));
+ if (!_.isFunction(func)) throw new TypeError;
+ args = slice.call(arguments, 2);
+ return bound = function() {
+ if (!(this instanceof bound)) return func.apply(context, args.concat(slice.call(arguments)));
+ ctor.prototype = func.prototype;
+ var self = new ctor;
+ var result = func.apply(self, args.concat(slice.call(arguments)));
+ if (Object(result) === result) return result;
+ return self;
+ };
+ };
+
+ // Bind all of an object's methods to that object. Useful for ensuring that
+ // all callbacks defined on an object belong to it.
+ _.bindAll = function(obj) {
+ var funcs = slice.call(arguments, 1);
+ if (funcs.length == 0) funcs = _.functions(obj);
+ each(funcs, function(f) { obj[f] = _.bind(obj[f], obj); });
+ return obj;
+ };
+
+ // Memoize an expensive function by storing its results.
+ _.memoize = function(func, hasher) {
+ var memo = {};
+ hasher || (hasher = _.identity);
+ return function() {
+ var key = hasher.apply(this, arguments);
+ return _.has(memo, key) ? memo[key] : (memo[key] = func.apply(this, arguments));
+ };
+ };
+
+ // Delays a function for the given number of milliseconds, and then calls
+ // it with the arguments supplied.
+ _.delay = function(func, wait) {
+ var args = slice.call(arguments, 2);
+ return setTimeout(function(){ return func.apply(func, args); }, wait);
+ };
+
+ // Defers a function, scheduling it to run after the current call stack has
+ // cleared.
+ _.defer = function(func) {
+ return _.delay.apply(_, [func, 1].concat(slice.call(arguments, 1)));
+ };
+
+ // Returns a function, that, when invoked, will only be triggered at most once
+ // during a given window of time.
+ _.throttle = function(func, wait) {
+ var context, args, timeout, throttling, more;
+ var whenDone = _.debounce(function(){ more = throttling = false; }, wait);
+ return function() {
+ context = this; args = arguments;
+ var later = function() {
+ timeout = null;
+ if (more) func.apply(context, args);
+ whenDone();
+ };
+ if (!timeout) timeout = setTimeout(later, wait);
+ if (throttling) {
+ more = true;
+ } else {
+ func.apply(context, args);
+ }
+ whenDone();
+ throttling = true;
+ };
+ };
+
+ // Returns a function, that, as long as it continues to be invoked, will not
+ // be triggered. The function will be called after it stops being called for
+ // N milliseconds.
+ _.debounce = function(func, wait) {
+ var timeout;
+ return function() {
+ var context = this, args = arguments;
+ var later = function() {
+ timeout = null;
+ func.apply(context, args);
+ };
+ clearTimeout(timeout);
+ timeout = setTimeout(later, wait);
+ };
+ };
+
+ // Returns a function that will be executed at most one time, no matter how
+ // often you call it. Useful for lazy initialization.
+ _.once = function(func) {
+ var ran = false, memo;
+ return function() {
+ if (ran) return memo;
+ ran = true;
+ return memo = func.apply(this, arguments);
+ };
+ };
+
+ // Returns the first function passed as an argument to the second,
+ // allowing you to adjust arguments, run code before and after, and
+ // conditionally execute the original function.
+ _.wrap = function(func, wrapper) {
+ return function() {
+ var args = [func].concat(slice.call(arguments, 0));
+ return wrapper.apply(this, args);
+ };
+ };
+
+ // Returns a function that is the composition of a list of functions, each
+ // consuming the return value of the function that follows.
+ _.compose = function() {
+ var funcs = arguments;
+ return function() {
+ var args = arguments;
+ for (var i = funcs.length - 1; i >= 0; i--) {
+ args = [funcs[i].apply(this, args)];
+ }
+ return args[0];
+ };
+ };
+
+ // Returns a function that will only be executed after being called N times.
+ _.after = function(times, func) {
+ if (times <= 0) return func();
+ return function() {
+ if (--times < 1) { return func.apply(this, arguments); }
+ };
+ };
+
+ // Object Functions
+ // ----------------
+
+ // Retrieve the names of an object's properties.
+ // Delegates to **ECMAScript 5**'s native `Object.keys`
+ _.keys = nativeKeys || function(obj) {
+ if (obj !== Object(obj)) throw new TypeError('Invalid object');
+ var keys = [];
+ for (var key in obj) if (_.has(obj, key)) keys[keys.length] = key;
+ return keys;
+ };
+
+ // Retrieve the values of an object's properties.
+ _.values = function(obj) {
+ return _.map(obj, _.identity);
+ };
+
+ // Return a sorted list of the function names available on the object.
+ // Aliased as `methods`
+ _.functions = _.methods = function(obj) {
+ var names = [];
+ for (var key in obj) {
+ if (_.isFunction(obj[key])) names.push(key);
+ }
+ return names.sort();
+ };
+
+ // Extend a given object with all the properties in passed-in object(s).
+ _.extend = function(obj) {
+ each(slice.call(arguments, 1), function(source) {
+ for (var prop in source) {
+ obj[prop] = source[prop];
+ }
+ });
+ return obj;
+ };
+
+ // Fill in a given object with default properties.
+ _.defaults = function(obj) {
+ each(slice.call(arguments, 1), function(source) {
+ for (var prop in source) {
+ if (obj[prop] == null) obj[prop] = source[prop];
+ }
+ });
+ return obj;
+ };
+
+ // Create a (shallow-cloned) duplicate of an object.
+ _.clone = function(obj) {
+ if (!_.isObject(obj)) return obj;
+ return _.isArray(obj) ? obj.slice() : _.extend({}, obj);
+ };
+
+ // Invokes interceptor with the obj, and then returns obj.
+ // The primary purpose of this method is to "tap into" a method chain, in
+ // order to perform operations on intermediate results within the chain.
+ _.tap = function(obj, interceptor) {
+ interceptor(obj);
+ return obj;
+ };
+
+ // Internal recursive comparison function.
+ function eq(a, b, stack) {
+ // Identical objects are equal. `0 === -0`, but they aren't identical.
+ // See the Harmony `egal` proposal: http://wiki.ecmascript.org/doku.php?id=harmony:egal.
+ if (a === b) return a !== 0 || 1 / a == 1 / b;
+ // A strict comparison is necessary because `null == undefined`.
+ if (a == null || b == null) return a === b;
+ // Unwrap any wrapped objects.
+ if (a._chain) a = a._wrapped;
+ if (b._chain) b = b._wrapped;
+ // Invoke a custom `isEqual` method if one is provided.
+ if (a.isEqual && _.isFunction(a.isEqual)) return a.isEqual(b);
+ if (b.isEqual && _.isFunction(b.isEqual)) return b.isEqual(a);
+ // Compare `[[Class]]` names.
+ var className = toString.call(a);
+ if (className != toString.call(b)) return false;
+ switch (className) {
+ // Strings, numbers, dates, and booleans are compared by value.
+ case '[object String]':
+ // Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
+ // equivalent to `new String("5")`.
+ return a == String(b);
+ case '[object Number]':
+ // `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
+ // other numeric values.
+ return a != +a ? b != +b : (a == 0 ? 1 / a == 1 / b : a == +b);
+ case '[object Date]':
+ case '[object Boolean]':
+ // Coerce dates and booleans to numeric primitive values. Dates are compared by their
+ // millisecond representations. Note that invalid dates with millisecond representations
+ // of `NaN` are not equivalent.
+ return +a == +b;
+ // RegExps are compared by their source patterns and flags.
+ case '[object RegExp]':
+ return a.source == b.source &&
+ a.global == b.global &&
+ a.multiline == b.multiline &&
+ a.ignoreCase == b.ignoreCase;
+ }
+ if (typeof a != 'object' || typeof b != 'object') return false;
+ // Assume equality for cyclic structures. The algorithm for detecting cyclic
+ // structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
+ var length = stack.length;
+ while (length--) {
+ // Linear search. Performance is inversely proportional to the number of
+ // unique nested structures.
+ if (stack[length] == a) return true;
+ }
+ // Add the first object to the stack of traversed objects.
+ stack.push(a);
+ var size = 0, result = true;
+ // Recursively compare objects and arrays.
+ if (className == '[object Array]') {
+ // Compare array lengths to determine if a deep comparison is necessary.
+ size = a.length;
+ result = size == b.length;
+ if (result) {
+ // Deep compare the contents, ignoring non-numeric properties.
+ while (size--) {
+ // Ensure commutative equality for sparse arrays.
+ if (!(result = size in a == size in b && eq(a[size], b[size], stack))) break;
+ }
+ }
+ } else {
+ // Objects with different constructors are not equivalent.
+ if ('constructor' in a != 'constructor' in b || a.constructor != b.constructor) return false;
+ // Deep compare objects.
+ for (var key in a) {
+ if (_.has(a, key)) {
+ // Count the expected number of properties.
+ size++;
+ // Deep compare each member.
+ if (!(result = _.has(b, key) && eq(a[key], b[key], stack))) break;
+ }
+ }
+ // Ensure that both objects contain the same number of properties.
+ if (result) {
+ for (key in b) {
+ if (_.has(b, key) && !(size--)) break;
+ }
+ result = !size;
+ }
+ }
+ // Remove the first object from the stack of traversed objects.
+ stack.pop();
+ return result;
+ }
+
+ // Perform a deep comparison to check if two objects are equal.
+ _.isEqual = function(a, b) {
+ return eq(a, b, []);
+ };
+
+ // Is a given array, string, or object empty?
+ // An "empty" object has no enumerable own-properties.
+ _.isEmpty = function(obj) {
+ if (_.isArray(obj) || _.isString(obj)) return obj.length === 0;
+ for (var key in obj) if (_.has(obj, key)) return false;
+ return true;
+ };
+
+ // Is a given value a DOM element?
+ _.isElement = function(obj) {
+ return !!(obj && obj.nodeType == 1);
+ };
+
+ // Is a given value an array?
+ // Delegates to ECMA5's native Array.isArray
+ _.isArray = nativeIsArray || function(obj) {
+ return toString.call(obj) == '[object Array]';
+ };
+
+ // Is a given variable an object?
+ _.isObject = function(obj) {
+ return obj === Object(obj);
+ };
+
+ // Is a given variable an arguments object?
+ _.isArguments = function(obj) {
+ return toString.call(obj) == '[object Arguments]';
+ };
+ if (!_.isArguments(arguments)) {
+ _.isArguments = function(obj) {
+ return !!(obj && _.has(obj, 'callee'));
+ };
+ }
+
+ // Is a given value a function?
+ _.isFunction = function(obj) {
+ return toString.call(obj) == '[object Function]';
+ };
+
+ // Is a given value a string?
+ _.isString = function(obj) {
+ return toString.call(obj) == '[object String]';
+ };
+
+ // Is a given value a number?
+ _.isNumber = function(obj) {
+ return toString.call(obj) == '[object Number]';
+ };
+
+ // Is the given value `NaN`?
+ _.isNaN = function(obj) {
+ // `NaN` is the only value for which `===` is not reflexive.
+ return obj !== obj;
+ };
+
+ // Is a given value a boolean?
+ _.isBoolean = function(obj) {
+ return obj === true || obj === false || toString.call(obj) == '[object Boolean]';
+ };
+
+ // Is a given value a date?
+ _.isDate = function(obj) {
+ return toString.call(obj) == '[object Date]';
+ };
+
+ // Is the given value a regular expression?
+ _.isRegExp = function(obj) {
+ return toString.call(obj) == '[object RegExp]';
+ };
+
+ // Is a given value equal to null?
+ _.isNull = function(obj) {
+ return obj === null;
+ };
+
+ // Is a given variable undefined?
+ _.isUndefined = function(obj) {
+ return obj === void 0;
+ };
+
+ // Has own property?
+ _.has = function(obj, key) {
+ return hasOwnProperty.call(obj, key);
+ };
+
+ // Utility Functions
+ // -----------------
+
+ // Run Underscore.js in *noConflict* mode, returning the `_` variable to its
+ // previous owner. Returns a reference to the Underscore object.
+ _.noConflict = function() {
+ root._ = previousUnderscore;
+ return this;
+ };
+
+ // Keep the identity function around for default iterators.
+ _.identity = function(value) {
+ return value;
+ };
+
+ // Run a function **n** times.
+ _.times = function (n, iterator, context) {
+ for (var i = 0; i < n; i++) iterator.call(context, i);
+ };
+
+ // Escape a string for HTML interpolation.
+ _.escape = function(string) {
+ return (''+string).replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>').replace(/"/g, '"').replace(/'/g, ''').replace(/\//g,'/');
+ };
+
+ // Add your own custom functions to the Underscore object, ensuring that
+ // they're correctly added to the OOP wrapper as well.
+ _.mixin = function(obj) {
+ each(_.functions(obj), function(name){
+ addToWrapper(name, _[name] = obj[name]);
+ });
+ };
+
+ // Generate a unique integer id (unique within the entire client session).
+ // Useful for temporary DOM ids.
+ var idCounter = 0;
+ _.uniqueId = function(prefix) {
+ var id = idCounter++;
+ return prefix ? prefix + id : id;
+ };
+
+ // By default, Underscore uses ERB-style template delimiters, change the
+ // following template settings to use alternative delimiters.
+ _.templateSettings = {
+ evaluate : /<%([\s\S]+?)%>/g,
+ interpolate : /<%=([\s\S]+?)%>/g,
+ escape : /<%-([\s\S]+?)%>/g
+ };
+
+ // When customizing `templateSettings`, if you don't want to define an
+ // interpolation, evaluation or escaping regex, we need one that is
+ // guaranteed not to match.
+ var noMatch = /.^/;
+
+ // Within an interpolation, evaluation, or escaping, remove HTML escaping
+ // that had been previously added.
+ var unescape = function(code) {
+ return code.replace(/\\\\/g, '\\').replace(/\\'/g, "'");
+ };
+
+ // JavaScript micro-templating, similar to John Resig's implementation.
+ // Underscore templating handles arbitrary delimiters, preserves whitespace,
+ // and correctly escapes quotes within interpolated code.
+ _.template = function(str, data) {
+ var c = _.templateSettings;
+ var tmpl = 'var __p=[],print=function(){__p.push.apply(__p,arguments);};' +
+ 'with(obj||{}){__p.push(\'' +
+ str.replace(/\\/g, '\\\\')
+ .replace(/'/g, "\\'")
+ .replace(c.escape || noMatch, function(match, code) {
+ return "',_.escape(" + unescape(code) + "),'";
+ })
+ .replace(c.interpolate || noMatch, function(match, code) {
+ return "'," + unescape(code) + ",'";
+ })
+ .replace(c.evaluate || noMatch, function(match, code) {
+ return "');" + unescape(code).replace(/[\r\n\t]/g, ' ') + ";__p.push('";
+ })
+ .replace(/\r/g, '\\r')
+ .replace(/\n/g, '\\n')
+ .replace(/\t/g, '\\t')
+ + "');}return __p.join('');";
+ var func = new Function('obj', '_', tmpl);
+ if (data) return func(data, _);
+ return function(data) {
+ return func.call(this, data, _);
+ };
+ };
+
+ // Add a "chain" function, which will delegate to the wrapper.
+ _.chain = function(obj) {
+ return _(obj).chain();
+ };
+
+ // The OOP Wrapper
+ // ---------------
+
+ // If Underscore is called as a function, it returns a wrapped object that
+ // can be used OO-style. This wrapper holds altered versions of all the
+ // underscore functions. Wrapped objects may be chained.
+ var wrapper = function(obj) { this._wrapped = obj; };
+
+ // Expose `wrapper.prototype` as `_.prototype`
+ _.prototype = wrapper.prototype;
+
+ // Helper function to continue chaining intermediate results.
+ var result = function(obj, chain) {
+ return chain ? _(obj).chain() : obj;
+ };
+
+ // A method to easily add functions to the OOP wrapper.
+ var addToWrapper = function(name, func) {
+ wrapper.prototype[name] = function() {
+ var args = slice.call(arguments);
+ unshift.call(args, this._wrapped);
+ return result(func.apply(_, args), this._chain);
+ };
+ };
+
+ // Add all of the Underscore functions to the wrapper object.
+ _.mixin(_);
+
+ // Add all mutator Array functions to the wrapper.
+ each(['pop', 'push', 'reverse', 'shift', 'sort', 'splice', 'unshift'], function(name) {
+ var method = ArrayProto[name];
+ wrapper.prototype[name] = function() {
+ var wrapped = this._wrapped;
+ method.apply(wrapped, arguments);
+ var length = wrapped.length;
+ if ((name == 'shift' || name == 'splice') && length === 0) delete wrapped[0];
+ return result(wrapped, this._chain);
+ };
+ });
+
+ // Add all accessor Array functions to the wrapper.
+ each(['concat', 'join', 'slice'], function(name) {
+ var method = ArrayProto[name];
+ wrapper.prototype[name] = function() {
+ return result(method.apply(this._wrapped, arguments), this._chain);
+ };
+ });
+
+ // Start chaining a wrapped Underscore object.
+ wrapper.prototype.chain = function() {
+ this._chain = true;
+ return this;
+ };
+
+ // Extracts the result from a wrapped and chained object.
+ wrapper.prototype.value = function() {
+ return this._wrapped;
+ };
+
+}).call(this);
diff --git a/doc/build/_static/underscore.js b/doc/build/_static/underscore.js
new file mode 100644
index 0000000..5b55f32
--- /dev/null
+++ b/doc/build/_static/underscore.js
@@ -0,0 +1,31 @@
+// Underscore.js 1.3.1
+// (c) 2009-2012 Jeremy Ashkenas, DocumentCloud Inc.
+// Underscore is freely distributable under the MIT license.
+// Portions of Underscore are inspired or borrowed from Prototype,
+// Oliver Steele's Functional, and John Resig's Micro-Templating.
+// For all details and documentation:
+// http://documentcloud.github.com/underscore
+(function(){function q(a,c,d){if(a===c)return a!==0||1/a==1/c;if(a==null||c==null)return a===c;if(a._chain)a=a._wrapped;if(c._chain)c=c._wrapped;if(a.isEqual&&b.isFunction(a.isEqual))return a.isEqual(c);if(c.isEqual&&b.isFunction(c.isEqual))return c.isEqual(a);var e=l.call(a);if(e!=l.call(c))return false;switch(e){case "[object String]":return a==String(c);case "[object Number]":return a!=+a?c!=+c:a==0?1/a==1/c:a==+c;case "[object Date]":case "[object Boolean]":return+a==+c;case "[object [...]
+c.source&&a.global==c.global&&a.multiline==c.multiline&&a.ignoreCase==c.ignoreCase}if(typeof a!="object"||typeof c!="object")return false;for(var f=d.length;f--;)if(d[f]==a)return true;d.push(a);var f=0,g=true;if(e=="[object Array]"){if(f=a.length,g=f==c.length)for(;f--;)if(!(g=f in a==f in c&&q(a[f],c[f],d)))break}else{if("constructor"in a!="constructor"in c||a.constructor!=c.constructor)return false;for(var h in a)if(b.has(a,h)&&(f++,!(g=b.has(c,h)&&q(a[h],c[h],d))))break;if(g){for(h i [...]
+h)&&!f--)break;g=!f}}d.pop();return g}var r=this,G=r._,n={},k=Array.prototype,o=Object.prototype,i=k.slice,H=k.unshift,l=o.toString,I=o.hasOwnProperty,w=k.forEach,x=k.map,y=k.reduce,z=k.reduceRight,A=k.filter,B=k.every,C=k.some,p=k.indexOf,D=k.lastIndexOf,o=Array.isArray,J=Object.keys,s=Function.prototype.bind,b=function(a){return new m(a)};if(typeof exports!=="undefined"){if(typeof module!=="undefined"&&module.exports)exports=module.exports=b;exports._=b}else r._=b;b.VERSION="1.3.1";var [...]
+b.forEach=function(a,c,d){if(a!=null)if(w&&a.forEach===w)a.forEach(c,d);else if(a.length===+a.length)for(var e=0,f=a.length;e<f;e++){if(e in a&&c.call(d,a[e],e,a)===n)break}else for(e in a)if(b.has(a,e)&&c.call(d,a[e],e,a)===n)break};b.map=b.collect=function(a,c,b){var e=[];if(a==null)return e;if(x&&a.map===x)return a.map(c,b);j(a,function(a,g,h){e[e.length]=c.call(b,a,g,h)});if(a.length===+a.length)e.length=a.length;return e};b.reduce=b.foldl=b.inject=function(a,c,d,e){var f=arguments.l [...]
+null&&(a=[]);if(y&&a.reduce===y)return e&&(c=b.bind(c,e)),f?a.reduce(c,d):a.reduce(c);j(a,function(a,b,i){f?d=c.call(e,d,a,b,i):(d=a,f=true)});if(!f)throw new TypeError("Reduce of empty array with no initial value");return d};b.reduceRight=b.foldr=function(a,c,d,e){var f=arguments.length>2;a==null&&(a=[]);if(z&&a.reduceRight===z)return e&&(c=b.bind(c,e)),f?a.reduceRight(c,d):a.reduceRight(c);var g=b.toArray(a).reverse();e&&!f&&(c=b.bind(c,e));return f?b.reduce(g,c,d,e):b.reduce(g,c)};b.f [...]
+function(a,c,b){var e;E(a,function(a,g,h){if(c.call(b,a,g,h))return e=a,true});return e};b.filter=b.select=function(a,c,b){var e=[];if(a==null)return e;if(A&&a.filter===A)return a.filter(c,b);j(a,function(a,g,h){c.call(b,a,g,h)&&(e[e.length]=a)});return e};b.reject=function(a,c,b){var e=[];if(a==null)return e;j(a,function(a,g,h){c.call(b,a,g,h)||(e[e.length]=a)});return e};b.every=b.all=function(a,c,b){var e=true;if(a==null)return e;if(B&&a.every===B)return a.every(c,b);j(a,function(a,g, [...]
+e&&c.call(b,a,g,h)))return n});return e};var E=b.some=b.any=function(a,c,d){c||(c=b.identity);var e=false;if(a==null)return e;if(C&&a.some===C)return a.some(c,d);j(a,function(a,b,h){if(e||(e=c.call(d,a,b,h)))return n});return!!e};b.include=b.contains=function(a,c){var b=false;if(a==null)return b;return p&&a.indexOf===p?a.indexOf(c)!=-1:b=E(a,function(a){return a===c})};b.invoke=function(a,c){var d=i.call(arguments,2);return b.map(a,function(a){return(b.isFunction(c)?c||a:a[c]).apply(a,d) [...]
+function(a,c){return b.map(a,function(a){return a[c]})};b.max=function(a,c,d){if(!c&&b.isArray(a))return Math.max.apply(Math,a);if(!c&&b.isEmpty(a))return-Infinity;var e={computed:-Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b>=e.computed&&(e={value:a,computed:b})});return e.value};b.min=function(a,c,d){if(!c&&b.isArray(a))return Math.min.apply(Math,a);if(!c&&b.isEmpty(a))return Infinity;var e={computed:Infinity};j(a,function(a,b,h){b=c?c.call(d,a,b,h):a;b<e.computed&&(e={value:a [...]
+return e.value};b.shuffle=function(a){var b=[],d;j(a,function(a,f){f==0?b[0]=a:(d=Math.floor(Math.random()*(f+1)),b[f]=b[d],b[d]=a)});return b};b.sortBy=function(a,c,d){return b.pluck(b.map(a,function(a,b,g){return{value:a,criteria:c.call(d,a,b,g)}}).sort(function(a,b){var c=a.criteria,d=b.criteria;return c<d?-1:c>d?1:0}),"value")};b.groupBy=function(a,c){var d={},e=b.isFunction(c)?c:function(a){return a[c]};j(a,function(a,b){var c=e(a,b);(d[c]||(d[c]=[])).push(a)});return d};b.sortedInd [...]
+c,d){d||(d=b.identity);for(var e=0,f=a.length;e<f;){var g=e+f>>1;d(a[g])<d(c)?e=g+1:f=g}return e};b.toArray=function(a){return!a?[]:a.toArray?a.toArray():b.isArray(a)?i.call(a):b.isArguments(a)?i.call(a):b.values(a)};b.size=function(a){return b.toArray(a).length};b.first=b.head=function(a,b,d){return b!=null&&!d?i.call(a,0,b):a[0]};b.initial=function(a,b,d){return i.call(a,0,a.length-(b==null||d?1:b))};b.last=function(a,b,d){return b!=null&&!d?i.call(a,Math.max(a.length-b,0)):a[a.length- [...]
+b.tail=function(a,b,d){return i.call(a,b==null||d?1:b)};b.compact=function(a){return b.filter(a,function(a){return!!a})};b.flatten=function(a,c){return b.reduce(a,function(a,e){if(b.isArray(e))return a.concat(c?e:b.flatten(e));a[a.length]=e;return a},[])};b.without=function(a){return b.difference(a,i.call(arguments,1))};b.uniq=b.unique=function(a,c,d){var d=d?b.map(a,d):a,e=[];b.reduce(d,function(d,g,h){if(0==h||(c===true?b.last(d)!=g:!b.include(d,g)))d[d.length]=g,e[e.length]=a[h];retur [...]
+return e};b.union=function(){return b.uniq(b.flatten(arguments,true))};b.intersection=b.intersect=function(a){var c=i.call(arguments,1);return b.filter(b.uniq(a),function(a){return b.every(c,function(c){return b.indexOf(c,a)>=0})})};b.difference=function(a){var c=b.flatten(i.call(arguments,1));return b.filter(a,function(a){return!b.include(c,a)})};b.zip=function(){for(var a=i.call(arguments),c=b.max(b.pluck(a,"length")),d=Array(c),e=0;e<c;e++)d[e]=b.pluck(a,""+e);return d};b.indexOf=func [...]
+d){if(a==null)return-1;var e;if(d)return d=b.sortedIndex(a,c),a[d]===c?d:-1;if(p&&a.indexOf===p)return a.indexOf(c);for(d=0,e=a.length;d<e;d++)if(d in a&&a[d]===c)return d;return-1};b.lastIndexOf=function(a,b){if(a==null)return-1;if(D&&a.lastIndexOf===D)return a.lastIndexOf(b);for(var d=a.length;d--;)if(d in a&&a[d]===b)return d;return-1};b.range=function(a,b,d){arguments.length<=1&&(b=a||0,a=0);for(var d=arguments[2]||1,e=Math.max(Math.ceil((b-a)/d),0),f=0,g=Array(e);f<e;)g[f++]=a,a+=d; [...]
+var F=function(){};b.bind=function(a,c){var d,e;if(a.bind===s&&s)return s.apply(a,i.call(arguments,1));if(!b.isFunction(a))throw new TypeError;e=i.call(arguments,2);return d=function(){if(!(this instanceof d))return a.apply(c,e.concat(i.call(arguments)));F.prototype=a.prototype;var b=new F,g=a.apply(b,e.concat(i.call(arguments)));return Object(g)===g?g:b}};b.bindAll=function(a){var c=i.call(arguments,1);c.length==0&&(c=b.functions(a));j(c,function(c){a[c]=b.bind(a[c],a)});return a};b.mem [...]
+c){var d={};c||(c=b.identity);return function(){var e=c.apply(this,arguments);return b.has(d,e)?d[e]:d[e]=a.apply(this,arguments)}};b.delay=function(a,b){var d=i.call(arguments,2);return setTimeout(function(){return a.apply(a,d)},b)};b.defer=function(a){return b.delay.apply(b,[a,1].concat(i.call(arguments,1)))};b.throttle=function(a,c){var d,e,f,g,h,i=b.debounce(function(){h=g=false},c);return function(){d=this;e=arguments;var b;f||(f=setTimeout(function(){f=null;h&&a.apply(d,e);i()},c)) [...]
+a.apply(d,e);i();g=true}};b.debounce=function(a,b){var d;return function(){var e=this,f=arguments;clearTimeout(d);d=setTimeout(function(){d=null;a.apply(e,f)},b)}};b.once=function(a){var b=false,d;return function(){if(b)return d;b=true;return d=a.apply(this,arguments)}};b.wrap=function(a,b){return function(){var d=[a].concat(i.call(arguments,0));return b.apply(this,d)}};b.compose=function(){var a=arguments;return function(){for(var b=arguments,d=a.length-1;d>=0;d--)b=[a[d].apply(this,b)] [...]
+b.after=function(a,b){return a<=0?b():function(){if(--a<1)return b.apply(this,arguments)}};b.keys=J||function(a){if(a!==Object(a))throw new TypeError("Invalid object");var c=[],d;for(d in a)b.has(a,d)&&(c[c.length]=d);return c};b.values=function(a){return b.map(a,b.identity)};b.functions=b.methods=function(a){var c=[],d;for(d in a)b.isFunction(a[d])&&c.push(d);return c.sort()};b.extend=function(a){j(i.call(arguments,1),function(b){for(var d in b)a[d]=b[d]});return a};b.defaults=function( [...]
+1),function(b){for(var d in b)a[d]==null&&(a[d]=b[d])});return a};b.clone=function(a){return!b.isObject(a)?a:b.isArray(a)?a.slice():b.extend({},a)};b.tap=function(a,b){b(a);return a};b.isEqual=function(a,b){return q(a,b,[])};b.isEmpty=function(a){if(b.isArray(a)||b.isString(a))return a.length===0;for(var c in a)if(b.has(a,c))return false;return true};b.isElement=function(a){return!!(a&&a.nodeType==1)};b.isArray=o||function(a){return l.call(a)=="[object Array]"};b.isObject=function(a){ret [...]
+b.isArguments=function(a){return l.call(a)=="[object Arguments]"};if(!b.isArguments(arguments))b.isArguments=function(a){return!(!a||!b.has(a,"callee"))};b.isFunction=function(a){return l.call(a)=="[object Function]"};b.isString=function(a){return l.call(a)=="[object String]"};b.isNumber=function(a){return l.call(a)=="[object Number]"};b.isNaN=function(a){return a!==a};b.isBoolean=function(a){return a===true||a===false||l.call(a)=="[object Boolean]"};b.isDate=function(a){return l.call(a) [...]
+b.isRegExp=function(a){return l.call(a)=="[object RegExp]"};b.isNull=function(a){return a===null};b.isUndefined=function(a){return a===void 0};b.has=function(a,b){return I.call(a,b)};b.noConflict=function(){r._=G;return this};b.identity=function(a){return a};b.times=function(a,b,d){for(var e=0;e<a;e++)b.call(d,e)};b.escape=function(a){return(""+a).replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'").replace(/\//g,"/")};b.mixin [...]
+function(c){K(c,b[c]=a[c])})};var L=0;b.uniqueId=function(a){var b=L++;return a?a+b:b};b.templateSettings={evaluate:/<%([\s\S]+?)%>/g,interpolate:/<%=([\s\S]+?)%>/g,escape:/<%-([\s\S]+?)%>/g};var t=/.^/,u=function(a){return a.replace(/\\\\/g,"\\").replace(/\\'/g,"'")};b.template=function(a,c){var d=b.templateSettings,d="var __p=[],print=function(){__p.push.apply(__p,arguments);};with(obj||{}){__p.push('"+a.replace(/\\/g,"\\\\").replace(/'/g,"\\'").replace(d.escape||t,function(a,b){return [...]
+u(b)+"),'"}).replace(d.interpolate||t,function(a,b){return"',"+u(b)+",'"}).replace(d.evaluate||t,function(a,b){return"');"+u(b).replace(/[\r\n\t]/g," ")+";__p.push('"}).replace(/\r/g,"\\r").replace(/\n/g,"\\n").replace(/\t/g,"\\t")+"');}return __p.join('');",e=new Function("obj","_",d);return c?e(c,b):function(a){return e.call(this,a,b)}};b.chain=function(a){return b(a).chain()};var m=function(a){this._wrapped=a};b.prototype=m.prototype;var v=function(a,c){return c?b(a).chain():a},K=func [...]
+function(){var a=i.call(arguments);H.call(a,this._wrapped);return v(c.apply(b,a),this._chain)}};b.mixin(b);j("pop,push,reverse,shift,sort,splice,unshift".split(","),function(a){var b=k[a];m.prototype[a]=function(){var d=this._wrapped;b.apply(d,arguments);var e=d.length;(a=="shift"||a=="splice")&&e===0&&delete d[0];return v(d,this._chain)}});j(["concat","join","slice"],function(a){var b=k[a];m.prototype[a]=function(){return v(b.apply(this._wrapped,arguments),this._chain)}});m.prototype.ch [...]
+true;return this};m.prototype.value=function(){return this._wrapped}}).call(this);
diff --git a/doc/build/_static/up-pressed.png b/doc/build/_static/up-pressed.png
new file mode 100644
index 0000000..99e7210
Binary files /dev/null and b/doc/build/_static/up-pressed.png differ
diff --git a/doc/build/_static/up.png b/doc/build/_static/up.png
new file mode 100644
index 0000000..26de002
Binary files /dev/null and b/doc/build/_static/up.png differ
diff --git a/doc/build/_static/websupport.js b/doc/build/_static/websupport.js
new file mode 100644
index 0000000..98e7f40
--- /dev/null
+++ b/doc/build/_static/websupport.js
@@ -0,0 +1,808 @@
+/*
+ * websupport.js
+ * ~~~~~~~~~~~~~
+ *
+ * sphinx.websupport utilities for all documentation.
+ *
+ * :copyright: Copyright 2007-2016 by the Sphinx team, see AUTHORS.
+ * :license: BSD, see LICENSE for details.
+ *
+ */
+
+(function($) {
+ $.fn.autogrow = function() {
+ return this.each(function() {
+ var textarea = this;
+
+ $.fn.autogrow.resize(textarea);
+
+ $(textarea)
+ .focus(function() {
+ textarea.interval = setInterval(function() {
+ $.fn.autogrow.resize(textarea);
+ }, 500);
+ })
+ .blur(function() {
+ clearInterval(textarea.interval);
+ });
+ });
+ };
+
+ $.fn.autogrow.resize = function(textarea) {
+ var lineHeight = parseInt($(textarea).css('line-height'), 10);
+ var lines = textarea.value.split('\n');
+ var columns = textarea.cols;
+ var lineCount = 0;
+ $.each(lines, function() {
+ lineCount += Math.ceil(this.length / columns) || 1;
+ });
+ var height = lineHeight * (lineCount + 1);
+ $(textarea).css('height', height);
+ };
+})(jQuery);
+
+(function($) {
+ var comp, by;
+
+ function init() {
+ initEvents();
+ initComparator();
+ }
+
+ function initEvents() {
+ $(document).on("click", 'a.comment-close', function(event) {
+ event.preventDefault();
+ hide($(this).attr('id').substring(2));
+ });
+ $(document).on("click", 'a.vote', function(event) {
+ event.preventDefault();
+ handleVote($(this));
+ });
+ $(document).on("click", 'a.reply', function(event) {
+ event.preventDefault();
+ openReply($(this).attr('id').substring(2));
+ });
+ $(document).on("click", 'a.close-reply', function(event) {
+ event.preventDefault();
+ closeReply($(this).attr('id').substring(2));
+ });
+ $(document).on("click", 'a.sort-option', function(event) {
+ event.preventDefault();
+ handleReSort($(this));
+ });
+ $(document).on("click", 'a.show-proposal', function(event) {
+ event.preventDefault();
+ showProposal($(this).attr('id').substring(2));
+ });
+ $(document).on("click", 'a.hide-proposal', function(event) {
+ event.preventDefault();
+ hideProposal($(this).attr('id').substring(2));
+ });
+ $(document).on("click", 'a.show-propose-change', function(event) {
+ event.preventDefault();
+ showProposeChange($(this).attr('id').substring(2));
+ });
+ $(document).on("click", 'a.hide-propose-change', function(event) {
+ event.preventDefault();
+ hideProposeChange($(this).attr('id').substring(2));
+ });
+ $(document).on("click", 'a.accept-comment', function(event) {
+ event.preventDefault();
+ acceptComment($(this).attr('id').substring(2));
+ });
+ $(document).on("click", 'a.delete-comment', function(event) {
+ event.preventDefault();
+ deleteComment($(this).attr('id').substring(2));
+ });
+ $(document).on("click", 'a.comment-markup', function(event) {
+ event.preventDefault();
+ toggleCommentMarkupBox($(this).attr('id').substring(2));
+ });
+ }
+
+ /**
+ * Set comp, which is a comparator function used for sorting and
+ * inserting comments into the list.
+ */
+ function setComparator() {
+ // If the first three letters are "asc", sort in ascending order
+ // and remove the prefix.
+ if (by.substring(0,3) == 'asc') {
+ var i = by.substring(3);
+ comp = function(a, b) { return a[i] - b[i]; };
+ } else {
+ // Otherwise sort in descending order.
+ comp = function(a, b) { return b[by] - a[by]; };
+ }
+
+ // Reset link styles and format the selected sort option.
+ $('a.sel').attr('href', '#').removeClass('sel');
+ $('a.by' + by).removeAttr('href').addClass('sel');
+ }
+
+ /**
+ * Create a comp function. If the user has preferences stored in
+ * the sortBy cookie, use those, otherwise use the default.
+ */
+ function initComparator() {
+ by = 'rating'; // Default to sort by rating.
+ // If the sortBy cookie is set, use that instead.
+ if (document.cookie.length > 0) {
+ var start = document.cookie.indexOf('sortBy=');
+ if (start != -1) {
+ start = start + 7;
+ var end = document.cookie.indexOf(";", start);
+ if (end == -1) {
+ end = document.cookie.length;
+ by = unescape(document.cookie.substring(start, end));
+ }
+ }
+ }
+ setComparator();
+ }
+
+ /**
+ * Show a comment div.
+ */
+ function show(id) {
+ $('#ao' + id).hide();
+ $('#ah' + id).show();
+ var context = $.extend({id: id}, opts);
+ var popup = $(renderTemplate(popupTemplate, context)).hide();
+ popup.find('textarea[name="proposal"]').hide();
+ popup.find('a.by' + by).addClass('sel');
+ var form = popup.find('#cf' + id);
+ form.submit(function(event) {
+ event.preventDefault();
+ addComment(form);
+ });
+ $('#s' + id).after(popup);
+ popup.slideDown('fast', function() {
+ getComments(id);
+ });
+ }
+
+ /**
+ * Hide a comment div.
+ */
+ function hide(id) {
+ $('#ah' + id).hide();
+ $('#ao' + id).show();
+ var div = $('#sc' + id);
+ div.slideUp('fast', function() {
+ div.remove();
+ });
+ }
+
+ /**
+ * Perform an ajax request to get comments for a node
+ * and insert the comments into the comments tree.
+ */
+ function getComments(id) {
+ $.ajax({
+ type: 'GET',
+ url: opts.getCommentsURL,
+ data: {node: id},
+ success: function(data, textStatus, request) {
+ var ul = $('#cl' + id);
+ var speed = 100;
+ $('#cf' + id)
+ .find('textarea[name="proposal"]')
+ .data('source', data.source);
+
+ if (data.comments.length === 0) {
+ ul.html('<li>No comments yet.</li>');
+ ul.data('empty', true);
+ } else {
+ // If there are comments, sort them and put them in the list.
+ var comments = sortComments(data.comments);
+ speed = data.comments.length * 100;
+ appendComments(comments, ul);
+ ul.data('empty', false);
+ }
+ $('#cn' + id).slideUp(speed + 200);
+ ul.slideDown(speed);
+ },
+ error: function(request, textStatus, error) {
+ showError('Oops, there was a problem retrieving the comments.');
+ },
+ dataType: 'json'
+ });
+ }
+
+ /**
+ * Add a comment via ajax and insert the comment into the comment tree.
+ */
+ function addComment(form) {
+ var node_id = form.find('input[name="node"]').val();
+ var parent_id = form.find('input[name="parent"]').val();
+ var text = form.find('textarea[name="comment"]').val();
+ var proposal = form.find('textarea[name="proposal"]').val();
+
+ if (text == '') {
+ showError('Please enter a comment.');
+ return;
+ }
+
+ // Disable the form that is being submitted.
+ form.find('textarea,input').attr('disabled', 'disabled');
+
+ // Send the comment to the server.
+ $.ajax({
+ type: "POST",
+ url: opts.addCommentURL,
+ dataType: 'json',
+ data: {
+ node: node_id,
+ parent: parent_id,
+ text: text,
+ proposal: proposal
+ },
+ success: function(data, textStatus, error) {
+ // Reset the form.
+ if (node_id) {
+ hideProposeChange(node_id);
+ }
+ form.find('textarea')
+ .val('')
+ .add(form.find('input'))
+ .removeAttr('disabled');
+ var ul = $('#cl' + (node_id || parent_id));
+ if (ul.data('empty')) {
+ $(ul).empty();
+ ul.data('empty', false);
+ }
+ insertComment(data.comment);
+ var ao = $('#ao' + node_id);
+ ao.find('img').attr({'src': opts.commentBrightImage});
+ if (node_id) {
+ // if this was a "root" comment, remove the commenting box
+ // (the user can get it back by reopening the comment popup)
+ $('#ca' + node_id).slideUp();
+ }
+ },
+ error: function(request, textStatus, error) {
+ form.find('textarea,input').removeAttr('disabled');
+ showError('Oops, there was a problem adding the comment.');
+ }
+ });
+ }
+
+ /**
+ * Recursively append comments to the main comment list and children
+ * lists, creating the comment tree.
+ */
+ function appendComments(comments, ul) {
+ $.each(comments, function() {
+ var div = createCommentDiv(this);
+ ul.append($(document.createElement('li')).html(div));
+ appendComments(this.children, div.find('ul.comment-children'));
+ // To avoid stagnating data, don't store the comments children in data.
+ this.children = null;
+ div.data('comment', this);
+ });
+ }
+
+ /**
+ * After adding a new comment, it must be inserted in the correct
+ * location in the comment tree.
+ */
+ function insertComment(comment) {
+ var div = createCommentDiv(comment);
+
+ // To avoid stagnating data, don't store the comments children in data.
+ comment.children = null;
+ div.data('comment', comment);
+
+ var ul = $('#cl' + (comment.node || comment.parent));
+ var siblings = getChildren(ul);
+
+ var li = $(document.createElement('li'));
+ li.hide();
+
+ // Determine where in the parents children list to insert this comment.
+ for(i=0; i < siblings.length; i++) {
+ if (comp(comment, siblings[i]) <= 0) {
+ $('#cd' + siblings[i].id)
+ .parent()
+ .before(li.html(div));
+ li.slideDown('fast');
+ return;
+ }
+ }
+
+ // If we get here, this comment rates lower than all the others,
+ // or it is the only comment in the list.
+ ul.append(li.html(div));
+ li.slideDown('fast');
+ }
+
+ function acceptComment(id) {
+ $.ajax({
+ type: 'POST',
+ url: opts.acceptCommentURL,
+ data: {id: id},
+ success: function(data, textStatus, request) {
+ $('#cm' + id).fadeOut('fast');
+ $('#cd' + id).removeClass('moderate');
+ },
+ error: function(request, textStatus, error) {
+ showError('Oops, there was a problem accepting the comment.');
+ }
+ });
+ }
+
+ function deleteComment(id) {
+ $.ajax({
+ type: 'POST',
+ url: opts.deleteCommentURL,
+ data: {id: id},
+ success: function(data, textStatus, request) {
+ var div = $('#cd' + id);
+ if (data == 'delete') {
+ // Moderator mode: remove the comment and all children immediately
+ div.slideUp('fast', function() {
+ div.remove();
+ });
+ return;
+ }
+ // User mode: only mark the comment as deleted
+ div
+ .find('span.user-id:first')
+ .text('[deleted]').end()
+ .find('div.comment-text:first')
+ .text('[deleted]').end()
+ .find('#cm' + id + ', #dc' + id + ', #ac' + id + ', #rc' + id +
+ ', #sp' + id + ', #hp' + id + ', #cr' + id + ', #rl' + id)
+ .remove();
+ var comment = div.data('comment');
+ comment.username = '[deleted]';
+ comment.text = '[deleted]';
+ div.data('comment', comment);
+ },
+ error: function(request, textStatus, error) {
+ showError('Oops, there was a problem deleting the comment.');
+ }
+ });
+ }
+
+ function showProposal(id) {
+ $('#sp' + id).hide();
+ $('#hp' + id).show();
+ $('#pr' + id).slideDown('fast');
+ }
+
+ function hideProposal(id) {
+ $('#hp' + id).hide();
+ $('#sp' + id).show();
+ $('#pr' + id).slideUp('fast');
+ }
+
+ function showProposeChange(id) {
+ $('#pc' + id).hide();
+ $('#hc' + id).show();
+ var textarea = $('#pt' + id);
+ textarea.val(textarea.data('source'));
+ $.fn.autogrow.resize(textarea[0]);
+ textarea.slideDown('fast');
+ }
+
+ function hideProposeChange(id) {
+ $('#hc' + id).hide();
+ $('#pc' + id).show();
+ var textarea = $('#pt' + id);
+ textarea.val('').removeAttr('disabled');
+ textarea.slideUp('fast');
+ }
+
+ function toggleCommentMarkupBox(id) {
+ $('#mb' + id).toggle();
+ }
+
+ /** Handle when the user clicks on a sort by link. */
+ function handleReSort(link) {
+ var classes = link.attr('class').split(/\s+/);
+ for (var i=0; i<classes.length; i++) {
+ if (classes[i] != 'sort-option') {
+ by = classes[i].substring(2);
+ }
+ }
+ setComparator();
+ // Save/update the sortBy cookie.
+ var expiration = new Date();
+ expiration.setDate(expiration.getDate() + 365);
+ document.cookie= 'sortBy=' + escape(by) +
+ ';expires=' + expiration.toUTCString();
+ $('ul.comment-ul').each(function(index, ul) {
+ var comments = getChildren($(ul), true);
+ comments = sortComments(comments);
+ appendComments(comments, $(ul).empty());
+ });
+ }
+
+ /**
+ * Function to process a vote when a user clicks an arrow.
+ */
+ function handleVote(link) {
+ if (!opts.voting) {
+ showError("You'll need to login to vote.");
+ return;
+ }
+
+ var id = link.attr('id');
+ if (!id) {
+ // Didn't click on one of the voting arrows.
+ return;
+ }
+ // If it is an unvote, the new vote value is 0,
+ // Otherwise it's 1 for an upvote, or -1 for a downvote.
+ var value = 0;
+ if (id.charAt(1) != 'u') {
+ value = id.charAt(0) == 'u' ? 1 : -1;
+ }
+ // The data to be sent to the server.
+ var d = {
+ comment_id: id.substring(2),
+ value: value
+ };
+
+ // Swap the vote and unvote links.
+ link.hide();
+ $('#' + id.charAt(0) + (id.charAt(1) == 'u' ? 'v' : 'u') + d.comment_id)
+ .show();
+
+ // The div the comment is displayed in.
+ var div = $('div#cd' + d.comment_id);
+ var data = div.data('comment');
+
+ // If this is not an unvote, and the other vote arrow has
+ // already been pressed, unpress it.
+ if ((d.value !== 0) && (data.vote === d.value * -1)) {
+ $('#' + (d.value == 1 ? 'd' : 'u') + 'u' + d.comment_id).hide();
+ $('#' + (d.value == 1 ? 'd' : 'u') + 'v' + d.comment_id).show();
+ }
+
+ // Update the comments rating in the local data.
+ data.rating += (data.vote === 0) ? d.value : (d.value - data.vote);
+ data.vote = d.value;
+ div.data('comment', data);
+
+ // Change the rating text.
+ div.find('.rating:first')
+ .text(data.rating + ' point' + (data.rating == 1 ? '' : 's'));
+
+ // Send the vote information to the server.
+ $.ajax({
+ type: "POST",
+ url: opts.processVoteURL,
+ data: d,
+ error: function(request, textStatus, error) {
+ showError('Oops, there was a problem casting that vote.');
+ }
+ });
+ }
+
+ /**
+ * Open a reply form used to reply to an existing comment.
+ */
+ function openReply(id) {
+ // Swap out the reply link for the hide link
+ $('#rl' + id).hide();
+ $('#cr' + id).show();
+
+ // Add the reply li to the children ul.
+ var div = $(renderTemplate(replyTemplate, {id: id})).hide();
+ $('#cl' + id)
+ .prepend(div)
+ // Setup the submit handler for the reply form.
+ .find('#rf' + id)
+ .submit(function(event) {
+ event.preventDefault();
+ addComment($('#rf' + id));
+ closeReply(id);
+ })
+ .find('input[type=button]')
+ .click(function() {
+ closeReply(id);
+ });
+ div.slideDown('fast', function() {
+ $('#rf' + id).find('textarea').focus();
+ });
+ }
+
+ /**
+ * Close the reply form opened with openReply.
+ */
+ function closeReply(id) {
+ // Remove the reply div from the DOM.
+ $('#rd' + id).slideUp('fast', function() {
+ $(this).remove();
+ });
+
+ // Swap out the hide link for the reply link
+ $('#cr' + id).hide();
+ $('#rl' + id).show();
+ }
+
+ /**
+ * Recursively sort a tree of comments using the comp comparator.
+ */
+ function sortComments(comments) {
+ comments.sort(comp);
+ $.each(comments, function() {
+ this.children = sortComments(this.children);
+ });
+ return comments;
+ }
+
+ /**
+ * Get the children comments from a ul. If recursive is true,
+ * recursively include childrens' children.
+ */
+ function getChildren(ul, recursive) {
+ var children = [];
+ ul.children().children("[id^='cd']")
+ .each(function() {
+ var comment = $(this).data('comment');
+ if (recursive)
+ comment.children = getChildren($(this).find('#cl' + comment.id), true);
+ children.push(comment);
+ });
+ return children;
+ }
+
+ /** Create a div to display a comment in. */
+ function createCommentDiv(comment) {
+ if (!comment.displayed && !opts.moderator) {
+ return $('<div class="moderate">Thank you! Your comment will show up '
+ + 'once it is has been approved by a moderator.</div>');
+ }
+ // Prettify the comment rating.
+ comment.pretty_rating = comment.rating + ' point' +
+ (comment.rating == 1 ? '' : 's');
+ // Make a class (for displaying not yet moderated comments differently)
+ comment.css_class = comment.displayed ? '' : ' moderate';
+ // Create a div for this comment.
+ var context = $.extend({}, opts, comment);
+ var div = $(renderTemplate(commentTemplate, context));
+
+ // If the user has voted on this comment, highlight the correct arrow.
+ if (comment.vote) {
+ var direction = (comment.vote == 1) ? 'u' : 'd';
+ div.find('#' + direction + 'v' + comment.id).hide();
+ div.find('#' + direction + 'u' + comment.id).show();
+ }
+
+ if (opts.moderator || comment.text != '[deleted]') {
+ div.find('a.reply').show();
+ if (comment.proposal_diff)
+ div.find('#sp' + comment.id).show();
+ if (opts.moderator && !comment.displayed)
+ div.find('#cm' + comment.id).show();
+ if (opts.moderator || (opts.username == comment.username))
+ div.find('#dc' + comment.id).show();
+ }
+ return div;
+ }
+
+ /**
+ * A simple template renderer. Placeholders such as <%id%> are replaced
+ * by context['id'] with items being escaped. Placeholders such as <#id#>
+ * are not escaped.
+ */
+ function renderTemplate(template, context) {
+ var esc = $(document.createElement('div'));
+
+ function handle(ph, escape) {
+ var cur = context;
+ $.each(ph.split('.'), function() {
+ cur = cur[this];
+ });
+ return escape ? esc.text(cur || "").html() : cur;
+ }
+
+ return template.replace(/<([%#])([\w\.]*)\1>/g, function() {
+ return handle(arguments[2], arguments[1] == '%' ? true : false);
+ });
+ }
+
+ /** Flash an error message briefly. */
+ function showError(message) {
+ $(document.createElement('div')).attr({'class': 'popup-error'})
+ .append($(document.createElement('div'))
+ .attr({'class': 'error-message'}).text(message))
+ .appendTo('body')
+ .fadeIn("slow")
+ .delay(2000)
+ .fadeOut("slow");
+ }
+
+ /** Add a link the user uses to open the comments popup. */
+ $.fn.comment = function() {
+ return this.each(function() {
+ var id = $(this).attr('id').substring(1);
+ var count = COMMENT_METADATA[id];
+ var title = count + ' comment' + (count == 1 ? '' : 's');
+ var image = count > 0 ? opts.commentBrightImage : opts.commentImage;
+ var addcls = count == 0 ? ' nocomment' : '';
+ $(this)
+ .append(
+ $(document.createElement('a')).attr({
+ href: '#',
+ 'class': 'sphinx-comment-open' + addcls,
+ id: 'ao' + id
+ })
+ .append($(document.createElement('img')).attr({
+ src: image,
+ alt: 'comment',
+ title: title
+ }))
+ .click(function(event) {
+ event.preventDefault();
+ show($(this).attr('id').substring(2));
+ })
+ )
+ .append(
+ $(document.createElement('a')).attr({
+ href: '#',
+ 'class': 'sphinx-comment-close hidden',
+ id: 'ah' + id
+ })
+ .append($(document.createElement('img')).attr({
+ src: opts.closeCommentImage,
+ alt: 'close',
+ title: 'close'
+ }))
+ .click(function(event) {
+ event.preventDefault();
+ hide($(this).attr('id').substring(2));
+ })
+ );
+ });
+ };
+
+ var opts = {
+ processVoteURL: '/_process_vote',
+ addCommentURL: '/_add_comment',
+ getCommentsURL: '/_get_comments',
+ acceptCommentURL: '/_accept_comment',
+ deleteCommentURL: '/_delete_comment',
+ commentImage: '/static/_static/comment.png',
+ closeCommentImage: '/static/_static/comment-close.png',
+ loadingImage: '/static/_static/ajax-loader.gif',
+ commentBrightImage: '/static/_static/comment-bright.png',
+ upArrow: '/static/_static/up.png',
+ downArrow: '/static/_static/down.png',
+ upArrowPressed: '/static/_static/up-pressed.png',
+ downArrowPressed: '/static/_static/down-pressed.png',
+ voting: false,
+ moderator: false
+ };
+
+ if (typeof COMMENT_OPTIONS != "undefined") {
+ opts = jQuery.extend(opts, COMMENT_OPTIONS);
+ }
+
+ var popupTemplate = '\
+ <div class="sphinx-comments" id="sc<%id%>">\
+ <p class="sort-options">\
+ Sort by:\
+ <a href="#" class="sort-option byrating">best rated</a>\
+ <a href="#" class="sort-option byascage">newest</a>\
+ <a href="#" class="sort-option byage">oldest</a>\
+ </p>\
+ <div class="comment-header">Comments</div>\
+ <div class="comment-loading" id="cn<%id%>">\
+ loading comments... <img src="<%loadingImage%>" alt="" /></div>\
+ <ul id="cl<%id%>" class="comment-ul"></ul>\
+ <div id="ca<%id%>">\
+ <p class="add-a-comment">Add a comment\
+ (<a href="#" class="comment-markup" id="ab<%id%>">markup</a>):</p>\
+ <div class="comment-markup-box" id="mb<%id%>">\
+ reStructured text markup: <i>*emph*</i>, <b>**strong**</b>, \
+ <code>``code``</code>, \
+ code blocks: <code>::</code> and an indented block after blank line</div>\
+ <form method="post" id="cf<%id%>" class="comment-form" action="">\
+ <textarea name="comment" cols="80"></textarea>\
+ <p class="propose-button">\
+ <a href="#" id="pc<%id%>" class="show-propose-change">\
+ Propose a change ▹\
+ </a>\
+ <a href="#" id="hc<%id%>" class="hide-propose-change">\
+ Propose a change ▿\
+ </a>\
+ </p>\
+ <textarea name="proposal" id="pt<%id%>" cols="80"\
+ spellcheck="false"></textarea>\
+ <input type="submit" value="Add comment" />\
+ <input type="hidden" name="node" value="<%id%>" />\
+ <input type="hidden" name="parent" value="" />\
+ </form>\
+ </div>\
+ </div>';
+
+ var commentTemplate = '\
+ <div id="cd<%id%>" class="sphinx-comment<%css_class%>">\
+ <div class="vote">\
+ <div class="arrow">\
+ <a href="#" id="uv<%id%>" class="vote" title="vote up">\
+ <img src="<%upArrow%>" />\
+ </a>\
+ <a href="#" id="uu<%id%>" class="un vote" title="vote up">\
+ <img src="<%upArrowPressed%>" />\
+ </a>\
+ </div>\
+ <div class="arrow">\
+ <a href="#" id="dv<%id%>" class="vote" title="vote down">\
+ <img src="<%downArrow%>" id="da<%id%>" />\
+ </a>\
+ <a href="#" id="du<%id%>" class="un vote" title="vote down">\
+ <img src="<%downArrowPressed%>" />\
+ </a>\
+ </div>\
+ </div>\
+ <div class="comment-content">\
+ <p class="tagline comment">\
+ <span class="user-id"><%username%></span>\
+ <span class="rating"><%pretty_rating%></span>\
+ <span class="delta"><%time.delta%></span>\
+ </p>\
+ <div class="comment-text comment"><#text#></div>\
+ <p class="comment-opts comment">\
+ <a href="#" class="reply hidden" id="rl<%id%>">reply ▹</a>\
+ <a href="#" class="close-reply" id="cr<%id%>">reply ▿</a>\
+ <a href="#" id="sp<%id%>" class="show-proposal">proposal ▹</a>\
+ <a href="#" id="hp<%id%>" class="hide-proposal">proposal ▿</a>\
+ <a href="#" id="dc<%id%>" class="delete-comment hidden">delete</a>\
+ <span id="cm<%id%>" class="moderation hidden">\
+ <a href="#" id="ac<%id%>" class="accept-comment">accept</a>\
+ </span>\
+ </p>\
+ <pre class="proposal" id="pr<%id%>">\
+<#proposal_diff#>\
+ </pre>\
+ <ul class="comment-children" id="cl<%id%>"></ul>\
+ </div>\
+ <div class="clearleft"></div>\
+ </div>\
+ </div>';
+
+ var replyTemplate = '\
+ <li>\
+ <div class="reply-div" id="rd<%id%>">\
+ <form id="rf<%id%>">\
+ <textarea name="comment" cols="80"></textarea>\
+ <input type="submit" value="Add reply" />\
+ <input type="button" value="Cancel" />\
+ <input type="hidden" name="parent" value="<%id%>" />\
+ <input type="hidden" name="node" value="" />\
+ </form>\
+ </div>\
+ </li>';
+
+ $(document).ready(function() {
+ init();
+ });
+})(jQuery);
+
+$(document).ready(function() {
+ // add comment anchors for all paragraphs that are commentable
+ $('.sphinx-has-comment').comment();
+
+ // highlight search words in search results
+ $("div.context").each(function() {
+ var params = $.getQueryParameters();
+ var terms = (params.q) ? params.q[0].split(/\s+/) : [];
+ var result = $(this);
+ $.each(terms, function() {
+ result.highlightText(this.toLowerCase(), 'highlighted');
+ });
+ });
+
+ // directly open comment window if requested
+ var anchor = document.location.hash;
+ if (anchor.substring(0, 9) == '#comment-') {
+ $('#ao' + anchor.substring(9)).click();
+ document.location.hash = '#s' + anchor.substring(9);
+ }
+});
diff --git a/doc/build/doctrees/documentation.doctree b/doc/build/doctrees/documentation.doctree
new file mode 100644
index 0000000..cea3e4e
Binary files /dev/null and b/doc/build/doctrees/documentation.doctree differ
diff --git a/doc/build/doctrees/environment.pickle b/doc/build/doctrees/environment.pickle
new file mode 100644
index 0000000..0e349c6
Binary files /dev/null and b/doc/build/doctrees/environment.pickle differ
diff --git a/doc/build/documentation.html b/doc/build/documentation.html
new file mode 100644
index 0000000..8dfe1da
--- /dev/null
+++ b/doc/build/documentation.html
@@ -0,0 +1,289 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>Welcome to Umap’s documentation! — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: './',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="_static/jquery.js"></script>
+ <script type="text/javascript" src="_static/underscore.js"></script>
+ <script type="text/javascript" src="_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="#" />
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+ <div class="section" id="welcome-to-umap-s-documentation">
+<h1>Welcome to Umap’s documentation!<a class="headerlink" href="#welcome-to-umap-s-documentation" title="Permalink to this headline">¶</a></h1>
+<p>Contents:</p>
+<div class="toctree-wrapper compound">
+<ul class="simple">
+</ul>
+</div>
+<div class="section" id="introduction">
+<h2>Introduction<a class="headerlink" href="#introduction" title="Permalink to this headline">¶</a></h2>
+<p><strong>The free umap software package efficiently identifies uniquely mappable regions of any genome.
+Its Bismap extension identifies mappability of the bisulfite converted genome (methylome).</strong></p>
+<p>the mappability of a genome for a given read length <em>k</em>.
+First, it generates all possible <em>k</em>-mers of the genome.
+Second, it maps these unique <em>k</em>-mers to the genome with <a class="reference external" href="http://bowtie-bio.sourceforge.net/index.shtml">Bowtie</a> version 1.1.0.
+Third, Umap marks the start position of each <em>k</em>-mer that aligns to only one region in the genome.
+Umap repeats these steps for a range of different <em>k</em>-mers and stores the data of each chromosome
+in a binary vector <em>X</em> with the same length as the chromosome’s sequence.
+For read length <em>k</em>, <span class="math">\(X_i = 1\)</span> means that the sequence starting at <span class="math">\(X_i\)</span> and ending
+at <span class="math">\(X_{i+k}\)</span> is uniquely mappable on the forward strand.
+Since we align to both strands of the genome, the reverse complement of this same sequence
+starting at <span class="math">\(X_{i+k}\)</span> on the reverse strand is also uniquely mappable.
+<span class="math">\(X_i = 0\)</span> means that the sequence starting at <span class="math">\(X_i\)</span> and ending at
+<span class="math">\(X_{i+k}\)</span> can be mapped to at least two different regions in the genome.</p>
+</div>
+<div class="section" id="mappability-of-the-bisulfite-converted-genome">
+<h2>Mappability of the bisulfite-converted genome<a class="headerlink" href="#mappability-of-the-bisulfite-converted-genome" title="Permalink to this headline">¶</a></h2>
+<p>To identify the single-read mappability of a bisulfite-converted genome,
+we create two altered genome sequences.
+In the first sequence, we convert all cytosines to thymine (C <span class="math">\(\rightarrow\)</span> T).
+In the other sequence we convert all guanines to adenine (G <span class="math">\(\rightarrow\)</span> A).
+Our approach follows those of <a class="reference external" href="http://www.bioinformatics.babraham.ac.uk/projects/bismark/">Bismark</a>
+and <a class="reference external" href="https://github.com/brentp/bwa-meth">BWA-meth</a>.
+We convert the genome sequence this way because bisulfite
+treatment converts un-methylated cytosine to uracil which is read as thymine.
+Similarly the guanine that is base-pairing with the un-methylated cytosine in
+reverse strand converts to adenine. However these two conversions never occur
+at the same time on the same read. We identify the uniquely mappable regions
+of these two genomes separately, and then combine the data to represent the
+single-read mappability of the forward and reverse strands in the bisulfite-converted genome.</p>
+<p>Bismap requires special handling of reverse complementation of C <span class="math">\(\rightarrow\)</span> T
+or G <span class="math">\(\rightarrow\)</span> A converted genomes.
+Conversion of C <span class="math">\(\rightarrow\)</span> T on the sequence AATTCCGG produces AATT <strong>TT</strong> GG.
+In the Bowtie index, the reverse complement would be CCAAAATT.
+However for the purpose of identifying the mappability of the bisulfite-converted genome,
+we expect the reverse complement to be TTGGAA <strong>TT</strong>. The reason is that both forward and reverse
+strands undergo bisulfite treatment simultaneously. There is no DNA replication after bisulfite treatment.
+To handle this issue, Bismap creates its own reverse complemented chromosomes and suppresses Bowtie’s usual reverse complement mapping.</p>
+<p>Umap and Bismap each take approximately 200 CPU hours to run for a given read length. This can be parallelized in a computing cluster over 400 cores to take only 30 minutes.</p>
+<div class="section" id="measures-of-mappability">
+<h3>Measures of mappability<a class="headerlink" href="#measures-of-mappability" title="Permalink to this headline">¶</a></h3>
+<p>Umap efficiently identifies the single-read mappability of any genome for a
+range of sequencing read lengths. The single-read mappability of a genomic
+region is a fraction of that region which overlaps with at least one uniquely
+mappable <em>k</em>-mer. The Bismap extension of Umap produces the single-read mappability
+of a bisulfite-converted genome. Both Umap and Bismap produce an integer vector for
+each chromosome that efficiently defines the mappability for any region and can be
+converted to a browser extensible data (BED) file. In addition to single-read mappability,
+we can measure the mappability of a genomic region by another approach. To quantify
+the single-read mappability of a given genomic region, we measure the fraction of
+potential uniquely mappable reads in that region. A region, however, can have 100% single-read
+mappability, but in practice require a high coverage sequencing to properly identify that region.
+For example, a 1 kbp region with 100% single-read mappability can be mappable due to a
+minimum of 10 unique 100-mers that none of them overlap or a maximum of 1100 unique 100-mers
+that highly overlap. Therefore, we define the multi-read mappability, the probability that a
+randomly selected read of length k in a given region is uniquely mappable. For the genomic
+region <span class="math">\(G_{i:j}\)</span> starting at <em>i</em> and ending at <em>j</em>, there are <span class="math">\(j - i + k + 1\)</span>
+<em>k</em>-mers that overlap with <span class="math">\(G_{i:j}\)</span>.
+The multi-read mappability of <span class="math">\(G_{i:j}\)</span> is the fraction of those <em>k</em>-mers that are uniquely mappable.</p>
+</div>
+</div>
+<div class="section" id="quick-start">
+<h2>Quick start<a class="headerlink" href="#quick-start" title="Permalink to this headline">¶</a></h2>
+<p>We have tested Umap installation on a CentOS system using python 2.7.11.
+Bismap requires numpy and pandas and it uses other python modules such as:</p>
+<ul class="simple">
+<li>gzip</li>
+<li>os</li>
+<li>re</li>
+<li>subprocess</li>
+</ul>
+<p>Umap uses mercurial version control. Make sure that mercurial (hg) is installed.
+Download Umap to the directory of your python packages using:</p>
+<div class="highlight-default"><div class="highlight"><pre><span class="n">hg</span> <span class="n">clone</span> <span class="n">https</span><span class="p">:</span><span class="o">//</span><span class="n">bitbucket</span><span class="o">.</span><span class="n">org</span><span class="o">/</span><span class="n">hoffmanlab</span><span class="o">/</span><span class="n">umap</span>
+<span class="n">cd</span> <span class="n">umap</span>
+<span class="n">python</span> <span class="n">setup</span><span class="o">.</span><span class="n">py</span> <span class="n">install</span>
+</pre></div>
+</div>
+<p>Now we will run a test using a wrapper in the umap directory called ubismap.py
+and a toy genome stored under umap/data</p>
+<div class="highlight-default"><div class="highlight"><pre>cd umap
+python ubismap.py data/genome.fa data/chrsize.tsv data/TestGenomeMappability all.q $BOWTIRDIR/bowtie-build --kmer 8 12 -write_script test_run.sh
+sh test_run.sh
+</pre></div>
+</div>
+<p>The scripts that are produced by <strong>ubismap.py</strong> assume that you are using a Sun Grid Engine computing cluster.
+You can use parameters of this script to adjust it to your own system. You may need to manually edit this file
+because many of the SGE settings are very different than other computing clusters.
+However, all of the Umap modules accept <em>-job_id</em> which allows you to use the modules without a cluster or if
+your cluster does not support job arrays.</p>
+<p>Basically, the job array saves an environmental variable (defined by (<em>-var_id</em>) that Umap uses for paralellizing processes.
+You can run the modules in a for loop and set the <em>-job_id</em> manually.
+For example, in order to find <em>k</em>-mers of a genome with 10 million base pairs, the get_kmers
+and run_bowtie modules each need to be executed with -job_ids ranging between 1 to 10.</p>
+</div>
+<div class="section" id="module-umap">
+<span id="get-k-mers"></span><h2>Get <em>k</em>-mers<a class="headerlink" href="#module-umap" title="Permalink to this headline">¶</a></h2>
+<dl class="class">
+<dt id="umap.GetKmers">
+<em class="property">class </em><code class="descclassname">umap.</code><code class="descname">GetKmers</code><span class="sig-paren">(</span><em>out_dir</em>, <em>kmer</em>, <em>job_id</em>, <em>chr_dir</em>, <em>chrsize_path</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/umap/get_kmers.html#GetKmers"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#umap.GetKmers" title="Permalink to this definition">¶</a></dt>
+<dd></dd></dl>
+
+</div>
+<div class="section" id="run-bowtie">
+<h2>Run Bowtie<a class="headerlink" href="#run-bowtie" title="Permalink to this headline">¶</a></h2>
+<dl class="class">
+<dt id="umap.BowtieWrapper">
+<em class="property">class </em><code class="descclassname">umap.</code><code class="descname">BowtieWrapper</code><span class="sig-paren">(</span><em>kmer_dir</em>, <em>bowtie_dir</em>, <em>index_dir</em>, <em>index_name</em>, <em>job_id</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/umap/run_bowtie.html#BowtieWrapper"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#umap.BowtieWrapper" title="Permalink to this definition">¶</a></dt>
+<dd></dd></dl>
+
+</div>
+<div class="section" id="merge-bowtie-outputs">
+<h2>Merge bowtie outputs<a class="headerlink" href="#merge-bowtie-outputs" title="Permalink to this headline">¶</a></h2>
+<dl class="class">
+<dt id="umap.UnifyBowtie">
+<em class="property">class </em><code class="descclassname">umap.</code><code class="descname">UnifyBowtie</code><span class="sig-paren">(</span><em>bowtie_outdir</em>, <em>chrsize_path</em>, <em>job_id</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/umap/unify_bowtie.html#UnifyBowtie"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#umap.UnifyBowtie" title="Permalink to this definition">¶</a></dt>
+<dd></dd></dl>
+
+</div>
+<div class="section" id="merge-data-of-various-k-mers">
+<h2>Merge data of various <em>k</em>-mers<a class="headerlink" href="#merge-data-of-various-k-mers" title="Permalink to this headline">¶</a></h2>
+<dl class="class">
+<dt id="umap.CombineUmaps">
+<em class="property">class </em><code class="descclassname">umap.</code><code class="descname">CombineUmaps</code><span class="sig-paren">(</span><em>kmer_dir</em>, <em>chrsize_path</em>, <em>out_dir</em>, <em>job_id</em>, <em>kmer_dir_2</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/umap/combine_umaps.html#CombineUmaps"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#umap.CombineUmaps" title="Permalink to this definition">¶</a></dt>
+<dd></dd></dl>
+
+</div>
+<div class="section" id="convert-numeric-vectors-to-bed-and-wiggle">
+<h2>Convert numeric vectors to BED and Wiggle<a class="headerlink" href="#convert-numeric-vectors-to-bed-and-wiggle" title="Permalink to this headline">¶</a></h2>
+<dl class="class">
+<dt id="umap.Int8Handler">
+<em class="property">class </em><code class="descclassname">umap.</code><code class="descname">Int8Handler</code><span class="sig-paren">(</span><em>in_dir</em>, <em>out_dir</em>, <em>C2T</em>, <em>G2A</em>, <em>chrsize_path</em><span class="sig-paren">)</span><a class="reference internal" href="_modules/umap/uint8_to_bed.html#Int8Handler"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#umap.Int8Handler" title="Permalink to this definition">¶</a></dt>
+<dd></dd></dl>
+
+<dl class="method">
+<dt id="umap.Int8Handler.write_beds">
+<code class="descclassname">Int8Handler.</code><code class="descname">write_beds</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/umap/uint8_to_bed.html#Int8Handler.write_beds"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#umap.Int8Handler.write_beds" title="Permalink to this definition">¶</a></dt>
+<dd></dd></dl>
+
+<dl class="method">
+<dt id="umap.Int8Handler.write_as_wig">
+<code class="descclassname">Int8Handler.</code><code class="descname">write_as_wig</code><span class="sig-paren">(</span><span class="sig-paren">)</span><a class="reference internal" href="_modules/umap/uint8_to_bed.html#Int8Handler.write_as_wig"><span class="viewcode-link">[source]</span></a><a class="headerlink" href="#umap.Int8Handler.write_as_wig" title="Permalink to this definition">¶</a></dt>
+<dd></dd></dl>
+
+</div>
+<div class="section" id="requesting-genomes">
+<h2>Requesting Genomes<a class="headerlink" href="#requesting-genomes" title="Permalink to this headline">¶</a></h2>
+<p>In case you need these data for other genomes and do not have access to a Sun Grid Engine computing cluster,
+we may accept to do this for you.
+Please contact the software maintainer by email and we will do our best to assist you as soon as possible.</p>
+</div>
+<div class="section" id="contact-support-and-questions">
+<h2>Contact, support and questions<a class="headerlink" href="#contact-support-and-questions" title="Permalink to this headline">¶</a></h2>
+<p>For support of Umap, please user our <a class="reference external" href="https://groups.google.com/forum/#!forum/ubismap">mailing list</a>.
+Specifically, if you want to report a bug or request a feature,
+please do so using
+the <a class="reference external" href="https://bitbucket.org/hoffmanlab/umap/issues">Umap issue tracker</a>.
+We are interested in all comments on the package,
+and the ease of use of installation and documentation.</p>
+</div>
+</div>
+<div class="section" id="indices-and-tables">
+<h1>Indices and tables<a class="headerlink" href="#indices-and-tables" title="Permalink to this headline">¶</a></h1>
+<ul class="simple">
+<li><a class="reference internal" href="genindex.html"><span class="std std-ref">Index</span></a></li>
+<li><a class="reference internal" href="py-modindex.html"><span class="std std-ref">Module Index</span></a></li>
+<li><a class="reference internal" href="search.html"><span class="std std-ref">Search Page</span></a></li>
+</ul>
+</div>
+
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper">
+ <h3><a href="#">Table Of Contents</a></h3>
+ <ul>
+<li><a class="reference internal" href="#">Welcome to Umap’s documentation!</a><ul>
+<li><a class="reference internal" href="#introduction">Introduction</a></li>
+<li><a class="reference internal" href="#mappability-of-the-bisulfite-converted-genome">Mappability of the bisulfite-converted genome</a><ul>
+<li><a class="reference internal" href="#measures-of-mappability">Measures of mappability</a></li>
+</ul>
+</li>
+<li><a class="reference internal" href="#quick-start">Quick start</a></li>
+<li><a class="reference internal" href="#module-umap">Get <em>k</em>-mers</a></li>
+<li><a class="reference internal" href="#run-bowtie">Run Bowtie</a></li>
+<li><a class="reference internal" href="#merge-bowtie-outputs">Merge bowtie outputs</a></li>
+<li><a class="reference internal" href="#merge-data-of-various-k-mers">Merge data of various <em>k</em>-mers</a></li>
+<li><a class="reference internal" href="#convert-numeric-vectors-to-bed-and-wiggle">Convert numeric vectors to BED and Wiggle</a></li>
+<li><a class="reference internal" href="#requesting-genomes">Requesting Genomes</a></li>
+<li><a class="reference internal" href="#contact-support-and-questions">Contact, support and questions</a></li>
+</ul>
+</li>
+<li><a class="reference internal" href="#indices-and-tables">Indices and tables</a></li>
+</ul>
+<div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="#">Documentation overview</a><ul>
+ </ul></li>
+</ul>
+</div>
+ <div role="note" aria-label="source link">
+ <h3>This Page</h3>
+ <ul class="this-page-menu">
+ <li><a href="_sources/documentation.txt"
+ rel="nofollow">Show Source</a></li>
+ </ul>
+ </div>
+<div id="searchbox" style="display: none" role="search">
+ <h3>Quick search</h3>
+ <form class="search" action="search.html" method="get">
+ <input type="text" name="q" />
+ <input type="submit" value="Go" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+ </form>
+</div>
+<script type="text/javascript">$('#searchbox').show(0);</script>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ |
+ <a href="_sources/documentation.txt"
+ rel="nofollow">Page source</a>
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/genindex.html b/doc/build/genindex.html
new file mode 100644
index 0000000..9db8022
--- /dev/null
+++ b/doc/build/genindex.html
@@ -0,0 +1,168 @@
+
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>Index — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: './',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="_static/jquery.js"></script>
+ <script type="text/javascript" src="_static/underscore.js"></script>
+ <script type="text/javascript" src="_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="documentation.html" />
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+
+<h1 id="index">Index</h1>
+
+<div class="genindex-jumpbox">
+ <a href="#B"><strong>B</strong></a>
+ | <a href="#C"><strong>C</strong></a>
+ | <a href="#G"><strong>G</strong></a>
+ | <a href="#I"><strong>I</strong></a>
+ | <a href="#U"><strong>U</strong></a>
+ | <a href="#W"><strong>W</strong></a>
+
+</div>
+<h2 id="B">B</h2>
+<table style="width: 100%" class="indextable genindextable"><tr>
+ <td style="width: 33%" valign="top"><dl>
+
+ <dt><a href="documentation.html#umap.BowtieWrapper">BowtieWrapper (class in umap)</a>
+ </dt>
+
+ </dl></td>
+</tr></table>
+
+<h2 id="C">C</h2>
+<table style="width: 100%" class="indextable genindextable"><tr>
+ <td style="width: 33%" valign="top"><dl>
+
+ <dt><a href="documentation.html#umap.CombineUmaps">CombineUmaps (class in umap)</a>
+ </dt>
+
+ </dl></td>
+</tr></table>
+
+<h2 id="G">G</h2>
+<table style="width: 100%" class="indextable genindextable"><tr>
+ <td style="width: 33%" valign="top"><dl>
+
+ <dt><a href="documentation.html#umap.GetKmers">GetKmers (class in umap)</a>
+ </dt>
+
+ </dl></td>
+</tr></table>
+
+<h2 id="I">I</h2>
+<table style="width: 100%" class="indextable genindextable"><tr>
+ <td style="width: 33%" valign="top"><dl>
+
+ <dt><a href="documentation.html#umap.Int8Handler">Int8Handler (class in umap)</a>
+ </dt>
+
+ </dl></td>
+</tr></table>
+
+<h2 id="U">U</h2>
+<table style="width: 100%" class="indextable genindextable"><tr>
+ <td style="width: 33%" valign="top"><dl>
+
+ <dt><a href="documentation.html#module-umap">umap (module)</a>
+ </dt>
+
+ </dl></td>
+ <td style="width: 33%" valign="top"><dl>
+
+ <dt><a href="documentation.html#umap.UnifyBowtie">UnifyBowtie (class in umap)</a>
+ </dt>
+
+ </dl></td>
+</tr></table>
+
+<h2 id="W">W</h2>
+<table style="width: 100%" class="indextable genindextable"><tr>
+ <td style="width: 33%" valign="top"><dl>
+
+ <dt><a href="documentation.html#umap.Int8Handler.write_as_wig">write_as_wig() (umap.Int8Handler method)</a>
+ </dt>
+
+ </dl></td>
+ <td style="width: 33%" valign="top"><dl>
+
+ <dt><a href="documentation.html#umap.Int8Handler.write_beds">write_beds() (umap.Int8Handler method)</a>
+ </dt>
+
+ </dl></td>
+</tr></table>
+
+
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper">
+
+ <div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="documentation.html">Documentation overview</a><ul>
+ </ul></li>
+</ul>
+</div>
+
+<div id="searchbox" style="display: none" role="search">
+ <h3>Quick search</h3>
+ <form class="search" action="search.html" method="get">
+ <input type="text" name="q" />
+ <input type="submit" value="Go" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+ </form>
+</div>
+<script type="text/javascript">$('#searchbox').show(0);</script>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/latex/Makefile b/doc/build/latex/Makefile
new file mode 100644
index 0000000..d748006
--- /dev/null
+++ b/doc/build/latex/Makefile
@@ -0,0 +1,78 @@
+# Makefile for Sphinx LaTeX output
+
+ALLDOCS = $(basename $(wildcard *.tex))
+ALLPDF = $(addsuffix .pdf,$(ALLDOCS))
+ALLDVI = $(addsuffix .dvi,$(ALLDOCS))
+
+# Prefix for archive names
+ARCHIVEPRREFIX =
+# Additional LaTeX options
+LATEXOPTS =
+# format: pdf or dvi
+FMT = pdf
+
+LATEX = latex
+PDFLATEX = pdflatex
+MAKEINDEX = makeindex
+
+all: $(ALLPDF)
+all-pdf: $(ALLPDF)
+all-dvi: $(ALLDVI)
+all-ps: all-dvi
+ for f in *.dvi; do dvips $$f; done
+
+all-pdf-ja:
+ for f in *.pdf *.png *.gif *.jpg *.jpeg; do extractbb $$f; done
+ for f in *.tex; do platex -kanji=utf8 $(LATEXOPTS) $$f; done
+ for f in *.tex; do platex -kanji=utf8 $(LATEXOPTS) $$f; done
+ for f in *.tex; do platex -kanji=utf8 $(LATEXOPTS) $$f; done
+ -for f in *.idx; do mendex -U -f -d "`basename $$f .idx`.dic" -s python.ist $$f; done
+ for f in *.tex; do platex -kanji=utf8 $(LATEXOPTS) $$f; done
+ for f in *.tex; do platex -kanji=utf8 $(LATEXOPTS) $$f; done
+ for f in *.dvi; do dvipdfmx $$f; done
+
+zip: all-$(FMT)
+ mkdir $(ARCHIVEPREFIX)docs-$(FMT)
+ cp $(ALLPDF) $(ARCHIVEPREFIX)docs-$(FMT)
+ zip -q -r -9 $(ARCHIVEPREFIX)docs-$(FMT).zip $(ARCHIVEPREFIX)docs-$(FMT)
+ rm -r $(ARCHIVEPREFIX)docs-$(FMT)
+
+tar: all-$(FMT)
+ mkdir $(ARCHIVEPREFIX)docs-$(FMT)
+ cp $(ALLPDF) $(ARCHIVEPREFIX)docs-$(FMT)
+ tar cf $(ARCHIVEPREFIX)docs-$(FMT).tar $(ARCHIVEPREFIX)docs-$(FMT)
+ rm -r $(ARCHIVEPREFIX)docs-$(FMT)
+
+gz: tar
+ gzip -9 < $(ARCHIVEPREFIX)docs-$(FMT).tar > $(ARCHIVEPREFIX)docs-$(FMT).tar.gz
+
+bz2: tar
+ bzip2 -9 -k $(ARCHIVEPREFIX)docs-$(FMT).tar
+
+xz: tar
+ xz -9 -k $(ARCHIVEPREFIX)docs-$(FMT).tar
+
+# The number of LaTeX runs is quite conservative, but I don't expect it
+# to get run often, so the little extra time won't hurt.
+%.dvi: %.tex
+ $(LATEX) $(LATEXOPTS) '$<'
+ $(LATEX) $(LATEXOPTS) '$<'
+ $(LATEX) $(LATEXOPTS) '$<'
+ -$(MAKEINDEX) -s python.ist '$(basename $<).idx'
+ $(LATEX) $(LATEXOPTS) '$<'
+ $(LATEX) $(LATEXOPTS) '$<'
+
+%.pdf: %.tex
+ $(PDFLATEX) $(LATEXOPTS) '$<'
+ $(PDFLATEX) $(LATEXOPTS) '$<'
+ $(PDFLATEX) $(LATEXOPTS) '$<'
+ -$(MAKEINDEX) -s python.ist '$(basename $<).idx'
+ $(PDFLATEX) $(LATEXOPTS) '$<'
+ $(PDFLATEX) $(LATEXOPTS) '$<'
+
+clean:
+ rm -f *.log *.ind *.aux *.toc *.syn *.idx *.out *.ilg *.pla *.ps *.tar *.tar.gz *.tar.bz2 *.tar.xz $(ALLPDF) $(ALLDVI)
+
+.PHONY: all all-pdf all-dvi all-ps clean zip tar gz bz2 xz
+.PHONY: all-pdf-ja
+
diff --git a/doc/build/latex/Umap.aux b/doc/build/latex/Umap.aux
new file mode 100644
index 0000000..39ad4c7
--- /dev/null
+++ b/doc/build/latex/Umap.aux
@@ -0,0 +1,91 @@
+\relax
+\providecommand\hyper at newdestlabel[2]{}
+\providecommand\HyperFirstAtBeginDocument{\AtBeginDocument}
+\HyperFirstAtBeginDocument{\ifx\hyper at anchor\@undefined
+\global\let\oldcontentsline\contentsline
+\gdef\contentsline#1#2#3#4{\oldcontentsline{#1}{#2}{#3}}
+\global\let\oldnewlabel\newlabel
+\gdef\newlabel#1#2{\newlabelxx{#1}#2}
+\gdef\newlabelxx#1#2#3#4#5#6{\oldnewlabel{#1}{{#2}{#3}}}
+\AtEndDocument{\ifx\hyper at anchor\@undefined
+\let\contentsline\oldcontentsline
+\let\newlabel\oldnewlabel
+\fi}
+\fi}
+\global\let\hyper at last\relax
+\gdef\HyperFirstAtBeginDocument#1{#1}
+\providecommand\HyField at AuxAddToFields[1]{}
+\providecommand\HyField at AuxAddToCoFields[2]{}
+\select at language{english}
+\@writefile{toc}{\select at language{english}}
+\@writefile{lof}{\select at language{english}}
+\@writefile{lot}{\select at language{english}}
+\newlabel{documentation::doc}{{}{1}{}{section*.2}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {1}Introduction}{3}{chapter.1}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:introduction}{{1}{3}{Introduction}{chapter.1}{}}
+\newlabel{documentation:welcome-to-umap-s-documentation}{{1}{3}{Introduction}{chapter.1}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {2}Mappability of the bisulfite-converted genome}{5}{chapter.2}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:mappability-of-the-bisulfite-converted-genome}{{2}{5}{Mappability of the bisulfite-converted genome}{chapter.2}{}}
+\@writefile{toc}{\contentsline {section}{\numberline {2.1}Measures of mappability}{5}{section.2.1}}
+\newlabel{documentation:measures-of-mappability}{{2.1}{5}{Measures of mappability}{section.2.1}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {3}Quick start}{7}{chapter.3}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:quick-start}{{3}{7}{Quick start}{chapter.3}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {4}Get \emph {k}-mers}{9}{chapter.4}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:get-k-mers}{{4}{9}{Get \emph {k}-mers}{chapter.4}{}}
+\newlabel{documentation:module-umap}{{4}{9}{Get \emph {k}-mers}{chapter.4}{}}
+\newlabel{documentation:umap.GetKmers}{{4}{9}{Get \emph {k}-mers}{section*.3}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {5}Run Bowtie}{11}{chapter.5}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:run-bowtie}{{5}{11}{Run Bowtie}{chapter.5}{}}
+\newlabel{documentation:umap.BowtieWrapper}{{5}{11}{Run Bowtie}{section*.4}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {6}Merge bowtie outputs}{13}{chapter.6}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:merge-bowtie-outputs}{{6}{13}{Merge bowtie outputs}{chapter.6}{}}
+\newlabel{documentation:umap.UnifyBowtie}{{6}{13}{Merge bowtie outputs}{section*.5}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {7}Merge data of various \emph {k}-mers}{15}{chapter.7}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:merge-data-of-various-k-mers}{{7}{15}{Merge data of various \emph {k}-mers}{chapter.7}{}}
+\newlabel{documentation:umap.CombineUmaps}{{7}{15}{Merge data of various \emph {k}-mers}{section*.6}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {8}Convert numeric vectors to BED and Wiggle}{17}{chapter.8}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:convert-numeric-vectors-to-bed-and-wiggle}{{8}{17}{Convert numeric vectors to BED and Wiggle}{chapter.8}{}}
+\newlabel{documentation:umap.Int8Handler}{{8}{17}{Convert numeric vectors to BED and Wiggle}{section*.7}{}}
+\newlabel{documentation:umap.Int8Handler.write_beds}{{8}{17}{Convert numeric vectors to BED and Wiggle}{section*.8}{}}
+\newlabel{documentation:umap.Int8Handler.write_as_wig}{{8}{17}{Convert numeric vectors to BED and Wiggle}{section*.9}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {9}Requesting Genomes}{19}{chapter.9}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:requesting-genomes}{{9}{19}{Requesting Genomes}{chapter.9}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {10}Contact, support and questions}{21}{chapter.10}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:contact-support-and-questions}{{10}{21}{Contact, support and questions}{chapter.10}{}}
+\@writefile{toc}{\contentsline {chapter}{\numberline {11}Indices and tables}{23}{chapter.11}}
+\@writefile{lof}{\addvspace {10\p@ }}
+\@writefile{lot}{\addvspace {10\p@ }}
+\@writefile{loliteral-block}{\addvspace {10\p@ }}
+\newlabel{documentation:indices-and-tables}{{11}{23}{Indices and tables}{chapter.11}{}}
+\@writefile{toc}{\contentsline {chapter}{Python Module Index}{25}{section*.10}}
+\@writefile{toc}{\contentsline {chapter}{Index}{27}{section*.11}}
diff --git a/doc/build/latex/Umap.idx b/doc/build/latex/Umap.idx
new file mode 100644
index 0000000..01ed21f
--- /dev/null
+++ b/doc/build/latex/Umap.idx
@@ -0,0 +1,8 @@
+\indexentry{umap (module)|hyperpage}{9}
+\indexentry{GetKmers (class in umap)|hyperpage}{9}
+\indexentry{BowtieWrapper (class in umap)|hyperpage}{11}
+\indexentry{UnifyBowtie (class in umap)|hyperpage}{13}
+\indexentry{CombineUmaps (class in umap)|hyperpage}{15}
+\indexentry{Int8Handler (class in umap)|hyperpage}{17}
+\indexentry{write\_beds() (umap.Int8Handler method)|hyperpage}{17}
+\indexentry{write\_as\_wig() (umap.Int8Handler method)|hyperpage}{17}
diff --git a/doc/build/latex/Umap.ilg b/doc/build/latex/Umap.ilg
new file mode 100644
index 0000000..b255691
--- /dev/null
+++ b/doc/build/latex/Umap.ilg
@@ -0,0 +1,7 @@
+This is makeindex, version 2.15 [TeX Live 2014] (kpathsea + Thai support).
+Scanning style file ./python.ist......done (6 attributes redefined, 0 ignored).
+Scanning input file Umap.idx....done (8 entries accepted, 0 rejected).
+Sorting entries....done (24 comparisons).
+Generating output file Umap.ind....done (29 lines written, 0 warnings).
+Output written in Umap.ind.
+Transcript written in Umap.ilg.
diff --git a/doc/build/latex/Umap.ind b/doc/build/latex/Umap.ind
new file mode 100644
index 0000000..a70842f
--- /dev/null
+++ b/doc/build/latex/Umap.ind
@@ -0,0 +1,29 @@
+\begin{theindex}
+\def\bigletter#1{{\Large\sffamily#1}\nopagebreak\vspace{1mm}}
+
+ \bigletter B
+ \item BowtieWrapper (class in umap), \hyperpage{11}
+
+ \indexspace
+ \bigletter C
+ \item CombineUmaps (class in umap), \hyperpage{15}
+
+ \indexspace
+ \bigletter G
+ \item GetKmers (class in umap), \hyperpage{9}
+
+ \indexspace
+ \bigletter I
+ \item Int8Handler (class in umap), \hyperpage{17}
+
+ \indexspace
+ \bigletter U
+ \item umap (module), \hyperpage{9}
+ \item UnifyBowtie (class in umap), \hyperpage{13}
+
+ \indexspace
+ \bigletter W
+ \item write\_as\_wig() (umap.Int8Handler method), \hyperpage{17}
+ \item write\_beds() (umap.Int8Handler method), \hyperpage{17}
+
+\end{theindex}
diff --git a/doc/build/latex/Umap.log b/doc/build/latex/Umap.log
new file mode 100644
index 0000000..092eeba
--- /dev/null
+++ b/doc/build/latex/Umap.log
@@ -0,0 +1,1203 @@
+This is pdfTeX, Version 3.14159265-2.6-1.40.15 (TeX Live 2014) (preloaded format=pdflatex 2015.1.15) 20 JUN 2016 16:41
+entering extended mode
+ restricted \write18 enabled.
+ %&-line parsing enabled.
+**Umap.tex
+(./Umap.tex
+LaTeX2e <2014/05/01>
+Babel <3.9l> and hyphenation patterns for 79 languages loaded.
+(./sphinxmanual.cls
+Document Class: sphinxmanual 2009/06/02 Document class (Sphinx manual)
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/report.cls
+Document Class: report 2014/09/29 v1.4h Standard LaTeX document class
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/size10.clo
+File: size10.clo 2014/09/29 v1.4h Standard LaTeX file (size option)
+)
+\c at part=\count79
+\c at chapter=\count80
+\c at section=\count81
+\c at subsection=\count82
+\c at subsubsection=\count83
+\c at paragraph=\count84
+\c at subparagraph=\count85
+\c at figure=\count86
+\c at table=\count87
+\abovecaptionskip=\skip41
+\belowcaptionskip=\skip42
+\bibindent=\dimen102
+))
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/inputenc.sty
+Package: inputenc 2014/04/30 v1.2b Input encoding file
+\inpenc at prehook=\toks14
+\inpenc at posthook=\toks15
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/utf8.def
+File: utf8.def 2014/09/29 v1.1m UTF-8 support for inputenc
+Now handling font encoding OML ...
+... no UTF-8 mapping file for font encoding OML
+Now handling font encoding T1 ...
+... processing UTF-8 mapping file for font encoding T1
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/t1enc.dfu
+File: t1enc.dfu 2014/09/29 v1.1m UTF-8 support for inputenc
+ defining Unicode char U+00A1 (decimal 161)
+ defining Unicode char U+00A3 (decimal 163)
+ defining Unicode char U+00AB (decimal 171)
+ defining Unicode char U+00BB (decimal 187)
+ defining Unicode char U+00BF (decimal 191)
+ defining Unicode char U+00C0 (decimal 192)
+ defining Unicode char U+00C1 (decimal 193)
+ defining Unicode char U+00C2 (decimal 194)
+ defining Unicode char U+00C3 (decimal 195)
+ defining Unicode char U+00C4 (decimal 196)
+ defining Unicode char U+00C5 (decimal 197)
+ defining Unicode char U+00C6 (decimal 198)
+ defining Unicode char U+00C7 (decimal 199)
+ defining Unicode char U+00C8 (decimal 200)
+ defining Unicode char U+00C9 (decimal 201)
+ defining Unicode char U+00CA (decimal 202)
+ defining Unicode char U+00CB (decimal 203)
+ defining Unicode char U+00CC (decimal 204)
+ defining Unicode char U+00CD (decimal 205)
+ defining Unicode char U+00CE (decimal 206)
+ defining Unicode char U+00CF (decimal 207)
+ defining Unicode char U+00D0 (decimal 208)
+ defining Unicode char U+00D1 (decimal 209)
+ defining Unicode char U+00D2 (decimal 210)
+ defining Unicode char U+00D3 (decimal 211)
+ defining Unicode char U+00D4 (decimal 212)
+ defining Unicode char U+00D5 (decimal 213)
+ defining Unicode char U+00D6 (decimal 214)
+ defining Unicode char U+00D8 (decimal 216)
+ defining Unicode char U+00D9 (decimal 217)
+ defining Unicode char U+00DA (decimal 218)
+ defining Unicode char U+00DB (decimal 219)
+ defining Unicode char U+00DC (decimal 220)
+ defining Unicode char U+00DD (decimal 221)
+ defining Unicode char U+00DE (decimal 222)
+ defining Unicode char U+00DF (decimal 223)
+ defining Unicode char U+00E0 (decimal 224)
+ defining Unicode char U+00E1 (decimal 225)
+ defining Unicode char U+00E2 (decimal 226)
+ defining Unicode char U+00E3 (decimal 227)
+ defining Unicode char U+00E4 (decimal 228)
+ defining Unicode char U+00E5 (decimal 229)
+ defining Unicode char U+00E6 (decimal 230)
+ defining Unicode char U+00E7 (decimal 231)
+ defining Unicode char U+00E8 (decimal 232)
+ defining Unicode char U+00E9 (decimal 233)
+ defining Unicode char U+00EA (decimal 234)
+ defining Unicode char U+00EB (decimal 235)
+ defining Unicode char U+00EC (decimal 236)
+ defining Unicode char U+00ED (decimal 237)
+ defining Unicode char U+00EE (decimal 238)
+ defining Unicode char U+00EF (decimal 239)
+ defining Unicode char U+00F0 (decimal 240)
+ defining Unicode char U+00F1 (decimal 241)
+ defining Unicode char U+00F2 (decimal 242)
+ defining Unicode char U+00F3 (decimal 243)
+ defining Unicode char U+00F4 (decimal 244)
+ defining Unicode char U+00F5 (decimal 245)
+ defining Unicode char U+00F6 (decimal 246)
+ defining Unicode char U+00F8 (decimal 248)
+ defining Unicode char U+00F9 (decimal 249)
+ defining Unicode char U+00FA (decimal 250)
+ defining Unicode char U+00FB (decimal 251)
+ defining Unicode char U+00FC (decimal 252)
+ defining Unicode char U+00FD (decimal 253)
+ defining Unicode char U+00FE (decimal 254)
+ defining Unicode char U+00FF (decimal 255)
+ defining Unicode char U+0102 (decimal 258)
+ defining Unicode char U+0103 (decimal 259)
+ defining Unicode char U+0104 (decimal 260)
+ defining Unicode char U+0105 (decimal 261)
+ defining Unicode char U+0106 (decimal 262)
+ defining Unicode char U+0107 (decimal 263)
+ defining Unicode char U+010C (decimal 268)
+ defining Unicode char U+010D (decimal 269)
+ defining Unicode char U+010E (decimal 270)
+ defining Unicode char U+010F (decimal 271)
+ defining Unicode char U+0110 (decimal 272)
+ defining Unicode char U+0111 (decimal 273)
+ defining Unicode char U+0118 (decimal 280)
+ defining Unicode char U+0119 (decimal 281)
+ defining Unicode char U+011A (decimal 282)
+ defining Unicode char U+011B (decimal 283)
+ defining Unicode char U+011E (decimal 286)
+ defining Unicode char U+011F (decimal 287)
+ defining Unicode char U+0130 (decimal 304)
+ defining Unicode char U+0131 (decimal 305)
+ defining Unicode char U+0132 (decimal 306)
+ defining Unicode char U+0133 (decimal 307)
+ defining Unicode char U+0139 (decimal 313)
+ defining Unicode char U+013A (decimal 314)
+ defining Unicode char U+013D (decimal 317)
+ defining Unicode char U+013E (decimal 318)
+ defining Unicode char U+0141 (decimal 321)
+ defining Unicode char U+0142 (decimal 322)
+ defining Unicode char U+0143 (decimal 323)
+ defining Unicode char U+0144 (decimal 324)
+ defining Unicode char U+0147 (decimal 327)
+ defining Unicode char U+0148 (decimal 328)
+ defining Unicode char U+014A (decimal 330)
+ defining Unicode char U+014B (decimal 331)
+ defining Unicode char U+0150 (decimal 336)
+ defining Unicode char U+0151 (decimal 337)
+ defining Unicode char U+0152 (decimal 338)
+ defining Unicode char U+0153 (decimal 339)
+ defining Unicode char U+0154 (decimal 340)
+ defining Unicode char U+0155 (decimal 341)
+ defining Unicode char U+0158 (decimal 344)
+ defining Unicode char U+0159 (decimal 345)
+ defining Unicode char U+015A (decimal 346)
+ defining Unicode char U+015B (decimal 347)
+ defining Unicode char U+015E (decimal 350)
+ defining Unicode char U+015F (decimal 351)
+ defining Unicode char U+0160 (decimal 352)
+ defining Unicode char U+0161 (decimal 353)
+ defining Unicode char U+0162 (decimal 354)
+ defining Unicode char U+0163 (decimal 355)
+ defining Unicode char U+0164 (decimal 356)
+ defining Unicode char U+0165 (decimal 357)
+ defining Unicode char U+016E (decimal 366)
+ defining Unicode char U+016F (decimal 367)
+ defining Unicode char U+0170 (decimal 368)
+ defining Unicode char U+0171 (decimal 369)
+ defining Unicode char U+0178 (decimal 376)
+ defining Unicode char U+0179 (decimal 377)
+ defining Unicode char U+017A (decimal 378)
+ defining Unicode char U+017B (decimal 379)
+ defining Unicode char U+017C (decimal 380)
+ defining Unicode char U+017D (decimal 381)
+ defining Unicode char U+017E (decimal 382)
+ defining Unicode char U+200C (decimal 8204)
+ defining Unicode char U+2013 (decimal 8211)
+ defining Unicode char U+2014 (decimal 8212)
+ defining Unicode char U+2018 (decimal 8216)
+ defining Unicode char U+2019 (decimal 8217)
+ defining Unicode char U+201A (decimal 8218)
+ defining Unicode char U+201C (decimal 8220)
+ defining Unicode char U+201D (decimal 8221)
+ defining Unicode char U+201E (decimal 8222)
+ defining Unicode char U+2030 (decimal 8240)
+ defining Unicode char U+2031 (decimal 8241)
+ defining Unicode char U+2039 (decimal 8249)
+ defining Unicode char U+203A (decimal 8250)
+ defining Unicode char U+2423 (decimal 9251)
+)
+Now handling font encoding OT1 ...
+... processing UTF-8 mapping file for font encoding OT1
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/ot1enc.dfu
+File: ot1enc.dfu 2014/09/29 v1.1m UTF-8 support for inputenc
+ defining Unicode char U+00A1 (decimal 161)
+ defining Unicode char U+00A3 (decimal 163)
+ defining Unicode char U+00B8 (decimal 184)
+ defining Unicode char U+00BF (decimal 191)
+ defining Unicode char U+00C5 (decimal 197)
+ defining Unicode char U+00C6 (decimal 198)
+ defining Unicode char U+00D8 (decimal 216)
+ defining Unicode char U+00DF (decimal 223)
+ defining Unicode char U+00E6 (decimal 230)
+ defining Unicode char U+00EC (decimal 236)
+ defining Unicode char U+00ED (decimal 237)
+ defining Unicode char U+00EE (decimal 238)
+ defining Unicode char U+00EF (decimal 239)
+ defining Unicode char U+00F8 (decimal 248)
+ defining Unicode char U+0131 (decimal 305)
+ defining Unicode char U+0141 (decimal 321)
+ defining Unicode char U+0142 (decimal 322)
+ defining Unicode char U+0152 (decimal 338)
+ defining Unicode char U+0153 (decimal 339)
+ defining Unicode char U+2013 (decimal 8211)
+ defining Unicode char U+2014 (decimal 8212)
+ defining Unicode char U+2018 (decimal 8216)
+ defining Unicode char U+2019 (decimal 8217)
+ defining Unicode char U+201C (decimal 8220)
+ defining Unicode char U+201D (decimal 8221)
+)
+Now handling font encoding OMS ...
+... processing UTF-8 mapping file for font encoding OMS
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/omsenc.dfu
+File: omsenc.dfu 2014/09/29 v1.1m UTF-8 support for inputenc
+ defining Unicode char U+00A7 (decimal 167)
+ defining Unicode char U+00B6 (decimal 182)
+ defining Unicode char U+00B7 (decimal 183)
+ defining Unicode char U+2020 (decimal 8224)
+ defining Unicode char U+2021 (decimal 8225)
+ defining Unicode char U+2022 (decimal 8226)
+)
+Now handling font encoding OMX ...
+... no UTF-8 mapping file for font encoding OMX
+Now handling font encoding U ...
+... no UTF-8 mapping file for font encoding U
+ defining Unicode char U+00A9 (decimal 169)
+ defining Unicode char U+00AA (decimal 170)
+ defining Unicode char U+00AE (decimal 174)
+ defining Unicode char U+00BA (decimal 186)
+ defining Unicode char U+02C6 (decimal 710)
+ defining Unicode char U+02DC (decimal 732)
+ defining Unicode char U+200C (decimal 8204)
+ defining Unicode char U+2026 (decimal 8230)
+ defining Unicode char U+2122 (decimal 8482)
+ defining Unicode char U+2423 (decimal 9251)
+))
+ defining Unicode char U+00A0 (decimal 160)
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/cmap/cmap.sty
+Package: cmap 2008/03/06 v1.0h CMap support: searchable PDF
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/fontenc.sty
+Package: fontenc 2005/09/27 v1.99g Standard LaTeX package
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/t1enc.def
+File: t1enc.def 2005/09/27 v1.99g Standard LaTeX file
+LaTeX Font Info: Redeclaring font encoding T1 on input line 43.
+)<<t1.cmap>>)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/amsmath/amsmath.sty
+Package: amsmath 2013/01/14 v2.14 AMS math features
+\@mathmargin=\skip43
+
+For additional information on amsmath, use the `?' option.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/amsmath/amstext.sty
+Package: amstext 2000/06/29 v2.01
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/amsmath/amsgen.sty
+File: amsgen.sty 1999/11/30 v2.0
+\@emptytoks=\toks16
+\ex@=\dimen103
+))
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/amsmath/amsbsy.sty
+Package: amsbsy 1999/11/29 v1.2d
+\pmbraise@=\dimen104
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/amsmath/amsopn.sty
+Package: amsopn 1999/12/14 v2.01 operator names
+)
+\inf at bad=\count88
+LaTeX Info: Redefining \frac on input line 210.
+\uproot@=\count89
+\leftroot@=\count90
+LaTeX Info: Redefining \overline on input line 306.
+\classnum@=\count91
+\DOTSCASE@=\count92
+LaTeX Info: Redefining \ldots on input line 378.
+LaTeX Info: Redefining \dots on input line 381.
+LaTeX Info: Redefining \cdots on input line 466.
+\Mathstrutbox@=\box26
+\strutbox@=\box27
+\big at size=\dimen105
+LaTeX Font Info: Redeclaring font encoding OML on input line 566.
+LaTeX Font Info: Redeclaring font encoding OMS on input line 567.
+\macc at depth=\count93
+\c at MaxMatrixCols=\count94
+\dotsspace@=\muskip10
+\c at parentequation=\count95
+\dspbrk at lvl=\count96
+\tag at help=\toks17
+\row@=\count97
+\column@=\count98
+\maxfields@=\count99
+\andhelp@=\toks18
+\eqnshift@=\dimen106
+\alignsep@=\dimen107
+\tagshift@=\dimen108
+\tagwidth@=\dimen109
+\totwidth@=\dimen110
+\lineht@=\dimen111
+\@envbody=\toks19
+\multlinegap=\skip44
+\multlinetaggap=\skip45
+\mathdisplay at stack=\toks20
+LaTeX Info: Redefining \[ on input line 2665.
+LaTeX Info: Redefining \] on input line 2666.
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/amsfonts/amssymb.sty
+Package: amssymb 2013/01/14 v3.01 AMS font symbols
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/amsfonts/amsfonts.sty
+Package: amsfonts 2013/01/14 v3.01 Basic AMSFonts support
+\symAMSa=\mathgroup4
+\symAMSb=\mathgroup5
+LaTeX Font Info: Overwriting math alphabet `\mathfrak' in version `bold'
+(Font) U/euf/m/n --> U/euf/b/n on input line 106.
+))
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/babel/babel.sty
+Package: babel 2014/09/25 3.9l The Babel package
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/babel-english/english.ldf
+Language: english 2012/08/20 v3.3p English support from the babel system
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/babel/babel.def
+File: babel.def 2014/09/25 3.9l Babel common definitions
+\babel at savecnt=\count100
+\U at D=\dimen112
+)
+\l at canadian = a dialect from \language\l at american
+\l at australian = a dialect from \language\l at british
+\l at newzealand = a dialect from \language\l at british
+))
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/psnfss/times.sty
+Package: times 2005/04/12 PSNFSS-v9.2a (SPQR)
+) (./fncychap.sty
+Package: fncychap 2007/07/30 v1.34 LaTeX package (Revised chapters)
+\RW=\skip46
+\mylen=\skip47
+\myhi=\skip48
+\px=\skip49
+\py=\skip50
+\pyy=\skip51
+\pxx=\skip52
+\c at AlphaCnt=\count101
+\c at AlphaDecCnt=\count102
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/tools/longtable.sty
+Package: longtable 2014/10/28 v4.11 Multi-page Table package (DPC)
+\LTleft=\skip53
+\LTright=\skip54
+\LTpre=\skip55
+\LTpost=\skip56
+\LTchunksize=\count103
+\LTcapwidth=\dimen113
+\LT at head=\box28
+\LT at firsthead=\box29
+\LT at foot=\box30
+\LT at lastfoot=\box31
+\LT at cols=\count104
+\LT at rows=\count105
+\c at LT@tables=\count106
+\c at LT@chunks=\count107
+\LT at p@ftn=\toks21
+) (./sphinx.sty
+Package: sphinx 2010/01/15 LaTeX package (Sphinx markup)
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/fancyhdr/fancyhdr.sty
+\fancy at headwidth=\skip57
+\f at ncyO@elh=\skip58
+\f at ncyO@erh=\skip59
+\f at ncyO@olh=\skip60
+\f at ncyO@orh=\skip61
+\f at ncyO@elf=\skip62
+\f at ncyO@erf=\skip63
+\f at ncyO@olf=\skip64
+\f at ncyO@orf=\skip65
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/textcomp.sty
+Package: textcomp 2005/09/27 v1.99g Standard LaTeX package
+Package textcomp Info: Sub-encoding information:
+(textcomp) 5 = only ISO-Adobe without \textcurrency
+(textcomp) 4 = 5 + \texteuro
+(textcomp) 3 = 4 + \textohm
+(textcomp) 2 = 3 + \textestimated + \textcurrency
+(textcomp) 1 = TS1 - \textcircled - \t
+(textcomp) 0 = TS1 (full)
+(textcomp) Font families with sub-encoding setting implement
+(textcomp) only a restricted character set as indicated.
+(textcomp) Family '?' is the default used for unknown fonts.
+(textcomp) See the documentation for details.
+Package textcomp Info: Setting ? sub-encoding to TS1/1 on input line 71.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/ts1enc.def
+File: ts1enc.def 2001/06/05 v3.0e (jk/car/fm) Standard LaTeX file
+Now handling font encoding TS1 ...
+... processing UTF-8 mapping file for font encoding TS1
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/ts1enc.dfu
+File: ts1enc.dfu 2014/09/29 v1.1m UTF-8 support for inputenc
+ defining Unicode char U+00A2 (decimal 162)
+ defining Unicode char U+00A3 (decimal 163)
+ defining Unicode char U+00A4 (decimal 164)
+ defining Unicode char U+00A5 (decimal 165)
+ defining Unicode char U+00A6 (decimal 166)
+ defining Unicode char U+00A7 (decimal 167)
+ defining Unicode char U+00A8 (decimal 168)
+ defining Unicode char U+00A9 (decimal 169)
+ defining Unicode char U+00AA (decimal 170)
+ defining Unicode char U+00AC (decimal 172)
+ defining Unicode char U+00AE (decimal 174)
+ defining Unicode char U+00AF (decimal 175)
+ defining Unicode char U+00B0 (decimal 176)
+ defining Unicode char U+00B1 (decimal 177)
+ defining Unicode char U+00B2 (decimal 178)
+ defining Unicode char U+00B3 (decimal 179)
+ defining Unicode char U+00B4 (decimal 180)
+ defining Unicode char U+00B5 (decimal 181)
+ defining Unicode char U+00B6 (decimal 182)
+ defining Unicode char U+00B7 (decimal 183)
+ defining Unicode char U+00B9 (decimal 185)
+ defining Unicode char U+00BA (decimal 186)
+ defining Unicode char U+00BC (decimal 188)
+ defining Unicode char U+00BD (decimal 189)
+ defining Unicode char U+00BE (decimal 190)
+ defining Unicode char U+00D7 (decimal 215)
+ defining Unicode char U+00F7 (decimal 247)
+ defining Unicode char U+0192 (decimal 402)
+ defining Unicode char U+02C7 (decimal 711)
+ defining Unicode char U+02D8 (decimal 728)
+ defining Unicode char U+02DD (decimal 733)
+ defining Unicode char U+0E3F (decimal 3647)
+ defining Unicode char U+2016 (decimal 8214)
+ defining Unicode char U+2020 (decimal 8224)
+ defining Unicode char U+2021 (decimal 8225)
+ defining Unicode char U+2022 (decimal 8226)
+ defining Unicode char U+2030 (decimal 8240)
+ defining Unicode char U+2031 (decimal 8241)
+ defining Unicode char U+203B (decimal 8251)
+ defining Unicode char U+203D (decimal 8253)
+ defining Unicode char U+2044 (decimal 8260)
+ defining Unicode char U+204E (decimal 8270)
+ defining Unicode char U+2052 (decimal 8274)
+ defining Unicode char U+20A1 (decimal 8353)
+ defining Unicode char U+20A4 (decimal 8356)
+ defining Unicode char U+20A6 (decimal 8358)
+ defining Unicode char U+20A9 (decimal 8361)
+ defining Unicode char U+20AB (decimal 8363)
+ defining Unicode char U+20AC (decimal 8364)
+ defining Unicode char U+20B1 (decimal 8369)
+ defining Unicode char U+2103 (decimal 8451)
+ defining Unicode char U+2116 (decimal 8470)
+ defining Unicode char U+2117 (decimal 8471)
+ defining Unicode char U+211E (decimal 8478)
+ defining Unicode char U+2120 (decimal 8480)
+ defining Unicode char U+2122 (decimal 8482)
+ defining Unicode char U+2126 (decimal 8486)
+ defining Unicode char U+2127 (decimal 8487)
+ defining Unicode char U+212E (decimal 8494)
+ defining Unicode char U+2190 (decimal 8592)
+ defining Unicode char U+2191 (decimal 8593)
+ defining Unicode char U+2192 (decimal 8594)
+ defining Unicode char U+2193 (decimal 8595)
+ defining Unicode char U+2329 (decimal 9001)
+ defining Unicode char U+232A (decimal 9002)
+ defining Unicode char U+2422 (decimal 9250)
+ defining Unicode char U+25E6 (decimal 9702)
+ defining Unicode char U+25EF (decimal 9711)
+ defining Unicode char U+266A (decimal 9834)
+))
+LaTeX Info: Redefining \oldstylenums on input line 266.
+Package textcomp Info: Setting cmr sub-encoding to TS1/0 on input line 281.
+Package textcomp Info: Setting cmss sub-encoding to TS1/0 on input line 282.
+Package textcomp Info: Setting cmtt sub-encoding to TS1/0 on input line 283.
+Package textcomp Info: Setting cmvtt sub-encoding to TS1/0 on input line 284.
+Package textcomp Info: Setting cmbr sub-encoding to TS1/0 on input line 285.
+Package textcomp Info: Setting cmtl sub-encoding to TS1/0 on input line 286.
+Package textcomp Info: Setting ccr sub-encoding to TS1/0 on input line 287.
+Package textcomp Info: Setting ptm sub-encoding to TS1/4 on input line 288.
+Package textcomp Info: Setting pcr sub-encoding to TS1/4 on input line 289.
+Package textcomp Info: Setting phv sub-encoding to TS1/4 on input line 290.
+Package textcomp Info: Setting ppl sub-encoding to TS1/3 on input line 291.
+Package textcomp Info: Setting pag sub-encoding to TS1/4 on input line 292.
+Package textcomp Info: Setting pbk sub-encoding to TS1/4 on input line 293.
+Package textcomp Info: Setting pnc sub-encoding to TS1/4 on input line 294.
+Package textcomp Info: Setting pzc sub-encoding to TS1/4 on input line 295.
+Package textcomp Info: Setting bch sub-encoding to TS1/4 on input line 296.
+Package textcomp Info: Setting put sub-encoding to TS1/5 on input line 297.
+Package textcomp Info: Setting uag sub-encoding to TS1/5 on input line 298.
+Package textcomp Info: Setting ugq sub-encoding to TS1/5 on input line 299.
+Package textcomp Info: Setting ul8 sub-encoding to TS1/4 on input line 300.
+Package textcomp Info: Setting ul9 sub-encoding to TS1/4 on input line 301.
+Package textcomp Info: Setting augie sub-encoding to TS1/5 on input line 302.
+Package textcomp Info: Setting dayrom sub-encoding to TS1/3 on input line 303.
+Package textcomp Info: Setting dayroms sub-encoding to TS1/3 on input line 304.
+
+Package textcomp Info: Setting pxr sub-encoding to TS1/0 on input line 305.
+Package textcomp Info: Setting pxss sub-encoding to TS1/0 on input line 306.
+Package textcomp Info: Setting pxtt sub-encoding to TS1/0 on input line 307.
+Package textcomp Info: Setting txr sub-encoding to TS1/0 on input line 308.
+Package textcomp Info: Setting txss sub-encoding to TS1/0 on input line 309.
+Package textcomp Info: Setting txtt sub-encoding to TS1/0 on input line 310.
+Package textcomp Info: Setting lmr sub-encoding to TS1/0 on input line 311.
+Package textcomp Info: Setting lmdh sub-encoding to TS1/0 on input line 312.
+Package textcomp Info: Setting lmss sub-encoding to TS1/0 on input line 313.
+Package textcomp Info: Setting lmssq sub-encoding to TS1/0 on input line 314.
+Package textcomp Info: Setting lmvtt sub-encoding to TS1/0 on input line 315.
+Package textcomp Info: Setting qhv sub-encoding to TS1/0 on input line 316.
+Package textcomp Info: Setting qag sub-encoding to TS1/0 on input line 317.
+Package textcomp Info: Setting qbk sub-encoding to TS1/0 on input line 318.
+Package textcomp Info: Setting qcr sub-encoding to TS1/0 on input line 319.
+Package textcomp Info: Setting qcs sub-encoding to TS1/0 on input line 320.
+Package textcomp Info: Setting qpl sub-encoding to TS1/0 on input line 321.
+Package textcomp Info: Setting qtm sub-encoding to TS1/0 on input line 322.
+Package textcomp Info: Setting qzc sub-encoding to TS1/0 on input line 323.
+Package textcomp Info: Setting qhvc sub-encoding to TS1/0 on input line 324.
+Package textcomp Info: Setting futs sub-encoding to TS1/4 on input line 325.
+Package textcomp Info: Setting futx sub-encoding to TS1/4 on input line 326.
+Package textcomp Info: Setting futj sub-encoding to TS1/4 on input line 327.
+Package textcomp Info: Setting hlh sub-encoding to TS1/3 on input line 328.
+Package textcomp Info: Setting hls sub-encoding to TS1/3 on input line 329.
+Package textcomp Info: Setting hlst sub-encoding to TS1/3 on input line 330.
+Package textcomp Info: Setting hlct sub-encoding to TS1/5 on input line 331.
+Package textcomp Info: Setting hlx sub-encoding to TS1/5 on input line 332.
+Package textcomp Info: Setting hlce sub-encoding to TS1/5 on input line 333.
+Package textcomp Info: Setting hlcn sub-encoding to TS1/5 on input line 334.
+Package textcomp Info: Setting hlcw sub-encoding to TS1/5 on input line 335.
+Package textcomp Info: Setting hlcf sub-encoding to TS1/5 on input line 336.
+Package textcomp Info: Setting pplx sub-encoding to TS1/3 on input line 337.
+Package textcomp Info: Setting pplj sub-encoding to TS1/3 on input line 338.
+Package textcomp Info: Setting ptmx sub-encoding to TS1/4 on input line 339.
+Package textcomp Info: Setting ptmj sub-encoding to TS1/4 on input line 340.
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/fancybox/fancybox.sty
+Package: fancybox 2010/05/15 1.4
+
+Style option: `fancybox' v1.4 <2010/05/15> (tvz)
+\@fancybox=\box32
+\shadowsize=\dimen114
+\@Sbox=\box33
+\do at VerbBox=\toks22
+\the at fancyput=\toks23
+\this at fancyput=\toks24
+\EndVerbatimTokens=\toks25
+\Verbatim at Outfile=\write3
+\Verbatim at Infile=\read1
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/titlesec/titlesec.sty
+Package: titlesec 2011/12/15 v2.10.0 Sectioning titles
+\ttl at box=\box34
+\beforetitleunit=\skip66
+\aftertitleunit=\skip67
+\ttl at plus=\dimen115
+\ttl at minus=\dimen116
+\ttl at toksa=\toks26
+\titlewidth=\dimen117
+\titlewidthlast=\dimen118
+\titlewidthfirst=\dimen119
+) (./tabulary.sty
+Package: tabulary 2008/12/01 v0.9 tabulary package (DPC)
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/tools/array.sty
+Package: array 2014/10/28 v2.4c Tabular extension package (FMi)
+\col at sep=\dimen120
+\extrarowheight=\dimen121
+\NC at list=\toks27
+\extratabsurround=\skip68
+\backup at length=\skip69
+)
+\TY at count=\count108
+\TY at linewidth=\dimen122
+\tymin=\dimen123
+\tymax=\dimen124
+\TY at tablewidth=\dimen125
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/makeidx.sty
+Package: makeidx 2014/09/29 v1.0m Standard LaTeX package
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/framed/framed.sty
+Package: framed 2011/10/22 v 0.96: framed or shaded text with page breaks
+\OuterFrameSep=\skip70
+\fb at frw=\dimen126
+\fb at frh=\dimen127
+\FrameRule=\dimen128
+\FrameSep=\dimen129
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/ifthen.sty
+Package: ifthen 2014/09/29 v1.1c Standard LaTeX ifthen package (DPC)
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/xcolor/xcolor.sty
+Package: xcolor 2007/01/21 v2.11 LaTeX color extensions (UK)
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/latexconfig/color.cfg
+File: color.cfg 2007/01/18 v1.5 color configuration of teTeX/TeXLive
+)
+Package xcolor Info: Driver file: pdftex.def on input line 225.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/pdftex-def/pdftex.def
+File: pdftex.def 2011/05/27 v0.06d Graphics/color for pdfTeX
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/oberdiek/infwarerr.sty
+Package: infwarerr 2010/04/08 v1.3 Providing info/warning/error messages (HO)
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/oberdiek/ltxcmds.sty
+Package: ltxcmds 2011/11/09 v1.22 LaTeX kernel commands for general use (HO)
+)
+\Gread at gobject=\count109
+)
+Package xcolor Info: Model `cmy' substituted by `cmy0' on input line 1337.
+Package xcolor Info: Model `hsb' substituted by `rgb' on input line 1341.
+Package xcolor Info: Model `RGB' extended on input line 1353.
+Package xcolor Info: Model `HTML' substituted by `rgb' on input line 1355.
+Package xcolor Info: Model `Hsb' substituted by `hsb' on input line 1356.
+Package xcolor Info: Model `tHsb' substituted by `hsb' on input line 1357.
+Package xcolor Info: Model `HSB' substituted by `hsb' on input line 1358.
+Package xcolor Info: Model `Gray' substituted by `gray' on input line 1359.
+Package xcolor Info: Model `wave' substituted by `hsb' on input line 1360.
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/fancyvrb/fancyvrb.sty
+Package: fancyvrb 2008/02/07
+
+Style option: `fancyvrb' v2.7a, with DG/SPQR fixes, and firstline=lastline fix
+<2008/02/07> (tvz)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/graphics/keyval.sty
+Package: keyval 2014/10/28 v1.15 key=value parser (DPC)
+\KV at toks@=\toks28
+)
+\FV at CodeLineNo=\count110
+\FV at InFile=\read2
+\FV at TabBox=\box35
+\c at FancyVerbLine=\count111
+\FV at StepNumber=\count112
+\FV at OutFile=\write4
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/threeparttable/threeparttable.sty
+Package: threeparttable 2003/06/13 v 3.0
+\@tempboxb=\box36
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/mdwtools/footnote.sty
+Package: footnote 1997/01/28 1.13 Save footnotes around boxes
+\fn at notes=\box37
+\fn at width=\dimen130
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/wrapfig/wrapfig.sty
+\wrapoverhang=\dimen131
+\WF at size=\dimen132
+\c at WF@wrappedlines=\count113
+\WF at box=\box38
+\WF at everypar=\toks29
+Package: wrapfig 2003/01/31 v 3.6
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/parskip/parskip.sty
+Package: parskip 2001/04/09 non-zero parskip adjustments
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/alltt.sty
+Package: alltt 1997/06/16 v2.0g defines alltt environment
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/upquote/upquote.sty
+Package: upquote 2012/04/19 v1.3 upright-quote and grave-accent glyphs in verba
+tim
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/graphics/graphicx.sty
+Package: graphicx 2014/10/28 v1.0g Enhanced LaTeX Graphics (DPC,SPQR)
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/graphics/graphics.sty
+Package: graphics 2014/10/28 v1.0p Standard LaTeX Graphics (DPC,SPQR)
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/graphics/trig.sty
+Package: trig 1999/03/16 v1.09 sin cos tan (DPC)
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/latexconfig/graphics.cfg
+File: graphics.cfg 2010/04/23 v1.9 graphics configuration of TeX Live
+)
+Package graphics Info: Driver file: pdftex.def on input line 91.
+)
+\Gin at req@height=\dimen133
+\Gin at req@width=\dimen134
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/pdftex/pdfcolor.tex)
+\Sphinx at scratchlength=\skip71
+\py at argswidth=\skip72
+\py at noticelength=\skip73
+\lineblockindentation=\skip74
+\image at box=\box39
+\image at width=\dimen135
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/hyperref/hyperref.sty
+Package: hyperref 2012/11/06 v6.83m Hypertext links for LaTeX
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/oberdiek/hobsub-hyperref.sty
+Package: hobsub-hyperref 2012/05/28 v1.13 Bundle oberdiek, subset hyperref (HO)
+
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/oberdiek/hobsub-generic.sty
+Package: hobsub-generic 2012/05/28 v1.13 Bundle oberdiek, subset generic (HO)
+Package: hobsub 2012/05/28 v1.13 Construct package bundles (HO)
+Package hobsub Info: Skipping package `infwarerr' (already loaded).
+Package hobsub Info: Skipping package `ltxcmds' (already loaded).
+Package: ifluatex 2010/03/01 v1.3 Provides the ifluatex switch (HO)
+Package ifluatex Info: LuaTeX not detected.
+Package: ifvtex 2010/03/01 v1.5 Detect VTeX and its facilities (HO)
+Package ifvtex Info: VTeX not detected.
+Package: intcalc 2007/09/27 v1.1 Expandable calculations with integers (HO)
+Package: ifpdf 2011/01/30 v2.3 Provides the ifpdf switch (HO)
+Package ifpdf Info: pdfTeX in PDF mode is detected.
+Package: etexcmds 2011/02/16 v1.5 Avoid name clashes with e-TeX commands (HO)
+Package etexcmds Info: Could not find \expanded.
+(etexcmds) That can mean that you are not using pdfTeX 1.50 or
+(etexcmds) that some package has redefined \expanded.
+(etexcmds) In the latter case, load this package earlier.
+Package: kvsetkeys 2012/04/25 v1.16 Key value parser (HO)
+Package: kvdefinekeys 2011/04/07 v1.3 Define keys (HO)
+Package: pdftexcmds 2011/11/29 v0.20 Utility functions of pdfTeX for LuaTeX (HO
+)
+Package pdftexcmds Info: LuaTeX not detected.
+Package pdftexcmds Info: \pdf at primitive is available.
+Package pdftexcmds Info: \pdf at ifprimitive is available.
+Package pdftexcmds Info: \pdfdraftmode found.
+Package: pdfescape 2011/11/25 v1.13 Implements pdfTeX's escape features (HO)
+Package: bigintcalc 2012/04/08 v1.3 Expandable calculations on big integers (HO
+)
+Package: bitset 2011/01/30 v1.1 Handle bit-vector datatype (HO)
+Package: uniquecounter 2011/01/30 v1.2 Provide unlimited unique counter (HO)
+)
+Package hobsub Info: Skipping package `hobsub' (already loaded).
+Package: letltxmacro 2010/09/02 v1.4 Let assignment for LaTeX macros (HO)
+Package: hopatch 2012/05/28 v1.2 Wrapper for package hooks (HO)
+Package: xcolor-patch 2011/01/30 xcolor patch
+Package: atveryend 2011/06/30 v1.8 Hooks at the very end of document (HO)
+Package atveryend Info: \enddocument detected (standard20110627).
+Package: atbegshi 2011/10/05 v1.16 At begin shipout hook (HO)
+Package: refcount 2011/10/16 v3.4 Data extraction from label references (HO)
+Package: hycolor 2011/01/30 v1.7 Color options for hyperref/bookmark (HO)
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/ifxetex/ifxetex.sty
+Package: ifxetex 2010/09/12 v0.6 Provides ifxetex conditional
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/oberdiek/auxhook.sty
+Package: auxhook 2011/03/04 v1.3 Hooks for auxiliary files (HO)
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/oberdiek/kvoptions.sty
+Package: kvoptions 2011/06/30 v3.11 Key value format for package options (HO)
+)
+\@linkdim=\dimen136
+\Hy at linkcounter=\count114
+\Hy at pagecounter=\count115
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/hyperref/pd1enc.def
+File: pd1enc.def 2012/11/06 v6.83m Hyperref: PDFDocEncoding definition (HO)
+Now handling font encoding PD1 ...
+... no UTF-8 mapping file for font encoding PD1
+)
+\Hy at SavedSpaceFactor=\count116
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/latexconfig/hyperref.cfg
+File: hyperref.cfg 2002/06/06 v1.2 hyperref configuration of TeXLive
+)
+Package hyperref Info: Option `colorlinks' set `true' on input line 4319.
+Package hyperref Info: Option `breaklinks' set `true' on input line 4319.
+Package hyperref Info: Hyper figures OFF on input line 4443.
+Package hyperref Info: Link nesting OFF on input line 4448.
+Package hyperref Info: Hyper index ON on input line 4451.
+Package hyperref Info: Plain pages OFF on input line 4458.
+Package hyperref Info: Backreferencing OFF on input line 4463.
+Package hyperref Info: Implicit mode ON; LaTeX internals redefined.
+Package hyperref Info: Bookmarks ON on input line 4688.
+\c at Hy@tempcnt=\count117
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/url/url.sty
+\Urlmuskip=\muskip11
+Package: url 2013/09/16 ver 3.4 Verb mode for urls, etc.
+)
+LaTeX Info: Redefining \url on input line 5041.
+\XeTeXLinkMargin=\dimen137
+\Fld at menulength=\count118
+\Field at Width=\dimen138
+\Fld at charsize=\dimen139
+Package hyperref Info: Hyper figures OFF on input line 6295.
+Package hyperref Info: Link nesting OFF on input line 6300.
+Package hyperref Info: Hyper index ON on input line 6303.
+Package hyperref Info: backreferencing OFF on input line 6310.
+Package hyperref Info: Link coloring ON on input line 6313.
+Package hyperref Info: Link coloring with OCG OFF on input line 6320.
+Package hyperref Info: PDF/A mode OFF on input line 6325.
+LaTeX Info: Redefining \ref on input line 6365.
+LaTeX Info: Redefining \pageref on input line 6369.
+\Hy at abspage=\count119
+\c at Item=\count120
+\c at Hfootnote=\count121
+)
+
+Package hyperref Message: Driver (autodetected): hpdftex.
+
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/hyperref/hpdftex.def
+File: hpdftex.def 2012/11/06 v6.83m Hyperref driver for pdfTeX
+\Fld at listcount=\count122
+\c at bookmark@seq at number=\count123
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/oberdiek/rerunfilecheck.sty
+Package: rerunfilecheck 2011/04/15 v1.7 Rerun checks for auxiliary files (HO)
+Package uniquecounter Info: New unique counter `rerunfilecheck' on input line 2
+82.
+)
+\Hy at SectionHShift=\skip75
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/oberdiek/hypcap.sty
+Package: hypcap 2011/02/16 v1.11 Adjusting the anchors of captions (HO)
+)
+\DUlineblockindent=\skip76
+ (./newfloat.sty
+Package: newfloat 2015/09/17 v1.1-109 Defining new floating environments (AR)
+)
+Package newfloat Info: New float `literal-block' with options `' on input line
+627.
+\c at literal-block=\count124
+\newfloat at ftype=\count125
+Package newfloat Info: float type `literal-block'=8 on input line 627.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/capt-of/capt-of.sty
+Package: capt-of 2009/12/29 v0.2 standard captions outside of floats
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/needspace/needspace.sty
+Package: needspace 2010/09/12 v1.3d reserve vertical space
+))
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/multirow/multirow.sty
+\bigstrutjot=\dimen140
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/eqparbox/eqparbox.sty
+Package: eqparbox 2013/03/15 v4.0 Create equal-widthed boxes
+\eqp at tempdima=\skip77
+\eqp at tempdimb=\skip78
+\eqp at tabular@box=\box40
+\eqp at list@box=\box41
+\eqp at list@indent=\skip79
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/environ/environ.sty
+Package: environ 2014/05/04 v0.3 A new way to define environments
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/trimspaces/trimspaces.sty
+Package: trimspaces 2009/09/17 v1.1 Trim spaces around a token list
+)))
+\@indexfile=\write5
+\openout5 = `Umap.idx'.
+
+
+Writing index file Umap.idx
+(./Umap.aux)
+\openout1 = `Umap.aux'.
+
+LaTeX Font Info: Checking defaults for OML/cmm/m/it on input line 136.
+LaTeX Font Info: ... okay on input line 136.
+LaTeX Font Info: Checking defaults for T1/cmr/m/n on input line 136.
+LaTeX Font Info: ... okay on input line 136.
+LaTeX Font Info: Checking defaults for OT1/cmr/m/n on input line 136.
+LaTeX Font Info: ... okay on input line 136.
+LaTeX Font Info: Checking defaults for OMS/cmsy/m/n on input line 136.
+LaTeX Font Info: ... okay on input line 136.
+LaTeX Font Info: Checking defaults for OMX/cmex/m/n on input line 136.
+LaTeX Font Info: ... okay on input line 136.
+LaTeX Font Info: Checking defaults for U/cmr/m/n on input line 136.
+LaTeX Font Info: ... okay on input line 136.
+LaTeX Font Info: Checking defaults for TS1/cmr/m/n on input line 136.
+LaTeX Font Info: Try loading font information for TS1+cmr on input line 136.
+
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/base/ts1cmr.fd
+File: ts1cmr.fd 2014/09/29 v2.5h Standard LaTeX font definitions
+)
+LaTeX Font Info: ... okay on input line 136.
+LaTeX Font Info: Checking defaults for PD1/pdf/m/n on input line 136.
+LaTeX Font Info: ... okay on input line 136.
+LaTeX Font Info: Try loading font information for T1+ptm on input line 136.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/psnfss/t1ptm.fd
+File: t1ptm.fd 2001/06/04 font definitions for T1/ptm.
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/context/base/supp-pdf.mkii
+[Loading MPS to PDF converter (version 2006.09.02).]
+\scratchcounter=\count126
+\scratchdimen=\dimen141
+\scratchbox=\box42
+\nofMPsegments=\count127
+\nofMParguments=\count128
+\everyMPshowfont=\toks30
+\MPscratchCnt=\count129
+\MPscratchDim=\dimen142
+\MPnumerator=\count130
+\makeMPintoPDFobject=\count131
+\everyMPtoPDFconversion=\toks31
+)
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/oberdiek/epstopdf-base.sty
+Package: epstopdf-base 2010/02/09 v2.5 Base part for package epstopdf
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/oberdiek/grfext.sty
+Package: grfext 2010/08/19 v1.1 Manage graphics extensions (HO)
+)
+Package grfext Info: Graphics extension search list:
+(grfext) [.png,.pdf,.jpg,.mps,.jpeg,.jbig2,.jb2,.PNG,.PDF,.JPG,.JPE
+G,.JBIG2,.JB2,.eps]
+(grfext) \AppendGraphicsExtensions on input line 452.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/latexconfig/epstopdf-sys.cfg
+File: epstopdf-sys.cfg 2010/07/13 v1.3 Configuration of (r)epstopdf for TeX Liv
+e
+))
+\AtBeginShipoutBox=\box43
+Package hyperref Info: Link coloring ON on input line 136.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/hyperref/nameref.sty
+Package: nameref 2012/10/27 v2.43 Cross-referencing by name of section
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/generic/oberdiek/gettitlestring.sty
+Package: gettitlestring 2010/12/03 v1.4 Cleanup title references (HO)
+)
+\c at section@level=\count132
+)
+LaTeX Info: Redefining \ref on input line 136.
+LaTeX Info: Redefining \pageref on input line 136.
+LaTeX Info: Redefining \nameref on input line 136.
+ (./Umap.out) (./Umap.out)
+\@outlinefile=\write6
+\openout6 = `Umap.out'.
+
+
+Underfull \hbox (badness 10000) in paragraph at lines 139--139
+
+ []
+
+LaTeX Font Info: Try loading font information for T1+phv on input line 139.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/psnfss/t1phv.fd
+File: t1phv.fd 2001/06/04 scalable font definitions for T1/phv.
+)
+LaTeX Font Info: Font shape `T1/phv/bx/n' in size <24.88> not available
+(Font) Font shape `T1/phv/b/n' tried instead on input line 139.
+LaTeX Font Info: Font shape `T1/phv/m/it' in size <17.28> not available
+(Font) Font shape `T1/phv/m/sl' tried instead on input line 139.
+LaTeX Font Info: Font shape `T1/phv/bx/it' in size <17.28> not available
+(Font) Font shape `T1/phv/b/it' tried instead on input line 139.
+LaTeX Font Info: Font shape `T1/phv/b/it' in size <17.28> not available
+(Font) Font shape `T1/phv/b/sl' tried instead on input line 139.
+LaTeX Font Info: Font shape `T1/phv/bx/n' in size <17.28> not available
+(Font) Font shape `T1/phv/b/n' tried instead on input line 139.
+<<ot1.cmap>><<oml.cmap>><<oms.cmap>><<omx.cmap>>
+LaTeX Font Info: Try loading font information for U+msa on input line 139.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/amsfonts/umsa.fd
+File: umsa.fd 2013/01/14 v3.01 AMS symbols A
+)
+LaTeX Font Info: Try loading font information for U+msb on input line 139.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/amsfonts/umsb.fd
+File: umsb.fd 2013/01/14 v3.01 AMS symbols B
+)
+Overfull \hbox (111.11311pt too wide) in paragraph at lines 139--139
+ [][]
+ []
+
+[1
+
+{/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-var/fonts/map/pdftex/updmap/pdftex.map}] [2
+
+] (./Umap.toc
+LaTeX Font Info: Font shape `T1/ptm/bx/n' in size <10> not available
+(Font) Font shape `T1/ptm/b/n' tried instead on input line 2.
+LaTeX Font Info: Font shape `T1/ptm/bx/it' in size <10> not available
+(Font) Font shape `T1/ptm/b/it' tried instead on input line 6.
+)
+\tf at toc=\write7
+\openout7 = `Umap.toc'.
+
+
+Adding blank page after the table of contents.
+LaTeX Font Info: Font shape `T1/phv/bx/n' in size <10> not available
+(Font) Font shape `T1/phv/b/n' tried instead on input line 139.
+[1
+
+] [2] [1
+
+] [2
+
+]
+Chapter 1.
+LaTeX Font Info: Font shape `T1/phv/bx/n' in size <14.4> not available
+(Font) Font shape `T1/phv/b/n' tried instead on input line 146.
+LaTeX Font Info: Font shape `T1/ptm/bx/n' in size <14.4> not available
+(Font) Font shape `T1/ptm/b/n' tried instead on input line 146.
+LaTeX Font Info: Font shape `T1/ptm/bx/n' in size <24.88> not available
+(Font) Font shape `T1/ptm/b/n' tried instead on input line 146.
+[3] [4
+
+]
+Chapter 2.
+[5] [6
+
+]
+Chapter 3.
+LaTeX Font Info: Try loading font information for TS1+ptm on input line 220.
+
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/psnfss/ts1ptm.fd
+File: ts1ptm.fd 2001/06/04 font definitions for TS1/ptm.
+)
+LaTeX Font Info: Try loading font information for T1+pcr on input line 237.
+
+(/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf
+-dist/tex/latex/psnfss/t1pcr.fd
+File: t1pcr.fd 2001/06/04 font definitions for T1/pcr.
+) [7] [8
+
+]
+Chapter 4.
+LaTeX Font Info: Font shape `T1/phv/bx/it' in size <14.4> not available
+(Font) Font shape `T1/phv/b/it' tried instead on input line 264.
+LaTeX Font Info: Font shape `T1/phv/b/it' in size <14.4> not available
+(Font) Font shape `T1/phv/b/sl' tried instead on input line 264.
+LaTeX Font Info: Font shape `T1/pcr/bx/n' in size <10> not available
+(Font) Font shape `T1/pcr/b/n' tried instead on input line 268.
+[9]
+LaTeX Font Info: Font shape `T1/phv/bx/it' in size <10> not available
+(Font) Font shape `T1/phv/b/it' tried instead on input line 273.
+LaTeX Font Info: Font shape `T1/phv/b/it' in size <10> not available
+(Font) Font shape `T1/phv/b/sl' tried instead on input line 273.
+ [10
+
+]
+Chapter 5.
+[11] [12
+
+]
+Chapter 6.
+[13] [14
+
+]
+Chapter 7.
+[15] [16
+
+]
+Chapter 8.
+[17] [18
+
+]
+Chapter 9.
+[19] [20
+
+]
+Chapter 10.
+[21] [22
+
+]
+Chapter 11.
+[23] [24
+
+] [25
+
+
+] (./Umap.ind [26
+
+
+] [27
+
+
+])
+Package atveryend Info: Empty hook `BeforeClearDocument' on input line 361.
+Package atveryend Info: Empty hook `AfterLastShipout' on input line 361.
+ (./Umap.aux)
+Package atveryend Info: Executing hook `AtVeryEndDocument' on input line 361.
+Package atveryend Info: Executing hook `AtEndAfterFileList' on input line 361.
+Package rerunfilecheck Info: File `Umap.out' has not changed.
+(rerunfilecheck) Checksum: BE53FFC91D75B9E1FD7346679990A46F;802.
+Package atveryend Info: Empty hook `AtVeryVeryEnd' on input line 361.
+ )
+Here is how much of TeX's memory you used:
+ 10134 strings out of 493109
+ 150446 string characters out of 6113058
+ 244410 words of memory out of 5000000
+ 13242 multiletter control sequences out of 15000+600000
+ 66298 words of font info for 79 fonts, out of 8000000 for 9000
+ 1142 hyphenation exceptions out of 8191
+ 41i,11n,45p,251b,401s stack positions out of 5000i,500n,10000p,200000b,80000s
+{/mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/tex
+mf-dist/fonts/enc/dvips/base/8r.enc}</mnt/work1/users/home2/mkarimzadeh/softwar
+e/LaTeX/usr/local/texlive/2014/texmf-dist/fonts/type1/public/amsfonts/cm/cmmi10
+.pfb></mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/
+texmf-dist/fonts/type1/public/amsfonts/cm/cmmi7.pfb></mnt/work1/users/home2/mka
+rimzadeh/software/LaTeX/usr/local/texlive/2014/texmf-dist/fonts/type1/public/am
+sfonts/cm/cmr10.pfb></mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/loca
+l/texlive/2014/texmf-dist/fonts/type1/public/amsfonts/cm/cmr7.pfb></mnt/work1/u
+sers/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf-dist/fonts/t
+ype1/public/amsfonts/cm/cmsy10.pfb></mnt/work1/users/home2/mkarimzadeh/software
+/LaTeX/usr/local/texlive/2014/texmf-dist/fonts/type1/urw/courier/ucrb8a.pfb></m
+nt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texmf-di
+st/fonts/type1/urw/courier/ucrr8a.pfb></mnt/work1/users/home2/mkarimzadeh/softw
+are/LaTeX/usr/local/texlive/2014/texmf-dist/fonts/type1/urw/helvetic/uhvb8a.pfb
+></mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/2014/texm
+f-dist/fonts/type1/urw/helvetic/uhvbo8a.pfb></mnt/work1/users/home2/mkarimzadeh
+/software/LaTeX/usr/local/texlive/2014/texmf-dist/fonts/type1/urw/helvetic/uhvr
+8a.pfb></mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/201
+4/texmf-dist/fonts/type1/urw/times/utmb8a.pfb></mnt/work1/users/home2/mkarimzad
+eh/software/LaTeX/usr/local/texlive/2014/texmf-dist/fonts/type1/urw/times/utmbi
+8a.pfb></mnt/work1/users/home2/mkarimzadeh/software/LaTeX/usr/local/texlive/201
+4/texmf-dist/fonts/type1/urw/times/utmr8a.pfb></mnt/work1/users/home2/mkarimzad
+eh/software/LaTeX/usr/local/texlive/2014/texmf-dist/fonts/type1/urw/times/utmri
+8a.pfb>
+Output written on Umap.pdf (31 pages, 163429 bytes).
+PDF statistics:
+ 309 PDF objects out of 1000 (max. 8388607)
+ 254 compressed objects within 3 object streams
+ 55 named destinations out of 1000 (max. 500000)
+ 133 words of extra memory for PDF output out of 10000 (max. 10000000)
+
diff --git a/doc/build/latex/Umap.out b/doc/build/latex/Umap.out
new file mode 100644
index 0000000..0c607c3
--- /dev/null
+++ b/doc/build/latex/Umap.out
@@ -0,0 +1,14 @@
+\BOOKMARK [0][-]{chapter.1}{Introduction}{}% 1
+\BOOKMARK [0][-]{chapter.2}{Mappability of the bisulfite-converted genome}{}% 2
+\BOOKMARK [1][-]{section.2.1}{Measures of mappability}{chapter.2}% 3
+\BOOKMARK [0][-]{chapter.3}{Quick start}{}% 4
+\BOOKMARK [0][-]{chapter.4}{Get k-mers}{}% 5
+\BOOKMARK [0][-]{chapter.5}{Run Bowtie}{}% 6
+\BOOKMARK [0][-]{chapter.6}{Merge bowtie outputs}{}% 7
+\BOOKMARK [0][-]{chapter.7}{Merge data of various k-mers}{}% 8
+\BOOKMARK [0][-]{chapter.8}{Convert numeric vectors to BED and Wiggle}{}% 9
+\BOOKMARK [0][-]{chapter.9}{Requesting Genomes}{}% 10
+\BOOKMARK [0][-]{chapter.10}{Contact, support and questions}{}% 11
+\BOOKMARK [0][-]{chapter.11}{Indices and tables}{}% 12
+\BOOKMARK [0][-]{section*.10}{Python Module Index}{}% 13
+\BOOKMARK [0][-]{section*.11}{Index}{}% 14
diff --git a/doc/build/latex/Umap.pdf b/doc/build/latex/Umap.pdf
new file mode 100644
index 0000000..8c0ab37
Binary files /dev/null and b/doc/build/latex/Umap.pdf differ
diff --git a/doc/build/latex/Umap.tex b/doc/build/latex/Umap.tex
new file mode 100644
index 0000000..96fbda3
--- /dev/null
+++ b/doc/build/latex/Umap.tex
@@ -0,0 +1,361 @@
+% Generated by Sphinx.
+\def\sphinxdocclass{report}
+\documentclass[letterpaper,10pt,english]{sphinxmanual}
+
+\usepackage[utf8]{inputenc}
+\ifdefined\DeclareUnicodeCharacter
+ \DeclareUnicodeCharacter{00A0}{\nobreakspace}
+\else\fi
+\usepackage{cmap}
+\usepackage[T1]{fontenc}
+\usepackage{amsmath,amssymb}
+\usepackage{babel}
+\usepackage{times}
+\usepackage[Bjarne]{fncychap}
+\usepackage{longtable}
+\usepackage{sphinx}
+\usepackage{multirow}
+\usepackage{eqparbox}
+
+
+\addto\captionsenglish{\renewcommand{\figurename}{Fig. }}
+\addto\captionsenglish{\renewcommand{\tablename}{Table }}
+\SetupFloatingEnvironment{literal-block}{name=Listing }
+
+\addto\extrasenglish{\def\pageautorefname{page}}
+
+\setcounter{tocdepth}{1}
+
+
+\title{Umap Documentation}
+\date{Jun 20, 2016}
+\release{0.1.0}
+\author{Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman}
+\newcommand{\sphinxlogo}{}
+\renewcommand{\releasename}{Release}
+\makeindex
+
+\makeatletter
+\def\PYG at reset{\let\PYG at it=\relax \let\PYG at bf=\relax%
+ \let\PYG at ul=\relax \let\PYG at tc=\relax%
+ \let\PYG at bc=\relax \let\PYG at ff=\relax}
+\def\PYG at tok#1{\csname PYG at tok@#1\endcsname}
+\def\PYG at toks#1+{\ifx\relax#1\empty\else%
+ \PYG at tok{#1}\expandafter\PYG at toks\fi}
+\def\PYG at do#1{\PYG at bc{\PYG at tc{\PYG at ul{%
+ \PYG at it{\PYG at bf{\PYG at ff{#1}}}}}}}
+\def\PYG#1#2{\PYG at reset\PYG at toks#1+\relax+\PYG at do{#2}}
+
+\expandafter\def\csname PYG at tok@gd\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.63,0.00,0.00}{##1}}}
+\expandafter\def\csname PYG at tok@gu\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.50,0.00,0.50}{##1}}}
+\expandafter\def\csname PYG at tok@gt\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.00,0.27,0.87}{##1}}}
+\expandafter\def\csname PYG at tok@gs\endcsname{\let\PYG at bf=\textbf}
+\expandafter\def\csname PYG at tok@gr\endcsname{\def\PYG at tc##1{\textcolor[rgb]{1.00,0.00,0.00}{##1}}}
+\expandafter\def\csname PYG at tok@cm\endcsname{\let\PYG at it=\textit\def\PYG at tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
+\expandafter\def\csname PYG at tok@vg\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
+\expandafter\def\csname PYG at tok@vi\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
+\expandafter\def\csname PYG at tok@mh\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
+\expandafter\def\csname PYG at tok@cs\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}\def\PYG at bc##1{\setlength{\fboxsep}{0pt}\colorbox[rgb]{1.00,0.94,0.94}{\strut ##1}}}
+\expandafter\def\csname PYG at tok@ge\endcsname{\let\PYG at it=\textit}
+\expandafter\def\csname PYG at tok@vc\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
+\expandafter\def\csname PYG at tok@il\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
+\expandafter\def\csname PYG at tok@go\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.20,0.20,0.20}{##1}}}
+\expandafter\def\csname PYG at tok@cp\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@gi\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.00,0.63,0.00}{##1}}}
+\expandafter\def\csname PYG at tok@gh\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.00,0.00,0.50}{##1}}}
+\expandafter\def\csname PYG at tok@ni\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.84,0.33,0.22}{##1}}}
+\expandafter\def\csname PYG at tok@nl\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.00,0.13,0.44}{##1}}}
+\expandafter\def\csname PYG at tok@nn\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.05,0.52,0.71}{##1}}}
+\expandafter\def\csname PYG at tok@no\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.38,0.68,0.84}{##1}}}
+\expandafter\def\csname PYG at tok@na\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
+\expandafter\def\csname PYG at tok@nb\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@nc\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.05,0.52,0.71}{##1}}}
+\expandafter\def\csname PYG at tok@nd\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.33,0.33,0.33}{##1}}}
+\expandafter\def\csname PYG at tok@ne\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@nf\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.02,0.16,0.49}{##1}}}
+\expandafter\def\csname PYG at tok@si\endcsname{\let\PYG at it=\textit\def\PYG at tc##1{\textcolor[rgb]{0.44,0.63,0.82}{##1}}}
+\expandafter\def\csname PYG at tok@s2\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
+\expandafter\def\csname PYG at tok@nt\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.02,0.16,0.45}{##1}}}
+\expandafter\def\csname PYG at tok@nv\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.73,0.38,0.84}{##1}}}
+\expandafter\def\csname PYG at tok@s1\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
+\expandafter\def\csname PYG at tok@ch\endcsname{\let\PYG at it=\textit\def\PYG at tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
+\expandafter\def\csname PYG at tok@m\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
+\expandafter\def\csname PYG at tok@gp\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.78,0.36,0.04}{##1}}}
+\expandafter\def\csname PYG at tok@sh\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
+\expandafter\def\csname PYG at tok@ow\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@sx\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.78,0.36,0.04}{##1}}}
+\expandafter\def\csname PYG at tok@bp\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@c1\endcsname{\let\PYG at it=\textit\def\PYG at tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
+\expandafter\def\csname PYG at tok@o\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.40,0.40,0.40}{##1}}}
+\expandafter\def\csname PYG at tok@kc\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@c\endcsname{\let\PYG at it=\textit\def\PYG at tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
+\expandafter\def\csname PYG at tok@mf\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
+\expandafter\def\csname PYG at tok@err\endcsname{\def\PYG at bc##1{\setlength{\fboxsep}{0pt}\fcolorbox[rgb]{1.00,0.00,0.00}{1,1,1}{\strut ##1}}}
+\expandafter\def\csname PYG at tok@mb\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
+\expandafter\def\csname PYG at tok@ss\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.32,0.47,0.09}{##1}}}
+\expandafter\def\csname PYG at tok@sr\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.14,0.33,0.53}{##1}}}
+\expandafter\def\csname PYG at tok@mo\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
+\expandafter\def\csname PYG at tok@kd\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@mi\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.13,0.50,0.31}{##1}}}
+\expandafter\def\csname PYG at tok@kn\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@cpf\endcsname{\let\PYG at it=\textit\def\PYG at tc##1{\textcolor[rgb]{0.25,0.50,0.56}{##1}}}
+\expandafter\def\csname PYG at tok@kr\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@s\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
+\expandafter\def\csname PYG at tok@kp\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@w\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.73,0.73,0.73}{##1}}}
+\expandafter\def\csname PYG at tok@kt\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.56,0.13,0.00}{##1}}}
+\expandafter\def\csname PYG at tok@sc\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
+\expandafter\def\csname PYG at tok@sb\endcsname{\def\PYG at tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
+\expandafter\def\csname PYG at tok@k\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.00,0.44,0.13}{##1}}}
+\expandafter\def\csname PYG at tok@se\endcsname{\let\PYG at bf=\textbf\def\PYG at tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
+\expandafter\def\csname PYG at tok@sd\endcsname{\let\PYG at it=\textit\def\PYG at tc##1{\textcolor[rgb]{0.25,0.44,0.63}{##1}}}
+
+\def\PYGZbs{\char`\\}
+\def\PYGZus{\char`\_}
+\def\PYGZob{\char`\{}
+\def\PYGZcb{\char`\}}
+\def\PYGZca{\char`\^}
+\def\PYGZam{\char`\&}
+\def\PYGZlt{\char`\<}
+\def\PYGZgt{\char`\>}
+\def\PYGZsh{\char`\#}
+\def\PYGZpc{\char`\%}
+\def\PYGZdl{\char`\$}
+\def\PYGZhy{\char`\-}
+\def\PYGZsq{\char`\'}
+\def\PYGZdq{\char`\"}
+\def\PYGZti{\char`\~}
+% for compatibility with earlier versions
+\def\PYGZat{@}
+\def\PYGZlb{[}
+\def\PYGZrb{]}
+\makeatother
+
+\renewcommand\PYGZsq{\textquotesingle}
+
+\begin{document}
+
+\maketitle
+\tableofcontents
+\phantomsection\label{documentation::doc}
+
+
+Contents:
+
+
+\chapter{Introduction}
+\label{documentation:introduction}\label{documentation:welcome-to-umap-s-documentation}
+\textbf{The free umap software package efficiently identifies uniquely mappable regions of any genome.
+Its Bismap extension identifies mappability of the bisulfite converted genome (methylome).}
+
+the mappability of a genome for a given read length \emph{k}.
+First, it generates all possible \emph{k}-mers of the genome.
+Second, it maps these unique \emph{k}-mers to the genome with \href{http://bowtie-bio.sourceforge.net/index.shtml}{Bowtie} version 1.1.0.
+Third, Umap marks the start position of each \emph{k}-mer that aligns to only one region in the genome.
+Umap repeats these steps for a range of different \emph{k}-mers and stores the data of each chromosome
+in a binary vector \emph{X} with the same length as the chromosome's sequence.
+For read length \emph{k}, \(X_i = 1\) means that the sequence starting at \(X_i\) and ending
+at \(X_{i+k}\) is uniquely mappable on the forward strand.
+Since we align to both strands of the genome, the reverse complement of this same sequence
+starting at \(X_{i+k}\) on the reverse strand is also uniquely mappable.
+\(X_i = 0\) means that the sequence starting at \(X_i\) and ending at
+\(X_{i+k}\) can be mapped to at least two different regions in the genome.
+
+
+\chapter{Mappability of the bisulfite-converted genome}
+\label{documentation:mappability-of-the-bisulfite-converted-genome}
+To identify the single-read mappability of a bisulfite-converted genome,
+we create two altered genome sequences.
+In the first sequence, we convert all cytosines to thymine (C \(\rightarrow\) T).
+In the other sequence we convert all guanines to adenine (G \(\rightarrow\) A).
+Our approach follows those of \href{http://www.bioinformatics.babraham.ac.uk/projects/bismark/}{Bismark}
+and \href{https://github.com/brentp/bwa-meth}{BWA-meth}.
+We convert the genome sequence this way because bisulfite
+treatment converts un-methylated cytosine to uracil which is read as thymine.
+Similarly the guanine that is base-pairing with the un-methylated cytosine in
+reverse strand converts to adenine. However these two conversions never occur
+at the same time on the same read. We identify the uniquely mappable regions
+of these two genomes separately, and then combine the data to represent the
+single-read mappability of the forward and reverse strands in the bisulfite-converted genome.
+
+Bismap requires special handling of reverse complementation of C \(\rightarrow\) T
+or G \(\rightarrow\) A converted genomes.
+Conversion of C \(\rightarrow\) T on the sequence AATTCCGG produces AATT \textbf{TT} GG.
+In the Bowtie index, the reverse complement would be CCAAAATT.
+However for the purpose of identifying the mappability of the bisulfite-converted genome,
+we expect the reverse complement to be TTGGAA \textbf{TT}. The reason is that both forward and reverse
+strands undergo bisulfite treatment simultaneously. There is no DNA replication after bisulfite treatment.
+To handle this issue, Bismap creates its own reverse complemented chromosomes and suppresses Bowtie's usual reverse complement mapping.
+
+Umap and Bismap each take approximately 200 CPU hours to run for a given read length. This can be parallelized in a computing cluster over 400 cores to take only 30 minutes.
+
+
+\section{Measures of mappability}
+\label{documentation:measures-of-mappability}
+Umap efficiently identifies the single-read mappability of any genome for a
+range of sequencing read lengths. The single-read mappability of a genomic
+region is a fraction of that region which overlaps with at least one uniquely
+mappable \emph{k}-mer. The Bismap extension of Umap produces the single-read mappability
+of a bisulfite-converted genome. Both Umap and Bismap produce an integer vector for
+each chromosome that efficiently defines the mappability for any region and can be
+converted to a browser extensible data (BED) file. In addition to single-read mappability,
+we can measure the mappability of a genomic region by another approach. To quantify
+the single-read mappability of a given genomic region, we measure the fraction of
+potential uniquely mappable reads in that region. A region, however, can have 100\% single-read
+mappability, but in practice require a high coverage sequencing to properly identify that region.
+For example, a 1 kbp region with 100\% single-read mappability can be mappable due to a
+minimum of 10 unique 100-mers that none of them overlap or a maximum of 1100 unique 100-mers
+that highly overlap. Therefore, we define the multi-read mappability, the probability that a
+randomly selected read of length k in a given region is uniquely mappable. For the genomic
+region \(G_{i:j}\) starting at \emph{i} and ending at \emph{j}, there are \(j - i + k + 1\)
+\emph{k}-mers that overlap with \(G_{i:j}\).
+The multi-read mappability of \(G_{i:j}\) is the fraction of those \emph{k}-mers that are uniquely mappable.
+
+
+\chapter{Quick start}
+\label{documentation:quick-start}
+We have tested Umap installation on a CentOS system using python 2.7.11.
+Bismap requires numpy and pandas and it uses other python modules such as:
+\begin{itemize}
+\item {}
+gzip
+
+\item {}
+os
+
+\item {}
+re
+
+\item {}
+subprocess
+
+\end{itemize}
+
+Umap uses mercurial version control. Make sure that mercurial (hg) is installed.
+Download Umap to the directory of your python packages using:
+
+\begin{Verbatim}[commandchars=\\\{\}]
+\PYG{n}{hg} \PYG{n}{clone} \PYG{n}{https}\PYG{p}{:}\PYG{o}{/}\PYG{o}{/}\PYG{n}{bitbucket}\PYG{o}{.}\PYG{n}{org}\PYG{o}{/}\PYG{n}{hoffmanlab}\PYG{o}{/}\PYG{n}{umap}
+\PYG{n}{cd} \PYG{n}{umap}
+\PYG{n}{python} \PYG{n}{setup}\PYG{o}{.}\PYG{n}{py} \PYG{n}{install}
+\end{Verbatim}
+
+Now we will run a test using a wrapper in the umap directory called ubismap.py
+and a toy genome stored under umap/data
+
+\begin{Verbatim}[commandchars=\\\{\}]
+cd umap
+python ubismap.py data/genome.fa data/chrsize.tsv data/TestGenomeMappability all.q \PYGZdl{}BOWTIRDIR/bowtie\PYGZhy{}build \PYGZhy{}\PYGZhy{}kmer 8 12 \PYGZhy{}write\PYGZus{}script test\PYGZus{}run.sh
+sh test\PYGZus{}run.sh
+\end{Verbatim}
+
+The scripts that are produced by \textbf{ubismap.py} assume that you are using a Sun Grid Engine computing cluster.
+You can use parameters of this script to adjust it to your own system. You may need to manually edit this file
+because many of the SGE settings are very different than other computing clusters.
+However, all of the Umap modules accept \emph{-job\_id} which allows you to use the modules without a cluster or if
+your cluster does not support job arrays.
+
+Basically, the job array saves an environmental variable (defined by (\emph{-var\_id}) that Umap uses for paralellizing processes.
+You can run the modules in a for loop and set the \emph{-job\_id} manually.
+For example, in order to find \emph{k}-mers of a genome with 10 million base pairs, the get\_kmers
+and run\_bowtie modules each need to be executed with -job\_ids ranging between 1 to 10.
+
+
+\chapter{Get \emph{k}-mers}
+\label{documentation:get-k-mers}\label{documentation:module-umap}\index{umap (module)}\index{GetKmers (class in umap)}
+
+\begin{fulllineitems}
+\phantomsection\label{documentation:umap.GetKmers}\pysiglinewithargsret{\strong{class }\code{umap.}\bfcode{GetKmers}}{\emph{out\_dir}, \emph{kmer}, \emph{job\_id}, \emph{chr\_dir}, \emph{chrsize\_path}}{}
+\end{fulllineitems}
+
+
+
+\chapter{Run Bowtie}
+\label{documentation:run-bowtie}\index{BowtieWrapper (class in umap)}
+
+\begin{fulllineitems}
+\phantomsection\label{documentation:umap.BowtieWrapper}\pysiglinewithargsret{\strong{class }\code{umap.}\bfcode{BowtieWrapper}}{\emph{kmer\_dir}, \emph{bowtie\_dir}, \emph{index\_dir}, \emph{index\_name}, \emph{job\_id}}{}
+\end{fulllineitems}
+
+
+
+\chapter{Merge bowtie outputs}
+\label{documentation:merge-bowtie-outputs}\index{UnifyBowtie (class in umap)}
+
+\begin{fulllineitems}
+\phantomsection\label{documentation:umap.UnifyBowtie}\pysiglinewithargsret{\strong{class }\code{umap.}\bfcode{UnifyBowtie}}{\emph{bowtie\_outdir}, \emph{chrsize\_path}, \emph{job\_id}}{}
+\end{fulllineitems}
+
+
+
+\chapter{Merge data of various \emph{k}-mers}
+\label{documentation:merge-data-of-various-k-mers}\index{CombineUmaps (class in umap)}
+
+\begin{fulllineitems}
+\phantomsection\label{documentation:umap.CombineUmaps}\pysiglinewithargsret{\strong{class }\code{umap.}\bfcode{CombineUmaps}}{\emph{kmer\_dir}, \emph{chrsize\_path}, \emph{out\_dir}, \emph{job\_id}, \emph{kmer\_dir\_2}}{}
+\end{fulllineitems}
+
+
+
+\chapter{Convert numeric vectors to BED and Wiggle}
+\label{documentation:convert-numeric-vectors-to-bed-and-wiggle}\index{Int8Handler (class in umap)}
+
+\begin{fulllineitems}
+\phantomsection\label{documentation:umap.Int8Handler}\pysiglinewithargsret{\strong{class }\code{umap.}\bfcode{Int8Handler}}{\emph{in\_dir}, \emph{out\_dir}, \emph{C2T}, \emph{G2A}, \emph{chrsize\_path}}{}
+\end{fulllineitems}
+
+\index{write\_beds() (umap.Int8Handler method)}
+
+\begin{fulllineitems}
+\phantomsection\label{documentation:umap.Int8Handler.write_beds}\pysiglinewithargsret{\code{Int8Handler.}\bfcode{write\_beds}}{}{}
+\end{fulllineitems}
+
+\index{write\_as\_wig() (umap.Int8Handler method)}
+
+\begin{fulllineitems}
+\phantomsection\label{documentation:umap.Int8Handler.write_as_wig}\pysiglinewithargsret{\code{Int8Handler.}\bfcode{write\_as\_wig}}{}{}
+\end{fulllineitems}
+
+
+
+\chapter{Requesting Genomes}
+\label{documentation:requesting-genomes}
+In case you need these data for other genomes and do not have access to a Sun Grid Engine computing cluster,
+we may accept to do this for you.
+Please contact the software maintainer by email and we will do our best to assist you as soon as possible.
+
+
+\chapter{Contact, support and questions}
+\label{documentation:contact-support-and-questions}
+For support of Umap, please user our \href{https://groups.google.com/forum/\#!forum/ubismap}{mailing list}.
+Specifically, if you want to report a bug or request a feature,
+please do so using
+the \href{https://bitbucket.org/hoffmanlab/umap/issues}{Umap issue tracker}.
+We are interested in all comments on the package,
+and the ease of use of installation and documentation.
+
+
+\chapter{Indices and tables}
+\label{documentation:indices-and-tables}\begin{itemize}
+\item {}
+\DUrole{xref,std,std-ref}{genindex}
+
+\item {}
+\DUrole{xref,std,std-ref}{modindex}
+
+\item {}
+\DUrole{xref,std,std-ref}{search}
+
+\end{itemize}
+
+
+\renewcommand{\indexname}{Python Module Index}
+\begin{theindex}
+\def\bigletter#1{{\Large\sffamily#1}\nopagebreak\vspace{1mm}}
+\bigletter{u}
+\item {\texttt{umap}} \emph{(Unix)}, \pageref{documentation:module-umap}
+\end{theindex}
+
+\renewcommand{\indexname}{Index}
+\printindex
+\end{document}
diff --git a/doc/build/latex/Umap.toc b/doc/build/latex/Umap.toc
new file mode 100644
index 0000000..cd824a0
--- /dev/null
+++ b/doc/build/latex/Umap.toc
@@ -0,0 +1,15 @@
+\select at language {english}
+\contentsline {chapter}{\numberline {1}Introduction}{3}{chapter.1}
+\contentsline {chapter}{\numberline {2}Mappability of the bisulfite-converted genome}{5}{chapter.2}
+\contentsline {section}{\numberline {2.1}Measures of mappability}{5}{section.2.1}
+\contentsline {chapter}{\numberline {3}Quick start}{7}{chapter.3}
+\contentsline {chapter}{\numberline {4}Get \emph {k}-mers}{9}{chapter.4}
+\contentsline {chapter}{\numberline {5}Run Bowtie}{11}{chapter.5}
+\contentsline {chapter}{\numberline {6}Merge bowtie outputs}{13}{chapter.6}
+\contentsline {chapter}{\numberline {7}Merge data of various \emph {k}-mers}{15}{chapter.7}
+\contentsline {chapter}{\numberline {8}Convert numeric vectors to BED and Wiggle}{17}{chapter.8}
+\contentsline {chapter}{\numberline {9}Requesting Genomes}{19}{chapter.9}
+\contentsline {chapter}{\numberline {10}Contact, support and questions}{21}{chapter.10}
+\contentsline {chapter}{\numberline {11}Indices and tables}{23}{chapter.11}
+\contentsline {chapter}{Python Module Index}{25}{section*.10}
+\contentsline {chapter}{Index}{27}{section*.11}
diff --git a/doc/build/latex/fncychap.sty b/doc/build/latex/fncychap.sty
new file mode 100644
index 0000000..9a56c04
--- /dev/null
+++ b/doc/build/latex/fncychap.sty
@@ -0,0 +1,683 @@
+%%% Copyright Ulf A. Lindgren
+%%%
+%%% Note Premission is granted to modify this file under
+%%% the condition that it is saved using another
+%%% file and package name.
+%%%
+%%% Revision 1.1 (1997)
+%%%
+%%% Jan. 8th Modified package name base date option
+%%% Jan. 22th Modified FmN and FmTi for error in book.cls
+%%% \MakeUppercase{#}->{\MakeUppercase#}
+%%% Apr. 6th Modified Lenny option to prevent undesired
+%%% skip of line.
+%%% Nov. 8th Fixed \@chapapp for AMS
+%%%
+%%% Revision 1.2 (1998)
+%%%
+%%% Feb. 11th Fixed appendix problem related to Bjarne
+%%% Aug. 11th Fixed problem related to 11pt and 12pt
+%%% suggested by Tomas Lundberg. THANKS!
+%%%
+%%% Revision 1.3 (2004)
+%%% Sep. 20th problem with frontmatter, mainmatter and
+%%% backmatter, pointed out by Lapo Mori
+%%%
+%%% Revision 1.31 (2004)
+%%% Sep. 21th problem with the Rejne definition streched text
+%%% caused ugly gaps in the vrule aligned with the title
+%%% text. Kindly pointed out to me by Hendri Adriaens
+%%%
+%%% Revision 1.32 (2005)
+%%% Jun. 23th compatibility problem with the KOMA class 'scrbook.cls'
+%%% a remedy is a redefinition of '\@schapter' in
+%%% line with that used in KOMA. The problem was pointed
+%%% out to me by Mikkel Holm Olsen
+%%%
+%%% Revision 1.33 (2005)
+%%% Aug. 9th misspelled ``TWELV'' corrected, the error was pointed
+%%% out to me by George Pearson
+%%%
+%%% Revision 1.34 (2007)
+%%% Added an alternative to Lenny provided by Peter
+%%% Osborne (2005-11-28)
+%%% Corrected front, main and back matter, based on input
+%%% from Bas van Gils (2006-04-24)
+%%% Jul. 30th Added Bjornstrup option provided by Jean-Marc
+%%% Francois (2007-01-05).
+%%% Reverted to \MakeUppercase{#} see rev 1.1, solved
+%%% problem with MakeUppercase and MakeLowercase pointed
+%%% out by Marco Feuerstein (2007-06-06)
+
+
+%%% Last modified Jul. 2007
+
+\NeedsTeXFormat{LaTeX2e}[1995/12/01]
+\ProvidesPackage{fncychap}
+ [2007/07/30 v1.34
+ LaTeX package (Revised chapters)]
+
+%%%% For conditional inclusion of color
+\newif\ifusecolor
+\usecolorfalse
+
+
+
+%%%% DEFINITION OF Chapapp variables
+\newcommand{\CNV}{\huge\bfseries}
+\newcommand{\ChNameVar}[1]{\renewcommand{\CNV}{#1}}
+
+
+%%%% DEFINITION OF TheChapter variables
+\newcommand{\CNoV}{\huge\bfseries}
+\newcommand{\ChNumVar}[1]{\renewcommand{\CNoV}{#1}}
+
+\newif\ifUCN
+\UCNfalse
+\newif\ifLCN
+\LCNfalse
+\def\ChNameLowerCase{\LCNtrue\UCNfalse}
+\def\ChNameUpperCase{\UCNtrue\LCNfalse}
+\def\ChNameAsIs{\UCNfalse\LCNfalse}
+
+%%%%% Fix for AMSBook 971008
+
+\@ifundefined{@chapapp}{\let\@chapapp\chaptername}{}
+
+
+%%%%% Fix for Bjarne and appendix 980211
+
+\newif\ifinapp
+\inappfalse
+\renewcommand\appendix{\par
+ \setcounter{chapter}{0}%
+ \setcounter{section}{0}%
+ \inapptrue%
+ \renewcommand\@chapapp{\appendixname}%
+ \renewcommand\thechapter{\@Alph\c at chapter}}
+
+%%%%% Fix for frontmatter, mainmatter, and backmatter 040920
+
+\@ifundefined{@mainmatter}{\newif\if at mainmatter \@mainmattertrue}{}
+
+%%%%%
+
+
+
+\newcommand{\FmN}[1]{%
+\ifUCN
+ {\MakeUppercase{#1}}\LCNfalse
+\else
+ \ifLCN
+ {\MakeLowercase{#1}}\UCNfalse
+ \else #1
+ \fi
+\fi}
+
+
+%%%% DEFINITION OF Title variables
+\newcommand{\CTV}{\Huge\bfseries}
+\newcommand{\ChTitleVar}[1]{\renewcommand{\CTV}{#1}}
+
+%%%% DEFINITION OF the basic rule width
+\newlength{\RW}
+\setlength{\RW}{1pt}
+\newcommand{\ChRuleWidth}[1]{\setlength{\RW}{#1}}
+
+\newif\ifUCT
+\UCTfalse
+\newif\ifLCT
+\LCTfalse
+\def\ChTitleLowerCase{\LCTtrue\UCTfalse}
+\def\ChTitleUpperCase{\UCTtrue\LCTfalse}
+\def\ChTitleAsIs{\UCTfalse\LCTfalse}
+\newcommand{\FmTi}[1]{%
+\ifUCT
+ {\MakeUppercase{#1}}\LCTfalse
+\else
+ \ifLCT
+ {\MakeLowercase{#1}}\UCTfalse
+ \else {#1}
+ \fi
+\fi}
+
+
+
+\newlength{\mylen}
+\newlength{\myhi}
+\newlength{\px}
+\newlength{\py}
+\newlength{\pyy}
+\newlength{\pxx}
+
+
+\def\mghrulefill#1{\leavevmode\leaders\hrule\@height #1\hfill\kern\z@}
+
+\newcommand{\DOCH}{%
+ \CNV\FmN{\@chapapp}\space \CNoV\thechapter
+ \par\nobreak
+ \vskip 20\p@
+ }
+\newcommand{\DOTI}[1]{%
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 40\p@
+ }
+\newcommand{\DOTIS}[1]{%
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 40\p@
+ }
+
+%%%%%% SONNY DEF
+
+\DeclareOption{Sonny}{%
+ \ChNameVar{\Large\sf}
+ \ChNumVar{\Huge}
+ \ChTitleVar{\Large\sf}
+ \ChRuleWidth{0.5pt}
+ \ChNameUpperCase
+ \renewcommand{\DOCH}{%
+ \raggedleft
+ \CNV\FmN{\@chapapp}\space \CNoV\thechapter
+ \par\nobreak
+ \vskip 40\p@}
+ \renewcommand{\DOTI}[1]{%
+ \CTV\raggedleft\mghrulefill{\RW}\par\nobreak
+ \vskip 5\p@
+ \CTV\FmTi{#1}\par\nobreak
+ \mghrulefill{\RW}\par\nobreak
+ \vskip 40\p@}
+ \renewcommand{\DOTIS}[1]{%
+ \CTV\raggedleft\mghrulefill{\RW}\par\nobreak
+ \vskip 5\p@
+ \CTV\FmTi{#1}\par\nobreak
+ \mghrulefill{\RW}\par\nobreak
+ \vskip 40\p@}
+}
+
+%%%%%% LENNY DEF
+
+\DeclareOption{Lenny}{%
+
+ \ChNameVar{\fontsize{14}{16}\usefont{OT1}{phv}{m}{n}\selectfont}
+ \ChNumVar{\fontsize{60}{62}\usefont{OT1}{ptm}{m}{n}\selectfont}
+ \ChTitleVar{\Huge\bfseries\rm}
+ \ChRuleWidth{1pt}
+ \renewcommand{\DOCH}{%
+ \settowidth{\px}{\CNV\FmN{\@chapapp}}
+ \addtolength{\px}{2pt}
+ \settoheight{\py}{\CNV\FmN{\@chapapp}}
+ \addtolength{\py}{1pt}
+
+ \settowidth{\mylen}{\CNV\FmN{\@chapapp}\space\CNoV\thechapter}
+ \addtolength{\mylen}{1pt}
+ \settowidth{\pxx}{\CNoV\thechapter}
+ \addtolength{\pxx}{-1pt}
+
+ \settoheight{\pyy}{\CNoV\thechapter}
+ \addtolength{\pyy}{-2pt}
+ \setlength{\myhi}{\pyy}
+ \addtolength{\myhi}{-1\py}
+ \par
+ \parbox[b]{\textwidth}{%
+ \rule[\py]{\RW}{\myhi}%
+ \hskip -\RW%
+ \rule[\pyy]{\px}{\RW}%
+ \hskip -\px%
+ \raggedright%
+ \CNV\FmN{\@chapapp}\space\CNoV\thechapter%
+ \hskip1pt%
+ \mghrulefill{\RW}%
+ \rule{\RW}{\pyy}\par\nobreak%
+ \vskip -\baselineskip%
+ \vskip -\pyy%
+ \hskip \mylen%
+ \mghrulefill{\RW}\par\nobreak%
+ \vskip \pyy}%
+ \vskip 20\p@}
+
+
+ \renewcommand{\DOTI}[1]{%
+ \raggedright
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 40\p@}
+
+ \renewcommand{\DOTIS}[1]{%
+ \raggedright
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 40\p@}
+ }
+
+%%%%%% Peter Osbornes' version of LENNY DEF
+
+\DeclareOption{PetersLenny}{%
+
+% five new lengths
+\newlength{\bl} % bottom left : orig \space
+\setlength{\bl}{6pt}
+\newcommand{\BL}[1]{\setlength{\bl}{#1}}
+\newlength{\br} % bottom right : orig 1pt
+\setlength{\br}{1pt}
+\newcommand{\BR}[1]{\setlength{\br}{#1}}
+\newlength{\tl} % top left : orig 2pt
+\setlength{\tl}{2pt}
+\newcommand{\TL}[1]{\setlength{\tl}{#1}}
+\newlength{\trr} % top right :orig 1pt
+\setlength{\trr}{1pt}
+\newcommand{\TR}[1]{\setlength{\trr}{#1}}
+\newlength{\blrule} % top right :orig 1pt
+\setlength{\trr}{0pt}
+\newcommand{\BLrule}[1]{\setlength{\blrule}{#1}}
+
+
+ \ChNameVar{\fontsize{14}{16}\usefont{OT1}{phv}{m}{n}\selectfont}
+ \ChNumVar{\fontsize{60}{62}\usefont{OT1}{ptm}{m}{n}\selectfont}
+ \ChTitleVar{\Huge\bfseries\rm}
+ \ChRuleWidth{1pt}
+\renewcommand{\DOCH}{%
+
+
+%%%%%%% tweaks for 1--9 and A--Z
+\ifcase\c at chapter\relax%
+\or\BL{-3pt}\TL{-4pt}\BR{0pt}\TR{-6pt}%1
+\or\BL{0pt}\TL{-4pt}\BR{2pt}\TR{-4pt}%2
+\or\BL{0pt}\TL{-4pt}\BR{2pt}\TR{-4pt}%3
+\or\BL{0pt}\TL{5pt}\BR{2pt}\TR{-4pt}%4
+\or\BL{0pt}\TL{3pt}\BR{2pt}\TR{-4pt}%5
+\or\BL{-1pt}\TL{0pt}\BR{2pt}\TR{-2pt}%6
+\or\BL{0pt}\TL{-3pt}\BR{2pt}\TR{-2pt}%7
+\or\BL{0pt}\TL{-3pt}\BR{2pt}\TR{-2pt}%8
+\or\BL{0pt}\TL{-3pt}\BR{-4pt}\TR{-2pt}%9
+\or\BL{-3pt}\TL{-3pt}\BR{2pt}\TR{-7pt}%10
+\or\BL{-6pt}\TL{-6pt}\BR{0pt}\TR{-9pt}%11
+\or\BL{-6pt}\TL{-6pt}\BR{2pt}\TR{-7pt}%12
+\or\BL{-5pt}\TL{-5pt}\BR{0pt}\TR{-9pt}%13
+\or\BL{-6pt}\TL{-6pt}\BR{0pt}\TR{-9pt}%14
+\or\BL{-3pt}\TL{-3pt}\BR{3pt}\TR{-6pt}%15
+\or\BL{-3pt}\TL{-3pt}\BR{3pt}\TR{-6pt}%16
+\or\BL{-5pt}\TL{-3pt}\BR{-8pt}\TR{-6pt}%17
+\or\BL{-5pt}\TL{-5pt}\BR{0pt}\TR{-9pt}%18
+\or\BL{-3pt}\TL{-3pt}\BR{-6pt}\TR{-9pt}%19
+\or\BL{0pt}\TL{0pt}\BR{0pt}\TR{-5pt}%20
+\fi
+
+\ifinapp\ifcase\c at chapter\relax%
+\or\BL{0pt}\TL{14pt}\BR{5pt}\TR{-19pt}%A
+\or\BL{0pt}\TL{-5pt}\BR{-3pt}\TR{-8pt}%B
+\or\BL{-3pt}\TL{-2pt}\BR{1pt}\TR{-6pt}\BLrule{0pt}%C
+\or\BL{0pt}\TL{-5pt}\BR{-3pt}\TR{-8pt}\BLrule{0pt}%D
+\or\BL{0pt}\TL{-5pt}\BR{2pt}\TR{-3pt}%E
+\or\BL{0pt}\TL{-5pt}\BR{-10pt}\TR{-1pt}%F
+\or\BL{-3pt}\TL{0pt}\BR{0pt}\TR{-7pt}%G
+\or\BL{0pt}\TL{-5pt}\BR{3pt}\TR{-1pt}%H
+\or\BL{0pt}\TL{-5pt}\BR{3pt}\TR{-1pt}%I
+\or\BL{2pt}\TL{0pt}\BR{-3pt}\TR{1pt}%J
+\or\BL{0pt}\TL{-5pt}\BR{3pt}\TR{-1pt}%K
+\or\BL{0pt}\TL{-5pt}\BR{2pt}\TR{-19pt}%L
+\or\BL{0pt}\TL{-5pt}\BR{3pt}\TR{-1pt}%M
+\or\BL{0pt}\TL{-5pt}\BR{-2pt}\TR{-1pt}%N
+\or\BL{-3pt}\TL{-2pt}\BR{-3pt}\TR{-11pt}%O
+\or\BL{0pt}\TL{-5pt}\BR{-9pt}\TR{-3pt}%P
+\or\BL{-3pt}\TL{-2pt}\BR{-3pt}\TR{-11pt}%Q
+\or\BL{0pt}\TL{-5pt}\BR{4pt}\TR{-8pt}%R
+\or\BL{-2pt}\TL{-2pt}\BR{-2pt}\TR{-7pt}%S
+\or\BL{-3pt}\TL{0pt}\BR{-5pt}\TR{4pt}\BLrule{8pt}%T
+\or\BL{-7pt}\TL{-11pt}\BR{-5pt}\TR{-7pt}\BLrule{0pt}%U
+\or\BL{-14pt}\TL{-5pt}\BR{-14pt}\TR{-1pt}\BLrule{14pt}%V
+\or\BL{-10pt}\TL{-9pt}\BR{-13pt}\TR{-3pt}\BLrule{7pt}%W
+\or\BL{0pt}\TL{-5pt}\BR{3pt}\TR{-1pt}\BLrule{0pt}%X
+\or\BL{-6pt}\TL{-4pt}\BR{-7pt}\TR{1pt}\BLrule{7pt}%Y
+\or\BL{0pt}\TL{-5pt}\BR{3pt}\TR{-1pt}\BLrule{0pt}%Z
+\fi\fi
+%%%%%%%
+ \settowidth{\px}{\CNV\FmN{\@chapapp}}
+ \addtolength{\px}{\tl} %MOD change 2pt to \tl
+ \settoheight{\py}{\CNV\FmN{\@chapapp}}
+ \addtolength{\py}{1pt}
+
+ \settowidth{\mylen}{\CNV\FmN{\@chapapp}\space\CNoV\thechapter}
+ \addtolength{\mylen}{\trr}% MOD change 1pt to \tr
+ \settowidth{\pxx}{\CNoV\thechapter}
+ \addtolength{\pxx}{-1pt}
+
+ \settoheight{\pyy}{\CNoV\thechapter}
+ \addtolength{\pyy}{-2pt}
+ \setlength{\myhi}{\pyy}
+ \addtolength{\myhi}{-1\py}
+ \par
+ \parbox[b]{\textwidth}{%
+ \rule[\py]{\RW}{\myhi}%
+ \hskip -\RW%
+ \rule[\pyy]{\px}{\RW}%
+ \hskip -\px%
+ \raggedright%
+ \CNV\FmN{\@chapapp}\rule{\blrule}{\RW}\hskip\bl\CNoV\thechapter%MOD
+% \CNV\FmN{\@chapapp}\space\CNoV\thechapter %ORIGINAL
+ \hskip\br% %MOD 1pt to \br
+ \mghrulefill{\RW}%
+ \rule{\RW}{\pyy}\par\nobreak%
+ \vskip -\baselineskip%
+ \vskip -\pyy%
+ \hskip \mylen%
+ \mghrulefill{\RW}\par\nobreak%
+ \vskip \pyy}%
+ \vskip 20\p@}
+
+
+ \renewcommand{\DOTI}[1]{%
+ \raggedright
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 40\p@}
+
+ \renewcommand{\DOTIS}[1]{%
+ \raggedright
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 40\p@}
+ }
+
+
+%
+
+
+%%%%%% BJORNSTRUP DEF
+
+\DeclareOption{Bjornstrup}{%
+ \usecolortrue
+ % pzc (Zapf Chancelery) is nice. ppl (Palatino) is cool too.
+ \ChNumVar{\fontsize{76}{80}\usefont{OT1}{pzc}{m}{n}\selectfont}
+ \ChTitleVar{\raggedleft\Large\sffamily\bfseries}
+
+ \setlength{\myhi}{10pt} % Space between grey box border and text
+ \setlength{\mylen}{\textwidth}
+ \addtolength{\mylen}{-2\myhi}
+ \renewcommand{\DOCH}{%
+ \settowidth{\py}{\CNoV\thechapter}
+ \addtolength{\py}{-10pt} % Amount of space by which the
+% % number is shifted right
+ \fboxsep=0pt%
+ \colorbox[gray]{.85}{\rule{0pt}{40pt}\parbox[b]{\textwidth}{\hfill}}%
+ \kern-\py\raise20pt%
+ \hbox{\color[gray]{.5}\CNoV\thechapter}\\%
+ }
+
+ \renewcommand{\DOTI}[1]{%
+ \nointerlineskip\raggedright%
+ \fboxsep=\myhi%
+ \vskip-1ex%
+ \colorbox[gray]{.85}{\parbox[t]{\mylen}{\CTV\FmTi{#1}}}\par\nobreak%
+ \vskip 40\p@%
+ }
+
+ \renewcommand{\DOTIS}[1]{%
+ \fboxsep=0pt
+ \colorbox[gray]{.85}{\rule{0pt}{40pt}\parbox[b]{\textwidth}{\hfill}}\\%
+ \nointerlineskip\raggedright%
+ \fboxsep=\myhi%
+ \colorbox[gray]{.85}{\parbox[t]{\mylen}{\CTV\FmTi{#1}}}\par\nobreak%
+ \vskip 40\p@%
+ }
+}
+
+
+%%%%%%% GLENN DEF
+
+
+\DeclareOption{Glenn}{%
+ \ChNameVar{\bfseries\Large\sf}
+ \ChNumVar{\Huge}
+ \ChTitleVar{\bfseries\Large\rm}
+ \ChRuleWidth{1pt}
+ \ChNameUpperCase
+ \ChTitleUpperCase
+ \renewcommand{\DOCH}{%
+ \settoheight{\myhi}{\CTV\FmTi{Test}}
+ \setlength{\py}{\baselineskip}
+ \addtolength{\py}{\RW}
+ \addtolength{\py}{\myhi}
+ \setlength{\pyy}{\py}
+ \addtolength{\pyy}{-1\RW}
+
+ \raggedright
+ \CNV\FmN{\@chapapp}\space\CNoV\thechapter
+ \hskip 3pt\mghrulefill{\RW}\rule[-1\pyy]{2\RW}{\py}\par\nobreak}
+
+ \renewcommand{\DOTI}[1]{%
+ \addtolength{\pyy}{-4pt}
+ \settoheight{\myhi}{\CTV\FmTi{#1}}
+ \addtolength{\myhi}{\py}
+ \addtolength{\myhi}{-1\RW}
+ \vskip -1\pyy
+ \rule{2\RW}{\myhi}\mghrulefill{\RW}\hskip 2pt
+ \raggedleft\CTV\FmTi{#1}\par\nobreak
+ \vskip 80\p@}
+
+\newlength{\backskip}
+ \renewcommand{\DOTIS}[1]{%
+% \setlength{\py}{10pt}
+% \setlength{\pyy}{\py}
+% \addtolength{\pyy}{\RW}
+% \setlength{\myhi}{\baselineskip}
+% \addtolength{\myhi}{\pyy}
+% \mghrulefill{\RW}\rule[-1\py]{2\RW}{\pyy}\par\nobreak
+% \addtolength{}{}
+%\vskip -1\baselineskip
+% \rule{2\RW}{\myhi}\mghrulefill{\RW}\hskip 2pt
+% \raggedleft\CTV\FmTi{#1}\par\nobreak
+% \vskip 60\p@}
+%% Fix suggested by Tomas Lundberg
+ \setlength{\py}{25pt} % eller vad man vill
+ \setlength{\pyy}{\py}
+ \setlength{\backskip}{\py}
+ \addtolength{\backskip}{2pt}
+ \addtolength{\pyy}{\RW}
+ \setlength{\myhi}{\baselineskip}
+ \addtolength{\myhi}{\pyy}
+ \mghrulefill{\RW}\rule[-1\py]{2\RW}{\pyy}\par\nobreak
+ \vskip -1\backskip
+ \rule{2\RW}{\myhi}\mghrulefill{\RW}\hskip 3pt %
+ \raggedleft\CTV\FmTi{#1}\par\nobreak
+ \vskip 40\p@}
+ }
+
+%%%%%%% CONNY DEF
+
+\DeclareOption{Conny}{%
+ \ChNameUpperCase
+ \ChTitleUpperCase
+ \ChNameVar{\centering\Huge\rm\bfseries}
+ \ChNumVar{\Huge}
+ \ChTitleVar{\centering\Huge\rm}
+ \ChRuleWidth{2pt}
+
+ \renewcommand{\DOCH}{%
+ \mghrulefill{3\RW}\par\nobreak
+ \vskip -0.5\baselineskip
+ \mghrulefill{\RW}\par\nobreak
+ \CNV\FmN{\@chapapp}\space \CNoV\thechapter
+ \par\nobreak
+ \vskip -0.5\baselineskip
+ }
+ \renewcommand{\DOTI}[1]{%
+ \mghrulefill{\RW}\par\nobreak
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 60\p@
+ }
+ \renewcommand{\DOTIS}[1]{%
+ \mghrulefill{\RW}\par\nobreak
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 60\p@
+ }
+ }
+
+%%%%%%% REJNE DEF
+
+\DeclareOption{Rejne}{%
+
+ \ChNameUpperCase
+ \ChTitleUpperCase
+ \ChNameVar{\centering\Large\rm}
+ \ChNumVar{\Huge}
+ \ChTitleVar{\centering\Huge\rm}
+ \ChRuleWidth{1pt}
+ \renewcommand{\DOCH}{%
+ \settoheight{\py}{\CNoV\thechapter}
+ \parskip=0pt plus 1pt % Set parskip to default, just in case v1.31
+ \addtolength{\py}{-1pt}
+ \CNV\FmN{\@chapapp}\par\nobreak
+ \vskip 20\p@
+ \setlength{\myhi}{2\baselineskip}
+ \setlength{\px}{\myhi}
+ \addtolength{\px}{-1\RW}
+ \rule[-1\px]{\RW}{\myhi}\mghrulefill{\RW}\hskip
+ 10pt\raisebox{-0.5\py}{\CNoV\thechapter}\hskip 10pt\mghrulefill{\RW}\rule[-1\px]{\RW}{\myhi}\par\nobreak
+ \vskip -3\p@% Added -2pt vskip to correct for streched text v1.31
+ }
+ \renewcommand{\DOTI}[1]{%
+ \setlength{\mylen}{\textwidth}
+ \parskip=0pt plus 1pt % Set parskip to default, just in case v1.31
+ \addtolength{\mylen}{-2\RW}
+ {\vrule width\RW}\parbox{\mylen}{\CTV\FmTi{#1}}{\vrule width\RW}\par\nobreak%
+ \vskip -3pt\rule{\RW}{2\baselineskip}\mghrulefill{\RW}\rule{\RW}{2\baselineskip}%
+ \vskip 60\p@% Added -2pt in vskip to correct for streched text v1.31
+ }
+ \renewcommand{\DOTIS}[1]{%
+ \setlength{\py}{\fboxrule}
+ \setlength{\fboxrule}{\RW}
+ \setlength{\mylen}{\textwidth}
+ \addtolength{\mylen}{-2\RW}
+ \fbox{\parbox{\mylen}{\vskip 2\baselineskip\CTV\FmTi{#1}\par\nobreak\vskip \baselineskip}}
+ \setlength{\fboxrule}{\py}
+ \vskip 60\p@
+ }
+ }
+
+
+%%%%%%% BJARNE DEF
+
+\DeclareOption{Bjarne}{%
+ \ChNameUpperCase
+ \ChTitleUpperCase
+ \ChNameVar{\raggedleft\normalsize\rm}
+ \ChNumVar{\raggedleft \bfseries\Large}
+ \ChTitleVar{\raggedleft \Large\rm}
+ \ChRuleWidth{1pt}
+
+
+%% Note thechapter -> c at chapter fix appendix bug
+%% Fixed misspelled 12
+
+ \newcounter{AlphaCnt}
+ \newcounter{AlphaDecCnt}
+ \newcommand{\AlphaNo}{%
+ \ifcase\number\theAlphaCnt
+ \ifnum\c at chapter=0
+ ZERO\else{}\fi
+ \or ONE\or TWO\or THREE\or FOUR\or FIVE
+ \or SIX\or SEVEN\or EIGHT\or NINE\or TEN
+ \or ELEVEN\or TWELVE\or THIRTEEN\or FOURTEEN\or FIFTEEN
+ \or SIXTEEN\or SEVENTEEN\or EIGHTEEN\or NINETEEN\fi
+}
+
+ \newcommand{\AlphaDecNo}{%
+ \setcounter{AlphaDecCnt}{0}
+ \@whilenum\number\theAlphaCnt>0\do
+ {\addtocounter{AlphaCnt}{-10}
+ \addtocounter{AlphaDecCnt}{1}}
+ \ifnum\number\theAlphaCnt=0
+ \else
+ \addtocounter{AlphaDecCnt}{-1}
+ \addtocounter{AlphaCnt}{10}
+ \fi
+
+
+ \ifcase\number\theAlphaDecCnt\or TEN\or TWENTY\or THIRTY\or
+ FORTY\or FIFTY\or SIXTY\or SEVENTY\or EIGHTY\or NINETY\fi
+ }
+ \newcommand{\TheAlphaChapter}{%
+
+ \ifinapp
+ \thechapter
+ \else
+ \setcounter{AlphaCnt}{\c at chapter}
+ \ifnum\c at chapter<20
+ \AlphaNo
+ \else
+ \AlphaDecNo\AlphaNo
+ \fi
+ \fi
+ }
+ \renewcommand{\DOCH}{%
+ \mghrulefill{\RW}\par\nobreak
+ \CNV\FmN{\@chapapp}\par\nobreak
+ \CNoV\TheAlphaChapter\par\nobreak
+ \vskip -1\baselineskip\vskip 5pt\mghrulefill{\RW}\par\nobreak
+ \vskip 20\p@
+ }
+ \renewcommand{\DOTI}[1]{%
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 40\p@
+ }
+ \renewcommand{\DOTIS}[1]{%
+ \CTV\FmTi{#1}\par\nobreak
+ \vskip 40\p@
+ }
+}
+
+\DeclareOption*{%
+ \PackageWarning{fancychapter}{unknown style option}
+ }
+
+\ProcessOptions* \relax
+
+\ifusecolor
+ \RequirePackage{color}
+\fi
+\def\@makechapterhead#1{%
+ \vspace*{50\p@}%
+ {\parindent \z@ \raggedright \normalfont
+ \ifnum \c at secnumdepth >\m at ne
+ \if at mainmatter%%%%% Fix for frontmatter, mainmatter, and backmatter 040920
+ \DOCH
+ \fi
+ \fi
+ \interlinepenalty\@M
+ \if at mainmatter%%%%% Fix for frontmatter, mainmatter, and backmatter 060424
+ \DOTI{#1}%
+ \else%
+ \DOTIS{#1}%
+ \fi
+ }}
+
+
+%%% Begin: To avoid problem with scrbook.cls (fncychap version 1.32)
+
+%%OUT:
+%\def\@schapter#1{\if at twocolumn
+% \@topnewpage[\@makeschapterhead{#1}]%
+% \else
+% \@makeschapterhead{#1}%
+% \@afterheading
+% \fi}
+
+%%IN:
+\def\@schapter#1{%
+\if at twocolumn%
+ \@makeschapterhead{#1}%
+\else%
+ \@makeschapterhead{#1}%
+ \@afterheading%
+\fi}
+
+%%% End: To avoid problem with scrbook.cls (fncychap version 1.32)
+
+\def\@makeschapterhead#1{%
+ \vspace*{50\p@}%
+ {\parindent \z@ \raggedright
+ \normalfont
+ \interlinepenalty\@M
+ \DOTIS{#1}
+ \vskip 40\p@
+ }}
+
+\endinput
+
+
diff --git a/doc/build/latex/newfloat.sty b/doc/build/latex/newfloat.sty
new file mode 100644
index 0000000..47ac5e5
--- /dev/null
+++ b/doc/build/latex/newfloat.sty
@@ -0,0 +1,737 @@
+%%
+%% This is file `newfloat.sty',
+%% generated with the docstrip utility.
+%%
+%% The original source files were:
+%%
+%% newfloat.dtx (with options: `package')
+%%
+%% Copyright (C) 1994-2016 Axel Sommerfeldt (axel.sommerfeldt at f-m.fm)
+%%
+%% http://sourceforge.net/projects/latex-caption/
+%%
+%% --------------------------------------------------------------------------
+%%
+%% This work may be distributed and/or modified under the
+%% conditions of the LaTeX Project Public License, either version 1.3
+%% of this license or (at your option) any later version.
+%% The latest version of this license is in
+%% http://www.latex-project.org/lppl.txt
+%% and version 1.3 or later is part of all distributions of LaTeX
+%% version 2003/12/01 or later.
+%%
+%% This work has the LPPL maintenance status "maintained".
+%%
+%% This Current Maintainer of this work is Axel Sommerfeldt.
+%%
+%% This work consists of the files
+%% CHANGELOG, README, SUMMARY, caption.ins,
+%% caption.dtx, caption2.dtx, caption3.dtx,
+%% bicaption.dtx, ltcaption.dtx, subcaption.dtx,
+%% newfloat.dtx, and totalcount.dtx
+%% the derived files
+%% caption.sty, caption2.sty, caption3.sty,
+%% bicaption.sty, ltcaption.sty, subcaption.sty,
+%% newfloat.sty, and totalcount.sty
+%% and the user manuals
+%% caption-deu.tex, caption-eng.tex, and caption-rus.tex.
+%%
+\NeedsTeXFormat{LaTeX2e}[1994/12/01]
+\def\caption at tempa$Id: #1 #2 #3-#4-#5 #6${%
+ \def\caption at tempa{#3/#4/#5 }\def\caption at tempb{#2 }}
+\caption at tempa $Id: newfloat.dtx 109 2015-09-17 09:29:07Z sommerfeldt $
+\ProvidesPackage{newfloat}[\caption at tempa v1.1-\caption at tempb Defining new floating environments (AR)]
+\newcommand*\newfloat at Info[1]{%
+ \PackageInfo{newfloat}{#1}}
+\newcommand*\newfloat at InfoNoLine[1]{%
+ \newfloat at Info{#1\@gobble}}
+\newcommand*\newfloat at Error[1]{%
+ \PackageError{newfloat}{#1}\newfloat at eh}
+\newcommand*\newfloat at eh{%
+ If you do not understand this error, please take a closer look\MessageBreak
+ at the documentation of the `newfloat' package.\MessageBreak\@ehc}
+\RequirePackage{keyval}[1997/11/10]
+\newcommand*\newfloat at def[2]{%
+ \newfloat at ifundefined{#1}{%
+ \@namedef{#1}{#2}}}
+\newcommand*\newfloat at let[2]{%
+ \newfloat at ifundefined{#1}{%
+ \expandafter\let\csname #1\endcsname#2}}
+\newcommand*\newfloat at ifundefined[2]{%
+ \@ifundefined{#1}{#2}{%
+ \newfloat at Info{%
+ \expandafter\string\csname#1\endcsname\space is already defined}}}
+\newcommand*\DeclareFloatingEnvironment{%
+ \@testopt\@DeclareFloatingEnvironment{}}
+\@onlypreamble\DeclareFloatingEnvironment
+\def\@DeclareFloatingEnvironment[#1]#2{%
+ \newfloat at Info{New float `#2' with options `#1'}%
+ \newfloat at ifundefined{c@#2}{\newcounter{#2}}%
+ \ifdefined\c at float@type % from float package
+ \expandafter\edef\csname ftype@#2\endcsname{\the\value{float at type}}%
+ \addtocounter{float at type}{\value{float at type}}%
+ \else\ifdefined\c at newflo@tctr % from memoir document class
+ \expandafter\edef\csname ftype@#2\endcsname{\the\c at newflo@tctr}%
+ \advance\c at newflo@tctr \c at newflo@tctr
+ \else
+ \ifdefined\newfloat at ftype \else
+ \newcount\newfloat at ftype
+ \newfloat at ftype=8\relax
+ \fi
+ \expandafter\xdef\csname ftype@#2\endcsname{\the\newfloat at ftype}%
+ \advance\newfloat at ftype\newfloat at ftype
+ \fi\fi
+ \newfloat at Info{float type `#2'=\@nameuse{ftype@#2}}%
+ \newfloat at def{fnum@#2}%
+ {\@nameuse{#2name}\nobreakspace\@nameuse{the#2}\@nameuse{autodot}}%
+ \newfloat at capitalize\newfloat at Type{#2}%
+ \newfloat at let{#2name}{\newfloat at Type}%
+ \newfloat at def{fleg#2}{\@nameuse{#2name}}% legend naming (memoir)
+ \newfloat at ifundefined{flegtoc#2}{\@namedef{flegtoc#2}##1{}}%
+ \ifcsname @tufte at float\endcsname
+ \newenvironment{#2}[1][htbp]%
+ {\begin{@tufte at float}[##1]{#2}{}}%
+ {\end{@tufte at float}}%
+ \newenvironment{#2*}[1][htbp]%
+ {\begin{@tufte at float}[##1]{#2}{star}}%
+ {\end{@tufte at float}}%
+ \else
+ \newenvironment{#2}{\@float{#2}}{\end at float}%
+ \newenvironment{#2*}{\@dblfloat{#2}}{\end at dblfloat}%
+ \fi
+ \newfloat at def{listof#2}{\newfloat at listof{#2}}%
+ \newfloat at def{listof#2s}{\@nameuse{listof#2}}%
+ \newfloat at def{listof#2es}{\@nameuse{listof#2s}}%
+ \newfloat at def{newfloat at listof#2 at hook}{}%
+ \ifdefined\l at figure
+ \newfloat at let{l@#2}{\l at figure}%
+ \else
+ \newfloat at def{l@#2}{\@dottedtocline{1}{1.5em}{2.3em}}%
+ \fi
+ \edef\newfloat at tempa{List of \newfloat at Type s}%
+ \newfloat at let{list#2name}{\newfloat at tempa}%
+ \expandafter\let\csname fst@#2\endcsname\@undefined
+ \newfloat at ifundefined{fps@#2}{\newfloat at setplacement{#2}{tbp}}%
+ \newfloat at ifundefined{ext@#2}{\newfloat at setfileext{#2}{lo#2}}%
+ \newfloat at setoptions*{#2}{#1}%
+ \@expandtwoargs\newfloat at announce{#2}{\@nameuse{ext@#2}}%
+ \@ifnextchar[\newfloat at DFE@setname\relax}
+\@onlypreamble\@DeclareFloatingEnvironment
+\def\newfloat at DFE@setname[#1]{%
+ \KV@@newfloat at name{#1}%
+ \@ifnextchar[\newfloat at DFE@setlistname\relax}
+\@onlypreamble\newfloat at DFE@setname
+\def\newfloat at DFE@setlistname[#1]{%
+ \KV@@newfloat at listname{#1}}
+\@onlypreamble\newfloat at DFE@setlistname
+\newcommand*\newfloat at capitalize[2]{%
+ \edef\newfloat at tempa{\gdef\noexpand#1{\@car#2\@nil}}%
+ \uppercase\expandafter{\newfloat at tempa}%
+ \edef\newfloat at tempa{%
+ \noexpand\g at addto@macro\noexpand#1{\@cdr#2\@nil}}%
+ \newfloat at tempa}
+\newcommand*\newfloat at listof[1]{%
+ \@expandtwoargs\newfloat at list@of{#1}{\@nameuse{ext@#1}}}
+\newcommand*\newfloat at list@of[2]{%
+ \begingroup
+ \expandafter\let\expandafter\listfigurename\csname list#1name\endcsname
+ \def\ext at figure{#2}%
+ \let\newfloat at starttoc\@starttoc
+ \def\@starttoc##1{\newfloat at starttoc{#2}}%
+ \let\newfloat at listoftoc\listoftoc
+ \def\listoftoc##1{\newfloat at listoftoc{#2}}%
+ \@nameuse{newfloat at listof#1 at hook}%
+ \listoffigures
+ \endgroup}
+\newcommand*\newfloat at setoptions{%
+ \@ifstar
+ {\newfloat@@setoptions\@firstofone}%
+ {\newfloat@@setoptions\@gobble}}
+\newcommand*\newfloat@@setoptions[3]{%
+ \let\newfloat at within@value\@undefined
+ \let\newfloat at chapterlistsgaps@value\@undefined
+ #1{\KV@@newfloat at within\newfloat at within@default}% set default value for new floats
+ \def\newfloat at type{#2}%
+ \setkeys{@newfloat}{#3}%
+ \ifx\newfloat at within@value\@undefined \else
+ \newfloat at setoption{within}\newfloat at within@value
+ \fi
+ \ifx\newfloat at chapterlistsgaps@value\@undefined \else
+ \newfloat at setoption{chapterlistsgaps}\newfloat at chapterlistsgaps@value
+ \fi}
+\newcommand*\newfloat at within@default{%
+ \ifcsname c at chapter\endcsname chapter\else none\fi}
+\@onlypreamble\newfloat at within@default
+\newcommand*\newfloat at setoption[1]{%
+ \edef\caption at tempa{\noexpand\@nameuse{newfloat at set#1}{\newfloat at type}}%
+ \caption at tempa}
+\newcommand*\newfloat at setfileext[2]{%
+ \@namedef{ext@#1}{#2}}
+\define at key{@newfloat}{fileext}{%
+ \newfloat at setoption{fileext}{#1}}
+\newcommand*\newfloat at setlistname[2]{%
+ \@namedef{list#1name}{#2}}
+\define at key{@newfloat}{listname}{%
+ \newfloat at setoption{listname}{#1}}
+\newcommand*\newfloat at setname[2]{%
+ \newfloat@@setname{#1}{#2}%
+ \begingroup
+ \ifcsname languagename\endcsname
+ \ifcsname captions\languagename\endcsname
+ \expandafter\g at addto@macro\csname captions\languagename\endcsname
+ {\newfloat@@setname{#1}{#2}}%
+ \fi
+ \fi
+ \endgroup}
+%%\AtBeginDocument{\let\newfloat at setname\newfloat@@setname}
+\newcommand*\newfloat@@setname[2]{%
+ \@namedef{#1name}{#2}}
+\define at key{@newfloat}{name}{%
+ \newfloat at setoption{name}{#1}}
+\newcommand*\newfloat at setplacement[2]{%
+ \@namedef{fps@#1}{#2}}
+\define at key{@newfloat}{placement}{%
+ \newfloat at setoption{placement}{#1}}
+\newcommand*\newfloat at setwithin[2]{%
+ \ifcsname c at chapter\endcsname
+ \@removefromreset{#1}{chapter}%
+ \fi
+ \@removefromreset{#1}{section}%
+ \edef\@tempa{#2}%
+ \ifx\@tempa\@empty
+ \def\@tempa{none}%
+ \fi
+ \def\@tempb{none}%
+ \ifx\@tempa\@tempb
+ \ifcsname c at chapter\endcsname
+ \@chapterlistsgap at off{#1}%
+ \fi
+ \newfloat@@setwithin{#1}{}{}%
+ \else
+ \def\@tempb{chapter}%
+ \ifx\@tempa\@tempb
+ \@addtoreset{#1}{chapter}%
+ \@chapterlistsgap at on{#1}%
+ \newfloat@@setwithin{#1}{\ifnum\c at chapter>\z@ \thechapter.\fi}{\theHchapter.}%
+ \else
+ \def\@tempb{section}%
+ \ifx\@tempa\@tempb
+ \@addtoreset{#1}{section}%
+ \ifcsname c at chapter\endcsname
+ \@addtoreset{#1}{chapter}%
+ \@chapterlistsgap at on{#1}%
+ \newfloat@@setwithin{#1}{\thesection.}{\theHsection.}%
+ \else
+ \newfloat@@setwithin{#1}{\ifnum\c at section>\z@ \thesection.\fi}{\theHsection.}%
+ \fi
+ \else
+ \newfloat at Error{Invalid value `#2' for option `within'}%
+ \fi
+ \fi
+ \fi}
+\newcommand*\newfloat@@setwithin[3]{%
+ \global\@namedef{the#1}{#2\arabic{#1}}%
+ \global\@namedef{theH#1}{#3\arabic{#1}}}
+\define at key{@newfloat}{within}{%
+ \def\newfloat at within@value{#1}}
+\newcommand*\newfloat at setwithout[1]{%
+ \newfloat at setwithin{#1}{none}}
+\define at key{@newfloat}{without}[]{%
+ \def\newfloat at within@value{none}}
+\newcommand*\newfloat at setchapterlistsgaps[2]{%
+ \edef\@tempa{#2}%
+ \def\@tempb{off}%
+ \ifx\@tempa\@tempb
+ \@chapterlistsgap at off{#1}%
+ \else
+ \def\@tempb{on}%
+ \ifx\@tempa\@tempb
+ \@chapterlistsgap at on{#1}%
+ \else
+ \newfloat at Error{Invalid value `#2' for option `chapterlistsgaps'}%
+ \fi
+ \fi}
+\define at key{@newfloat}{chapterlistsgaps}{%
+ \def\newfloat at chapterlistsgaps@value{#1}}
+\providecommand*\@removefromreset[2]{{%
+ \expandafter\let\csname c@#1\endcsname\@removefromreset
+ \def\@elt##1{%
+ \expandafter\ifx\csname c@##1\endcsname\@removefromreset
+ \else
+ \noexpand\@elt{##1}%
+ \fi}%
+ \expandafter\xdef\csname cl@#2\endcsname{%
+ \csname cl@#2\endcsname}}}
+\newcommand*\newfloat at announce[2]{%
+ \@cons\newfloat at list{{#1}}%
+ \@cons\newfloat@@list{{#1}}%
+ \newfloat at ifundefined{newfloat at ext@#2}{%
+ \@namedef{newfloat at ext@#2}{#1}%
+ \ifcsname c at lofdepth\endcsname
+ \newfloat at ifundefined{c@#2depth}{%
+ \newcounter{#2depth}%
+ \setcounter{#2depth}{1}}%
+ \fi
+ \ifcsname addtotoclist\endcsname
+ \addtotoclist[float]{#2}%
+ \newfloat at def{listof#2name}{\@nameuse{list#1name}}%
+ \fi
+ }%
+ \ifcsname contentsuse\endcsname
+ \contentsuse{#1}{#2}%
+ \fi
+ \newfloat at hook{#1}}
+\@onlypreamble\newfloat at announce
+\newcommand*\newfloat@@list{}
+\newcommand*\SetupFloatingEnvironment[1]{%
+ \newfloat at addtolist{#1}%
+ \newfloat at setoptions{#1}}
+\newcommand\ForEachFloatingEnvironment{%
+ \@ifstar
+ {\@ForEachFloatingEnvironment\@gobble}%
+ {\@ForEachFloatingEnvironment\@iden}}
+\newcommand\@ForEachFloatingEnvironment[2]{%
+ \def\@elt##1{#2}%
+ \newfloat at list
+ \let\@elt\relax
+ #1{\newfloat at addtohook{#2}}}
+\providecommand\newfloat at addtohook[1]{%
+ \toks@=\expandafter{\newfloat at hook{##1}#1}%
+ \edef\@tempa{\def\noexpand\newfloat at hook####1{\the\toks@}}%
+ \@tempa}
+\providecommand*\newfloat at hook[1]{}
+\newcommand\PrepareListOf[1]{%
+ \expandafter\g at addto@macro\csname newfloat at listof#1 at hook\endcsname}
+\@onlypreamble\PrepareListOf
+\newcommand*\newfloat at list{}
+\newcommand*\newfloat at addtolist[1]{%
+ \newfloat at ifinlist{#1}{}{%
+ \ifcsname ext@#1\endcsname
+ \@cons\newfloat at list{{#1}}%
+ \@namedef{newfloat at ext@\@nameuse{ext@#1}}{#1}%
+ \newfloat at let{@ifchapterlistsgap@#1}{\@iden}%
+ \else
+ \newfloat at Error{`#1' does not seem to be a floating environment}%
+ \fi}}
+\newcommand*\newfloat at ifinlist[1]{%
+ \let\next\@secondoftwo
+ \begingroup
+ \expandafter\let\csname c@#1\endcsname\newfloat at ifinlist
+ \def\@elt##1{%
+ \expandafter\ifx\csname c@##1\endcsname\newfloat at ifinlist
+ \global\let\next\@firstoftwo
+ \fi}%
+ \newfloat at list
+ \endgroup
+ \next}
+\ifcsname ext at figure\endcsname
+ \newfloat at addtolist{figure}
+\fi
+\ifcsname ext at table\endcsname
+ \newfloat at addtolist{table}
+\fi
+\ifcsname @chapter\endcsname
+ \providecommand*\@chapterlistsgap{10\p@}%
+ \providecommand*\@addchapterlistsgap[2]{%
+ \@nameuse{@ifchapterlistsgap@#1}{% if switched on
+ \@@addchapterlistsgap{#1}{#2}}}
+ \providecommand*\@@addchapterlistsgap[2]{%
+ \@ifundefined{@addchapterlistsgap@#2}{% only once per extension
+ \@namedef{@addchapterlistsgap@#2}{#1}%
+ \@@@addchapterlistsgap{#2}}{}}
+ \providecommand*\@@@addchapterlistsgap[1]{%
+ \ifdim \@chapterlistsgap>\z@
+ \addtocontents{#1}{\protect\addvspace{\@chapterlistsgap}}%
+ \fi}
+ \providecommand*\@addchapterlistsgaps{%
+ \begingroup
+ \def\@elt##1{%
+ \@expandtwoargs\@addchapterlistsgap{##1}{\@nameuse{ext@##1}}}%
+ \newfloat at list
+ \endgroup}
+ \providecommand*\@chapterlistsgap at off[1]{%
+ \expandafter\let\csname @ifchapterlistsgap@#1\endcsname\@gobble
+ \ifcsname unsettoc\endcsname
+ \@expandtwoargs\unsettoc{\@nameuse{ext@#1}}{chapteratlist}%
+ \fi}
+ \providecommand*\@chapterlistsgap at on[1]{%
+ \expandafter\let\csname @ifchapterlistsgap@#1\endcsname\@iden
+ \ifcsname setuptoc\endcsname
+ \@expandtwoargs\setuptoc{\@nameuse{ext@#1}}{chapteratlist}%
+ \fi}
+\fi
+\define at key{newfloat}{chapterlistsgap}{%
+ \renewcommand*\@chapterlistsgap{#1}}
+\define at key{newfloat}{within}{%
+ \def\newfloat at within@default{#1}% set new default value
+ \def\@elt##1{\newfloat at setwithin{##1}{#1}}%
+ \newfloat at list
+ \let\@elt\relax}
+\define at key{newfloat}{without}[]{%
+ \KV at newfloat@within{none}}
+\def\@elt#1{%
+ \define at key{newfloat}{#1name}{%
+ \newfloat at setname{#1}{##1}}%
+ \define at key{newfloat}{list#1name}{%
+ \newfloat at setname{list#1}{##1}}%
+ \define at key{newfloat}{#1within}{%
+ \newfloat at setwithin{#1}{##1}}%
+ \define at key{newfloat}{#1without}[]{%
+ \newfloat at setwithout{#1}}%
+}%
+\newfloat at list
+\let\@elt\relax
+\define at key{newfloat}{planb}[true]{%
+ \def\@tempa{#1}%
+ \def\@tempb{false}%
+ \ifx\@tempa\@tempb
+ \let\newfloat at ifplanb\@gobble
+ \else
+ \def\@tempb{true}%
+ \ifx\@tempa\@tempb
+ \let\newfloat at ifplanb\@iden
+ \else
+ \newfloat at Error{Invalid value `#1' for option `planb'}%
+ \fi
+ \fi}
+\define at key{newfloat}{planb-fileext}{%
+ \newfloat at Info{Setting Plan B file extension to `#1'}
+ \xdef\newfloat at addtocontents@ext{#1}}
+
+\let\@tempc\relax
+\@expandtwoargs\setkeys{newfloat}{planb,\@ptionlist{\@currname.\@currext}}%
+\AtEndOfPackage{\let\@unprocessedoptions\relax}
+\newcommand*\newfloatsetup{\setkeys{newfloat}}
+\newcommand\newfloat at replace@chapter[2]{%
+ \begingroup
+ \let\if at twocolumn\iffalse
+ \let\if at mainmatter\iffalse
+ \let\if at thema\iffalse
+ \def\@tempa[##1]##2{#1}%
+ \ifx\@tempa\@chapter
+ \gdef\@chapter[##1]##2{#2}%
+ \global\let\newfloat at replace@chapter\@gobbletwo
+ \else\ifx\@tempa\Hy at org@chapter
+ \gdef\Hy at org@chapter[##1]##2{#2}%
+ \global\let\newfloat at replace@chapter\@gobbletwo
+ \fi\fi
+ \endgroup}
+\ifcsname @chapter\endcsname \else
+ \let\newfloat at replace@chapter\@gobbletwo
+\fi
+\newfloat at replace@chapter{%
+ \ifnum \c at secnumdepth >\m at ne
+ \refstepcounter{chapter}%
+ \typeout{\@chapapp\space\thechapter.}%
+ \addcontentsline{toc}{chapter}%
+ {\protect\numberline{\thechapter}#1}%
+ \else
+ \addcontentsline{toc}{chapter}{#1}%
+ \fi
+ \chaptermark{#1}%
+ \addtocontents{lof}{\protect\addvspace{10\p@}}%
+ \addtocontents{lot}{\protect\addvspace{10\p@}}%
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]%
+ \else
+ \@makechapterhead{#2}%
+ \@afterheading
+ \fi
+}{%
+ \ifnum \c at secnumdepth >\m at ne
+ \refstepcounter{chapter}%
+ \typeout{\@chapapp\space\thechapter.}%
+ \addcontentsline{toc}{chapter}%
+ {\protect\numberline{\thechapter}#1}%
+ \else
+ \addcontentsline{toc}{chapter}{#1}%
+ \fi
+ \chaptermark{#1}%
+ \@addchapterlistsgaps
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]%
+ \else
+ \@makechapterhead{#2}%
+ \@afterheading
+ \fi}
+\newfloat at replace@chapter{%
+ \ifnum \c at secnumdepth >\m at ne
+ \if at mainmatter
+ \refstepcounter{chapter}%
+ \typeout{\@chapapp\space\thechapter.}%
+ \addcontentsline{toc}{chapter}%
+ {\protect\numberline{\thechapter}#1}%
+ \else
+ \addcontentsline{toc}{chapter}{#1}%
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{#1}%
+ \fi
+ \chaptermark{#1}%
+ \addtocontents{lof}{\protect\addvspace{10\p@}}%
+ \addtocontents{lot}{\protect\addvspace{10\p@}}%
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]%
+ \else
+ \@makechapterhead{#2}%
+ \@afterheading
+ \fi
+}{%
+ \ifnum \c at secnumdepth >\m at ne
+ \if at mainmatter
+ \refstepcounter{chapter}%
+ \typeout{\@chapapp\space\thechapter.}%
+ \addcontentsline{toc}{chapter}%
+ {\protect\numberline{\thechapter}#1}%
+ \else
+ \addcontentsline{toc}{chapter}{#1}%
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{#1}%
+ \fi
+ \chaptermark{#1}%
+ \@addchapterlistsgaps
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]%
+ \else
+ \@makechapterhead{#2}%
+ \@afterheading
+ \fi}
+\newfloat at replace@chapter{%
+ \refstepcounter{chapter}%
+ \ifnum\c at secnumdepth<\z@ \let\@secnumber\@empty
+ \else \let\@secnumber\thechapter \fi
+ \typeout{\chaptername\space\@secnumber}%
+ \def\@toclevel{0}%
+ \ifx\chaptername\appendixname \@tocwriteb\tocappendix{chapter}{#2}%
+ \else \@tocwriteb\tocchapter{chapter}{#2}\fi
+ \chaptermark{#1}%
+ \addtocontents{lof}{\protect\addvspace{10\p@}}%
+ \addtocontents{lot}{\protect\addvspace{10\p@}}%
+ \@makechapterhead{#2}\@afterheading
+}{%
+ \refstepcounter{chapter}%
+ \ifnum\c at secnumdepth<\z@ \let\@secnumber\@empty
+ \else \let\@secnumber\thechapter \fi
+ \typeout{\chaptername\space\@secnumber}%
+ \def\@toclevel{0}%
+ \ifx\chaptername\appendixname \@tocwriteb\tocappendix{chapter}{#2}%
+ \else \@tocwriteb\tocchapter{chapter}{#2}\fi
+ \chaptermark{#1}%
+ \@addchapterlistsgaps
+ \@makechapterhead{#2}\@afterheading}
+\@ifpackageloaded{tocbasic}{%
+ \let\newfloat at replace@chapter\@gobbletwo}{}
+\ifcsname insertchapterspace\endcsname
+ \renewcommand*\insertchapterspace{\@addchapterlistsgaps}
+ \let\newfloat at replace@chapter\@gobbletwo
+\fi
+\newfloat at replace@chapter{%
+ \ifnum \c at secnumdepth >\m at ne
+ \refstepcounter{chapter}%
+ \typeout{\@chapapp\space\thechapter.}%
+ \addcontentsline{toc}{chapter}%
+ {\protect\numberline{\thechapter}\toc at font0 #1}%
+ \else
+ \addcontentsline{toc}{chapter}{\toc at font0 #1}%
+ \fi
+ \chaptermark{#1}%
+ \addtocontents{lof}{\protect\addvspace{10\p@}}%
+ \addtocontents{lot}{\protect\addvspace{10\p@}}%
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]%
+ \else
+ \@makechapterhead{#2}%
+ \@afterheading
+ \fi
+}{%
+ \ifnum \c at secnumdepth >\m at ne
+ \refstepcounter{chapter}%
+ \typeout{\@chapapp\space\thechapter.}%
+ \addcontentsline{toc}{chapter}%
+ {\protect\numberline{\thechapter}\toc at font0 #1}%
+ \else
+ \addcontentsline{toc}{chapter}{\toc at font0 #1}%
+ \fi
+ \chaptermark{#1}%
+ \@addchapterlistsgaps
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]%
+ \else
+ \@makechapterhead{#2}%
+ \@afterheading
+ \fi}
+ % boek(3).cls [2004/06/07 v2.1a NTG LaTeX document class]
+\newfloat at replace@chapter{%
+ \ifnum \c at secnumdepth >\m at ne
+ \if at mainmatter
+ \refstepcounter{chapter}%
+ \typeout{\@chapapp\space\thechapter.}%
+ \addcontentsline{toc}{chapter}%
+ {\protect\numberline{\thechapter}\toc at font0 #1}%
+ \else
+ \addcontentsline{toc}{chapter}{\toc at font0 #1}%
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{\toc at font0 #1}%
+ \fi
+ \chaptermark{#1}%
+ \addtocontents{lof}{\protect\addvspace{10\p@}}%
+ \addtocontents{lot}{\protect\addvspace{10\p@}}%
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]%
+ \else
+ \@makechapterhead{#2}%
+ \@afterheading
+ \fi
+}{%
+ \ifnum \c at secnumdepth >\m at ne
+ \if at mainmatter
+ \refstepcounter{chapter}%
+ \typeout{\@chapapp\space\thechapter.}%
+ \addcontentsline{toc}{chapter}%
+ {\protect\numberline{\thechapter}\toc at font0 #1}%
+ \else
+ \addcontentsline{toc}{chapter}{\toc at font0 #1}%
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{\toc at font0 #1}%
+ \fi
+ \chaptermark{#1}%
+ \@addchapterlistsgaps
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]%
+ \else
+ \@makechapterhead{#2}%
+ \@afterheading
+ \fi}
+\newfloat at replace@chapter{%
+ \ifnum \c at secnumdepth >\m at ne
+ \if at mainmatter
+ \refstepcounter{chapter}%
+ \typeout{\chaptername\space\thechapter.}
+ \if at thema
+ \ifx\@shortauthor\@empty
+ \addcontentsline{toc}{chapter}{%
+ \protect\numberline{\thechapter.}#1}%
+ \else
+ \addcontentsline{toc}{chapter}{%
+ \protect\numberline{\thechapter.}%
+ \@shortauthor\hfill\mbox{}\vskip\normallineskip #1}%
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{%
+ \protect\numberline{\thechapter.}#1}%
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{#1}
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{#1}
+ \fi
+ \chaptermark{#1}
+ \addtocontents{lof}{\protect\addvspace{10pt}}
+ \addtocontents{lot}{\protect\addvspace{10pt}}
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]
+ \else
+ \@makechapterhead{#2}
+ \@afterheading
+ \fi
+}{%
+ \ifnum \c at secnumdepth >\m at ne
+ \if at mainmatter
+ \refstepcounter{chapter}%
+ \typeout{\chaptername\space\thechapter.}%
+ \if at thema
+ \ifx\@shortauthor\@empty
+ \addcontentsline{toc}{chapter}{%
+ \protect\numberline{\thechapter.}#1}%
+ \else
+ \addcontentsline{toc}{chapter}{%
+ \protect\numberline{\thechapter.}%
+ \@shortauthor\hfill\mbox{}\vskip\normallineskip #1}%
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{%
+ \protect\numberline{\thechapter.}#1}%
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{#1}%
+ \fi
+ \else
+ \addcontentsline{toc}{chapter}{#1}%
+ \fi
+ \chaptermark{#1}%
+ \@addchapterlistsgaps
+ \if at twocolumn
+ \@topnewpage[\@makechapterhead{#2}]%
+ \else
+ \@makechapterhead{#2}%
+ \@afterheading
+ \fi}
+\ifx\newfloat at replace@chapter\@gobbletwo \else
+ \newfloat at InfoNoLine{%
+ Unsupported document class, or \noexpand\@chapter\MessageBreak
+ was already redefined by another package}
+ \newfloat at InfoNoLine{\string\@chapter\space=\space\meaning\@chapter}
+ \newfloat at InfoNoLine{\string\Hy at org@chapter\space=\space\meaning\Hy at org@chapter}
+ \newfloat at ifplanb{%
+ \newfloat at InfoNoLine{Trying Plan B..}%
+ \let\newfloat at addtocontents@ORI\addtocontents
+ \long\def\addtocontents#1#2{%
+ \newfloat at addtocontents{#1}{#2}#2\addvspace\newfloat at nil}%
+ \long\def\newfloat at addtocontents#1#2#3\addvspace#4\newfloat at nil{%
+ \def\newfloat at tempa{#4}%
+ \ifx\newfloat at tempa\@empty
+ \newfloat at addtocontents@ORI{#1}{#2}%
+ \else
+ \ifx\newfloat at addtocontents@ext\@undefined
+ \newfloat at Info{Setting Plan B file extension to `#1'...}%
+ \xdef\newfloat at addtocontents@ext{#1}%
+ \fi
+ \edef\newfloat at tempa{#1}%
+ \ifx\newfloat at tempa\newfloat at addtocontents@ext
+ \begingroup
+ \let\addtocontents\newfloat at addtocontents@ORI
+ \@addchapterlistsgaps
+ \endgroup
+ \fi
+ \fi}}
+\fi
+\newcommand\newfloat at ForEachNew[2][newfloat@@list]{%
+ \AtBeginDocument{%
+ \ifcsname#1\endcsname
+ \def\@elt##1{#2}%
+ \newfloat@@list
+ \let\@elt\relax
+ \fi}}%
+\@onlypreamble\newfloat at ForEachNew
+%% \begin{macrocode}
+\newfloat at ForEachNew[float at exts]{%
+ \@nameuse{@ifchapterlistsgap@#1}{% if switched on
+ \let\float at do=\relax
+ \edef\@tempa{%
+ \noexpand\float at exts{\the\float at exts\float at do{\@nameuse{ext@#1}}}}%
+ \@tempa}}
+\newfloat at ForEachNew[FP at floatBegin]{%
+ \newcounter{FP@#1C}%
+ \newenvironment{FP#1}{\FP at floatBegin{#1}}{\FP at floatEnd}}
+\providecommand*\ext at lstlisting{lol}%
+\newfloat at ForEachNew[@rotfloat]{%
+ \newenvironment{sideways#1}{\@rotfloat{#1}}{\end at rotfloat}%
+ \newenvironment{sideways#1*}{\@rotdblfloat{#1}}{\end at rotdblfloat}}
+\newcommand*\newfloat at For@SC[2]{%
+ \def#1{b}% = \sidecaptionvpos{#2}{b} (v1.6)
+ \newenvironment{SC#2}%
+ {\SC at float[#1]{#2}}{\endSC at float}%
+ \newenvironment{SC#2*}%
+ {\SC at dblfloat[#1]{#2}}{\endSC at dblfloat}}
+\@onlypreamble\newfloat at For@SC
+\newfloat at ForEachNew[SC at float]{%
+ \expandafter\newfloat at For@SC\csname SC@#1 at vpos\endcsname{#1}}
+\newfloat at ForEachNew[wrapfloat]{%
+ \newenvironment{wrap#1}{\wrapfloat{#1}}{\endwrapfloat}}
+\endinput
+%%
+%% End of file `newfloat.sty'.
diff --git a/doc/build/latex/python.ist b/doc/build/latex/python.ist
new file mode 100644
index 0000000..9ffa0f9
--- /dev/null
+++ b/doc/build/latex/python.ist
@@ -0,0 +1,11 @@
+line_max 100
+headings_flag 1
+heading_prefix " \\bigletter "
+
+preamble "\\begin{theindex}
+\\def\\bigletter#1{{\\Large\\sffamily#1}\\nopagebreak\\vspace{1mm}}
+
+"
+
+symhead_positive "{Symbols}"
+numhead_positive "{Numbers}"
diff --git a/doc/build/latex/sphinx.sty b/doc/build/latex/sphinx.sty
new file mode 100644
index 0000000..ce17407
--- /dev/null
+++ b/doc/build/latex/sphinx.sty
@@ -0,0 +1,641 @@
+%
+% sphinx.sty
+%
+% Adapted from the old python.sty, mostly written by Fred Drake,
+% by Georg Brandl.
+%
+
+\NeedsTeXFormat{LaTeX2e}[1995/12/01]
+\ProvidesPackage{sphinx}[2010/01/15 LaTeX package (Sphinx markup)]
+
+\@ifclassloaded{memoir}{}{\RequirePackage{fancyhdr}}
+
+\RequirePackage{textcomp}
+\RequirePackage{fancybox}
+\RequirePackage{titlesec}
+\RequirePackage{tabulary}
+\RequirePackage{makeidx}
+\RequirePackage{framed}
+\RequirePackage{ifthen}
+%The xcolor package draws better fcolorboxes
+%around verbatim code
+\IfFileExists{xcolor.sty}{
+ \RequirePackage{xcolor}
+}{
+ \RequirePackage{color}
+}
+% For highlighted code.
+\RequirePackage{fancyvrb}
+% For table captions.
+\RequirePackage{threeparttable}
+% Handle footnotes in tables.
+\RequirePackage{footnote}
+\makesavenoteenv{tabulary}
+% For floating figures in the text.
+\RequirePackage{wrapfig}
+% Separate paragraphs by space by default.
+\RequirePackage{parskip}
+% For parsed-literal blocks.
+\RequirePackage{alltt}
+% Display "real" single quotes in literal blocks.
+\RequirePackage{upquote}
+
+% Redefine these colors to your liking in the preamble.
+\definecolor{TitleColor}{rgb}{0.126,0.263,0.361}
+\definecolor{InnerLinkColor}{rgb}{0.208,0.374,0.486}
+\definecolor{OuterLinkColor}{rgb}{0.216,0.439,0.388}
+% Redefine these colors to something if you want to have colored
+% background and border for code examples.
+\definecolor{VerbatimColor}{rgb}{1,1,1}
+\definecolor{VerbatimBorderColor}{rgb}{0,0,0}
+
+% Uncomment these two lines to ignore the paper size and make the page
+% size more like a typical published manual.
+%\renewcommand{\paperheight}{9in}
+%\renewcommand{\paperwidth}{8.5in} % typical squarish manual
+%\renewcommand{\paperwidth}{7in} % O'Reilly ``Programmming Python''
+
+% use pdfoutput for pTeX and dvipdfmx
+% when pTeX (\kanjiskip is defined), set pdfoutput to evade \include{pdfcolor}
+\ifx\kanjiskip\undefined\else
+ \newcount\pdfoutput\pdfoutput=0
+\fi
+
+\RequirePackage{graphicx}
+
+% for PDF output, use colors and maximal compression
+\newif\ifsphinxpdfoutput\sphinxpdfoutputfalse
+\ifx\pdfoutput\undefined\else\ifcase\pdfoutput
+ \let\py at NormalColor\relax
+ \let\py at TitleColor\relax
+\else
+ \sphinxpdfoutputtrue
+ \input{pdfcolor}
+ \def\py at NormalColor{\color[rgb]{0.0,0.0,0.0}}
+ \def\py at TitleColor{\color{TitleColor}}
+ \pdfcompresslevel=9
+\fi\fi
+
+% XeLaTeX can do colors, too
+\ifx\XeTeXrevision\undefined\else
+ \def\py at NormalColor{\color[rgb]{0.0,0.0,0.0}}
+ \def\py at TitleColor{\color{TitleColor}}
+\fi
+
+% Increase printable page size (copied from fullpage.sty)
+\topmargin 0pt
+\advance \topmargin by -\headheight
+\advance \topmargin by -\headsep
+
+% attempt to work a little better for A4 users
+\textheight \paperheight
+\advance\textheight by -2in
+
+\oddsidemargin 0pt
+\evensidemargin 0pt
+%\evensidemargin -.25in % for ``manual size'' documents
+\marginparwidth 0.5in
+
+\textwidth \paperwidth
+\advance\textwidth by -2in
+
+
+% Style parameters and macros used by most documents here
+\raggedbottom
+\sloppy
+\hbadness = 5000 % don't print trivial gripes
+
+\pagestyle{empty} % start this way
+
+% Use this to set the font family for headers and other decor:
+\newcommand{\py at HeaderFamily}{\sffamily\bfseries}
+
+% Redefine the 'normal' header/footer style when using "fancyhdr" package:
+\@ifundefined{fancyhf}{}{
+ % Use \pagestyle{normal} as the primary pagestyle for text.
+ \fancypagestyle{normal}{
+ \fancyhf{}
+ \fancyfoot[LE,RO]{{\py at HeaderFamily\thepage}}
+ \fancyfoot[LO]{{\py at HeaderFamily\nouppercase{\rightmark}}}
+ \fancyfoot[RE]{{\py at HeaderFamily\nouppercase{\leftmark}}}
+ \fancyhead[LE,RO]{{\py at HeaderFamily \@title, \py at release}}
+ \renewcommand{\headrulewidth}{0.4pt}
+ \renewcommand{\footrulewidth}{0.4pt}
+ % define chaptermark with \@chappos when \@chappos is available for Japanese
+ \ifx\@chappos\undefined\else
+ \def\chaptermark##1{\markboth{\@chapapp\space\thechapter\space\@chappos\space ##1}{}}
+ \fi
+ }
+ % Update the plain style so we get the page number & footer line,
+ % but not a chapter or section title. This is to keep the first
+ % page of a chapter and the blank page between chapters `clean.'
+ \fancypagestyle{plain}{
+ \fancyhf{}
+ \fancyfoot[LE,RO]{{\py at HeaderFamily\thepage}}
+ \renewcommand{\headrulewidth}{0pt}
+ \renewcommand{\footrulewidth}{0.4pt}
+ }
+}
+
+% Some custom font markup commands.
+%
+\newcommand{\strong}[1]{{\textbf{#1}}}
+\newcommand{\code}[1]{\texttt{#1}}
+\newcommand{\bfcode}[1]{\code{\bfseries#1}}
+\newcommand{\email}[1]{\textsf{#1}}
+\newcommand{\tablecontinued}[1]{\textsf{#1}}
+\newcommand{\titleref}[1]{\emph{#1}}
+\newcommand{\menuselection}[1]{\emph{#1}}
+\newcommand{\accelerator}[1]{\underline{#1}}
+\newcommand{\crossref}[1]{\emph{#1}}
+\newcommand{\termref}[1]{\emph{#1}}
+
+\newcommand*{\sphinxAtStartFootnote}{\mbox{ }}
+
+% Redefine the Verbatim environment to allow border and background colors.
+% The original environment is still used for verbatims within tables.
+\let\OriginalVerbatim=\Verbatim
+\let\endOriginalVerbatim=\endVerbatim
+
+% Play with vspace to be able to keep the indentation.
+\newlength\Sphinx at scratchlength
+\newcommand\Sphinxcolorbox [1]{%
+ \setlength\Sphinx at scratchlength{\linewidth}%
+ \advance\Sphinx at scratchlength -\@totalleftmargin %
+ \fcolorbox{VerbatimBorderColor}{VerbatimColor}{%
+ \begin{minipage}{\Sphinx at scratchlength}%
+ #1
+ \end{minipage}%
+ }%
+}
+% used for split frames for continuation on next and final page
+\def\MidFrameCommand{\Sphinxcolorbox}
+\let\LastFrameCommand\MidFrameCommand
+
+% We customize \FrameCommand (for non split frames) and \FirstFrameCommand
+% (split frames), in order for the framed environment to insert a Title above
+% the frame, which can not be separated by a pagebreak.
+
+% The title is specified from outside as macro \SphinxVerbatimTitle.
+% \SphinxVerbatimTitle is reset to empty after each use of Verbatim environment.
+
+% It is also possible to use directly framed environment (i.e. not indirectly
+% via the Verbatim environment next), then it is \SphinxFrameTitle which specifies
+% the title.
+\newcommand*\SphinxFrameTitle {}
+\newcommand*\SphinxVerbatimTitle {}
+\newcommand*\SphinxSetupCaptionForVerbatim [2]
+{%
+ \needspace{\literalblockneedspace}\vspace{\literalblockcaptiontopvspace}%
+ \def\SphinxVerbatimTitle
+ {\captionof{#1}{\SphinxLiteralBlockLabel #2}\smallskip }%
+}
+% \SphinxLiteralBlockLabel will be set dynamically to hold the label for links
+\newcommand*\SphinxLiteralBlockLabel {}
+
+% \SphinxCustomFBox is copied from framed.sty's \CustomFBox, but
+% #1=title/caption is to be set _above_ the top rule, not _below_
+% #1 must be "vertical material", it may be left empty.
+
+% The amsmath patches \stepcounter to inhibit stepping under
+% \firstchoice at false. We use it because framed.sty typesets multiple
+% times its contents.
+\newif\ifSphinx at myfirstframedpass
+
+\long\def\SphinxCustomFBox#1#2#3#4#5#6#7{%
+ % we set up amsmath (amstext.sty) conditional to inhibit counter stepping
+ % except in first pass
+ \ifSphinx at myfirstframedpass\firstchoice at true
+ \else\firstchoice at false\fi
+ \leavevmode\begingroup
+ \setbox\@tempboxa\hbox{%
+ \color at begingroup
+ \kern\fboxsep{#7}\kern\fboxsep
+ \color at endgroup}%
+ \hbox{%
+ \lower\dimexpr#4+\fboxsep+\dp\@tempboxa\hbox{%
+ \vbox{%
+ #1% TITLE
+ \hrule\@height#3\relax
+ \hbox{%
+ \vrule\@width#5\relax
+ \vbox{%
+ \vskip\fboxsep
+ \copy\@tempboxa
+ \vskip\fboxsep}%
+ \vrule\@width#6\relax}%
+ #2%
+ \hrule\@height#4\relax}%
+ }%
+ }%
+ \endgroup
+ \global\Sphinx at myfirstframedpassfalse
+}
+
+% for non split frames:
+\def\FrameCommand{%
+ % this is inspired from framed.sty v 0.96 2011/10/22 lines 185--190
+ % \fcolorbox (see \Sphinxcolorbox above) from color.sty uses \fbox.
+ \def\fbox{\SphinxCustomFBox{\SphinxFrameTitle}{}%
+ \fboxrule\fboxrule\fboxrule\fboxrule}%
+ % \fcolorbox from xcolor.sty may use rather \XC at fbox.
+ \let\XC at fbox\fbox
+ \Sphinxcolorbox
+}
+% for first portion of split frames:
+\let\FirstFrameCommand\FrameCommand
+
+\renewcommand{\Verbatim}[1][1]{%
+ % list starts new par, but we don't want it to be set apart vertically
+ \parskip\z at skip
+ \smallskip
+ % first, let's check if there is a caption
+ \ifx\SphinxVerbatimTitle\empty
+ % there was no caption. Check if nevertheless a label was set.
+ \ifx\SphinxLiteralBlockLabel\empty\else
+ % we require some space to be sure hyperlink target from \phantomsection
+ % will not be separated from upcoming verbatim by a page break
+ \needspace{\literalblockwithoutcaptionneedspace}%
+ \phantomsection\SphinxLiteralBlockLabel
+ \fi
+ \fi
+ % non-empty \SphinxVerbatimTitle has label inside it (in case there is one)
+ \let\SphinxFrameTitle\SphinxVerbatimTitle
+ \global\Sphinx at myfirstframedpasstrue
+ % The list environement is needed to control perfectly the vertical
+ % space.
+ \list{}{%
+ \setlength\parskip{0pt}%
+ \setlength\itemsep{0ex}%
+ \setlength\topsep{0ex}%
+ \setlength\partopsep{0pt}%
+ \setlength\leftmargin{0pt}%
+ }%
+ \item\MakeFramed {\FrameRestore}%
+ \small
+ \OriginalVerbatim[#1]%
+}
+\renewcommand{\endVerbatim}{%
+ \endOriginalVerbatim
+ \endMakeFramed
+ \endlist
+ % LaTeX environments always revert local changes on exit, here e.g. \parskip
+}
+
+
+% \moduleauthor{name}{email}
+\newcommand{\moduleauthor}[2]{}
+
+% \sectionauthor{name}{email}
+\newcommand{\sectionauthor}[2]{}
+
+% Augment the sectioning commands used to get our own font family in place,
+% and reset some internal data items:
+\titleformat{\section}{\Large\py at HeaderFamily}%
+ {\py at TitleColor\thesection}{0.5em}{\py at TitleColor}{\py at NormalColor}
+\titleformat{\subsection}{\large\py at HeaderFamily}%
+ {\py at TitleColor\thesubsection}{0.5em}{\py at TitleColor}{\py at NormalColor}
+\titleformat{\subsubsection}{\py at HeaderFamily}%
+ {\py at TitleColor\thesubsubsection}{0.5em}{\py at TitleColor}{\py at NormalColor}
+\titleformat{\paragraph}{\small\py at HeaderFamily}%
+ {\py at TitleColor}{0em}{\py at TitleColor}{\py at NormalColor}
+
+% {fulllineitems} is the main environment for object descriptions.
+%
+\newcommand{\py at itemnewline}[1]{%
+ \@tempdima\linewidth%
+ \advance\@tempdima \leftmargin\makebox[\@tempdima][l]{#1}%
+}
+
+\newenvironment{fulllineitems}{
+ \begin{list}{}{\labelwidth \leftmargin \labelsep 0pt
+ \rightmargin 0pt \topsep -\parskip \partopsep \parskip
+ \itemsep -\parsep
+ \let\makelabel=\py at itemnewline}
+}{\end{list}}
+
+% \optional is used for ``[, arg]``, i.e. desc_optional nodes.
+\newcommand{\optional}[1]{%
+ {\textnormal{\Large[}}{#1}\hspace{0.5mm}{\textnormal{\Large]}}}
+
+\newlength{\py at argswidth}
+\newcommand{\py at sigparams}[2]{%
+ \parbox[t]{\py at argswidth}{#1\code{)}#2}}
+\newcommand{\pysigline}[1]{\item[#1]\nopagebreak}
+\newcommand{\pysiglinewithargsret}[3]{%
+ \settowidth{\py at argswidth}{#1\code{(}}%
+ \addtolength{\py at argswidth}{-2\py at argswidth}%
+ \addtolength{\py at argswidth}{\linewidth}%
+ \item[#1\code{(}\py at sigparams{#2}{#3}]}
+
+% Production lists
+%
+\newenvironment{productionlist}{
+% \def\optional##1{{\Large[}##1{\Large]}}
+ \def\production##1##2{\\\code{##1}&::=&\code{##2}}
+ \def\productioncont##1{\\& &\code{##1}}
+ \parindent=2em
+ \indent
+ \setlength{\LTpre}{0pt}
+ \setlength{\LTpost}{0pt}
+ \begin{longtable}[l]{lcl}
+}{%
+ \end{longtable}
+}
+
+% Notices / Admonitions
+%
+\newlength{\py at noticelength}
+
+\newcommand{\py at heavybox}{
+ \setlength{\fboxrule}{1pt}
+ \setlength{\fboxsep}{6pt}
+ \setlength{\py at noticelength}{\linewidth}
+ \addtolength{\py at noticelength}{-2\fboxsep}
+ \addtolength{\py at noticelength}{-2\fboxrule}
+ %\setlength{\shadowsize}{3pt}
+ \noindent\Sbox
+ \minipage{\py at noticelength}
+}
+\newcommand{\py at endheavybox}{
+ \endminipage
+ \endSbox
+ \fbox{\TheSbox}
+}
+
+\newcommand{\py at lightbox}{%
+ \par\allowbreak
+ \noindent\rule{\linewidth}{0.5pt}\par\nobreak
+ {\parskip\z at skip\noindent}%
+ }
+\newcommand{\py at endlightbox}{%
+ \par\nobreak
+ {\parskip\z at skip\noindent\rule[.4\baselineskip]{\linewidth}{0.5pt}}\par
+ }
+
+% Some are quite plain:
+\newcommand{\py at noticestart@note}{\py at lightbox}
+\newcommand{\py at noticeend@note}{\py at endlightbox}
+\newcommand{\py at noticestart@hint}{\py at lightbox}
+\newcommand{\py at noticeend@hint}{\py at endlightbox}
+\newcommand{\py at noticestart@important}{\py at lightbox}
+\newcommand{\py at noticeend@important}{\py at endlightbox}
+\newcommand{\py at noticestart@tip}{\py at lightbox}
+\newcommand{\py at noticeend@tip}{\py at endlightbox}
+
+% Others gets more visible distinction:
+\newcommand{\py at noticestart@warning}{\py at heavybox}
+\newcommand{\py at noticeend@warning}{\py at endheavybox}
+\newcommand{\py at noticestart@caution}{\py at heavybox}
+\newcommand{\py at noticeend@caution}{\py at endheavybox}
+\newcommand{\py at noticestart@attention}{\py at heavybox}
+\newcommand{\py at noticeend@attention}{\py at endheavybox}
+\newcommand{\py at noticestart@danger}{\py at heavybox}
+\newcommand{\py at noticeend@danger}{\py at endheavybox}
+\newcommand{\py at noticestart@error}{\py at heavybox}
+\newcommand{\py at noticeend@error}{\py at endheavybox}
+
+\newenvironment{notice}[2]{
+ \def\py at noticetype{#1}
+ \csname py at noticestart@#1\endcsname
+ \strong{#2}
+}{\csname py at noticeend@\py at noticetype\endcsname}
+
+% Allow the release number to be specified independently of the
+% \date{}. This allows the date to reflect the document's date and
+% release to specify the release that is documented.
+%
+\newcommand{\py at release}{}
+\newcommand{\version}{}
+\newcommand{\shortversion}{}
+\newcommand{\releaseinfo}{}
+\newcommand{\releasename}{Release}
+\newcommand{\release}[1]{%
+ \renewcommand{\py at release}{\releasename\space\version}%
+ \renewcommand{\version}{#1}}
+\newcommand{\setshortversion}[1]{%
+ \renewcommand{\shortversion}{#1}}
+\newcommand{\setreleaseinfo}[1]{%
+ \renewcommand{\releaseinfo}{#1}}
+
+% Allow specification of the author's address separately from the
+% author's name. This can be used to format them differently, which
+% is a good thing.
+%
+\newcommand{\py at authoraddress}{}
+\newcommand{\authoraddress}[1]{\renewcommand{\py at authoraddress}{#1}}
+
+% This sets up the fancy chapter headings that make the documents look
+% at least a little better than the usual LaTeX output.
+%
+\@ifundefined{ChTitleVar}{}{
+ \ChNameVar{\raggedleft\normalsize\py at HeaderFamily}
+ \ChNumVar{\raggedleft \bfseries\Large\py at HeaderFamily}
+ \ChTitleVar{\raggedleft \textrm{\Huge\py at HeaderFamily}}
+ % This creates chapter heads without the leading \vspace*{}:
+ \def\@makechapterhead#1{%
+ {\parindent \z@ \raggedright \normalfont
+ \ifnum \c at secnumdepth >\m at ne
+ \DOCH
+ \fi
+ \interlinepenalty\@M
+ \DOTI{#1}
+ }
+ }
+}
+
+% Redefine description environment so that it is usable inside fulllineitems.
+%
+\renewcommand{\description}{%
+ \list{}{\labelwidth\z@%
+ \itemindent-\leftmargin%
+ \labelsep5pt%
+ \let\makelabel=\descriptionlabel}}
+
+% Definition lists; requested by AMK for HOWTO documents. Probably useful
+% elsewhere as well, so keep in in the general style support.
+%
+\newenvironment{definitions}{%
+ \begin{description}%
+ \def\term##1{\item[##1]\mbox{}\\*[0mm]}
+}{%
+ \end{description}%
+}
+
+% Tell TeX about pathological hyphenation cases:
+\hyphenation{Base-HTTP-Re-quest-Hand-ler}
+
+
+% The following is stuff copied from docutils' latex writer.
+%
+\newcommand{\optionlistlabel}[1]{\bf #1 \hfill}
+\newenvironment{optionlist}[1]
+{\begin{list}{}
+ {\setlength{\labelwidth}{#1}
+ \setlength{\rightmargin}{1cm}
+ \setlength{\leftmargin}{\rightmargin}
+ \addtolength{\leftmargin}{\labelwidth}
+ \addtolength{\leftmargin}{\labelsep}
+ \renewcommand{\makelabel}{\optionlistlabel}}
+}{\end{list}}
+
+\newlength{\lineblockindentation}
+\setlength{\lineblockindentation}{2.5em}
+\newenvironment{lineblock}[1]
+{\begin{list}{}
+ {\setlength{\partopsep}{\parskip}
+ \addtolength{\partopsep}{\baselineskip}
+ \topsep0pt\itemsep0.15\baselineskip\parsep0pt
+ \leftmargin#1}
+ \raggedright}
+{\end{list}}
+
+% Redefine includgraphics for avoiding images larger than the screen size
+% If the size is not specified.
+\let\py at Oldincludegraphics\includegraphics
+
+\newbox\image at box%
+\newdimen\image at width%
+\renewcommand\includegraphics[2][\@empty]{%
+ \ifx#1\@empty%
+ \setbox\image at box=\hbox{\py at Oldincludegraphics{#2}}%
+ \image at width\wd\image at box%
+ \ifdim \image at width>\linewidth%
+ \setbox\image at box=\hbox{\py at Oldincludegraphics[width=\linewidth]{#2}}%
+ \box\image at box%
+ \else%
+ \py at Oldincludegraphics{#2}%
+ \fi%
+ \else%
+ \py at Oldincludegraphics[#1]{#2}%
+ \fi%
+}
+
+% to make pdf with correct encoded bookmarks in Japanese
+% this should precede the hyperref package
+\ifx\kanjiskip\undefined\else
+ \usepackage{atbegshi}
+ \ifx\ucs\undefined
+ \ifnum 42146=\euc"A4A2
+ \AtBeginShipoutFirst{\special{pdf:tounicode EUC-UCS2}}
+ \else
+ \AtBeginShipoutFirst{\special{pdf:tounicode 90ms-RKSJ-UCS2}}
+ \fi
+ \else
+ \AtBeginShipoutFirst{\special{pdf:tounicode UTF8-UCS2}}
+ \fi
+\fi
+
+% Include hyperref last.
+\RequirePackage[colorlinks,breaklinks,
+ linkcolor=InnerLinkColor,filecolor=OuterLinkColor,
+ menucolor=OuterLinkColor,urlcolor=OuterLinkColor,
+ citecolor=InnerLinkColor]{hyperref}
+% Fix anchor placement for figures with captions.
+% (Note: we don't use a package option here; instead, we give an explicit
+% \capstart for figures that actually have a caption.)
+\RequirePackage{hypcap}
+
+% Set up styles of URL: it should be placed after hyperref
+\urlstyle{same}
+
+% From docutils.writers.latex2e
+% inline markup (custom roles)
+% \DUrole{#1}{#2} tries \DUrole#1{#2}
+\providecommand*{\DUrole}[2]{%
+ \ifcsname DUrole#1\endcsname%
+ \csname DUrole#1\endcsname{#2}%
+ \else% backwards compatibility: try \docutilsrole#1{#2}
+ \ifcsname docutilsrole#1\endcsname%
+ \csname docutilsrole#1\endcsname{#2}%
+ \else%
+ #2%
+ \fi%
+ \fi%
+}
+
+\providecommand*{\DUprovidelength}[2]{
+ \ifthenelse{\isundefined{#1}}{\newlength{#1}\setlength{#1}{#2}}{}
+}
+
+\DUprovidelength{\DUlineblockindent}{2.5em}
+\ifthenelse{\isundefined{\DUlineblock}}{
+ \newenvironment{DUlineblock}[1]{%
+ \list{}{\setlength{\partopsep}{\parskip}
+ \addtolength{\partopsep}{\baselineskip}
+ \setlength{\topsep}{0pt}
+ \setlength{\itemsep}{0.15\baselineskip}
+ \setlength{\parsep}{0pt}
+ \setlength{\leftmargin}{#1}}
+ \raggedright
+ }
+ {\endlist}
+}{}
+
+
+% From footmisc.sty: allows footnotes in titles
+\let\FN at sf@@footnote\footnote
+\def\footnote{\ifx\protect\@typeset at protect
+ \expandafter\FN at sf@@footnote
+ \else
+ \expandafter\FN at sf@gobble at opt
+ \fi
+}
+\edef\FN at sf@gobble at opt{\noexpand\protect
+ \expandafter\noexpand\csname FN at sf@gobble at opt \endcsname}
+\expandafter\def\csname FN at sf@gobble at opt \endcsname{%
+ \@ifnextchar[%]
+ \FN at sf@gobble at twobracket
+ \@gobble
+}
+\def\FN at sf@gobble at twobracket[#1]#2{}
+
+% adjust the margins for footer,
+% this works with the jsclasses only (Japanese standard document classes)
+\ifx\@jsc at uplatextrue\undefined\else
+ \hypersetup{setpagesize=false}
+ \setlength\footskip{2\baselineskip}
+ \addtolength{\textheight}{-2\baselineskip}
+\fi
+
+% fix the double index and bibliography on the table of contents
+% in jsclasses (Japanese standard document classes)
+\ifx\@jsc at uplatextrue\undefined\else
+ \renewcommand{\theindex}{
+ \cleardoublepage
+ \phantomsection
+ \py at OldTheindex
+ }
+ \renewcommand{\thebibliography}[1]{
+ \cleardoublepage
+ \phantomsection
+ \py at OldThebibliography{1}
+ }
+\fi
+
+% disable \@chappos in Appendix in pTeX
+\ifx\kanjiskip\undefined\else
+ \let\py at OldAppendix=\appendix
+ \renewcommand{\appendix}{
+ \py at OldAppendix
+ \gdef\@chappos{}
+ }
+\fi
+
+% Define literal-block environment
+\RequirePackage{newfloat}
+\DeclareFloatingEnvironment{literal-block}
+\ifx\thechapter\undefined
+ \SetupFloatingEnvironment{literal-block}{within=section,placement=h}
+\else
+ \SetupFloatingEnvironment{literal-block}{within=chapter,placement=h}
+\fi
+\SetupFloatingEnvironment{literal-block}{name=List}
+% control caption around literal-block
+\RequirePackage{capt-of}
+\RequirePackage{needspace}
+% if the left page space is less than \literalblockneedsapce, insert page-break
+\newcommand{\literalblockneedspace}{5\baselineskip}
+\newcommand{\literalblockwithoutcaptionneedspace}{1.5\baselineskip}
+% margin before the caption of literal-block
+\newcommand{\literalblockcaptiontopvspace}{0.5\baselineskip}
diff --git a/doc/build/latex/sphinxhowto.cls b/doc/build/latex/sphinxhowto.cls
new file mode 100644
index 0000000..26e63a7
--- /dev/null
+++ b/doc/build/latex/sphinxhowto.cls
@@ -0,0 +1,104 @@
+%
+% sphinxhowto.cls for Sphinx (http://sphinx-doc.org/)
+%
+
+\NeedsTeXFormat{LaTeX2e}[1995/12/01]
+\ProvidesClass{sphinxhowto}[2009/06/02 Document class (Sphinx HOWTO)]
+
+% 'oneside' option overriding the 'twoside' default
+\newif\if at oneside
+\DeclareOption{oneside}{\@onesidetrue}
+% Pass remaining document options to the parent class.
+\DeclareOption*{\PassOptionsToClass{\CurrentOption}{\sphinxdocclass}}
+\ProcessOptions\relax
+
+% Default to two-side document
+\if at oneside
+% nothing to do (oneside is the default)
+\else
+\PassOptionsToClass{twoside}{\sphinxdocclass}
+\fi
+
+\LoadClass{\sphinxdocclass}
+
+% Set some sane defaults for section numbering depth and TOC depth. You can
+% reset these counters in your preamble.
+%
+\setcounter{secnumdepth}{2}
+
+% Change the title page to look a bit better, and fit in with the fncychap
+% ``Bjarne'' style a bit better.
+%
+\renewcommand{\maketitle}{
+ \rule{\textwidth}{1pt}
+ \ifsphinxpdfoutput
+ \begingroup
+ % These \defs are required to deal with multi-line authors; it
+ % changes \\ to ', ' (comma-space), making it pass muster for
+ % generating document info in the PDF file.
+ \def\\{, }
+ \def\and{and }
+ \pdfinfo{
+ /Author (\@author)
+ /Title (\@title)
+ }
+ \endgroup
+ \fi
+ \begin{flushright}
+ \sphinxlogo%
+ {\rm\Huge\py at HeaderFamily \@title} \par
+ {\em\large\py at HeaderFamily \py at release\releaseinfo} \par
+ \vspace{25pt}
+ {\Large\py at HeaderFamily
+ \begin{tabular}[t]{c}
+ \@author
+ \end{tabular}} \par
+ \vspace{25pt}
+ \@date \par
+ \py at authoraddress \par
+ \end{flushright}
+ \@thanks
+ \setcounter{footnote}{0}
+ \let\thanks\relax\let\maketitle\relax
+ %\gdef\@thanks{}\gdef\@author{}\gdef\@title{}
+}
+
+\let\py at OldTableofcontents=\tableofcontents
+\renewcommand{\tableofcontents}{
+ \begingroup
+ \parskip = 0mm
+ \py at OldTableofcontents
+ \endgroup
+ \rule{\textwidth}{1pt}
+ \vspace{12pt}
+}
+
+\@ifundefined{fancyhf}{
+ \pagestyle{plain}}{
+ \pagestyle{normal}} % start this way; change for
+\pagenumbering{arabic} % ToC & chapters
+
+\thispagestyle{empty}
+
+% Fix the bibliography environment to add an entry to the Table of
+% Contents.
+% For an article document class this environment is a section,
+% so no page break before it.
+\let\py at OldThebibliography=\thebibliography
+\renewcommand{\thebibliography}[1]{
+ \phantomsection
+ \py at OldThebibliography{1}
+ \addcontentsline{toc}{section}{\bibname}
+}
+
+% Same for the indices.
+% The memoir class already does this, so we don't duplicate it in that case.
+%
+\@ifclassloaded{memoir}{}{
+ \let\py at OldTheindex=\theindex
+ \renewcommand{\theindex}{
+ \phantomsection
+ \py at OldTheindex
+ \addcontentsline{toc}{section}{\indexname}
+ }
+}
diff --git a/doc/build/latex/sphinxmanual.cls b/doc/build/latex/sphinxmanual.cls
new file mode 100644
index 0000000..a6b9b39
--- /dev/null
+++ b/doc/build/latex/sphinxmanual.cls
@@ -0,0 +1,148 @@
+%
+% sphinxmanual.cls for Sphinx (http://sphinx-doc.org/)
+%
+
+\NeedsTeXFormat{LaTeX2e}[1995/12/01]
+\ProvidesClass{sphinxmanual}[2009/06/02 Document class (Sphinx manual)]
+
+% chapters starting at odd pages (overridden by 'openany' document option)
+\PassOptionsToClass{openright}{\sphinxdocclass}
+
+% 'oneside' option overriding the 'twoside' default
+\newif\if at oneside
+\DeclareOption{oneside}{\@onesidetrue}
+% Pass remaining document options to the parent class.
+\DeclareOption*{\PassOptionsToClass{\CurrentOption}{\sphinxdocclass}}
+\ProcessOptions\relax
+
+% Defaults two-side document
+\if at oneside
+% nothing to do (oneside is the default)
+\else
+\PassOptionsToClass{twoside}{\sphinxdocclass}
+\fi
+
+\LoadClass{\sphinxdocclass}
+
+% Set some sane defaults for section numbering depth and TOC depth. You can
+% reset these counters in your preamble.
+%
+\setcounter{secnumdepth}{2}
+\setcounter{tocdepth}{1}
+
+% Change the title page to look a bit better, and fit in with the fncychap
+% ``Bjarne'' style a bit better.
+%
+\renewcommand{\maketitle}{%
+ \begin{titlepage}%
+ \let\footnotesize\small
+ \let\footnoterule\relax
+ \rule{\textwidth}{1pt}%
+ \ifsphinxpdfoutput
+ \begingroup
+ % These \defs are required to deal with multi-line authors; it
+ % changes \\ to ', ' (comma-space), making it pass muster for
+ % generating document info in the PDF file.
+ \def\\{, }
+ \def\and{and }
+ \pdfinfo{
+ /Author (\@author)
+ /Title (\@title)
+ }
+ \endgroup
+ \fi
+ \begin{flushright}%
+ \sphinxlogo%
+ {\rm\Huge\py at HeaderFamily \@title \par}%
+ {\em\LARGE\py at HeaderFamily \py at release\releaseinfo \par}
+ \vfill
+ {\LARGE\py at HeaderFamily
+ \begin{tabular}[t]{c}
+ \@author
+ \end{tabular}
+ \par}
+ \vfill\vfill
+ {\large
+ \@date \par
+ \vfill
+ \py at authoraddress \par
+ }%
+ \end{flushright}%\par
+ \@thanks
+ \end{titlepage}%
+ \cleardoublepage%
+ \setcounter{footnote}{0}%
+ \let\thanks\relax\let\maketitle\relax
+ %\gdef\@thanks{}\gdef\@author{}\gdef\@title{}
+}
+
+
+% Catch the end of the {abstract} environment, but here make sure the abstract
+% is followed by a blank page if the 'openright' option is used.
+%
+\let\py at OldEndAbstract=\endabstract
+\renewcommand{\endabstract}{
+ \if at openright
+ \ifodd\value{page}
+ \typeout{Adding blank page after the abstract.}
+ \vfil\pagebreak
+ \fi
+ \fi
+ \py at OldEndAbstract
+}
+
+% This wraps the \tableofcontents macro with all the magic to get the spacing
+% right and have the right number of pages if the 'openright' option has been
+% used. This eliminates a fair amount of crud in the individual document files.
+%
+\let\py at OldTableofcontents=\tableofcontents
+\renewcommand{\tableofcontents}{%
+ \pagenumbering{roman}%
+ \setcounter{page}{1}%
+ \pagebreak%
+ \pagestyle{plain}%
+ {%
+ \parskip = 0mm%
+ \py at OldTableofcontents%
+ \if at openright%
+ \ifodd\value{page}%
+ \typeout{Adding blank page after the table of contents.}%
+ \pagebreak\hspace{0pt}%
+ \fi%
+ \fi%
+ \cleardoublepage%
+ }%
+ \pagenumbering{arabic}%
+ \@ifundefined{fancyhf}{}{\pagestyle{normal}}%
+}
+\pagenumbering{alph}
+
+% This is needed to get the width of the section # area wide enough in the
+% library reference. Doing it here keeps it the same for all the manuals.
+%
+\renewcommand*\l at section{\@dottedtocline{1}{1.5em}{2.6em}}
+\renewcommand*\l at subsection{\@dottedtocline{2}{4.1em}{3.5em}}
+
+% Fix the bibliography environment to add an entry to the Table of
+% Contents.
+% For a report document class this environment is a chapter.
+\let\py at OldThebibliography=\thebibliography
+\renewcommand{\thebibliography}[1]{
+ \cleardoublepage
+ \phantomsection
+ \py at OldThebibliography{1}
+ \addcontentsline{toc}{chapter}{\bibname}
+}
+
+% Same for the indices.
+% The memoir class already does this, so we don't duplicate it in that case.
+%
+\@ifclassloaded{memoir}{}{
+ \let\py at OldTheindex=\theindex
+ \renewcommand{\theindex}{
+ \cleardoublepage
+ \phantomsection
+ \py at OldTheindex
+ \addcontentsline{toc}{chapter}{\indexname}
+ }
+}
diff --git a/doc/build/latex/tabulary.sty b/doc/build/latex/tabulary.sty
new file mode 100644
index 0000000..11fdf74
--- /dev/null
+++ b/doc/build/latex/tabulary.sty
@@ -0,0 +1,452 @@
+%%
+%% This is file `tabulary.sty',
+%% generated with the docstrip utility.
+%%
+%% The original source files were:
+%%
+%% tabulary.dtx (with options: `package')
+%% DRAFT VERSION
+%%
+%% File `tabulary.dtx'.
+%% Copyright (C) 1995 1996 2003 2008 David Carlisle
+%% This file may be distributed under the terms of the LPPL.
+%% See 00readme.txt for details.
+%%
+\NeedsTeXFormat{LaTeX2e}
+\ProvidesPackage{tabulary}
+ [2008/12/01 v0.9 tabulary package (DPC)]
+\RequirePackage{array}
+\catcode`\Z=14
+\DeclareOption{debugshow}{\catcode`\Z=9\relax}
+\ProcessOptions
+\def\arraybackslash{\let\\=\@arraycr}
+\def\@finalstrut#1{%
+ \unskip\ifhmode\nobreak\fi\vrule\@width\z@\@height\z@\@depth\dp#1}
+\newcount\TY at count
+\def\tabulary{%
+ \let\TY at final\tabular
+ \let\endTY at final\endtabular
+ \TY at tabular}
+\def\TY at tabular#1{%
+ \edef\TY@{\@currenvir}%
+ {\ifnum0=`}\fi
+ \@ovxx\TY at linewidth
+ \@ovyy\TY at tablewidth
+ \count@\z@
+ \@tempswatrue
+ \@whilesw\if at tempswa\fi{%
+ \advance\count@\@ne
+ \expandafter\ifx\csname TY at F\the\count@\endcsname\relax
+ \@tempswafalse
+ \else
+ \expandafter\let\csname TY at SF\the\count@\expandafter\endcsname
+ \csname TY at F\the\count@\endcsname
+ \global\expandafter\let\csname TY at F\the\count@\endcsname\relax
+ \expandafter\let\csname TY at S\the\count@\expandafter\endcsname
+ \csname TY@\the\count@\endcsname
+ \fi}%
+ \global\TY at count\@ne
+ \TY at width\xdef{0pt}%
+ \global\TY at tablewidth\z@
+ \global\TY at linewidth#1\relax
+Z\message{^^J^^JTable^^J%
+Z Target Width: \the\TY at linewidth^^J%
+Z \string\tabcolsep: \the\tabcolsep\space
+Z \string\arrayrulewidth: \the\arrayrulewidth\space
+Z \string\doublerulesep: \the\doublerulesep^^J%
+Z \string\tymin: \the\tymin\space
+Z \string\tymax: \the\tymax^^J}%
+ \let\@classz\TY at classz
+ \let\verb\TX at verb
+ \toks@{}\TY at get@body}
+\let\TY@@mkpream\@mkpream
+\def\TY at mkpream{%
+ \def\@addamp{%
+ \if at firstamp \@firstampfalse \else
+ \global\advance\TY at count\@ne
+ \edef\@preamble{\@preamble &}\fi
+ \TY at width\xdef{0pt}}%
+ \def\@acol{%
+ \TY at subwidth\col at sep
+ \@addtopreamble{\hskip\col at sep}}%
+ \let\@arrayrule\TY at arrayrule
+ \let\@classvi\TY at classvi
+ \def\@classv{\save at decl
+ \expandafter\NC at ecs\@nextchar\extracolsep{}\extracolsep\@@@
+ \sbox\z@{\d at llarbegin\@nextchar\d at llarend}%
+ \TY at subwidth{\wd\z@}%
+ \@addtopreamble{\d at llarbegin\the at toks\the\count@\relax\d at llarend}%
+ \prepnext at tok}%
+ \global\let\@mkpream\TY@@mkpream
+ \TY@@mkpream}
+\def\TY at arrayrule{%
+ \TY at subwidth\arrayrulewidth
+ \@addtopreamble \vline}
+\def\TY at classvi{\ifcase \@lastchclass
+ \@acol \or
+ \TY at subwidth\doublerulesep
+ \@addtopreamble{\hskip \doublerulesep}\or
+ \@acol \or
+ \@classvii
+ \fi}
+\def\TY at tab{%
+ \setbox\z@\hbox\bgroup
+ \let\[$\let\]$%
+ \let\equation$\let\endequation$%
+ \col at sep\tabcolsep
+ \let\d at llarbegin\begingroup\let\d at llarend\endgroup
+ \let\@mkpream\TY at mkpream
+ \def\multicolumn##1##2##3{\multispan##1\relax}%
+ \CT at start\TY at tabarray}
+\def\TY at tabarray{\@ifnextchar[{\TY at array}{\@array[t]}}
+\def\TY at array[#1]{\@array[t]}
+\def\TY at width#1{%
+ \expandafter#1\csname TY@\the\TY at count\endcsname}
+\def\TY at subwidth#1{%
+ \TY at width\dimen@
+ \advance\dimen at -#1\relax
+ \TY at width\xdef{\the\dimen@}%
+ \global\advance\TY at linewidth-#1\relax}
+\def\endtabulary{%
+ \gdef\@halignto{}%
+ \let\TY at footnote\footnote%
+ \def\footnote{}% prevent footnotes from doing anything
+ \expandafter\TY at tab\the\toks@
+ \crcr\omit
+ {\xdef\TY at save@row{}%
+ \loop
+ \advance\TY at count\m at ne
+ \ifnum\TY at count>\z@
+ \xdef\TY at save@row{\TY at save@row&\omit}%
+ \repeat}\TY at save@row
+ \endarray\global\setbox1=\lastbox\setbox0=\vbox{\unvbox1
+ \unskip\global\setbox1=\lastbox}\egroup
+ \dimen@\TY at linewidth
+ \divide\dimen@\TY at count
+ \ifdim\dimen@<\tymin
+ \TY at warn{tymin too large (\the\tymin), resetting to \the\dimen@}%
+ \tymin\dimen@
+ \fi
+ \setbox\tw@=\hbox{\unhbox\@ne
+ \loop
+\@tempdima=\lastskip
+\ifdim\@tempdima>\z@
+Z \message{ecs=\the\@tempdima^^J}%
+ \global\advance\TY at linewidth-\@tempdima
+\fi
+ \unskip
+ \setbox\tw@=\lastbox
+ \ifhbox\tw@
+Z \message{Col \the\TY at count: Initial=\the\wd\tw@\space}%
+ \ifdim\wd\tw@>\tymax
+ \wd\tw@\tymax
+Z \message{> max\space}%
+Z \else
+Z \message{ \@spaces\space}%
+ \fi
+ \TY at width\dimen@
+Z \message{\the\dimen@\space}%
+ \advance\dimen@\wd\tw@
+Z \message{Final=\the\dimen@\space}%
+ \TY at width\xdef{\the\dimen@}%
+ \ifdim\dimen@<\tymin
+Z \message{< tymin}%
+ \global\advance\TY at linewidth-\dimen@
+ \expandafter\xdef\csname TY at F\the\TY at count\endcsname
+ {\the\dimen@}%
+ \else
+ \expandafter\ifx\csname TY at F\the\TY at count\endcsname\z@
+Z \message{***}%
+ \global\advance\TY at linewidth-\dimen@
+ \expandafter\xdef\csname TY at F\the\TY at count\endcsname
+ {\the\dimen@}%
+ \else
+Z \message{> tymin}%
+ \global\advance\TY at tablewidth\dimen@
+ \global\expandafter\let\csname TY at F\the\TY at count\endcsname
+ \maxdimen
+ \fi\fi
+ \advance\TY at count\m at ne
+ \repeat}%
+ \TY at checkmin
+ \TY at checkmin
+ \TY at checkmin
+ \TY at checkmin
+ \TY at count\z@
+ \let\TY at box\TY at box@v
+ \let\footnote\TY at footnote % restore footnotes
+ {\expandafter\TY at final\the\toks@\endTY at final}%
+ \count@\z@
+ \@tempswatrue
+ \@whilesw\if at tempswa\fi{%
+ \advance\count@\@ne
+ \expandafter\ifx\csname TY at SF\the\count@\endcsname\relax
+ \@tempswafalse
+ \else
+ \global\expandafter\let\csname TY at F\the\count@\expandafter\endcsname
+ \csname TY at SF\the\count@\endcsname
+ \global\expandafter\let\csname TY@\the\count@\expandafter\endcsname
+ \csname TY at S\the\count@\endcsname
+ \fi}%
+ \TY at linewidth\@ovxx
+ \TY at tablewidth\@ovyy
+ \ifnum0=`{\fi}}
+\def\TY at checkmin{%
+ \let\TY at checkmin\relax
+\ifdim\TY at tablewidth>\z@
+ \Gscale at div\TY at ratio\TY at linewidth\TY at tablewidth
+ \ifdim\TY at tablewidth <\TY at linewidth
+ \def\TY at ratio{1}%
+ \fi
+\else
+ \TY at warn{No suitable columns!}%
+ \def\TY at ratio{1}%
+\fi
+\count@\z@
+Z \message{^^JLine Width: \the\TY at linewidth,
+Z Natural Width: \the\TY at tablewidth,
+Z Ratio: \TY at ratio^^J}%
+\@tempdima\z@
+\loop
+\ifnum\count@<\TY at count
+\advance\count@\@ne
+ \ifdim\csname TY at F\the\count@\endcsname>\tymin
+ \dimen@\csname TY@\the\count@\endcsname
+ \dimen@\TY at ratio\dimen@
+ \ifdim\dimen@<\tymin
+Z \message{Column \the\count@\space ->}%
+ \global\expandafter\let\csname TY at F\the\count@\endcsname\tymin
+ \global\advance\TY at linewidth-\tymin
+ \global\advance\TY at tablewidth-\csname TY@\the\count@\endcsname
+ \let\TY at checkmin\TY@@checkmin
+ \else
+ \expandafter\xdef\csname TY at F\the\count@\endcsname{\the\dimen@}%
+ \advance\@tempdima\csname TY at F\the\count@\endcsname
+ \fi
+ \fi
+Z \dimen@\csname TY at F\the\count@\endcsname\message{\the\dimen@, }%
+\repeat
+Z \message{^^JTotal:\the\@tempdima^^J}%
+}
+\let\TY@@checkmin\TY at checkmin
+\newdimen\TY at linewidth
+\def\tyformat{\everypar{{\nobreak\hskip\z at skip}}}
+\newdimen\tymin
+\tymin=10pt
+\newdimen\tymax
+\tymax=2\textwidth
+\def\@testpach{\@chclass
+ \ifnum \@lastchclass=6 \@ne \@chnum \@ne \else
+ \ifnum \@lastchclass=7 5 \else
+ \ifnum \@lastchclass=8 \tw@ \else
+ \ifnum \@lastchclass=9 \thr@@
+ \else \z@
+ \ifnum \@lastchclass = 10 \else
+ \edef\@nextchar{\expandafter\string\@nextchar}%
+ \@chnum
+ \if \@nextchar c\z@ \else
+ \if \@nextchar l\@ne \else
+ \if \@nextchar r\tw@ \else
+ \if \@nextchar C7 \else
+ \if \@nextchar L8 \else
+ \if \@nextchar R9 \else
+ \if \@nextchar J10 \else
+ \z@ \@chclass
+ \if\@nextchar |\@ne \else
+ \if \@nextchar !6 \else
+ \if \@nextchar @7 \else
+ \if \@nextchar <8 \else
+ \if \@nextchar >9 \else
+ 10
+ \@chnum
+ \if \@nextchar m\thr@@\else
+ \if \@nextchar p4 \else
+ \if \@nextchar b5 \else
+ \z@ \@chclass \z@ \@preamerr \z@ \fi \fi \fi \fi\fi \fi \fi\fi \fi
+ \fi \fi \fi \fi \fi \fi \fi \fi \fi \fi \fi}
+\def\TY at classz{%
+ \@classx
+ \@tempcnta\count@
+ \ifx\TY at box\TY at box@v
+ \global\advance\TY at count\@ne
+ \fi
+ \let\centering c%
+ \let\raggedright\noindent
+ \let\raggedleft\indent
+ \let\arraybackslash\relax
+ \prepnext at tok
+ \ifnum\@chnum<4
+ \global\expandafter\let\csname TY at F\the\TY at count\endcsname\z@
+ \fi
+ \ifnum\@chnum=6
+ \global\expandafter\let\csname TY at F\the\TY at count\endcsname\z@
+ \fi
+ \@addtopreamble{%
+ \ifcase\@chnum
+ \hfil \d at llarbegin\insert at column\d at llarend \hfil \or
+ \kern\z@
+ \d at llarbegin \insert at column \d at llarend \hfil \or
+ \hfil\kern\z@ \d at llarbegin \insert at column \d at llarend \or
+ $\vcenter\@startpbox{\@nextchar}\insert at column \@endpbox $\or
+ \vtop \@startpbox{\@nextchar}\insert at column \@endpbox \or
+ \vbox \@startpbox{\@nextchar}\insert at column \@endpbox \or
+ \d at llarbegin \insert at column \d at llarend \or% dubious "s" case
+ \TY at box\centering\or
+ \TY at box\raggedright\or
+ \TY at box\raggedleft\or
+ \TY at box\relax
+ \fi}\prepnext at tok}
+\def\TY at box#1{%
+ \ifx\centering#1%
+ \hfil \d at llarbegin\insert at column\d at llarend \hfil \else
+ \ifx\raggedright#1%
+ \kern\z@%<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<
+ \d at llarbegin \insert at column \d at llarend \hfil \else
+ \ifx\raggedleft#1%
+ \hfil\kern\z@ \d at llarbegin \insert at column \d at llarend \else
+ \ifx\relax#1%
+ \d at llarbegin \insert at column \d at llarend
+ \fi \fi \fi \fi}
+\def\TY at box@v#1{%
+ \vtop \@startpbox{\csname TY at F\the\TY at count\endcsname}%
+ #1\arraybackslash\tyformat
+ \insert at column\@endpbox}
+\newdimen\TY at tablewidth
+\def\Gscale at div#1#2#3{%
+ \setlength\dimen@{#3}%
+ \ifdim\dimen@=\z@
+ \PackageError{graphics}{Division by 0}\@eha
+ \dimen@#2%
+ \fi
+ \edef\@tempd{\the\dimen@}%
+ \setlength\dimen@{#2}%
+ \count at 65536\relax
+ \ifdim\dimen@<\z@
+ \dimen at -\dimen@
+ \count at -\count@
+ \fi
+ \loop
+ \ifdim\dimen@<8192\p@
+ \dimen@\tw@\dimen@
+ \divide\count@\tw@
+ \repeat
+ \dimen at ii=\@tempd\relax
+ \divide\dimen at ii\count@
+ \divide\dimen@\dimen at ii
+ \edef#1{\strip at pt\dimen@}}
+\long\def\TY at get@body#1\end
+ {\toks@\expandafter{\the\toks@#1}\TY at find@end}
+\def\TY at find@end#1{%
+ \def\@tempa{#1}%
+ \ifx\@tempa\TY@\def\@tempa{\end{#1}}\expandafter\@tempa
+ \else\toks@\expandafter
+ {\the\toks@\end{#1}}\expandafter\TY at get@body\fi}
+\def\TY at warn{%
+ \PackageWarning{tabulary}}
+\catcode`\Z=11
+\AtBeginDocument{
+\@ifpackageloaded{colortbl}{%
+\expandafter\def\expandafter\@mkpream\expandafter#\expandafter1%
+ \expandafter{%
+ \expandafter\let\expandafter\CT at setup\expandafter\relax
+ \expandafter\let\expandafter\CT at color\expandafter\relax
+ \expandafter\let\expandafter\CT at do@color\expandafter\relax
+ \expandafter\let\expandafter\color\expandafter\relax
+ \expandafter\let\expandafter\CT at column@color\expandafter\relax
+ \expandafter\let\expandafter\CT at row@color\expandafter\relax
+ \@mkpream{#1}}
+\let\TY@@mkpream\@mkpream
+\def\TY at classz{%
+ \@classx
+ \@tempcnta\count@
+ \ifx\TY at box\TY at box@v
+ \global\advance\TY at count\@ne
+ \fi
+ \let\centering c%
+ \let\raggedright\noindent
+ \let\raggedleft\indent
+ \let\arraybackslash\relax
+ \prepnext at tok
+\expandafter\CT at extract\the\toks\@tempcnta\columncolor!\@nil
+ \ifnum\@chnum<4
+ \global\expandafter\let\csname TY at F\the\TY at count\endcsname\z@
+ \fi
+ \ifnum\@chnum=6
+ \global\expandafter\let\csname TY at F\the\TY at count\endcsname\z@
+ \fi
+ \@addtopreamble{%
+ \setbox\z@\hbox\bgroup\bgroup
+ \ifcase\@chnum
+ \hskip\stretch{.5}\kern\z@
+ \d at llarbegin\insert at column\d at llarend\hskip\stretch{.5}\or
+ \kern\z@%<<<<<<<<<<<<<<<<<<<<<<<<<<<
+ \d at llarbegin \insert at column \d at llarend \hfill \or
+ \hfill\kern\z@ \d at llarbegin \insert at column \d at llarend \or
+ $\vcenter\@startpbox{\@nextchar}\insert at column \@endpbox $\or
+ \vtop \@startpbox{\@nextchar}\insert at column \@endpbox \or
+ \vbox \@startpbox{\@nextchar}\insert at column \@endpbox \or
+ \d at llarbegin \insert at column \d at llarend \or% dubious s case
+ \TY at box\centering\or
+ \TY at box\raggedright\or
+ \TY at box\raggedleft\or
+ \TY at box\relax
+ \fi
+ \egroup\egroup
+\begingroup
+ \CT at setup
+ \CT at column@color
+ \CT at row@color
+ \CT at do@color
+\endgroup
+ \@tempdima\ht\z@
+ \advance\@tempdima\minrowclearance
+ \vrule\@height\@tempdima\@width\z@
+\unhbox\z@
+}\prepnext at tok}%
+ \def\TY at arrayrule{%
+ \TY at subwidth\arrayrulewidth
+ \@addtopreamble{{\CT at arc@\vline}}}%
+ \def\TY at classvi{\ifcase \@lastchclass
+ \@acol \or
+ \TY at subwidth\doublerulesep
+ \ifx\CT at drsc@\relax
+ \@addtopreamble{\hskip\doublerulesep}%
+ \else
+ \@addtopreamble{{\CT at drsc@\vrule\@width\doublerulesep}}%
+ \fi\or
+ \@acol \or
+ \@classvii
+ \fi}%
+}{%
+\let\CT at start\relax
+}
+}
+{\uccode`\*=`\ %
+\uppercase{\gdef\TX at verb{%
+ \leavevmode\null\TX at vwarn
+ {\ifnum0=`}\fi\ttfamily\let\\\ignorespaces
+ \@ifstar{\let~*\TX at vb}{\TX at vb}}}}
+\def\TX at vb#1{\def\@tempa##1#1{\toks@{##1}\edef\@tempa{\the\toks@}%
+ \expandafter\TX at v\meaning\@tempa\\ \\\ifnum0=`{\fi}}\@tempa!}
+\def\TX at v#1!{\afterassignment\TX at vfirst\let\@tempa= }
+\begingroup
+\catcode`\*=\catcode`\#
+\catcode`\#=12
+\gdef\TX at vfirst{%
+ \if\@tempa#%
+ \def\@tempb{\TX at v@#}%
+ \else
+ \let\@tempb\TX at v@
+ \if\@tempa\space~\else\@tempa\fi
+ \fi
+ \@tempb}
+\gdef\TX at v@*1 *2{%
+ \TX at v@hash*1##\relax\if*2\\\else~\expandafter\TX at v@\fi*2}
+\gdef\TX at v@hash*1##*2{*1\ifx*2\relax\else#\expandafter\TX at v@hash\fi*2}
+\endgroup
+\def\TX at vwarn{%
+ \@warning{\noexpand\verb may be unreliable inside tabularx/y}%
+ \global\let\TX at vwarn\@empty}
+\endinput
+%%
+%% End of file `tabulary.sty'.
diff --git a/doc/build/objects.inv b/doc/build/objects.inv
new file mode 100644
index 0000000..87acaa3
--- /dev/null
+++ b/doc/build/objects.inv
@@ -0,0 +1,6 @@
+# Sphinx inventory version 2
+# Project: Umap
+# Version: 0.1.0
+# The remainder of this file is compressed using zlib.
+xڕ��j�@
��~
+�z�io!��ЄR(��c������ʸ~��)1�����|��[
ƭ��7/�|�[r����:��Qv��E?٫�X�)bg�1����Л��vt��˼X������
�2�g�!�5��y���ΫԤR6~t�g�B3N^ȐXm'�5?��4������4=-9��^s
�d椛*!�y,�Xq���-��)?$L"�M�$D�쿰��H�
\ No newline at end of file
diff --git a/doc/build/py-modindex.html b/doc/build/py-modindex.html
new file mode 100644
index 0000000..37a5715
--- /dev/null
+++ b/doc/build/py-modindex.html
@@ -0,0 +1,104 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>Python Module Index — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: './',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="_static/jquery.js"></script>
+ <script type="text/javascript" src="_static/underscore.js"></script>
+ <script type="text/javascript" src="_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="documentation.html" />
+
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+
+ <script type="text/javascript">
+ DOCUMENTATION_OPTIONS.COLLAPSE_INDEX = true;
+ </script>
+
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+
+ <h1>Python Module Index</h1>
+
+ <div class="modindex-jumpbox">
+ <a href="#cap-u"><strong>u</strong></a>
+ </div>
+
+ <table class="indextable modindextable" cellspacing="0" cellpadding="2">
+ <tr class="pcap"><td></td><td> </td><td></td></tr>
+ <tr class="cap" id="cap-u"><td></td><td>
+ <strong>u</strong></td><td></td></tr>
+ <tr>
+ <td></td>
+ <td>
+ <a href="documentation.html#module-umap"><code class="xref">umap</code></a> <em>(Unix)</em></td><td>
+ <em></em></td></tr>
+ </table>
+
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper"><div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="documentation.html">Documentation overview</a><ul>
+ </ul></li>
+</ul>
+</div>
+<div id="searchbox" style="display: none" role="search">
+ <h3>Quick search</h3>
+ <form class="search" action="search.html" method="get">
+ <input type="text" name="q" />
+ <input type="submit" value="Go" />
+ <input type="hidden" name="check_keywords" value="yes" />
+ <input type="hidden" name="area" value="default" />
+ </form>
+</div>
+<script type="text/javascript">$('#searchbox').show(0);</script>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/search.html b/doc/build/search.html
new file mode 100644
index 0000000..d5bb37c
--- /dev/null
+++ b/doc/build/search.html
@@ -0,0 +1,100 @@
+<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
+ "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+
+
+<html xmlns="http://www.w3.org/1999/xhtml">
+ <head>
+ <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
+
+ <title>Search — Umap 0.1.0 documentation</title>
+
+ <link rel="stylesheet" href="_static/alabaster.css" type="text/css" />
+ <link rel="stylesheet" href="_static/pygments.css" type="text/css" />
+
+ <script type="text/javascript">
+ var DOCUMENTATION_OPTIONS = {
+ URL_ROOT: './',
+ VERSION: '0.1.0',
+ COLLAPSE_INDEX: false,
+ FILE_SUFFIX: '.html',
+ HAS_SOURCE: true
+ };
+ </script>
+ <script type="text/javascript" src="_static/jquery.js"></script>
+ <script type="text/javascript" src="_static/underscore.js"></script>
+ <script type="text/javascript" src="_static/doctools.js"></script>
+ <script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-AMS-MML_HTMLorMML"></script>
+ <script type="text/javascript" src="_static/searchtools.js"></script>
+ <link rel="top" title="Umap 0.1.0 documentation" href="documentation.html" />
+ <script type="text/javascript">
+ jQuery(function() { Search.loadIndex("searchindex.js"); });
+ </script>
+
+ <script type="text/javascript" id="searchindexloader"></script>
+
+
+
+ <meta name="viewport" content="width=device-width, initial-scale=0.9, maximum-scale=0.9" />
+
+
+ </head>
+ <body role="document">
+
+ <div class="document">
+ <div class="documentwrapper">
+ <div class="bodywrapper">
+ <div class="body" role="main">
+
+ <h1 id="search-documentation">Search</h1>
+ <div id="fallback" class="admonition warning">
+ <script type="text/javascript">$('#fallback').hide();</script>
+ <p>
+ Please activate JavaScript to enable the search
+ functionality.
+ </p>
+ </div>
+ <p>
+ From here you can search these documents. Enter your search
+ words into the box below and click "search". Note that the search
+ function will automatically search for all of the words. Pages
+ containing fewer words won't appear in the result list.
+ </p>
+ <form action="" method="get">
+ <input type="text" name="q" value="" />
+ <input type="submit" value="search" />
+ <span id="search-progress" style="padding-left: 10px"></span>
+ </form>
+
+ <div id="search-results">
+
+ </div>
+
+ </div>
+ </div>
+ </div>
+ <div class="sphinxsidebar" role="navigation" aria-label="main navigation">
+ <div class="sphinxsidebarwrapper"><div class="relations">
+<h3>Related Topics</h3>
+<ul>
+ <li><a href="documentation.html">Documentation overview</a><ul>
+ </ul></li>
+</ul>
+</div>
+ </div>
+ </div>
+ <div class="clearer"></div>
+ </div>
+ <div class="footer">
+ ©2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman.
+
+ |
+ Powered by <a href="http://sphinx-doc.org/">Sphinx 1.4.1</a>
+ & <a href="https://github.com/bitprophet/alabaster">Alabaster 0.7.7</a>
+
+ </div>
+
+
+
+
+ </body>
+</html>
\ No newline at end of file
diff --git a/doc/build/searchindex.js b/doc/build/searchindex.js
new file mode 100644
index 0000000..1408a8b
--- /dev/null
+++ b/doc/build/searchindex.js
@@ -0,0 +1 @@
+Search.setIndex({envversion:47,filenames:["documentation"],objects:{"":{umap:[0,0,0,"-"]},"umap.Int8Handler":{write_as_wig:[0,2,1,""],write_beds:[0,2,1,""]},umap:{BowtieWrapper:[0,1,1,""],CombineUmaps:[0,1,1,""],GetKmers:[0,1,1,""],Int8Handler:[0,1,1,""],UnifyBowtie:[0,1,1,""]}},objnames:{"0":["py","module","Python module"],"1":["py","class","Python class"],"2":["py","method","Python method"]},objtypes:{"0":"py:module","1":"py:class","2":"py:method"},terms:{"case":0,"class":0,aatt:0,aatt [...]
\ No newline at end of file
diff --git a/doc/source/conf.py b/doc/source/conf.py
new file mode 100644
index 0000000..43c9e85
--- /dev/null
+++ b/doc/source/conf.py
@@ -0,0 +1,297 @@
+# -*- coding: utf-8 -*-
+#
+# Umap documentation build configuration file, created by
+# sphinx-quickstart on Mon Jun 20 14:29:08 2016.
+#
+# This file is execfile()d with the current directory set to its
+# containing dir.
+#
+# Note that not all possible configuration values are present in this
+# autogenerated file.
+#
+# All configuration values have a default; values that are commented out
+# serve to show the default.
+
+import sys
+import os
+
+# Add sys.paths for
+sys.path.insert(0, "../..")
+
+
+# If extensions (or modules to document with autodoc) are in another directory,
+# add these directories to sys.path here. If the directory is relative to the
+# documentation root, use os.path.abspath to make it absolute, like shown here.
+#sys.path.insert(0, os.path.abspath('.'))
+
+# -- General configuration ------------------------------------------------
+
+# If your documentation needs a minimal Sphinx version, state it here.
+#needs_sphinx = '1.0'
+
+# Add any Sphinx extension module names here, as strings. They can be
+# extensions coming with Sphinx (named 'sphinx.ext.*') or your custom
+# ones.
+extensions = [
+ 'sphinx.ext.autodoc',
+ 'sphinx.ext.doctest',
+ 'sphinx.ext.todo',
+ 'sphinx.ext.coverage',
+ 'sphinx.ext.mathjax',
+ 'sphinx.ext.viewcode',
+]
+
+# Add any paths that contain templates here, relative to this directory.
+templates_path = ['_templates']
+
+# The suffix(es) of source filenames.
+# You can specify multiple suffix as a list of string:
+# source_suffix = ['.rst', '.md']
+source_suffix = '.rst'
+
+# The encoding of source files.
+#source_encoding = 'utf-8-sig'
+
+# The master toctree document.
+master_doc = 'documentation'
+
+# General information about the project.
+project = u'Umap'
+copyright = u'2016, Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman'
+author = u'Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman'
+
+# The version info for the project you're documenting, acts as replacement for
+# |version| and |release|, also used in various other places throughout the
+# built documents.
+#
+# The short X.Y version.
+version = u'0.1.0'
+# The full version, including alpha/beta/rc tags.
+release = u'0.1.0'
+
+# The language for content autogenerated by Sphinx. Refer to documentation
+# for a list of supported languages.
+#
+# This is also used if you do content translation via gettext catalogs.
+# Usually you set "language" from the command line for these cases.
+language = None
+
+# There are two options for replacing |today|: either, you set today to some
+# non-false value, then it is used:
+#today = ''
+# Else, today_fmt is used as the format for a strftime call.
+#today_fmt = '%B %d, %Y'
+
+# List of patterns, relative to source directory, that match files and
+# directories to ignore when looking for source files.
+# This patterns also effect to html_static_path and html_extra_path
+exclude_patterns = []
+
+# The reST default role (used for this markup: `text`) to use for all
+# documents.
+#default_role = None
+
+# If true, '()' will be appended to :func: etc. cross-reference text.
+#add_function_parentheses = True
+
+# If true, the current module name will be prepended to all description
+# unit titles (such as .. function::).
+#add_module_names = True
+
+# If true, sectionauthor and moduleauthor directives will be shown in the
+# output. They are ignored by default.
+#show_authors = False
+
+# The name of the Pygments (syntax highlighting) style to use.
+pygments_style = 'sphinx'
+
+# A list of ignored prefixes for module index sorting.
+#modindex_common_prefix = []
+
+# If true, keep warnings as "system message" paragraphs in the built documents.
+#keep_warnings = False
+
+# If true, `todo` and `todoList` produce output, else they produce nothing.
+todo_include_todos = True
+
+
+# -- Options for HTML output ----------------------------------------------
+
+# The theme to use for HTML and HTML Help pages. See the documentation for
+# a list of builtin themes.
+html_theme = 'alabaster'
+
+# Theme options are theme-specific and customize the look and feel of a theme
+# further. For a list of options available for each theme, see the
+# documentation.
+#html_theme_options = {}
+
+# Add any paths that contain custom themes here, relative to this directory.
+#html_theme_path = []
+
+# The name for this set of Sphinx documents.
+# "<project> v<release> documentation" by default.
+#html_title = u'Umap v0.1.0'
+
+# A shorter title for the navigation bar. Default is the same as html_title.
+#html_short_title = None
+
+# The name of an image file (relative to this directory) to place at the top
+# of the sidebar.
+#html_logo = None
+
+# The name of an image file (relative to this directory) to use as a favicon of
+# the docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32
+# pixels large.
+#html_favicon = None
+
+# Add any paths that contain custom static files (such as style sheets) here,
+# relative to this directory. They are copied after the builtin static files,
+# so a file named "default.css" will overwrite the builtin "default.css".
+html_static_path = ['_static']
+
+# Add any extra paths that contain custom files (such as robots.txt or
+# .htaccess) here, relative to this directory. These files are copied
+# directly to the root of the documentation.
+#html_extra_path = []
+
+# If not None, a 'Last updated on:' timestamp is inserted at every page
+# bottom, using the given strftime format.
+# The empty string is equivalent to '%b %d, %Y'.
+#html_last_updated_fmt = None
+
+# If true, SmartyPants will be used to convert quotes and dashes to
+# typographically correct entities.
+#html_use_smartypants = True
+
+# Custom sidebar templates, maps document names to template names.
+#html_sidebars = {}
+
+# Additional templates that should be rendered to pages, maps page names to
+# template names.
+#html_additional_pages = {}
+
+# If false, no module index is generated.
+#html_domain_indices = True
+
+# If false, no index is generated.
+#html_use_index = True
+
+# If true, the index is split into individual pages for each letter.
+#html_split_index = False
+
+# If true, links to the reST sources are added to the pages.
+#html_show_sourcelink = True
+
+# If true, "Created using Sphinx" is shown in the HTML footer. Default is True.
+#html_show_sphinx = True
+
+# If true, "(C) Copyright ..." is shown in the HTML footer. Default is True.
+#html_show_copyright = True
+
+# If true, an OpenSearch description file will be output, and all pages will
+# contain a <link> tag referring to it. The value of this option must be the
+# base URL from which the finished HTML is served.
+#html_use_opensearch = ''
+
+# This is the file name suffix for HTML files (e.g. ".xhtml").
+#html_file_suffix = None
+
+# Language to be used for generating the HTML full-text search index.
+# Sphinx supports the following languages:
+# 'da', 'de', 'en', 'es', 'fi', 'fr', 'hu', 'it', 'ja'
+# 'nl', 'no', 'pt', 'ro', 'ru', 'sv', 'tr', 'zh'
+#html_search_language = 'en'
+
+# A dictionary with options for the search language support, empty by default.
+# 'ja' uses this config value.
+# 'zh' user can custom change `jieba` dictionary path.
+#html_search_options = {'type': 'default'}
+
+# The name of a javascript file (relative to the configuration directory) that
+# implements a search results scorer. If empty, the default will be used.
+#html_search_scorer = 'scorer.js'
+
+# Output file base name for HTML help builder.
+htmlhelp_basename = 'Umapdoc'
+
+# -- Options for LaTeX output ---------------------------------------------
+
+latex_elements = {
+# The paper size ('letterpaper' or 'a4paper').
+#'papersize': 'letterpaper',
+
+# The font size ('10pt', '11pt' or '12pt').
+#'pointsize': '10pt',
+
+# Additional stuff for the LaTeX preamble.
+#'preamble': '',
+
+# Latex figure (float) alignment
+#'figure_align': 'htbp',
+}
+
+# Grouping the document tree into LaTeX files. List of tuples
+# (source start file, target name, title,
+# author, documentclass [howto, manual, or own class]).
+latex_documents = [
+ (master_doc, 'Umap.tex', u'Umap Documentation',
+ u'Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman', 'manual'),
+]
+
+# The name of an image file (relative to this directory) to place at the top of
+# the title page.
+#latex_logo = None
+
+# For "manual" documents, if this is true, then toplevel headings are parts,
+# not chapters.
+#latex_use_parts = False
+
+# If true, show page references after internal links.
+#latex_show_pagerefs = False
+
+# If true, show URL addresses after external links.
+#latex_show_urls = False
+
+# Documents to append as an appendix to all manuals.
+#latex_appendices = []
+
+# If false, no module index is generated.
+#latex_domain_indices = True
+
+
+# -- Options for manual page output ---------------------------------------
+
+# One entry per manual page. List of tuples
+# (source start file, name, description, authors, manual section).
+man_pages = [
+ (master_doc, 'umap', u'Umap Documentation',
+ [author], 1)
+]
+
+# If true, show URL addresses after external links.
+#man_show_urls = False
+
+
+# -- Options for Texinfo output -------------------------------------------
+
+# Grouping the document tree into Texinfo files. List of tuples
+# (source start file, target name, title, author,
+# dir menu entry, description, category)
+texinfo_documents = [
+ (master_doc, 'Umap', u'Umap Documentation',
+ author, 'Umap', 'One line description of project.',
+ 'Miscellaneous'),
+]
+
+# Documents to append as an appendix to all manuals.
+#texinfo_appendices = []
+
+# If false, no module index is generated.
+#texinfo_domain_indices = True
+
+# How to display URL addresses: 'footnote', 'no', or 'inline'.
+#texinfo_show_urls = 'footnote'
+
+# If true, do not generate a @detailmenu in the "Top" node's menu.
+#texinfo_no_detailmenu = False
diff --git a/doc/source/documentation.rst b/doc/source/documentation.rst
new file mode 100644
index 0000000..51ccce1
--- /dev/null
+++ b/doc/source/documentation.rst
@@ -0,0 +1,195 @@
+.. Umap documentation master file, created by
+ sphinx-quickstart on Mon Jun 20 14:29:08 2016.
+ You can adapt this file completely to your liking, but it should at least
+ contain the root `toctree` directive.
+
+Welcome to Umap's documentation!
+================================
+
+Contents:
+
+.. toctree::
+ :maxdepth: 2
+
+
+Introduction
+------------
+
+**The free umap software package efficiently identifies uniquely mappable regions of any genome.
+Its Bismap extension identifies mappability of the bisulfite converted genome (methylome).**
+
+the mappability of a genome for a given read length *k*.
+First, it generates all possible *k*-mers of the genome.
+Second, it maps these unique *k*-mers to the genome with `Bowtie <http://bowtie-bio.sourceforge.net/index.shtml>`_ version 1.1.0.
+Third, Umap marks the start position of each *k*-mer that aligns to only one region in the genome.
+Umap repeats these steps for a range of different *k*-mers and stores the data of each chromosome
+in a binary vector *X* with the same length as the chromosome's sequence.
+For read length *k*, :math:`X_i = 1` means that the sequence starting at :math:`X_i` and ending
+at :math:`X_{i+k}` is uniquely mappable on the forward strand.
+Since we align to both strands of the genome, the reverse complement of this same sequence
+starting at :math:`X_{i+k}` on the reverse strand is also uniquely mappable.
+:math:`X_i = 0` means that the sequence starting at :math:`X_i` and ending at
+:math:`X_{i+k}` can be mapped to at least two different regions in the genome.
+
+
+Mappability of the bisulfite-converted genome
+---------------------------------------------
+
+To identify the single-read mappability of a bisulfite-converted genome,
+we create two altered genome sequences.
+In the first sequence, we convert all cytosines to thymine (C :math:`\rightarrow` T).
+In the other sequence we convert all guanines to adenine (G :math:`\rightarrow` A).
+Our approach follows those of `Bismark <http://www.bioinformatics.babraham.ac.uk/projects/bismark/>`_
+and `BWA-meth <https://github.com/brentp/bwa-meth>`_.
+We convert the genome sequence this way because bisulfite
+treatment converts un-methylated cytosine to uracil which is read as thymine.
+Similarly the guanine that is base-pairing with the un-methylated cytosine in
+reverse strand converts to adenine. However these two conversions never occur
+at the same time on the same read. We identify the uniquely mappable regions
+of these two genomes separately, and then combine the data to represent the
+single-read mappability of the forward and reverse strands in the bisulfite-converted genome.
+
+
+Bismap requires special handling of reverse complementation of C :math:`\rightarrow` T
+or G :math:`\rightarrow` A converted genomes.
+Conversion of C :math:`\rightarrow` T on the sequence AATTCCGG produces AATT **TT** GG.
+In the Bowtie index, the reverse complement would be CCAAAATT.
+However for the purpose of identifying the mappability of the bisulfite-converted genome,
+we expect the reverse complement to be TTGGAA **TT**. The reason is that both forward and reverse
+strands undergo bisulfite treatment simultaneously. There is no DNA replication after bisulfite treatment.
+To handle this issue, Bismap creates its own reverse complemented chromosomes and suppresses Bowtie's usual reverse complement mapping.
+
+Umap and Bismap each take approximately 200 CPU hours to run for a given read length. This can be parallelized in a computing cluster over 400 cores to take only 30 minutes.
+
+
+
+Measures of mappability
+:::::::::::::::::::::::
+
+Umap efficiently identifies the single-read mappability of any genome for a
+range of sequencing read lengths. The single-read mappability of a genomic
+region is a fraction of that region which overlaps with at least one uniquely
+mappable *k*-mer. The Bismap extension of Umap produces the single-read mappability
+of a bisulfite-converted genome. Both Umap and Bismap produce an integer vector for
+each chromosome that efficiently defines the mappability for any region and can be
+converted to a browser extensible data (BED) file. In addition to single-read mappability,
+we can measure the mappability of a genomic region by another approach. To quantify
+the single-read mappability of a given genomic region, we measure the fraction of
+potential uniquely mappable reads in that region. A region, however, can have 100% single-read
+mappability, but in practice require a high coverage sequencing to properly identify that region.
+For example, a 1 kbp region with 100% single-read mappability can be mappable due to a
+minimum of 10 unique 100-mers that none of them overlap or a maximum of 1100 unique 100-mers
+that highly overlap. Therefore, we define the multi-read mappability, the probability that a
+randomly selected read of length k in a given region is uniquely mappable. For the genomic
+region :math:`G_{i:j}` starting at *i* and ending at *j*, there are :math:`j - i + k + 1`
+*k*-mers that overlap with :math:`G_{i:j}`.
+The multi-read mappability of :math:`G_{i:j}` is the fraction of those *k*-mers that are uniquely mappable.
+
+
+
+Quick start
+-----------
+
+We have tested Umap installation on a CentOS system using python 2.7.11.
+Bismap requires numpy and pandas and it uses other python modules such as:
+
+* gzip
+* os
+* re
+* subprocess
+
+Umap uses mercurial version control. Make sure that mercurial (hg) is installed.
+Download Umap to the directory of your python packages using::
+
+ hg clone https://bitbucket.org/hoffmanlab/umap
+ cd umap
+ python setup.py install
+
+
+Now we will run a test using a wrapper in the umap directory called ubismap.py
+and a toy genome stored under umap/data ::
+
+ cd umap
+ python ubismap.py data/genome.fa data/chrsize.tsv data/TestGenomeMappability all.q $BOWTIRDIR/bowtie-build --kmer 8 12 -write_script test_run.sh
+ sh test_run.sh
+
+The scripts that are produced by **ubismap.py** assume that you are using a Sun Grid Engine computing cluster.
+You can use parameters of this script to adjust it to your own system. You may need to manually edit this file
+because many of the SGE settings are very different than other computing clusters.
+However, all of the Umap modules accept *-job_id* which allows you to use the modules without a cluster or if
+your cluster does not support job arrays.
+
+Basically, the job array saves an environmental variable (defined by (*-var_id*) that Umap uses for paralellizing processes.
+You can run the modules in a for loop and set the *-job_id* manually.
+For example, in order to find *k*-mers of a genome with 10 million base pairs, the get_kmers
+and run_bowtie modules each need to be executed with -job_ids ranging between 1 to 10.
+
+Get *k*-mers
+------------
+
+.. module:: umap
+ :platform: Unix
+
+.. currentmodule:: umap
+.. autoclass:: GetKmers
+
+
+Run Bowtie
+----------
+
+.. currentmodule:: umap
+.. autoclass:: BowtieWrapper
+
+
+Merge bowtie outputs
+--------------------
+
+
+.. currentmodule:: umap
+.. autoclass:: UnifyBowtie
+
+
+Merge data of various *k*-mers
+------------------------------
+
+
+.. currentmodule:: umap
+.. autoclass:: CombineUmaps
+
+
+Convert numeric vectors to BED and Wiggle
+-----------------------------------------
+
+
+.. currentmodule:: umap
+.. autoclass:: Int8Handler
+.. method:: Int8Handler.write_beds
+.. method:: Int8Handler.write_as_wig
+
+Requesting Genomes
+------------------
+
+In case you need these data for other genomes and do not have access to a Sun Grid Engine computing cluster,
+we may accept to do this for you.
+Please contact the software maintainer by email and we will do our best to assist you as soon as possible.
+
+
+
+Contact, support and questions
+------------------------------
+
+For support of Umap, please user our `mailing list <https://groups.google.com/forum/#!forum/ubismap>`_.
+Specifically, if you want to report a bug or request a feature,
+please do so using
+the `Umap issue tracker <https://bitbucket.org/hoffmanlab/umap/issues>`_.
+We are interested in all comments on the package,
+and the ease of use of installation and documentation.
+
+
+Indices and tables
+==================
+
+* :ref:`genindex`
+* :ref:`modindex`
+* :ref:`search`
+
diff --git a/setup.py b/setup.py
new file mode 100644
index 0000000..f920709
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,37 @@
+from setuptools import setup
+
+
+DESCRIPTION = "Umap and Bismap: tools for genome " +\
+ "and methylome mappability"
+
+
+def readme():
+ with open('README.rst') as f:
+ return f.read()
+
+
+setup(name='umap',
+ version='1.0.0',
+ description=DESCRIPTION,
+ long_description=readme(),
+ classifiers=[
+ "Natural Language :: English",
+ "Topic :: Scientific/Engineering :: Bio-Informatics",
+ "Intended Audience :: Science/Research",
+ "Operating System :: Unix",
+ "Programming Language :: Python",
+ "Programming Language :: Python :: 2.7",
+ "License :: OSI Approved :: GNU General Public License v3 ",
+ "(GPLv3)"],
+ url='https://bitbucket.org/hoffmanlab/proj/bismap',
+ author="Mehran Karimzadeh, Carl Ernst, " +
+ "Anshul Kundaje, Michael M. Hoffman",
+ author_email='mehran.karimzadeh at uhnresearch.ca',
+ license='GPLv3',
+ packages=['umap'],
+ install_requires=[
+ "argparse",
+ "numpy",
+ "pandas"],
+ include_package_data=True,
+ zip_safe=False)
diff --git a/umap.egg-info/PKG-INFO b/umap.egg-info/PKG-INFO
new file mode 100644
index 0000000..7b46f19
--- /dev/null
+++ b/umap.egg-info/PKG-INFO
@@ -0,0 +1,259 @@
+Metadata-Version: 1.1
+Name: umap
+Version: 1.0.0
+Summary: Umap and Bismap: tools for genome and methylome mappability
+Home-page: https://bitbucket.org/hoffmanlab/proj/bismap
+Author: Mehran Karimzadeh, Carl Ernst, Anshul Kundaje, Michael M. Hoffman
+Author-email: mehran.karimzadeh at uhnresearch.ca
+License: GPLv3
+Description: .. image:: https://readthedocs.org/projects/umap/badge/?version=latest
+
+
+ Umap and Bismap: quantifying genome and methylome mappability
+ =============================================================
+
+
+ Introduction
+ ------------
+
+ **The free umap software package efficiently identifies uniquely mappable regions of any genome.
+ Its Bismap extension identifies mappability of the bisulfite converted genome (methylome).**
+
+ the mappability of a genome for a given read length *k*.
+ First, it generates all possible *k*-mers of the genome.
+ Second, it maps these unique *k*-mers to the genome with `Bowtie <http://bowtie-bio.sourceforge.net/index.shtml>`_ version 1.1.0.
+ Third, Umap marks the start position of each *k*-mer that aligns to only one region in the genome.
+ Umap repeats these steps for a range of different *k*-mers and stores the data of each chromosome
+ in a binary vector *X* with the same length as the chromosome's sequence.
+ For read length *k*, :math:`X_i = 1` means that the sequence starting at :math:`X_i` and ending
+ at :math:`X_{i+k}` is uniquely mappable on the forward strand.
+ Since we align to both strands of the genome, the reverse complement of this same sequence
+ starting at :math:`X_{i+k}` on the reverse strand is also uniquely mappable.
+ :math:`X_i = 0` means that the sequence starting at :math:`X_i` and ending at
+ :math:`X_{i+k}` can be mapped to at least two different regions in the genome.
+
+
+ Mappability of the bisulfite-converted genome
+ ---------------------------------------------
+
+ To identify the single-read mappability of a bisulfite-converted genome,
+ we create two altered genome sequences.
+ In the first sequence, we convert all cytosines to thymine (C :math:`\rightarrow` T).
+ In the other sequence we convert all guanines to adenine (G :math:`\rightarrow` A).
+ Our approach follows those of `Bismark <http://www.bioinformatics.babraham.ac.uk/projects/bismark/>`_
+ and `BWA-meth <https://github.com/brentp/bwa-meth>`_.
+ We convert the genome sequence this way because bisulfite
+ treatment converts un-methylated cytosine to uracil which is read as thymine.
+ Similarly the guanine that is base-pairing with the un-methylated cytosine in
+ reverse strand converts to adenine. However these two conversions never occur
+ at the same time on the same read. We identify the uniquely mappable regions
+ of these two genomes separately, and then combine the data to represent the
+ single-read mappability of the forward and reverse strands in the bisulfite-converted genome.
+
+
+ Bismap requires special handling of reverse complementation of C :math:`\rightarrow` T
+ or G :math:`\rightarrow` A converted genomes.
+ Conversion of C :math:`\rightarrow` T on the sequence AATTCCGG produces AATT **TT** GG.
+ In the Bowtie index, the reverse complement would be CCAAAATT.
+ However for the purpose of identifying the mappability of the bisulfite-converted genome,
+ we expect the reverse complement to be TTGGAA **TT**. The reason is that both forward and reverse
+ strands undergo bisulfite treatment simultaneously. There is no DNA replication after bisulfite treatment.
+ To handle this issue, Bismap creates its own reverse complemented chromosomes and suppresses Bowtie's usual reverse complement mapping.
+
+ Umap and Bismap each take approximately 200 CPU hours to run for a given read length. This can be parallelized in a computing cluster over 400 cores to take only 30 minutes.
+
+
+ Measures of mappability
+ :::::::::::::::::::::::
+
+ Umap efficiently identifies the single-read mappability of any genome for a
+ range of sequencing read lengths. The single-read mappability of a genomic
+ region is a fraction of that region which overlaps with at least one uniquely
+ mappable *k*-mer. The Bismap extension of Umap produces the single-read mappability
+ of a bisulfite-converted genome. Both Umap and Bismap produce an integer vector for
+ each chromosome that efficiently defines the mappability for any region and can be
+ converted to a browser extensible data (BED) file. In addition to single-read mappability,
+ we can measure the mappability of a genomic region by another approach. To quantify
+ the single-read mappability of a given genomic region, we measure the fraction of
+ potential uniquely mappable reads in that region. A region, however, can have 100% single-read
+ mappability, but in practice require a high coverage sequencing to properly identify that region.
+ For example, a 1 kbp region with 100% single-read mappability can be mappable due to a
+ minimum of 10 unique 100-mers that none of them overlap or a maximum of 1100 unique 100-mers
+ that highly overlap. Therefore, we define the multi-read mappability, the probability that a
+ randomly selected read of length k in a given region is uniquely mappable. For the genomic
+ region :math:`G_{i:j}` starting at *i* and ending at *j*, there are :math:`j - i + k + 1`
+ *k*-mers that overlap with :math:`G_{i:j}`.
+ The multi-read mappability of :math:`G_{i:j}` is the fraction of those *k*-mers that are uniquely mappable.
+
+
+
+ Quick start
+ -----------
+
+ We have tested Umap installation on a CentOS system using python 2.7.11.
+ Bismap requires numpy and pandas and it uses other python modules such as:
+
+ * gzip
+ * os
+ * re
+ * subprocess
+
+ Umap uses mercurial version control. Make sure that mercurial (hg) is installed.
+ Download Umap to the directory of your python packages using::
+
+ hg clone https://bitbucket.org/hoffmanlab/umap
+ cd umap
+ python setup.py install
+
+
+ Now we will run a test using a wrapper in the umap directory called ubismap.py
+ and a toy genome stored under umap/data ::
+
+ cd umap
+ python ubismap.py data/genome.fa data/chrsize.tsv data/TestGenomeMappability all.q $BOWTIRDIR/bowtie-build --kmer 8 12 -write_script test_run.sh
+ sh test_run.sh
+
+ The scripts that are produced by **ubismap.py** assume that you are using a Sun Grid Engine computing cluster.
+ You can use parameters of this script to adjust it to your own system. You may need to manually edit this file
+ because many of the SGE settings are very different than other computing clusters.
+ However, all of the Umap modules accept *-job_id* which allows you to use the modules without a cluster or if
+ your cluster does not support job arrays.
+
+ Basically, the job array saves an environmental variable (defined by (*-var_id*) that Umap uses for paralellizing processes.
+ You can run the modules in a for loop and set the *-job_id* manually.
+ For example, in order to find *k*-mers of a genome with 10 million base pairs, the get_kmers
+ and run_bowtie modules each need to be executed with -job_ids ranging between 1 to 10.
+
+
+ Get *k*-mers
+ ------------
+
+ .. module:: umap
+ :platform: Unix
+
+ .. currentmodule:: get_kmers
+ .. autoclass:: GetKmers
+
+
+ The first step of finding the mappability of the genome for a given read length,
+ is to create all of the possible sequences of the genome with the read length of interest.
+ GetKmers requires an index reference and an index ID to do this step for one chunk of
+ the genome at a time. The index ID can be specified by -job_id, or if GetKmers is
+ submitted as a job array, GetKmers will use the variable name set by -var_id to obtain
+ the environmental variable for the job array ID.
+
+
+
+ **Important: The chromosome names in the fasta file should not contain underscore.
+ Underscore is used in Bismap to differentiate reverse complement chromosomes.**
+
+
+ Run Bowtie
+ ----------
+
+ .. currentmodule:: run_bowtie
+ .. autoclass:: BowtieWrapper
+
+
+ When all of the possible *k*-mers of the genome are created, BowtieWrapper keeps record
+ of all of the k-mers that are unique. Similar to GetKmers, the parallel process relies on
+ an index reference, or -job_id.
+
+
+ Merge bowtie outputs
+ --------------------
+
+
+ .. currentmodule:: unify_bowtie
+ .. autoclass:: UnifyBowtie
+
+
+ For each *k*-mer file, there will be a bowtie file with information of unique *k*-mers.
+ For each chromosome, a binary vector with length of the chromosome will be created.
+ If a *k*-mer starting at a given position is unique, the value will be 1.
+
+
+ Merge data of various *k*-mers
+ ------------------------------
+
+
+ .. currentmodule:: combine_umaps
+ .. autoclass:: CombineUmaps
+
+ If the above steps are repeated for various *k*-mers, these data can be efficiently
+ stored in a numeric vector for each chromosome. For each position, the length of the smallest
+ *k*-mer that uniquely maps to that position is specified.
+
+
+ Convert numeric vectors to BED and Wiggle
+ -----------------------------------------
+
+
+ .. currentmodule:: uint8_to_bed
+ .. autoclass:: Int8Handler
+ .. method:: Int8Handler.write_beds
+ .. method:: Int8Handler.write_as_wig
+
+ To visualize binary and numeric vectors that are produced by Umap, you can use Int8Handler.
+
+
+ Special instructions for Bismap
+ -------------------------------
+
+ For Bismap, you must create the mappability of C :math:`\rightarrow` T
+ and G :math:`\rightarrow` A by specifying -Bismap, -C2T, and -G2A each time.
+ After creating these two mappability, for each genome you will have a
+ kmers/globalmap_k<min>tok<max> folder with normal and reverse complemented chromosome mappabilities.
+
+
+ The first step is to merge the mappability of normal and reverse complemented chromosomes for each
+ genome. This can be done through uint8_to_bed.py ::
+
+ python uint8_to_bed.py <MergedKmerDir> <OutDirC2T> <LabelForOutputFiles> -C2T -chrsize_path <ChromSizeFile> -WriteUnique
+ python uint8_to_bed.py <MergedKmerDir> <OutDirG2A> <LabelForOutputFiles> -G2A -chrsize_path <ChromSizeFile> -WriteUnique
+
+
+ When you have created the merged mappability of each chromosome once for C :math:`\rightarrow` T genome
+ and once for G :math:`\rightarrow` A genome, you should use combine_umaps.py and specify -kmer_dir_2 ::
+
+ qsub <...> -t 1-<NumberOfChromosomes> python combine_umaps.py <OutDirC2T> <ChromSizePath> -out_dir <OutDir> -kmer_dir_2 <OutDirG2A>
+
+
+ Requesting Genomes
+ ------------------
+
+ In case you need these data for other genomes and do not have access to a Sun Grid Engine computing cluster,
+ we may accept to do this for you.
+ Please contact the software maintainer by email and we will do our best to assist you as soon as possible.
+
+
+
+ Contact, support and questions
+ ------------------------------
+
+ For support of Umap, please user our `mailing list <https://groups.google.com/forum/#!forum/ubismap>`_.
+ Specifically, if you want to report a bug or request a feature,
+ please do so using
+ the `Umap issue tracker <https://bitbucket.org/hoffmanlab/umap/issues>`_.
+ We are interested in all comments on the package,
+ and the ease of use of installation and documentation.
+
+
+ Credits
+ -------
+
+
+ Umap was originally developed by Anshul Kundaje and was written in MATLAB.
+ The original repository is available `here <https://sites.google.com/site/anshulkundaje/projects/mappability>`_.
+ The version of Umap that is available in this repository, is a python reimplementation of the original Umap, and
+ is initially written by Mehran Karimzadeh.
+
+Platform: UNKNOWN
+Classifier: Natural Language :: English
+Classifier: Topic :: Scientific/Engineering :: Bio-Informatics
+Classifier: Intended Audience :: Science/Research
+Classifier: Operating System :: Unix
+Classifier: Programming Language :: Python
+Classifier: Programming Language :: Python :: 2.7
+Classifier: License :: OSI Approved :: GNU General Public License v3
+Classifier: (GPLv3)
diff --git a/umap.egg-info/SOURCES.txt b/umap.egg-info/SOURCES.txt
new file mode 100644
index 0000000..6e5d2d6
--- /dev/null
+++ b/umap.egg-info/SOURCES.txt
@@ -0,0 +1,18 @@
+MANIFEST.in
+README.rst
+setup.py
+umap/__init__.py
+umap/combine_umaps.py
+umap/get_kmers.py
+umap/handle_fasta.py
+umap/map_bed.py
+umap/run_bowtie.py
+umap/ubismap.py
+umap/uint8_to_bed.py
+umap/unify_bowtie.py
+umap.egg-info/PKG-INFO
+umap.egg-info/SOURCES.txt
+umap.egg-info/dependency_links.txt
+umap.egg-info/not-zip-safe
+umap.egg-info/requires.txt
+umap.egg-info/top_level.txt
\ No newline at end of file
diff --git a/umap.egg-info/dependency_links.txt b/umap.egg-info/dependency_links.txt
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/umap.egg-info/dependency_links.txt
@@ -0,0 +1 @@
+
diff --git a/umap.egg-info/not-zip-safe b/umap.egg-info/not-zip-safe
new file mode 100644
index 0000000..8b13789
--- /dev/null
+++ b/umap.egg-info/not-zip-safe
@@ -0,0 +1 @@
+
diff --git a/umap.egg-info/requires.txt b/umap.egg-info/requires.txt
new file mode 100644
index 0000000..fb28f93
--- /dev/null
+++ b/umap.egg-info/requires.txt
@@ -0,0 +1,3 @@
+argparse
+numpy
+pandas
\ No newline at end of file
diff --git a/umap.egg-info/top_level.txt b/umap.egg-info/top_level.txt
new file mode 100644
index 0000000..a64745f
--- /dev/null
+++ b/umap.egg-info/top_level.txt
@@ -0,0 +1 @@
+umap
diff --git a/umap/__init__.py b/umap/__init__.py
new file mode 100644
index 0000000..a2ef449
--- /dev/null
+++ b/umap/__init__.py
@@ -0,0 +1,6 @@
+from get_kmers import GetKmers
+from run_bowtie import BowtieWrapper
+from unify_bowtie import UnifyBowtie
+from combine_umaps import CombineUmaps
+from uint8_to_bed import Int8Handler
+import map_bed
diff --git a/umap/combine_umaps.py b/umap/combine_umaps.py
new file mode 100644
index 0000000..37a4caf
--- /dev/null
+++ b/umap/combine_umaps.py
@@ -0,0 +1,183 @@
+from argparse import ArgumentParser
+import gzip
+import numpy as np
+import os
+
+
+def get_args():
+ parser = ArgumentParser(
+ description="Combines mappability uint8 vectors of "
+ "several kmers into 1 uint8 vector per chromosome. "
+ "It requires a directory with subfolders names as "
+ "k<read length>. This script requires a number to infer "
+ "chromosome. If not specifying -job_id, it will "
+ "identify the chromosome using -var_id environmental "
+ "varibale which by default is SGE_TASK_ID.")
+ parser.add_argument(
+ "kmer_dir",
+ help="Directory with subfolders "
+ "named as k<read length>)")
+ parser.add_argument(
+ "chrsize_path",
+ help="Path to 2 column tsv file with first column "
+ "as chromosome and second column as its size. Will "
+ "be used to identify order of the chromosomes.")
+ parser.add_argument(
+ "-out_dir",
+ default="infer",
+ help="If not specified, a subfolder "
+ "will be created in kmer_dir names as "
+ "globalmap_k<smallestkmer>tok<largestkmer>")
+ parser.add_argument(
+ "-job_id",
+ default=0,
+ type=int,
+ help="1-based index for finding chromosome from -chrsize_path. "
+ "If not specified, it will user -var_id to "
+ "infer the chromosome for combining mappabilitiy of "
+ "different kmers.")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="If -job_id is not specified, job_id will be inferred "
+ "from environmental variable -var_id.")
+ parser.add_argument(
+ "-kmer_dir_2",
+ default="NA",
+ help="Specify to merge kmers of two different directories "
+ "by logical operation AND.")
+ args = parser.parse_args()
+ job_id = args.job_id
+ out_dir = args.out_dir
+ kmers = [each_kmer for each_kmer in next(os.walk(args.kmer_dir))[1]
+ if "k" == each_kmer[0]]
+ if len(kmers) < 1:
+ raise ValueError("{} lacks kmer folders".format(args.kmer_dir))
+ if args.job_id == 0:
+ job_id = int(os.environ[args.var_id]) - 1
+ else:
+ job_id = job_id - 1
+ if args.out_dir == "infer":
+ kmer_ints = [int(each_kmer.replace("k", "")) for each_kmer in kmers]
+ out_dir = "{}/globalmap_k{}tok{}".format(
+ args.kmer_dir, min(kmer_ints), max(kmer_ints))
+ try:
+ out_list = [args.kmer_dir, args.chrsize_path,
+ out_dir, job_id, args.kmer_dir_2]
+ except:
+ raise ValueError(
+ "chrsize_path or job_id were invalid.")
+ if not os.path.exists(out_dir):
+ os.makedirs(out_dir)
+ return out_list
+
+
+class CombineUmaps:
+ def __init__(self, kmer_dir, chrsize_path,
+ out_dir, job_id, kmer_dir_2):
+ """Combine <chr>.<kmer>.uint8.unique.gz files
+
+ The kmer_dir has subfolders named as k<integer> with
+ <chr>.<kmer>.uint8.unique.gz files inside. This script
+ will use the job_id to use a particular chromosome and
+ merge the uint8.gz files across all of the different
+ kmers into one uint8.gz. Note: All methods would
+ run consequently when creating the class instance.
+
+ Args:
+ kmer_dir: Directory with k<integer> subfolders
+ chrsize_path: 2-column tsv file of <chrom>\t<size>\n...
+ out_dir: Output files will be saved to this folder
+ job_id: 0-based index to find chromosome from chrsize_path
+ kmer_dir_2: If using Bismap and want to merge C2T and G2A data
+
+ Returns
+ Saves the output to outdir/<chrom>.uint8.unique.gz files
+ """
+ self.kmer_dir = kmer_dir
+ self.kmer_dir_2 = kmer_dir_2
+ self.chrsize_path = chrsize_path
+ self.out_dir = out_dir
+ self.job_id = job_id
+ self.chrom, self.size = self.get_chrom_size()
+ self.kmers = [each_kmer for each_kmer in
+ next(os.walk(self.kmer_dir))[1]
+ if "k" == each_kmer[0]]
+ combined_ar = self.combine_uints()
+ self.write_ar(combined_ar)
+
+ def get_chrom_size(self):
+ """Finds chrom and size from self.chrsize_path"""
+ with open(self.chrsize_path, "r") as chrsize_link:
+ ind_chr = 0
+ for chrsize_line in chrsize_link:
+ if ind_chr == self.job_id:
+ chromosome = chrsize_line.rstrip().split("\t")[0]
+ size = int(chrsize_line.rstrip().split("\t")[1])
+ ind_chr = ind_chr + 1
+ return chromosome, size
+
+ def combine_uints(self):
+ """Merged different kmer arrays of one chromosome
+ """
+ MergeKmers = False
+ if os.path.exists(self.kmer_dir_2):
+ print(
+ "Limit mappability to regions {} {} and {}".format(
+ "that are unique in both",
+ kmer_dir, kmer_dir_2))
+ MergeKmers = True
+ combined_ar = np.zeros(self.size, dtype=np.uint8)
+ kmer_nums = [int(kmer.replace("k", "")) for kmer in self.kmers]
+ kmer_nums.sort()
+ for kmer_num in kmer_nums:
+ kmer = "k{}".format(kmer_num)
+ full_kmer_path = "{}/{}/{}.{}.uint8.unique.gz".format(
+ self.kmer_dir, kmer, self.chrom, kmer)
+ if not os.path.exists(full_kmer_path):
+ raise ValueError("{} does not exist".format(full_kmer_path))
+ kmer_link = gzip.open(full_kmer_path, "rb")
+ kmer_ar = np.frombuffer(kmer_link.read(), dtype=np.uint8)
+ if len(kmer_ar) != self.size:
+ kmer_ar = np.append(kmer_ar, np.zeros(kmer_num))
+ kmer_link.close()
+ index_comb_0 = combined_ar == 0
+ index_kmer = kmer_ar != 0
+ index_adkmer = np.logical_and(index_comb_0, index_kmer)
+ if MergeKmers:
+ full_kmer_path_2 = "{}/{}/{}.{}.uint8.unique.gz".format(
+ self.kmer_dir_2, kmer, self.chrom, kmer)
+ kmer_link_2 = gzip.open(full_kmer_path_2, "rb")
+ kmer_ar_2 = np.frombuffer(kmer_link_2.read(), dtype=np.uint8)
+ if len(kmer_ar_2) != self.size:
+ kmer_ar_2 = np.append(kmer_ar_2, np.zeros(kmer_num))
+ kmer_link_2.close()
+ index_kmer_2 = kmer_ar_2 != 0
+ index_adkmer_2 = np.logical_and(index_comb_0, index_kmer_2)
+ index_adkmer = np.logical_and(index_adkmer, index_adkmer_2)
+ combined_ar[index_adkmer] = kmer_num
+ print(
+ "Added information of {} for {}".format(
+ kmer, self.chrom))
+ return combined_ar
+
+ def write_ar(self, combined_ar):
+ """Writes merged array to unsigned 8bit integer file.
+
+ Used self.out_dir and self.chrom.
+
+ Args:
+ combined_ar: Can be any numpy array
+ """
+ if not os.path.exists(self.out_dir):
+ os.makedirs(self.out_dir)
+ out_path = "{}/{}.uint8.unique.gz".format(
+ self.out_dir, self.chrom)
+ out_link = gzip.open(out_path, "wb")
+ out_link.write(combined_ar.tobytes())
+ out_link.close()
+
+
+if __name__ == "__main__":
+ kmer_dir, chrsize_path, out_dir, job_id, kmer_dir_2 = get_args()
+ CombineUmaps(kmer_dir, chrsize_path, out_dir, job_id, kmer_dir_2)
diff --git a/umap/data/chrsize.tsv b/umap/data/chrsize.tsv
new file mode 100644
index 0000000..3ec4542
--- /dev/null
+++ b/umap/data/chrsize.tsv
@@ -0,0 +1,2 @@
+chr1 60
+chr2 90
diff --git a/umap/data/genome.fa b/umap/data/genome.fa
new file mode 100644
index 0000000..bed0476
--- /dev/null
+++ b/umap/data/genome.fa
@@ -0,0 +1,7 @@
+>chr1
+AAAAATTTTTCCCCCGGGGGATCGAATCGA
+ATCGAATCGAATCGAATCGAATCGAATCGA
+>chr2
+AAAAAAAAAATTTTTTTTTTCCCCCCCCCC
+GGGGGGGGGGAAAAAAAATTTTTTTTGGGG
+CCCCCCCCCCCCCCCCCCCCCCCCCCCCCC
diff --git a/umap/get_kmers.py b/umap/get_kmers.py
new file mode 100644
index 0000000..a4fb0d4
--- /dev/null
+++ b/umap/get_kmers.py
@@ -0,0 +1,265 @@
+from argparse import ArgumentParser
+import gzip
+import numpy as np
+import os
+import pandas as pd
+
+
+def get_args():
+ parser = ArgumentParser(
+ description="Creates list of unique Kmers "
+ "for each 1Mb of the genome. Relies on an environmental "
+ "variable such as SGE_TASK_ID to identify the correct "
+ "megabase of the genome for this purpose. "
+ "If not using job arrays, specify -job_id manually.")
+ parser.add_argument(
+ "chromsize_path",
+ help="Path to 2 column tsv file where first column is "
+ "chromosome name and second column is chromosome size")
+ parser.add_argument(
+ "out_dir",
+ help="Path to the directory for creating "
+ "<chromosome>.<Megabase>.<kmer>.kmer.gz files")
+ parser.add_argument(
+ "chr_dir",
+ help="Path to directory with <chromosome>.fasta files.")
+ parser.add_argument(
+ "idx_path",
+ help="Path to the 4 column file with the following columns: "
+ "Index | Chromosome | Start | End. This file will be used "
+ "for identifying the chunk of the chromosome.")
+ parser.add_argument(
+ "--kmer",
+ default="infer",
+ help="The software would infer it based on the "
+ "name of the 'out_dir'. If it is set and "
+ "contradicts the 'out_dir', a subfolder "
+ "under out_dir will be created named 'kmer' and "
+ "out_dir will be changed to that.")
+ parser.add_argument(
+ "--job_id",
+ default=0,
+ type=int,
+ help="If not submitted in job array, would require this "
+ "parameter to be set. (1-based index)")
+ parser.add_argument(
+ "--var_id",
+ default="SGE_TASK_ID",
+ help="The variable name that the script would use "
+ "for identifying the job id. By default: SGE_TASK_ID.")
+ args = parser.parse_args()
+ out_dir = args.out_dir
+ inferred_kmer = args.out_dir.split("/")[-1]
+ kmer = args.kmer
+ job_id = args.job_id
+ if args.kmer == "infer":
+ kmer = inferred_kmer
+ elif args.kmer != inferred_kmer:
+ kmer = args.kmer
+ out_dir = "{}/{}".format(out_dir, kmer)
+ if job_id == 0:
+ job_id = int(os.environ[args.var_id]) - 1
+ out_list = [args.chromsize_path, out_dir,
+ kmer, job_id, args.chr_dir,
+ args.idx_path]
+ return out_list
+
+
+class GetKmers:
+ def __init__(self, out_dir, kmer, job_id,
+ chr_dir, chromsize_path, idx_path):
+ """Creates all the possible k-mers for part of the genome.
+
+ Used a referece file to find the appropriate chromosome,
+ start and end position. Passes through the fasta file
+ of the chromosome and generates all of the possible k-mers.
+
+ Args:
+ :param out_dir: Directory for saving <chrom>.<jobid>.kmer.gz files
+ :param str kmer: k-mer string such as 'k24'
+ :param int job_id: Reference ID used for finding chrom, start and end
+ :param chr_dir: Path to directory with chromosome fasta files
+ :param chromsize_path: Path to 2 column file of chrom\tsize\n
+ :param idx_path: Path to 4 column file of index\tchrom\t\st\tend\n
+
+ :returns: An object with methods such as get_step_fasta(),
+ get_seq_ar(), write_kmers() and write_regions().
+
+ :raises ValueError: if expected chromosome path does not exist
+ """
+ self.out_dir = out_dir
+ self.kmer = kmer
+ self.job_id = job_id
+ self.chromsize_path = chromsize_path
+ self.chr_dir = chr_dir
+ self.idx_path = idx_path
+ self.chrom, self.start, self.end = self.get_region()
+ self.chrom_path = "{}/{}.fasta".format(
+ self.chr_dir, self.chrom)
+ if not os.path.exists(self.chrom_path):
+ raise ValueError(
+ "{} does not exist".format(self.chrom_path))
+ elif not os.path.exists(self.idx_path):
+ raise ValueError(
+ "{} does not exist".format(self.idx_path))
+
+ def get_region(self):
+ """Find chromosomal chunk
+
+ Using job_id and chromsize_path, finds chromosome,
+ start and end. Looks if chrsize_index.tsv exists.
+ If it doesn't, it will create chrsize_index.tsv.
+ Otherwise will use it for finding that information.
+
+ :returns: chrom, start, end
+
+ :raises ValueError: If job_id is out of expected range
+ """
+ job_id = self.job_id
+ idx_path = self.idx_path
+ idx_df = pd.read_csv(idx_path, sep="\t", index_col=0)
+ dict_idx = idx_df.to_dict()
+ try:
+ chrom, start, end = [
+ dict_idx[each_line][job_id] for
+ each_line in ["Chromosome", "Start", "End"]]
+ except:
+ raise ValueError(
+ "{} Job id is larger than available indices".format(
+ job_id))
+ return chrom, int(start), int(end)
+
+ def get_step_fasta(self):
+ """Finds number of nucleotides at each line of FASTA
+
+
+ :raises ValueError: If top 10 FASTA lines have
+ sequences of varying length
+ """
+ chrom_path = self.chrom_path
+ line_nums = 10
+ len_lines = []
+ with open(chrom_path, "r") as chr_link:
+ for line_num in range(line_nums):
+ chr_line = chr_link.readline().rstrip()
+ if ">" not in chr_line:
+ len_line = len(chr_line)
+ if len_line not in len_lines:
+ if chr_line != "":
+ len_lines.append(len_line)
+ if len(len_lines) == 1:
+ return(len_lines[0])
+ else:
+ raise ValueError(
+ "Top 10 FASTA lines have sequences of varying length")
+
+ def get_seq_ar(self, fasta_fix):
+ """Gets sequence as numpy array
+
+ get_seq_ar creates a numpy array matching sequence
+ of the region specified by chromosome, start and
+ end. However it starts the sequence with kmer - 1
+ less than the specified start to account for the
+ missing kmers from the previous chunk of chromosome.
+ Each element is one line of a fasta file that may be
+ cut to match the exact start/end positions.
+
+ Args:
+ :param int fasta_fix: Number of nucleotides per fasta line.
+
+ :returns: Numpy array with each member being one line of FASTA
+ """
+ start = self.start
+ end, chrom_path = self.end, self.chrom_path
+ kmer = int(self.kmer.replace("k", ""))
+ start = start - kmer
+ if start < 0:
+ start = 0
+ st_line = int(np.floor(start / fasta_fix))
+ st_line_pos = start % fasta_fix
+ end_line = int(np.floor(end / fasta_fix))
+ end_line_pos = (end % fasta_fix) + 1
+ seq_ar = np.empty(int(end_line - st_line + 1),
+ dtype="|S{}".format(fasta_fix + 1))
+ ind_seq = 0
+ STORE_LINE = False
+ with open(chrom_path, "r") as chr_link:
+ line_ind = 0
+ for each_line in chr_link:
+ if line_ind == st_line:
+ STORE_LINE = True
+ each_line = each_line.rstrip()[st_line_pos:]
+ if STORE_LINE:
+ if line_ind == end_line:
+ STORE_LINE = False
+ each_line = each_line.rstrip()[:end_line_pos]
+ seq_ar[ind_seq] = each_line.rstrip()
+ ind_seq = ind_seq + 1
+ line_ind = line_ind + 1
+ if "chr" in seq_ar[0]:
+ seq_ar = seq_ar[1:]
+ return seq_ar
+
+ def write_kmers(self, cur_seq, kmer_int, out_link):
+ """Creates k-mers and saves them to the file
+
+ Using a numpy array of sequences, generates and
+ saves all of the possible k-mers.
+
+ Args:
+ :param cur_seq: A string of sequences
+ :param kmer_int: An integer denoting the k-mer size
+ :param out_link: File link for writing k-mers
+
+ :returns: May modify cur_seq by deducing the k-mers that
+ are written to the out_link file object.
+ """
+ if len(cur_seq) < kmer_int:
+ return cur_seq
+ elif len(cur_seq) == kmer_int:
+ out_link.write(cur_seq + "\n")
+ cur_seq = cur_seq[1:]
+ return cur_seq
+ else:
+ for i in range(len(cur_seq) - kmer_int):
+ j = i + kmer_int
+ if j > len(cur_seq):
+ j = len(cur_seq)
+ seq_out = cur_seq[i:j]
+ if "N" not in seq_out:
+ out_link.write(seq_out + "\n")
+ cur_seq = cur_seq[(i + 1):]
+ return cur_seq
+
+ def write_region(self):
+ """Wrapper of GetKmers to get and write k-mers
+
+ write_region method executes all the other methods
+ of the GetKmers class for writing out all of the
+ possible k-mers from chunk of a FASTA file.
+ """
+ out_dir, kmer, job_id = self.out_dir, self.kmer, self.job_id
+ chrom = self.chrom
+ start, end = self.start, self.end
+ out_path = "{}/{}.{}.{}.kmer.gz".format(
+ out_dir, chrom, job_id, kmer.replace("k", ""))
+ out_link = gzip.open(out_path, "wb")
+ fasta_fix = self.get_step_fasta()
+ kmer_int = int(kmer.replace("k", ""))
+ seq_ar = self.get_seq_ar(fasta_fix)
+ cur_seq = ""
+ for each_seq in seq_ar:
+ cur_seq = cur_seq + each_seq
+ cur_seq = self.write_kmers(cur_seq, kmer_int, out_link)
+ print("Created all sequences for {}:{}-{}".format(
+ chrom, start, end))
+ out_link.close()
+
+
+if __name__ == "__main__":
+ chromsize_path, out_dir, kmer, job_id, chr_dir, idx_path = get_args()
+ GetKmerObj = GetKmers(
+ out_dir, kmer, job_id,
+ chr_dir, chromsize_path,
+ idx_path)
+ GetKmerObj.write_region()
diff --git a/umap/handle_fasta.py b/umap/handle_fasta.py
new file mode 100644
index 0000000..e1b8288
--- /dev/null
+++ b/umap/handle_fasta.py
@@ -0,0 +1,181 @@
+from argparse import ArgumentParser
+from datetime import datetime
+import numpy as np
+import os
+from subprocess import call
+
+
+class FastaHandler:
+ def __init__(self, in_path, out_path, chrsize_path,
+ chr_dir, complement=True, conversion="None"):
+ """Reverse complement the genome for Bismap
+
+ This class generates the necessary FASTA files
+ for running Umap or Bismap. If using Bismap,
+ a reverse complemented set of chromosomes for
+ the specified conversion will be produced.
+
+ :param in_path: Path to genome .fasta file
+ :param out_path: Path to output .fasta file
+ :param chrsize_path: Path to 2-column chrom\tsize\n file
+ :param chr_dir: Path to directory for
+ writing chromosome fasta files
+ :param complement: If reverse complemented chromosomes
+ must be created
+ :param conversion: One of 'None', 'C2T' or 'G2A'
+ """
+ self.in_path = in_path
+ self.out_path = out_path
+ self.chrsize_path = chrsize_path
+ self.chr_dir = chr_dir
+ self.complement = complement
+ self.conversion = conversion
+
+ def handle_fasta(self):
+ """Wrapper function of FastaHandler
+
+ Writes individual fasta files for each chromosome
+ and converts nucleotides or reverse complements
+ sequences if necessary (for Bismap feature)
+ """
+ chrsize_dict = self.get_chrsize_dict()
+ print("Reverse complementation: {}".format(self.complement))
+ print("Nucleotide conversion: {}".format(self.conversion))
+ if not os.path.exists(self.chr_dir):
+ os.makedirs(self.chr_dir)
+ chr_path = self.chr_dir + "/chr1.fasta"
+ chr_link = open(chr_path, "w")
+ if self.complement:
+ chr_path_rc = chr_path.replace(".fasta", "_RC.fasta")
+ chr_link_rc = open(chr_path_rc, "w")
+ out_link_rc = open(self.out_path.replace(
+ ".fasta", "_RC.fasta"), "w")
+ out_link = open(self.out_path, "w")
+ ad_fin = ""
+ chr_len = 0
+ if self.complement:
+ complement_ar = np.zeros(10)
+ with open(self.in_path, "r") as fas_link:
+ for each_line in fas_link:
+ ad_line = each_line.rstrip()
+ if ">chr" in ad_line:
+ if " " in ad_line:
+ ad_line = ad_line.split(" ")[0]
+ if "\t" in ad_line:
+ ad_line = ad_line.split("\t")[0]
+ chr_link.close()
+ print ad_fin
+ chrom = ad_line[1:]
+ chr_path = "{}/{}.fasta".format(
+ self.chr_dir, chrom)
+ chr_link = open(chr_path, "w")
+ if self.complement:
+ if complement_ar[0] != 0:
+ self.write_reverse(complement_ar, chr_link_rc,
+ out_link_rc, chr_len, chrom)
+ chr_len = chrsize_dict[chrom]
+ complement_ar = np.empty((chr_len), dtype="|S8")
+ start = 0
+ ad_line_rc = ad_line + "_RC"
+ chr_link_rc.close()
+ chr_link_rc = open(
+ chr_path.replace(".fasta", "_RC.fasta"), "w")
+ out_link_rc.write(ad_line_rc + "\n")
+ chr_link_rc.write(ad_line_rc + "\n")
+ print "%s started at %s" % (ad_line, str(datetime.now()))
+ else:
+ ad_line = ad_line.upper()
+ if self.complement:
+ ad_line_rc = ad_line.replace("A", "1")
+ ad_line_rc = ad_line_rc.replace("T", "A")
+ ad_line_rc = ad_line_rc.replace("C", "2")
+ ad_line_rc = ad_line_rc.replace("G", "C")
+ ad_line_rc = ad_line_rc.replace("1", "T")
+ ad_line_rc = ad_line_rc.replace("2", "G")
+ # ad_line_rc = ad_line_rc[::-1]
+ if self.conversion == "C2T":
+ ad_line = ad_line.replace("C", "T")
+ ad_line_rc = ad_line_rc.replace("C", "T")
+ elif self.conversion == "G2A":
+ ad_line = ad_line.replace("G", "A")
+ ad_line_rc = ad_line_rc.replace("G", "A")
+ ad_fin = ad_line + "\n"
+ out_link.write(ad_fin)
+ chr_link.write(ad_fin)
+ if self.complement:
+ ad_fin_rc = ad_line_rc + "\n"
+ if "chr" not in ad_fin_rc:
+ end_pos = start + len(ad_line_rc)
+ try:
+ complement_ar[start:end_pos] = list(ad_line_rc)
+ except:
+ print(
+ "{} to {} with length of {}".format(
+ start, end_pos,
+ len(range(start, end_pos))))
+ print(ad_line_rc)
+ raise ValueError("Failed to add sequences")
+ start = start + len(ad_line_rc)
+ out_link.close()
+ chr_link.close()
+ if self.complement:
+ self.write_reverse(complement_ar, chr_link_rc,
+ out_link_rc, chr_len, chrom)
+ out_link_rc.close()
+ chr_link_rc.close()
+ call(" ".join(["cat", self.out_path.replace(".fasta", "_RC.fasta"),
+ ">>", self.out_path]), shell=True)
+ call(["mv", self.out_path.replace(".fasta", "_RC.fasta"),
+ self.out_path.replace(".fasta", "_Deprecated_RC.fasta")])
+
+ def write_reverse(complement_ar, chr_link_rc,
+ out_link_rc, chr_len, chrom):
+ complement_ar = complement_ar[::-1]
+ print("Length of {} was {}".format(chrom, chr_len))
+ for start in range(0, chr_len, 50):
+ end = start + 50
+ if end > chr_len:
+ end = chr_len
+ ad_seq = "".join(complement_ar[start:end])
+ out_link_rc.write(ad_seq + "\n")
+ chr_link_rc.write(ad_seq + "\n")
+
+ def get_chrsize_dict(self):
+ chrsize_dict = {}
+ with open(self.chrsize_path, "r") as chrsize_link:
+ for chrsize_line in chrsize_link:
+ chrom, size = chrsize_line.rstrip().split("\t")
+ chrsize_dict[chrom] = int(size)
+ return chrsize_dict
+
+
+if __name__ == "__main__":
+ parser = ArgumentParser(
+ description="Reverse complements a fasta genome")
+ parser.add_argument(
+ "in_fasta",
+ help="FASTA format genome")
+ parser.add_argument(
+ "out_fasta",
+ help="Output FASTA full path")
+ parser.add_argument(
+ "chrsize_path",
+ help="Path to 2 column file with first column "
+ "being the chromosome name and the second "
+ "column being the chromosome size")
+ parser.add_argument(
+ "chr_dir",
+ help="Path to directory for writing individual "
+ "fasta files for each chromosome")
+ parser.add_argument(
+ "--Complement",
+ action="store_true",
+ help="Create a double genome with both "
+ "+ and - strand information")
+ parser.add_argument(
+ "-Conversion",
+ help="Specify C2T or G2A")
+ args = parser.parse_args()
+ FastaObj = FastaHandler(args.in_fasta, args.out_fasta, args.chrsize_path,
+ args.chr_dir, args.Complement, args.Conversion)
+ FastaObj.handle_fasta()
diff --git a/umap/hg19_august.sh b/umap/hg19_august.sh
new file mode 100644
index 0000000..3d8af42
--- /dev/null
+++ b/umap/hg19_august.sh
@@ -0,0 +1,156 @@
+# Bismap/Umap job submission commands follow.
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.UniqueKmers -terse -tc 120 -hold_jid 1 -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.ERR python get_kmers.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/chrsize.tsv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/km [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.RunBowtie -terse -tc 120 -hold_jid 1,$WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.ERR python run_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k24 /mnt/work1/software/bowtie/1.1.0 /mnt/work1/users/hoffmangroup/mkarimzadeh/ [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-24:1 -N Bismap.UnifyBowtie -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.ERR python unify_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k24 /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/ [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k24/*kmer* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k24/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k24/*bowtie* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k24/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.UniqueKmers -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.ERR python get_kmers.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/chrsize.tsv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/h [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.RunBowtie -terse -tc 120 -hold_jid 1,$WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.ERR python run_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k36 /mnt/work1/software/bowtie/1.1.0 /mnt/work1/users/hoffmangroup/mkarimzadeh/ [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-24:1 -N Bismap.UnifyBowtie -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.ERR python unify_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k36 /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/ [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k36/*kmer* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k36/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k36/*bowtie* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k36/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.UniqueKmers -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.ERR python get_kmers.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/chrsize.tsv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/h [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.RunBowtie -terse -tc 120 -hold_jid 1,$WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.ERR python run_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k50 /mnt/work1/software/bowtie/1.1.0 /mnt/work1/users/hoffmangroup/mkarimzadeh/ [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-24:1 -N Bismap.UnifyBowtie -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.ERR python unify_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k50 /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/ [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k50/*kmer* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k50/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k50/*bowtie* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k50/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.UniqueKmers -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.ERR python get_kmers.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/chrsize.tsv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/h [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.RunBowtie -terse -tc 120 -hold_jid 1,$WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.ERR python run_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k76 /mnt/work1/software/bowtie/1.1.0 /mnt/work1/users/hoffmangroup/mkarimzadeh/ [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-24:1 -N Bismap.UnifyBowtie -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.ERR python unify_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k76 /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/ [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k76/*kmer* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k76/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k76/*bowtie* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k76/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.UniqueKmers -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.ERR python get_kmers.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/chrsize.tsv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/h [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.RunBowtie -terse -tc 120 -hold_jid 1,$WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.ERR python run_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k100 /mnt/work1/software/bowtie/1.1.0 /mnt/work1/users/hoffmangroup/mkarimzadeh [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-24:1 -N Bismap.UnifyBowtie -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.ERR python unify_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k100 /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k100/*kmer* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k100/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k100/*bowtie* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k100/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.UniqueKmers -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UniqueKmers.ERR python get_kmers.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/chrsize.tsv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/h [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-3114 -N Bismap.RunBowtie -terse -tc 120 -hold_jid 1,$WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.RunBowtie.ERR python run_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k152 /mnt/work1/software/bowtie/1.1.0 /mnt/work1/users/hoffmangroup/mkarimzadeh [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -t 1-24:1 -N Bismap.UnifyBowtie -terse -tc 120 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.UnifyBowtie.ERR python unify_bowtie.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k152 /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k152/*kmer* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k152/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N Moving.Intermediary.Files -hold_jid $WAITID -terse -cwd -b y -o Bismap.FileMov.LOG -e Bismap.FileMov.ERR mv /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k152/*bowtie* /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/k152/TEMPs)
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
+
+JOBID=$(qsub -q hoffmangroup -N CombineUmappedFiles -terse -t 1-24 -hold_jid $WAITID -cwd -b y -o /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.combine.LOG -e /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers/Bismap.combine.ERR python combine_umaps.py /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/kmers /mnt/work1/users/hoffmangroup/mkarimzadeh/2016/mappability/data/Umap/hg19/chrsize.tsv -va [...]
+IDPARTS=($(echo $JOBID | tr "." "\n"))
+WAITID=${IDPARTS[0]}
+echo "Submitted JOB ID $WAITID"
diff --git a/umap/map_bed.py b/umap/map_bed.py
new file mode 100644
index 0000000..23e5dc1
--- /dev/null
+++ b/umap/map_bed.py
@@ -0,0 +1,262 @@
+from argparse import ArgumentParser
+import gzip
+import numpy as np
+import os
+import pandas as pd
+import re
+
+
+def get_args():
+ parser = ArgumentParser(
+ description="This script expects an input "
+ "gzipped BED file, a directory with umap/bismap "
+ "produced files names as <chr>.uint8."
+ "unique.gz. It will add one column to the bed "
+ "file which would determine the fraction of "
+ "uniquely mappable reads that passover this "
+ "region. The first column added to input is "
+ "single-read mappability, which is the percent "
+ "of the region that is uniquely mappable. "
+ "The second added column is the multi-read"
+ " mappability; the probability that a randonly "
+ "selected read overlapping with that region "
+ "is uniquely mappable. If the input BED file "
+ "has 1 bp intervals, you can specify -SingleNucleotide "
+ "and -wigdir to use a faster algorithm.")
+ parser.add_argument(
+ "bed_path",
+ help="Path to gzipped bed file")
+ parser.add_argument(
+ "out_path",
+ help="Path to gzipped output file")
+ parser.add_argument(
+ "umap_dir",
+ help="Path to directory with uint8 binary "
+ "files produced by Umap/Bismap.")
+ parser.add_argument(
+ "kmer",
+ type=int,
+ help="The read length for defining single-read "
+ "and multi-read mappability.")
+ parser.add_argument(
+ "-SingleNucleotide",
+ action="store_true",
+ help="If specified, assumes each region is only one "
+ "nucleotide. You must specify -wig as well.")
+ parser.add_argument(
+ "-wigdir",
+ default="",
+ help="Path to directory with <kmer>_<chrom>."
+ "MultiTrackMappability.wg.gz files.")
+ args = parser.parse_args()
+ if args.SingleNucleotide:
+ if not os.path.exists(args.wigdir):
+ raise ValueError("-wigdir didn't exist!")
+ out_list = [args.bed_path, args.out_path,
+ args.umap_dir, args.kmer,
+ args.wigdir]
+ return out_list
+
+
+def load_wig(wig_path, chrom_size):
+ '''
+ Translated a fixed step wig file of a chromosome
+ with step size 1 to a numpy array.
+ Will be used internally by BedMappability.
+ Unexpected behaviour if wig file has multiple
+ chromosomes.
+ '''
+ wig_ar = np.zeros(chrom_size, dtype=float)
+ pos = 0
+ with gzip.open(wig_path, "rb") as wig_link:
+ for wig_line in wig_link:
+ if "start" in wig_line:
+ pos_str = wig_line.rstrip().split(" ")[2]
+ pos = int(pos_str.replace("start=", "")) - 1
+ else:
+ value = float(wig_line.rstrip())
+ wig_ar[pos] = value
+ pos = pos + 1
+ print("Loaded {}".format(wig_path))
+ return wig_ar
+
+
+def bed_handler(bed_path):
+ '''
+ Saves a gzipped BED file to a pandas
+ dataframe.
+ '''
+ no_header = True
+ with gzip.open(bed_path, "rb") as bed_link:
+ header_line = bed_link.readline()
+ header_list = header_line.rstrip().split("\t")
+ if len(header_list) < 3:
+ no_header = False
+ elif "chr" not in header_list[0]:
+ no_header = False
+ if no_header:
+ bed_df = pd.read_csv(
+ bed_path,
+ sep="\t",
+ header=None,
+ compression="gzip")
+ else:
+ bed_df = pd.read_csv(
+ bed_path,
+ skiprows=1,
+ sep="\t",
+ header=None,
+ compression="gzip")
+ column_names = list(bed_df.columns)
+ column_names[:3] = ["Chromosome", "Start", "End"]
+ bed_df.columns = column_names
+ return bed_df
+
+
+def subsetter(my_list, regex):
+ '''
+ Finds elements of a list matching a regex
+ '''
+ out_list = []
+ for each in my_list:
+ RE = re.search(regex, each)
+ if RE:
+ out_list.append(each)
+ return out_list
+
+
+class BedMappability:
+ '''
+ This class provides methods for identifying
+ single-read and multi-read mappability of
+ an input BED file. it uses local functions
+ such as bed_handler and get_wig if necessary.
+ '''
+ def __init__(self, bed_path, umap_dir,
+ out_path, kmer, wigdir="NA"):
+ '''
+
+ :param bed_path: Input gzipped BED path
+ :param umap_dir: Umap/Bismap unique uint directory
+ :param out_path: Path to output gzipped BED
+ :param kmer: Integer kmer size
+ :param wigdir: Directory of multi-read mappability
+ files of different chromosomes. Optional.
+ '''
+ self.bed_path = bed_path
+ self.umap_dir = umap_dir
+ self.out_path = out_path
+ self.kmer = kmer
+ self.kmer_str = "k{}".format(kmer)
+ self.wigdir = wigdir
+
+ def annotate_bed(self):
+ '''
+ Main motor method for getting single-read
+ and multi-read mappability of BedMappability object.
+
+ Returns:
+ Pandas dataframe BED file with mappability info
+ '''
+ bed_df = bed_handler(self.bed_path)
+ all_chrs = list(pd.unique(bed_df["Chromosome"]))
+ all_chrs.sort()
+ bed_out_list = []
+ for each_chr in all_chrs:
+ print("Started working on {}".format(each_chr))
+ temp_df = bed_df[bed_df["Chromosome"] == each_chr]
+ mapped_df = self.get_df_mappability(temp_df, each_chr)
+ if len(mapped_df) > 0:
+ bed_out_list.append(mapped_df)
+ out_df = pd.concat(bed_out_list)
+ return out_df
+
+ def get_df_mappability(self, temp_df, cur_chr):
+ '''
+ Internally used method for finding the single-read
+ and multi-read mappability of a bed file for a given
+ chromosome.
+ '''
+ dists = pd.unique(temp_df.iloc[2] - temp_df.iloc[1])
+ FIXED_DIST_1 = False
+ if len(dists) < 2:
+ if 1 in dists or 0 in dists:
+ FIXED_DIST_1 = True
+ temp_df["SingleRead.Mappability"] = 0
+ temp_df["MultiRead.Mappability"] = 0
+ umap_paths = subsetter(os.listdir(self.umap_dir),
+ "uint8.unique.gz")
+ umap_path = subsetter(umap_paths, "{}.uint".format(cur_chr))
+ if len(umap_path) == 0:
+ temp_df = []
+ else:
+ umap_path = umap_path[0]
+ uint_path = "{}/{}".format(
+ self.umap_dir, umap_path)
+ uint_link = gzip.open(uint_path, "rb")
+ uint_ar = np.frombuffer(uint_link.read(), dtype=np.uint8)
+ uint_link.close()
+ print("Using {}".format(umap_path))
+ kmer = self.kmer
+ wig_path = "{}/{}_{}.MultiTrackMappability.wg.gz".format(
+ self.wigdir, self.kmer_str, cur_chr)
+ if os.path.exists(wig_path) and FIXED_DIST_1:
+ wig_ar = load_wig(wig_path, len(uint_ar))
+ temp_df["MultiRead.Mappability"] = \
+ wig_ar[temp_df.iloc[:, 1] - 1]
+ temp_df["SingleRead.Mappability"] = \
+ temp_df["MultiRead.Mappability"]
+ ind_unique, = np.where(temp_df["SingleRead.Mappability"] > 0)
+ temp_df["SingleRead.Mappability"].iloc[ind_unique] = 1
+ else:
+ less_than_kmer = uint_ar <= kmer
+ not_zero = uint_ar != 0
+ uniquely_mappable = np.array(
+ np.logical_and(less_than_kmer, not_zero),
+ dtype=int)
+ for i in range(temp_df.shape[0]):
+ chr, start, end = temp_df.iloc[i, :3]
+ st_vec = start - kmer
+ if st_vec < 0:
+ st_vec = 0
+ region_vec = np.zeros(
+ len(range(st_vec, end + 1)),
+ dtype=float)
+ single_vec = np.zeros(
+ len(range(st_vec, end + 1)),
+ dtype=float)
+ idxs_unique, = np.where(
+ [each_idx == 1 for each_idx in
+ uniquely_mappable[st_vec:(end + 1)]])
+ for idx_unique in idxs_unique:
+ end_idx = idx_unique + kmer
+ if end_idx > len(region_vec):
+ end_idx = len(region_vec)
+ region_vec[idx_unique:end_idx] = 1
+ single_vec[idx_unique:end_idx] = \
+ single_vec[idx_unique:end_idx] + 1
+ unique_map_percent = float(
+ sum(single_vec[kmer:(kmer + end - start + 1)] > 0)) /\
+ float(len(single_vec[kmer:(kmer + end - start + 1)]))
+ map_prob = float(len(idxs_unique)) / float(len(region_vec))
+ temp_df.iloc[i, -1] = map_prob
+ temp_df.iloc[i, -2] = unique_map_percent
+ return temp_df
+
+ def write_bed(self, mapped_df):
+ '''
+ Use this method to write the output of
+ BedMappability.annotate_bed() to a gzipped file,
+ '''
+ out_link = gzip.open(self.out_path, "wb")
+ mapped_df.to_csv(out_link, sep="\t", index=False, header=False)
+ out_link.close()
+ print("Successfully created {}".format(self.out_path))
+
+
+if __name__ == "__main__":
+ bed_path, out_path, umap_dir, kmer, wigdir = get_args()
+ BedMapObj = BedMappability(bed_path, umap_dir,
+ out_path, kmer, wigdir)
+ mapped_df = BedMapObj.annotate_bed()
+ BedMapObj.write_bed(mapped_df)
diff --git a/umap/run_bowtie.py b/umap/run_bowtie.py
new file mode 100644
index 0000000..59db64c
--- /dev/null
+++ b/umap/run_bowtie.py
@@ -0,0 +1,136 @@
+from argparse import ArgumentParser
+from datetime import datetime
+import os
+import re
+import subprocess
+
+
+def subset_list(list_items, regex):
+ out_list = []
+ for each_item in list_items:
+ RE = re.search(regex, each_item)
+ if RE:
+ out_list.append(each_item)
+ return out_list
+
+
+class BowtieWrapper:
+ def __init__(self, kmer_dir, bowtie_dir,
+ index_dir, index_name,
+ job_id, Bismap):
+ """Runs Bowtie one <chrom>.<kmer>.<jobid>.kmer.gz
+
+ Using the job_id, this function identifies
+ one kmer.gz file and runs bowtie on that and saves
+ the output to <chrom>.<kmer>.<jobid>.bowtie.gz.
+
+ :param kmer_dir: Directory with <chrom>.<kmer>.<jobid>.kmer.gz files
+ :param bowtie_dir: Directory with Bowtie 1.1.0 executable files.
+ :param index_dir: Directory with Bowtie index
+ :param index_name: Name used for generating Bowtie index files
+ :param int job_id: will be used for finding kmer.gz file
+ :param bool Bismap: Run bowtie with --norc
+
+ :returns: Saves the output to a file in the same directory as kmer_dir
+ """
+ self.kmer_dir = kmer_dir
+ self.bowtie_dir = bowtie_dir
+ self.index_dir = index_dir
+ self.index_name = index_name
+ self.job_id = job_id
+ self.Bismap = Bismap
+ self.execute_bowtie_command()
+
+ def execute_bowtie_command(self):
+ """The only method of BowtieWrapper
+
+ Will be executed automatically by BowtieWrapper
+
+ :raises ValueError: If job_id is out of expected range
+ """
+ if self.Bismap:
+ rev_comp = " --norc "
+ else:
+ rev_comp = ""
+ kmer_names = ["{}/{}".format(self.kmer_dir, each_kmer) for each_kmer
+ in subset_list(os.listdir(self.kmer_dir), ".kmer.gz$")]
+ kmer_names.sort()
+ LongIndex = False
+ short_ind_path = "{}/{}.1.ebwtl".format(
+ self.index_dir, self.index_name)
+ if os.path.exists(short_ind_path):
+ LongIndex = True
+ print("Switching to use of long index")
+ if job_id <= len(kmer_names):
+ try:
+ kmer_file = kmer_names[job_id]
+ except:
+ raise ValueError(
+ "{} does not exist. Time: {}".format(
+ job_id, str(datetime.now())))
+ print("processing Kmer File {}".format(kmer_file))
+ # kmer_name = kmer_dir.split("/")[-1]
+ kmer_path = "{}/{}".format(self.kmer_dir, kmer_file.split("/")[-1])
+ bowtie_out_path = kmer_path.replace(".kmer.gz", ".bowtie.gz")
+ first_part_of_command = "gunzip -c {} | {}/bowtie ".format(
+ kmer_path, self.bowtie_dir)
+ if LongIndex:
+ first_part_of_command = first_part_of_command +\
+ "--large-index "
+ bowtiecmd = first_part_of_command +\
+ "{}/{} ".format(self.index_dir, self.index_name) +\
+ "-v 0 -k 1 -m 1 {}--mm ".format(rev_comp) +\
+ "-r --refidx --suppress 5,6,7,8 - " +\
+ "| gzip -c > {}".format(bowtie_out_path)
+ subprocess.call(bowtiecmd, shell=True)
+ print("Executing {}".format(bowtiecmd))
+ else:
+ print("The length of files was {} but the index was {}".format(
+ len(kmer_names), job_id))
+
+
+def check_genome(index_dir, index_name):
+ all_idx_paths = [
+ each_path for each_path in
+ os.listdir(index_dir) if index_name in each_path]
+ if len(all_idx_paths) < 6:
+ raise ValueError("Index does not exist")
+
+
+if __name__ == "__main__":
+ parser = ArgumentParser(
+ description="Umap wrapper for running bowtie "
+ "on individual k-mer files.")
+ parser.add_argument(
+ "kmer_dir",
+ help="Directory containing the .kmer files")
+ parser.add_argument(
+ "bowtie_dir",
+ help="Directory containing bowtie executable")
+ parser.add_argument(
+ "index_dir",
+ help="Directory containing bowtie index")
+ parser.add_argument(
+ "index_name",
+ help="prefix name of bowtie index")
+ parser.add_argument(
+ "-Bismap",
+ action="store_true",
+ help="Run bowtie with --norc")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="HPC environmental variable for JOB ID")
+ parser.add_argument(
+ "-job_id",
+ type=int,
+ default=0,
+ help="1-based index for selecting a k-mer file")
+ args = parser.parse_args()
+ check_genome(args.index_dir, args.index_name)
+ job_id = args.job_id
+ if job_id == 0:
+ job_id = int(os.environ[args.var_id]) - 1
+ BowtieWrapper(args.kmer_dir, args.bowtie_dir,
+ args.index_dir, args.index_name, job_id,
+ args.Bismap)
diff --git a/umap/ubismap.py b/umap/ubismap.py
new file mode 100644
index 0000000..65fdf67
--- /dev/null
+++ b/umap/ubismap.py
@@ -0,0 +1,636 @@
+from argparse import ArgumentParser
+from datetime import datetime
+import os
+import pandas as pd
+import re
+import subprocess
+from handle_fasta import FastaHandler
+
+
+class ArgHandler:
+ def __init__(self):
+ """Makes an argument class
+
+ Uses ArgumentParser and generates some local arguments as well
+ for direct use by other classes and functions.
+ """
+ parser = ArgumentParser(
+ description="This scripts is a wrapper that writes qsub "
+ "job submission commands for executing other scripts of the "
+ "software in order to identify mappability of a given genome "
+ "for a range of various read lengths. This script assumes "
+ "that you are using a cluster system that accepts the following "
+ "parameters: -N, -e, -o, -t, -tc, -cwd, "
+ "-b y, -terse. If these options do not exist in your "
+ "cluster, specify -write so you can modify the "
+ "qsub job submissions manually.")
+ parser.add_argument(
+ "fasta_path",
+ help="Path to the genome fasta file.")
+ parser.add_argument(
+ "chrsize_path",
+ help="Path to a 2-column file where the first column "
+ "is the chromosome name and the second column is its size")
+ parser.add_argument(
+ "out_dir",
+ help="Path to directory to create output files/folders")
+ parser.add_argument(
+ "queue_name",
+ help="Queue name for qsub job submission.")
+ parser.add_argument(
+ "bowtie_path",
+ help="Path to bowtie-build executable")
+ parser.add_argument(
+ "--kmers",
+ default=[24, 36, 50, 100],
+ nargs="*",
+ help="Kmer length for mappability. e.g. 24 36 50 100")
+ parser.add_argument(
+ "-GenomeReady",
+ action="store_true",
+ help="If in the 'out_dir' "
+ "there already exists a /chrs and /genome subdirectory "
+ "where genome directory has a genome.fasta "
+ "with bowtie index suffix as 'BisMap_bowtie.ind' or "
+ "'Umap_bowtie.ind' if --Bismap is not specified and "
+ "the ./chrs directory has indivudal chromosome "
+ "FASTA files, specify this option")
+ parser.add_argument(
+ "-Bismap",
+ action="store_true",
+ help="Specify --Bismap if double genome indexing is expected. "
+ "This would create a genome that is concatenation of forward "
+ "and reverse complement. If -C2T or -G2A is expected, "
+ "this must be specified")
+ parser.add_argument(
+ "-C2T",
+ action="store_true",
+ help="If --Bismap is provided, specify --C2T or --G2A")
+ parser.add_argument(
+ "-G2A",
+ action="store_true",
+ help="If --Bismap is provided, specify --C2T or --G2A")
+ parser.add_argument(
+ "-ExitAfterIndexing",
+ action="store_true",
+ help="If you only want the index, specify this option")
+ parser.add_argument(
+ "-SimultaneousJobs",
+ default=120,
+ type=int,
+ help="Number of jobs to run simultaneously")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="Environmental variable for accessing job IDs. "
+ "By default is set to SGE_TASK_ID assuming a sungrid "
+ "engine environment.")
+ parser.add_argument(
+ "-write_script",
+ default="False",
+ help="Specify -write <Path to output job submission file> "
+ "if instead of direct execution, "
+ "you want to save the job submission file.")
+ parser.add_argument(
+ "-pipe",
+ action="store_true",
+ help="If -pipe is specified, the software command "
+ "will be piped into the qsub command. For example "
+ "instead of: 'qsub -q <queuename> -N <jobname> "
+ "python <script>.py <arg1> <arg2>', 'echo python "
+ "<script>.py <arg1> <arg2> | qsub -q <queuename> "
+ "-N <jobname>' will be written/executed.")
+ parser.add_argument(
+ "-chunk",
+ default=1000000,
+ type=int,
+ help="Length of chromosomal chunks")
+ args = parser.parse_args()
+ out_dir = args.out_dir
+ chrom_dir, dir_kmers, index_dir = make_dir_structure(out_dir)
+ print("{} Jobs will be run simultaneously at each step".format(
+ args.SimultaneousJobs))
+ # Create paths and key parameters
+ chrsize_path = "{}/chrsize.tsv".format(out_dir)
+ if args.chrsize_path != chrsize_path:
+ subprocess.call(["cp", args.chrsize_path, chrsize_path])
+ chrsize_df = pd.read_csv(chrsize_path, sep="\t", names=["Chr", "Size"])
+ LenChrs = len(pd.unique(chrsize_df["Chr"]))
+ conversion = "None"
+ genome_path = "{}/genome.fa".format(index_dir)
+ # Make sure write is a new file
+ if args.write_script != "False":
+ with open(args.write_script, "w") as out_link:
+ out_link.write(
+ "# Bismap/Umap job submission commands follow.\n")
+ source_dir = os.getcwd()
+ if args.C2T:
+ if args.G2A:
+ raise ValueError("Cannot specify both -C2T and -G2A")
+ conversion = "C2T"
+ elif args.G2A:
+ conversion = "G2A"
+ if args.Bismap:
+ # It is possible that chrx_RC information does not exist
+ # in the chrsize.tsv file. The function below would check
+ # and add this information if necessary and would update
+ # chromosome length
+ len_chrs_after_complement = complement_chrsize_file(chrsize_path)
+ if len_chrs_after_complement != LenChrs:
+ LenChrs = len_chrs_after_complement
+ print "Length of chromosomes changed to %d to account for\
+ reverse complements" % LenChrs
+ idx_path = index_unique_kmer_jobids(chrsize_path, args.chunk)
+ self.genome_path = genome_path
+ self.chrom_dir = chrom_dir
+ self.dir_kmers = dir_kmers
+ self.chrsize_path = chrsize_path
+ self.out_dir = out_dir
+ self.idx_path = idx_path
+ self.conversion = conversion
+ self.Bismap = args.Bismap
+ self.queue_name = args.queue_name
+ self.kmers = args.kmers
+ self.SimultaneousJobs = args.SimultaneousJobs
+ self.ExitAfterIndexing = args.ExitAfterIndexing
+ self.var_id = args.var_id
+ self.write_script = args.write_script
+ self.source_dir = source_dir
+ self.GenomeReady = args.GenomeReady
+ self.fasta_path = args.fasta_path
+ self.bowtie_path = args.bowtie_path
+ self.LenChrs = LenChrs
+ self.pipe = args.pipe
+
+
+def pipe_job(job_list):
+ '''Assumes the qsub command has the
+ qsub ... -cwd -b y <executing command>.
+ It will change it to: echo <executing command>
+ | qsub ...'''
+ for ind_job in range(len(job_list)):
+ if job_list[ind_job] == "-cwd":
+ if job_list[ind_job + 1] == "-b":
+ if job_list[ind_job + 2] == "y":
+ ind_cwd = ind_job
+ try:
+ qsub_list = job_list[:ind_cwd]
+ exec_list = job_list[(ind_cwd + 3):]
+ piped_list = [
+ ['echo "'] + exec_list + ['" | '] + qsub_list]
+ return piped_list
+ except:
+ raise ValueError(
+ "The submitted command to pipe_job must "
+ "include -cwd -b y.")
+
+
+def index_genome(queue_name, converted_path,
+ bowtie_build_path, Bismap, write_path, pipe):
+ path_genome = "{}/genome.fa".format(converted_path)
+ if Bismap:
+ index_suffix = "BisMap_bowtie.ind"
+ else:
+ index_suffix = "Umap_bowtie.ind"
+ index_job_line = ["qsub", "-q", queue_name, "-terse",
+ "-N", "Index-Bowtie", "-o",
+ "{}/index_genome.LOG".format(converted_path),
+ "-e", "{}/index_genome.ERR".format(converted_path),
+ "-cwd", "-b", "y",
+ bowtie_build_path, path_genome,
+ "{}/{}".format(converted_path, index_suffix)]
+ if pipe:
+ index_job_line = pipe_job(index_job_line)
+ if write_path != "False":
+ job_num = write_job(index_job_line, write_path)
+ else:
+ try:
+ job_line = subprocess.Popen(index_job_line, stdout=subprocess.PIPE)
+ job_num = job_line.stdout.read().rstrip()
+ except:
+ raise ValueError(
+ "Your system is incompatible with direct job "
+ "submission. Please specify -write and manually "
+ "modify the job submission options.")
+ print "job id %s from indexing genome" % job_num
+ return index_suffix, job_num
+
+
+def get_unique_kmer_jobnums(idx_path):
+ ind_df = pd.read_csv(idx_path, sep="\t")
+ last_ind = ind_df.shape[0] + 1
+ return last_ind
+
+
+def write_job(list_out, write_path):
+ write_link = open(write_path, "a")
+ out_str = "\nJOBID=$({})\n".format(
+ " ".join(list_out))
+ write_link.write(out_str)
+ write_link.write(
+ 'IDPARTS=($(echo $JOBID | tr "." "\\n"))\n')
+ write_link.write(
+ 'WAITID=${IDPARTS[0]}\n')
+ write_link.write(
+ 'echo "Submitted JOB ID $WAITID"\n')
+ write_link.close()
+ return "$WAITID"
+
+
+def make_unique_kmers(chrom_dir, dir_kmers,
+ kmer_size, queue_name,
+ source_dir, conversion_job_id,
+ idx_path, chrsize_path,
+ write_path, var_id,
+ job_lim, pipe):
+ """Generates kmer.gz files of the genome
+ """
+ # chr_files = os.listdir(chrom_dir)
+ # chr_fas = sublist_by_reg(".fa$", chr_files)
+ out_dir = "{}/k{}".format(dir_kmers, kmer_size)
+ ind_jobs = get_unique_kmer_jobnums(idx_path)
+ array_param = "1-{}".format(ind_jobs)
+ get_kmers = ["qsub", "-q",
+ queue_name, "-t",
+ array_param, "-N",
+ "Bismap.UniqueKmers",
+ "-terse",
+ "-tc", str(job_lim),
+ "-hold_jid", conversion_job_id,
+ "-cwd", "-b", "y",
+ "-o", "{}/Bismap.UniqueKmers.LOG".format(dir_kmers),
+ "-e", "{}/Bismap.UniqueKmers.ERR".format(dir_kmers),
+ "python", "get_kmers.py",
+ chrsize_path, out_dir,
+ chrom_dir, idx_path,
+ "--var_id", var_id, "--kmer", "k{}".format(kmer_size)]
+ if pipe:
+ get_kmers = pipe_job(get_kmers)
+ if write_path != "False":
+ job_num = write_job(get_kmers, write_path)
+ else:
+ try:
+ job_line = subprocess.Popen(get_kmers, stdout=subprocess.PIPE)
+ except:
+ raise ValueError("Incompatible system? Try -write.")
+ job_num = job_line.stdout.read().rstrip()
+ print "job id %s from creating unique kmers" % job_num
+ job_num = job_num.split(".")[0]
+ return job_num, ind_jobs
+
+
+def run_bowtie(queue_name, dir_kmers, bowtie_path, index_dir,
+ index_suffix, kmer_job_id,
+ index_job_id, kmer, source_dir,
+ Bismap, num_jobs, write_path, var_id,
+ job_lim, pipe):
+ """Calls bowtie on kmer.gz files
+ """
+ bowtie_dir = "/".join(bowtie_path.split("/")[:-1])
+ kmer_folder = "{}/k{}".format(dir_kmers, kmer)
+ array_param = "1-{}".format(num_jobs)
+ wait_param = "%s,%s" % (index_job_id, kmer_job_id)
+ run_bowtie = ["qsub", "-q",
+ queue_name, "-t",
+ array_param, "-N",
+ "Bismap.RunBowtie",
+ "-terse",
+ "-tc", str(job_lim),
+ "-hold_jid", wait_param,
+ "-cwd", "-b", "y",
+ # "-l", "\"mem_requested={%s}G\"" % (mem_GB),
+ "-o", "{}/Bismap.RunBowtie.LOG".format(dir_kmers),
+ "-e", "{}/Bismap.RunBowtie.ERR".format(dir_kmers),
+ "python", "run_bowtie.py", kmer_folder,
+ bowtie_dir, index_dir, index_suffix,
+ "-var_id", var_id]
+ if Bismap:
+ run_bowtie.append("-Bismap")
+ if pipe:
+ run_bowtie = pipe_job(run_bowtie)
+ if write_path != "False":
+ job_num = write_job(run_bowtie, write_path)
+ else:
+ try:
+ job_line = subprocess.Popen(run_bowtie, stdout=subprocess.PIPE)
+ except:
+ raise ValueError("Incompatible system? Try -write")
+ job_num = job_line.stdout.read()
+ print "job id %s from mapping with bowtie" % job_num
+ job_num = job_num.split(".")[0]
+ return job_num
+
+
+def unify_bowtie(queue_name, bowtie_job_id, dir_kmers,
+ kmer, chrom_dir, source_dir,
+ LenChrs, write_path, var_id,
+ chrsize_path, job_lim, pipe):
+ """Generates qsub command for interpreting bowtie outputs
+
+ Saves collectinve bowtie.gz files of each chromosome into
+ a binary unsigned 8-bit integer file for each chromosome
+ which is an array with the same length as the chromosome
+ """
+ kmer_folder = "{}/k{}".format(dir_kmers, kmer)
+ len_chrs = LenChrs
+ array_param = "1-%d:1" % (len_chrs)
+ chr_order_path = chrsize_path
+ wait_param = bowtie_job_id
+ unify_bw_lst = ["qsub", "-q",
+ queue_name,
+ "-t", array_param,
+ "-N",
+ "Bismap.UnifyBowtie",
+ "-terse",
+ "-tc", str(job_lim),
+ "-hold_jid", wait_param,
+ "-cwd", "-b", "y",
+ "-o", "{}/Bismap.UnifyBowtie.LOG".format(dir_kmers),
+ "-e", "{}/Bismap.UnifyBowtie.ERR".format(dir_kmers),
+ "python", "unify_bowtie.py",
+ kmer_folder, chr_order_path, "-var_id", var_id]
+ if pipe:
+ unify_bw_lst = pipe_job(unify_bw_lst)
+ if write_path != "False":
+ job_num = write_job(unify_bw_lst, write_path)
+ else:
+ try:
+ job_line = subprocess.Popen(unify_bw_lst, stdout=subprocess.PIPE)
+ except:
+ raise ValueError("Incompatible system? try -write")
+ job_num = job_line.stdout.read()
+ job_num = job_num.split(".")[0]
+ TempDir = "%s/TEMPs" % kmer_folder
+ make_dir(TempDir)
+ move_intermediary_files = ["qsub", "-q",
+ queue_name, "-N",
+ "Moving.Intermediary.Files",
+ "-hold_jid", job_num,
+ "-terse",
+ "-cwd", "-b", "y",
+ "-o", "Bismap.FileMov.LOG",
+ "-e", "Bismap.FileMov.ERR",
+ "mv",
+ "%s/*kmer*" % (kmer_folder),
+ TempDir]
+ if write_path != "False":
+ job_num = write_job(move_intermediary_files, write_path)
+ else:
+ job_line = subprocess.Popen(
+ move_intermediary_files, stdout=subprocess.PIPE)
+ move_intermediary_files_2 = move_intermediary_files[:-2] +\
+ ["%s/*bowtie*" % (kmer_folder), TempDir]
+ if write_path != "False":
+ job_num = write_job(move_intermediary_files_2, write_path)
+ else:
+ job_line = subprocess.Popen(
+ move_intermediary_files_2,
+ stdout=subprocess.PIPE)
+ job_num = job_line.stdout.read()
+ return job_num
+
+
+def sublist_by_reg(regex, my_list):
+ subsetted_list = []
+ for item in my_list:
+ RE = re.search(regex, item)
+ if RE:
+ subsetted_list.append(item)
+ return subsetted_list
+
+
+def make_dir(dir_name):
+ if not os.path.exists(dir_name):
+ os.makedirs(dir_name)
+
+
+def make_dir_structure(out_dir):
+ """Generates subfolders needed for Umap in out_dir
+ """
+ chrom_dir = "{}/chrs".format(out_dir)
+ path_genome = "{}/genome".format(out_dir)
+ dir_kmers = "{}/kmers".format(out_dir)
+ make_dir(chrom_dir)
+ make_dir(path_genome)
+ make_dir(dir_kmers)
+ return chrom_dir, dir_kmers, path_genome
+
+
+def combine_files(bowtie_unify_id, source_dir, dir_kmers, queue_name,
+ chrsize_path, write_path, var_id, LenChrs, pipe):
+ """Creates the qsub command for merging data of several k-mers
+ """
+ combine_job_line = ["qsub", "-q",
+ queue_name, "-N",
+ "CombineUmappedFiles",
+ "-terse",
+ "-t", "1-{}".format(LenChrs),
+ "-hold_jid", bowtie_unify_id,
+ "-cwd", "-b", "y",
+ "-o", "{}/Bismap.combine.LOG".format(dir_kmers),
+ "-e", "{}/Bismap.combine.ERR".format(dir_kmers),
+ "python", "combine_umaps.py", dir_kmers,
+ chrsize_path, "-var_id", var_id]
+ if pipe:
+ combine_job_line = pipe_job(combine_job_line)
+ if write_path != "False":
+ write_job(combine_job_line, write_path)
+ else:
+ subprocess.call(combine_job_line)
+
+
+def complement_chrsize_file(chrsize_path):
+ """Complement chromosome size file
+
+ If using Bismap, an extra set of chromosomes
+ will be generated with the _RC suffix.
+ These need to be added to the chromosome size
+ file as well.
+
+ :param chrsize_path: Path to 2-column file of chrom\tsize\n
+
+ :returns: The actual number of chromosomes
+ """
+ if not os.path.exists(chrsize_path):
+ print "%s didn't exist!" % chrsize_path
+ ad_lines = []
+ len_chrs = 0
+ NO_RC = True
+ with open(chrsize_path, "r") as chrsize_link:
+ for each_line in chrsize_link:
+ len_chrs = len_chrs + 1
+ if "_RC" in each_line:
+ NO_RC = False
+ chrsize_list = each_line.rstrip().split("\t")
+ chrsize_list[0] = chrsize_list[0] + "_RC"
+ ad_lines.append("\t".join(chrsize_list) + "\n")
+ if len(ad_lines) > 0 and NO_RC:
+ with open(chrsize_path, "a") as chrsize_link:
+ for each_line in ad_lines:
+ len_chrs = len_chrs + 1
+ print "adding %s" % each_line
+ chrsize_link.write(each_line)
+ print "Added reverse complemented chromosomes"
+ else:
+ "Reverse complemented chromosomes existed"
+ return len_chrs
+
+
+def process_genome(GenomeReady, genome_path,
+ Bismap, fasta_path,
+ conversion, out_dir, chr_dir,
+ queue_name, bowtie_path,
+ chrsize_path, write_script, pipe):
+ """Generates necessary fasta files for Umap and Bismap
+
+ Umap and Bismap require fasta files for each chromosome.
+ Bismap requires the fasta files to have a C>T or G>A
+ conversion as well. Additionally, Bismap requires a
+ reverse complemented set of chromosome where the
+ C>T or G>A conversion occurs after reverse complementation.
+
+ :param GenomeRead: Boolean indicating if index of genome exists
+ :param genome_path: Path to the output fasta file of the genome
+ :param Bismap: Boolean indicating if Bismap option is selected
+ :param fasta_path: Path to the already existing input fasta file
+ :param conversion: One of None, C2T or G2A
+ :param out_dir: Directory for Umap output
+ :param chr_dir: Directory for making individual chromosome fastas
+ :param bowtie_path: Path to executable bowtie-build binary
+ :param chrsize_path: Path to 2-column file of chromosome\tsize\n
+ :param write_script: File path for writing the qsub command
+ or the string 'False'
+ :param pipe: Boolean indicating if the qsub command should be piped
+
+ :returns: index_suffix, index_job_id (qsub wait IDs)
+ """
+ if GenomeReady:
+ print("Assuming the genome and index files exist")
+ index_suffix = "BisMap_bowtie.ind"
+ index_job_id = "1"
+ else:
+ print "Started copying/reverse complementing/converting"
+ if not os.path.exists(genome_path):
+ if Bismap:
+ print "Bismap reverse complementation started\
+ at %s" % str(datetime.now())
+ FastaObj = FastaHandler(fasta_path, genome_path, chrsize_path,
+ chr_dir, True, conversion)
+ else:
+ print "Umap genome is being processed"
+ FastaObj = FastaHandler(fasta_path, genome_path, chrsize_path,
+ chr_dir, False, "None")
+ FastaObj.handle_fasta()
+ elif Bismap:
+ print "Assuming that %s/genome/genome.fa includes reverse\
+ complemented chromosomes." % out_dir
+ print "Indexing the genome started at %s" % str(datetime.now())
+ index_suffix, index_job_id = index_genome(
+ queue_name,
+ "{}/genome".format(out_dir),
+ bowtie_path, Bismap, write_script, pipe)
+ print "Done with indexing at %s" % str(datetime.now())
+ return index_suffix, index_job_id
+
+
+def index_unique_kmer_jobids(chrsize_path, CHUNK_SIZE=1e6):
+ """Generate index file mapping job_ids to chromosomal chunks
+
+ Umap (or Bismap) requires around 200 hours of computation.
+ All of the scripts accept -job_id arguments to perform the
+ embarrassingly parallel process on different chromosomal
+ chunks using a 0-based index that refers to part of the
+ genome. This script creates a 4-column index file with
+ the following columns:
+ Index\tChromosome\tStart\tend\n
+
+ :param chrsize_path: Path to 2-column file of chrom\tsize\n
+ :param CHUNK_SIZE: The maximum length of each chromosomal chunk
+ :type CHUNK_SIZE: Integer
+
+ :returns: Path to index file
+ """
+ CHUNK_SIZE = int(CHUNK_SIZE)
+ ind_path = "{}/chrsize_index.tsv".format(
+ "/".join(chrsize_path.split("/")[:-1]))
+ if not os.path.exists(ind_path):
+ ind_link = open(ind_path, "w")
+ ind_link.write("Index\tChromosome\tStart\tEnd\n")
+ start = 1
+ ind = 0
+ # Identifying chromosome, start, end for job_id
+ with open(chrsize_path, "r") as chrsize_link:
+ for chrsize_line in chrsize_link:
+ chr, len_chr = chrsize_line.rstrip().split("\t")
+ end = int(len_chr) + start
+ for pos in range(start, end, CHUNK_SIZE):
+ if pos < end:
+ if pos + CHUNK_SIZE - 1 > end:
+ pos_end = end
+ else:
+ pos_end = pos + CHUNK_SIZE - 1
+ ind_link.write(
+ "\t".join(
+ [str(ind), chr, str(pos), str(int(pos_end))]) +
+ "\n")
+ ind = ind + 1
+ ind_link.close()
+ return ind_path
+
+
+if __name__ == "__main__":
+ args = ArgHandler()
+ # genome_path, chrom_dir, dir_kmers, chrsize_path, out_dir = args_list[:5]
+ # idx_path, conversion, Bismap, queue_name = args_list[5:9]
+ # kmers, SimultaneousJobs, ExitAfterIndexing = args_list[9:12]
+ # var_id, write_script, source_dir, GenomeReady = args_list[12:16]
+ # fasta_path, bowtie_path, LenChrs, pipe = args_list[16:]
+ index_dir = os.path.dirname(args.genome_path)
+ conversion_job_id = "1" # initiate job dependency with an invalid ID
+ index_suffix, index_job_id = process_genome(
+ args.GenomeReady, args.genome_path,
+ args.Bismap, args.fasta_path,
+ args.conversion, args.out_dir,
+ args.chrom_dir, args.queue_name,
+ args.bowtie_path, args.chrsize_path,
+ args.write_script, args.pipe)
+ if args.ExitAfterIndexing:
+ pass
+ print "Exiting because -ExitAfterIndexing is specified"
+ else:
+ for kmer in args.kmers:
+ kmer = int(kmer)
+ make_dir("{}/k{}".format(args.dir_kmers, kmer))
+ kmer_job_id, num_jobs = make_unique_kmers(
+ args.chrom_dir, args.dir_kmers, kmer,
+ args.queue_name, args.source_dir,
+ conversion_job_id,
+ args.idx_path, args.chrsize_path,
+ args.write_script, args.var_id,
+ args.SimultaneousJobs, args.pipe)
+ bowtie_job_id = run_bowtie(
+ args.queue_name, args.dir_kmers,
+ args.bowtie_path,
+ index_dir, index_suffix,
+ kmer_job_id, index_job_id, kmer,
+ args.source_dir, args.Bismap,
+ num_jobs, args.write_script, args.var_id,
+ args.SimultaneousJobs, args.pipe)
+ bowtie_unify_id = unify_bowtie(
+ args.queue_name, bowtie_job_id,
+ args.dir_kmers,
+ kmer, args.chrom_dir,
+ args.source_dir, args.LenChrs,
+ args.write_script,
+ args.var_id, args.chrsize_path,
+ args.SimultaneousJobs, args.pipe)
+ conversion_job_id = kmer_job_id
+ print "Jobs submitted for k%d" % kmer
+ combine_files(bowtie_unify_id, args.source_dir,
+ args.dir_kmers,
+ args.queue_name,
+ args.chrsize_path, args.write_script,
+ args.var_id,
+ args.LenChrs, args.pipe)
+ conversion_job_id = bowtie_unify_id
+ print("Successfully done with creating all jobs")
diff --git a/umap/uint8_to_bed.py b/umap/uint8_to_bed.py
new file mode 100644
index 0000000..d5b21d7
--- /dev/null
+++ b/umap/uint8_to_bed.py
@@ -0,0 +1,423 @@
+import argparse
+from datetime import datetime
+import gzip
+import numpy as np
+import os
+import re
+import warnings
+
+
+def subset_list(my_list, regex, reg_neg=False):
+ out_list = []
+ for item in my_list:
+ RE = re.search(regex, item)
+ if RE and not reg_neg:
+ out_list.append(item)
+ elif not RE and reg_neg:
+ out_list.append(item)
+ return out_list
+
+
+class Int8Handler:
+ def __init__(self, in_dir, out_dir, C2T, G2A, chrsize_path):
+ """Infers important directory structure from in_dir
+
+ The Int8Handler class requires in_dir argument which
+ is a directory with subfolders named as k<integer>
+ that have <chrom>.<kmer>.uint8.unique.gz files.
+ The Int8Handler.write_beds method creates one
+ browser extensible data (BED) file for each of the
+ k<integer> subfolders.
+
+ :param in_dir: Directory with <chrom>.uint8.unique.gz files
+ :param out_dir: Directory for saving output BED files
+ """
+ self.in_dir = in_dir
+ self.C2T = C2T
+ self.G2A = G2A
+ self.chrsize_path = chrsize_path
+ self.in_prev_dir = "/".join(in_dir.split("/")[:-1])
+ self.fix = ".uint8.unique.gz"
+ self.uint8s = subset_list(os.listdir(in_dir), self.fix)
+ self.prev_dir = "/".join(self.in_dir.split("/")[:-1])
+ self.kmers = subset_list(next(os.walk(self.in_prev_dir))[1],
+ "^k")
+ self.out_dir = out_dir
+ self.type = self.find_type()
+ self.chrsize_dict = self.make_chrsize_dict()
+ self.chroms = [each_chr for each_chr in
+ self.chrsize_dict.keys() if
+ "RC" not in each_chr]
+ self.chroms.sort()
+
+ def find_type(self):
+ if self.C2T:
+ self.type = "Bismap.Forward"
+ elif self.G2A:
+ self.type = "Bismap.Reverse"
+ else:
+ self.type = "Umap"
+ return self.type
+
+ def write_beds(self, out_label, kmer_cur,
+ WriteUnique=False):
+ """Convert uint8 files to BED
+
+ A method of class Int8Handler, it reads uint8 files of
+ different chromosomes and saves them into a BED file.
+ This is the only method in this class that needs
+ to be called manually by the user.
+
+ Args:
+ out_label: Will be used in output names: <kmer>.<out_label>.bed.gz
+ kmer_cur: k-mer size in format of k<integer>
+ WriteUnique: Defaults to False. Will merge and save uint files.
+ Use if working with -Bismap and have reverse
+ complemented chromosomes.
+
+ Returns:
+ Saved ths output to a gzipped BED file
+
+ Raises:
+ Warning: If no uniquely mappable read is found in
+ any of the uint8 arrays.
+ """
+ kmer = int(kmer_cur.replace("k", ""))
+ STRAND = "+"
+ if self.G2A:
+ STRAND = "-"
+ in_dir = self.in_dir
+ all_chrs = self.chroms
+ all_chrs.sort()
+ for cur_chr in self.chroms:
+ other_chr = cur_chr + "_RC"
+ uint_path = "{}/{}{}".format(
+ in_dir, cur_chr, self.fix)
+ uniquely_mappable = self.load_uint_ar(
+ uint_path, kmer, cur_chr)
+ if self.type != "Umap":
+ uint_path_other = in_dir +\
+ "/" + uint_path.split("/")[-1].replace(cur_chr, other_chr)
+ uniquely_mappable_other = self.load_uint_ar(
+ uint_path_other, kmer, other_chr)
+
+ # Remove the last k nucleotides of the reverse chromosome
+ uniquely_mappable_other = uniquely_mappable_other[:-kmer]
+
+ # Reverse the chromosome (Hence it's a reverse complement)
+ uniquely_mappable_other = uniquely_mappable_other[::-1]
+
+ # Remove the last k nucleotides of the forward chromosome
+ uniquely_mappable = uniquely_mappable[:-kmer]
+
+ # Merge to find uniquely mappable reads in both strands
+ uniquely_mappable = np.array(
+ np.logical_and(
+ uniquely_mappable_other, uniquely_mappable),
+ dtype=int)
+ if WriteUnique:
+ unique_ar = np.array(uniquely_mappable, dtype=np.uint8)
+ out_dir_uint = "{}/k{}".format(self.out_dir, kmer)
+ if not os.path.exists(out_dir_uint):
+ os.makedirs(out_dir_uint)
+ out_path_uint = "{}/{}.k{}.uint8.unique.gz".format(
+ out_dir_uint, cur_chr, kmer)
+ out_link_uint = gzip.open(out_path_uint, "wb")
+ out_link_uint.write(unique_ar.tobytes())
+ out_link_uint.close()
+
+ bed_kmer_pos = self.get_bed6(
+ uniquely_mappable, kmer, STRAND, uint_path, cur_chr)
+
+ # Write the BED6 to a gzipped tsv file
+ out_name = "{}/{}.{}.bed.gz".format(
+ self.out_dir, kmer_cur, out_label)
+ if cur_chr == all_chrs[0]:
+ header = self.make_header(kmer_cur, type)
+ out_link = gzip.open(out_name, "wb")
+ out_link.write(header)
+ else:
+ out_link = gzip.open(out_name, "ab")
+ if len(bed_kmer_pos) > 0:
+ print "Found %d regions in %s" %\
+ (bed_kmer_pos.shape[0], cur_chr)
+ for bed_line in bed_kmer_pos:
+ line_out = [str(val) for val in bed_line]
+ line_out = "\t".join(line_out) + "\n"
+ out_link.write(line_out)
+ print "Created data of %s at %s" %\
+ (cur_chr, str(datetime.now()))
+ out_link.close()
+
+ def get_bed6(self, uniquely_mappable, kmer,
+ STRAND, uint_path, cur_chr):
+ """Make BED6 from a binary vector
+
+ Converts a binary vector with the same length
+ as the chromosome to a BED6 file. Each 1
+ entry in the binary file indicates that the
+ k-mer starting at that position and ending at
+ k nucleotides downstream is uniquely mappable.
+ Thus the BED6 would show any region in the genome
+ that is uniquely mappable by at least one k-mer.
+
+ :param uniquely_mappable: numpy binary array (0 or 1 values)
+ :param kmer: Integer scalar showing read length (k-mer)
+ :param STRAND: Strand that will be saved to the BED6
+ :param uint_path: Path of the uint8 array that was used
+ :param cur_chr: Chromosome name the the data is from
+
+ :returns: A numpy string array with BED6 information
+ """
+ unimap_diff = np.diff(uniquely_mappable)
+ poses_start, = np.where(unimap_diff == 1)
+ poses_end, = np.where(unimap_diff == -1)
+ if len(poses_start) != len(poses_end):
+ if len(poses_start) > len(poses_end):
+ poses_end = np.append(poses_end, [len(uniquely_mappable)])
+ else:
+ poses_start = np.append([0], poses_start)
+ elif uniquely_mappable[0] == 1:
+ poses_start = np.append([0], poses_start)
+ poses_end = np.append(poses_end, [len(uniquely_mappable)])
+ if len(poses_start) == 0:
+ warnings.warn(
+ "Found no uniquely mappable reads for {}!".format(
+ uint_path))
+ bed_kmer_pos = []
+ else:
+ chr_length = self.chrsize_dict[cur_chr]
+ bed_kmer_pos = np.empty(shape=(len(poses_start), 6),
+ dtype="S16")
+ ind_high = []
+ for ind_st in range(len(poses_start)):
+ if poses_end[ind_st] + kmer - 1 > chr_length:
+ ind_high.append(ind_st)
+ bed_kmer_pos = np.array(
+ [[cur_chr, str(poses_start[i] + 1),
+ str(poses_end[i] + kmer - 1),
+ "k" + str(kmer),
+ 1, STRAND] for i in range(len(poses_start))],
+ dtype="S64")
+ for each_ind in ind_high:
+ if int(bed_kmer_pos[each_ind][2]) > chr_length:
+ bed_kmer_pos[each_ind][2] = str(chr_length)
+ return bed_kmer_pos
+
+ def load_uint_ar(self, uint_path, kmer, cur_chr):
+ """Loads a gzipped unsigned 8-bit integer as a numpy array
+ """
+ uint_link = gzip.open(uint_path, "rb")
+ uint_ar = np.frombuffer(uint_link.read(), dtype=np.uint8)
+ uint_link.close()
+ print "Processing {} for {} {}".format(
+ uint_path, kmer, cur_chr)
+ less_than_kmer = uint_ar <= kmer
+ not_zero = uint_ar != 0
+ uniquely_mappable = np.array(
+ np.logical_and(less_than_kmer, not_zero), dtype=int)
+ return uniquely_mappable
+
+ def make_header(self, kmer, type):
+ """Created BED6 header
+
+ :param str kmer: k<integer>
+ :param type: One of Bismap.Forward, Bismap.Reverse or Umap
+ """
+ dict_col = {"Bisulfite.Converted": "240,40,80",
+ "Umap": "80,40,240",
+ "Bismap.Forward": "220,20,80",
+ "Bismap.Reverse": "80,20,220"}
+ header = 'track name="{} {}"'.format(type, kmer) +\
+ 'description="Single-read mappability with {}-mers'.format(
+ kmer) +\
+ 'color=%s \n'.format(dict_col.get(type, "40,40,240"))
+ return header
+
+ def make_chrsize_dict(self):
+ """Creates dictionary from 2-column chromosome size file
+ """
+ chrsize_dict = {}
+ with open(self.chrsize_path, "r") as chrsize_link:
+ for each_line in chrsize_link:
+ chr = each_line.rstrip("\n").split("\t")[0]
+ length = int(each_line.rstrip("\n").split("\t")[1])
+ chrsize_dict[chr] = length
+ return chrsize_dict
+
+ def bin_arr_to_wig(self, uniquely_mappable, kmer):
+ """Converts a uniquely a binary array to mult-read mappability
+
+ Unique mappability array is a binary array where each
+ value of 1 indicates that the k-mer starting at that
+ position is uniquely mappable. This function generates
+ an array of the same length and saves the multi-read mappability
+ of each position in that array. Multi-read mappability is the
+ probability of finding a uniquely mappable k-mer among all of
+ the k-mers that overlap with a given position.
+
+ :param uniquely_mappable: A binary numpy array
+ :param kmer: An integer defining read length
+
+ :returns: Multi-read mappability array.
+ """
+ LEN_AR = len(uniquely_mappable)
+ poses_start, = np.where(uniquely_mappable == 1)
+ ar_quant = np.zeros(len(uniquely_mappable), dtype=float)
+ for ind_st in poses_start:
+ ind_end = ind_st + kmer
+ if ind_end > LEN_AR:
+ ind_end = LEN_AR
+ ar_quant[ind_st:ind_end] = ar_quant[ind_st:ind_end] + 1.0
+ print("Finished generating multi-read mappability date at {}".format(
+ str(datetime.now())))
+ del poses_start
+ ar_quant = ar_quant / float(kmer)
+ return ar_quant
+
+ def write_as_wig(self, uint_path, out_path, kmer, chrom):
+ """unsigned 8-bit integer array file to wiggle
+
+ For a given numeric unsigned 8-bit integer vector that
+ is generated by Umap, this method save the wiggle file
+ which is specific for one chromosome over one read length.
+
+ :param uint_path: Path to a gzipped numeric unsigned 8-bit array
+ :param out_path: Gzipped path for saving wiggle
+ :param kmer: Integer defining read length
+ :param chrom: Chromosome that the uint_path is specific to
+ """
+ uniquely_mappable = self.load_uint_ar(uint_path, kmer, chrom)
+ ar_quant = self.bin_arr_to_wig(uniquely_mappable, kmer)
+ out_link = gzip.open(out_path, "wb")
+ unimap_diff = np.diff(np.array(ar_quant > 0, dtype=int))
+ poses_start, = np.where(unimap_diff == 1)
+ poses_end, = np.where(unimap_diff == -1)
+ if len(poses_start) != len(poses_end):
+ if len(poses_start) > len(poses_end):
+ poses_end = np.append(poses_end, [len(uniquely_mappable)])
+ else:
+ poses_start = np.append([0], poses_start)
+ elif uniquely_mappable[0] == 1:
+ poses_start = np.append([0], poses_start)
+ poses_end = np.append(poses_end, [len(uniquely_mappable)])
+ for ind_st in range(len(poses_start)):
+ pos_st = poses_start[ind_st] + 1
+ pos_end = poses_end[ind_st] + 1
+ start_line = "fixedStep chrom={} start={} step=1 span=1\n".format(
+ chrom, pos_st)
+ out_link.write(start_line)
+ for each_pos in range(pos_st, pos_end):
+ out_link.write(str(ar_quant[each_pos]) + "\n")
+ print(
+ "Finished saving the data to {} at {}".format(
+ out_path, str(datetime.now())))
+ out_link.close()
+
+
+if __name__ == "__main__":
+ parser = argparse.ArgumentParser(description="Converts\
+ unionized uint8 outputs of umap/ubismap to bed files")
+ parser.add_argument(
+ "in_dir",
+ help="folder with <chrom>.uint8.unique.gz files")
+ parser.add_argument(
+ "out_dir",
+ help="Folder for writing the output files")
+ parser.add_argument(
+ "out_label",
+ help="File names would be kmer.<out_label>.bed.gz")
+ parser.add_argument(
+ "-C2T",
+ action="store_true",
+ help="If using converted genomes specify -C2T or -G2A")
+ parser.add_argument(
+ "-G2A",
+ action="store_true",
+ help="If using converted genomes specify -C2T or -G2A")
+ parser.add_argument(
+ "-chrsize_path",
+ default="../../chrsize.tsv",
+ help="Path to a 2 column file of chromosome and length. "
+ "By default it goes to ../../chrsize.tsv from out_dir")
+ parser.add_argument(
+ "-WriteUnique",
+ action="store_true",
+ help="If -Bismap is true and want to store the merged "
+ "uint file, specify this option")
+ parser.add_argument(
+ "-wiggle",
+ action="store_true",
+ help="If specified, will generate wiggle files "
+ "for each chromosome. Make sure to specify -job_id "
+ "or run in job array for parallel computation.")
+ parser.add_argument(
+ "-bed",
+ action="store_true",
+ help="If specified, will generate bed files that specify "
+ "all of the regions in the genome that are uniquely mappable "
+ "by each of the k-mers")
+ parser.add_argument(
+ "-kmers",
+ default=["k0"],
+ nargs="*",
+ help="Specify kmers separated by space such as: -kmers k10 k20")
+ parser.add_argument(
+ "-job_id",
+ type=int,
+ default=0,
+ help="If not using job array, specify this index "
+ "which will be used for selecting the chromosomes")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="Environmental variable for finding chromosome indices")
+ args = parser.parse_args()
+ if not args.bed and not args.wiggle:
+ raise ValueError("Please specify only one of -bed or -wiggle")
+ if args.bed and args.wiggle:
+ raise ValueError("Please specify at least one of -bed or -wiggle")
+ if not os.path.exists(args.out_dir):
+ os.makedirs(args.out_dir)
+ FileHandler = Int8Handler(args.in_dir,
+ args.out_dir, args.C2T, args.G2A,
+ args.chrsize_path)
+ job_id = args.job_id
+ PARALLEL = True
+ if job_id == 0:
+ job_id = os.environ[args.var_id]
+ if job_id == "":
+ PARALLEL = False
+ kmers = FileHandler.kmers
+ if args.kmers[0] != "k0":
+ kmers = args.kmers
+ # for kmer in kmers:
+ for kmer in kmers:
+ if args.bed:
+ print("Creating BED file")
+ FileHandler.write_beds(args.out_label,
+ kmer, args.WriteUnique)
+ elif PARALLEL and args.wiggle:
+ chrom = FileHandler.chroms[int(job_id) - 1]
+ print(
+ "Saving Wiggle using job id {}, selected {}".format(
+ job_id, chrom))
+ out_path = "{}/{}.{}.{}.MultiReadMappability.wg.gz".format(
+ args.out_dir, args.out_label, chrom, kmer)
+ uint_path = "{}/{}.uint8.unique.gz".format(
+ args.in_dir, chrom)
+ kmer_num = int(kmer.replace("k", ""))
+ FileHandler.write_as_wig(uint_path, out_path, kmer_num, chrom)
+ elif args.wiggle:
+ print("Creating wiggles for all chromosomes consequently")
+ print("This may take long...")
+ for chrom in FileHandler.chroms:
+ out_path = "{}/{}.{}.{}.MultiReadMappability.wg.gz".format(
+ args.out_dir, args.out_label, chrom, kmer)
+ uint_path = "{}/{}.uint8.unique.gz".format(
+ args.in_dir, chrom)
+ kmer_num = int(kmer.replace("k", ""))
+ FileHandler.write_as_wig(uint_path, out_path, kmer_num, chrom)
+ print(
+ "Tired of waiting? Try parallel processing "
+ "by specifying -job_id")
diff --git a/umap/unify_bowtie.py b/umap/unify_bowtie.py
new file mode 100644
index 0000000..9f7f80e
--- /dev/null
+++ b/umap/unify_bowtie.py
@@ -0,0 +1,151 @@
+from argparse import ArgumentParser
+import gzip
+import numpy as np
+import os
+import pandas as pd
+import re
+
+
+def subset_list(list_items, regex):
+ out_list = []
+ for each_item in list_items:
+ RE = re.search(regex, each_item)
+ if RE:
+ out_list.append(each_item)
+ return out_list
+
+
+class UnifyBowtie:
+ def __init__(self, bowtie_outdir, chrsize_path, job_id):
+ """Merges bowtie.gz outputs of run_bowtie
+
+ Based on outputs of run_bowtie that are saved in format
+ of <chr>.<kmer>.<job_id>.bowtie.gz, this class uses
+ a variable ID to select a particular chromosome and
+ merge the data in all of the different bowtie.gz files
+ of that chromosome.
+
+ :param bowtie_outdir: Directory with <chr>.<kmer>.<job_id>.bowtie.gz
+ :param chrsize_path: Path to 2-column file: <chr>\t<size>\n...
+ :param int job_id: A 0-based index to select chromosome
+ based on chrsize_path
+
+ :returns: Saves the output to bowtie_outdir/
+ <chr>.<kmer>.uint8.unique.gz file
+ """
+ self.bowtie_outdir = bowtie_outdir
+ self.chrsize_path = chrsize_path
+ self.ind_chr = job_id
+ self.chr_dict = self.make_chr_dict()
+ self.bowtie_to_unique()
+
+ def make_chr_dict(self):
+ """Makes a dictionary using self.chrsize_path"""
+ chr_dict = {}
+ with open(self.chrsize_path, "r") as chrsize_link:
+ for chrsize_line in chrsize_link:
+ chrom, size = chrsize_line.rstrip().split("\t")
+ chr_dict[chrom] = int(size)
+ return chr_dict
+
+ def get_mapped_positions(self, bowtie_path):
+ """Finds mapped regions in bowtie output
+
+ In a gzipped bowtie output with perfect matches,
+ filters the results to those in the forward strand
+ and saves them to an array.
+
+ Why results filtered for forward strand?
+ The results uniquely mapped
+ to the reverse strand are rare and a mistake of the
+ aligning algorithm because all of the k-mers are
+ generated from the forward strand. If match happens
+ on reverse strand, it means that the match is not the
+ only unique match (reads were generated from forward
+ strand).
+ """
+ bowtie_df = pd.read_csv(
+ bowtie_path, sep="\t",
+ compression="gzip",
+ names=["Ind", "Strand", "Chr", "Start"])
+ bowtie_df = bowtie_df[bowtie_df["Strand"] == "+"]
+ ind_ar = bowtie_df.iloc[:, 3]
+ return ind_ar
+
+ def get_other_chr_name(self, chr_name):
+ """Finds name of the reverse complement chromosome
+
+ In Bismap, we generate a set of reverse complemented
+ chromosomes to account for bisulfite conversion before
+ reverse complementation. This function finds those
+ chromosomes"""
+ new_name = chr_name
+ if "RC" in chr_name:
+ len_paths = len(
+ subset_list(
+ os.listdir(self.bowtie_outdir), chr_name))
+ if len_paths == 0:
+ new_name = chr_name + "_RC"
+ return new_name
+
+ def bowtie_to_unique(self):
+ """Wrapper method of UnifyBowtie
+
+ Uses information of bowtie.gz files to find mappability
+ of a given chromosome. Is automatically called by
+ UnifyBowtie."""
+ KMER = int(self.bowtie_outdir.split("/")[-1].split("k")[-1])
+ all_chrs = self.chr_dict.keys()
+ all_chrs.sort()
+ chrom = all_chrs[self.ind_chr]
+ size = self.chr_dict[chrom]
+ new_chr_name = self.get_other_chr_name(chrom)
+ chr_paths = ["{}/{}".format(self.bowtie_outdir, bowtie_path)
+ for bowtie_path in subset_list(
+ os.listdir(self.bowtie_outdir),
+ "{}\.".format(new_chr_name))]
+ bowtie_paths = subset_list(chr_paths, ".bowtie.gz")
+ unique_ar = np.zeros(size, dtype=np.uint8)
+ for bowtie_path in bowtie_paths:
+ mapped_indices = self.get_mapped_positions(bowtie_path)
+ for st_index in mapped_indices:
+ end_index = st_index + KMER
+ unique_ar[st_index:end_index] = 1
+ print("Done with {}".format(bowtie_path))
+ out_path = "{}/{}.k{}.uint8.unique.gz".format(
+ self.bowtie_outdir, chrom, KMER)
+ out_link = gzip.open(out_path, "wb")
+ # np.save(out_link, unique_ar)
+ out_link.write(unique_ar.tobytes())
+ # unique_ar.tofile(out_link)
+ out_link.close()
+ print("Saved {}".format(out_path))
+ print("Exiting successfully")
+
+
+if __name__ == "__main__":
+ parser = ArgumentParser(
+ description="")
+ parser.add_argument(
+ "bowtie_outdir",
+ help="Directory containing bowtie output files")
+ parser.add_argument(
+ "chrsize_path",
+ help="A file containing the order of chromosome names\
+ to consider (one chromosome name per line)")
+ parser.add_argument(
+ "-job_id",
+ default=0,
+ type=int,
+ help="If not using a cluster for submitting jobs, "
+ "specify the job_id by integer ranging from 1 to "
+ "total number of chromosomes in chrsize_path")
+ parser.add_argument(
+ "-var_id",
+ default="SGE_TASK_ID",
+ help="HPC variable name for job ID (1-based index)")
+ args = parser.parse_args()
+ job_id = args.job_id
+ if job_id == 0:
+ job_id = int(os.environ[args.var_id]) - 1
+ UnifyBowtie(args.bowtie_outdir, args.chrsize_path, job_id)
--
Alioth's /usr/local/bin/git-commit-notice on /srv/git.debian.org/git/debian-med/umap.git
More information about the debian-med-commit
mailing list