<commit_before>#!/usr/bin/env python3
#
# Author    : Manuel Bernal Llinares
# Project   : trackhub-creator
# Timestamp : 29-06-2017 11:47
# ---
# © 2017 Manuel Bernal Llinares <mbdebian@gmail.com>
# All rights reserved.
#

"""
Pipeline Runner - Main Application
"""

import nose
import argparse
import unittest
# Modules from package
import config_manager
import ensembl.service
import ensembl.data_downloader

__DEFAULT_CONFIG_FILE = "config_default.json"

# Running mode
__run_test_mode = False
__logger = None
__args = None

def get_cmdl():
    cmdl_version = '2017.06.29'
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', "--config_file",
                        help='Application configuration file')
    parser.add_argument('-p', '--pipeline_config_file',
                        help='Configuration file for the pipeline that is going to be run')
    parser.add_argument('-a', '--pipeline_arguments',
                        help='Comma separated of pipeline command line arguments (key=value pairs)')
    parser.add_argument('-v', '--version',
                        help='display version information',
                        action='version',
                        version=cmdl_version + ' %(prog)s ')
    parser.add_argument('pipeline_name',
                        help='Module Name that contains the director of the pipeline to run')
    args = parser.parse_args()
    return args

def app_bootstrap():
    global __run_test_mode
    global __logger
    global __args
    __args = get_cmdl()
    if __args.config_file:
        config_manager.set_application_config_file(__args.config_file)
    else:
        config_manager.set_application_config_file(__DEFAULT_CONFIG_FILE)
    if __args.pipeline_name:
        config_manager.set_pipeline_name(__args.pipeline_name)
        if __args.pipeline_name == 'test':
            __run_test_mode = True
    __logger = config_manager.get_app_config_manager().get_logger_for(__name__)
    if __run_test_mode:
        __logger.info(
            "Session '{}' STARTED, RUNNING UNIT TESTS".format(config_manager.get_app_config_manager().get_session_id()))
    else:
        __logger.info(
            "Session '{}' STARTED, pipeline '{}'".format(config_manager.get_app_config_manager().get_session_id(),
                                                         __args.pipeline_name))

def modules_bootstrap():
    ensembl_config_file = config_manager.get_app_config_manager().get_file_name_config_modules_ensembl_service()
    __logger.debug("Setting Ensembl configuration file -- {}".format(ensembl_config_file))
    ensembl.service.set_configuration_file(ensembl_config_file)
    # TODO - Should I delegate this to a main entry point for every module?.
    # TODO - REFACTOR THIS IN THE FUTURE, WHEN MODULE FUNCTIONALITY HAS BEEN TESTED
    __logger.debug("Setting Ensembl Data Downloader configuration file -- {}"
                   .format(config_manager
                           .get_app_config_manager()
                           .get_file_name_config_modules_ensembl_data_downloader()))
    ensembl.data_downloader.set_configuration_file(
        config_manager
            .get_app_config_manager()
            .get_file_name_config_modules_ensembl_data_downloader())

def run_unit_tests():
    __logger.debug("Running Unit Tests")
    test_loader = unittest.TestLoader()
    test_suite = test_loader.discover('.')
    nose.run(suite=test_suite)

def run_pipeline():
    # TODO
    global __args
    pipeline_factory_module = config_manager\
        .get_app_config_manager()\
        .get_pipeline_factory_instance(__args.pipeline_name)
    # TODO I should refactor this in the future, in case I use this information anywhere else
    # Set the configuration file
    __logger.info("Pipeline configuration file '{}'".format(__args.pipeline_config_file))
    pipeline_factory_module.set_configuration_file(__args.pipeline_config_file)
    # Set the pipeline command line arguments
    __logger.info("Pipeline command line arguments: '{}'".format(__args.pipeline_arguments))
    pipeline_factory_module.set_pipeline_arguments(__args.pipeline_arguments)
    # Get an instance of the pipeline
    pipeline_instance = pipeline_factory_module.get_pipeline_director()

def main():
    app_bootstrap()
    modules_bootstrap()
    if __run_test_mode:
        run_unit_tests()
    else:
        run_pipeline()

if __name__ == "__main__":
    main()
<commit_msg>run the pipeline<commit_after>#!/usr/bin/env python3
#
# Author    : Manuel Bernal Llinares
# Project   : trackhub-creator
# Timestamp : 29-06-2017 11:47
# ---
# © 2017 Manuel Bernal Llinares <mbdebian@gmail.com>
# All rights reserved.
#

"""
Pipeline Runner - Main Application
"""

import nose
import argparse
import unittest
# Modules from package
import config_manager
import ensembl.service
import ensembl.data_downloader

__DEFAULT_CONFIG_FILE = "config_default.json"

# Running mode
__run_test_mode = False
__logger = None
__args = None

def get_cmdl():
    cmdl_version = '2017.06.29'
    parser = argparse.ArgumentParser()
    parser.add_argument('-c', "--config_file",
                        help='Application configuration file')
    parser.add_argument('-p', '--pipeline_config_file',
                        help='Configuration file for the pipeline that is going to be run')
    parser.add_argument('-a', '--pipeline_arguments',
                        help='Comma separated of pipeline command line arguments (key=value pairs)')
    parser.add_argument('-v', '--version',
                        help='display version information',
                        action='version',
                        version=cmdl_version + ' %(prog)s ')
    parser.add_argument('pipeline_name',
                        help='Module Name that contains the director of the pipeline to run')
    args = parser.parse_args()
    return args

def app_bootstrap():
    global __run_test_mode
    global __logger
    global __args
    __args = get_cmdl()
    if __args.config_file:
        config_manager.set_application_config_file(__args.config_file)
    else:
        config_manager.set_application_config_file(__DEFAULT_CONFIG_FILE)
    if __args.pipeline_name:
        config_manager.set_pipeline_name(__args.pipeline_name)
        if __args.pipeline_name == 'test':
            __run_test_mode = True
    __logger = config_manager.get_app_config_manager().get_logger_for(__name__)
    if __run_test_mode:
        __logger.info(
            "Session '{}' STARTED, RUNNING UNIT TESTS".format(config_manager.get_app_config_manager().get_session_id()))
    else:
        __logger.info(
            "Session '{}' STARTED, pipeline '{}'".format(config_manager.get_app_config_manager().get_session_id(),
                                                         __args.pipeline_name))

def modules_bootstrap():
    ensembl_config_file = config_manager.get_app_config_manager().get_file_name_config_modules_ensembl_service()
    __logger.debug("Setting Ensembl configuration file -- {}".format(ensembl_config_file))
    ensembl.service.set_configuration_file(ensembl_config_file)
    # TODO - Should I delegate this to a main entry point for every module?.
    # TODO - REFACTOR THIS IN THE FUTURE, WHEN MODULE FUNCTIONALITY HAS BEEN TESTED
    __logger.debug("Setting Ensembl Data Downloader configuration file -- {}"
                   .format(config_manager
                           .get_app_config_manager()
                           .get_file_name_config_modules_ensembl_data_downloader()))
    ensembl.data_downloader.set_configuration_file(
        config_manager
            .get_app_config_manager()
            .get_file_name_config_modules_ensembl_data_downloader())

def run_unit_tests():
    __logger.debug("Running Unit Tests")
    test_loader = unittest.TestLoader()
    test_suite = test_loader.discover('.')
    nose.run(suite=test_suite)

def run_pipeline():
    # TODO
    global __args
    pipeline_factory_module = config_manager\
        .get_app_config_manager()\
        .get_pipeline_factory_instance(__args.pipeline_name)
    # TODO I should refactor this in the future, in case I use this information anywhere else
    # Set the configuration file
    __logger.info("Pipeline configuration file '{}'".format(__args.pipeline_config_file))
    pipeline_factory_module.set_configuration_file(__args.pipeline_config_file)
    # Set the pipeline command line arguments
    __logger.info("Pipeline command line arguments: '{}'".format(__args.pipeline_arguments))
    pipeline_factory_module.set_pipeline_arguments(__args.pipeline_arguments)
    # Get an instance of the pipeline
    pipeline_instance = pipeline_factory_module.get_pipeline_director()
    # Run it
    pipeline_instance.run()

def main():
    app_bootstrap()
    modules_bootstrap()
    if __run_test_mode:
        run_unit_tests()
    else:
        run_pipeline()

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


<commit_before># -*- coding: utf-8 -*-
"""
Some helpful functions for parsing or changing Chinese text
"""
import re
import os
import subprocess
from HTMLParser import HTMLParser

import jieba
import jieba.posseg as pseg

from constants import SIMPLIFIED, TRADITIONAL, EITHER, BOTH, NEITHER

from hanzidentifier import hanzidentifier

_curpath=os.path.normpath( os.path.join( os.getcwd(), os.path.dirname(__file__) ))
settings_path = os.environ.get('MAFAN_DICTIONARY_PATH')
if settings_path and os.path.exists(settings_path):
    jieba.set_dictionary(settings_path)
elif os.path.exists(os.path.join(_curpath, 'data/dict.txt.big')):
    jieba.set_dictionary('data/dict.txt.big')
else:
    try:
        import mafan_traditional
        jieba.set_dictionary(mafan_traditional.path)
        print "Using traditional dictionary!"
    except ImportError:
        pass

from jianfan import jtof as tradify, ftoj as simplify
to_traditional = tradify
to_simplified = simplify

known_stops = u'。。…！？'
known_punctuation = u'／（）、，。：「」…。『』！？《》“”；’ ‘【】·〔〕'

re_split_sentences = re.compile(r"[%s]+" % known_stops)

def contains_ascii(unicode_string):
    u"""Attempts to determine whether the string contains any ASCII characters.

    Checks for any printable ASCII characters (0020-007E).

    It does not check for non-printable ASCII characters such as tabs and spaces,
        because those are often present in Chinese typing as well.

    :TODO: Tests
    """
    if re.search(ur'[\u0020-\u007E]', unicode_string) is None:
            return False
    else:
            return True

def contains_latin(unicode_string):
    u"""
    Kept for backwards-compatibility.

    :TODO: Improve this to also look for characters
    such as ô,ê,ā,ɛ, etc.
    """
    return contains_ascii(unicode_string)

def contains_english(unicode_string):
    u"""
    Kept for backwards-compatibility.
    Just a wrapper for contains_ascii
    """
    return contains_ascii(unicode_string)

def contains_chinese(unicode_string):
    u"""
    Add new method for checking chinese characters by given unicode string.
    >>> contains_chinese(u'Hello,這是麻煩啦')
    True
    >>> contains_chinese(u'Hello')
    False
    """
    if re.search(ur'[\u4E00-\u9FFF]+', unicode_string) is None:
        return False
    else:
        return True

def has_punctuation(word):
    u"""
    Check if a string has any of the common Chinese punctuation marks.
    """
    if re.search(r'[%s]' % known_punctuation, word) is not None:
            return True
    else:
            return False

def is_punctuation(character):
    u"""Tells whether the supplied character is a Chinese punctuation mark.

    This is useful for filtering out punctuation, for example.

    >>> sentence = u"你的電子郵件信箱「爆」了！無法寄信給你。"
    >>> print filter(lambda c: not is_punctuation(c), sentence)
    你的電子郵件信箱爆了無法寄信給你

    >>> word = u"『爆』？"
    >>> is_punctuation(word[0])
    True
    >>> is_punctuation(word[1])
    False
    >>> all(map(is_punctuation, word[2:]))
    True
    """
    return has_punctuation(character)

def iconv(text, args):
    p1 = subprocess.Popen(["echo", text], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['iconv'] + list(args), stdout=subprocess.PIPE, stdin = p1.stdout, stderr=subprocess.STDOUT)
    p1.stdout.close()
    output = p2.communicate()[0]
    print output
    return output

def identify(text):
    u"""
    Wrapper for hanzidentifier identify function

    Returns:
        None: if there are no recognizd Chinese characters.
        EITHER: if the test is inconclusive.
        TRADITIONAL: if the text is traditional.
        SIMPLIFIED: if the text is simplified.
        BOTH: the text has characters recognized as being solely traditional
                and other characters recognized as being solely simplified.
        NEITHER: (or None) It's neither simplified nor traditional Chinese text.

    >>> identify(u'这是麻烦啦') is SIMPLIFIED
    True
    >>> identify(u'這是麻煩啦') is TRADITIONAL
    True
    >>> identify(u'这是麻烦啦! 這是麻煩啦') is BOTH
    True
    >>> identify(u'This is so mafan.') is NEITHER
    True
    """
    return hanzidentifier.identify(text)

def is_simplified(text):
    u"""
    Determine whether a text is simplified Chinese
    Returns True if written in Simplified, False otherwise.

    Note: This assumes the text is known to be one or the other.

    >>> is_simplified(u'这是麻烦啦')
    True

    """
    return hanzidentifier.identify(text) is SIMPLIFIED

def is_traditional(text):
    u"""
    Determine whether a text is simplified Chinese
    Returns True if written in Simplified, False otherwise.

    Note: This assumes the text is known to be one or the other.

    >>> is_traditional(u'Hello,這是麻煩啦')
    True

    """
    return hanzidentifier.identify(text) is TRADITIONAL

def is_chinese(text):
    u"""
    Determine whether the entire string contains only Chinese characters.
    This checks every character, so it is pretty slow - try to use only on
    short sentences or words.

    >>> is_chinese(u'這是麻煩啦')
    True
    >>> is_chinese(u'Hello,這是麻煩啦')
    False
    >>> is_chinese(u'♪')
    False
    """
    return all([c in hanzidentifier.ALL_CHARS for c in text])

def _is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

def split_text(text, include_part_of_speech=False, strip_english=False, strip_numbers=False):
    u"""
    Split Chinese text at word boundaries.

    include_pos: also returns the Part Of Speech for each of the words.
    Some of the different parts of speech are:
        r: pronoun
        v: verb
        ns: proper noun
        etc...

    This all gets returned as a tuple:
        index 0: the split word
        index 1: the word's part of speech

    strip_english: remove all entries that have English or numbers in them (useful sometimes)
    """

    if not include_part_of_speech:
        seg_list = pseg.cut(text)
        if strip_english:
            seg_list = filter(lambda x: not contains_english(x), seg_list)
        if strip_numbers:
            seg_list = filter(lambda x: not _is_number(x), seg_list)
        return list(map(lambda i: i.word, seg_list))
    else:
        seg_list = pseg.cut(text)
        objs = map(lambda w: (w.word, w.flag), seg_list)
        if strip_english:
            objs = filter(lambda x: not contains_english(x[0]), objs)
        if strip_english:
            objs = filter(lambda x: not _is_number(x[0]), objs)
        return objs

    # if was_traditional:
    #   seg_list = map(tradify, seg_list)

    return list(seg_list)

def split_sentences(text):
    u"""
    Split Chinese text into a list of sentences, separated by punctuation.

    >>> sentence = u"你的電子郵件信箱「爆」了！無法寄信給你。我知道，我正在刪除信件中。"
    >>> print '_'.join(split_sentences(text=sentence))
    你的電子郵件信箱「爆」了_無法寄信給你_我知道，我正在刪除信件中
    """
    s = list(text)
    return filter(None, re.split(re_split_sentences, text))

if __name__ == "__main__":
        import doctest
        doctest.testmod()
<commit_msg>Add test for punctuation in contains_chinese<commit_after># -*- coding: utf-8 -*-
"""
Some helpful functions for parsing or changing Chinese text
"""
import re
import os
import subprocess
from HTMLParser import HTMLParser

import jieba
import jieba.posseg as pseg

from constants import SIMPLIFIED, TRADITIONAL, EITHER, BOTH, NEITHER

from hanzidentifier import hanzidentifier

_curpath=os.path.normpath( os.path.join( os.getcwd(), os.path.dirname(__file__) ))
settings_path = os.environ.get('MAFAN_DICTIONARY_PATH')
if settings_path and os.path.exists(settings_path):
    jieba.set_dictionary(settings_path)
elif os.path.exists(os.path.join(_curpath, 'data/dict.txt.big')):
    jieba.set_dictionary('data/dict.txt.big')
else:
    try:
        import mafan_traditional
        jieba.set_dictionary(mafan_traditional.path)
        print "Using traditional dictionary!"
    except ImportError:
        pass

from jianfan import jtof as tradify, ftoj as simplify
to_traditional = tradify
to_simplified = simplify

known_stops = u'。。…！？'
known_punctuation = u'／（）、，。：「」…。『』！？《》“”；’ ‘【】·〔〕'

re_split_sentences = re.compile(r"[%s]+" % known_stops)

def contains_ascii(unicode_string):
    u"""Attempts to determine whether the string contains any ASCII characters.

    Checks for any printable ASCII characters (0020-007E).

    It does not check for non-printable ASCII characters such as tabs and spaces,
        because those are often present in Chinese typing as well.

    :TODO: Tests
    """
    if re.search(ur'[\u0020-\u007E]', unicode_string) is None:
            return False
    else:
            return True

def contains_latin(unicode_string):
    u"""
    Kept for backwards-compatibility.

    :TODO: Improve this to also look for characters
    such as ô,ê,ā,ɛ, etc.
    """
    return contains_ascii(unicode_string)

def contains_english(unicode_string):
    u"""
    Kept for backwards-compatibility.
    Just a wrapper for contains_ascii
    """
    return contains_ascii(unicode_string)

def contains_chinese(unicode_string):
    u"""
    Check whether the given unicode string contains any chinese characters.
    >>> contains_chinese(u'Hello,這是麻煩啦')
    True
    >>> contains_chinese(u'Hello')
    False
    >>> contains_chinese(u'。…！？') # punctuation does not count as Chinese
    False
    """
    if re.search(ur'[\u4E00-\u9FFF]+', unicode_string) is None:
        return False
    else:
        return True

def has_punctuation(word):
    u"""
    Check if a string has any of the common Chinese punctuation marks.
    """
    if re.search(r'[%s]' % known_punctuation, word) is not None:
            return True
    else:
            return False

def is_punctuation(character):
    u"""Tells whether the supplied character is a Chinese punctuation mark.

    This is useful for filtering out punctuation, for example.

    >>> sentence = u"你的電子郵件信箱「爆」了！無法寄信給你。"
    >>> print filter(lambda c: not is_punctuation(c), sentence)
    你的電子郵件信箱爆了無法寄信給你

    >>> word = u"『爆』？"
    >>> is_punctuation(word[0])
    True
    >>> is_punctuation(word[1])
    False
    >>> all(map(is_punctuation, word[2:]))
    True
    """
    return has_punctuation(character)

def iconv(text, args):
    p1 = subprocess.Popen(["echo", text], stdout=subprocess.PIPE)
    p2 = subprocess.Popen(['iconv'] + list(args), stdout=subprocess.PIPE, stdin = p1.stdout, stderr=subprocess.STDOUT)
    p1.stdout.close()
    output = p2.communicate()[0]
    print output
    return output

def identify(text):
    u"""
    Wrapper for hanzidentifier identify function

    Returns:
        None: if there are no recognizd Chinese characters.
        EITHER: if the test is inconclusive.
        TRADITIONAL: if the text is traditional.
        SIMPLIFIED: if the text is simplified.
        BOTH: the text has characters recognized as being solely traditional
                and other characters recognized as being solely simplified.
        NEITHER: (or None) It's neither simplified nor traditional Chinese text.

    >>> identify(u'这是麻烦啦') is SIMPLIFIED
    True
    >>> identify(u'這是麻煩啦') is TRADITIONAL
    True
    >>> identify(u'这是麻烦啦! 這是麻煩啦') is BOTH
    True
    >>> identify(u'This is so mafan.') is NEITHER
    True
    """
    return hanzidentifier.identify(text)

def is_simplified(text):
    u"""
    Determine whether a text is simplified Chinese
    Returns True if written in Simplified, False otherwise.

    Note: This assumes the text is known to be one or the other.

    >>> is_simplified(u'这是麻烦啦')
    True

    """
    return hanzidentifier.identify(text) is SIMPLIFIED

def is_traditional(text):
    u"""
    Determine whether a text is simplified Chinese
    Returns True if written in Simplified, False otherwise.

    Note: This assumes the text is known to be one or the other.

    >>> is_traditional(u'Hello,這是麻煩啦')
    True

    """
    return hanzidentifier.identify(text) is TRADITIONAL

def is_chinese(text):
    u"""
    Determine whether the entire string contains only Chinese characters.
    This checks every character, so it is pretty slow - try to use only on
    short sentences or words.

    >>> is_chinese(u'這是麻煩啦')
    True
    >>> is_chinese(u'Hello,這是麻煩啦')
    False
    >>> is_chinese(u'♪')
    False
    """
    return all([c in hanzidentifier.ALL_CHARS for c in text])

def _is_number(s):
    try:
        float(s)
        return True
    except ValueError:
        return False

def split_text(text, include_part_of_speech=False, strip_english=False, strip_numbers=False):
    u"""
    Split Chinese text at word boundaries.

    include_pos: also returns the Part Of Speech for each of the words.
    Some of the different parts of speech are:
        r: pronoun
        v: verb
        ns: proper noun
        etc...

    This all gets returned as a tuple:
        index 0: the split word
        index 1: the word's part of speech

    strip_english: remove all entries that have English or numbers in them (useful sometimes)
    """

    if not include_part_of_speech:
        seg_list = pseg.cut(text)
        if strip_english:
            seg_list = filter(lambda x: not contains_english(x), seg_list)
        if strip_numbers:
            seg_list = filter(lambda x: not _is_number(x), seg_list)
        return list(map(lambda i: i.word, seg_list))
    else:
        seg_list = pseg.cut(text)
        objs = map(lambda w: (w.word, w.flag), seg_list)
        if strip_english:
            objs = filter(lambda x: not contains_english(x[0]), objs)
        if strip_english:
            objs = filter(lambda x: not _is_number(x[0]), objs)
        return objs

    # if was_traditional:
    #   seg_list = map(tradify, seg_list)

    return list(seg_list)

def split_sentences(text):
    u"""
    Split Chinese text into a list of sentences, separated by punctuation.

    >>> sentence = u"你的電子郵件信箱「爆」了！無法寄信給你。我知道，我正在刪除信件中。"
    >>> print '_'.join(split_sentences(text=sentence))
    你的電子郵件信箱「爆」了_無法寄信給你_我知道，我正在刪除信件中
    """
    s = list(text)
    return filter(None, re.split(re_split_sentences, text))

if __name__ == "__main__":
        import doctest
        doctest.testmod()
<|endoftext|>


<commit_before>import numpy as np
from scipy.optimize import fsolve
from .eos_selecction import eos, convert_argument

from constants import RGAS, A0, B0, C0, A1, B1, C1, D

'''
This module calculate parameters necessary to use the equations of state:
SRK, PR and RKPR
'''

# Constante universal de los gases R
# RGAS = 0.08314472

# Definir el significado fisicoquímico
# A0, B0, C0 = 0.0017, 1.9681, -2.7238

# Definir el significado fisicoquímico
# A1, B1, C1 = -2.4407, 7.4513, 12.504

# Definir el significado fisicoquímico
# D = np.array([0.428363, 18.496215, 0.338426, 0.660, 789.723105, 2.512392])

def getdel1(Zcin, del_1_init):
    del1 = del_1_init
    d1 = (1 + del1 ** 2) / (1 + del1)
    y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
    Zc = y / (3 * y + d1 - 1.0)
    dold = del1

    if Zc > Zcin:
        del1 = 1.01 * del1
    else:
        del1 = 0.99 * del1

    error_Z_critico = abs(Zc - Zcin)

    while error_Z_critico >= 1e-6:

        d1 = (1 + del1 ** 2) / (1 + del1)
        y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
        Zold = Zc
        Zc = y / (3 * y + d1 - 1.0)
        aux = del1
        del1 = del1 - (Zc - Zcin) * (del1 - dold) / (Zc - Zold)
        dold = aux
        error_Z_critico = abs(Zc - Zcin)

        if error_Z_critico <= 1e-6:
            break

    return del1, error_Z_critico

def get_del_1(Zcin, del_1_init):
    del1 = del_1_init
    d1 = (1 + del1 ** 2) / (1 + del1)
    y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
    Zc = y / (3 * y + d1 - 1.0)
    dold = del1

    if Zc > Zcin:
        del1 = 1.01 * del1
    else:
        del1 = 0.99 * del1

    error_Z_critico = abs(Zc - Zcin)

    while error_Z_critico >= 1e-6:

        d1 = (1 + del1 ** 2) / (1 + del1)
        y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
        Zold = Zc
        Zc = y / (3 * y + d1 - 1.0)
        aux = del1
        del1 = del1 - (Zc - Zcin) * (del1 - dold) / (Zc - Zold)
        dold = aux
        error_Z_critico = abs(Zc - Zcin)

    else:
        print("delta_1 = {0} with a error of = {1}".format(del1, error_Z_critico))

        if error_Z_critico <= 1e-6:
            break

    return del1, error_Z_critico

def compressibility_factor_cal(del1):
    d1 = (1 + del1 ** 2) / (1 + del1)
    y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
    OMa = (3 * y * y + 3 * y * d1 + d1 ** 2 + d1 - 1.0) / (3 * y + d1 - 1.0) ** 2
    OMb = 1 / (3 * y + d1 - 1.0)
    Zc = y / (3 * y + d1 - 1.0)

    return Zc, OMa, OMb

def acentric_factor_cal(*arg):
    al = arg[0]
    be = arg[1]
    ga = arg[2]
    try:
        OM = 0.5 * (- be + np.sqrt(be ** 2 - 4 * al * ga)) / al
    except RuntimeWarning:
        raise RuntimeWarning
    else:
        OM = 0
    return OM

class Parameter_eos(object):
    '''
    Parameter_eos contains the methods to adjust the parameters
    delta 1 rk for the energy parameter to a function of temperature and
    setting the parameter to represent a point of density - temperature curve
    '''

    def energetic_parameter_cal(self, rk, delta_1_initial, Pc, Tc, Tr):

        self.ac = self.parameter_ab_cal(delta_1_initial, Pc, Tc)[0]
        self.a = self.ac * (3 / (2 + Tr)) ** rk

        return self.a

    def gvdW_Derivatives_cal(self, NDER, Volume, a, b, delta_1_initial, Tc, Tr):
        '''
        gvdW_Derivatives_cal: calculate the derivatives from Generalized van
        der Waals equation of state
        '''
        self.d = delta_1_initial

        c = (1 - self.d) / (1 + self.d)
        #aRT = self.a / (RGAS * T_especific)
        aRT = self.a / (RGAS * Tr * Tc)
        relation_covolume = 0.25 * b / Volume
        SUMC = c * b + Volume
        SUMD = self.d * b + Volume
        REP = -np.log(1 - 4 * relation_covolume)
        ATT = aRT * np.log(SUMD / SUMC) / (b * (c - self.d))
        ATTV = aRT / SUMC / SUMD
        REPV = 1 / (1 - 4 * relation_covolume) - 1
        REP2V = 1 / (1 - 4 * relation_covolume) ** 2 - 1
        ATT2V = aRT * Volume ** 2 * (1 / SUMD ** 2 - 1 / SUMC ** 2) \
        / (b * (c - self.d))
        F = REP + ATT
        F_V = (- REPV / Volume + ATTV)

        if NDER == 'Derivatives_of_V':
            F_2V = REP2V - ATT2V
            calculo_1 = 'F_V'
            calculo_2 = 'F_2V'
            return F, F_V, F_2V, calculo_1, calculo_2
        elif NDER == 'Derivatives_of_N':
            F_N = REP + ATT - Volume * F_V
            calculo = 'F_N'
            return F_N, calculo

    def volume_cal(self, ITYP, T, P, a, b, delta_1_initial, Tc, Tr):
        volume_iteration = 0
        VCP = b
        S3R = 1.0 / VCP
        relation_covolume_min, relation_covolume_max = 0.00, 0.99
        P_sur = P
        if ITYP >= 0.0:
            relation_covolume = 0.5
        else:
            # IDEAL GAS ESTIMATE
            relation_covolume = min(0.5, (VCP * P_sur) / (RGAS * T))
        while True:
            Volume = VCP / relation_covolume

            vdWg = self.gvdW_Derivatives_cal('Derivatives_of_V', Volume, a, b, delta_1_initial, Tc, Tr)
            F = vdWg[0]
            F_V = vdWg[1]
            F_2V = vdWg[2]
            pressure_cal_eos = RGAS * T * (1 / Volume - F_V)
            if pressure_cal_eos > P_sur:
                relation_covolume_max = relation_covolume
            else:
                relation_covolume_min = relation_covolume
            AT = F - np.log(Volume) + Volume * P_sur / (T * RGAS)
            DER = RGAS * T * (F_2V + 1.0) * S3R
            DEL = - (pressure_cal_eos - P_sur) / DER
            relation_covolume = relation_covolume + 1.0 * max(min(DEL, 0.1), -0.1)
            if relation_covolume > relation_covolume_max or relation_covolume < relation_covolume_min:
                relation_covolume = 0.5 * (relation_covolume_max + relation_covolume_min)
            if abs(DEL) < 1e-10 or volume_iteration >= 20:
                break
            volume_iteration += 1
        return Volume, pressure_cal_eos

    def fugacity_cal(self, T, P, Volume, delta_1_initial, Tc, Tr):

        Z = P * Volume / (RGAS * T)
        vdWg = self.gvdW_Derivatives_cal('Derivatives_of_N', Volume, self.a, self.b, delta_1_initial, Tc, Tr)
        F_N = vdWg[0]
        phi_fugacity = np.exp(F_N) / Z

        #print(T, T_especific)
        #print(T)
        return phi_fugacity

    def saturation_pressure_cal(self, PV_supuesta, rk_inicial, delta_1_initial, Pc, Tc, Tr):
        self.Tsat = Tr * Tc
        P_sur = PV_supuesta

        #print(self.Tsat)

        self.a = self.energetic_parameter_cal(rk_inicial, delta_1_initial, Pc, Tc, Tr)
        self.b = self.parameter_ab_cal(delta_1_initial, Pc, Tc)[1]

        self.volume_liquid = self.volume_cal(1, self.Tsat, P_sur, self.a,
        self.b, delta_1_initial, Tc, Tr)[0]

        phi_fugacity_liquid = self.fugacity_cal(self.Tsat, P_sur,
        self.volume_liquid, delta_1_initial, Tc, Tr)

        self.volume_vapor = self.volume_cal(-1, self.Tsat, P_sur, self.a,
        self.b, delta_1_initial, Tc, Tr)[0]

        phi_fugacity_vapor = self.fugacity_cal(self.Tsat, P_sur,
        self.volume_vapor, delta_1_initial, Tc, Tr)

        self.phase_equilibrium = abs(phi_fugacity_vapor - phi_fugacity_liquid)

        return self.phase_equilibrium

    def phase_equilibrium_cal(self, rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr):
        PV_inicial = Pvdat

        rk_class = rk_inicial

        self.PV_calculed = fsolve(self.saturation_pressure_cal, PV_inicial,
        args=(rk_class, delta_1_initial, Pc, Tc, Tr), xtol=1e-4)

        return self.PV_calculed

    def funcion_saturacion_cal(self, rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr):

        presion_saturada_modelo = self.phase_equilibrium_cal(rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr)
        self.saturation_function = abs(presion_saturada_modelo - Pvdat) / Pvdat

        return self.saturation_function

    def resolver_rk_cal(self, rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr):

        self.rk_calculated = fsolve(self.funcion_saturacion_cal, rk_inicial,
        args = (delta_1_initial, Pvdat, Pc, Tc, Tr), xtol=1e-4)

        return self.rk_calculated

    def parameter_ab_cal(self, delta_1_initial, Pc, Tc):

        Zc, OMa, OMb = compressibility_factor_cal(delta_1_initial)

        dc = Pc / Zc / (RGAS * Tc)
        Vceos = 1.0 / dc

        self.ac = OMa * (RGAS * Tc)**2 / Pc
        self.b = OMb * (RGAS * Tc) / Pc

        return self.ac, self.b

    def density_cal(self, delta_1_initial, rk_inicial, Pvdat, Pc, Tc, Tr):

        self.a = self.energetic_parameter_cal(rk_inicial, delta_1_initial, Pc, Tc, Tr)
        self.b = self.parameter_ab_cal(delta_1_initial, Pc, Tc)[1]

        self.rk_calculated = self.resolver_rk_cal(rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr)

        self.volume_liquid_delta = self.volume_liquid
        self.density_liquid = 1 / self.volume_liquid_delta

        return self.density_liquid

    def density_function_cal(self, delta_1_initial, rk_inicial, Pvdat, RHOLSat_esp, Pc, Tc, Tr):

        RHOLSat_cal = self.density_cal(delta_1_initial, rk_inicial, Pvdat, Pc, Tc, Tr)
        self.density_function = abs(RHOLSat_cal - RHOLSat_esp)
        self.density_function = self.density_function / RHOLSat_esp

        #print(self.density_function)

        return self.density_function

    def resolver_delta_1_cal(self, delta_1_initial, rk_inicial, Pvdat, RHOLSat_esp, Pc, Tc, Tr):

        self.delta_1_calculated = fsolve(self.density_function_cal, delta_1_initial, args = (rk_inicial, Pvdat, RHOLSat_esp, Pc, Tc, Tr),
            xtol=1e-3)

        return self.delta_1_calculated

    def abstract_cal(self):
        return self.a, self.b
<commit_msg>eos parameters<commit_after>import numpy as np
from scipy.optimize import fsolve
from .eos_selecction import eos, convert_argument
from .constants import RGAS

'''
This module calculate parameters necessary to use the equations of state:
SRK, PR and RKPR
'''

# Constante universal de los gases R
# RGAS = 0.08314472

# Definir el significado fisicoquímico
# A0, B0, C0 = 0.0017, 1.9681, -2.7238

# Definir el significado fisicoquímico
# A1, B1, C1 = -2.4407, 7.4513, 12.504

# Definir el significado fisicoquímico
# D = np.array([0.428363, 18.496215, 0.338426, 0.660, 789.723105, 2.512392])

def getdel1(Zcin, del_1_init):
    del1 = del_1_init
    d1 = (1 + del1 ** 2) / (1 + del1)
    y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
    Zc = y / (3 * y + d1 - 1.0)
    dold = del1

    if Zc > Zcin:
        del1 = 1.01 * del1
    else:
        del1 = 0.99 * del1

    error_Z_critico = abs(Zc - Zcin)

    while error_Z_critico >= 1e-6:

        d1 = (1 + del1 ** 2) / (1 + del1)
        y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
        Zold = Zc
        Zc = y / (3 * y + d1 - 1.0)
        aux = del1
        del1 = del1 - (Zc - Zcin) * (del1 - dold) / (Zc - Zold)
        dold = aux
        error_Z_critico = abs(Zc - Zcin)

        if error_Z_critico <= 1e-6:
            break

    return del1, error_Z_critico

def get_del_1(Zcin, del_1_init):
    del1 = del_1_init
    d1 = (1 + del1 ** 2) / (1 + del1)
    y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
    Zc = y / (3 * y + d1 - 1.0)
    dold = del1

    if Zc > Zcin:
        del1 = 1.01 * del1
    else:
        del1 = 0.99 * del1

    error_Z_critico = abs(Zc - Zcin)

    while error_Z_critico >= 1e-6:

        d1 = (1 + del1 ** 2) / (1 + del1)
        y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
        Zold = Zc
        Zc = y / (3 * y + d1 - 1.0)
        aux = del1
        del1 = del1 - (Zc - Zcin) * (del1 - dold) / (Zc - Zold)
        dold = aux
        error_Z_critico = abs(Zc - Zcin)

    else:
        print("delta_1 = {0} with a error of = {1}".format(del1, error_Z_critico))

        if error_Z_critico <= 1e-6:
            break

    return del1, error_Z_critico

def compressibility_factor_cal(del1):
    d1 = (1 + del1 ** 2) / (1 + del1)
    y = 1 + (2 * (1 + del1)) ** (1.0 / 3) + (4 / (1 + del1)) ** (1.0 / 3)
    OMa = (3 * y * y + 3 * y * d1 + d1 ** 2 + d1 - 1.0) / (3 * y + d1 - 1.0) ** 2
    OMb = 1 / (3 * y + d1 - 1.0)
    Zc = y / (3 * y + d1 - 1.0)

    return Zc, OMa, OMb

def acentric_factor_cal(*arg):
    al = arg[0]
    be = arg[1]
    ga = arg[2]
    try:
        OM = 0.5 * (- be + np.sqrt(be ** 2 - 4 * al * ga)) / al
    except RuntimeWarning:
        raise RuntimeWarning
    else:
        OM = 0
    return OM

class Parameter_eos(object):
    '''
    Parameter_eos contains the methods to adjust the parameters
    delta 1 rk for the energy parameter to a function of temperature and
    setting the parameter to represent a point of density - temperature curve
    '''

    def energetic_parameter_cal(self, rk, delta_1_initial, Pc, Tc, Tr):

        self.ac = self.parameter_ab_cal(delta_1_initial, Pc, Tc)[0]
        self.a = self.ac * (3 / (2 + Tr)) ** rk

        return self.a

    def gvdW_Derivatives_cal(self, NDER, Volume, a, b, delta_1_initial, Tc, Tr):
        '''
        gvdW_Derivatives_cal: calculate the derivatives from Generalized van
        der Waals equation of state
        '''
        self.d = delta_1_initial

        c = (1 - self.d) / (1 + self.d)
        #aRT = self.a / (RGAS * T_especific)
        aRT = self.a / (RGAS * Tr * Tc)
        relation_covolume = 0.25 * b / Volume
        SUMC = c * b + Volume
        SUMD = self.d * b + Volume
        REP = -np.log(1 - 4 * relation_covolume)
        ATT = aRT * np.log(SUMD / SUMC) / (b * (c - self.d))
        ATTV = aRT / SUMC / SUMD
        REPV = 1 / (1 - 4 * relation_covolume) - 1
        REP2V = 1 / (1 - 4 * relation_covolume) ** 2 - 1
        ATT2V = aRT * Volume ** 2 * (1 / SUMD ** 2 - 1 / SUMC ** 2) \
        / (b * (c - self.d))
        F = REP + ATT
        F_V = (- REPV / Volume + ATTV)

        if NDER == 'Derivatives_of_V':
            F_2V = REP2V - ATT2V
            calculo_1 = 'F_V'
            calculo_2 = 'F_2V'
            return F, F_V, F_2V, calculo_1, calculo_2
        elif NDER == 'Derivatives_of_N':
            F_N = REP + ATT - Volume * F_V
            calculo = 'F_N'
            return F_N, calculo

    def volume_cal(self, ITYP, T, P, a, b, delta_1_initial, Tc, Tr):
        volume_iteration = 0
        VCP = b
        S3R = 1.0 / VCP
        relation_covolume_min, relation_covolume_max = 0.00, 0.99
        P_sur = P
        if ITYP >= 0.0:
            relation_covolume = 0.5
        else:
            # IDEAL GAS ESTIMATE
            relation_covolume = min(0.5, (VCP * P_sur) / (RGAS * T))
        while True:
            Volume = VCP / relation_covolume

            vdWg = self.gvdW_Derivatives_cal('Derivatives_of_V', Volume, a, b, delta_1_initial, Tc, Tr)
            F = vdWg[0]
            F_V = vdWg[1]
            F_2V = vdWg[2]
            pressure_cal_eos = RGAS * T * (1 / Volume - F_V)
            if pressure_cal_eos > P_sur:
                relation_covolume_max = relation_covolume
            else:
                relation_covolume_min = relation_covolume
            AT = F - np.log(Volume) + Volume * P_sur / (T * RGAS)
            DER = RGAS * T * (F_2V + 1.0) * S3R
            DEL = - (pressure_cal_eos - P_sur) / DER
            relation_covolume = relation_covolume + 1.0 * max(min(DEL, 0.1), -0.1)
            if relation_covolume > relation_covolume_max or relation_covolume < relation_covolume_min:
                relation_covolume = 0.5 * (relation_covolume_max + relation_covolume_min)
            if abs(DEL) < 1e-10 or volume_iteration >= 20:
                break
            volume_iteration += 1
        return Volume, pressure_cal_eos

    def fugacity_cal(self, T, P, Volume, delta_1_initial, Tc, Tr):

        Z = P * Volume / (RGAS * T)
        vdWg = self.gvdW_Derivatives_cal('Derivatives_of_N', Volume, self.a, self.b, delta_1_initial, Tc, Tr)
        F_N = vdWg[0]
        phi_fugacity = np.exp(F_N) / Z

        #print(T, T_especific)
        #print(T)
        return phi_fugacity

    def saturation_pressure_cal(self, PV_supuesta, rk_inicial, delta_1_initial, Pc, Tc, Tr):
        self.Tsat = Tr * Tc
        P_sur = PV_supuesta

        #print(self.Tsat)

        self.a = self.energetic_parameter_cal(rk_inicial, delta_1_initial, Pc, Tc, Tr)
        self.b = self.parameter_ab_cal(delta_1_initial, Pc, Tc)[1]

        self.volume_liquid = self.volume_cal(1, self.Tsat, P_sur, self.a,
        self.b, delta_1_initial, Tc, Tr)[0]

        phi_fugacity_liquid = self.fugacity_cal(self.Tsat, P_sur,
        self.volume_liquid, delta_1_initial, Tc, Tr)

        self.volume_vapor = self.volume_cal(-1, self.Tsat, P_sur, self.a,
        self.b, delta_1_initial, Tc, Tr)[0]

        phi_fugacity_vapor = self.fugacity_cal(self.Tsat, P_sur,
        self.volume_vapor, delta_1_initial, Tc, Tr)

        self.phase_equilibrium = abs(phi_fugacity_vapor - phi_fugacity_liquid)

        return self.phase_equilibrium

    def phase_equilibrium_cal(self, rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr):
        PV_inicial = Pvdat

        rk_class = rk_inicial

        self.PV_calculed = fsolve(self.saturation_pressure_cal, PV_inicial,
        args=(rk_class, delta_1_initial, Pc, Tc, Tr), xtol=1e-4)

        return self.PV_calculed

    def funcion_saturacion_cal(self, rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr):

        presion_saturada_modelo = self.phase_equilibrium_cal(rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr)
        self.saturation_function = abs(presion_saturada_modelo - Pvdat) / Pvdat

        return self.saturation_function

    def resolver_rk_cal(self, rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr):

        self.rk_calculated = fsolve(self.funcion_saturacion_cal, rk_inicial,
        args = (delta_1_initial, Pvdat, Pc, Tc, Tr), xtol=1e-4)

        return self.rk_calculated

    def parameter_ab_cal(self, delta_1_initial, Pc, Tc):

        Zc, OMa, OMb = compressibility_factor_cal(delta_1_initial)

        dc = Pc / Zc / (RGAS * Tc)
        Vceos = 1.0 / dc

        self.ac = OMa * (RGAS * Tc)**2 / Pc
        self.b = OMb * (RGAS * Tc) / Pc

        return self.ac, self.b

    def density_cal(self, delta_1_initial, rk_inicial, Pvdat, Pc, Tc, Tr):

        self.a = self.energetic_parameter_cal(rk_inicial, delta_1_initial, Pc, Tc, Tr)
        self.b = self.parameter_ab_cal(delta_1_initial, Pc, Tc)[1]

        self.rk_calculated = self.resolver_rk_cal(rk_inicial, delta_1_initial, Pvdat, Pc, Tc, Tr)

        self.volume_liquid_delta = self.volume_liquid
        self.density_liquid = 1 / self.volume_liquid_delta

        return self.density_liquid

    def density_function_cal(self, delta_1_initial, rk_inicial, Pvdat, RHOLSat_esp, Pc, Tc, Tr):

        RHOLSat_cal = self.density_cal(delta_1_initial, rk_inicial, Pvdat, Pc, Tc, Tr)
        self.density_function = abs(RHOLSat_cal - RHOLSat_esp)
        self.density_function = self.density_function / RHOLSat_esp

        #print(self.density_function)

        return self.density_function

    def resolver_delta_1_cal(self, delta_1_initial, rk_inicial, Pvdat, RHOLSat_esp, Pc, Tc, Tr):

        self.delta_1_calculated = fsolve(self.density_function_cal, delta_1_initial, args = (rk_inicial, Pvdat, RHOLSat_esp, Pc, Tc, Tr),
            xtol=1e-3)

        return self.delta_1_calculated

    def abstract_cal(self):
        return self.a, self.b
<|endoftext|>


<commit_before>"""
Support for manual alarms.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/alarm_control_panel.manual/
"""
import datetime
import logging

import blumate.components.alarm_control_panel as alarm
import blumate.util.dt as dt_util
from blumate.const import (
    STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED,
    STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED)
from blumate.helpers.event import track_point_in_time

_LOGGER = logging.getLogger(__name__)

DEFAULT_ALARM_NAME = 'HA Alarm'
DEFAULT_PENDING_TIME = 60
DEFAULT_TRIGGER_TIME = 120

def setup_platform(hass, config, add_devices, discovery_info=None):
    """Setup the manual alarm platform."""
    add_devices([VirtualAlarm(
        hass,
        config.get('name', DEFAULT_ALARM_NAME),
        config.get('code'),
        config.get('pending_time', DEFAULT_PENDING_TIME),
        config.get('trigger_time', DEFAULT_TRIGGER_TIME),
        )])

# pylint: disable=too-many-arguments, too-many-instance-attributes
# pylint: disable=abstract-method
class VirtualAlarm(alarm.AlarmControlPanel):
    """
    Represents an alarm status.

    When armed, will be pending for 'pending_time', after that armed.
    When triggered, will be pending for 'trigger_time'. After that will be
    triggered for 'trigger_time', after that we return to disarmed.
    """

    def __init__(self, hass, name, code, pending_time, trigger_time):
        """Initalize the manual alarm panel."""
        self._state = STATE_ALARM_DISARMED
        self._hass = hass
        self._name = name
        self._code = str(code) if code else None
        self._pending_time = datetime.timedelta(seconds=pending_time)
        self._trigger_time = datetime.timedelta(seconds=trigger_time)
        self._state_ts = None

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @property
    def name(self):
        """Return the name of the device."""
        return self._name

    @property
    def state(self):
        """Return the state of the device."""
        if self._state in (STATE_ALARM_ARMED_HOME,
                           STATE_ALARM_ARMED_AWAY) and \
           self._pending_time and self._state_ts + self._pending_time > \
           dt_util.utcnow():
            return STATE_ALARM_PENDING

        if self._state == STATE_ALARM_TRIGGERED and self._trigger_time:
            if self._state_ts + self._pending_time > dt_util.utcnow():
                return STATE_ALARM_PENDING
            elif (self._state_ts + self._pending_time +
                  self._trigger_time) < dt_util.utcnow():
                return STATE_ALARM_DISARMED

        return self._state

    @property
    def code_format(self):
        """One or more characters."""
        return None if self._code is None else '.+'

    def alarm_disarm(self, code=None):
        """Send disarm command."""
        if not self._validate_code(code, STATE_ALARM_DISARMED):
            return

        self._state = STATE_ALARM_DISARMED
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

    def alarm_arm_home(self, code=None):
        """Send arm home command."""
        if not self._validate_code(code, STATE_ALARM_ARMED_HOME):
            return

        self._state = STATE_ALARM_ARMED_HOME
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

        if self._pending_time:
            track_point_in_time(
                self._hass, self.update_ha_state,
                self._state_ts + self._pending_time)

    def alarm_arm_away(self, code=None):
        """Send arm away command."""
        if not self._validate_code(code, STATE_ALARM_ARMED_AWAY):
            return

        self._state = STATE_ALARM_ARMED_AWAY
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

        if self._pending_time:
            track_point_in_time(
                self._hass, self.update_ha_state,
                self._state_ts + self._pending_time)

    def alarm_trigger(self, code=None):
        """Send alarm trigger command. No code needed."""
        self._state = STATE_ALARM_TRIGGERED
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

        if self._trigger_time:
            track_point_in_time(
                self._hass, self.update_ha_state,
                self._state_ts + self._pending_time)

            track_point_in_time(
                self._hass, self.update_ha_state,
                self._state_ts + self._pending_time + self._trigger_time)

    def _validate_code(self, code, state):
        """Validate given code."""
        check = self._code is None or code == self._code
        if not check:
            _LOGGER.warning('Invalid code given for %s', state)
        return check
<commit_msg>refactor hass --> bmss<commit_after>"""
Support for manual alarms.

For more details about this platform, please refer to the documentation at
https://home-assistant.io/components/alarm_control_panel.manual/
"""
import datetime
import logging

import blumate.components.alarm_control_panel as alarm
import blumate.util.dt as dt_util
from blumate.const import (
    STATE_ALARM_ARMED_AWAY, STATE_ALARM_ARMED_HOME, STATE_ALARM_DISARMED,
    STATE_ALARM_PENDING, STATE_ALARM_TRIGGERED)
from blumate.helpers.event import track_point_in_time

_LOGGER = logging.getLogger(__name__)

DEFAULT_ALARM_NAME = 'HA Alarm'
DEFAULT_PENDING_TIME = 60
DEFAULT_TRIGGER_TIME = 120

def setup_platform(bmss, config, add_devices, discovery_info=None):
    """Setup the manual alarm platform."""
    add_devices([VirtualAlarm(
        bmss,
        config.get('name', DEFAULT_ALARM_NAME),
        config.get('code'),
        config.get('pending_time', DEFAULT_PENDING_TIME),
        config.get('trigger_time', DEFAULT_TRIGGER_TIME),
        )])

# pylint: disable=too-many-arguments, too-many-instance-attributes
# pylint: disable=abstract-method
class VirtualAlarm(alarm.AlarmControlPanel):
    """
    Represents an alarm status.

    When armed, will be pending for 'pending_time', after that armed.
    When triggered, will be pending for 'trigger_time'. After that will be
    triggered for 'trigger_time', after that we return to disarmed.
    """

    def __init__(self, bmss, name, code, pending_time, trigger_time):
        """Initalize the manual alarm panel."""
        self._state = STATE_ALARM_DISARMED
        self._bmss = bmss
        self._name = name
        self._code = str(code) if code else None
        self._pending_time = datetime.timedelta(seconds=pending_time)
        self._trigger_time = datetime.timedelta(seconds=trigger_time)
        self._state_ts = None

    @property
    def should_poll(self):
        """No polling needed."""
        return False

    @property
    def name(self):
        """Return the name of the device."""
        return self._name

    @property
    def state(self):
        """Return the state of the device."""
        if self._state in (STATE_ALARM_ARMED_HOME,
                           STATE_ALARM_ARMED_AWAY) and \
           self._pending_time and self._state_ts + self._pending_time > \
           dt_util.utcnow():
            return STATE_ALARM_PENDING

        if self._state == STATE_ALARM_TRIGGERED and self._trigger_time:
            if self._state_ts + self._pending_time > dt_util.utcnow():
                return STATE_ALARM_PENDING
            elif (self._state_ts + self._pending_time +
                  self._trigger_time) < dt_util.utcnow():
                return STATE_ALARM_DISARMED

        return self._state

    @property
    def code_format(self):
        """One or more characters."""
        return None if self._code is None else '.+'

    def alarm_disarm(self, code=None):
        """Send disarm command."""
        if not self._validate_code(code, STATE_ALARM_DISARMED):
            return

        self._state = STATE_ALARM_DISARMED
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

    def alarm_arm_home(self, code=None):
        """Send arm home command."""
        if not self._validate_code(code, STATE_ALARM_ARMED_HOME):
            return

        self._state = STATE_ALARM_ARMED_HOME
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

        if self._pending_time:
            track_point_in_time(
                self._bmss, self.update_ha_state,
                self._state_ts + self._pending_time)

    def alarm_arm_away(self, code=None):
        """Send arm away command."""
        if not self._validate_code(code, STATE_ALARM_ARMED_AWAY):
            return

        self._state = STATE_ALARM_ARMED_AWAY
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

        if self._pending_time:
            track_point_in_time(
                self._bmss, self.update_ha_state,
                self._state_ts + self._pending_time)

    def alarm_trigger(self, code=None):
        """Send alarm trigger command. No code needed."""
        self._state = STATE_ALARM_TRIGGERED
        self._state_ts = dt_util.utcnow()
        self.update_ha_state()

        if self._trigger_time:
            track_point_in_time(
                self._bmss, self.update_ha_state,
                self._state_ts + self._pending_time)

            track_point_in_time(
                self._bmss, self.update_ha_state,
                self._state_ts + self._pending_time + self._trigger_time)

    def _validate_code(self, code, state):
        """Validate given code."""
        check = self._code is None or code == self._code
        if not check:
            _LOGGER.warning('Invalid code given for %s', state)
        return check
<|endoftext|>


<commit_before>"""
Functions to spot hemy regions
"""
import os.path as op
from collections import defaultdict, Counter
import pybedtools
import pysam

from bcbio.distributed.transaction import file_transaction
from bcbio.utils import append_stem

def is_good_cpg(frmt, record):
    if record[6] != "PASS":
        return False
    if int(frmt['CU']) > 3 and int(frmt['CM']) > 3:
        return True

def _genotype(alleles):
    if alleles[0] == alleles[1]:
        return "homoz"
    else:
        return "heteroz"

def is_good_het(frmt, record):
    depth = sum(map(int, frmt['DP4'].split(','))[1:])
    if _genotype(frmt['GT'].split("/")) == "heteroz" and int(frmt['DP']) > 3 and depth > 3 and record[6] == "PASS":
        return True

def cpg_het_pairs(cpgvcf, snpvcf, out_file, workdir):
    """
    Detect het close to hemi-met sites
    """
    cpg_filter = op.join(workdir, op.basename(append_stem(cpgvcf, "_filtered")))
    snp_filter = op.join(workdir, op.basename(append_stem(snpvcf, "_filtered")))

    with open(cpg_filter, 'w') as out_handle:
        with open(cpgvcf) as in_handle:
            for line in in_handle:
                if line.startswith("#"):
                    continue
                record = line.strip().split("\t")
                # print record
                header, frmt = record[8], record[9]
                frmt = dict(zip(header.split(":"), frmt.split(':')))
                if is_good_cpg(frmt, record):
                    print >>out_handle, line

    with open(snp_filter, 'w') as out_handle:
        with open(snpvcf) as in_handle:
            for line in in_handle:
                if line.startswith("#"):
                    continue
                record = line.strip().split("\t")
                header, frmt = record[8], record[9]
                frmt = dict(zip(header.split(":"), frmt.split(':')))
                if is_good_het(frmt, record):
                    print >>out_handle, line
    res = pybedtools.BedTool(cpg_filter).window(snp_filter, w=75)
    with open(out_file, 'w') as out_handle:
        for record in res:
            if record[1] != record[11]:
                print >>out_handle, record

def _make_linkage(bam_file, chrom, cpg, snp):
    pairs = defaultdict(dict)
    pairs = _pairs_matrix(bam_file, [chrom, cpg-1, cpg], pairs, 'cpg')
    pairs = _pairs_matrix(bam_file, [chrom, snp-1, snp], pairs, 'snp')
    link = Counter()
    for pair in pairs:
        print pair
        print pairs[pair]
        if len(pairs[pair].keys()) > 1:
            link["/".join(pairs[pair].values())] += 1
    print link

def _pairs_matrix(bam_file, region, pileup, tag):
    """
    Get reads from the cpg region and pairs
    cpg nt with snp nt
    """
    c, s, e = region
    samfile = pysam.AlignmentFile(bam_file, "rb")
    for pileupcolumn in samfile.pileup(c, s, e):
        if pileupcolumn.pos == s:
            # print ("\ncoverage at base %s = %s" % (pileupcolumn.pos, pileupcolumn.n))
            for pileupread in pileupcolumn.pileups:
                if not pileupread.is_del and not pileupread.is_refskip:  # query position is None if is_del or is_refskip is set.
                    pileup[pileupread.alignment.query_name].update({tag: pileupread.alignment.query_sequence[pileupread.query_position]})

    return pileup

def get_het(in_vcf, region, sample, out_file):
    res = pybedtools.BedTool(in_vcf).intersect(b=region, wo=True)
    with file_transaction(out_file) as tx_out:
        with open(tx_out, 'w') as out_handle:
            # print >> out_handle, "chrom\tstart\tend\tgen\dp4\tstrand\tgene\tsample"

            for record in res:
                gene = record[-2]
                chrom, pos, info, header, frmt = record[0], int(record[1]), record[7], record[8], record[9]
                # cs = info.split(';')[0].split('=')[1]
                frmt = dict(zip(header.split(":"), frmt.split(':')))
                # if _genotype(frmt['GT'].split("/")) == "heteroz" and int(frmt['DP']) > 10 and int(frmt['DP4']) > 10 and record[6] == "PASS":
                if is_good_het(frmt, record):
                    tag = "%s-%s-%s-%s" % (frmt['GT'], frmt['DP'], gene, sample)
                    print >> out_handle, "%s\t%s\t%s\t%s\t.\t+" % (chrom, pos, pos + 1, tag )

<commit_msg>detect linkage<commit_after>"""
Functions to spot hemy regions
"""
import os.path as op
from collections import defaultdict, Counter
import pybedtools
import pysam

from bcbio.distributed.transaction import file_transaction
from bcbio.utils import append_stem

def is_good_cpg(frmt, record):
    alt_depth = sum(map(int, frmt['DP4'].split(','))[2:])
    ref_depth = sum(map(int, frmt['DP4'].split(','))[:2])
    if record[6] != "PASS":
        return False
    if int(ref_depth) > 3 and int(alt_depth) > 3:
        return True

def _genotype(alleles):
    if alleles[0] == alleles[1]:
        return "homoz"
    else:
        return "heteroz"

def is_good_het(frmt, record):
    depth = sum(map(int, frmt['DP4'].split(','))[2:])
    # if _genotype(frmt['GT'].split("/")) == "heteroz" and int(frmt['DP']) > 3 and depth > 3 and record[6] == "PASS":
    if _genotype(frmt['GT'].split("/")) == "heteroz" and int(frmt['DP']) > 3:
        return True

def cpg_het_pairs(cpgvcf, snpvcf, bam_file, out_file, workdir):
    """
    Detect het close to hemi-met sites
    """
    cpg_filter = op.join(workdir, op.basename(append_stem(cpgvcf, "_filtered")))
    snp_filter = op.join(workdir, op.basename(append_stem(snpvcf, "_filtered")))

    with open(cpg_filter, 'w') as out_handle:
        with open(cpgvcf) as in_handle:
            for line in in_handle:
                if line.startswith("#"):
                    continue
                record = line.strip().split("\t")
                # print record
                header, frmt = record[8], record[9]
                frmt = dict(zip(header.split(":"), frmt.split(':')))
                if is_good_cpg(frmt, record):
                    print >>out_handle, line

    with open(snp_filter, 'w') as out_handle:
        with open(snpvcf) as in_handle:
            for line in in_handle:
                if line.startswith("#"):
                    continue
                record = line.strip().split("\t")
                header, frmt = record[8], record[9]
                frmt = dict(zip(header.split(":"), frmt.split(':')))
                if is_good_het(frmt, record):
                    print >>out_handle, line
    res = pybedtools.BedTool(cpg_filter).window(snp_filter, w=75)
    with open(out_file, 'w') as out_handle:
        for record in res:
            if record[1] != record[11]:
                if record[1] == "19889634":
                    print "do"
                    _make_linkage(bam_file, record[0], int(record[1]), int(record[11]))
                print >>out_handle, record

def _make_linkage(bam_file, chrom, cpg, snp):
    pairs = defaultdict(dict)
    pairs = _pairs_matrix(bam_file, [chrom, cpg-1, cpg], pairs, 'cpg')
    pairs = _pairs_matrix(bam_file, [chrom, snp-1, snp], pairs, 'snp')
    link = Counter()
    for pair in pairs:
        print pair
        print pairs[pair]
        if len(pairs[pair].keys()) > 1:
            link["/".join(pairs[pair].values())] += 1
    print link

def _pairs_matrix(bam_file, region, pileup, tag):
    """
    Get reads from the cpg region and pairs
    cpg nt with snp nt
    """
    c, s, e = region
    samfile = pysam.AlignmentFile(bam_file, "rb")
    for pileupcolumn in samfile.pileup(c, s, e):
        if pileupcolumn.pos == s:
            # print ("\ncoverage at base %s = %s" % (pileupcolumn.pos, pileupcolumn.n))
            for pileupread in pileupcolumn.pileups:
                if not pileupread.is_del and not pileupread.is_refskip:  # query position is None if is_del or is_refskip is set.
                    pileup[pileupread.alignment.query_name].update({tag: pileupread.alignment.query_sequence[pileupread.query_position]})

    return pileup

def get_het(in_vcf, region, sample, out_file):
    res = pybedtools.BedTool(in_vcf).intersect(b=region, wo=True)
    with file_transaction(out_file) as tx_out:
        with open(tx_out, 'w') as out_handle:
            # print >> out_handle, "chrom\tstart\tend\tgen\dp4\tstrand\tgene\tsample"

            for record in res:
                gene = record[-2]
                chrom, pos, info, header, frmt = record[0], int(record[1]), record[7], record[8], record[9]
                # cs = info.split(';')[0].split('=')[1]
                frmt = dict(zip(header.split(":"), frmt.split(':')))
                # if _genotype(frmt['GT'].split("/")) == "heteroz" and int(frmt['DP']) > 10 and int(frmt['DP4']) > 10 and record[6] == "PASS":
                if is_good_het(frmt, record):
                    tag = "%s-%s-%s-%s" % (frmt['GT'], frmt['DP'], gene, sample)
                    print >> out_handle, "%s\t%s\t%s\t%s\t.\t+" % (chrom, pos, pos + 1, tag )

<|endoftext|>


<commit_before>__author__ = 'Lei Xu <eddyxu@gmail.com>'
__version__ = '0.0.1'

__classifiers__ = [
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: Apache Software License',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Topic :: Internet :: WWW/HTTP',
    'Topic :: Software Development :: Libraries']

__copyright__ = '2013, %s ' % __author__
__license__ = """
    Copyright %s.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expressed or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    """ % __copyright__

def run():
    """Run cpp coverage."""
    import os
    import argparse
    from coveralls import coverage, report

    parser = argparse.ArgumentParser('coveralls')
    parser.add_argument('--gcov', metavar='FILE', default='gcov',
                        help='Sets the location of gcov')
    parser.add_argument('-r', '--root', metavar='DIR', default='.',
                        help='Sets the root directory')
    parser.add_argument('-e', '--exclude', metavar='DIR|FILE', action='append',
                        help='Exclude file or directory.')
    parser.add_argument('--coveralls-yaml', '-y', default='.coveralls.yml',
                        help='coveralls yaml file name')
    args = parser.parse_args()

    try:
        import yaml
    except ImportError:
        yaml = None

    yml = {}
    try:
        with open(args.coveralls_yaml, 'r') as fp:
            yml = yaml.load(fp)
    except IOError:
        pass
    yml = yml or {}

    args.service_name = yml.get('service_name', 'travis-ci')
    args.service_job_id = os.environ.get('TRAVIS_JOB_ID', '')

    coverage.run_gcov(args)
    cov_report = coverage.collect(args)
    report.post_report(cov_report)
<commit_msg>Warn if PyYAML is necessary<commit_after>__author__ = 'Lei Xu <eddyxu@gmail.com>'
__version__ = '0.0.1'

__classifiers__ = [
    'Development Status :: 5 - Production/Stable',
    'Intended Audience :: Developers',
    'License :: OSI Approved :: Apache Software License',
    'Operating System :: OS Independent',
    'Programming Language :: Python',
    'Topic :: Internet :: WWW/HTTP',
    'Topic :: Software Development :: Libraries']

__copyright__ = '2013, %s ' % __author__
__license__ = """
    Copyright %s.

    Licensed under the Apache License, Version 2.0 (the "License");
    you may not use this file except in compliance with the License.
    You may obtain a copy of the License at

    http://www.apache.org/licenses/LICENSE-2.0

    Unless required by applicable law or agreed to in writing, software
    distributed under the License is distributed on an "AS IS" BASIS,
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either expressed or implied.
    See the License for the specific language governing permissions and
    limitations under the License.
    """ % __copyright__

def run():
    """Run cpp coverage."""
    import os
    import argparse
    from coveralls import coverage, report

    parser = argparse.ArgumentParser('coveralls')
    parser.add_argument('--gcov', metavar='FILE', default='gcov',
                        help='Sets the location of gcov')
    parser.add_argument('-r', '--root', metavar='DIR', default='.',
                        help='Sets the root directory')
    parser.add_argument('-e', '--exclude', metavar='DIR|FILE', action='append',
                        help='Exclude file or directory.')
    parser.add_argument('--coveralls-yaml', '-y', default='.coveralls.yml',
                        help='coveralls yaml file name')
    args = parser.parse_args()

    try:
        import yaml
    except ImportError:
        yaml = None

    yml = {}
    try:
        with open(args.coveralls_yaml, 'r') as fp:
            if yaml is None:
                raise SystemExit(
                    'PyYAML is required for parsing configuration')
            yml = yaml.load(fp)
    except IOError:
        pass
    yml = yml or {}

    args.service_name = yml.get('service_name', 'travis-ci')
    args.service_job_id = os.environ.get('TRAVIS_JOB_ID', '')

    coverage.run_gcov(args)
    cov_report = coverage.collect(args)
    report.post_report(cov_report)
<|endoftext|>


<commit_before># Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

from __future__ import absolute_import

import tornado.ioloop

from handler import register_example_endpoints
from options import get_args
from tchannel.tornado import TChannel

def main():  # pragma: no cover
    args = get_args()

    client = TChannel(
        name='tchannel_server',
        hostport='%s:%d' % (args.host, args.port),
    )

    register_example_endpoints(client)
    client.listen()

    tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':  # pragma: no cover
    main()
<commit_msg>unbreak x-language target<commit_after># Copyright (c) 2015 Uber Technologies, Inc.
#
# Permission is hereby granted, free of charge, to any person obtaining a copy
# of this software and associated documentation files (the "Software"), to deal
# in the Software without restriction, including without limitation the rights
# to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
# copies of the Software, and to permit persons to whom the Software is
# furnished to do so, subject to the following conditions:
#
# The above copyright notice and this permission notice shall be included in
# all copies or substantial portions of the Software.
#
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
# THE SOFTWARE.

import sys

import tornado.ioloop

from handler import register_example_endpoints
from options import get_args
from tchannel.tornado import TChannel

def main():  # pragma: no cover
    args = get_args()

    client = TChannel(
        name='tchannel_server',
        hostport='%s:%d' % (args.host, args.port),
    )

    register_example_endpoints(client)
    client.listen()

    print("listening on %s" % client.hostport)
    sys.stdout.flush()

    tornado.ioloop.IOLoop.instance().start()

if __name__ == '__main__':  # pragma: no cover
    main()
<|endoftext|>


<commit_before>#!/usr/bin/env python

import argparse

parser = argparse.ArgumentParser(description='Generate Latex DRS tabulars from command line')
parser.add_argument('--cols',
    help="Number of cols in main table")
parser.add_argument('--rows',
    help="Number of cols in main table")
parser.add_argument('--subtables',
    help="subtabes in main table e.g. (no spaces) [[[2, 4],[2,4]],[[6,8],[2,4]]]")

args = parser.parse_args()

def check_subtables(row, col, sub_tables):
	row_action = ""
	col_action = ""
	for s in sub_tables:
		if row == s[0][0]:
			row_action = "start row"
		if row == s[0][1]:
			row_action = "end row"
		if row >= s[0][0] and row <= s[0][1] and col == s[1][0]:
			col_action = "start col"
		if row >= s[0][0] and row <= s[0][1] and col == s[1][1]:
			col_action = "end col"
	return [row_action, col_action]

def getclines(row):
	start_row_string = ""
	end_row_string = ""
	i = 1
	for c in row:
		if c[0] == "start row" and c[1] == "start col":
			start_row_string = start_row_string + r"\cline{" + str(i) + "-"
		if c[0] == "start row" and c[1] == "end col":
			start_row_string = start_row_string + str(i) +"}"
		if c[0] == "end row" and c[1] == "start col":
			end_row_string = end_row_string + r"\cline{" + str(i) + "-"
		if c[0] == "end row" and c[1] == "end col":
			end_row_string = end_row_string + str(i) +"}"
		i += 1
	return start_row_string, end_row_string

#rows = number of rows in main table
#cols = number of columns in main table
#sub_tables: [[row_start, row_end], [col_start, cold_end]]
def makeDRS3(rows, cols, sub_tables=[]):
	r = 1
	header_cols = "".join(["c " for i in range(0, cols+1)]).strip()
	header_line = "\\begin{tabular}{|" + header_cols + "|}"
	tablegrid = []
	for rownum in range(0, rows+1):
		row = []
		for colnum in range(0, cols+1):
			row.append(check_subtables(rownum, colnum, sub_tables))
		tablegrid.append(row)
	print tablegrid
	print header_line
	print "\\hline"
	print "\multicolumn{" + str(len(tablegrid[0])) + "}{|c|}{} \\\\"
	print "\\hline"
	for row in tablegrid:
		start_row_string, end_row_string = getclines(row)
		if len(start_row_string) > 1:
			print start_row_string
		row_string = ""
		i = 1
		for c in row:
			if i > 1:
				if c[1] != "start col" and c[1] != "end col":
					row_string = row_string + "& "
				if c[1] == "start col":
					row_string = row_string + r"& \multicolumn{1}{|c}{}"
				if c[1] == "end col":
					row_string = row_string + r"& \multicolumn{1}{c|}{}"
			i += 1
		row_string = row_string + r"\\"
		print row_string
		if len(end_row_string) > 1:
			print end_row_string
	print "\\hline"
	print "\\end{tabular}"

sub_tables = []

#cols = 5
#rows = 9
#sub_tables = [[[2, 4],[2,4]], [[6,8],[2,4]]]

#print args

cols = int(args.cols)
rows = int(args.rows)
try:
	sub_tables = eval(args.subtables)
except:
	print "ERROR: improper format sub table"

makeDRS3(rows, cols, sub_tables)

<commit_msg>Fix some issues with multiple embedded tables<commit_after>#!/usr/bin/env python

import argparse

parser = argparse.ArgumentParser(description='Generate Latex DRS tabulars from command line')
parser.add_argument('--cols',
    help="Number of cols in main table")
parser.add_argument('--rows',
    help="Number of cols in main table")
parser.add_argument('--subtables',
    help="subtabes in main table e.g. (no spaces) [[[2, 4],[2,4]],[[6,8],[2,4]]]")

args = parser.parse_args()

def check_subtables(row, col, sub_tables):
	row_action = ""
	col_action = ""
	for s in sub_tables:
		#if row == s[0][0]:
		#	row_action = "start row"
		if row >= s[0][0] and row <= s[0][1] and col == s[1][0]:
			col_action = "start col"
			if row == s[0][0]:
				row_action = "start row"
			if row == s[0][1]:
				row_action = "end row"
		if row >= s[0][0] and row <= s[0][1] and col == s[1][1]:
			col_action = "end col"
			if row == s[0][0]:
				row_action = "start row"
			if row == s[0][1]:
				row_action = "end row"
	return [row_action, col_action]

def getclines(row):
	start_row_string = ""
	end_row_string = ""
	started = False
	i = 1
	#print row
	for c in row:
		if c[0] == "start row" and c[1] == "start col" and started == False:
			start_row_string = start_row_string + r"\cline{" + str(i) + "-"
			started = True
		if c[0] == "start row" and c[1] == "end col" and started == True:
			start_row_string = start_row_string + str(i) +"}"
			started = False
		if c[0] == "end row" and c[1] == "start col" and started == False:
			end_row_string = end_row_string + r"\cline{" + str(i) + "-"
			started = True
		if c[0] == "end row" and c[1] == "end col" and started == True:
			end_row_string = end_row_string + str(i) +"}"
			started = False
		i += 1
	return start_row_string, end_row_string

#rows = number of rows in main table
#cols = number of columns in main table
#sub_tables: [[row_start, row_end], [col_start, col_end]]
def makeDRS3(rows, cols, sub_tables=[], index=True):
	r = 1
	header_cols = "".join(["c " for i in range(0, cols+1)]).strip()
	header_line = "\\begin{tabular}{|" + header_cols + "|}"
	tablegrid = []
	for rownum in range(0, rows+1):
		row = []
		for colnum in range(0, cols+1):
			row.append(check_subtables(rownum, colnum, sub_tables))
		tablegrid.append(row)
	print tablegrid
	print header_line
	print "\\hline"
	print "\multicolumn{" + str(len(tablegrid[0])) + "}{|c|}{} \\\\"
	print "\\hline"
	j = 0
	for row in tablegrid:
		j += 1
		start_row_string, end_row_string = getclines(row)
		if len(start_row_string) > 1:
			print start_row_string
		row_string = ""
		i = 1
		lastc = ["", ""]
		for c in row:
			if i > 1:
				if c[1] != "start col" and c[1] != "end col":
					if index == True and j == rows + 1:
						row_string = row_string + "& " + str(i) + " "
					else:
						row_string = row_string + "& "
				if c[1] == "start col":
					row_string = row_string + r"& \multicolumn{1}{|c}{}"
				if lastc[1] == "end col" and i == len(row):
					row_string = row_string + r"& \multicolumn{1}{|c|}{}"
				elif lastc[1] == "end col":
					row_string = row_string + r"& \multicolumn{1}{|c}{}"
				lastc = c
			i += 1
		row_string = row_string + r"\\"
		print row_string
		if len(end_row_string) > 1:
			print end_row_string
	print "\\hline"
	print "\\end{tabular}"

sub_tables = []

#cols = 9
#rows = 18
#sub_tables = [[[2, 14],[2,8]], [[5,8],[4,6]], [[10,13],[4,6]]]

#print args

cols = int(args.cols)
rows = int(args.rows)
try:
	sub_tables = eval(args.subtables)
except:
	print "ERROR: improper format sub table"

makeDRS3(rows, cols, sub_tables)

<|endoftext|>


<commit_before>'''
Q-Learning is used to estimate the state-action values for a
Tic-Tac-Toe board position against a fixed Alpha-Beta opponent
'''
from capstone.game.games import TicTacToe
from capstone.game.players import AlphaBeta, RandPlayer
from capstone.game.utils import tic2pdf
from capstone.rl import FixedGameMDP, Environment
from capstone.rl.learners import QLearning
from capstone.rl.policies import RandomPolicy
from capstone.rl.utils import QValuesPlotter
from capstone.rl.value_functions import TabularQ

seed = 23
game = TicTacToe()
mdp = FixedGameMDP(game, AlphaBeta(), 1)
env = Environment(mdp)
qlearning = QLearning(
    env=env,
    qfunction=TabularQ(random_state=seed),
    policy=RandomPolicy(env.actions, random_state=seed),
    learning_rate=0.1,
    discount_factor=1.0,
    n_episodes=800,
)
qlearning.train(
    callbacks=[
        QValuesPlotter(
            state=game,
            actions=game.legal_moves(),
            filepath='figures/tic_ql_tab_full_qvalues_plot.pdf'
        )
    ]
)

####################
# Generate figures #
####################

tic2pdf('figures/tic_ql_tab_full_start_board.pdf', game.board)

for move in game.legal_moves():
    print('*' * 80)
    value = qlearning.qfunction[(game, move)]
    print('Move: %d' % move)
    print('Value: %f' % value)
    new_game = game.copy().make_move(move)
    print(new_game)
    filename = 'figures/tic_ql_tab_full_move_{}_board.pdf'.format(move)
    tic2pdf(filename, new_game.board)
<commit_msg>Refactor comments<commit_after>'''
Q-Learning is used to estimate the state-action values for all
Tic-Tac-Toe board position against a fixed Alpha-Beta opponent.
'''
from capstone.game.games import TicTacToe
from capstone.game.players import AlphaBeta, RandPlayer
from capstone.game.utils import tic2pdf
from capstone.rl import FixedGameMDP, Environment
from capstone.rl.learners import QLearning
from capstone.rl.policies import RandomPolicy
from capstone.rl.utils import QValuesPlotter
from capstone.rl.value_functions import TabularQ

seed = 23
game = TicTacToe()
mdp = FixedGameMDP(game, AlphaBeta(), 1)
env = Environment(mdp)
qlearning = QLearning(
    env=env,
    qfunction=TabularQ(random_state=seed),
    policy=RandomPolicy(env.actions, random_state=seed),
    learning_rate=0.1,
    discount_factor=1.0,
    n_episodes=800,
)
qlearning.train(
    callbacks=[
        QValuesPlotter(
            state=game,
            actions=game.legal_moves(),
            filepath='figures/tic_ql_tab_full_qvalues_plot.pdf'
        )
    ]
)

####################
# Generate figures #
####################

tic2pdf('figures/tic_ql_tab_full_start_board.pdf', game.board)

for move in game.legal_moves():
    print('*' * 80)
    value = qlearning.qfunction[(game, move)]
    print('Move: %d' % move)
    print('Value: %f' % value)
    new_game = game.copy().make_move(move)
    print(new_game)
    filename = 'figures/tic_ql_tab_full_move_{}_board.pdf'.format(move)
    tic2pdf(filename, new_game.board)
<|endoftext|>