<commit_before>"""Analysis methods for TACA."""
import glob
import logging
import os
import subprocess

from shutil import copyfile
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.illumina.HiSeq_Runs import HiSeq_Run
from taca.illumina.MiSeq_Runs import MiSeq_Run
from taca.illumina.NextSeq_Runs import NextSeq_Run
from taca.illumina.NovaSeq_Runs import NovaSeq_Run
from taca.utils.config import CONFIG
from taca.utils.transfer import RsyncAgent
from taca.utils import statusdb

from flowcell_parser.classes import RunParametersParser
from io import open

logger = logging.getLogger(__name__)


def get_runObj(run):
    """Tries to read runParameters.xml to parse the type of sequencer
        and then return the respective Run object (MiSeq, HiSeq..)

    :param run: run name identifier
    :type run: string
    :rtype: Object
    :returns: returns the sequencer type object,
    None if the sequencer type is unknown of there was an error
    """

    if os.path.exists(os.path.join(run, 'runParameters.xml')):
        run_parameters_file = 'runParameters.xml'
    elif os.path.exists(os.path.join(run, 'RunParameters.xml')):
        run_parameters_file = 'RunParameters.xml'
    else:
        logger.error('Cannot find RunParameters.xml or runParameters.xml in the run folder for run {}'.format(run))
        return

    rppath = os.path.join(run, run_parameters_file)
    try:
        rp = RunParametersParser(os.path.join(run, run_parameters_file))
    except OSError:
        logger.warn('Problems parsing the runParameters.xml file at {}. '
                    'This is quite unexpected. please archive the run {} manually'.format(rppath, run))
    else:
        # Do a case by case test becasue there are so many version of RunParameters that there is no real other way
        runtype = rp.data['RunParameters'].get('Application', '')
        if 'Setup' in rp.data['RunParameters']:
            # This is the HiSeq2500, MiSeq, and HiSeqX case
            try:
                # Works for recent control software
                runtype = rp.data['RunParameters']['Setup']['Flowcell']
            except KeyError:
                # Use this as second resource but print a warning in the logs
                logger.warn('Parsing runParameters to fecth instrument type, '
                            'not found Flowcell information in it. Using ApplicationName')
                # Here makes sense to use get with default value '' ->
                # so that it doesn't raise an exception in the next lines
                # (in case ApplicationName is not found, get returns None)
                runtype = rp.data['RunParameters']['Setup'].get('ApplicationName', '')

        if 'HiSeq X' in runtype:
            return HiSeqX_Run(run, CONFIG['analysis']['HiSeqX'])
        elif 'HiSeq' in runtype or 'TruSeq' in runtype:
            return HiSeq_Run(run, CONFIG['analysis']['HiSeq'])
        elif 'MiSeq' in runtype:<commit_msg>Fix runtype for NextSeq 2000<commit_after>"""Analysis methods for TACA."""
import glob
import logging
import os
import subprocess

from shutil import copyfile
from taca.illumina.HiSeqX_Runs import HiSeqX_Run
from taca.illumina.HiSeq_Runs import HiSeq_Run
from taca.illumina.MiSeq_Runs import MiSeq_Run
from taca.illumina.NextSeq_Runs import NextSeq_Run
from taca.illumina.NovaSeq_Runs import NovaSeq_Run
from taca.utils.config import CONFIG
from taca.utils.transfer import RsyncAgent
from taca.utils import statusdb

from flowcell_parser.classes import RunParametersParser
from io import open

logger = logging.getLogger(__name__)


def get_runObj(run):
    """Tries to read runParameters.xml to parse the type of sequencer
        and then return the respective Run object (MiSeq, HiSeq..)

    :param run: run name identifier
    :type run: string
    :rtype: Object
    :returns: returns the sequencer type object,
    None if the sequencer type is unknown of there was an error
    """

    if os.path.exists(os.path.join(run, 'runParameters.xml')):
        run_parameters_file = 'runParameters.xml'
    elif os.path.exists(os.path.join(run, 'RunParameters.xml')):
        run_parameters_file = 'RunParameters.xml'
    else:
        logger.error('Cannot find RunParameters.xml or runParameters.xml in the run folder for run {}'.format(run))
        return

    rppath = os.path.join(run, run_parameters_file)
    try:
        rp = RunParametersParser(os.path.join(run, run_parameters_file))
    except OSError:
        logger.warn('Problems parsing the runParameters.xml file at {}. '
                    'This is quite unexpected. please archive the run {} manually'.format(rppath, run))
    else:
        # Do a case by case test becasue there are so many version of RunParameters that there is no real other way
        runtype = rp.data['RunParameters'].get('Application', '')
        if 'Setup' in rp.data['RunParameters']:
            # This is the HiSeq2500, MiSeq, and HiSeqX case
            try:
                # Works for recent control software
                runtype = rp.data['RunParameters']['Setup']['Flowcell']
            except KeyError:
                # Use this as second resource but print a warning in the logs
                logger.warn('Parsing runParameters to fecth instrument type, '
                            'not found Flowcell information in it. Using ApplicationName')
                # Here makes sense to use get with default value '' ->
                # so that it doesn't raise an exception in the next lines
                # (in case ApplicationName is not found, get returns None)
                runtype = rp.data['RunParameters']['Setup'].get('ApplicationName', '')
        else:
            # This is the case for NextSeq 2000
            runtype = rp.data['RunParameters'].get('ApplicationName', '')

        if 'HiSeq X' in runtype:
            return HiSeqX_Run(run, CONFIG['analysis']['HiSeqX'])
        elif 'HiSeq' in runtype or 'TruSeq' in runtype:
            return HiSeq_Run(run, CONFIG['analysis']['HiSeq'])
        elif 'MiSeq' in runtype:
{'fraction_non_alphanumeric': 0.08552088492653129, 'fraction_numerical': 0.0026415717351824337, 'mean_word_length': 2.829329962073325, 'pattern_counts': {'":': 0, '<': 3, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 16}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '4195739', 'n_tokens_mistral': 1725, 'n_tokens_neox': 1654, 'n_words': 577}