<commit_before>"""Assess transcript abundance in RNA-seq experiments using Cufflinks.

http://cufflinks.cbcb.umd.edu/manual.html
"""
import os
import tempfile

from bcbio.utils import get_in, file_exists, safe_makedir
from bcbio.distributed.transaction import file_transaction
from bcbio.pipeline import config_utils
from bcbio.provenance import do
from bcbio.rnaseq import gtf, annotate_gtf
import pandas as pd

def run(align_file, ref_file, data):
    config = data["config"]
    cmd = _get_general_options(align_file, config)
    cmd.extend(_get_no_assembly_options(ref_file, data))
    out_dir = _get_output_dir(align_file, data)
    tracking_file = os.path.join(out_dir, "genes.fpkm_tracking")
    fpkm_file = os.path.join(out_dir, data['rgnames']['sample']) + ".fpkm"
    tracking_file_isoform = os.path.join(out_dir, "isoforms.fpkm_tracking")
    fpkm_file_isoform = os.path.join(out_dir, data['rgnames']['sample']) + ".isoform.fpkm"
    if not file_exists(fpkm_file):
        with file_transaction(data, out_dir) as tmp_out_dir:
            cmd.extend(["--output-dir", tmp_out_dir])
            cmd.extend([align_file])
            cmd = map(str, cmd)
            do.run(cmd, "Cufflinks on %s." % (align_file))
        fpkm_file = gene_tracking_to_fpkm(tracking_file, fpkm_file)
        fpkm_file_isoform = gene_tracking_to_fpkm(tracking_file_isoform, fpkm_file_isoform)
    return out_dir, fpkm_file, fpkm_file_isoform

def gene_tracking_to_fpkm(tracking_file, out_file):
    """
    take a gene-level tracking file from Cufflinks and output a two column
    table with the first column as IDs and the second column as FPKM for the
    sample. combines FPKM from the same genes into one FPKM value to fix
    this bug: http://seqanswers.com/forums/showthread.php?t=5224&page=2
    """
    if file_exists(out_file):
        return out_file
    df = pd.io.parsers.read_table(tracking_file, sep="\t", header=0)
    df = df[['tracking_id', 'FPKM']]
    df = df.groupby(['tracking_id']).sum()
    df.to_csv(out_file, sep="\t", header=False, index_label=False)
    return out_file

def _get_general_options(align_file, config):
    options = []
    cufflinks = config_utils.get_program("cufflinks", config)
    options.extend([cufflinks])
    options.extend(["--num-threads", config["algorithm"].get("num_cores", 1)])
    options.extend(["--quiet"])
    options.extend(["--no-update-check"])
    options.extend(["--max-bundle-frags", 2000000])
    options.extend(_get_stranded_flag(config))
    return options

def _get_no_assembly_options(ref_file, data):
    options = []
    options.extend(["--frag-bias-correct", ref_file])
    options.extend(["--multi-read-correct"])
    options.extend(["--upper-quartile-norm"])
    gtf_file = data["genome_resources"]["rnaseq"].get("transcripts", "")
    if gtf_file:
        options.extend(["--GTF", gtf_file])
    mask_file = data["genome_resources"]["rnaseq"].get("transcripts_mask", "")
    if mask_file:
        options.extend(["--mask-file", mask_file])

    return options

def _get_stranded_flag(config):
    strand_flag = {"unstranded": "fr-unstranded",
                   "firststrand": "fr-firststrand",
                   "secondstrand": "fr-secondstrand"}
    stranded = get_in(config, ("algorithm", "strandedness"), "unstranded").lower()
    assert stranded in strand_flag, ("%s is not a valid strandedness value. "
                                     "Valid values are 'firststrand', "
                                     "'secondstrand' and 'unstranded" % (stranded))
    flag = strand_flag[stranded]
    return ["--library-type", flag]

def _get_output_dir(align_file, data, sample_dir=True):
    config = data["config"]
    name = data["rgnames"]["sample"] if sample_dir else ""
    return os.path.join(get_in(data, ("dirs", "work")), "cufflinks", name)

def assemble(bam_file, ref_file, num_cores, out_dir, data):
    out_dir = os.path.join(out_dir, data["rgnames"]["sample"])
    safe_makedir(out_dir)
    out_file = os.path.join(out_dir, data["rgnames"]["sample"], "transcripts.gtf")
    if file_exists(out_file):
        return out_file
    with file_transaction(data, out_dir) as tmp_out_dir:
        cmd = ("cufflinks --output-dir {tmp_out_dir} --num-threads {num_cores} "
               "--frag-bias-correct {ref_file} "
               "--multi-read-correct --upper-quartile-norm {bam_file}")
        cmd = cmd.format(**locals())
        do.run(cmd, "Assembling transcripts with Cufflinks using %s." % bam_file)
    return out_file

def clean_assembly(gtf_file, clean=None, dirty=None):
    """
    clean the likely garbage transcripts from the GTF file including:
    1. any novel single-exon transcripts
    2. any features with an unknown strand
    """
    base, ext = os.path.splitext(gtf_file)
    db = gtf.get_gtf_db(gtf_file, in_memory=True)
    clean = clean if clean else base + ".clean" + ext
    dirty = dirty if dirty else base + ".dirty" + ext
    if file_exists(clean):
        return clean, dirty
    with open(clean, "w") as clean_handle, open(dirty, "w") as dirty_handle:
        for gene in db.features_of_type('gene'):
            for transcript in db.children(gene, level=1):
                if is_likely_noise(db, transcript):
                    write_transcript(db, dirty_handle, transcript)
                else:
                    write_transcript(db, clean_handle, transcript)
    return clean, dirty

def write_transcript(db, handle, transcript):
    for feature in db.children(transcript):
        handle.write(str(feature) + "\n")

def is_likely_noise(db, transcript):
    if is_novel_single_exon(db, transcript):
        return True
    if strand_unknown(db, transcript):
        return True

def strand_unknown(db, transcript):
    """
    for unstranded data with novel transcripts single exon genes
    will have no strand information. single exon novel genes are also
    a source of noise in the Cufflinks assembly so this removes them
    """
    features = list(db.children(transcript))
    strand = features[0].strand
    if strand == ".":
        return True
    else:
        return False

def is_novel_single_exon(db, transcript):
    features = list(db.children(transcript))
    exons = [x for x in features if x.featuretype == "exon"]
    class_code = features[0].attributes.get("class_code", None)[0]
    if len(exons) == 1 and class_code == "u":
        return True
    return False

def fix_cufflinks_attributes(ref_gtf, merged_gtf, data, out_file=None):
    """
    replace the cufflinks gene_id and transcript_id with the
    gene_id and transcript_id from ref_gtf, where available

    """
    ref_db = gtf.get_gtf_db(ref_gtf, in_memory=True)
    merged_db = gtf.get_gtf_db(merged_gtf, in_memory=True)
    base, ext = os.path.splitext(merged_gtf)
    fixed = out_file if out_file else base + ".clean.fixed" + ext
    if file_exists(fixed):
        return fixed

    ref_tid_to_gid = {}
    for gene in ref_db.features_of_type('gene'):
        for transcript in ref_db.children(gene, level=1):
            ref_tid_to_gid[transcript.id] = gene.id

    ctid_to_cgid = {}
    ctid_to_oid = {}
    for gene in merged_db.features_of_type('gene'):
        for transcript in merged_db.children(gene, level=1):
            ctid_to_cgid[transcript.id] = gene.id
            feature = list(merged_db.children(transcript))[0]
            oid = feature.attributes.get("oId", [None])[0]
            if oid:
                ctid_to_oid[transcript.id] = oid
    cgid_to_gid = {}
    for ctid, oid in ctid_to_oid.items():
        cgid = ctid_to_cgid.get(ctid, None)
        oid = ctid_to_oid.get(ctid, None)
        gid = ref_tid_to_gid.get(oid, None) if oid else None
        if cgid and gid:
            cgid_to_gid[cgid] = gid

    with file_transaction(data, fixed) as tmp_fixed_file:
        with open(tmp_fixed_file, "w") as out_handle:
            for gene in merged_db.features_of_type('gene'):
                for transcript in merged_db.children(gene, level=1):
                    for feature in merged_db.children(transcript):
                        cgid = feature.attributes.get("gene_id", [None])[0]
                        gid = cgid_to_gid.get(cgid, None)
                        ctid = None
                        if gid:
                            feature.attributes["gene_id"][0] = gid
                            ctid = feature.attributes.get("transcript_id",
                                                          [None])[0]
                        tid = ctid_to_oid.get(ctid, None)
                        if tid:
                            feature.attributes["transcript_id"][0] = tid
                        if "nearest_ref" in feature.attributes:
                            del feature.attributes["nearest_ref"]
                        if "oId" in feature.attributes:
                            del feature.attributes["oId"]
                        out_handle.write(str(feature) + "\n")
    return fixed

def merge(assembled_gtfs, ref_file, gtf_file, num_cores, data):
    """
    run cuffmerge on a set of assembled GTF files
    """
    assembled_file = tempfile.NamedTemporaryFile(delete=False).name
    with open(assembled_file, "w") as temp_handle:
        for assembled in assembled_gtfs:
            temp_handle.write(assembled + "\n")
    out_dir = os.path.join("assembly", "cuffmerge")
    merged_file = os.path.join(out_dir, "merged.gtf")
    out_file = os.path.join(out_dir, "assembled.gtf")
    if file_exists(out_file):
        return out_file
    with file_transaction(data, out_dir) as tmp_out_dir:
        cmd = ("cuffmerge -o {tmp_out_dir} --ref-gtf {gtf_file} "
               "--num-threads {num_cores} --ref-sequence {ref_file} "
               "{assembled_file}")
        cmd = cmd.format(**locals())
        do.run(cmd, "Merging transcript assemblies with reference.")
    clean, _ = clean_assembly(merged_file)
    fixed = fix_cufflinks_attributes(gtf_file, clean, data)
    classified = annotate_gtf.annotate_novel_coding(fixed, gtf_file, ref_file)
    filtered = annotate_gtf.cleanup_transcripts(classified, gtf_file, ref_file)
    os.rename(filtered, out_file)
    return out_file
<commit_msg>Explicitly make output directory, Cufflinks won't make the whole path.<commit_after>"""Assess transcript abundance in RNA-seq experiments using Cufflinks.

http://cufflinks.cbcb.umd.edu/manual.html
"""
import os
import tempfile

from bcbio.utils import get_in, file_exists, safe_makedir
from bcbio.distributed.transaction import file_transaction
from bcbio.pipeline import config_utils
from bcbio.provenance import do
from bcbio.rnaseq import gtf, annotate_gtf
import pandas as pd

def run(align_file, ref_file, data):
    config = data["config"]
    cmd = _get_general_options(align_file, config)
    cmd.extend(_get_no_assembly_options(ref_file, data))
    out_dir = _get_output_dir(align_file, data)
    tracking_file = os.path.join(out_dir, "genes.fpkm_tracking")
    fpkm_file = os.path.join(out_dir, data['rgnames']['sample']) + ".fpkm"
    tracking_file_isoform = os.path.join(out_dir, "isoforms.fpkm_tracking")
    fpkm_file_isoform = os.path.join(out_dir, data['rgnames']['sample']) + ".isoform.fpkm"
    if not file_exists(fpkm_file):
        with file_transaction(data, out_dir) as tmp_out_dir:
            safe_makedir(tmp_out_dir)
            cmd.extend(["--output-dir", tmp_out_dir])
            cmd.extend([align_file])
            cmd = map(str, cmd)
            do.run(cmd, "Cufflinks on %s." % (align_file))
        fpkm_file = gene_tracking_to_fpkm(tracking_file, fpkm_file)
        fpkm_file_isoform = gene_tracking_to_fpkm(tracking_file_isoform, fpkm_file_isoform)
    return out_dir, fpkm_file, fpkm_file_isoform

def gene_tracking_to_fpkm(tracking_file, out_file):
    """
    take a gene-level tracking file from Cufflinks and output a two column
    table with the first column as IDs and the second column as FPKM for the
    sample. combines FPKM from the same genes into one FPKM value to fix
    this bug: http://seqanswers.com/forums/showthread.php?t=5224&page=2
    """
    if file_exists(out_file):
        return out_file
    df = pd.io.parsers.read_table(tracking_file, sep="\t", header=0)
    df = df[['tracking_id', 'FPKM']]
    df = df.groupby(['tracking_id']).sum()
    df.to_csv(out_file, sep="\t", header=False, index_label=False)
    return out_file

def _get_general_options(align_file, config):
    options = []
    cufflinks = config_utils.get_program("cufflinks", config)
    options.extend([cufflinks])
    options.extend(["--num-threads", config["algorithm"].get("num_cores", 1)])
    options.extend(["--quiet"])
    options.extend(["--no-update-check"])
    options.extend(["--max-bundle-frags", 2000000])
    options.extend(_get_stranded_flag(config))
    return options

def _get_no_assembly_options(ref_file, data):
    options = []
    options.extend(["--frag-bias-correct", ref_file])
    options.extend(["--multi-read-correct"])
    options.extend(["--upper-quartile-norm"])
    gtf_file = data["genome_resources"]["rnaseq"].get("transcripts", "")
    if gtf_file:
        options.extend(["--GTF", gtf_file])
    mask_file = data["genome_resources"]["rnaseq"].get("transcripts_mask", "")
    if mask_file:
        options.extend(["--mask-file", mask_file])

    return options

def _get_stranded_flag(config):
    strand_flag = {"unstranded": "fr-unstranded",
                   "firststrand": "fr-firststrand",
                   "secondstrand": "fr-secondstrand"}
    stranded = get_in(config, ("algorithm", "strandedness"), "unstranded").lower()
    assert stranded in strand_flag, ("%s is not a valid strandedness value. "
                                     "Valid values are 'firststrand', "
                                     "'secondstrand' and 'unstranded" % (stranded))
    flag = strand_flag[stranded]
    return ["--library-type", flag]

def _get_output_dir(align_file, data, sample_dir=True):
    config = data["config"]
    name = data["rgnames"]["sample"] if sample_dir else ""
    return os.path.join(get_in(data, ("dirs", "work")), "cufflinks", name)

def assemble(bam_file, ref_file, num_cores, out_dir, data):
    out_dir = os.path.join(out_dir, data["rgnames"]["sample"])
    safe_makedir(out_dir)
    out_file = os.path.join(out_dir, data["rgnames"]["sample"], "transcripts.gtf")
    if file_exists(out_file):
        return out_file
    with file_transaction(data, out_dir) as tmp_out_dir:
        cmd = ("cufflinks --output-dir {tmp_out_dir} --num-threads {num_cores} "
               "--frag-bias-correct {ref_file} "
               "--multi-read-correct --upper-quartile-norm {bam_file}")
        cmd = cmd.format(**locals())
        do.run(cmd, "Assembling transcripts with Cufflinks using %s." % bam_file)
    return out_file

def clean_assembly(gtf_file, clean=None, dirty=None):
    """
    clean the likely garbage transcripts from the GTF file including:
    1. any novel single-exon transcripts
    2. any features with an unknown strand
    """
    base, ext = os.path.splitext(gtf_file)
    db = gtf.get_gtf_db(gtf_file, in_memory=True)
    clean = clean if clean else base + ".clean" + ext
    dirty = dirty if dirty else base + ".dirty" + ext
    if file_exists(clean):
        return clean, dirty
    with open(clean, "w") as clean_handle, open(dirty, "w") as dirty_handle:
        for gene in db.features_of_type('gene'):
            for transcript in db.children(gene, level=1):
                if is_likely_noise(db, transcript):
                    write_transcript(db, dirty_handle, transcript)
                else:
                    write_transcript(db, clean_handle, transcript)
    return clean, dirty

def write_transcript(db, handle, transcript):
    for feature in db.children(transcript):
        handle.write(str(feature) + "\n")

def is_likely_noise(db, transcript):
    if is_novel_single_exon(db, transcript):
        return True
    if strand_unknown(db, transcript):
        return True

def strand_unknown(db, transcript):
    """
    for unstranded data with novel transcripts single exon genes
    will have no strand information. single exon novel genes are also
    a source of noise in the Cufflinks assembly so this removes them
    """
    features = list(db.children(transcript))
    strand = features[0].strand
    if strand == ".":
        return True
    else:
        return False

def is_novel_single_exon(db, transcript):
    features = list(db.children(transcript))
    exons = [x for x in features if x.featuretype == "exon"]
    class_code = features[0].attributes.get("class_code", None)[0]
    if len(exons) == 1 and class_code == "u":
        return True
    return False

def fix_cufflinks_attributes(ref_gtf, merged_gtf, data, out_file=None):
    """
    replace the cufflinks gene_id and transcript_id with the
    gene_id and transcript_id from ref_gtf, where available

    """
    ref_db = gtf.get_gtf_db(ref_gtf, in_memory=True)
    merged_db = gtf.get_gtf_db(merged_gtf, in_memory=True)
    base, ext = os.path.splitext(merged_gtf)
    fixed = out_file if out_file else base + ".clean.fixed" + ext
    if file_exists(fixed):
        return fixed

    ref_tid_to_gid = {}
    for gene in ref_db.features_of_type('gene'):
        for transcript in ref_db.children(gene, level=1):
            ref_tid_to_gid[transcript.id] = gene.id

    ctid_to_cgid = {}
    ctid_to_oid = {}
    for gene in merged_db.features_of_type('gene'):
        for transcript in merged_db.children(gene, level=1):
            ctid_to_cgid[transcript.id] = gene.id
            feature = list(merged_db.children(transcript))[0]
            oid = feature.attributes.get("oId", [None])[0]
            if oid:
                ctid_to_oid[transcript.id] = oid
    cgid_to_gid = {}
    for ctid, oid in ctid_to_oid.items():
        cgid = ctid_to_cgid.get(ctid, None)
        oid = ctid_to_oid.get(ctid, None)
        gid = ref_tid_to_gid.get(oid, None) if oid else None
        if cgid and gid:
            cgid_to_gid[cgid] = gid

    with file_transaction(data, fixed) as tmp_fixed_file:
        with open(tmp_fixed_file, "w") as out_handle:
            for gene in merged_db.features_of_type('gene'):
                for transcript in merged_db.children(gene, level=1):
                    for feature in merged_db.children(transcript):
                        cgid = feature.attributes.get("gene_id", [None])[0]
                        gid = cgid_to_gid.get(cgid, None)
                        ctid = None
                        if gid:
                            feature.attributes["gene_id"][0] = gid
                            ctid = feature.attributes.get("transcript_id",
                                                          [None])[0]
                        tid = ctid_to_oid.get(ctid, None)
                        if tid:
                            feature.attributes["transcript_id"][0] = tid
                        if "nearest_ref" in feature.attributes:
                            del feature.attributes["nearest_ref"]
                        if "oId" in feature.attributes:
                            del feature.attributes["oId"]
                        out_handle.write(str(feature) + "\n")
    return fixed

def merge(assembled_gtfs, ref_file, gtf_file, num_cores, data):
    """
    run cuffmerge on a set of assembled GTF files
    """
    assembled_file = tempfile.NamedTemporaryFile(delete=False).name
    with open(assembled_file, "w") as temp_handle:
        for assembled in assembled_gtfs:
            temp_handle.write(assembled + "\n")
    out_dir = os.path.join("assembly", "cuffmerge")
    merged_file = os.path.join(out_dir, "merged.gtf")
    out_file = os.path.join(out_dir, "assembled.gtf")
    if file_exists(out_file):
        return out_file
    with file_transaction(data, out_dir) as tmp_out_dir:
        cmd = ("cuffmerge -o {tmp_out_dir} --ref-gtf {gtf_file} "
               "--num-threads {num_cores} --ref-sequence {ref_file} "
               "{assembled_file}")
        cmd = cmd.format(**locals())
        do.run(cmd, "Merging transcript assemblies with reference.")
    clean, _ = clean_assembly(merged_file)
    fixed = fix_cufflinks_attributes(gtf_file, clean, data)
    classified = annotate_gtf.annotate_novel_coding(fixed, gtf_file, ref_file)
    filtered = annotate_gtf.cleanup_transcripts(classified, gtf_file, ref_file)
    os.rename(filtered, out_file)
    return out_file
<|endoftext|>


<commit_before>#!/usr/bin/env python3
"""Bcl2fastq QC checks

We are running bcl2fastq per MUX, hence one demux html input
corresponds to one MUX. Since a single lane cannot hold more than one
MUX, the lane info contained in one html is complete. In other words,
all/all/all/lane.html contains info for all lanes in which
this mux was (and includes samples in this MUX plus
'undetermined'). Since MUXs cannot be shared in a lane it follows this
file contains all info for the resp. lanes.

However the flowcell info is incomplete and only reflects data in the
listed lanes. To get the full flowcell info demux htmls from all MUXes
have to be summed up.

'Undetermined' specific info is separately listed in
default/Undetermined/unknown/lane.html

"""

#--- standard library imports
#
import sys
import os
import glob
import re
import pprint
from collections import OrderedDict
import argparse
import logging

#--- third-party imports
#
import yaml

#--- project specific imports
#
from html_table_parser import HTMLTableParser
# add lib dir for this pipeline installation to PYTHONPATH
LIB_PATH = os.path.abspath(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "lib"))
if LIB_PATH not in sys.path:
    sys.path.insert(0, LIB_PATH)
from config import bcl2fastq_qc_conf as config
from pipelines import is_devel_version
from pipelines import email_for_user
from pipelines import send_mail
from pipelines import path_to_url

__author__ = "Andreas Wilm"
__email__ = "wilma@gis.a-star.edu.sg"
__copyright__ = "2017 Genome Institute of Singapore"
__license__ = "The MIT License (MIT)"

# global logger
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
    '[{asctime}] {levelname:8s} {filename} {message}', style='{'))
logger.addHandler(handler)

DEMUX_HTML_FILE_PATTERN = r'.*Project_(\w+)/html/([\w-]+)/\w+/\w+/\w+/lane.html'

def get_machine_type_from_run_num(run_num):
    """these are the values to be used in config for machine dependent settings"""
    id_to_machine = {
        'MS001': 'miseq',
        'NS001': 'nextseq',
        'HS001': 'hiseq 2500 rapid',
        'HS002': 'hiseq 2500',
        'HS003': 'hiseq 2500',
        'HS004': 'hiseq 2500',
        'HS005': 'macrogen',
        'HS006': 'hiseq 4000',
        'HS007': 'hiseq 4000',
    }
    machine_id = run_num.split('-')[0]
    machine_type = id_to_machine[machine_id]
    return machine_type

def email_qcfails(subject, body):
    """email qc failures
    """
    if is_devel_version():
        toaddr = email_for_user()
        ccaddr = None
    else:
        toaddr = config['emails']
        ccaddr = "rpd@gis.a-star.edu.sg"

    send_mail(subject, body, toaddr=toaddr, ccaddr=ccaddr,
              pass_exception=False)

def htmlparser_demux_table_to_dict(table_in, decimal_mark=".", thousands_sep=","):
    """cleans raw bcl2fastq html table formatting as created by htmlparser
    and converts to OrderedDict using sequential row numbers as first
    key (i.e. row[0][key] = value)
    """

    assert decimal_mark != thousands_sep
    table_out = OrderedDict()
    header = table_in[0]
    for row_no, row in enumerate(table_in[1:]):
        table_out[row_no] = OrderedDict()
        for k, v in OrderedDict(zip(header, row)).items():
            #print("RAW", k, v)
            if thousands_sep:
                v = v.replace(thousands_sep, "")
            if v == "NaN":
                v = None
            elif decimal_mark in v:
                v = float(v)
            elif len(v):
                v = int(v)
            else:
                v = None
            table_out[row_no][k] = v
            #print(k, ":", v)
        #print()
    return table_out

def process_demux_html(html_file):
    """returns flowcell summary and lane summary as dicts"""

    with open(html_file, encoding='utf-8') as fh:
        html_data = fh.read()
    p = HTMLTableParser()
    p.feed(html_data)

    assert len(p.tables) == 3, (
        "Parsing tables from {} failed".format(html_file))
    flowcell_id = p.tables[0][0][0].split()[0]# html parsing sucks
    flowcell_htmlparser_table = p.tables[1]
    lane_htmlparser_table = p.tables[2]

    # clean up flowcell table
    #
    flowcell_table = htmlparser_demux_table_to_dict(flowcell_htmlparser_table)
    # htmlparser_demux_table_to_dict() creates rows which don't make
    # sense for flowcell, so we rename the sole row 0 to flowcell_id
    assert len(flowcell_table) == 1
    flowcell_table[flowcell_id] = flowcell_table.pop(0)

    # clean up lane table
    #
    lane_table = htmlparser_demux_table_to_dict(lane_htmlparser_table)
    # htmlparser_demux_table_to_dict() creates sequentially numbered
    # rows but we want to use the lane numbers as keys. has to happen
    # in two iterations, to avoid overwriting existing keys
    row_idxs = list(lane_table.keys())
    for row_idx in row_idxs:# can't mutate during key iteration
        d = lane_table.pop(row_idx)
        k = "Lane " + str(d['Lane'])
        del d['Lane']
        lane_table[k] = d
    # now convert back to int/lane
    row_idxs = list(lane_table.keys())
    for row_idx in row_idxs:# can't mutate during key iteration
        d = lane_table.pop(row_idx)
        assert row_idx.startswith("Lane ")
        k = int(row_idx.split()[1])
        lane_table[k] = d

    return flowcell_table, lane_table

def gather_demux_stats(demux_html_files):
    """Parse all demux html stats, parse and combine (logically
    representing one run). Teturn flowcell summary table and lane
    summary table as two dicts()
    """

    flowcell_table = OrderedDict()
    lane_table = OrderedDict()

    # extract tables from all demux_html_files
    #
    for html_file in demux_html_files:
        m = re.search(DEMUX_HTML_FILE_PATTERN, html_file)
        if not m or not len(m.groups()) == 2:
            logger.fatal("html file name (%s) doesn't match"
                         " expected pattern (%s)\n",
                         html_file, DEMUX_HTML_FILE_PATTERN)
            sys.exit(1)

        #mux_id = m.groups()[0]
        flowcell_id = m.groups()[1]
        logger.info("Reading %s", html_file)
        this_flowcell_table, this_lane_table = process_demux_html(html_file)
        # pure paranoia test
        assert [flowcell_id] == list(this_flowcell_table.keys())

        for lane in this_lane_table.keys():
            assert lane not in lane_table.keys(), (
                "Seen lane {} before, i.e. html files are not from same run".format(lane))
        lane_table.update(this_lane_table)

        if not flowcell_id in flowcell_table:
            flowcell_table = this_flowcell_table
        else:
            for k, v in this_flowcell_table[flowcell_id].items():
                flowcell_table[flowcell_id][k] += v

    return flowcell_table, lane_table

def run_qc_checks(project_dirs, machine_type):
    """main function"""
    qcfails = []
    assert len(project_dirs) >= 1

    # determine all all/all/all/lane.html in project subdirs of given demux_dir
    #
    demux_html_files = []
    for d in project_dirs:
        g = os.path.join(d, 'html/*/all/all/all/lane.html')
        f = glob.glob(g)
        assert len(f) == 1, (
            "Was expecting exactly one matching demux html"
            " but found {} for glob {}".format(f, g))
        demux_html_files.extend(f)
    flowcell_table, lane_table = gather_demux_stats(demux_html_files)
    logger.debug("# Combined Flowcell Summary")
    logger.debug(pprint.pformat(flowcell_table))
    logger.debug("# Combined per Lane")
    logger.debug(pprint.pformat(lane_table))

    for lane, values in lane_table.items():
        # test: perfect barcode
        v = values['% Perfect barcode']
        l = config['min-percent-perfect-barcode']
        if v is not None:# muxed input
            if v < float(l):
                qcfails.append(
                    "Percent perfect barcode under limit"
                    " ({} < {}) for lane {}".format(v, l, lane))

        # test: Q30 bases
        v = values['% >= Q30 bases']
        l = config['min-percent-q30-bases'][machine_type]
        if v < float(l):
            qcfails.append(
                "Percent Q30 bases under limit"
                " ({} < {}) for lane {}".format(v, l, lane))

        # test: yield
        v = values['Yield (Mbases)'] / 1000.0
        l = config['min-lane-yield-gb'][machine_type]
        if v < float(l):
            qcfails.append(
                "Yield under limit"
                " ({} < {}) for lane {}".format(v, l, lane))

        # test: pf
        v = int(values['PF Clusters'] / 1000000.0)
        l = config['min-pf-cluster-in-mil'][machine_type]
        if v < float(l):
            qcfails.append(
                "PF clusters under limit"
                " ({} < {}) for lane {}".format(v, l, lane))

    # info about 'undetermined' sits elsewhere (only makes sense if demuxed)
    #
    undet_demux_html_files = []
    for d in project_dirs:
        g = os.path.join(d, 'html/*/default/Undetermined/all/lane.html')
        f = glob.glob(g)
        if f:
            # otherwise probably non-muxed
            undet_demux_html_files.extend(f)
    # for non-demuxed input (empty input files) everything below still works as expected
    _, undet_lane_table = gather_demux_stats(undet_demux_html_files)
    logger.debug("# Undetermined combined per Lane")
    logger.debug(pprint.pformat(undet_lane_table))

    # test: undetermined reads
    #
    for lane, values in undet_lane_table.items():
        v = values['% of the lane']
        l = config['max-percent-undetermined']
        if v is not None:# muxed input
            if v > float(l):
                qcfails.append(
                    "Percent undetermined reads exceeding limits"
                    " ({} > {}) for lane {}".format(v, l, lane))
    return qcfails

def main():
    """main function
    """

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-d', "--bcl2fastq-dir", required=True,
                        help="bcl2fastq directory (containing a conf.yaml)")
    parser.add_argument('--no-mail', action='store_true',
                        help="Don't send email on detected failures")
    parser.add_argument('-v', '--verbose', action='count', default=0,
                        help="Increase verbosity")
    parser.add_argument('-q', '--quiet', action='count', default=0,
                        help="Decrease verbosity")
    args = parser.parse_args()

    # Repeateable -v and -q for setting logging level.
    # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/
    # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4
    # script -vv -> DEBUG
    # script -v -> INFO
    # script -> WARNING
    # script -q -> ERROR
    # script -qq -> CRITICAL
    # script -qqq -> no logging at all
    logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose)

    assert os.path.isdir(args.bcl2fastq_dir)
    conf_file = os.path.join(args.bcl2fastq_dir, 'conf.yaml')
    if not os.path.exists(conf_file):
        logger.fatal("Expected config file missing: %s", conf_file)
        sys.exit(1)
    with open(conf_file) as fh:
        bcl2fastq_cfg = yaml.safe_load(fh)

    run_num = bcl2fastq_cfg["run_num"]
    machine_type = get_machine_type_from_run_num(run_num)

    project_dirs = []
    for _, mux_info in bcl2fastq_cfg["units"].items():
        d = os.path.join(args.bcl2fastq_dir, "out", mux_info['mux_dir'])
        if not os.path.exists(d):
            logger.warning("Ignoring missing directory %s", d)
        else:
            project_dirs.append(d)

    if len(project_dirs) == 0:
        logger.error("Exiting because no project directories where found in %s", args.bcl2fastq_dir)
        sys.exit(1)

    qcfails = run_qc_checks(project_dirs, machine_type)

    if qcfails:
        subject = "bcl2fastq QC checks failed for {} ({}):".format(
            run_num, args.bcl2fastq_dir)
        body = "The following " + subject
        for f in qcfails:
            body += "\n- {}".format(f)
        body += "\nPlease double-check here: {}\n".format(
            path_to_url(args.bcl2fastq_dir))
        body += "QC_FAILED"# signal for callers
        print(subject + "\n" + body)

        if not args.no_mail:
            email_qcfails(subject, body)
    else:
        print("QC checks completed. No tests failed")
        print("QC SUCCESS")# signal for callers

if __name__ == '__main__':
    main()
<commit_msg>bcl2fastq_qc: fixed access to wring config key for emails<commit_after>#!/usr/bin/env python3
"""Bcl2fastq QC checks

We are running bcl2fastq per MUX, hence one demux html input
corresponds to one MUX. Since a single lane cannot hold more than one
MUX, the lane info contained in one html is complete. In other words,
all/all/all/lane.html contains info for all lanes in which
this mux was (and includes samples in this MUX plus
'undetermined'). Since MUXs cannot be shared in a lane it follows this
file contains all info for the resp. lanes.

However the flowcell info is incomplete and only reflects data in the
listed lanes. To get the full flowcell info demux htmls from all MUXes
have to be summed up.

'Undetermined' specific info is separately listed in
default/Undetermined/unknown/lane.html

"""

#--- standard library imports
#
import sys
import os
import glob
import re
import pprint
from collections import OrderedDict
import argparse
import logging

#--- third-party imports
#
import yaml

#--- project specific imports
#
from html_table_parser import HTMLTableParser
# add lib dir for this pipeline installation to PYTHONPATH
LIB_PATH = os.path.abspath(
    os.path.join(os.path.dirname(os.path.realpath(__file__)), "..", "lib"))
if LIB_PATH not in sys.path:
    sys.path.insert(0, LIB_PATH)
from config import bcl2fastq_qc_conf as config
from pipelines import is_devel_version
from pipelines import email_for_user
from pipelines import send_mail
from pipelines import path_to_url

__author__ = "Andreas Wilm"
__email__ = "wilma@gis.a-star.edu.sg"
__copyright__ = "2017 Genome Institute of Singapore"
__license__ = "The MIT License (MIT)"

# global logger
logger = logging.getLogger(__name__)
handler = logging.StreamHandler()
handler.setFormatter(logging.Formatter(
    '[{asctime}] {levelname:8s} {filename} {message}', style='{'))
logger.addHandler(handler)

DEMUX_HTML_FILE_PATTERN = r'.*Project_(\w+)/html/([\w-]+)/\w+/\w+/\w+/lane.html'

def get_machine_type_from_run_num(run_num):
    """these are the values to be used in config for machine dependent settings"""
    id_to_machine = {
        'MS001': 'miseq',
        'NS001': 'nextseq',
        'HS001': 'hiseq 2500 rapid',
        'HS002': 'hiseq 2500',
        'HS003': 'hiseq 2500',
        'HS004': 'hiseq 2500',
        'HS005': 'macrogen',
        'HS006': 'hiseq 4000',
        'HS007': 'hiseq 4000',
    }
    machine_id = run_num.split('-')[0]
    machine_type = id_to_machine[machine_id]
    return machine_type

def email_qcfails(subject, body):
    """email qc failures
    """
    if is_devel_version():
        toaddr = email_for_user()
        ccaddr = None
    else:
        toaddr = config['email']
        ccaddr = "rpd@gis.a-star.edu.sg"

    send_mail(subject, body, toaddr=toaddr, ccaddr=ccaddr,
              pass_exception=False)

def htmlparser_demux_table_to_dict(table_in, decimal_mark=".", thousands_sep=","):
    """cleans raw bcl2fastq html table formatting as created by htmlparser
    and converts to OrderedDict using sequential row numbers as first
    key (i.e. row[0][key] = value)
    """

    assert decimal_mark != thousands_sep
    table_out = OrderedDict()
    header = table_in[0]
    for row_no, row in enumerate(table_in[1:]):
        table_out[row_no] = OrderedDict()
        for k, v in OrderedDict(zip(header, row)).items():
            #print("RAW", k, v)
            if thousands_sep:
                v = v.replace(thousands_sep, "")
            if v == "NaN":
                v = None
            elif decimal_mark in v:
                v = float(v)
            elif len(v):
                v = int(v)
            else:
                v = None
            table_out[row_no][k] = v
            #print(k, ":", v)
        #print()
    return table_out

def process_demux_html(html_file):
    """returns flowcell summary and lane summary as dicts"""

    with open(html_file, encoding='utf-8') as fh:
        html_data = fh.read()
    p = HTMLTableParser()
    p.feed(html_data)

    assert len(p.tables) == 3, (
        "Parsing tables from {} failed".format(html_file))
    flowcell_id = p.tables[0][0][0].split()[0]# html parsing sucks
    flowcell_htmlparser_table = p.tables[1]
    lane_htmlparser_table = p.tables[2]

    # clean up flowcell table
    #
    flowcell_table = htmlparser_demux_table_to_dict(flowcell_htmlparser_table)
    # htmlparser_demux_table_to_dict() creates rows which don't make
    # sense for flowcell, so we rename the sole row 0 to flowcell_id
    assert len(flowcell_table) == 1
    flowcell_table[flowcell_id] = flowcell_table.pop(0)

    # clean up lane table
    #
    lane_table = htmlparser_demux_table_to_dict(lane_htmlparser_table)
    # htmlparser_demux_table_to_dict() creates sequentially numbered
    # rows but we want to use the lane numbers as keys. has to happen
    # in two iterations, to avoid overwriting existing keys
    row_idxs = list(lane_table.keys())
    for row_idx in row_idxs:# can't mutate during key iteration
        d = lane_table.pop(row_idx)
        k = "Lane " + str(d['Lane'])
        del d['Lane']
        lane_table[k] = d
    # now convert back to int/lane
    row_idxs = list(lane_table.keys())
    for row_idx in row_idxs:# can't mutate during key iteration
        d = lane_table.pop(row_idx)
        assert row_idx.startswith("Lane ")
        k = int(row_idx.split()[1])
        lane_table[k] = d

    return flowcell_table, lane_table

def gather_demux_stats(demux_html_files):
    """Parse all demux html stats, parse and combine (logically
    representing one run). Teturn flowcell summary table and lane
    summary table as two dicts()
    """

    flowcell_table = OrderedDict()
    lane_table = OrderedDict()

    # extract tables from all demux_html_files
    #
    for html_file in demux_html_files:
        m = re.search(DEMUX_HTML_FILE_PATTERN, html_file)
        if not m or not len(m.groups()) == 2:
            logger.fatal("html file name (%s) doesn't match"
                         " expected pattern (%s)\n",
                         html_file, DEMUX_HTML_FILE_PATTERN)
            sys.exit(1)

        #mux_id = m.groups()[0]
        flowcell_id = m.groups()[1]
        logger.info("Reading %s", html_file)
        this_flowcell_table, this_lane_table = process_demux_html(html_file)
        # pure paranoia test
        assert [flowcell_id] == list(this_flowcell_table.keys())

        for lane in this_lane_table.keys():
            assert lane not in lane_table.keys(), (
                "Seen lane {} before, i.e. html files are not from same run".format(lane))
        lane_table.update(this_lane_table)

        if not flowcell_id in flowcell_table:
            flowcell_table = this_flowcell_table
        else:
            for k, v in this_flowcell_table[flowcell_id].items():
                flowcell_table[flowcell_id][k] += v

    return flowcell_table, lane_table

def run_qc_checks(project_dirs, machine_type):
    """main function"""
    qcfails = []
    assert len(project_dirs) >= 1

    # determine all all/all/all/lane.html in project subdirs of given demux_dir
    #
    demux_html_files = []
    for d in project_dirs:
        g = os.path.join(d, 'html/*/all/all/all/lane.html')
        f = glob.glob(g)
        assert len(f) == 1, (
            "Was expecting exactly one matching demux html"
            " but found {} for glob {}".format(f, g))
        demux_html_files.extend(f)
    flowcell_table, lane_table = gather_demux_stats(demux_html_files)
    logger.debug("# Combined Flowcell Summary")
    logger.debug(pprint.pformat(flowcell_table))
    logger.debug("# Combined per Lane")
    logger.debug(pprint.pformat(lane_table))

    for lane, values in lane_table.items():
        # test: perfect barcode
        v = values['% Perfect barcode']
        l = config['min-percent-perfect-barcode']
        if v is not None:# muxed input
            if v < float(l):
                qcfails.append(
                    "Percent perfect barcode under limit"
                    " ({} < {}) for lane {}".format(v, l, lane))

        # test: Q30 bases
        v = values['% >= Q30 bases']
        l = config['min-percent-q30-bases'][machine_type]
        if v < float(l):
            qcfails.append(
                "Percent Q30 bases under limit"
                " ({} < {}) for lane {}".format(v, l, lane))

        # test: yield
        v = values['Yield (Mbases)'] / 1000.0
        l = config['min-lane-yield-gb'][machine_type]
        if v < float(l):
            qcfails.append(
                "Yield under limit"
                " ({} < {}) for lane {}".format(v, l, lane))

        # test: pf
        v = int(values['PF Clusters'] / 1000000.0)
        l = config['min-pf-cluster-in-mil'][machine_type]
        if v < float(l):
            qcfails.append(
                "PF clusters under limit"
                " ({} < {}) for lane {}".format(v, l, lane))

    # info about 'undetermined' sits elsewhere (only makes sense if demuxed)
    #
    undet_demux_html_files = []
    for d in project_dirs:
        g = os.path.join(d, 'html/*/default/Undetermined/all/lane.html')
        f = glob.glob(g)
        if f:
            # otherwise probably non-muxed
            undet_demux_html_files.extend(f)
    # for non-demuxed input (empty input files) everything below still works as expected
    _, undet_lane_table = gather_demux_stats(undet_demux_html_files)
    logger.debug("# Undetermined combined per Lane")
    logger.debug(pprint.pformat(undet_lane_table))

    # test: undetermined reads
    #
    for lane, values in undet_lane_table.items():
        v = values['% of the lane']
        l = config['max-percent-undetermined']
        if v is not None:# muxed input
            if v > float(l):
                qcfails.append(
                    "Percent undetermined reads exceeding limits"
                    " ({} > {}) for lane {}".format(v, l, lane))
    return qcfails

def main():
    """main function
    """

    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument('-d', "--bcl2fastq-dir", required=True,
                        help="bcl2fastq directory (containing a conf.yaml)")
    parser.add_argument('--no-mail', action='store_true',
                        help="Don't send email on detected failures")
    parser.add_argument('-v', '--verbose', action='count', default=0,
                        help="Increase verbosity")
    parser.add_argument('-q', '--quiet', action='count', default=0,
                        help="Decrease verbosity")
    args = parser.parse_args()

    # Repeateable -v and -q for setting logging level.
    # See https://www.reddit.com/r/Python/comments/3nctlm/what_python_tools_should_i_be_using_on_every/
    # and https://gist.github.com/andreas-wilm/b6031a84a33e652680d4
    # script -vv -> DEBUG
    # script -v -> INFO
    # script -> WARNING
    # script -q -> ERROR
    # script -qq -> CRITICAL
    # script -qqq -> no logging at all
    logger.setLevel(logging.WARN + 10*args.quiet - 10*args.verbose)

    assert os.path.isdir(args.bcl2fastq_dir)
    conf_file = os.path.join(args.bcl2fastq_dir, 'conf.yaml')
    if not os.path.exists(conf_file):
        logger.fatal("Expected config file missing: %s", conf_file)
        sys.exit(1)
    with open(conf_file) as fh:
        bcl2fastq_cfg = yaml.safe_load(fh)

    run_num = bcl2fastq_cfg["run_num"]
    machine_type = get_machine_type_from_run_num(run_num)

    project_dirs = []
    for _, mux_info in bcl2fastq_cfg["units"].items():
        d = os.path.join(args.bcl2fastq_dir, "out", mux_info['mux_dir'])
        if not os.path.exists(d):
            logger.warning("Ignoring missing directory %s", d)
        else:
            project_dirs.append(d)

    if len(project_dirs) == 0:
        logger.error("Exiting because no project directories where found in %s", args.bcl2fastq_dir)
        sys.exit(1)

    qcfails = run_qc_checks(project_dirs, machine_type)

    if qcfails:
        subject = "bcl2fastq QC checks failed for {} ({}):".format(
            run_num, args.bcl2fastq_dir)
        body = "The following " + subject
        for f in qcfails:
            body += "\n- {}".format(f)
        body += "\nPlease double-check here: {}\n".format(
            path_to_url(args.bcl2fastq_dir))
        body += "QC_FAILED"# signal for callers
        print(subject + "\n" + body)

        if not args.no_mail:
            email_qcfails(subject, body)
    else:
        print("QC checks completed. No tests failed")
        print("QC SUCCESS")# signal for callers

if __name__ == '__main__':
    main()
<|endoftext|>


<commit_before>#-*- coding: utf-8 -*-
"""
@file
@brief Defines a very small set of modules.
"""
import sys
from ..installhelper.module_install import ModuleInstall

def minimal_set():
    """
    list of modules to add to python to get a minimal python
    """
    names = ["pipdeptree"
                "virtualenv",
                "six",
                "wheel",
                "pep8",
                "autopep8",
                "mccabe",
                "pyflakes",
                "flake8",
                'markupsafe',
                "psutil",
    ]

    if sys.platform.startswith("win"):
        mod.append("pywin32")
        mod.append("winshell"
        mod.append("pythonnet")

    from . import find_module_install

    return [find_module_install(_) for _ in mod if _ is not None]
<commit_msg>fix syntax error<commit_after>#-*- coding: utf-8 -*-
"""
@file
@brief Defines a very small set of modules.
"""
import sys
from ..installhelper.module_install import ModuleInstall

def minimal_set():
    """
    list of modules to add to python to get a minimal python
    """
    names = ["pipdeptree"
                "virtualenv",
                "six",
                "wheel",
                "pep8",
                "autopep8",
                "mccabe",
                "pyflakes",
                "flake8",
                'markupsafe',
                "psutil",
    ]

    if sys.platform.startswith("win"):
        mod.append("pywin32")
        mod.append("winshell")
        mod.append("pythonnet")

    from . import find_module_install

    return [find_module_install(_) for _ in mod if _ is not None]
<|endoftext|>


<commit_before>"""Synchronization functions.

File- and mutex-based mutual exclusion synchronizers are provided,
as well as a name-based mutex which locks within an application
based on a string name.

"""
import errno
import os
import sys
import tempfile

try:
    import threading as _threading
except ImportError:
    import dummy_threading as _threading

# check for fcntl module
try:
    sys.getwindowsversion()
    has_flock = False
except:
    try:
        import fcntl
        has_flock = True
    except ImportError:
        has_flock = False

from beaker import util
from beaker.exceptions import LockError

__all__ = ["file_synchronizer", "mutex_synchronizer", "null_synchronizer",
            "NameLock", "_threading"]

class NameLock(object):
    """a proxy for an RLock object that is stored in a name based
    registry.

    Multiple threads can get a reference to the same RLock based on the
    name alone, and synchronize operations related to that name.

    """
    locks = util.WeakValuedRegistry()

    class NLContainer(object):
        def __init__(self, reentrant):
            if reentrant:
                self.lock = _threading.RLock()
            else:
                self.lock = _threading.Lock()

        def __call__(self):
            return self.lock

    def __init__(self, identifier=None, reentrant=False):
        if identifier is None:
            self._lock = NameLock.NLContainer(reentrant)
        else:
            self._lock = NameLock.locks.get(identifier, NameLock.NLContainer,
                                            reentrant)

    def acquire(self, wait=True):
        return self._lock().acquire(wait)

    def release(self):
        self._lock().release()

_synchronizers = util.WeakValuedRegistry()

def _synchronizer(identifier, cls, **kwargs):
    return _synchronizers.sync_get((identifier, cls), cls, identifier, **kwargs)

def file_synchronizer(identifier, **kwargs):
    if not has_flock or 'lock_dir' not in kwargs:
        return mutex_synchronizer(identifier)
    else:
        return _synchronizer(identifier, FileSynchronizer, **kwargs)

def mutex_synchronizer(identifier, **kwargs):
    return _synchronizer(identifier, ConditionSynchronizer, **kwargs)

class null_synchronizer(object):
    """A 'null' synchronizer, which provides the :class:`.SynchronizerImpl` interface
    without any locking.

    """
    def acquire_write_lock(self, wait=True):
        return True

    def acquire_read_lock(self):
        pass

    def release_write_lock(self):
        pass

    def release_read_lock(self):
        pass
    acquire = acquire_write_lock
    release = release_write_lock

class SynchronizerImpl(object):
    """Base class for a synchronization object that allows
    multiple readers, single writers.

    """
    def __init__(self):
        self._state = util.ThreadLocal()

    class SyncState(object):
        __slots__ = 'reentrantcount', 'writing', 'reading'

        def __init__(self):
            self.reentrantcount = 0
            self.writing = False
            self.reading = False

    def state(self):
        if not self._state.has():
            state = SynchronizerImpl.SyncState()
            self._state.put(state)
            return state
        else:
            return self._state.get()
    state = property(state)

    def release_read_lock(self):
        state = self.state

        if state.writing:
            raise LockError("lock is in writing state")
        if not state.reading:
            raise LockError("lock is not in reading state")

        if state.reentrantcount == 1:
            self.do_release_read_lock()
            state.reading = False

        state.reentrantcount -= 1

    def acquire_read_lock(self, wait=True):
        state = self.state

        if state.writing:
            raise LockError("lock is in writing state")

        if state.reentrantcount == 0:
            x = self.do_acquire_read_lock(wait)
            if (wait or x):
                state.reentrantcount += 1
                state.reading = True
            return x
        elif state.reading:
            state.reentrantcount += 1
            return True

    def release_write_lock(self):
        state = self.state

        if state.reading:
            raise LockError("lock is in reading state")
        if not state.writing:
            raise LockError("lock is not in writing state")

        if state.reentrantcount == 1:
            self.do_release_write_lock()
            state.writing = False

        state.reentrantcount -= 1

    release = release_write_lock

    def acquire_write_lock(self, wait=True):
        state = self.state

        if state.reading:
            raise LockError("lock is in reading state")

        if state.reentrantcount == 0:
            x = self.do_acquire_write_lock(wait)
            if (wait or x):
                state.reentrantcount += 1
                state.writing = True
            return x
        elif state.writing:
            state.reentrantcount += 1
            return True

    acquire = acquire_write_lock

    def do_release_read_lock(self):
        raise NotImplementedError()

    def do_acquire_read_lock(self, wait):
        raise NotImplementedError()

    def do_release_write_lock(self):
        raise NotImplementedError()

    def do_acquire_write_lock(self, wait):
        raise NotImplementedError()

class FileSynchronizer(SynchronizerImpl):
    """A synchronizer which locks using flock().

    """
    def __init__(self, identifier, lock_dir):
        super(FileSynchronizer, self).__init__()
        self._filedescriptor = util.ThreadLocal()

        if lock_dir is None:
            lock_dir = tempfile.gettempdir()
        else:
            lock_dir = lock_dir

        self.filename = util.encoded_path(
                            lock_dir,
                            [identifier],
                            extension='.lock'
                        )
        self.lock_dir = os.path.dirname(self.filename)

    def _filedesc(self):
        return self._filedescriptor.get()
    _filedesc = property(_filedesc)

    def _ensuredir(self):
        if not os.path.exists(self.lock_dir):
            util.verify_directory(self.lock_dir)

    def _open(self, mode):
        filedescriptor = self._filedesc
        if filedescriptor is None:
            self._ensuredir()
            filedescriptor = os.open(self.filename, mode)
            self._filedescriptor.put(filedescriptor)
        return filedescriptor

    def do_acquire_read_lock(self, wait):
        filedescriptor = self._open(os.O_CREAT | os.O_RDONLY)
        if not wait:
            try:
                fcntl.flock(filedescriptor, fcntl.LOCK_SH | fcntl.LOCK_NB)
                return True
            except IOError:
                os.close(filedescriptor)
                self._filedescriptor.remove()
                return False
        else:
            fcntl.flock(filedescriptor, fcntl.LOCK_SH)
            return True

    def do_acquire_write_lock(self, wait):
        filedescriptor = self._open(os.O_CREAT | os.O_WRONLY)
        if not wait:
            try:
                fcntl.flock(filedescriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
                return True
            except IOError:
                os.close(filedescriptor)
                self._filedescriptor.remove()
                return False
        else:
            fcntl.flock(filedescriptor, fcntl.LOCK_EX)
            return True

    def do_release_read_lock(self):
        self._release_all_locks()

    def do_release_write_lock(self):
        self._release_all_locks()

    def _release_all_locks(self):
        filedescriptor = self._filedesc
        if filedescriptor is not None:
            fcntl.flock(filedescriptor, fcntl.LOCK_UN)
            os.close(filedescriptor)
            self._filedescriptor.remove()

class ConditionSynchronizer(SynchronizerImpl):
    """a synchronizer using a Condition."""

    def __init__(self, identifier):
        super(ConditionSynchronizer, self).__init__()

        # counts how many asynchronous methods are executing
        self.async = 0

        # pointer to thread that is the current sync operation
        self.current_sync_operation = None

        # condition object to lock on
        self.condition = _threading.Condition(_threading.Lock())

    def do_acquire_read_lock(self, wait=True):
        self.condition.acquire()
        try:
            # see if a synchronous operation is waiting to start
            # or is already running, in which case we wait (or just
            # give up and return)
            if wait:
                while self.current_sync_operation is not None:
                    self.condition.wait()
            else:
                if self.current_sync_operation is not None:
                    return False

            self.async += 1
        finally:
            self.condition.release()

        if not wait:
            return True

    def do_release_read_lock(self):
        self.condition.acquire()
        try:
            self.async -= 1

            # check if we are the last asynchronous reader thread
            # out the door.
            if self.async == 0:
                # yes. so if a sync operation is waiting, notifyAll to wake
                # it up
                if self.current_sync_operation is not None:
                    self.condition.notifyAll()
            elif self.async < 0:
                raise LockError("Synchronizer error - too many "
                                "release_read_locks called")
        finally:
            self.condition.release()

    def do_acquire_write_lock(self, wait=True):
        self.condition.acquire()
        try:
            # here, we are not a synchronous reader, and after returning,
            # assuming waiting or immediate availability, we will be.

            if wait:
                # if another sync is working, wait
                while self.current_sync_operation is not None:
                    self.condition.wait()
            else:
                # if another sync is working,
                # we dont want to wait, so forget it
                if self.current_sync_operation is not None:
                    return False

            # establish ourselves as the current sync
            # this indicates to other read/write operations
            # that they should wait until this is None again
            self.current_sync_operation = _threading.currentThread()

            # now wait again for asyncs to finish
            if self.async > 0:
                if wait:
                    # wait
                    self.condition.wait()
                else:
                    # we dont want to wait, so forget it
                    self.current_sync_operation = None
                    return False
        finally:
            self.condition.release()

        if not wait:
            return True

    def do_release_write_lock(self):
        self.condition.acquire()
        try:
            if self.current_sync_operation is not _threading.currentThread():
                raise LockError("Synchronizer error - current thread doesnt "
                                "have the write lock")

            # reset the current sync operation so
            # another can get it
            self.current_sync_operation = None

            # tell everyone to get ready
            self.condition.notifyAll()
        finally:
            # everyone go !!
            self.condition.release()
<commit_msg>Fix compatibility with Python 3.7<commit_after>"""Synchronization functions.

File- and mutex-based mutual exclusion synchronizers are provided,
as well as a name-based mutex which locks within an application
based on a string name.

"""
import errno
import os
import sys
import tempfile

try:
    import threading as _threading
except ImportError:
    import dummy_threading as _threading

# check for fcntl module
try:
    sys.getwindowsversion()
    has_flock = False
except:
    try:
        import fcntl
        has_flock = True
    except ImportError:
        has_flock = False

from beaker import util
from beaker.exceptions import LockError

__all__ = ["file_synchronizer", "mutex_synchronizer", "null_synchronizer",
            "NameLock", "_threading"]

class NameLock(object):
    """a proxy for an RLock object that is stored in a name based
    registry.

    Multiple threads can get a reference to the same RLock based on the
    name alone, and synchronize operations related to that name.

    """
    locks = util.WeakValuedRegistry()

    class NLContainer(object):
        def __init__(self, reentrant):
            if reentrant:
                self.lock = _threading.RLock()
            else:
                self.lock = _threading.Lock()

        def __call__(self):
            return self.lock

    def __init__(self, identifier=None, reentrant=False):
        if identifier is None:
            self._lock = NameLock.NLContainer(reentrant)
        else:
            self._lock = NameLock.locks.get(identifier, NameLock.NLContainer,
                                            reentrant)

    def acquire(self, wait=True):
        return self._lock().acquire(wait)

    def release(self):
        self._lock().release()

_synchronizers = util.WeakValuedRegistry()

def _synchronizer(identifier, cls, **kwargs):
    return _synchronizers.sync_get((identifier, cls), cls, identifier, **kwargs)

def file_synchronizer(identifier, **kwargs):
    if not has_flock or 'lock_dir' not in kwargs:
        return mutex_synchronizer(identifier)
    else:
        return _synchronizer(identifier, FileSynchronizer, **kwargs)

def mutex_synchronizer(identifier, **kwargs):
    return _synchronizer(identifier, ConditionSynchronizer, **kwargs)

class null_synchronizer(object):
    """A 'null' synchronizer, which provides the :class:`.SynchronizerImpl` interface
    without any locking.

    """
    def acquire_write_lock(self, wait=True):
        return True

    def acquire_read_lock(self):
        pass

    def release_write_lock(self):
        pass

    def release_read_lock(self):
        pass
    acquire = acquire_write_lock
    release = release_write_lock

class SynchronizerImpl(object):
    """Base class for a synchronization object that allows
    multiple readers, single writers.

    """
    def __init__(self):
        self._state = util.ThreadLocal()

    class SyncState(object):
        __slots__ = 'reentrantcount', 'writing', 'reading'

        def __init__(self):
            self.reentrantcount = 0
            self.writing = False
            self.reading = False

    def state(self):
        if not self._state.has():
            state = SynchronizerImpl.SyncState()
            self._state.put(state)
            return state
        else:
            return self._state.get()
    state = property(state)

    def release_read_lock(self):
        state = self.state

        if state.writing:
            raise LockError("lock is in writing state")
        if not state.reading:
            raise LockError("lock is not in reading state")

        if state.reentrantcount == 1:
            self.do_release_read_lock()
            state.reading = False

        state.reentrantcount -= 1

    def acquire_read_lock(self, wait=True):
        state = self.state

        if state.writing:
            raise LockError("lock is in writing state")

        if state.reentrantcount == 0:
            x = self.do_acquire_read_lock(wait)
            if (wait or x):
                state.reentrantcount += 1
                state.reading = True
            return x
        elif state.reading:
            state.reentrantcount += 1
            return True

    def release_write_lock(self):
        state = self.state

        if state.reading:
            raise LockError("lock is in reading state")
        if not state.writing:
            raise LockError("lock is not in writing state")

        if state.reentrantcount == 1:
            self.do_release_write_lock()
            state.writing = False

        state.reentrantcount -= 1

    release = release_write_lock

    def acquire_write_lock(self, wait=True):
        state = self.state

        if state.reading:
            raise LockError("lock is in reading state")

        if state.reentrantcount == 0:
            x = self.do_acquire_write_lock(wait)
            if (wait or x):
                state.reentrantcount += 1
                state.writing = True
            return x
        elif state.writing:
            state.reentrantcount += 1
            return True

    acquire = acquire_write_lock

    def do_release_read_lock(self):
        raise NotImplementedError()

    def do_acquire_read_lock(self, wait):
        raise NotImplementedError()

    def do_release_write_lock(self):
        raise NotImplementedError()

    def do_acquire_write_lock(self, wait):
        raise NotImplementedError()

class FileSynchronizer(SynchronizerImpl):
    """A synchronizer which locks using flock().

    """
    def __init__(self, identifier, lock_dir):
        super(FileSynchronizer, self).__init__()
        self._filedescriptor = util.ThreadLocal()

        if lock_dir is None:
            lock_dir = tempfile.gettempdir()
        else:
            lock_dir = lock_dir

        self.filename = util.encoded_path(
                            lock_dir,
                            [identifier],
                            extension='.lock'
                        )
        self.lock_dir = os.path.dirname(self.filename)

    def _filedesc(self):
        return self._filedescriptor.get()
    _filedesc = property(_filedesc)

    def _ensuredir(self):
        if not os.path.exists(self.lock_dir):
            util.verify_directory(self.lock_dir)

    def _open(self, mode):
        filedescriptor = self._filedesc
        if filedescriptor is None:
            self._ensuredir()
            filedescriptor = os.open(self.filename, mode)
            self._filedescriptor.put(filedescriptor)
        return filedescriptor

    def do_acquire_read_lock(self, wait):
        filedescriptor = self._open(os.O_CREAT | os.O_RDONLY)
        if not wait:
            try:
                fcntl.flock(filedescriptor, fcntl.LOCK_SH | fcntl.LOCK_NB)
                return True
            except IOError:
                os.close(filedescriptor)
                self._filedescriptor.remove()
                return False
        else:
            fcntl.flock(filedescriptor, fcntl.LOCK_SH)
            return True

    def do_acquire_write_lock(self, wait):
        filedescriptor = self._open(os.O_CREAT | os.O_WRONLY)
        if not wait:
            try:
                fcntl.flock(filedescriptor, fcntl.LOCK_EX | fcntl.LOCK_NB)
                return True
            except IOError:
                os.close(filedescriptor)
                self._filedescriptor.remove()
                return False
        else:
            fcntl.flock(filedescriptor, fcntl.LOCK_EX)
            return True

    def do_release_read_lock(self):
        self._release_all_locks()

    def do_release_write_lock(self):
        self._release_all_locks()

    def _release_all_locks(self):
        filedescriptor = self._filedesc
        if filedescriptor is not None:
            fcntl.flock(filedescriptor, fcntl.LOCK_UN)
            os.close(filedescriptor)
            self._filedescriptor.remove()

class ConditionSynchronizer(SynchronizerImpl):
    """a synchronizer using a Condition."""

    def __init__(self, identifier):
        super(ConditionSynchronizer, self).__init__()

        # counts how many asynchronous methods are executing
        self.asynch = 0

        # pointer to thread that is the current sync operation
        self.current_sync_operation = None

        # condition object to lock on
        self.condition = _threading.Condition(_threading.Lock())

    def do_acquire_read_lock(self, wait=True):
        self.condition.acquire()
        try:
            # see if a synchronous operation is waiting to start
            # or is already running, in which case we wait (or just
            # give up and return)
            if wait:
                while self.current_sync_operation is not None:
                    self.condition.wait()
            else:
                if self.current_sync_operation is not None:
                    return False

            self.asynch += 1
        finally:
            self.condition.release()

        if not wait:
            return True

    def do_release_read_lock(self):
        self.condition.acquire()
        try:
            self.asynch -= 1

            # check if we are the last asynchronous reader thread
            # out the door.
            if self.asynch == 0:
                # yes. so if a sync operation is waiting, notifyAll to wake
                # it up
                if self.current_sync_operation is not None:
                    self.condition.notifyAll()
            elif self.asynch < 0:
                raise LockError("Synchronizer error - too many "
                                "release_read_locks called")
        finally:
            self.condition.release()

    def do_acquire_write_lock(self, wait=True):
        self.condition.acquire()
        try:
            # here, we are not a synchronous reader, and after returning,
            # assuming waiting or immediate availability, we will be.

            if wait:
                # if another sync is working, wait
                while self.current_sync_operation is not None:
                    self.condition.wait()
            else:
                # if another sync is working,
                # we dont want to wait, so forget it
                if self.current_sync_operation is not None:
                    return False

            # establish ourselves as the current sync
            # this indicates to other read/write operations
            # that they should wait until this is None again
            self.current_sync_operation = _threading.currentThread()

            # now wait again for asyncs to finish
            if self.asynch > 0:
                if wait:
                    # wait
                    self.condition.wait()
                else:
                    # we dont want to wait, so forget it
                    self.current_sync_operation = None
                    return False
        finally:
            self.condition.release()

        if not wait:
            return True

    def do_release_write_lock(self):
        self.condition.acquire()
        try:
            if self.current_sync_operation is not _threading.currentThread():
                raise LockError("Synchronizer error - current thread doesnt "
                                "have the write lock")

            # reset the current sync operation so
            # another can get it
            self.current_sync_operation = None

            # tell everyone to get ready
            self.condition.notifyAll()
        finally:
            # everyone go !!
            self.condition.release()
<|endoftext|>