text:
from pyradioconfig.parts.lynx.calculators.calc_synth import CALC_Synth_lynx
from pyradioconfig.calculator_model_framework.Utils.LogMgr import LogMgr
from py_2_and_3_compatibility import *
from enum import Enum
from pyradioconfig.calculator_model_framework.Utils.CustomExceptions import CalculationException
from pycalcmodel.core.variable import ModelVariableFormat, CreateModelVariableEnum
import numpy as np
#This file contains calculations related to the configuring the frequency synthesizer

class CALC_Synth_ocelot(CALC_Synth_lynx):

    fvcomin = 4450e6
    fvcomax = 5950e6

    def buildVariables(self, model):
        """Populates a list of needed variables for this calculator
        Args:
            model (ModelRoot) : Builds the variables specific to this calculator
        """

        # Build variables from Lynx
        calc_synth_lynx_obj = CALC_Synth_lynx()
        calc_synth_lynx_obj.buildVariables(model)

        # New variables
        self._addModelVariable(model, 'synth_rx_mode', Enum, ModelVariableFormat.DECIMAL)
        model.vars.synth_rx_mode.var_enum = CreateModelVariableEnum(
            enum_name='SynthRxModeEnum',
            enum_desc='Defined Synth RX Mode',
            member_data=[
                ['MODE1', 0, 'RX Mode 1'],
                ['MODE2', 1, 'RX Mode 2'],
                ['MODE3', 2, 'RX Mode 3'],
            ])
        self._addModelActual(model, 'synth_rx_mode', Enum, ModelVariableFormat.DECIMAL)
        model.vars.synth_rx_mode_actual.var_enum = model.vars.synth_rx_mode.var_enum

        self._addModelVariable(model, 'synth_tx_mode', Enum, ModelVariableFormat.DECIMAL)
        model.vars.synth_tx_mode.var_enum = CreateModelVariableEnum(
            enum_name='SynthTxModeEnum',
            enum_desc='Defined Synth TX Mode',
            member_data=[
                ['MODE1', 0, 'TX Mode 1'],
                ['MODE2', 1, 'TX Mode 2'],
                ['MODE3', 2, 'TX Mode 3'],
                ['MODE4', 3, 'TX Mode 4'],
                ['MODE5', 4, 'TX Mode 5'],
                ['MODE6', 5, 'TX Mode 6'],
                ['MODE7', 6, 'TX Mode 7'],
                ['MODE8', 7, 'TX Mode 8'],
                ['MODE9', 8, 'TX Mode 9'],
                ['MODE10', 9, 'TX Mode 10']
            ])
        self._addModelActual(model, 'synth_tx_mode', Enum, ModelVariableFormat.DECIMAL)
        model.vars.synth_tx_mode_actual.var_enum = model.vars.synth_tx_mode.var_enum

        self._addModelVariable(model, 'rf_band', Enum, ModelVariableFormat.DECIMAL)
        model.vars.rf_band.var_enum = CreateModelVariableEnum(
            enum_name='RFBandEnum',
            enum_desc='RF Band',
            member_data=[
                ['BAND_169', 0, '169 MHz Band'],
                ['BAND_315', 1, '315 MHz Band'],
                ['BAND_434', 2, '434 MHz Band'],
                ['BAND_490', 3, '490 MHz Band'],
                ['BAND_868', 4, '868 MHz Band'],
                ['BAND_915', 5, '915 MHz Band'],
                ['BAND_1432', 6, '1432 MHz Band'],
                ['BAND_2400', 7, '2400 MHz Band'],
            ])

        self._addModelVariable(model, 'synth_settling_mode', Enum, ModelVariableFormat.DECIMAL)
        model.vars.synth_settling_mode.var_enum = CreateModelVariableEnum(
            enum_name='SynthSettlingMode',
            enum_desc='Synth Settling Mode',
            member_data=[
                ['NORMAL', 0, 'Normal Operation Mode (Recommended)'],
                ['FAST', 1, 'Fast Settling (higher current)'],
                ['FASTEST', 2, 'Fastest Settling (higher current and phase noise)'],
            ])

        #Deprecated variable (needs to stay around as we have a deprecated Profile Input)
        self._addModelVariable(model, 'max_tx_power_dbm', int, ModelVariableFormat.DECIMAL,
                               desc='Maximum transmit power expected from this device (DEPRECATED)')

    def calc_rf_band(self, model):
       ### revised to include BAND_315
        rf_freq = model.vars.base_frequency_hz.value

        if ( rf_freq > 2.0e9 ):
            model.vars.rf_band.value = model.vars.rf_band.var_enum.BAND_2400
        elif ( rf_freq > 1.2e9 ):
            model.vars.rf_band.value = model.vars.rf_band.var_enum.BAND_1432
        elif ( rf_freq > 885e6 ):
            model.vars.rf_band.value = model.vars.rf_band.var_enum.BAND_915
        elif( rf_freq > 700e6 ):
            model.vars.rf_band.value = model.vars.rf_band.var_enum.BAND_868
        elif( rf_freq > 455e6 ):
            model.vars.rf_band.value = model.vars.rf_band.var_enum.BAND_490
        elif( rf_freq > 400e6  ):
            model.vars.rf_band.value = model.vars.rf_band.var_enum.BAND_434
        elif (rf_freq > 300e6 ):
            model.vars.rf_band.value = model.vars.rf_band.var_enum.BAND_315
        else:
            model.vars.rf_band.value = model.vars.rf_band.var_enum.BAND_169

    #

    def calc_synth_settling_mode(self, model):

        #Set synth settling mode to Normal for now
        model.vars.synth_settling_mode.value = model.vars.synth_settling_mode.var_enum.NORMAL

    def calc_rx_mode(self, model):

        # Revised for unified PHYs from Ranga per https://jira.silabs.com/browse/MCUW_RADIO_CFG-1477

        synth_settling_mode = model.vars.synth_settling_mode.value

        if synth_settling_mode == model.vars.synth_settling_mode.var_enum.FAST:
            model.vars.synth_rx_mode.value = model.vars.synth_rx_mode.var_enum.MODE3
        elif synth_settling_mode == model.vars.synth_settling_mode.var_enum.FASTEST:
            model.vars.synth_rx_mode.value = model.vars.synth_rx_mode.var_enum.MODE1
        else:
            model.vars.synth_rx_mode.value = model.vars.synth_rx_mode.var_enum.MODE2

    def calc_tx_mode(self, model):

        band = model.vars.rf_band.value
        etsi = model.vars.etsi_cat1_compatible.value
        baudrate = model.vars.baudrate.value
        modulation_type = model.vars.modulation_type.value

        # Revised TX settings from Ranga per https://jira.silabs.com/browse/MCUW_RADIO_CFG-1379
        # Revised for unified PHYs per https://jira.silabs.com/browse/MCUW_RADIO_CFG-1476

        # Fixed settings for OOK, DBPSK, BPSK
        if modulation_type == model.vars.modulation_type.var_enum.DBPSK:
            model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE8       # Sub-GHz, 3 MHz, QNC
        elif modulation_type == model.vars.modulation_type.var_enum.BPSK:
            model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE6       # Sub-GHz, 2 MHz, QNC
        elif modulation_type == model.vars.modulation_type.var_enum.OOK:
            model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE4       # Sub-GHz, 500 kHz, QNC
        else:
            # Settings based on band and baudrate
            if band == model.vars.rf_band.var_enum.BAND_2400:
                if baudrate > 1.5e6:
                    model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE10  # 2.4 GHz, 1.5 MHz, BLE 2Mbps
                else:
                    model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE9  # 2.4 GHz, 1 MHz, BLE 1 Mbps
            elif baudrate > 1250e3:
                model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE8  # Sub-GHz, 3 MHz, QNC
            elif baudrate > 1000e3:
                model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE7  # Sub-GHz, 2.5 MHz, QNC
            elif baudrate > 750e3:
                model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE6  # Sub-GHz, 2 MHz, QNC
            elif baudrate > 500e3:
                model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE1  # Sub-GHz, 1.5 MHz, QNC
            elif baudrate > 333e3:
                model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE5  # Sub-GHz, 1 MHz, QNC
            elif baudrate > 200e3:
                model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE4  # Sub-GHz, 500 kHz, QNC
            elif etsi == model.vars.etsi_cat1_compatible.var_enum.Band_868:  # Mode 3 only for 868 MHz - 14/20/27 dBm
                model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE3  # Sub-GHz, 350 kHz, QNC
            else:  # Mode 2 default for all narrow-band PHYs and all Pout - 14/20/24/27/30 dBm
                model.vars.synth_tx_mode.value = model.vars.synth_tx_mode.var_enum.MODE2  # Sub-GHz, 300 kHz, LP

    def calc_rx_mode_reg(self, model):

        rx_mode = model.vars.synth_rx_mode.value
        ind = rx_mode.value

        # Revised for unified PHYs from Ranga per https://jira.silabs.com/browse/MCUW_RADIO_CFG-1477

        rx_mode_settings = {
            'SYNTH.LPFCTRL2RX.CASELRX':         [1,1,0],
            'SYNTH.LPFCTRL2RX.CAVALRX':         [8,16,0],
            'SYNTH.LPFCTRL2RX.CZSELRX':         [1,1,1],
            'SYNTH.LPFCTRL2RX.CZVALRX':         [70,128,254],
            'SYNTH.LPFCTRL2RX.CFBSELRX':        [0,0,0],
            'SYNTH.LPFCTRL2RX.LPFGNDSWENRX':    [0,0,0],
            'SYNTH.LPFCTRL2RX.MODESELRX':       [0,0,1],
            'SYNTH.LPFCTRL1RX.OP1BWRX':         [5,0,0],
            'SYNTH.LPFCTRL1RX.OP1COMPRX':       [13,7,10],
            'SYNTH.LPFCTRL1RX.RFBVALRX':        [0,0,2],
            'SYNTH.LPFCTRL1RX.RPVALRX':         [0,7,5],
            'SYNTH.LPFCTRL1RX.RZVALRX':         [3,14,9],
            'SYNTH.LPFCTRL2RX.LPFSWENRX':       [1,1,1],
            'SYNTH.DSMCTRLRX.REQORDERRX':       [0,0,0],
            'SYNTH.DSMCTRLRX.MASHORDERRX':      [0,1,0],
            'SYNTH.DSMCTRLRX.DEMMODERX':        [1,0,1],
            'SYNTH.DSMCTRLRX.LSBFORCERX':       [0,1,0],
            'SYNTH.DSMCTRLRX.DSMMODERX':        [0,1,0],
            'SYNTH.DSMCTRLRX.DITHERDACRX':      [3,0,3],
            'SYNTH.DSMCTRLRX.DITHERDSMOUTPUTRX':[7,0,7],
            'SYNTH.DSMCTRLRX.DITHERDSMINPUTRX': [1,0,1],
            'RAC.SYMMDCTRL.SYMMDMODERX':        [2,4,2],
            'RAC.SYTRIM1.SYLODIVLDOTRIMNDIORX': [4,4,4],
            'RAC.SYTRIM1.SYLODIVLDOTRIMCORERX': [0,0,0],
            'RAC.VCOCTRL.VCODETAMPLITUDERX':    [4,4,4],
            'RAC.SYTRIM0.SYCHPCURRRX':          [5,5,5],
            'RAC.SYTRIM0.SYCHPREPLICACURRADJ':  [1,1,1],
            'RAC.RX.SYCHPBIASTRIMBUFRX':        [1,0,1],
            'RAC.RX.SYPFDCHPLPENRX':            [0,1,0],
            'RAC.RX.SYPFDFPWENRX':              [0,1,0],
            'RAC.SYEN.SYCHPLPENRX':             [0,1,0],
            'RAC.SYTRIM0.SYCHPLEVPSRCRX':       [7,0,7],
            'RAC.SYTRIM0.SYCHPSRCENRX':         [1,0,1]}

        self._reg_write(model.vars.SYNTH_LPFCTRL2RX_CASELRX,          rx_mode_settings['SYNTH.LPFCTRL2RX.CASELRX'][ind] )
        self._reg_write(model.vars.SYNTH_LPFCTRL2RX_CAVALRX,          rx_mode_settings['SYNTH.LPFCTRL2RX.CAVALRX'][ind] )
        self._reg_write(model.vars.SYNTH_LPFCTRL2RX_CZSELRX,          rx_mode_settings['SYNTH.LPFCTRL2RX.CZSELRX'][ind] )
        self._reg_write(model.vars.SYNTH_LPFCTRL2RX_CZVALRX,          rx_mode_settings['SYNTH.LPFCTRL2RX.CZVALRX'][ind] )
        self._reg_write(model.vars.SYNTH_LPFCTRL2RX_CFBSELRX,         rx_mode_settings['SYNTH.LPFCTRL2RX.CFBSELRX'][ind] )
        self._reg_write(model.vars.SYNTH_LPFCTRL2RX_LPFGNDSWENRX,     rx_mode_settings['SYNTH.LPFCTRL2RX.LPFGNDSWENRX'][ind] )
        self._reg_write(model.vars.SYNTH_LPFCTRL2RX_MODESELRX,        rx_mode_settings['SYNTH.LPFCTRL2RX.MODESELRX'][ind] )
        self._reg_write(model.vars.SYNTH_LPFCTRL1RX_OP1BWRX,          rx_mode_settings['SYNTH.LPFCTRL1RX.OP1BWRX'][ind] )
        self._reg_write(model.vars.SYNTH_LPFCTRL1RX_OP1COMPRX,        rx_mode_settings['SYNTH.LPFCTRL1RX.OP1COMPRX'][ind] )
        self._reg_write(model.vars.SYNTH_LPFCTRL1RX_RFBVALRX,         rx_mode_settings['SYNTH.LPFCTRL1RX.RFBVALRX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL1RX_RPVALRX,          rx_mode_settings['SYNTH.LPFCTRL1RX.RPVALRX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL1RX_RZVALRX,          rx_mode_settings['SYNTH.LPFCTRL1RX.RZVALRX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL2RX_LPFSWENRX,        rx_mode_settings['SYNTH.LPFCTRL2RX.LPFSWENRX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLRX_REQORDERRX,        rx_mode_settings['SYNTH.DSMCTRLRX.REQORDERRX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLRX_MASHORDERRX,       rx_mode_settings['SYNTH.DSMCTRLRX.MASHORDERRX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLRX_DEMMODERX,         rx_mode_settings['SYNTH.DSMCTRLRX.DEMMODERX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLRX_LSBFORCERX,        rx_mode_settings['SYNTH.DSMCTRLRX.LSBFORCERX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLRX_DSMMODERX,         rx_mode_settings['SYNTH.DSMCTRLRX.DSMMODERX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLRX_DITHERDACRX,       rx_mode_settings['SYNTH.DSMCTRLRX.DITHERDACRX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLRX_DITHERDSMOUTPUTRX, rx_mode_settings['SYNTH.DSMCTRLRX.DITHERDSMOUTPUTRX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLRX_DITHERDSMINPUTRX,  rx_mode_settings['SYNTH.DSMCTRLRX.DITHERDSMINPUTRX'][ind])
        self._reg_write(model.vars.RAC_SYMMDCTRL_SYMMDMODERX,         rx_mode_settings['RAC.SYMMDCTRL.SYMMDMODERX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM1_SYLODIVLDOTRIMNDIORX,  rx_mode_settings['RAC.SYTRIM1.SYLODIVLDOTRIMNDIORX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM1_SYLODIVLDOTRIMCORERX,  rx_mode_settings['RAC.SYTRIM1.SYLODIVLDOTRIMCORERX'][ind])
        self._reg_write(model.vars.RAC_VCOCTRL_VCODETAMPLITUDERX,     rx_mode_settings['RAC.VCOCTRL.VCODETAMPLITUDERX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM0_SYCHPCURRRX,           rx_mode_settings['RAC.SYTRIM0.SYCHPCURRRX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM0_SYCHPREPLICACURRADJ,   rx_mode_settings['RAC.SYTRIM0.SYCHPREPLICACURRADJ'][ind])
        self._reg_write(model.vars.RAC_RX_SYCHPBIASTRIMBUFRX,         rx_mode_settings['RAC.RX.SYCHPBIASTRIMBUFRX'][ind])
        self._reg_write(model.vars.RAC_RX_SYPFDCHPLPENRX,             rx_mode_settings['RAC.RX.SYPFDCHPLPENRX'][ind])
        self._reg_write(model.vars.RAC_RX_SYPFDFPWENRX,               rx_mode_settings['RAC.RX.SYPFDFPWENRX'][ind])
        self._reg_write(model.vars.RAC_SYEN_SYCHPLPENRX,              rx_mode_settings['RAC.SYEN.SYCHPLPENRX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM0_SYCHPLEVPSRCRX,        rx_mode_settings['RAC.SYTRIM0.SYCHPLEVPSRCRX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM0_SYCHPSRCENRX,          rx_mode_settings['RAC.SYTRIM0.SYCHPSRCENRX'][ind])

    def calc_tx_mode_reg(self, model):

        tx_mode = model.vars.synth_tx_mode.value
        ind = tx_mode.value

        # Revised TX settings from Ranga per https://jira.silabs.com/browse/MCUW_RADIO_CFG-1379
        # Revised for unified PHYs per https://jira.silabs.com/browse/MCUW_RADIO_CFG-1476

        tx_mode_settings = {
            'SYNTH.LPFCTRL2TX.CASELTX':         [1,1,0,0,1,1,1,1,1,1],
            'SYNTH.LPFCTRL2TX.CAVALTX':         [8,16,0,0,15,6,4,2,15,8],
            'SYNTH.LPFCTRL2TX.CZSELTX':         [1,1,1,1,1,1,1,1,1,1],
            'SYNTH.LPFCTRL2TX.CZVALTX':         [70,128,255,215,126,40,22,6,126,70],
            'SYNTH.LPFCTRL2TX.CFBSELTX':        [0,0,0,0,0,0,0,0,0,0],
            'SYNTH.LPFCTRL2TX.LPFGNDSWENTX':    [0,0,0,0,0,0,0,0,0,0],
            'SYNTH.LPFCTRL2TX.MODESELTX':       [0,0,1,1,0,0,0,0,0,0],
            'SYNTH.LPFCTRL1TX.OP1BWTX':         [5,0,0,0,0,8,11,15,0,5],
            'SYNTH.LPFCTRL1TX.OP1COMPTX':       [13,7,10,11,13,13,14,15,13,13],
            'SYNTH.LPFCTR1TX.RFBVALTX':         [0,0,4,7,0,0,0,0,0,0],
            'SYNTH.LPFCTRL1TX.RPVALTX':         [0,7,3,1,0,0,0,0,0,0],
            'SYNTH.LPFCTRL1TX.RZVALTX':         [3,14,4,0,0,6,9,11,0,3],
            'SYNTH.LPFCTRL2TX.LPFSWENTX':       [1,1,1,1,1,1,1,1,1,1],
            'SYNTH.DSMCTRLTX.REQORDERTX':       [0,0,0,0,0,0,0,0,0,0],
            'SYNTH.DSMCTRLTX.MASHORDERTX':      [0,1,0,0,0,0,0,0,0,0],
            'SYNTH.DSMCTRLTX.DEMMODETX':        [1,0,1,1,1,1,1,1,1,1],
            'SYNTH.DSMCTRLTX.LSBFORCETX':       [0,1,0,0,0,0,0,0,0,0],
            'SYNTH.DSMCTRLTX.DSMMODETX':        [0,1,0,0,0,0,0,0,0,0],
            'SYNTH.DSMCTRLTX.DITHERDACTX':      [3,0,3,3,3,3,3,3,3,3],
            'SYNTH.DSMCTRLTX.DITHERDSMOUTPUTTX':[3,0,3,3,3,3,3,3,3,3],
            'SYNTH.DSMCTRLTX.DITHERDSMINPUTTX': [1,0,1,1,1,1,1,1,1,1],
            'RAC.SYMMDCTRL.SYMMDMODETX':        [2,4,2,2,2,2,2,2,2,2],
            'RAC.SYTRIM1.SYLODIVLDOTRIMNDIOTX': [4,4,4,4,4,4,4,4,4,4],
            'RAC.SYTRIM1.SYLODIVLDOTRIMCORETX': [0,0,0,0,0,0,0,0,0,0],
            'RAC.VCOCTRL.VCODETAMPLITUDETX':    [4,4,4,4,4,4,4,4,4,4],
            'RAC.TX.SYCHPBIASTRIMBUFTX':        [1,0,1,1,1,1,1,1,1,1],
            'RAC.TX.SYPFDCHPLPENTX':            [0,1,0,0,0,0,0,0,0,0],
            'RAC.TX.SYPFDFPWENTX':              [0,1,0,0,0,0,0,0,0,0],
            'RAC.SYEN.SYCHPLPENTX':             [0,1,0,0,0,0,0,0,0,0],
            'RAC.SYTRIM0.SYCHPLEVPSRCTX':       [7,0,7,7,7,7,7,7,7,7],
            'RAC.SYTRIM0.SYCHPSRCENTX':         [1,0,1,1,1,1,1,1,1,1]}

        self._reg_write(model.vars.SYNTH_LPFCTRL2TX_CASELTX,            tx_mode_settings['SYNTH.LPFCTRL2TX.CASELTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL2TX_CAVALTX,            tx_mode_settings['SYNTH.LPFCTRL2TX.CAVALTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL2TX_CZSELTX,            tx_mode_settings['SYNTH.LPFCTRL2TX.CZSELTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL2TX_CZVALTX,            tx_mode_settings['SYNTH.LPFCTRL2TX.CZVALTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL2TX_CFBSELTX,           tx_mode_settings['SYNTH.LPFCTRL2TX.CFBSELTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL2TX_LPFGNDSWENTX,       tx_mode_settings['SYNTH.LPFCTRL2TX.LPFGNDSWENTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL2TX_MODESELTX,          tx_mode_settings['SYNTH.LPFCTRL2TX.MODESELTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL1TX_OP1BWTX,            tx_mode_settings['SYNTH.LPFCTRL1TX.OP1BWTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL1TX_OP1COMPTX,          tx_mode_settings['SYNTH.LPFCTRL1TX.OP1COMPTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL1TX_RFBVALTX,           tx_mode_settings['SYNTH.LPFCTR1TX.RFBVALTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL1TX_RPVALTX,            tx_mode_settings['SYNTH.LPFCTRL1TX.RPVALTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL1TX_RZVALTX,            tx_mode_settings['SYNTH.LPFCTRL1TX.RZVALTX'][ind])
        self._reg_write(model.vars.SYNTH_LPFCTRL2TX_LPFSWENTX,          tx_mode_settings['SYNTH.LPFCTRL2TX.LPFSWENTX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLTX_REQORDERTX,          tx_mode_settings['SYNTH.DSMCTRLTX.REQORDERTX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLTX_MASHORDERTX,         tx_mode_settings['SYNTH.DSMCTRLTX.MASHORDERTX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLTX_DEMMODETX,           tx_mode_settings['SYNTH.DSMCTRLTX.DEMMODETX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLTX_LSBFORCETX,          tx_mode_settings['SYNTH.DSMCTRLTX.LSBFORCETX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLTX_DSMMODETX,           tx_mode_settings['SYNTH.DSMCTRLTX.DSMMODETX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLTX_DITHERDACTX,         tx_mode_settings['SYNTH.DSMCTRLTX.DITHERDACTX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLTX_DITHERDSMOUTPUTTX,   tx_mode_settings['SYNTH.DSMCTRLTX.DITHERDSMOUTPUTTX'][ind])
        self._reg_write(model.vars.SYNTH_DSMCTRLTX_DITHERDSMINPUTTX ,   tx_mode_settings['SYNTH.DSMCTRLTX.DITHERDSMINPUTTX'][ind])
        self._reg_write(model.vars.RAC_SYMMDCTRL_SYMMDMODETX,           tx_mode_settings['RAC.SYMMDCTRL.SYMMDMODETX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM1_SYLODIVLDOTRIMNDIOTX,    tx_mode_settings['RAC.SYTRIM1.SYLODIVLDOTRIMNDIOTX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM1_SYLODIVLDOTRIMCORETX,    tx_mode_settings['RAC.SYTRIM1.SYLODIVLDOTRIMCORETX'][ind])
        self._reg_write(model.vars.RAC_VCOCTRL_VCODETAMPLITUDETX,       tx_mode_settings['RAC.VCOCTRL.VCODETAMPLITUDETX'][ind])
        self._reg_write(model.vars.RAC_TX_SYCHPBIASTRIMBUFTX,           tx_mode_settings['RAC.TX.SYCHPBIASTRIMBUFTX'][ind])
        self._reg_write(model.vars.RAC_TX_SYPFDCHPLPENTX,               tx_mode_settings['RAC.TX.SYPFDCHPLPENTX'][ind])
        self._reg_write(model.vars.RAC_TX_SYPFDFPWENTX,                 tx_mode_settings['RAC.TX.SYPFDFPWENTX'][ind])
        self._reg_write(model.vars.RAC_SYEN_SYCHPLPENTX,                tx_mode_settings['RAC.SYEN.SYCHPLPENTX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM0_SYCHPLEVPSRCTX,          tx_mode_settings['RAC.SYTRIM0.SYCHPLEVPSRCTX'][ind])
        self._reg_write(model.vars.RAC_SYTRIM0_SYCHPSRCENTX,            tx_mode_settings['RAC.SYTRIM0.SYCHPSRCENTX'][ind])

    def calc_sytrim0_sychpcurrtx_reg(self, model):
        # This function calculates the SYTRIM0_SYCHPCURRTX field

        #For now, always use value 5
        sychpcurrtx = 5

        # Write the register
        self._reg_write(model.vars.RAC_SYTRIM0_SYCHPCURRTX, sychpcurrtx)

    def calc_adc_clock_config(self, model):
        #This function calculates both the ADC mode (e.g. fullrate, halfrate, etc) as well as the ADC clock divider path

        #Load model values into local variables
        bandwidth_hz = model.vars.bandwidth_hz.value

        if(bandwidth_hz < 100e3):
            #1/8 rate mode, noise density is lowest in 50-100kHz range
            #Use the HFXO for the ADC clock
            adc_rate_mode = model.vars.adc_rate_mode.var_enum.EIGHTHRATE
            adc_clock_mode = model.vars.adc_clock_mode.var_enum.HFXOMULT
        elif(bandwidth_hz < 1.25e6):
            #1/2 rate mode
            #Use the HFXO along with DPLL for the ADC clock
            adc_rate_mode = model.vars.adc_rate_mode.var_enum.HALFRATE
            adc_clock_mode = model.vars.adc_clock_mode.var_enum.HFXOMULT
        else:
            #Full rate mode
            #Use the divided down VCO for the ADC clock
            adc_rate_mode = model.vars.adc_rate_mode.var_enum.FULLRATE
            adc_clock_mode = model.vars.adc_clock_mode.var_enum.HFXOMULT

        #Load local variables back into model variables
        model.vars.adc_clock_mode.value = adc_clock_mode
        model.vars.adc_rate_mode.value = adc_rate_mode

    def calc_adc_clockmode_reg(self,model):
        #This function handles writes to the registers impacting ADC clock mode
        adc_clock_mode = model.vars.adc_clock_mode.value

        if( model.vars.adc_clock_mode.var_enum.HFXOMULT == adc_clock_mode ):
            self._reg_write(model.vars.RAC_IFADCTRIM0_IFADCCLKSEL, 1)
        else:
            self._reg_write(model.vars.RAC_IFADCTRIM0_IFADCCLKSEL, 0)

    def calc_adc_clockmode_actual(self, model):
        #This function calculates the actual value of the adc clock mode based on the register value used
        ifadc_clk_sel = model.vars.RAC_IFADCTRIM0_IFADCCLKSEL.value

        if( 1 == ifadc_clk_sel ):
            model.vars.adc_clock_mode_actual.value = model.vars.adc_clock_mode.var_enum.HFXOMULT
        else:
            model.vars.adc_clock_mode_actual.value = model.vars.adc_clock_mode.var_enum.VCODIV

    def calc_adc_rate_mode_reg(self,model):
        #This function handles writes to the registers impacting ADC clock mode and HFXO multiplier
        adc_rate_mode = model.vars.adc_rate_mode.value
        adc_clock_mode = model.vars.adc_clock_mode.value

        if(model.vars.adc_rate_mode.var_enum.FULLRATE == adc_rate_mode):
            self._reg_write(model.vars.RAC_IFADCPLLDCO_IFADCPLLDCOFULLRATE, 1)
            self._reg_write(model.vars.RAC_IFADCPLLEN_IFADCPLLENXOBYP, 0)
        elif (model.vars.adc_rate_mode.var_enum.HALFRATE == adc_rate_mode):
            self._reg_write(model.vars.RAC_IFADCPLLDCO_IFADCPLLDCOFULLRATE, 0)
            self._reg_write(model.vars.RAC_IFADCPLLEN_IFADCPLLENXOBYP, 0)
        else:
            # Eigthrate
            self._reg_write(model.vars.RAC_IFADCPLLEN_IFADCPLLENXOBYP, 1)
            self._reg_write(model.vars.RAC_IFADCPLLDCO_IFADCPLLDCOFULLRATE, 0)

    # FIXME: do we have VCO based on clock option in Sol? if not remove that path
    def calc_adc_target_freq(self, model):
        #This function calculates the target sample frequency based on the ADC clock configuration

        #Load model variables into local variables
        adc_rate_mode = model.vars.adc_rate_mode.value #Use the target rate mode for now because we haven't yet chosen the exact VCODIV value
        adc_clock_mode = model.vars.adc_clock_mode.value
        xtal_frequency_hz = model.vars.xtal_frequency_hz.value

        if (model.vars.adc_clock_mode.var_enum.HFXOMULT == adc_clock_mode):
            if (adc_rate_mode == model.vars.adc_rate_mode.var_enum.FULLRATE):
                fadc_target = 8 * xtal_frequency_hz
            elif(adc_rate_mode==model.vars.adc_rate_mode.var_enum.HALFRATE):
                fadc_target = 4 * xtal_frequency_hz
            else:
                fadc_target = xtal_frequency_hz
        else:
            #Clock mode is VCODIV
            if(adc_rate_mode==model.vars.adc_rate_mode.var_enum.HALFRATE):
                fadc_target = 152.5e6
            else:
                fadc_target = 305e6   #Target full rate

        #Load local variables back into model variables
        model.vars.adc_target_freq.value = int(fadc_target)

    def calc_lo_adc_dividers(self,model):
        #This function calculates A,B,C, ADC dividers

        #Load model variables into local variables
        adc_clock_mode = model.vars.adc_clock_mode_actual.value
        flo = model.vars.lo_target_freq.value #We don't know the LO frequency yet, this is based on the center freq and target IF
        fadc_target = model.vars.adc_target_freq.value #We don't know the ADC frequency yet

        #Define VCO pull range constants
        #fvcomin = 4450e6
        #fvcomax = 5950e6

        #These array variables store all valid divider sets
        # lodiv_codes[div-1] is the combined divider code for divider A, B, C
        #    div_m_1  [0,1,2,3,4,5,6, 7, 8, 9,10,11,12,13,14,15,16,17,18,19,20,21,22,23]
        lodiv_codes = [1,2,3,4,5,6,7,20,27,21, 0,22, 0,23,29,36, 0,30, 0,37,31, 0, 0,38]
        fosc = []
        lodiv = []
        #Loop through all C,B,A divider possibilities
        for div_m_1 in range(24):
            fvco = flo * (2 * (div_m_1 + 1))
            if (lodiv_codes[div_m_1] > 0) and (fvco < self.fvcomax) and (fvco > self.fvcomin):
                #If this is a valid value for the VCO, add to the list of valid divider combinations
                lodiv.append(div_m_1+1)
                fosc.append(fvco)

        #Now go through all of the possible solutions and pick the best one
        if (len(fosc) == 0):
            raise CalculationException('ERROR: no valid solution for VCO frequency in calc_lo_adc_dividers()')

        else:
            # If the ADC is based directly on the HFXO, then don't worry about the ADC divider and pick the first valid LO divider set
            if(adc_clock_mode==model.vars.adc_clock_mode.var_enum.HFXOMULT):
                adcdivfinal = 0 #This is a don't care, but make it 1 so that any calculations using the value don't divide by zero
                lodivfinal = lodiv[0]
            else:
                # Find target freq for ADC from potential candidates
                # Start with some initial values
                fadcerr = 1e20
                adcdivfinal = 1
                lodivfinal = 1
                for index in range(0,len(fosc)):
                    adcdiv = int(round(fosc[index] / 2.0 / fadc_target))
                    fadc = fosc[index] / (2 * adcdiv)

                    error = abs(fadc - fadc_target)

                    if (error < fadcerr):
                        #If the current divider set yields the lowest ADC error, then make that the final for now
                        fadcerr = error
                        adcdivfinal = adcdiv
                        lodivfinal = lodiv[index]

        #Calculate the A,B,C dividers from lodiv_reg and its 3 fields
        lodiv_reg  = lodiv_codes[lodivfinal-1]

        #Load local variables back into model variables
        model.vars.adc_vco_div.value = adcdivfinal
        model.vars.lodiv.value = lodivfinal

        #Write register
        self._reg_write(model.vars.SYNTH_DIVCTRL_LODIVFREQCTRL, lodiv_reg)

        # calculate proper variable flag to determine sub-GHz
        model.vars.subgig_band.value = bool(model.vars.lodiv_actual.value > 1)

    def calc_lodividers_actual(self, model):

        lodiv_reg = model.vars.SYNTH_DIVCTRL_LODIVFREQCTRL.value

        a_divider = 7 & lodiv_reg
        b_divider = 7 & (lodiv_reg >> 3)
        if b_divider == 0:
            b_divider = 1
        c_divider = 7 & (lodiv_reg >> 6)
        if c_divider == 0:
            c_divider = 1

        model.vars.a_divider_actual.value = a_divider
        model.vars.b_divider_actual.value = b_divider
        model.vars.c_divider_actual.value = c_divider

        model.vars.lodiv_actual.value = a_divider * b_divider * c_divider

    def calc_adc_vco_div_reg(self,model):
        #This function writes the registers associated with the VCO Divider going to ADC
        #Only care about this register when in VCO mode in XO mode exceptions are ignored
        adc_vco_div = model.vars.adc_vco_div.value
        adc_clock_mode = model.vars.adc_clock_mode_actual.value

        if adc_vco_div < 8:
            adc_vco_div = 8
            if adc_clock_mode==model.vars.adc_clock_mode.var_enum.VCODIV:
                raise CalculationException('WARNING: ADC_VCO_DIV is less than 8 in calc_adc_vco_div_reg()')

        if adc_vco_div > 23:
            adc_vco_div = 23
            if adc_clock_mode == model.vars.adc_clock_mode.var_enum.VCODIV:
                raise CalculationException('WARNING: ADC_VCO_DIV is greater than 8 in calc_adc_vco_div_reg()')

        # 16 codes [0:15]. Code 0 = div8 and code 15 = div23
        self._reg_write(model.vars.RAC_SYDIVCTRL_SYLODIVRADCDIV, adc_vco_div-8)

    def calc_adc_vco_div_actual(self,model):
        #This function calculates the actual ADC divider based on the register value
        sy_lo_divr_adc_div = model.vars.RAC_SYDIVCTRL_SYLODIVRADCDIV.value

        model.vars.adc_vco_div_actual.value = sy_lo_divr_adc_div + 8

    def calc_adc_freq_actual(self,model):
        #This function calculates the actual ADC sample frequency and error based on the registers

        #Load model variables into local variables
        adc_clock_mode_actual = model.vars.adc_clock_mode_actual.value
        adc_vco_div_actual = model.vars.adc_vco_div_actual.value
        xtal_frequency_hz = model.vars.xtal_frequency_hz.value
        fsynth = model.vars.rx_synth_freq_actual.value
        fadc_target = model.vars.adc_target_freq.value #The target frequency is used for computing error
        ifadcpll_dco_fullrate = model.vars.RAC_IFADCPLLDCO_IFADCPLLDCOFULLRATE.value
        ifadcpll_en_xo_bypass = model.vars.RAC_IFADCPLLEN_IFADCPLLENXOBYP.value

        if adc_clock_mode_actual == model.vars.adc_clock_mode.var_enum.HFXOMULT:
            #the ordering of the if statements is important - keep ifadcpll_en_xo_bypass on top
            if 1 == ifadcpll_en_xo_bypass:
                adc_freq_actual = xtal_frequency_hz
            elif 1 == ifadcpll_dco_fullrate:
                adc_freq_actual = xtal_frequency_hz * 8
            else:
                adc_freq_actual = xtal_frequency_hz * 4
        else:
            adc_freq_actual = int(fsynth / adc_vco_div_actual)

        # Compute the final ADC frequency percent error
        ferror = 100 * (fadc_target - adc_freq_actual) / float(fadc_target)

        #Load local variables back into model variables
        model.vars.adc_freq_actual.value = adc_freq_actual
        model.vars.adc_freq_error.value = ferror

    def calc_if_frequency_target(self,model):
        #This function calculates the target IF frequency

        #The lower bound for signal content is determined by the lowest usable frequency range of the ADC (DC filtering produces noise near DC, varies based on sample rate)
        #This upper bound for signal content is determined by the highest usable frequency range of the ADC (noise shaping, varies based on sample rate)

        #Load model variables into local variables
        bandwidth_hz = model.vars.bandwidth_hz.value
        adc_rate_mode = model.vars.adc_rate_mode.value #We can't use the actual rate mode, because the IF goes into calculating the actual VCO, which goes into final ADC divider

        if adc_rate_mode == model.vars.adc_rate_mode.var_enum.EIGHTHRATE:
            bandwidth_adc_hz = 150e3
            band_edge_min = 50e3
        elif adc_rate_mode == model.vars.adc_rate_mode.var_enum.HALFRATE:
            bandwidth_adc_hz = 1.25e6
            band_edge_min = 50e3
        else:
            bandwidth_adc_hz = 2.50e6
            band_edge_min = 100e3

        if_frequency_min = 80e3
        if_frequency_hz = max(if_frequency_min, band_edge_min + bandwidth_hz / 2)

        if ( (if_frequency_hz + bandwidth_hz / 2) > bandwidth_adc_hz):
            LogMgr.Warning("WARNING: IF + BW/2 > ADC Bandwidth")

        #Load local variables back into model variables
        model.vars.if_frequency_hz.value = int(if_frequency_hz)

    def calc_iffreq_reg(self, model):
        #This calculation writes the IF frequency to the register

        #Load model variables into local variables
        if_frequency_hz = model.vars.if_frequency_hz.value
        synth_res_actual = model.vars.synth_res_actual.value

        iffreq_reg = int(if_frequency_hz / synth_res_actual)

        #Load local variables back into model variables
        self._reg_write(model.vars.SYNTH_IFFREQ_IFFREQ, iffreq_reg)

    def calc_lodiv_value(self, model):
        #This calculation is now in the calc_demodulator file as it also computes the ADC divider
        pass

    def calc_lo_target_freq(self,model):
        #This function calculates the target LO frequency baed on RF, IF, and injection side

        #Load model variables into local variables
        lo_injection_side = model.vars.lo_injection_side.value
        rf_freq = model.vars.base_frequency_hz.value
        if_freq = model.vars.if_frequency_hz.value #We don't yet know the actual synth frequency to get the true IF

        if lo_injection_side == model.vars.lo_injection_side.var_enum.HIGH_SIDE:
            lo_freq = rf_freq + if_freq
        else:
            lo_freq = rf_freq - if_freq

        #Load local variables back into model variables
        model.vars.lo_target_freq.value = lo_freq

    def calc_chsp_freq_reg(self, model):
        #This function was ported due to a variable name mismatch

        ch_spacing = model.vars.channel_spacing_hz.value * 1.0
        f0 = model.vars.base_frequency_hz.value * 1.0
        res = model.vars.synth_res_actual.value

        #channel spacing in terms of res
        chsp = py2round(ch_spacing / res)

        self._reg_write(model.vars.SYNTH_CHSP_CHSP, int(chsp))

        # frequency in terms of res
        freq = math.floor(f0 / res)

        self._reg_write(model.vars.SYNTH_FREQ_FREQ, long(freq))

    def calc_synth_res_actual(self, model):
        #This function was ported due to a variable name mismatch

        xtal_frequency_hz = model.vars.xtal_frequency_hz.value * 1.0
        lodiv = model.vars.lodiv_actual.value

        # Calculate frequency resolution
        # Correct reference clock to use here is the xtal
        res = xtal_frequency_hz / lodiv / pow(2, 19)

        model.vars.synth_res_actual.value = res

    def calc_check_synth_limits(self,model):
        #Overriding limit check from Common
        #TODO: add in limits if we want to check on Ocelot
        pass

    def calc_rx_synth_freq_actual(self, model):
        """
        calculate synthesizer frequency for RX
        Equation (5.31) of EFR32 Reference Manual (internal.pdf)

        Args:
            model (ModelRoot) : Data model to read and write variables from
        """

        chan0_freq = model.vars.SYNTH_FREQ_FREQ.value
        chno = 0
        chan_spacing = model.vars.SYNTH_CHSP_CHSP.value
        cal_offset = 0
        if_freq = model.vars.SYNTH_IFFREQ_IFFREQ.value
        loside = model.vars.SYNTH_IFFREQ_LOSIDE.value
        res = model.vars.synth_res_actual.value
        lodiv = model.vars.lodiv_actual.value

        if loside:
            rx_synth_freq = (chan0_freq + chno * chan_spacing + cal_offset + if_freq) * res * lodiv
        else:
            rx_synth_freq = (chan0_freq + chno * chan_spacing + cal_offset - if_freq) * res * lodiv

        model.vars.rx_synth_freq_actual.value = long(round(rx_synth_freq))

    #FIXME: do we want to create another file called calc_rac.py and place this function there?
    def calc_pga_lna_bw_reg(self, model):

        # Notes
        # Panther used max if_bandwidth_hz = 2.5MHz for BW3dB = 5MHz
        # This gave 1dB droop for mixer pole response and 1dB droop for pga pole response (2dB total).
        # For Ocelot, the initial approach is to scale this to 4 ranges for the 4 filter options
        # 0:  BW3dB = 5 MHz -> max IF BW = 2.5 MHz
        # 1:  BW3dB = 2.5 MHz -> max IF BW = 1.25 MHz
        # 2:  BW3dB = 1.25 MHz -> max IF BW = 0.625 MHz
        # 3:  BW3dB = 0.625 MHz -> max IF BW = 0.3125 MHz

        if_frequency_hz = model.vars.if_frequency_hz.value
        bandwidth_hz = model.vars.bandwidth_hz.value
        if_bandwidth_hz = if_frequency_hz + bandwidth_hz / 2.0

        # Initial Ocelot approach:  same BW3dB for both poles, H(f) > -2dB at IF bandwidth edge
        # Adjusted thresholds by -15% for -2dB frequency based on Ocelot Silicon measurements
        if if_bandwidth_hz < 0.260e6:
            # eighth-rate modes
            # LNABWADJ = 15 for BW3dB = 0.625 MHz
            # PGABWMODE = 2 for BW3dB = 0.625 MHz
            mixer_bw_sel = 15
            pga_bw_sel = 2
        elif if_bandwidth_hz < 0.85*0.625e6:
            # half-rate modes
            # LNABWADJ = 7 for BW3dB = 1.25 MHz
            # PGABWMODE = 3 for BW3dB = 1.25 MHz
            mixer_bw_sel = 7
            pga_bw_sel = 3
        elif if_bandwidth_hz < 0.85*1.25e6:
            # half-rate modes
            # LNABWADJ = 3 for BW3dB = 2.5 MHz
            # PGABWMODE = 1 for BW3dB = 2.5 MHz
            mixer_bw_sel = 3
            pga_bw_sel = 1
        else:
            # full-rate modes
            # LNABWADJ = 0 for BW3dB = 2.5 MHz
            # PGABWMODE = 0 for BW3dB = 2.5 MHz
            mixer_bw_sel = 0
            pga_bw_sel = 0

        #For now, set mixer_bw_sel_boost to the same value as mixer_bw_sel (MCUW_RADIO_CFG-1174)
        mixer_bw_sel_boost = mixer_bw_sel

        self._reg_write(model.vars.RAC_PGACTRL_PGABWMODE, pga_bw_sel)
        self._reg_write(model.vars.AGC_LNABOOST_LNABWADJ, mixer_bw_sel)
        self._reg_write(model.vars.AGC_LNABOOST_LNABWADJBOOST, mixer_bw_sel_boost)

    def calc_boostlna_reg(self, model):

        # Calculating the boostlna value
        # https://jira.silabs.com/browse/MCUW_RADIO_CFG-1612 always set to 0
        boostlna = 0

        #Write the register
        self._reg_write(model.vars.AGC_LNABOOST_BOOSTLNA, boostlna)

    def calc_lodiv_actual(self, model):
        # Don't want to calculate this for Ocelot
        pass

    def calc_ifadcplldcofilter_reg(self, model):

        adc_rate_mode = model.vars.adc_rate_mode.value
        adc_clock_mode = model.vars.adc_clock_mode.value

        if adc_rate_mode == model.vars.adc_rate_mode.var_enum.FULLRATE and \
           adc_clock_mode == model.vars.adc_clock_mode.var_enum.HFXOMULT:
            reg = 1
        else:
            reg = 0

        self._reg_write(model.vars.RAC_IFADCPLLDCO_IFADCPLLDCOFILTER, reg)

    def calc_ifadcpolldcobiashalf_reg(self, model):
        adc_rate_mode = model.vars.adc_rate_mode.value
        adc_clock_mode = model.vars.adc_clock_mode.value

        if adc_rate_mode == model.vars.adc_rate_mode.var_enum.HALFRATE and \
                adc_clock_mode == model.vars.adc_clock_mode.var_enum.HFXOMULT:
            reg = 1
        else:
            reg = 0

        self._reg_write(model.vars.RAC_IFADCPLLDCO_IFADCPLLDCOBIASHALF, reg)

    def calc_ifadcenhalfmode_reg(self, model):

        adc_rate_mode = model.vars.adc_rate_mode.value

        if adc_rate_mode == model.vars.adc_rate_mode.var_enum.HALFRATE:
            reg = 1
        else:
            reg = 0

        self._reg_write(model.vars.RAC_IFADCTRIM0_IFADCENHALFMODE, reg)

    def calc_ifadctrim1_reg(self, model):
        adc_rate_mode = model.vars.adc_rate_mode.value
        adc_clock_mode = model.vars.adc_clock_mode.value

        if adc_rate_mode == model.vars.adc_rate_mode.var_enum.EIGHTHRATE and \
           adc_clock_mode == model.vars.adc_clock_mode.var_enum.HFXOMULT:
            reg = 1
            ifadctz = 4
            negres = 0
        else:
            reg = 0
            ifadctz = 1
            negres = 1

        self._reg_write(model.vars.RAC_IFADCTRIM1_IFADCENSUBGMODE, reg)
        self._reg_write(model.vars.RAC_IFADCTRIM1_IFADCENXOBYPASS, reg)
        self._reg_write(model.vars.RAC_IFADCTRIM1_IFADCTZ, ifadctz)
        self._reg_write(model.vars.RAC_IFADCTRIM1_IFADCENNEGRES, negres)

    def calc_pulsepairing_reg(self, model):
        fsynth = model.vars.rx_synth_freq_actual.value # fsynth =  fvco / 2
        fif = model.vars.if_frequency_hz_actual.value
        lo_injection_side = model.vars.lo_injection_side.value
        lodiv = model.vars.lodiv_actual.value
        if lo_injection_side == model.vars.lo_injection_side.var_enum.LOW_SIDE:
            fif = - fif

        model.vars.ppnd_0.value = 0
        model.vars.ppnd_1.value = 0
        model.vars.ppnd_2.value = 0
        model.vars.ppnd_3.value = 0
        if (lodiv >= 5):
            # only allow DCDC retiming for low frequency band
            # calculate 4 freqs equaly spaced over synth range
            # divide by 2 is to convert vco range to synth range
            fvcorange = self.fvcomax - self.fvcomin
            fvcostep = fvcorange / 4.0
            fsynth_list = np.arange(self.fvcomin+fvcostep/2,self.fvcomax-fvcostep/4,fvcostep)/2

            model.vars.ppnd_0.value = self.return_ppnd(fsynth_list[0], fif, lodiv)
            model.vars.ppnd_1.value = self.return_ppnd(fsynth_list[1], fif, lodiv)
            model.vars.ppnd_2.value = self.return_ppnd(fsynth_list[2], fif, lodiv)
            model.vars.ppnd_3.value = self.return_ppnd(fsynth_list[3], fif, lodiv)

    def return_ppnd(self, fsynth, fif, lodiv):

        dcdcdiv = 13 # assuming constant 13 for now
        Tdmin = 0.8e-6
        Tdmax = 0.95e-6

        Ndmin = int(math.ceil(Tdmin * fsynth / dcdcdiv))
        Ndmax = int(math.floor(Tdmax * fsynth / dcdcdiv))

        best_error = 9e9
        for Nd in range(Ndmin, Ndmax + 1):
            val = Nd * dcdcdiv * (1 / lodiv - fif / fsynth) + 0.5
            error = abs(val - round(val))
            if error < best_error:
                best_error = error
                best_Nd = Nd

        ppnd = best_Nd if best_Nd < 512 else 511

        return (ppnd - 1)

    def calc_synth_misc(self, model):

        part_family = model.part_family.lower()

        #Setting these regs to static values
        self._reg_write(model.vars.RAC_SYNTHENCTRL_MMDPOWERBALANCEDISABLE, 0)

        # Setting these values to POR
        self._reg_write_default(model.vars.SYNTH_LPFCTRL2TX_VCMLVLTX, part_family)
        self._reg_write_default(model.vars.RAC_SYNTHREGCTRL_MMDLDOVREFTRIM, part_family)

        # Fairly confident that these CAL values are not actually used, but Design can not confirm these are unused.
        # So if the value isn't forced then these are a do not care.
        if model.vars.SYNTH_LPFCTRL1CAL_OP1BWCAL.value_forced is None:
            self._reg_do_not_care(model.vars.SYNTH_LPFCTRL1CAL_OP1BWCAL)
        if model.vars.SYNTH_LPFCTRL1CAL_OP1COMPCAL.value_forced is None:
            self._reg_do_not_care(model.vars.SYNTH_LPFCTRL1CAL_OP1COMPCAL)
        if model.vars.SYNTH_LPFCTRL1CAL_RZVALCAL.value_forced is None:
            self._reg_do_not_care(model.vars.SYNTH_LPFCTRL1CAL_RZVALCAL)
        if model.vars.SYNTH_LPFCTRL1CAL_RPVALCAL.value_forced is None:
            self._reg_do_not_care(model.vars.SYNTH_LPFCTRL1CAL_RPVALCAL)
        if model.vars.SYNTH_LPFCTRL1CAL_RFBVALCAL.value_forced is None:
            self._reg_do_not_care(model.vars.SYNTH_LPFCTRL1CAL_RFBVALCAL)

    def calc_hfxo_retiming_table(self, model):
        # Initialize Table
        model.vars.lut_table_index.value = [0]
        model.vars.lut_freq.value = []
        model.vars.lut_freq_upper.value = []
        model.vars.lut_valid.value = []
        model.vars.lut_smuxdiv.value = []
        model.vars.lut_limitl.value = []
        model.vars.lut_limith.value = []
        model.vars.lut_dpll_freq_hz.value = []

        #setting for 1x HFXO frequency
        self.retime_print("calculating 1x HFXO freq")
        self.retime_main(model, model.vars.xtal_frequency_hz.value, 0, 0)

    def calc_txramp_txmodephaseflip_reg(self, model):
        #This function writes the TXMODEPHASEFLIP reg field

        #Read in model variables
        modulation_type = model.vars.modulation_type.value

        #Only set to 1 for DBPSK and BPSK
        if modulation_type == model.vars.modulation_type.var_enum.DBPSK or \
                modulation_type == model.vars.modulation_type.var_enum.BPSK:
            txmodephaseflip = 1
        else:
            txmodephaseflip = 0

        #Write the register
        self._reg_write(model.vars.RAC_TXRAMP_TXMODEPHASEFLIP, txmodephaseflip)


text:
import numpy as np
import bnpy.data

from BRefinery import makeCandidateLPWithNewComps
from BViz import showBirthBeforeAfter
import BLogger
from BirthProposalError import BirthProposalError

def runBirthMove(
        Data_b, curModel, curSS_notb, curLP_b,
        doVizBirth=0,
        **Plan):
    ''' Execute birth move on provided dataset and model

    Args
    -----
    Data_b : dataset
    hmodel : HModel object, with K comps
    SS_notb : SuffStatBag object with K comps
    LP_b : dict of local params, with K comps

    Returns
    -------
    Info : dict with fields
        LP_b : dict of local params for current batch, with K + Kx comps
    '''
    curModel = curModel.copy()
    propModel = curModel.copy()

    Plan['doVizBirth'] = doVizBirth

    # Create target dataset and LP
    try:
        Data_t, curLP_t, targetIDs = subsampleTargetFromDataAndLP(
            Data_b, curModel, curLP_b, **Plan)
    except BirthProposalError as e:
        # Planned target set does not exist, so exit
        BLogger.printEarlyExitMsg("Planned target dataset too small.", e)
        return dict(newLP_b=curLP_b, curLP_b=curLP_b)

    # Create relevant summaries
    curSS_b = curModel.get_global_suff_stats(
        Data_b, curLP_b, doPrecompEntropy=1)
    curSS_t = curModel.get_global_suff_stats(
        Data_t, curLP_t, doPrecompEntropy=1)
    curSS_nott = curSS_b - curSS_t

    if curSS_notb is not None:
        curSS_nott += curSS_notb

    # Log information about current target set
    relevantCompIDs = np.flatnonzero(curSS_t.getCountVec() > 0.01)
    relevantCompSizes = curSS_t.getCountVec()[relevantCompIDs]
    sortmask = np.argsort(-1*relevantCompSizes)
    relevantCompIDs = relevantCompIDs[sortmask]
    relevantCompSizes = relevantCompSizes[sortmask]
    Plan['relevantCompIDs'] = relevantCompIDs
    BLogger.printDataSummary(Data_t, curSS_t, curSS_nott, relevantCompIDs, Plan)

    # Evaluate current score
    curSS = curSS_nott + curSS_t
    curModel.update_global_params(curSS)
    curLscore = curModel.calc_evidence(SS=curSS)

    # Propose new local parameters for target set
    propLP_t, xcurSS_nott = makeCandidateLPWithNewComps(
        Data_t, curLP_t, propModel, curModel, curSS_nott, **Plan)
    # Evaluate proposal score
    propSS_t = propModel.get_global_suff_stats(
        Data_t, propLP_t, doPrecompEntropy=1)
    propSS = propSS_t + xcurSS_nott
    propModel.update_global_params(propSS)
    propLscore = propModel.calc_evidence(SS=propSS)

    propSize = propSS.getCountVec().sum()
    curSize = curSS.getCountVec().sum()
    assert np.allclose(propSize, curSize, rtol=0, atol=1e-6)

    if doVizBirth:
        showBirthBeforeAfter(**locals())
        keypress = raw_input('Press any key to continue >>>')
        if keypress.count('embed'):
            from IPython import embed;
            embed()

    Result = dict(
        curLP_b=curLP_b,
        propLP_t=propLP_t,
        newLP_b=curLP_b,
        curModel=curModel,
        propModel=propModel,
        Lscore_gain=propLscore - curLscore,
        propLscore=propLscore,
        curLscore=curLscore,
        )
    if propLscore > curLscore:
        # Accept
        propLP_b = propModel.allocModel.fillSubsetLP(
            Data_b, curLP_b, propLP_t, targetIDs=targetIDs)
        Result['newLP_b'] = propLP_b
    else:
        # Reject. Do nothing.
        pass

    return Result

def subsampleTargetFromDataAndLP(Data, model, LP, **Plan):
    ''' Select target data items and associated local parameters.

    Returns
    -------
    Data_t : bnpy dataset
    curLP_t : dict of local params

    Post Condition
    --------------
    Plan : dict, with updated fields
    * targetIDs
    '''
    # Perform common parsing tasks
    btargetMaxSize = Plan['btargetMaxSize']
    if btargetMaxSize is None or btargetMaxSize == 'None':
        btargetMaxSize = Data.get_size()
    else:
        btargetMaxSize = int(btargetMaxSize)
    Plan['btargetMaxSize'] = btargetMaxSize
    btargetCompID = Plan['btargetCompID']
    if btargetCompID is None or btargetCompID == 'None':
        btargetCompID = None
    else:
        btargetCompID = int(btargetCompID)
    Plan['btargetCompID'] = btargetCompID

    # Subsample according to specific data object type
    if isinstance(Data, bnpy.data.BagOfWordsData):
        return _sample_target_BagOfWordsData(Data, model, LP, **Plan)
    elif isinstance(Data, bnpy.data.GroupXData):
        if model.getAllocModelName().count('Mixture'):
            Data = Data.toXData()
            return _sample_target_XData(Data, model, LP, **Plan)
        else:
            return _sample_target_GroupXData(Data, model, LP, **Plan)
    elif isinstance(Data, bnpy.data.XData):
        return _sample_target_XData(Data, model, LP, **Plan)

def _sample_target_XData(
        Data, model, LP,
        PRNG=np.random,
        btargetMaxSize=1000, btargetCompID=None, btargetRespThr=0.01, **Plan):
    ''' Select subset of provided XData dataset
    '''
    if btargetCompID is None:
        # For births based on current Data from batch
        size = np.minimum(Data.get_size(), btargetMaxSize)
        if size == Data.get_size():
            targetIDs = np.arange(size)
        else:
            targetIDs = PRNG.choice(
                Data.get_size(), size=btargetMaxSize, replace=False)
    else:
        targetIDs = np.flatnonzero(
            LP['resp'][:, btargetCompID] > btargetRespThr)
        if len(targetIDs) < 2:
            raise BirthProposalError('Target too small.')
        PRNG.shuffle(targetIDs)
        targetIDs = targetIDs[:btargetMaxSize]

    if len(targetIDs) < 2:
        raise BirthProposalError('Target too small.')
    Data_t = Data.select_subset_by_mask(
        targetIDs, doTrackFullSize=False, doTrackTruth=True)
    LP_t = model.allocModel.selectSubsetLP(Data, LP, targetIDs)
    Plan['targetIDs'] = targetIDs
    return Data_t, LP_t, targetIDs

def _sample_target_GroupXData(
        Data, model, LP,
        PRNG=np.random,
        btargetMaxSize=1000, btargetCompID=None, btargetRespThr=0.01, **Plan):
    ''' Select subset of provided GroupXData dataset
    '''
    if btargetCompID is None:
        # For births based on current Data from batch
        size = np.minimum(Data.get_size(), btargetMaxSize)
        if size == Data.get_size():
            targetIDs = np.arange(size)
        else:
            targetIDs = PRNG.choice(
                Data.get_size(), size=btargetMaxSize, replace=False)
    else:
        if model.getAllocModelName().count('TopicModel'):
            targetIDs = np.flatnonzero(
                LP['DocTopicCount'][:, btargetCompID] > btargetRespThr)
        elif model.getAllocModelName().count('HMM'):
            # select sequences that use the target state
            targetIDs = list()
            for n in range(Data.nDoc):
                N_n = np.sum(LP['resp'][:, btargetCompID], axis=0)
                if N_n > btargetRespThr:
                    targetIDs.append(n)
            targetIDs = np.asarray(targetIDs)
        else:
            targetIDs = np.flatnonzero(
                LP['resp'][:, btargetCompID] > btargetRespThr)
            Data = Data.toXData()
        if len(targetIDs) < 1:
            raise BirthProposalError('Target too small.')
        PRNG.shuffle(targetIDs)
        targetIDs = targetIDs[:btargetMaxSize]
    if len(targetIDs) < 1:
        raise BirthProposalError('Target too small.')

    Data_t = Data.select_subset_by_mask(
        targetIDs, doTrackFullSize=False, doTrackTruth=True)
    LP_t = model.allocModel.selectSubsetLP(Data, LP, targetIDs)
    Plan['targetIDs'] = targetIDs
    return Data_t, LP_t, targetIDs

"""
def _sample_target_BagOfWordsData(Data, model, LP, return_Info=0, **kwargs):
    ''' Get subsample of set of documents satisfying provided criteria.

    minimum size of each document, relationship to targeted component, etc.

    Keyword Args
    --------
    targetCompID : int, range: [0, 1, ... K-1]. **optional**
                 if present, we target documents that use a specific topic

    targetMinWordsPerDoc : int,
                         each document in returned targetData
                         must have at least this many words
    Returns
    --------
    targetData : BagOfWordsData dataset,
                with at most targetMaxSize documents
    DebugInfo : (optional), dictionary with debugging info
    '''
    DocWordMat = Data.getSparseDocTypeCountMatrix()
    DebugInfo = dict()

    candidates = np.arange(Data.nDoc)
    if kwargs['targetMinWordsPerDoc'] > 0:
        nWordPerDoc = np.asarray(DocWordMat.sum(axis=1))
        candidates = nWordPerDoc >= kwargs['targetMinWordsPerDoc']
        candidates = np.flatnonzero(candidates)
    if len(candidates) < 1:
        return None, dict()

    # ............................................... target a specific Comp
    if hasValidKey('targetCompID', kwargs):
        if hasValidKey('DocTopicCount', LP):
            Ndk = LP['DocTopicCount'][candidates].copy()
            Ndk /= np.sum(Ndk, axis=1)[:, np.newaxis] + 1e-9
            mask = Ndk[:, kwargs['targetCompID']] > kwargs['targetCompFrac']
        elif hasValidKey('resp', LP):
            mask = LP['resp'][
                :,
                kwargs['targetCompID']] > kwargs['targetCompFrac']
            if candidates is not None:
                mask = mask[candidates]
        else:
            raise ValueError('LP must have either DocTopicCount or resp')
        candidates = candidates[mask]

    # ............................................... target a specific Word
    elif hasValidKey('targetWordIDs', kwargs):
        wordIDs = kwargs['targetWordIDs']
        TinyMatrix = DocWordMat[candidates, :].toarray()[:, wordIDs]
        targetCountPerDoc = np.sum(TinyMatrix > 0, axis=1)
        mask = targetCountPerDoc >= kwargs['targetWordMinCount']
        candidates = candidates[mask]

    # ............................................... target based on WordFreq
    elif hasValidKey('targetWordFreq', kwargs):
        wordFreq = kwargs['targetWordFreq']
        from TargetPlannerWordFreq import calcDocWordUnderpredictionScores

        ScoreMat = calcDocWordUnderpredictionScores(Data, model, LP)
        ScoreMat = ScoreMat[candidates]
        DebugInfo['ScoreMat'] = ScoreMat
        if kwargs['targetSelectName'].count('score'):
            ScoreMat = np.maximum(0, ScoreMat)
            ScoreMat /= ScoreMat.sum(axis=1)[:, np.newaxis]
            distPerDoc = calcDistBetweenHist(ScoreMat, wordFreq)

            DebugInfo['distPerDoc'] = distPerDoc
        else:
            EmpWordFreq = DocWordMat[candidates, :].toarray()
            EmpWordFreq /= EmpWordFreq.sum(axis=1)[:, np.newaxis]
            distPerDoc = calcDistBetweenHist(EmpWordFreq, wordFreq)
            DebugInfo['distPerDoc'] = distPerDoc

        keepIDs = distPerDoc.argsort()[:kwargs['targetMaxSize']]
        candidates = candidates[keepIDs]
        DebugInfo['candidates'] = candidates
        DebugInfo['dist'] = distPerDoc[keepIDs]

    if len(candidates) < 1:
        return None, dict()
    elif len(candidates) <= kwargs['targetMaxSize']:
        targetData = Data.select_subset_by_mask(candidates)
    else:
        targetData = Data.get_random_sample(kwargs['targetMaxSize'],
                                            randstate=kwargs['randstate'],
                                            candidates=candidates)

    return targetData, DebugInfo
"""

ext: py

max_stars_repo_name: HongminWu/bnpy

max_issues_repo_name: HongminWu/bnpy

max_forks_repo_name: birlrobotics/bnpy

reason: import numpy


text:
import os
import numpy
import glob
import shutil
import re
#cogemos el numero y nombre de archivos que hay

mypath=os.getcwd();

#.jpg , jpeg , png , PNG
meses=('Enero','Febrero','Marzo','Abril','Mayo','Junio','Julio','Agosto','Septiembre','Octubre','Noviembre','Diciembre')
types=('*.jpg' , '*.jpeg','*.png','*.PNG');
lista_archivos=[];

for tipo in types:
	lista_archivos.extend(glob.glob(tipo));

#vamos a recorrer la lista de archivos viendo a donde debe ir cada uno de ellos, si no existiera el
#directorio antes de mandarlo alli, lo debemos crear

#creamos el directorio de las fotos
if(not('photos_ordenadas' in os.listdir())):
	os.mkdir('photos_ordenadas')

dirgen=mypath +'/'+ 'photos_ordenadas'

for foto in lista_archivos:
	var=re.findall('[0-9]',foto);
	año1=var[0]+var[1]+var[2]+var[3]
	mes1=var[4]+var[5]
	dia1=var[6]+var[7]

	#comprobar si existe ese directorio de año y de mes
	lista_dir=os.listdir(dirgen)
	if(not(año1 in lista_dir)):
		os.mkdir(dirgen +'/'+ año1)

	lista_dir=os.listdir(dirgen +'/'+ año1)
	if(not(meses[int(mes1)-1] in lista_dir)):
		os.mkdir(dirgen +'/'+ año1 +'/'+ meses[int(mes1)-1])
	#ahora solo hay que moverlo
	shutil.move(mypath+'/'+ foto ,dirgen +'/'+ año1 +'/'+ meses[int(mes1)-1] +'/'+ foto)


text:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-

__author__ = "Christian Heider Nielsen"
__doc__ = r"""

           Created on 02/03/2020
           """

__all__ = ["NoData", "IncompatiblePackageVersions"]

class NoData(Exception):
    """ """

    def __init__(self, msg: str = "No Data Available"):
        Exception.__init__(self, msg)

class IncompatiblePackageVersions(Exception):
    """ """

    def __init__(self, *packages, **versions):
        str_o = ", "
        str_l = []

        for p in packages:
            if isinstance(p, str):
                s = f"({p},"
                if p in versions:
                    s += f"{versions[p]}"
                else:
                    s += f"NotSpecified"
                s += ")"
                str_l.append(s)
            else:
                str_l.append(f"{p.__name__, p.__version__}")

        Exception.__init__(self, f"Packages {str_o.join(str_l)} are not compatible")

if __name__ == "__main__":

    def main():
        """ """
        raise IncompatiblePackageVersions(
            "numpy", "scipy", "Something", numpy="0.0.1", scipy="0.0.2"
        )

    def main2():
        """ """
        import numpy
        import scipy

        raise IncompatiblePackageVersions(numpy, scipy)

    main2()

max_stars_repo_name: cnHeider/draugr

max_issues_repo_name: cnHeider/draugr

max_forks_repo_name: cnHeider/draugr

reason: import numpy,import scipy


text:
import numpy as np
import nibabel as nib
from scipy.ndimage import zoom
from glob import glob

def resize(plane):
    x, y, z = plane.shape
    return zoom(plane, (181.0/x, 217.0/y, 181.0/z))

def get_AD_risk(raw):
    x1, x2 = raw[0, :, :, :], raw[1, :, :, :]
    risk = np.exp(x2) / (np.exp(x1) + np.exp(x2))
    return risk

def get_AD_prob(seg):
    l1, l2, l3, l4, l5, l6, l7 = [], [], [], [], [], [], []
    for i in range(181):
        for j in range(217):
            for k in range(181):
                if seg[i, j, k] == 15:
                    l1.append(risk[i, j, k])
                if seg[i, j, k] in [6, 13, 25, 28, 29]:
                    l2.append(risk[i, j, k])
                if seg[i, j, k] in [31, 16]:
                    l3.append(risk[i, j, k])
                if seg[i, j, k] in [12]:
                    l4.append(risk[i, j, k])
                if seg[i, j, k] in [5, 18]:
                    l5.append(risk[i, j, k])
                if seg[i, j, k] in [10]:
                    l6.append(risk[i, j, k])
                if seg[i, j, k] in [17, 23]:
                    l7.append(risk[i, j, k])
    ans = [sum(l1) / len(l1), sum(l2) / len(l2), sum(l3) / len(l3), sum(l4) / len(l4), sum(l5) / len(l5),
           sum(l6) / len(l6), sum(l7) / len(l7)]
    return ans

fileList = ['0-1477', '0-1850', '0-1890', '0-2646', '0-2851', '0-3492', '0-3542',
            '0-5119', '0-5268', '1-2127', '1-6072']

for exp_idx in [1, 2, 3, 4]:
    print('{}'.format(exp_idx) * 20)
    compList = glob('../DPMs/fcn_exp{}/*.npy'.format(exp_idx))

    def find(filename, compList):
        for file in compList:
            if filename in file:
                return file.split('/')[-1]
        print('not found ', filename)

    for idx, filename in enumerate(fileList):
        compfilename = find(filename, compList)
        path = './segmen/subject_{}/segments/'.format(idx+1)
        seg_left = nib.load(path + 'lh_combined.mgz').get_data()
        seg_right = nib.load(path + 'rh_combined.mgz').get_data()
        mri = np.load('/data/datasets/FHS_NoBack/{}'.format(compfilename))
        risk = resize(get_AD_risk(np.load('../DPMs/fcn_exp{}/{}'.format(exp_idx, compfilename))))
        print(seg_right.shape, seg_left.shape, mri.shape, risk.shape)
        print(filename + 'left')
        print(get_AD_prob(seg_left))
        print(filename + 'right')
        print(get_AD_prob(seg_right))
        print('############################################################')
    print('{}'.format(exp_idx) * 20)

reason: import numpy,from scipy


text:
"""
Add small data to examine cursor positions
"""

import numpy as np
from skimage import data
import napari

with napari.gui_qt():

    viewer = napari.Viewer()
    image = np.array([[1, 0, 0, 1],
                      [0, 0, 1, 1],
                      [1, 0, 3, 0],
                      [0, 2, 0, 0]], dtype=int)

    viewer.add_labels(image)

    points = np.array([[0, 0], [2, 0], [1, 3]])
    viewer.add_points(points, size=0.25)

    rect = np.array([[0, 0], [3, 1]])
    viewer.add_shapes(rect, shape_type='rectangle', edge_width=0.1)

    vect = np.array([[[3, 2], [-1, 1]]])
    viewer.add_vectors(vect, edge_width=0.1)

max_stars_repo_name: mkitti/napari

max_issues_repo_name: mkitti/napari

max_forks_repo_name: mkitti/napari


text:
import numpy as np
import pickle as pkl
import networkx as nx
import scipy
import scipy.sparse as sp
from scipy.sparse.linalg.eigen.arpack import eigsh
import sys
import torch

def parse_index_file(filename):
    """Parse index file."""
    index = []
    for line in open(filename):
        index.append(int(line.strip()))
    return index

'''
def sample_mask(idx, l):
    """Create mask."""
    mask = np.zeros(l)
    mask[idx] = 1
    return np.array(mask, dtype=np.bool)
'''

def load_data(dataset_str, device):
    """
    Loads input data from gcn/data directory
    ind.dataset_str.x => the feature vectors of the training instances as scipy.sparse.csr.csr_matrix object;
    ind.dataset_str.tx => the feature vectors of the test instances as scipy.sparse.csr.csr_matrix object;
    ind.dataset_str.allx => the feature vectors of both labeled and unlabeled training instances
        (a superset of ind.dataset_str.x) as scipy.sparse.csr.csr_matrix object;
    ind.dataset_str.y => the one-hot labels of the labeled training instances as numpy.ndarray object;
    ind.dataset_str.ty => the one-hot labels of the test instances as numpy.ndarray object;
    ind.dataset_str.ally => the labels for instances in ind.dataset_str.allx as numpy.ndarray object;
    ind.dataset_str.graph => a dict in the format {index: [index_of_neighbor_nodes]} as collections.defaultdict
        object;
    ind.dataset_str.test.index => the indices of test instances in graph, for the inductive setting as list object.
    All objects above must be saved using python pickle module.
    :param dataset_str: Dataset name
    :return: All data input files loaded (as well the training/test data).
    """
    names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph']
    objects = []
    for i in range(len(names)):
        with open("data/ind.{}.{}".format(dataset_str, names[i]), 'rb') as f:
            if sys.version_info > (3, 0):
                objects.append(pkl.load(f, encoding='latin1'))
            else:
                objects.append(pkl.load(f))

    x, y, tx, ty, allx, ally, graph = tuple(objects)
    test_idx_reorder = parse_index_file("data/ind.{}.test.index".format(dataset_str))
    test_idx_range = np.sort(test_idx_reorder)

    if dataset_str == 'citeseer':
        # Fix citeseer dataset (there are some isolated nodes in the graph)
        # Find isolated nodes, add them as zero-vecs into the right position
        test_idx_range_full = range(min(test_idx_reorder), max(test_idx_reorder)+1)
        tx_extended = sp.lil_matrix((len(test_idx_range_full), x.shape[1]))
        tx_extended[test_idx_range-min(test_idx_range), :] = tx
        tx = tx_extended
        ty_extended = np.zeros((len(test_idx_range_full), y.shape[1]))
        ty_extended[test_idx_range-min(test_idx_range), :] = ty
        ty = ty_extended

    num_classes = y.shape[1]

    features = sp.vstack((allx, tx)).tolil()
    features[test_idx_reorder, :] = features[test_idx_range, :]
    features = torch.from_numpy(features.todense()).to(device)
    adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))
    adj = torch.from_numpy(adj.todense()).to_sparse().to(device)

    labels = torch.tensor(np.vstack((ally, ty)).argmax(axis=1)).to(device)
    labels[test_idx_reorder] = labels[test_idx_range]

    idx_test = torch.from_numpy(test_idx_range).to(device)
    idx_train = torch.arange(len(y)).to(device)
    idx_val = torch.arange(len(y), len(y)+500).to(device)

    return features, adj, labels, num_classes, idx_train, idx_val, idx_test
'''

def to_sparse_tensor(x):
    x = x.tocoo()
    i = torch.tensor(np.vstack((x.row, x.col)), dtype=torch.long)
    v = torch.tensor(x.data, dtype=torch.float)
    return torch.sparse_coo_tensor(i, v, torch.Size(x.shape))

def read_file(dataset, name):
    filename = 'data/ind.' + dataset + '.{}'.format(name)
    if name == 'test.index':
        return np.loadtxt(filename, dtype=np.long)
    else:
        with open(filename, 'rb') as f:
            return pkl.load(f, encoding='latin1')

def normalize(x):
    return scipy.sparse.diags(np.array(x.sum(1)).flatten() ** -1).dot(x)

def load_data(dataset, device):
    names = ['x', 'y', 'tx', 'ty', 'allx', 'ally', 'graph', 'test.index']
    x, y, tx, ty, allx, ally, graph, test_index = [read_file(dataset, name) for name in names]
    num_classes = y.shape[1]
    train_index = torch.arange(y.shape[0]).to(device)
    dev_index = torch.arange(y.shape[0], y.shape[0] + 500).to(device)
    test_index_sorted = torch.tensor(np.sort(test_index)).to(device)
    test_index = torch.tensor(test_index).to(device)

    x = torch.tensor(normalize(scipy.sparse.vstack([allx, tx])).todense()).to(device)
    y = torch.tensor(np.vstack([ally, ty]).argmax(axis=1)).to(device)

    x[test_index] = x[test_index_sorted]
    y[test_index] = y[test_index_sorted]

    adj = nx.adjacency_matrix(nx.from_dict_of_lists(graph))
    a = to_sparse_tensor(normalize(adj + scipy.sparse.eye(adj.shape[0]))).to(device)

    return x, a, y, num_classes, train_index, dev_index, test_index
'''

max_stars_repo_name: Fanerst/gcn-pytorch

max_issues_repo_name: Fanerst/gcn-pytorch

max_forks_repo_name: Fanerst/gcn-pytorch

reason: import numpy,import scipy,from scipy,import networkx


text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-

"""
Course :
GTI770 — Systèmes intelligents et apprentissage machine

Project :
Lab 1 - Lab's name

Students :
Amhad Al-Taher — Permanent Code
Jean-Philippe Decoste - DECJ19059105
Stéphanie Lacerte - LACS

Group :
GTI770-A18-02
"""

from helpers import utilities as Utils
import numpy as np
import os
from sklearn.model_selection import GridSearchCV
from sklearn.tree import DecisionTreeClassifier
from tabulate import tabulate as Tabulate
import tensorflow as tf
from tensorflow import keras
from keras.wrappers.scikit_learn import KerasClassifier
from keras.utils import np_utils

TENSORBOARD_SUMMARY = r"tensorboard"

class neuralNetwork(object):
    def __init__(self, validationMethod, id, layers, learn_rate, dimension, activation, epoch, batch_size):
        """
        Initialisation d'un classifier MLP
        Args:
            validationMethod:   Méthode de validation
            id:                 Identifiant unique du modèle (utiliser pour les dossier tensorboard)
            layers:             Array contenant le squelette du réseau
            learn_rate:         Taux d'apprentissage (entre 0 et 1)
            dimension:          Dimension du dataset (détermine le nombre de perceptron de la couche 1)
            activation:         Array des méthodes d'activations (max=2, la deuxième est l'activation de la dernière couche)
            epoch:              Nombre d'itération
            batch_size:         Taille de chaque lot de données
        """
        print("\nNew Neural Network Classifier")
        self.validationMethod = validationMethod
        self.id = id
        self.layers = layers
        self.learn_rate = learn_rate
        self.dimension = dimension
        self.activation = activation
        self.epoch = epoch
        self.batch_size = batch_size
        self.precision = []
        self.score_f1 = []
        self.best_params = []
        self.best_score = 0

        """
        # Create a default in-process session.
        directory = TENSORBOARD_SUMMARY + "/" + str(id)
        if not os.path.exists(directory):
            os.makedirs(directory)
        print("TensorBoard summary writer at :" + directory + "\n")
        self.tbCallBack = keras.callbacks.TensorBoard(log_dir=directory, histogram_freq=0, write_graph=False, write_images=False)
        """

    def create_model(self):
        """
        Crée un model MLP
        Args:

        """
        # The network type
        model = keras.Sequential()

        # Static Params
        counter = 1
        kernel_initializer = 'uniform'
        bias_initializer = 'zeros'
        dropout_rate = 0.1

        # Set layers
        # First layer is set according to data dimension
        model.add(keras.layers.Dense(self.dimension + 10,
                                     input_dim=self.dimension,
                                     kernel_initializer=kernel_initializer,
                                     bias_initializer=bias_initializer,
                                     activation=self.activation[0]))
        model.add(keras.layers.Dropout(dropout_rate))
        # Other layer set using layers array
        for perceptron in self.layers:
            if len(self.layers) == counter:
                # Last layer (25 neurons for 25 possible class, SIGMOID ensure result between 1 and 0)
                model.add(keras.layers.Dense(25,
                                             kernel_initializer=kernel_initializer,
                                             bias_initializer=bias_initializer,
                                             activation=self.activation[1]))
            else:
                # Adds Layer
                model.add(keras.layers.Dense(perceptron,
                                             kernel_initializer=kernel_initializer,
                                             bias_initializer=bias_initializer,
                                             activation=self.activation[0]))
                model.add(keras.layers.Dropout(dropout_rate))
            counter = counter + 1

        # Compile the network according to previous settings
        model.compile(optimizer=tf.train.AdamOptimizer(self.learn_rate),
                      loss='binary_crossentropy',
                      metrics=['accuracy'])

        return model

    def evaluate(self, features, answers):
        """
        Évaluation d'un classifier
        Args:
            features:           Array de données
            answers:            Array de label
            ValidationMethod:   Type de validation à utiliser
        """
        print("1.Evaluation\n")

        mlpPerf = [['Epoch', 'Batch Size', 'Accuracy']]
        params = dict(epochs=self.epoch, batch_size=self.batch_size)
        grid = GridSearchCV(KerasClassifier(build_fn=self.create_model, verbose=0),
                            param_grid=params,
                            cv=self.validationMethod,
                            n_jobs=-1,
                            verbose=0)

        # Fix answer array
        answers = np_utils.to_categorical(answers)

        #Fit data to algo
        grid.fit(features, answers)

        #Loop through results
        for i in range(0, len(grid.cv_results_['params'])):
            mlpPerf.append([grid.cv_results_['params'][i]['epochs'],
                            grid.cv_results_['params'][i]['batch_size'],
                            "{0:.2f}".format(grid.cv_results_['mean_test_score'][i]*100)])
            self.precision.append(grid.cv_results_['mean_test_score'][i])
            self.score_f1.append(grid.cv_results_['mean_test_score'][i])

        self.best_params = grid.best_params_
        self.best_params['layers'] = self.layers
        self.best_params['learn_rate'] = self.learn_rate
        self.best_params['activation'] = self.activation
        self.best_params['layers'] = self.layers
        self.best_score = grid.best_score_

        #Print table
        print(Tabulate(mlpPerf, headers='firstrow'))
        print("The best parameters are ", self.best_params,
              " with a score of {0:.2f}%".format(float(grid.best_score_)* 100))
        print()

        print("-> Done\n\n")

    def train(self, features, answers):
        """
        Entrainement du classifier MLP
        Args:
            features:           Array de données
            answers:            Array de label
            ValidationMethod:   Type de validation à utiliser
        """
        print("1.Training")

        mlpPerf = [['Epoch', 'Batch Size', 'Accuracy']]
        model = KerasClassifier(build_fn=self.create_model, verbose=0)

        # Fix answer array
        answers = np_utils.to_categorical(answers)

        #Fit data to algo
        model.fit(features, answers)

        #Save results
        mlpPerf.append([self.epoch, self.batch_size, "{0:.2f}".format(model.score(features, answers)*100)])
        self.precision.append(model.score(features, answers))
        self.best_score = self.precision[0]

        #Print table
        print(Tabulate(mlpPerf, headers='firstrow'))
        print()

        return model

    def printGraph(self, precision, score_f1):
        """
        Affiche un graphique comparant la précision et le score F1 de deux classifier
        Args:
            precision: Array des données de précision du classifier en comparaison
            score_f1: Array des données de score F1 du classifier en comparaison
        """
        if (len(self.precision) != len(precision)):
            print("Les tableaux de données fournient n'ont pas la même dimension")
        else:
            Utils.printGraph('Profondeur de l\'arbre', 'Précision', [0, 3, 5, 10], self.precision, precision)
            Utils.printGraph('Profondeur de l\'arbre', 'Score F1', [0, 3, 5, 10], self.score_f1, score_f1)

    def getDefinition(self):
        """
        Renvoi la définition du modèle
        Args:

        Return:
            best_score: Le meilleur résultat
        """
        return ['Réseau de neurones:', self.best_params]

    def getPrecision(self):
        """
        Renvoi un array des données de précision
        Args:

        Return:
            precision: Array des données de précision du classifier en comparaison
        """
        return self.precision

    def getScoreF1(self):
        """
        Renvoi un array des données de score f1
        Args:

        Return:
            score_f1: Array des données de score F1 du classifier en comparaison
        """
        return self.score_f1

    def getBestParams(self):
        """
        Renvoi un array des meilleurs paramètres
        Args:

        Return:
            best_params: Array des meilleurs paramètres du classifier en comparaison
        """
        return self.best_params

    def getBestScore(self):
        """
        Renvoi le meilleur score
        Args:

        Return:
            best_score: Le meilleur résultat
        """
        return self.best_score

max_stars_repo_name: iraqforlife/Smart-classification-system

max_issues_repo_name: iraqforlife/Smart-classification-system

max_forks_repo_name: iraqforlife/Smart-classification-system


text:
# Test the approximation function

from pmdarima.arima.approx import approx, _regularize
from pmdarima.utils.array import c
from pmdarima.arima.stationarity import ADFTest

from numpy.testing import assert_array_almost_equal
import numpy as np

import pytest

table = c(0.216, 0.176, 0.146, 0.119)
tablep = c(0.01, 0.025, 0.05, 0.10)
stat = 1.01

def test_regularize():
    x, y = c(0.5, 0.5, 1.0, 1.5), c(1, 2, 3, 4)
    x, y = _regularize(x, y, 'mean')

    assert_array_almost_equal(x, np.array([0.5, 1.0, 1.5]))
    assert_array_almost_equal(y, np.array([1.5, 3.0, 4.0]))

def test_approx_rule1():
    # for rule = 1
    x, y = approx(table, tablep, stat, rule=1)
    assert_array_almost_equal(x, c(1.01))
    assert_array_almost_equal(y, c(np.nan))

def test_approx_rule2():
    # for rule = 2
    x, y = approx(table, tablep, stat, rule=2)
    assert_array_almost_equal(x, c(1.01))
    assert_array_almost_equal(y, c(0.01))

@pytest.mark.parametrize(
    'kwargs', [

        # fails for length differences
        dict(x=[1, 2, 3], y=[1, 2], xout=1.0),

        # fails for bad string
        dict(x=table, y=table, xout=1.0, method='bad-string'),

        # fails for bad length
        dict(x=[], y=[], xout=[], ties='mean'),

        # fails for bad length
        dict(x=[], y=[], xout=[], method='constant'),

        # fails for linear when < 2 samples
        dict(x=[1], y=[1], xout=[], method='linear', ties='ordered'),

        # fails for bad length
        dict(x=[], y=[], xout=[], method='constant'),

    ]
)
def test_corner_errors(kwargs):
    with pytest.raises(ValueError):
        approx(**kwargs)

def test_valid_corner():
    # *doesn't* fail for constant when < 2 samples
    approx(x=[1], y=[1], xout=[], method='constant', ties='ordered')

def test_approx_precision():
    # Test an example from R vs. Python to compare the expected values and
    # make sure we get as close as possible. This is from an ADFTest where k=1
    # and x=austres
    tableipl = np.array([[-4.0664],
                         [-3.7468],
                         [-3.462],
                         [-3.1572],
                         [-1.2128],
                         [-0.8928],
                         [-0.6104],
                         [-0.2704]])

    _, interpol = approx(tableipl, ADFTest.tablep, xout=-1.337233, rule=2)
    assert np.allclose(interpol, 0.84880354)  # in R we get 0.8488036

max_stars_repo_name: tuomijal/pmdarima

max_issues_repo_name: tuomijal/pmdarima

max_forks_repo_name: tuomijal/pmdarima

reason: import numpy,from numpy


text:
"""
Routines for implementing Letteri et al.'s macrostate-to-macrostate rate calculations
using extrapolation to steady-state populations from average rate matrices

Internally, "labeled" objects (bin populations labeled by history, rate matrix elements labeled
by history) are stored as nested arrays -- e.g. rates[initial_label, final_label, initial_bin, final_bin].
These are converted to the flat forms required for, say, eigenvalue calculations internally, and the
results converted back. This is because these conversions are not expensive, and saves users of
this code from having to know how the flattened indexing works (something I screwed up all too
easily during development) -- mcz
"""

import logging
import warnings

import numpy as np
import scipy.linalg

from westpa.core.data_manager import weight_dtype

from . _kinetics import (calculate_labeled_fluxes,  # @UnresolvedImport
                         calculate_labeled_fluxes_alllags,  # @UnresolvedImport
                         labeled_flux_to_rate,  # @UnresolvedImport
                         nested_to_flat_matrix, nested_to_flat_vector,  # @UnresolvedImport
                         flat_to_nested_vector, _reduce_labeled_rate_matrix_to_macro)  # @UnresolvedImport

log = logging.getLogger(__name__)

class ConsistencyWarning(UserWarning):
    pass

def get_steady_state(rates):
    '''Get steady state solution for a rate matrix. As an optimization, returns the
    flattened labeled population vector (of length nstates*nbins); to convert to the
    nested vector used for storage, use nested_to_flat_vector().'''

    rates = rates.copy()

    # Convert to a transition probability matrix
    for i in range(rates.shape[0]):
        rowsum = rates[i,:].sum()
        if rowsum > 0:
            rates[i,:] = rates[i,:] / rowsum
        else:
            if rates[:,i].sum() != 0:
                warnings.warn('sink microstate in rate matrix', ConsistencyWarning)
            rates[i,:] = 0

    try:
        vals, vecs = scipy.linalg.eig(rates.T)
    except Exception:
        log.debug('exception obtaining eigenvectors', exc_info=True)
        return None

    vals = np.abs(vals)
    log.debug('eigenvalues: {!r}'.format(list(reversed(sorted(vals)))))
    asort = np.argsort(vals)
    vec = vecs[:,asort[-1]]
    ss = np.abs(vec)

    ss /= ss.sum()
    return ss

def get_macrostate_rates(labeled_rates, labeled_pops, extrapolate=True):
    '''Using a labeled rate matrix and labeled bin populations, calculate the steady state
    probability distribution and consequent state-to-state rates.

    Returns ``(ss, macro_rates)``, where ``ss`` is the steady-state probability distribution
    and ``macro_rates`` is the state-to-state rate matrix.'''

    nstates, nbins = labeled_pops.shape

    rates = nested_to_flat_matrix(labeled_rates)

    # Find steady-state solution
    if extrapolate:
        ss = get_steady_state(rates)
        if ss is None:
            warnings.warn('no well-defined steady state; using average populations',ConsistencyWarning)
            ss = nested_to_flat_vector(labeled_pops)
    else:
        ss = nested_to_flat_vector(labeled_pops)

    macro_rates = _reduce_labeled_rate_matrix_to_macro(nstates, nbins, rates, ss)

    return flat_to_nested_vector(nstates, nbins, ss), macro_rates

def estimate_rates(nbins, state_labels, weights, parent_ids, bin_assignments, label_assignments, state_map, labeled_pops,
                   all_lags=False,
                   labeled_fluxes = None, labeled_rates = None, unlabeled_rates = None):
    '''Estimate fluxes and rates over multiple iterations. The number of iterations is determined by how many
    vectors of weights, parent IDs, bin assignments, and label assignments are passed.

    If ``all_lags`` is true, then the average is over all possible lags within the length-N window given, otherwise
    simply the length N lag.

    Returns labeled flux matrix, labeled rate matrix, and unlabeled rate matrix.'''

    assert len(weights) == len(parent_ids) == len(bin_assignments) == len(label_assignments)
    nstates = len(state_labels)
    nbins = labeled_pops.shape[1]-1

    # Prepare output arrays
    if labeled_fluxes is None:
        labeled_fluxes = np.zeros((nstates, nstates, nbins, nbins), weight_dtype)
    else:
        labeled_fluxes.fill(0.0)

    if labeled_rates is None:
        labeled_rates = np.zeros_like(labeled_fluxes)
    else:
        labeled_rates.fill(0.0)

    if unlabeled_rates is None:
        unlabeled_rates = np.zeros((nbins,nbins), weight_dtype)
    else:
        unlabeled_rates.fill(0.0)

    # Loop over all possible windows to accumulate flux matrix
    # flux matrix is [initial_label][final_label][initial_bin][final_bin]
    if all_lags:
        twindow = calculate_labeled_fluxes_alllags(nstates, weights, parent_ids, bin_assignments, label_assignments, labeled_fluxes)
    else:
        twindow = calculate_labeled_fluxes(nstates, weights, parent_ids, bin_assignments, label_assignments, labeled_fluxes)
    labeled_fluxes /= twindow

    # Calculate rate matrix for this window, using populations from the last iteration (which correspond
    # to the weights that contribute to the flux matrix)
    labeled_flux_to_rate(labeled_fluxes, labeled_pops, labeled_rates)

    # Calculate an unlabeled rate matrix
    unlabeled_fluxes = np.sum(labeled_fluxes,axis=(0,1))
    unlabeled_pops = labeled_pops.sum(axis=0)
    unlabeled_rates[...] = labeled_flux_to_rate(unlabeled_fluxes[None,None,:,:], unlabeled_pops[None,:])[0,0]

    return labeled_fluxes, labeled_rates, unlabeled_rates


text:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date    : 2018-02-05 16:36:03
# @Author  : Zhi Liu (zhiliu.mind@gmail.com)
# @Link    : http://iridescent.ink
# @Version : $1.0$
from __future__ import division, print_function, absolute_import

import numpy as np

def nextpow2(x):
    if x == 0:
        y = 0
    else:
        y = int(np.ceil(np.log2(x)))

    return y

def prevpow2(x):
    if x == 0:
        y = 0
    else:
        y = int(np.floor(np.log2(x)))
    return y

def ebeo(a, b, op='+'):
    r"""element by element operation

    Element by element operation.

    Parameters
    ----------
    a : list, tuple or ndarray
        The first list/tuple/ndarray.
    b : list, tuple or ndarray
        The second list/tuple/ndarray.
    op : str, optional
        Supported operations are:
        - ``'+'`` or ``'add'`` for addition (default)
        - ``'-'`` or ``'sub'`` for substraction
        - ``'*'`` or ``'mul'`` for multiplication
        - ``'/'`` or ``'div'`` for division
        - ``'**'`` or ``pow`` for power
        - ``'<'``, or ``'lt'`` for less than
        - ``'<='``, or ``'le'`` for less than or equal to
        - ``'>'``, or ``'gt'`` for greater than
        - ``'>='``, or ``'ge'`` for greater than or equal to
        - ``'&'`` for bitwise and
        - ``'|'`` for bitwise or
        - ``'^'`` for bitwise xor
        - function for custom operation.

    Raises
    ------
    TypeError
        If the specified operator not in the above list, raise a TypeError.
    """
    if op in ['+', 'add']:
        return [i + j for i, j in zip(a, b)]
    if op in ['-', 'sub']:
        return [i - j for i, j in zip(a, b)]
    if op in ['*', 'mul']:
        return [i * j for i, j in zip(a, b)]
    if op in ['/', 'div']:
        return [i / j for i, j in zip(a, b)]
    if op in ['**', '^', 'pow']:
        return [i ** j for i, j in zip(a, b)]
    if isinstance(op, str):
        raise TypeError("Not supported operation: " + op + "!")
    else:
        return [op(i, j) for i, j in zip(a, b)]

def real2complex(X, axis=-1):

    if axis == -1:
        return X[..., 0] + 1j * X[..., 1]
    if axis == 1:
        return X[:, 0] + 1j * X[:, 1]
    if axis == 0:
        return X[0] + 1j * X[1]

def complex2real(X, axis=-1):

    return np.stack((X.real, X.imag), axis=axis)

if __name__ == '__main__':

    x = 120
    y = nextpow2(x)
    print(y)

max_stars_repo_name: antsfamily/pyailib

max_issues_repo_name: antsfamily/pyailib

max_forks_repo_name: antsfamily/pyailib


text:
#!/usr/bin/env python
# -*- coding:utf-8 -*-
# Author:

import os
import sys
sys.path.insert(0, os.getcwd() + "/..")
import cv2
import numpy as np
from easyai.helper import DirProcess
from easyai.helper import ImageProcess
from easyai.helper.arguments_parse import ToolArgumentsParse
from easyai.config.utility.config_factory import ConfigFactory
from easyai.base_name.task_name import TaskName

class ConvertSegmentionLable():

    def __init__(self):
        self.save_label_dir = "SegmentLabel"
        self.annotation_post = ".png"
        self.dirProcess = DirProcess()
        self.image_process = ImageProcess()

    def convert_segment_label(self, label_dir, is_gray, class_list):
        output_dir = os.path.join(label_dir, "../%s" % self.save_label_dir)
        if not os.path.exists(output_dir):
            os.makedirs(output_dir)
        label_list = list(self.dirProcess.getDirFiles(label_dir, "*.*"))
        for label_path in label_list:
            path, file_name_and_post = os.path.split(label_path)
            print(label_path)
            mask = self.process_segment_label(label_path, is_gray, class_list)
            if mask is not None:
                save_path = os.path.join(output_dir, file_name_and_post)
                cv2.imwrite(save_path, mask)

    def process_segment_label(self, label_path, is_gray, class_list):
        if is_gray:
            mask = self.image_process.read_gray_image(label_path)
        else:
            _, mask = self.image_process.readRgbImage(label_path)
        if mask is not None:
            if is_gray:
                mask = self.convert_gray_label(mask, class_list)
            else:
                mask = self.convert_color_label(mask, class_list)
        return mask

    def convert_gray_label(self, mask, class_list):
        shape = mask.shape  # shape = [height, width]
        result = np.full(shape, 250, dtype=np.uint8)
        for index, value in enumerate(class_list):
            gray_value = int(value[1].strip())
            result[mask == gray_value] = index
        return result

    def convert_color_label(self, mask, class_list):
        shape = mask.shape[:2]  # shape = [height, width]
        result = np.full(shape, 250, dtype=np.uint8)
        for index, value in enumerate(class_list):
            value_list = [int(x) for x in value[1].spilt(',') if x.strip()]
            color_value = np.array(value_list, dtype=np.uint8)
            temp1 = mask[:, :] == color_value
            temp2 = np.sum(temp1, axis=2)
            result[temp2 == 3] = index
        return result

def main():
    print("start...")
    options = ToolArgumentsParse.dir_path_parse()
    test = ConvertSegmentionLable()
    config_factory = ConfigFactory()
    task_config = config_factory.get_config(TaskName.Segment_Task, config_path=options.config_path)
    test.convert_segment_label(options.inputPath,
                               task_config.label_is_gray,
                               task_config.class_name)
    print("End of game, have a nice day!")

if __name__ == "__main__":
    main()


text:
import numpy as np
from gym import spaces
from gym import Env

# from . import register_env

# @register_env('point-robot')
class PointEnvOld(Env):
    """
    point robot on a 2-D plane with position control
    tasks (aka goals) are positions on the plane

     - tasks sampled from unit square
     - reward is L2 distance
    """

    def __init__(self):

        # self.observation_space = spaces.Box(low=-np.inf, high=np.inf, shape=(2,))
        self.observation_space = spaces.Box(low=-1.0, high=1.0, shape=(2,))
        self.action_space = spaces.Box(low=-1.0, high=1.0, shape=(2,))
        self.t = 0
        self.H = 15

    def reset_model(self):
        self._state = np.zeros(shape=(2,))
        return self._get_obs()

    def reset(self):
        self.t = 0
        return self.reset_model()

    def _get_obs(self):
        return np.copy(self._state)

    def step(self, action):
        self._state = self._state + action/10.0
        self._state = np.clip(self._state, -1.0, 1.0)
        # done = False
        ob = self._get_obs()
        self.t += 1
        done = (self.t >= self.H)
        return ob, 0.0, done, dict()

    def viewer_setup(self):
        print('no viewer')
        pass

    def render(self):
        print('current state:', self._state)

max_stars_repo_name: YashBit/accelerate-skillDiscovery

max_issues_repo_name: YashBit/accelerate-skillDiscovery

max_forks_repo_name: YashBit/accelerate-skillDiscovery