text:
from __future__ import division
import numpy as np
import pandas as pd

class TrexFunctions(object):
    """
    Function class for Trex.
    """

    def __init__(self):
        """Class representing the functions for Trex"""
        super(TrexFunctions, self).__init__()

    def app_rate_parsing(self):
        # extract first day and maximum application rates from each model simulation run
        # these variables are needed in various methods
        self.first_app_rate = pd.Series([], dtype='float') #series of first_day app rates across model simulations
        self.max_app_rate = pd.Series([], dtype='float') #series of maximum app_rates across model simulations
        for i in range(len(self.app_rates)):
            self.first_app_rate[i] = self.app_rates[i][0]
            self.max_app_rate[i] = max(self.app_rates[i])
        return

    def convert_strlist_float_python27(self, pd_series_strings):
        #method converts a panda series of lists whose elements are strings
        #to a series of lists of floats
        #create list of strings
        pd_series_floats = pd.Series([], dtype="object")
        temp1 = pd.Series([], dtype="object")
        temp = pd_series_strings.tolist()
        for j, item in enumerate(temp):
            temp1[j] = item.strip('[')
            temp1[j] = temp1[j].strip(']')
        #create list of vectors of strings
        temp2 = [str(i).split(',') for i in temp1]
        #convert to floats and assign back to series
        for j, item in enumerate(temp2):
            temp_item = map(float, item)
            pd_series_floats.loc[j] = temp_item
        return pd_series_floats

    def convert_strlist_float(self, pd_series_strings):
        #method converts a panda series of lists whose elements are strings
        #to a series of lists of floats
        #create list of strings
        temp1 = pd.Series([], dtype="object")
        temp = pd_series_strings.tolist()
        for j, item in enumerate(temp):
            temp1[j] = item.strip('[')
            temp1[j] = temp1[j].strip(']')
        #create list of vectors of strings
        temp2 = [str(i).split(',') for i in temp1]
        #convert to floats and assign back to series
        max_apps = 0
        for i, app_list in enumerate(pd_series_strings):
            temp_apps = len(app_list.split(','))
            max_apps = max(max_apps, temp_apps)
        pd_series_floats = [[0.0 for i in range(max_apps)] for j in range(len(self.num_apps))]
        for j, item in enumerate(temp2):
            for k in range(len(item)):
                pd_series_floats[j][k] = float(temp2[j][k])
        return pd_series_floats

    def convert_strlist_int(self, pd_series_strings):
        #method converts a panda series of lists whose elements are strings
        #to a series of lists of integers
        #create list of strings
        temp1 = pd.Series([], dtype="object")
        temp = pd_series_strings.tolist()
        for j, item in enumerate(temp):
            temp1[j] = item.strip('[')
            temp1[j] = temp1[j].strip(']')
        #create list of vectors of strings
        temp2 = [str(i).split(',') for i in temp1]
        #convert to integers and assign back to series
        max_apps = 0
        for i, app_list in enumerate(pd_series_strings):
            temp_apps = len(app_list.split(','))
            max_apps = max(max_apps, temp_apps)
        pd_series_ints = [[0 for i in range(max_apps)] for j in range (len(self.num_apps))]
        for j, item in enumerate(temp2):
            for k in range(len(item)):
                pd_series_ints[j][k] = int(temp2[j][k])
        return pd_series_ints

    def convert_strlist_int_python27(self, pd_series_strings):
        #method converts a panda series of lists whose elements are strings
        #to a series of lists of integers
        #create list of strings
        pd_series_ints = pd.Series([], dtype="object")
        temp1 = pd.Series([], dtype="object")
        temp = pd_series_strings.tolist()
        for j, item in enumerate(temp):
            temp1[j] = item.strip('[')
            temp1[j] = temp1[j].strip(']')
        #create list of vectors of strings
        temp2 = [str(i).split(',') for i in temp1]
        #convert to integers and assign back to series
        for j, item in enumerate(temp2):
            temp_item = map(int, item)
            pd_series_ints.loc[j] = temp_item
        return pd_series_ints

    def conc_initial(self, i, application_rate, food_multiplier):
    # Initial concentration from new application
        conc_0 = (application_rate * self.frac_act_ing[i] * food_multiplier)
        return conc_0

    def conc_timestep(self, i, conc_ini):
        # calculate concentration resulting from degradation for a daily timestep
        #??what is the purpose of the '* 1', just a timestep value to be complete
        conc = conc_ini * np.exp(-(np.log(2) / self.foliar_diss_hlife[i]) * 1)
        return conc

    def percent_to_frac(self, percent):
        fraction = percent / 100.
        return fraction

    def inches_to_feet(self, inches):
        feet = inches / 12
        return feet

    def sa_bird_1(self, size):
    # Seed treatment acute RQ for birds method 1

        # setup panda series
        at_bird_temp = pd.Series([], dtype='float', name="at_bird_temp")
        fi_bird_temp = pd.Series([], dtype='float',name="fi_bird_temp")
        #maximum seed application rate (m_s_r_p)
        m_s_a_r_temp = pd.Series([], dtype='float',name="m_s_a_r_temp")
        nagy_bird_temp = pd.Series([], dtype='float',name="nagy_bird_temp")
        aw_bird = pd.Series([], dtype = 'float', name="aw_bird")

        if size == "small":
                mf_w_bird = self.mf_w_bird_1
                nagy_bird_coef = self.nagy_bird_coef_sm
                aw_bird = self.aw_bird_sm
        elif size == "medium":
                mf_w_bird = self.mf_w_bird_1
                nagy_bird_coef = self.nagy_bird_coef_md
                aw_bird = self.aw_bird_md
        elif size == "large":
                mf_w_bird = self.mf_w_bird_1
                nagy_bird_coef = self.nagy_bird_coef_lg
                aw_bird = self.aw_bird_lg

        #fi_bird_temp = self.fi_bird(aw_bird, mf_w_bird)
        for i in range(len(aw_bird)):
            at_bird_temp[i] = self.at_bird(i, aw_bird[i])
        fi_bird_temp = self.fi_bird(aw_bird, mf_w_bird)
        m_s_a_r_temp = ((self.first_app_rate  * self.frac_act_ing) / 128.) * self.density * 10000
        nagy_bird_temp = fi_bird_temp * 0.001 * m_s_a_r_temp / nagy_bird_coef
        sa_bird_1_return = nagy_bird_temp / at_bird_temp
        return sa_bird_1_return

    def sa_bird_2(self, size):
        # Seed treatment acute RQ for birds method 2

        at_bird_temp = pd.Series([], dtype='float', name="at_bird_temp")
        m_a_r = pd.Series([], dtype='float', name="m_a_r")
        av_ai = pd.Series([], dtype='float', name="av_ai")
        sa_bird_2_return = pd.Series([], dtype='float', name="sa_bird_2_return")

        if size == "small":
            nagy_bird_coef = self.nagy_bird_coef_sm
            aw_bird = self.aw_bird_sm
        elif size == "medium":
            nagy_bird_coef = self.nagy_bird_coef_md
            aw_bird = self.aw_bird_md
        elif size == "large":
            nagy_bird_coef = self.nagy_bird_coef_lg
            aw_bird = self.aw_bird_lg

        for i in range(len(aw_bird)):
            at_bird_temp[i] = self.at_bird(i, aw_bird[i])
        m_a_r = (self.max_seed_rate * ((self.frac_act_ing * self.first_app_rate) / 128) * self.density) / 100  # maximum application rate
        av_ai = m_a_r * 1e6 / (43560 * 2.2)
        sa_bird_2_return = av_ai / (at_bird_temp * nagy_bird_coef)
        return sa_bird_2_return

    def sc_bird(self):
        # Seed treatment chronic RQ for birds
        m_s_a_r = ((self.first_app_rate * self.frac_act_ing) / 128) * self.density * 10000  # maximum seed application rate=application rate*10000
        risk_quotient = m_s_a_r / self.noaec_bird
        return risk_quotient

    def sa_mamm_1(self, size):
        # Seed treatment acute RQ for mammals method 1

        at_mamm_temp = pd.Series([], dtype='float', name="at_mamm_temp")

        if size == "small":
            mf_w_bird = self.mf_w_bird_1
            nagy_mamm_coef = self.nagy_mamm_coef_sm
            aw_mamm = self.aw_mamm_sm
        elif size == "medium":
            mf_w_bird = self.mf_w_bird_1
            nagy_mamm_coef = self.nagy_mamm_coef_md
            aw_mamm = self.aw_mamm_md
        elif size == "large":
            mf_w_bird = self.mf_w_bird_1
            nagy_mamm_coef = self.nagy_mamm_coef_lg
            aw_mamm = self.aw_mamm_lg

        for i in range(len(aw_mamm)):
            at_mamm_temp[i] = self.at_mamm(i, aw_mamm[i])
        fi_mamm_temp = self.fi_mamm(aw_mamm, mf_w_bird)
        m_s_a_r = ((self.first_app_rate * self.frac_act_ing) / 128) * self.density * 10000  # maximum seed application rate=application rate*10000
        nagy_mamm = fi_mamm_temp * 0.001 * m_s_a_r / nagy_mamm_coef
        quotient = nagy_mamm / at_mamm_temp
        return quotient

    def sa_mamm_2(self, size):
        # Seed treatment acute RQ for mammals method 2

        at_mamm_temp = pd.Series([], dtype='float', name="at_mamm_temp")

        if size == "small":
            nagy_mamm_coef = self.nagy_mamm_coef_sm
            aw_mamm = self.aw_mamm_sm
        elif size == "medium":
            nagy_mamm_coef = self.nagy_mamm_coef_md
            aw_mamm = self.aw_mamm_md
        elif size == "large":
            nagy_mamm_coef = self.nagy_mamm_coef_lg
            aw_mamm = self.aw_mamm_lg

        for i in range(len(aw_mamm)):
            at_mamm_temp[i] = self.at_mamm(i, aw_mamm[i])
        m_a_r = (self.max_seed_rate * ((self.first_app_rate * self.frac_act_ing) / 128) * self.density) / 100  # maximum application rate
        av_ai = m_a_r * 1000000 / (43560 * 2.2)
        quotient = av_ai / (at_mamm_temp * nagy_mamm_coef)
        return quotient

    def sc_mamm(self, size):
        # Seed treatment chronic RQ for mammals

        if size == "small":
            mf_w_mamm = self.mf_w_mamm_1
            nagy_mamm_coef = self.nagy_mamm_coef_sm
            aw_mamm = self.aw_mamm_sm
        elif size == "medium":
            mf_w_mamm = self.mf_w_mamm_1
            nagy_mamm_coef = self.nagy_mamm_coef_md
            aw_mamm = self.aw_mamm_md
        elif size == "large":
            mf_w_mamm = self.mf_w_mamm_1
            nagy_mamm_coef = self.nagy_mamm_coef_lg
            aw_mamm = self.aw_mamm_lg

        anoael_mamm_temp = self.anoael_mamm(aw_mamm)
        fi_mamm_temp = self.fi_mamm(aw_mamm, mf_w_mamm)
        m_s_a_r = ((self.first_app_rate * self.frac_act_ing) / 128) * self.density * 10000  # maximum seed application rate=application rate*10000
        nagy_mamm = fi_mamm_temp * 0.001 * m_s_a_r / nagy_mamm_coef
        quotient = nagy_mamm / anoael_mamm_temp
        return quotient

    def fi_bird(self, aw_bird, mf_w_bird):
        # food intake for birds
        food_intake = (0.648 * (aw_bird ** 0.651)) / (1 - mf_w_bird)
        return food_intake

    def fi_mamm(self, aw_mamm, mf_w_mamm):
        # food intake for mammals
        food_intake = (0.621 * (aw_mamm ** 0.564)) / (1 - mf_w_mamm)
        return food_intake

    def at_bird(self, i, aw_bird):
        # Acute adjusted toxicity value for birds
        adjusted_toxicity = self.ld50_bird[i] * (aw_bird / self.tw_bird_ld50[i]) ** (self.mineau_sca_fact[i] - 1)
        return adjusted_toxicity

    def at_bird1(self, aw_bird):
        # Acute adjusted toxicity value for birds
        adjusted_toxicity = self.ld50_bird * (aw_bird / self.tw_bird_ld50) ** (self.mineau_sca_fact - 1)
        return adjusted_toxicity

    def at_mamm(self, i, aw_mamm):
        # Acute adjusted toxicity value for mammals
        adjusted_toxicity = self.ld50_mamm[i] * ((self.tw_mamm[i] / aw_mamm) ** 0.25)
        return adjusted_toxicity

    def anoael_mamm(self, aw_mamm):
    # Adjusted chronic toxicity (NOAEL) value for mammals
        adjusted_toxicity = self.noael_mamm * ((self.tw_mamm / aw_mamm) ** 0.25)
        return adjusted_toxicity

    def eec_diet_max(self, food_multiplier):
        """
        method produces a concentration timeseries (daily for 1 yr + a week) and extracts the maximum concentration value
        also scans time series and extracts the maximum daily concentration for the year
        """

        #temp_ts = pd.Series([], dtype = 'float')

        #get timeseries of daily concentrations for the year (+ a week)
        temp_ts = self.eec_diet_timeseries(food_multiplier)
        # get maximum daily concentration that occurs during the year
        max_concs = pd.Series([temp_ts[i].max() for i in range(len(temp_ts))])
        return max_concs

    def eec_diet_timeseries(self, food_multiplier):
        # Dietary based EECs
        # calculations are performed daily from day of first application through the last day of the year
        # note: day numbers are synchronized with 0-based array indexing; thus January 1 is the 0th array index
        c_temp_1 = pd.Series([], dtype='object')
        c_temp = pd.Series([], dtype='float')
        temp_app_indices = pd.Series([], dtype='float')
        temp_app_rates = pd.Series([], dtype='float')
        temp_num_apps = pd.Series([], dtype='float')

        for i in range(len(self.num_apps)):  #i denotes model simulation run (e.g., within a monte carlo simulation)

            c_temp = np.zeros((371, 1))  # empty array to hold the concentrations over days of year (index 0 = Jan 1)
            app_counter = 0  #iniitalize application number counter for this model simulation run (i)
            temp_num_apps = self.num_apps[i]
            temp_app_indices = np.asarray(self.day_out[i]) - 1
            temp_app_rates = np.asarray(self.app_rates[i])

            for day_index in range(temp_app_indices[0], 371):     # day number of first application
                if day_index == temp_app_indices[0]:  # first day of application (single or multiple application model simulation run)
                    c_temp[day_index] = self.conc_initial(i, temp_app_rates[0], food_multiplier)
                    app_counter += 1
                elif app_counter <= temp_num_apps - 1:  # next application day
                    if day_index == temp_app_indices[app_counter]:
                        c_temp[day_index] = (self.conc_timestep(i, c_temp[day_index - 1]) +
                                             self.conc_initial(i, temp_app_rates[app_counter], food_multiplier))
                        app_counter += 1
                    else:
                        c_temp[day_index] = self.conc_timestep(i, c_temp[day_index - 1])
                else:
                    #following line allows for all days after last application to be computed
                    c_temp[day_index] = self.conc_timestep(i, c_temp[day_index - 1])
            c_temp_1[i] = c_temp #complete set of time series (e.g., for plotting)
        return c_temp_1

    def eec_dose_bird(self, aw_bird, mf_w_bird, food_multiplier):
    # Dose based EECs for birds
        fi_bird_temp = self.fi_bird(aw_bird, mf_w_bird)
        eec_diet_temp = self.eec_diet_max(food_multiplier)
        eec_out = eec_diet_temp * fi_bird_temp / aw_bird
        return eec_out

    def eec_dose_mamm(self, aw_mamm, mf_w_mamm, food_multiplier):
    # Dose based EECs for mammals
        eec_diet_temp = self.eec_diet_max(food_multiplier)
        fi_mamm_temp = self.fi_mamm(aw_mamm, mf_w_mamm)
        dose_eec = eec_diet_temp * fi_mamm_temp / aw_mamm
        return dose_eec

    def arq_dose_bird(self, aw_bird, mf_w_bird, food_multiplier):
    # Acute dose-based risk quotients for birds
        at_bird_temp = pd.Series([], dtype = 'float')
        eec_dose_bird_temp = self.eec_dose_bird(aw_bird, mf_w_bird, food_multiplier)
        for i in range(len(aw_bird)):
            at_bird_temp[i] = self.at_bird(i, aw_bird[i])
        risk_quotient = eec_dose_bird_temp / at_bird_temp
        return risk_quotient

    def arq_dose_mamm(self, aw_mamm, mf_w_mamm, food_multiplier):
    # Acute dose-based risk quotients for mammals
        at_mamm_temp = pd.Series([], dtype = 'float')
        eec_dose_mamm_temp = self.eec_dose_mamm(aw_mamm, mf_w_mamm, food_multiplier)
        for i in range(len(aw_mamm)):
            at_mamm_temp[i] = self.at_mamm(i, aw_mamm[i])
        risk_quotient = eec_dose_mamm_temp / at_mamm_temp
        return risk_quotient

    def arq_diet_bird(self, food_multiplier):
    # Acute dietary-based risk quotients for birds
        eec_diet_temp = self.eec_diet_max(food_multiplier)
        risk_quotient = eec_diet_temp / self.lc50_bird
        return risk_quotient

    def arq_diet_mamm(self, food_multiplier):
    # Acute dietary-based risk quotients for mammals
        eec_diet_temp = self.eec_diet_max(food_multiplier)
        risk_quotient = eec_diet_temp / self.lc50_mamm
        return risk_quotient

    def crq_diet_bird(self, food_multiplier):
    # Chronic dietary-based risk quotients for birds
        eec_diet_temp = self.eec_diet_max(food_multiplier)
        risk_quotient = eec_diet_temp / self.noaec_bird
        return risk_quotient

    def crq_diet_mamm(self, food_multiplier):
    # Chronic dietary-based risk quotients for mammals
        eec_diet_temp = self.eec_diet_max(food_multiplier)
        crq_diet_mamm_temp = eec_diet_temp / self.noaec_mamm
        return crq_diet_mamm_temp

    def crq_dose_mamm(self, aw_mamm, mf_w_mamm, food_multiplier):
    # Chronic dose-based risk quotients for mammals
        anoael_mamm_temp = self.anoael_mamm(aw_mamm)
        eec_dose_mamm_temp = self.eec_dose_mamm(aw_mamm, mf_w_mamm, food_multiplier)
        risk_quotient = eec_dose_mamm_temp / anoael_mamm_temp
        return risk_quotient

    def ld50_rg_bird(self, aw_bird):
        # LD50ft-2 for row/band/in-furrow granular birds
        ld50_rg_bird_temp = pd.Series([], dtype='float')
        at_bird_temp = pd.Series([], dtype = 'float')
        num_rows_peracre = pd.Series([], dtype = 'float')
        expo_rg_bird = pd.Series([], dtype = 'float')
        for i in range(len(aw_bird)):
            if self.application_type[i] == 'Row/Band/In-furrow-Granular':
                at_bird_temp = self.at_bird(i, aw_bird[i])
                num_rows_peracre = (43560 ** 0.5) / self.row_spacing[i] #43560 ft2/acre
                expo_rg_bird = ((max(self.app_rates[i]) * self.frac_act_ing[i] * 453590.0) /    #453,590 mg/lb
                               (num_rows_peracre * (43560.0 ** 0.5) * self.bandwidth[i])) *   \
                                (1 - self.frac_incorp[i])                                    #(43560.0 ** 0.5) = row_length
                ld50_rg_bird_temp[i] = expo_rg_bird / (at_bird_temp * (aw_bird[i] / 1000.0))
            else:
                ld50_rg_bird_temp[i] = np.nan
        return ld50_rg_bird_temp

    def ld50_rg_bird1(self, aw_bird):
        """
        # LD50ft-2 for row/band/in-furrow granular birds; alternative iterative approach
        """

        ld50_rg_bird_temp = pd.Series([], dtype='float')
        at_bird_temp = pd.Series([], dtype = 'float')
        num_rows_peracre = pd.Series([], dtype = 'float')
        expo_rg_bird = pd.Series([], dtype = 'float')

        # calculate all values of 'ld50_rg_bird_temp' regardless of application_type (to facilitate vectorization)
        at_bird_temp = self.at_bird1(aw_bird)
        num_rows_peracre = (43560 ** 0.5) / self.row_spacing  #43560 ft2/acre

        expo_rg_bird = ((self.max_app_rate * self.frac_act_ing * 453590.0) /
                       (num_rows_peracre * (43560.0 ** 0.5) * (self.bandwidth))) * (1 - self.frac_incorp)
        ld50_rg_bird_temp = expo_rg_bird / (at_bird_temp * (aw_bird / 1000.0))
        #go back and replace all non 'Row/Band/In-furrow-Granular' app types with value of nan (not a number)
        for i in range(len(aw_bird)):
            if self.application_type[i] != 'Row/Band/In-furrow-Granular':
                ld50_rg_bird_temp[i] = np.nan
        return ld50_rg_bird_temp

    def ld50_rl_bird(self, aw_bird):
        # LD50ft-2 for row/band/in-furrow liquid birds
        ld50_rl_bird_temp = pd.Series([], dtype = 'float')
        for i in range(len(aw_bird)):
            if self.application_type[i] == 'Row/Band/In-furrow-Liquid':
                at_bird_temp = self.at_bird(i, aw_bird[i])
                expo_rl_bird = ((max(self.app_rates[i]) * 28349 * self.frac_act_ing[i]) /
                                (1000 * self.bandwidth[i])) * (1 - self.frac_incorp[i])
                ld50_rl_bird_temp[i] = expo_rl_bird / (at_bird_temp * (aw_bird[i] / 1000.0))
            else:
                ld50_rl_bird_temp[i] = np.nan
        return ld50_rl_bird_temp

    def ld50_bg_bird(self, aw_bird):
        # LD50ft-2 for broadcast granular birds
        ld50_bg_bird_temp = pd.Series([], dtype = 'float')
        for i in range(len(aw_bird)):
            if self.application_type[i] == 'Broadcast-Granular':
                at_bird_temp = self.at_bird(i, aw_bird[i])
                expo_bg_bird = ((max(self.app_rates[i]) * self.frac_act_ing[i] * 453590) / 43560)
                ld50_bg_bird_temp[i] = expo_bg_bird / (at_bird_temp * (aw_bird[i] / 1000.0))
            else:
                ld50_bg_bird_temp[i] = np.nan
        return ld50_bg_bird_temp

    def ld50_bl_bird(self, aw_bird):
        # LD50ft-2 for broadcast liquid birds
        ld50_bl_bird_temp = pd.Series([], dtype = 'float')
        for i in range(len(aw_bird)):
            if self.application_type[i] == 'Broadcast-Liquid':
                at_bird_temp = self.at_bird(i, aw_bird[i])
                # this would be used for fl oz but front end requires lb/a
                # expo_bl_bird=((max(self.app_rates)*28349*frac_act_ing)/43560)*(1-frac_incorp)
                # for lb based liquid application rates
                expo_bl_bird = ((max(self.app_rates[i]) * 453590 * self.frac_act_ing[i]) / 43560)
                ld50_bl_bird_temp[i] = expo_bl_bird / (at_bird_temp * (aw_bird[i] / 1000.0))
            else:
                ld50_bl_bird_temp[i] = np.nan
        return ld50_bl_bird_temp

    def ld50_rg_mamm(self, aw_mamm):
        # LD50ft-2 for row/band/in-furrow granular mammals
        ld50_rg_mamm_temp = pd.Series([], dtype = 'float')
        for i in range(len(aw_mamm)):
            if self.application_type[i] == 'Row/Band/In-furrow-Granular':
                # a_r = max(app_rates)
                at_mamm_temp = self.at_mamm(i, aw_mamm[i])
                num_rows_peracre = (43560 ** 0.5) / self.row_spacing[i]
                expo_rg_mamm = ((max(self.app_rates[i]) * self.frac_act_ing[i] * 453590) /
                               (num_rows_peracre * (43560 ** 0.5) * self.bandwidth[i]) * (1 - self.frac_incorp[i]))
                ld50_rg_mamm_temp[i] = expo_rg_mamm / (at_mamm_temp * (aw_mamm[i] / 1000.0))
            else:
                ld50_rg_mamm_temp[i] = np.nan
        return ld50_rg_mamm_temp

    def ld50_rl_mamm(self, aw_mamm):
        # LD50ft-2 for row/band/in-furrow liquid mammals
        ld50_rl_mamm_temp = pd.Series([], dtype = 'float')
        for i in range(len(aw_mamm)):
            if self.application_type[i] == 'Row/Band/In-furrow-Liquid':
                at_mamm_temp = self.at_mamm(i, aw_mamm[i])
                expo_rl_mamm = ((max(self.app_rates[i]) * 28349 * self.frac_act_ing[i]) /
                                (1000 * self.bandwidth[i])) * (1 - self.frac_incorp[i])
                ld50_rl_mamm_temp[i] = expo_rl_mamm / (at_mamm_temp * (aw_mamm[i] / 1000.0))
            else:
                ld50_rl_mamm_temp[i] = np.nan
        return ld50_rl_mamm_temp

    def ld50_bg_mamm(self, aw_mamm):
    # LD50ft-2 for broadcast granular mammals
        ld50_bg_mamm_temp = pd.Series([], dtype="float")
        for i in range(len(aw_mamm)):
            if self.application_type[i] == 'Broadcast-Granular':
                at_mamm_temp = self.at_mamm(i, aw_mamm[i])
                expo_bg_mamm = ((max(self.app_rates[i]) * self.frac_act_ing[i] * 453590) / 43560)
                ld50_bg_mamm_temp[i] = expo_bg_mamm / (at_mamm_temp * (aw_mamm[i] / 1000.0))
            else:
                ld50_bg_mamm_temp[i] = np.nan
        return ld50_bg_mamm_temp

    def ld50_bl_mamm(self, aw_mamm):
    # LD50ft-2 for broadcast liquid mammals
        ld50_bl_mamm_temp = pd.Series([], dtype="float")
        for i in range(len(aw_mamm)):
            if self.application_type[i] == 'Broadcast-Liquid':
                at_mamm_temp = self.at_mamm(i, aw_mamm[i])
                # expo_bl_mamm=((max(self.app_rates)*28349*self.frac_act_ing)/43560)*(1-frac_incorp)
                expo_bl_mamm = ((max(self.app_rates[i]) * self.frac_act_ing[i] * 453590.) / 43560.)  #453590 mg/lb; 43560ft2/acre
                ld50_bl_mamm_temp[i] = expo_bl_mamm / (at_mamm_temp * (aw_mamm[i] / 1000.0))
            else:
                ld50_bl_mamm_temp[i] = np.nan
        return ld50_bl_mamm_temp

max_stars_repo_name: qed-uber/ubertool

max_issues_repo_name: qed-uber/ubertool

max_forks_repo_name: quanted/ubertool


text:
import sys
import time
import numpy as np
import torch

#
#_, term_width = os.popen('stty size', 'r').read().split()
term_width = 97#  int(term_width)

TOTAL_BAR_LENGTH = 65.
last_time = time.time()
begin_time = last_time
def progress_bar(current, total, msg=None):
    global last_time, begin_time
    if current == 0:
        begin_time = time.time()  # Reset for new bar.

    cur_len = int(TOTAL_BAR_LENGTH*current/total)
    rest_len = int(TOTAL_BAR_LENGTH - cur_len) - 1

    sys.stdout.write(' [')
    for i in range(cur_len):
        sys.stdout.write('=')
    sys.stdout.write('>')
    for i in range(rest_len):
        sys.stdout.write('.')
    sys.stdout.write(']')

    cur_time = time.time()
    step_time = cur_time - last_time
    last_time = cur_time
    tot_time = cur_time - begin_time

    L = []
    L.append('  Step: %s' % format_time(step_time))
    L.append(' | Tot: %s' % format_time(tot_time))
    if msg:
        L.append(' | ' + msg)

    msg = ''.join(L)
    sys.stdout.write(msg)
    for i in range(term_width-int(TOTAL_BAR_LENGTH)-len(msg)-3):
        sys.stdout.write(' ')

    # Go back to the center of the bar.
    for i in range(term_width-int(TOTAL_BAR_LENGTH/2)+2):
        sys.stdout.write('\b')
    sys.stdout.write(' %d/%d ' % (current+1, total))

    if current < total-1:
        sys.stdout.write('\r')
    else:
        sys.stdout.write('\n')
    sys.stdout.flush()

def format_time(seconds):
    days = int(seconds / 3600/24)
    seconds = seconds - days*3600*24
    hours = int(seconds / 3600)
    seconds = seconds - hours*3600
    minutes = int(seconds / 60)
    seconds = seconds - minutes*60
    secondsf = int(seconds)
    seconds = seconds - secondsf
    millis = int(seconds*1000)

    f = ''
    i = 1
    if days > 0:
        f += str(days) + 'D'
        i += 1
    if hours > 0 and i <= 2:
        f += str(hours) + 'h'
        i += 1
    if minutes > 0 and i <= 2:
        f += str(minutes) + 'm'
        i += 1
    if secondsf > 0 and i <= 2:
        f += str(secondsf) + 's'
        i += 1
    if millis > 0 and i <= 2:
        f += str(millis) + 'ms'
        i += 1
    if f == '':
        f = '0ms'
    return f

# count_net_parameters
def count_net_parameters(model):
    # for name, v in models.named_parameters():
    #     print(name, np.prod(v.size()))
    return np.sum(np.prod(v.size()) for name, v in model.named_parameters() if "auxiliary" not in name) / 1e6

# AvgrageMeter
class AvgrageMeter(object):
    def __init__(self):
        self.reset()

    def reset(self):
        self.avg = 0
        self.sum = 0
        self.cnt = 0

    def update(self, val, n=1):
        self.sum += val * n
        self.cnt += n
        self.avg = self.sum / self.cnt

# calAccuracy
def calAccuracy(output, target, topk=(1,)):
    # output, target: torch.Size([96, 10]) torch.Size([96])

    maxk = max(topk)
    #int

    batch_size = target.size(0)

    _, pred = output.topk(maxk, 1, True, True)
    # _, pred: torch.Size([96, 5]) torch.Size([96, 5])

    #print('output, target, pred:', output.shape, target.shape, pred.shape)
    pred = pred.t()
    # pred: torch.Size([5, 96])

    correct = pred.eq(target.view(1, -1).expand_as(pred))
    # correct: torch.Size([5, 96])

    res = []
    for k in topk:
        correct_k = correct[:k].view(-1).float().sum(0)
        res.append(correct_k.mul_(100.0 / batch_size))

    return res

class Cutout(object):
    def __init__(self, length):
        self.length = length

    def __call__(self, img):
        h, w = img.size(1), img.size(2)
        mask = np.ones((h, w), np.float32)
        y = np.random.randint(h)
        x = np.random.randint(w)

        y1 = np.clip(y - self.length // 2, 0, h)
        y2 = np.clip(y + self.length // 2, 0, h)
        x1 = np.clip(x - self.length // 2, 0, w)
        x2 = np.clip(x + self.length // 2, 0, w)

        mask[y1: y2, x1: x2] = 0.
        mask = torch.from_numpy(mask)
        mask = mask.expand_as(img)
        img *= mask
        return img

# combineSample, input: 3, 2  output:[0, 2]
def combineSample(maxNum, sampleNum):
    pool = np.r_[0:maxNum]

    ret = []
    for i in range(sampleNum):
        z = np.random.choice(pool, 1)
        index = np.where(pool == z)
        pool = np.delete(pool, index)
        ret.append(z[0])
    return ret

# combineSampleRetList, input: 3, 2  output:[0, 2]
def combineSampleRetList(maxNum, sampleNum):
    retFlagList = np.zeros(maxNum)

    pool = np.r_[0:maxNum]
    for i in range(sampleNum):
        z = np.random.choice(pool, 1)
        index = np.where(pool == z)
        pool = np.delete(pool, index)
        retFlagList[z[0]] = 1

    return retFlagList

#GenerateArch
def GenerateArch(testArchNum = 10):
    def SampleArch(sampleNum):
        nodeNum = 14
        opNum = 6

        choice = np.random.choice(opNum, sampleNum * nodeNum)
        choice = np.eye(opNum)[choice]
        choice = np.array(choice, dtype=np.int8).reshape(sampleNum, nodeNum, opNum)
        return choice

    def SampleEdge(sampleNum):
        cellSize = 4
        nodeNum = 14

        ret = []
        for sampleIndex in range(sampleNum):
            start = 0
            sampleList = np.zeros(nodeNum)
            for cellIndex in range(cellSize):
                edgeNum = 2 + cellIndex

                # 从edgeNum中选出2条
                choice = combineSample(edgeNum, 2)
                choice = [i + start for i in choice]

                start = start + edgeNum
                sampleList[choice] = 1

            ret.append(sampleList)

        ret = np.array(ret, dtype=np.int8)
        return ret

    allNormalOp = SampleArch(testArchNum)
    allReduceOp = SampleArch(testArchNum)

    allNormalEdge = SampleEdge(testArchNum)
    allReduceEdge = SampleEdge(testArchNum)
    return allNormalOp, allReduceOp, allNormalEdge, allReduceEdge

#combination
def combination(nums, k):
    ans = [[]]
    for i in range(k):
        ans = [pre + [sub]
               for pre in ans for sub in nums if i == 0 or sub > pre[-1]]
    return ans

# mixup
def mixup_data(x, y, device, alpha=2.0):
    '''Compute the mixup data. Return mixed inputs, pairs of targets, and lambda'''
    if alpha > 0.:
        lam = np.random.beta(alpha, alpha)
    else:
        lam = 1.
    batch_size = x.size()[0]
    index = torch.randperm(batch_size).to(device)

    mixed_x = lam * x + (1 - lam) * x[index,:]
    y_a, y_b = y, y[index]
    return mixed_x, y_a, y_b, lam

def mixup_criterion(y_a, y_b, lam):
    return lambda criterion, pred: lam * criterion(pred, y_a) + (1 - lam) * criterion(pred, y_b)

ext: py

max_stars_repo_name: pingguokiller/hoenas

max_issues_repo_name: Light-Reflection/hoenas

max_forks_repo_name: Light-Reflection/hoenas

reason: import numpy


text:
# Calculates the error of a given symbolic expression applied to a dataset. The input should be a string of the mathematical expression

from .get_pareto import Point, ParetoSet
from sympy.parsing.sympy_parser import parse_expr
import numpy as np
import matplotlib.pyplot as plt
import os
from os import path
from sympy import Symbol, lambdify, N

def get_symbolic_expr_error(data,expr):
    try:
        N_vars = len(data[0])-1
        possible_vars = ["x%s" %i for i in np.arange(0,30,1)]
        variables = []
        for i in range(N_vars):
            variables = variables + [possible_vars[i]]
        eq = parse_expr(expr)
        f = lambdify(variables, N(eq))
        real_variables = []

        for i in range(len(data[0])-1):
            check_var = "x"+str(i)
            if check_var in np.array(variables).astype('str'):
                real_variables = real_variables + [data[:,i]]

        # Remove accidental nan's
        good_idx = np.where(np.isnan(f(*real_variables))==False)

        # use this to get rid of cases where the loss gets complex because of transformations of the output variable
        if isinstance(np.mean((f(*real_variables)-data[:,-1])**2), complex):
            return 1000000
        else:
            try:
                return np.mean(np.log2(1+abs(f(*real_variables)[good_idx]-data[good_idx][:,-1])*2**30))
            except:
                return np.mean(np.log2(1+abs(f(*real_variables)-data[:,-1])*2**30))
    except:
        return 1000000

max_stars_repo_name: pranjukn/AI-Feynman

max_issues_repo_name: pranjukn/AI-Feynman

max_forks_repo_name: pranjukn/AI-Feynman

reason: import numpy,from sympy


text:
import time
import numpy as np
import ConfigParser
import os.path
import Adafruit_CharLCD as LCD
import Adafruit_GPIO.MCP230xx as MCP
import Adafruit_MAX31855.MAX31855 as MAX31855
import Adafruit_MCP3008
import RPi.GPIO as GPIO

import Utilities
import LedOutputs
import DigitalInputs
from CharLcdOutput import CharLcdOutput

from sqlalchemy import create_engine
from sqlalchemy.ext.declarative import declarative_base
from sqlalchemy.orm import sessionmaker

class MainControl:
    def __init__(self):
        self.program_mode = 'Startup'
        self.mode_state = 'Startup'
        self.previous_program_mode = 'Startup'
        self.lcd = CharLcdOutput.setup_char_lcd()
        #setting up SPI connected devices (temperature sensors and analog sensors)
        clk = 11
        cs_sensor_1  = 7
        cs_sensor_2 = 7
        cs_analog = 8
        data_out  = 9
        data_in = 10

        # set I2C reset pin high so we can see those devices
        i2c_reset = 21
        GPIO.setmode(GPIO.BCM)
        GPIO.setup(i2c_reset, GPIO.OUT)
        GPIO.output(i2c_reset, True)

        # set spi selector high so that we can engage the A2D chip
        analog_spi_select = 17
        GPIO.setup(analog_spi_select, GPIO.OUT)
        GPIO.setup(27, GPIO.OUT)
        GPIO.setup(22, GPIO.OUT)
        GPIO.output(analog_spi_select, True)

        try:
            sensor = MAX31855.MAX31855(clk, cs_sensor_1, data_out)
            sensor2 = MAX31855.MAX31855(clk, cs_sensor_2, data_out)

            mcp = Adafruit_MCP3008.MCP3008(clk=clk, cs=cs_analog, miso=data_out, mosi=data_in)

            self.temperature_sensors = [sensor, sensor2]
            self.analog_sensor = mcp
        except:
            print 'Could not reach temperature sensors or analog sensor.'

        # set up I2C GPIO for LEDs
        try:
            self.led_gpio = MCP.MCP23017(0x20, busnum=1)
            for i in range(0,16):
                self.led_gpio.setup(i, GPIO.OUT)
                self.led_gpio.output(i, GPIO.HIGH) #True is HIGH is OFF, False is LOW is ON
                #time.sleep(0.2)
            time.sleep(2)
            for i in range(0,16):
                self.led_gpio.output(i, GPIO.LOW) #True is HIGH is OFF, False is LOW is ON
                #time.sleep(0.1)

        except:
            print 'Could not reach LED control chip'

        # set up I2C GPIO for inputs
        try:
            self.digital_gpio = MCP.MCP23017(0x21, busnum=1)
            for i in range(0,4):
                self.digital_gpio.output(i,GPIO.HIGH)
            for i in range(4,16):
                self.digital_gpio.setup(i, GPIO.IN)
                self.digital_gpio.pullup(i, True)

        except:
            print 'Could not reach digital input control chip'

    def check_program_mode(self):

        self.mode_state
        self.program_mode
        pass
        #print 'Checking Program State'

    def set_relays(self):
        pass
        #print "setting relays"
        #TODO set relays based on input or program state

    def main_control_loop(self):
        temp, temp1, analog_input_values, digital_input_values = self.get_all_inputs()
        DigitalInputs.update_input_values(digital_input_values)
        if self.program_mode != self.previous_program_mode:
            pass
            # handle state changes first

        if self.program_mode == 'Manual':
            #self.lcd.clear()
            # GPIO.output(22, True)
            # i = 0
            # sensor = self.temperature_sensors[i]
            # temp = sensor.readTempC()
            # internal = sensor.readInternalC()
            # print('Thermocouple {2} Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(temp, Utilities.c_to_f(temp), i))
            # print('    Internal {2} Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(internal, Utilities.c_to_f(internal), i))
            # self.lcd.message('T{2}:{0:0.2F}*C/{1:0.2F}*F\n'.format(internal, Utilities.c_to_f(internal), i))
            # GPIO.output(22, False)
            # GPIO.output(27, True)
            # i = 1
            # sensor = self.temperature_sensors[i]
            # temp = sensor.readTempC()
            # internal = sensor.readInternalC()
            # print('Thermocouple {2} Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(temp, Utilities.c_to_f(temp), i))
            # print('    Internal {2} Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(internal, Utilities.c_to_f(internal), i))
            # self.lcd.message('T{2}:{0:0.2F}*C/{1:0.2F}*F\n'.format(internal, Utilities.c_to_f(internal), i))
            # GPIO.output(27, False)
            #
            # analog_spi_select = 17
            # GPIO.output(analog_spi_select, True)
            # values = [0] * 16
            # for sensor in range(8):
            #     # The read_ad function will get the value of the specified channel (0-7).
            #     values[sensor] = self.analog_sensor.read_adc(sensor)
            # print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values))
            # GPIO.output(analog_spi_select, False)
            # for i in range(16):
            #     values[i] = self.digital_gpio.input(i)
            # print('| {0:>4} | {1:>4} | {2:>4} | {3:>4} | {4:>4} | {5:>4} | {6:>4} | {7:>4} |'.format(*values))
            # print('| {8:>4} | {9:>4} | {10:>4} | {11:>4} | {12:>4} | {13:>4} | {14:>4} | {15:>4} |'.format(*values))

            time.sleep(1.0)
            self.set_relays()

        elif self.program_mode == 'Configure':
            self.lcd.clear()

        elif self.program_mode == 'Automatic':
            self.lcd.clear()

            def get_target_slope(initial_temp, target_temp, rampup):
                return (target_temp - initial_temp) / rampup

            duration = 40*60 #TODO set this
            rampup_time = 20*60 #TODO set this
            max_temperature = 82 #TODO set this

            myTimes = []
            myTemps = []
            storedTimes = []
            storedTemps = []
            counter = 0.

            dutyCycle = 0.5
            bufferLength = 10

            initialTemp = self.temperature_sensors[0].readTempC()

            isOn = False

            while counter < duration: #TODO need to refactor such that this doesn't block main control loop
                temp = self.temperature_sensors[0].readTempC()
                internal = self.temperature_sensors[0].readInternalC()

                if temp != float("NAN"):
                    myTimes.append(counter)
                    myTemps.append(temp)
                else:
                    print "error reading temperature. duty cycle may be wrong"

                if (counter % bufferLength) == 0 and dutyCycle > 0 and isOn == False:
                    # TODO turn On Relay
                    isOn = True

                if (counter % bufferLength) / float(bufferLength) >= dutyCycle and isOn == True:
                    # TODO turn Off Relay
                    isOn = False

                counter += 1.
                #TODO Logging/persist to DB
                #with open("temps{0}.txt".format("-s1" if args['sensor'] == '1' else "-s2"), "a") as myFile:
                #    myFile.write('{0:0.3F}\t{1}\n'.format(temp, "1" if isOn else "0"))
                if myTemps.__len__() == bufferLength:
                    timeArray = np.array([myTimes, np.ones(bufferLength)])
                    fitSlope, fitIntercept = np.linalg.lstsq(timeArray.T, myTemps)[0]
                    targetSlope = 0

                    if counter < rampup_time:
                        targetSlope = get_target_slope(initialTemp, max_temperature, rampup_time)
                        targetIntercept = initialTemp
                    else:
                        targetIntercept = max_temperature

                    futureTime = counter + 15
                    yError = (targetSlope * futureTime + targetIntercept) - (fitSlope * futureTime + fitIntercept)
                    currentYError = (targetSlope * counter + targetIntercept) - (fitSlope * counter + fitIntercept)

                    if yError > 0.25:  # increase dutyCycle if we're below target temp
                        dutyCycle = min(dutyCycle + 0.1, 1.0)
                    elif yError < -0.25:
                        dutyCycle = max(dutyCycle - 0.1, 0.0)

                    if currentYError < -1.0:  # if we are currently too hot, take immediate action
                        dutyCycle = 0.0

                    print('---------------------------------------------------')
                    print('Least Squares Values: m={0:0.3F}\tb={1:0.3F}\tyError={2:0.3F}\tNewDutyCycle={3:0.2F}'.format(
                        fitSlope, fitIntercept, yError, dutyCycle))
                    print('---------------------------------------------------')
                    # with open("fit{0}.txt".format("-s1" if args['sensor'] == '1' else "-s2"), "a") as myFile:
                    #     myFile.write('{0:0.3F}\t{1:0.3F}\t{2:0.3F}\t{3:0.2F}\n'.format(fitSlope, fitIntercept, yError, dutyCycle))
                    storedTimes += myTimes
                    storedTemps += myTemps
                    myTemps = []
                    myTimes = []

                print('Thermocouple Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(temp, Utilities.c_to_f(temp)))
                #    print('    Internal Temperature: {0:0.3F}*C / {1:0.3F}*F'.format(internal2, c_to_f(internal2)))
                time.sleep(1)
            # relayControl.turnOff()
            print 'finished run, relay off'

        self.check_program_mode()

    def get_all_inputs(self):
        GPIO.output(22, True)
        i = 0
        sensor = self.temperature_sensors[i]
        temp = sensor.readTempC()
        # internal = sensor.readInternalC()
        GPIO.output(22, False)
        GPIO.output(27, True)
        i = 1
        sensor = self.temperature_sensors[i]
        temp1 = sensor.readTempC()
        # internal1 = sensor.readInternalC()
        GPIO.output(27, False)
        analog_spi_select = 17
        GPIO.output(analog_spi_select, True)
        analog_input_values = [0] * 8
        for sensor in range(8):
            # The read_ad function will get the value of the specified channel (0-7).
            analog_input_values[sensor] = self.analog_sensor.read_adc(sensor)
        GPIO.output(analog_spi_select, False)
        digital_input_values = [0] * 16
        for i in range(16):
            digital_input_values[i] = self.digital_gpio.input(i)

        return temp, temp1, analog_input_values, digital_input_values

class SensorState:
    duty_cycle = 0.5
    initial_temp = 0.
    current_temp = 0.
    rampup_time = 20.
    hold_time = 20.
    max_temp = 180.
    def __init__(self):
        self.duty_cycle= 0.5

config_path = './pywork/.press_config'
print os.getcwd()
if os.path.isfile(config_path):
    Config = ConfigParser.ConfigParser()
    Config.read(config_path)
    try:
        conn_string = Config.get('ConnectionStrings','ConnectionString')
    except:
        print 'Error reading configuration file.  Expected Section "ConnectionStrings" and Expected Key: "ConnectionString"'
        exit()
else:
    print 'Configuration file not found, expected at ' + config_path
    exit()

control = MainControl()
while True:
    DigitalInputs.read_inputs()
    #AnalogInputs.read_inputs()
    #TemperatureSensors.read_inputs()
    control.main_control_loop()
    LedOutputs.set_outputs()

# engine = create_engine(conn_string, isolation_level="READ UNCOMMITTED")
# Base = declarative_base(engine)
#
# ########################################################################
# class Configuration(Base):
#     """"""
#     __tablename__ = 'Configuration'
#     __table_args__ = {'autoload': True}
# class FitLog(Base):
#     """"""
#     __tablename__ = 'FitLog'
#     __table_args__ = {'autoload': True}
# class RawLog(Base):
#     """"""
#     __tablename__ = 'RawLog'
#     __table_args__ = {'autoload': True}
# class RunInformation(Base):
#     """"""
#     __tablename__ = 'RunInformation'
#     __table_args__ = {'autoload': True}
# # ----------------------------------------------------------------------
# def loadSession():
#     """"""
#     metadata = Base.metadata
#     Session = sessionmaker(bind=engine)
#     session = Session()
#     return session
#
# if __name__ == "__main__":
#     session = loadSession()
#     res = session.query(Configuration).all()
#     # config = Configuration(TotalDuration=2200,TopRampUpTime=1000,BottomRampUpTime=1000,
#     #                        TopTemperature=80,BottomTemperature=80)
#     # session.add(config)
#     # session.commit()
#     print res[0].Id


text:
import vamp
import numpy as np
import vamp.frames as fr

plugin_key = "vamp-test-plugin:vamp-test-plugin"
plugin_key_freq = "vamp-test-plugin:vamp-test-plugin-freq"

rate = 44100.0

# Throughout this file we have the assumption that the plugin gets run with a
# blocksize of 1024, and with a step of 1024 for the time-domain version or 512
# for the frequency-domain one. That is certainly expected to be the norm for a
# plugin like this that declares no preference, and the Python Vamp module is
# expected to follow the norm

blocksize = 1024
eps = 1e-6

def input_data(n):
    # start at 1, not 0 so that all elts are non-zero
    return np.arange(n) + 1

def test_collect_runs_at_all():
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(buf, rate, plugin_key, "input-timestamp")
    step, results = rdict["vector"]
    assert results != []

##!!! add test for default output

def test_collect_one_sample_per_step():
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(buf, rate, plugin_key, "input-timestamp")
    step, results = rdict["vector"]
    assert abs(float(step) - (1024.0 / rate)) < eps
    assert len(results) == 10
    for i in range(len(results)):
        # The timestamp should be the frame number of the first frame in the
        # input buffer
        expected = i * blocksize
        actual = results[i]
        assert actual == expected

def test_process_summary_param():
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(buf, rate, plugin_key, "input-summary", { "produce_output": False })
    assert ("vector" in rdict)
    step, results = rdict["vector"]
    assert len(results) == 0
    rdict = vamp.collect(buf, rate, plugin_key, "input-summary", { "produce_output": True })
    assert ("vector" in rdict)
    step, results = rdict["vector"]
    assert len(results) > 0

def test_process_summary_param_kwargs_1():
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(plugin_key = plugin_key, output = "input-summary", parameters = { "produce_output": False }, data = buf, sample_rate = rate)
    assert ("vector" in rdict)
    step, results = rdict["vector"]
    assert len(results) == 0

def test_process_summary_param_kwargs_2():
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(plugin_key = plugin_key, output = "input-summary", data = buf, sample_rate = rate)
    assert ("vector" in rdict)
    step, results = rdict["vector"]
    assert len(results) > 0

def test_process_summary_param_kwargs_3():
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(plugin_key = plugin_key, output = "input-summary", data = buf, sample_rate = rate, process_timestamp_method = vamp.vampyhost.SHIFT_DATA)
    assert ("vector" in rdict)
    step, results = rdict["vector"]
    assert len(results) > 0

def test_process_summary_param_kwargs_fail():
    buf = input_data(blocksize * 10)
    try:
        rdict = vamp.collect(plugin_key = plugin_key, output = "input-summary", data = buf, sample_rate = rate, process_timestamp_method = vamp.vampyhost.SHIFT_DATA, unknown_argument = 1)
    except Exception: # unknown kwarg
        pass

def test_collect_fixed_sample_rate():
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(buf, rate, plugin_key, "curve-fsr")
    step, results = rdict["vector"]
    assert abs(float(step) - 0.4) < eps
    assert len(results) == 10
    for i in range(len(results)):
        assert abs(results[i] - i * 0.1) < eps

def test_collect_fixed_sample_rate_2_vector():
    # This one has discontinuities and overlaps, so it should be
    # returned to us in two forms: as a simple vector, and as an
    # additional tracks shape with one vector for each separate
    # bit. This test covers the simple vector part
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(buf, rate, plugin_key, "curve-fsr-timed")
    step, results = rdict["vector"]
    assert abs(float(step) - 0.4) < eps
    assert len(results) == 10
    for i in range(len(results)):
        assert abs(results[i] - i * 0.1) < eps

def test_collect_fixed_sample_rate_2_tracks():
    # This one has discontinuities and overlaps, so it should be
    # returned to us in two forms: as a simple vector, and as an
    # additional tracks shape with one vector for each separate
    # bit. This test covers the tracks part.
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(buf, rate, plugin_key, "curve-fsr-timed")
    results = rdict["tracks"]
    assert len(results) == 8
    expected_starts = [ 0.0, 0.0, 0.0, 2.0, 2.0, 2.0, 4.0, 4.0 ]
    expected_lengths = [ 1, 1, 2, 1, 1, 2, 1, 1 ]
    expected_values = [ [ 0.0 ], [ 0.1 ], [ 0.2, 0.3 ], [ 0.4 ], [ 0.5 ],
                        [ 0.6, 0.7 ], [ 0.8 ], [ 0.9 ] ]
    for i in range(len(results)):
        track = results[i]
        assert abs(float(track["step"]) - 0.4) < eps
        assert abs(float(track["start"]) - expected_starts[i]) < eps
        assert len(track["values"]) == expected_lengths[i]
        for j in range(expected_lengths[i]):
            assert abs(track["values"][j] - expected_values[i][j]) < eps

def test_collect_variable_sample_rate():
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(buf, rate, plugin_key, "curve-vsr")
    results = rdict["list"]
    assert len(results) == 10
    i = 0
    for r in results:
        assert r["timestamp"] == vamp.vampyhost.RealTime('seconds', i * 0.75)
        assert abs(r["values"][0] - i * 0.1) < eps
        i = i + 1

def test_collect_grid_one_sample_per_step():
    buf = input_data(blocksize * 10)
    rdict = vamp.collect(buf, rate, plugin_key, "grid-oss")
    step, results = rdict["matrix"]
    assert abs(float(step) - (1024.0 / rate)) < eps
    assert len(results) == 10
    for i in range(len(results)):
        expected = np.array([ (j + i + 2.0) / 30.0 for j in range(0, 10) ])
        assert (abs(results[i] - expected) < eps).all()

max_stars_repo_name: gesellkammer/vamphost

max_issues_repo_name: gesellkammer/vamphost

max_forks_repo_name: gesellkammer/vamphost


text:
import pickle
import numpy as np
from graphnas.utils.selector_utils import HallOfFame

class ModelSelector(object):
    """Manage the GNN child model selection process"""

    def __init__(self, args, search_space, action_list, submodel_manager):
        """
        Constructor for child model selection algorithm.
        Build sub-model manager and instantiates the search space.
        ATTENTION: The constructor of the subclasses
        are called BEFORE this one.
        Args:
            args: From command line, picked up by `argparse`.
        """
        self.args = args
        self.search_space = search_space
        self.action_list = action_list
        self.submodel_manager = submodel_manager
        self.hof = HallOfFame(self.args.hof_size)

    def get_model_params(self, candidate_arch):
        lr = self.args.lr \
            if self.args.search_mode == 'macro' \
            else candidate_arch['hyper_param'][0]
        in_drop = self.args.in_drop \
            if self.args.search_mode == 'macro' \
            else candidate_arch['hyper_param'][1]
        weight_decay = self.args.weight_decay \
            if self.args.search_mode == 'macro' \
            else candidate_arch['hyper_param'][2]
        return lr, in_drop, weight_decay

    def build_model(self):
        pass

    def _generate_random_individual(self):
        ind = []
        for action in self.action_list:
            ind.append(np.random.randint(0,
                                         len(self.search_space[action])))
        return ind

    def form_gnn_info(self, gnn):
        if self.args.search_mode == "micro":
            actual_action = {}
            if self.args.predict_hyper:
                actual_action["action"] = gnn[:-4]
                actual_action["hyper_param"] = gnn[-4:]
            else:
                actual_action["action"] = gnn
                actual_action["hyper_param"] = [0.005, 0.8, 5e-5, 128]
            return actual_action
        return gnn

    def dump_hall_of_fame(self):
        path = self.submodel_manager.record_action_info_filename
        path = path.replace('log_file', 'hall_of_fame')
        path = path.replace('.txt', '.pkl')
        print('Dumping hall of fame to pickle file...')
        print('Filename: ', path)
        with open(path, 'wb') as f:
            pickle.dump(self.hof, f)
        print('Dumping hall of fame to pickle file...DONE')

    def select(self):
        self.train()
        self.dump_hall_of_fame()
        print("\n\n====Printing HallOfFame====")
        print(self.hof.get_elements())
        print("\n\n")

    def train(self):
        pass

    def train_shared(self, max_step=50, gnn_list=None):
        pass

    def evaluate(self, gnn):
        pass


text:
import ai2thor.controller
import ai2thor.robot_controller
import random
import time
import numpy as np
from pprint import pprint

fps = ["FloorPlan311"]

runs = [
    {'id': 'unity', 'port': 8200, 'controller': ai2thor.controller.Controller()},
    {'id': 'robot', 'port': 9200, 'controller': ai2thor.robot_controller.Controller()}
    #{'id': 'robot', 'port': 9000, 'controller': ai2thor.robot_controller.Controller()}
]

for run_config in runs:
    port = run_config['port']
    controller = run_config['controller']
    event = controller.start(start_unity=False, host='127.0.0.1', port=port)
    # event = controller.step({'action': 'ChangeQuality', 'quality': 'High'})
    # event = controller.step({"action": "ChangeResolution", "x": 300, "y": 300})

    for fp in fps:
        print(fp)
        for i in range(1):
            event = controller.reset(fp)
            # event = controller.step(dict(action='Initialize', gridSize=0.25, fieldOfView=90, renderObjectImage=True))
            # event = controller.step(dict(action='InitialRandomSpawn', forceVisible=True, maxNumRepeats=10, randomSeed=1))
            # event = controller.step(dict(action='MoveAhead', noise=0.02))
            event = controller.step(dict(action='RotateLeft'))
            print("event for '{}':".format(run_config['id']))
            pprint(event.metadata)
            time.sleep(1)


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

from calibration import Calibration
from calibrate_point_manager import CalibratePointManager
from cell import Cell
from iwscanner import IWScanner
from fractions import Fraction
import decimal
import numpy as np
import sys

# np.mean(array)
# np.std(array)

Kd = 4
def euclidean_distance(cj, sk):
    # assert(len(cj) == len(sk) and type(cj) == type(sk) == list)
    return np.sqrt(reduce(lambda x, y: x + y,  \
            map(lambda x, y:
        (decimal.Decimal(x[0]) - decimal.Decimal(y[0])) ** decimal.Decimal(2)
        , cj, sk)))

def improved_euclidean_distance(cj, sk):
    #dev_k = decimal.Decimal(sk[2])
    #dev_ik = decimal.Decimal(cj[2])
    #sum_dev = dev_k + dev_ik
    #return np.sqrt(reduce(lambda a, b: a + b, \
    #        map(lambda a, b: ((np.abs(decimal.Decimal(a[1]) - decimal.Decimal(b[1])) \
    #            + sum_dev) ** decimal.Decimal(2)), cj, sk)))
    return (reduce(lambda a, b: a + b, \
            map(lambda a, b: ((np.abs(a[1] - b[1]) \
                + a[2] + b[2]) ** decimal.Decimal(2)), cj, sk))).sqrt()

def gaussian_dist(cj, sk):
    x = map(lambda a: a[1], sk)
    sigma = map(lambda a: (a[2]) , cj)
    if 0 in sigma:
        return 0
    mu = map(lambda a: a[1], cj)
#     if not reduce(lambda x, y: x and y,
            #map(lambda x: x != 0, sigma),
            #True):
    print "sigma: ", sigma
    print "x: ", x
    P = map(lambda a, b, c: \
            decimal.Decimal(np.e) ** -((a - c) ** 2 \
                / decimal.Decimal(2* (b ** 2))) \
                / decimal.Decimal(b * decimal.Decimal(2.0 * np.pi).sqrt()) \
                , x, sigma, mu)
    return decimal.Decimal(reduce(lambda a, b: a * b, P))

decimal.getcontext().prec = 128
# gmpy2.get_context().precision= 256

def calculate(s):
    cp = CalibratePointManager()
    cpoints = cp.get_cpoints()
    xy = cp.xy
    d = []
    p = []
    # sort_func = lambda x: x.bssid
    # sorted(cpoints, key=sort_func)
    # sorted(s, key=sort_func)
    for cpoint in cpoints:
        si = s

        # place Pavg instead of -80
        # cpoint = filter(lambda x: x.rssi > np.mean(global_avg), cpoint)
        si = filter(lambda x: x.rssi > np.mean(global_avg), si)
        bssid_list = set(map(lambda x: x.bssid, cpoint))
        bssid_list = bssid_list.intersection(set(map(lambda x: x.bssid, si)))

        c = filter(lambda x: x.bssid in bssid_list, cpoint)
        si = filter(lambda x: x.bssid in bssid_list, si)
        sort_func = lambda x: x.bssid
        c = sorted(c, key=sort_func)
        si = sorted(si, key=sort_func)
        c = map(lambda x: (x.bssid, decimal.Decimal(x.rssi), decimal.Decimal(x.std)), c)
        si = map(lambda x: (x.bssid, decimal.Decimal(x.rssi), decimal.Decimal(x.std)), si)
        assert(len(si) == len(c))
        # print bssid_list
        if len(bssid_list) != 0:
            d.append((improved_euclidean_distance(c, si), len(d)))
            p.append((gaussian_dist(c, si), len(p)))
        else:
            d.append((-1, len(d)))
            p.append((-1, len(p)))
    d = filter(lambda x: x[0] != -1, sorted(d))[:Kd]
    p = filter(lambda x: x[0] != 0 and x[0] != -1, sorted(p))[-Kd:]
    # เอา w = d -> ไปเข้าสูตร weight ได้เลย (x1, y1)
    # เอา w = p -> ไปเข้าสูตรเหมือน d ได้ออกมาเป็น (x2, y2)
    # def get_xy(d, p):
    def get_xy(d, p):
        ex = gx  = decimal.Decimal(0.0)
        ey = gy = decimal.Decimal(0.0)
        sum_d = decimal.Decimal(0.0)
        sum_p = decimal.Decimal(0.0)
        for i in range(len(d)):
            if d[i][0] == -1: continue
            sum_d += decimal.Decimal(1.0)/decimal.Decimal(d[i][0])
            ex += ((xy[d[i][1]][0]) / decimal.Decimal(d[i][0]))
            ey += ((xy[d[i][1]][1]) / decimal.Decimal(d[i][0]))

        for i in range(len(p)):
            if p[i][0] == -1: continue

            w = decimal.Decimal(np.log2(float(p[i][0])))
            sum_p += (w)
            gx += (xy[i][0]) * w
            gy += (xy[i][1]) * w
        # print sum_d
        if sum_d == 0: ox, oy = 0, 0

        ex = ex / sum_d
        ey = ey / sum_d

        gx = gx / sum_p # <<<< here
        gy = gy / sum_p

        return ex, ey, gx, gy

    x1, y1, x2, y2 = get_xy(d, p)
    print "(x1,y1): (%d, %d)" % (x1,y1)
    print "(x2,y2): (%d, %d)" % (x2,y2)

    D1 = np.var(map(lambda x: (x[0]),  d))
    print "p: ", p
    D2 = np.var(map(lambda x: (x[0]), p))
    sum_D = D1 + D2

    print "D1: {} D2: {}".format(D1, D2)
    x = x1 * decimal.Decimal(D1 / sum_D) + x2 * decimal.Decimal(D2 / sum_D)
    y = y1 * decimal.Decimal(D1 / sum_D) + y2 * decimal.Decimal(D2 / sum_D)

    return x , y

# x, y = raw_input("Current position (x, y): ").replace(" ", "").split(",")

# obs[i].bssid, obs[i].rssi (avg), obs[i].std
obs = list()
cells_hash = { }
global_avg = list()

for i in range(10):
    for result in IWScanner().do_scan():
        if result.bssid not in cells_hash:
            cells_hash[result.bssid] = [result]
        else:
            cells_hash[result.bssid].append(result)

for bssid, arr in cells_hash.iteritems():
    rssi_arr = list()
    for item in arr:
        rssi_arr.append(item.rssi)
    cell = Cell(bssid)
    cell.rssi = np.mean(rssi_arr)
    cell.std = np.std(rssi_arr)
    obs.append(cell)

    global_avg.append(cell.rssi)

print "Your position is about: (%d, %d)" % (calculate(obs))


text:
import json
import time
import pyotp
import pprint
import config
import numpy as np
import pandas as pd
import robin_stocks as rs

from decimal import *

from base import BaseClass

class EqualWeight(BaseClass):

    # returns decimal % of equity to be invested in each symbol
    def target_equal_weights(self):

        target_equal_weight = {}
        symbols_ = self.symbols_list()

        for symbol in symbols_:
            equal_weight = Decimal(1 / len(symbols_))
            target_equal_weight[symbol] = equal_weight

        return target_equal_weight

    # returns the equity $ to be invested in each symbol - depending on the weight % allocated to it - rounded to nearest penny
    def target_rebalance_equity_amt(self):

        rebalance_equity = self.portfolio_value_after_cash_reserved()
        symbol_target_weights = self.target_equal_weights()

        target_equity_allocation = {}

        for symbol, weight in symbol_target_weights.items():
            allocated_equity = weight * rebalance_equity
            target_equity_allocation[symbol] = Decimal(allocated_equity)

        return target_equity_allocation

    # returns for each symbol the $ amount required to buy or sell to reach the target decimal % weight allocated to each symbol
    def equity_allocation_difference(self):

        rebalance_target_equity_amts = self.target_rebalance_equity_amt()
        current_equity_amts = self.equity_of_shares_per_symbol()

        equity_allocation_difference = {}

        for symbol, curr_equity_allocation in current_equity_amts.items():
            for symbol_, target_equity_allocation in rebalance_target_equity_amts.items():
                if symbol == symbol_:
                    # if this is a positive, need to buy $ of share, if negative, sell that amount of shares
                    equity_allocation_difference[symbol] = (target_equity_allocation - curr_equity_allocation)

        return equity_allocation_difference

    # returns for each symbol the qty amount required to buy or sell to reach the target decimal % weight allocated to each symbol
    def quantity_allocation_difference(self):

        equity_allocation_difference = self.equity_allocation_difference()
        symbol_price_quote = self.price_quote()

        quantity_allocation_difference = {}

        for symbol, allocation_difference in equity_allocation_difference.items():
            for symbol_, price_quote in symbol_price_quote.items():
                if symbol == symbol_:
                    # if this is a positive, need to buy $ of share, if negative, sell that amount of shares
                    quantity_allocation_difference[symbol] = round(Decimal(allocation_difference / price_quote), 6)

        return quantity_allocation_difference

    # rebalance handler
    def rebalance(self, min_drift_amt=1.5):

        if self.is_market_open():

            print('Market is Open!')

            if min_drift_amt < 1.5:
                print(f'{min_drift_amt} is below the Min Threshold $ Amount Per Trade of $1.50')
                print('Min $ Amount Per Trade Set to Mandatory Minimum Default of $1.50')
                min_drift_amt = 1.5

            print('Rebalance Initiated - Checking User and Portfolio Eligibility for Fractional Trading...')
            if self.user_eligible_for_fractionals() and self.symbols_eligible_for_fractionals():

                print('User and Portfolio Approved – Starting Rebalance...')

                print('Calculating Rebalance Purchase and Sale Quantities For Each Symbol...')
                quantity_allocation = self.quantity_allocation_difference()

                print('Sorting Symbols for Rebalance Process...')
                # returns an array of tuples - used so that you sell first - keeps investable cash reserves ready to deploy for purchasing
                sorted_sell_to_buy = sorted(quantity_allocation.items(), key=lambda x: x[1])

                print('Starting Sales and Purchases to Achieve Target Weights...')
                for symbol, quantity_difference in sorted_sell_to_buy:

                    if quantity_difference >= 0:
                        if self.min_portfolio_drift(symbol, quantity_difference, min_drift_amt):
                            self.place_buy_order(symbol, quantity_difference, 1)
                    elif quantity_difference < 0:
                        if self.min_portfolio_drift(symbol, -quantity_difference, min_drift_amt):
                            self.place_sell_order(symbol, -quantity_difference, 1)
                    else:
                        return

                print('Rebalance Completed!')

            else:
                if not self.user_eligible_for_fractionals():
                    print('Sorry Your Account is Not Eligible For Fractional Trading')
                else:
                    print('Sorry a Symbol(s) in your Portfolio Are Not Eligible For Fractionals')

        else:
            print('Market is Closed or Within 30 Mins of Closing - Try During Next Open Market Hours')

max_stars_repo_name: alec-isaac/robinhood-rebalance

max_issues_repo_name: alec-isaac/robinhood-rebalance

max_forks_repo_name: alec-isaac/robinhood-rebalance


text:
import numpy as np
import pandas as pd
import cv2
from numba import jit

def load_motion_gen(path, axes, sensored_axes_tag, target_sampling_rate, indices, timediffs):
    df = pd.read_csv(path, encoding="ISO-8859-1")
    unsensored_axes = []#['surge', 'sway']
    for i in indices[1:]:
        ret = []
        for ax in axes:
            if ax in sensored_axes_tag.keys() and ax not in unsensored_axes:
                ret.append(df[sensored_axes_tag[ax]][i])
            else:
                ret.append(0)
        yield np.array(ret)

def load_visual_gen(path, target_sampling_rate, extension, indices, timediffs):
    src = _visual_src_maker(path, indices, extension)
    prev = next(src)
    for t in timediffs[1:]:
        cur = next(src)
        flow = cv2.calcOpticalFlowFarneback(prev, cur, None, 0.5, 4, 15, 3, 5, 1.2, 0)
        polars = np.asarray(cv2.cartToPolar(flow[...,0], flow[...,1], None, None, True))
        polars = polars.reshape(2, polars.shape[1] * polars.shape[2]).T
        # polars = polars.reshape(2, polars.shape[1] * polars.shape[2]).T / t \
            # / target_sampling_rate
        prev = cur
        yield polars

def _visual_src_maker(path, indices, extension):
    if extension == '.mp4':
        cap = cv2.VideoCapture(path)
        max_frame = cap.get(cv2.CAP_PROP_FRAME_COUNT)
        for i in range(int(max_frame)):
            if i % 20 == 0:
                yield cv2.cvtColor(cap.read()[1], cv2.COLOR_BGR2GRAY)
            else:
                cap.read()
        cap.release()

    elif extension == '.png':
        for i in indices:
            yield cv2.cvtColor(cv2.imread(path + "{:0>4d}.png".format(i)),
                               cv2.COLOR_BGR2GRAY)

def classification_motion(motion_vector, bins = None):
    return _classification_motion_helper(motion_vector)

def classification_visual(polars):
    return np.array(_classification_visual_helper(polars), dtype=int)

@jit(nopython = True)
def _classification_motion_helper(motion_vector):
    modifier = 1
    ret = 0
    for axis_class in motion_vector:
        if axis_class == 0:     # low motion
            ret += 2 * modifier
        elif axis_class == 1:   # medium positive motion
            ret += 3 * modifier
        elif axis_class == -1:   # medium negative motion
            ret += 1 * modifier
        elif axis_class == 2:   # high positive motion
            ret += 4 * modifier
        else:                   # high negative motion
            ret += -2
        modifier *= 5
    return np.array(ret)

@jit(nopython = True)
def _classification_visual_helper(polars):
    ret = np.zeros(polars.shape[0])
    for i in range(len(polars)):
        mag = polars[i,0]
        deg = polars[i,1]
        if deg < 195:
            if deg < 105:
                if deg < 45:
                    if deg > 15:
                        ret[i] = 1
                else:
                    if deg < 75:
                        ret[i] = 2
                    else:
                        ret[i] = 3
            else:
                if deg < 165:
                    if deg < 135:
                        ret[i] = 4
                    else:
                        ret[i] = 5
                else:
                    ret[i] = 6
        else:
            if deg < 315:
                if deg < 255:
                    if deg < 225:
                        ret[i] = 7
                    else:
                        ret[i] = 8
                else:
                    if deg < 285:
                        ret[i] = 9
                    else:
                        ret[i] = 10
            else:
                if deg < 345:
                    ret[i] = 11
        if mag < 20:
            if mag > 6:
                ret[i] += 12
        else:
            ret[i] += 24
    return ret

# def _save_as_table(self, data, tag):
#     if tag not in self._save_options.keys():
#         raise Exception('unsupported tag')
#     directory = self._save_dir + self._save_options['pro'] + self._save_options['tbl'] + \
#                 self._save_options[tag] + self._scenario + self._extension['csv']
#     df = pd.DataFrame(data)
#     df.index = self._timestamp[1:]
#     df.index.name = 'time'
#     df.columns = [self._save_options[tag]]
#     df.to_csv(directory)

# def _save_as_graph(self, data, tag, xlabel, ylabel, ylim):
#     from matplotlib import pyplot as plt
#     from matplotlib.collections import LineCollection
#     from matplotlib.colors import ListedColormap, BoundaryNorm

#     if tag not in self._save_options.keys():
#         raise Exception('unsupported tag')
#     directory = self._save_dir + self._save_options['pro'] + self._save_options['grp'] + \
#                 self._save_options[tag] + self._scenario + self._extension['png']

#     if not ylim:
#         ylim = [min(data) - 0.1 * np.abs(min(data)),
#                 max(data) + 0.1 * np.abs(max(data))]

#     plt.clf()
#     x = []
#     y = []
#     for i in range(len(data)-1):
#         x.append(self._timestamp[i])
#         y.append(data[i])
#         if data[i] * data[i + 1] <= 0:
#             x.append((self._timestamp[i] + self._timestamp[i+1]) / 2)
#             if data[i] > 0:
#                 y.append(-0.0000000001)
#             else:
#                 y.append(0.000000001)
#     i += 1
#     x.append(self._timestamp[i])
#     y.append(data[i])

#     points = np.array([x, y]).T.reshape(-1,1,2)
#     segments = np.concatenate([points[:-1], points[1:]], axis=1)

#     fig, axes = plt.subplots()
#     axes.set_xlabel(xlabel, fontsize = 18)
#     axes.set_ylabel(ylabel, fontsize = 18)
#     axes.set_xlim(x[0], x[-1])
#     axes.set_ylim(ylim)
#     cmap = ListedColormap(['C1', 'C0'])
#     norm = BoundaryNorm([-10000000, 0, 10000000], cmap.N)

#     lc = LineCollection(segments, cmap=cmap, norm=norm)
#     lc.set_array(np.array([1 if t > 0 else -1 for t in y]))
#     axes.add_collection(lc)

#     plt.savefig(directory, dpi = 300, bbox_inches = "tight")
#     plt.close()
# def _sampling_motion(self, motion_data):
#     for mv in motion_data.reshape((int) (motion_data.size / len(self._axis))
#                                   , len(self._axis)):
#         mv[3] = 2 # surge
#         mv[5] = 2 # sway
#         yield mv
# def _sampling_video(self, sampled_indices, load_dir):
#     cap = cv2.VideoCapture(load_dir)
#     prev = cv2.cvtColor(cap.read()[1][self._roi], cv2.COLOR_BGR2GRAY)
#     frame_max = cap.get(cv2.CAP_PROP_FRAME_COUNT)
#     frame_num = 1
#     while frame_num <= frame_max:
#         if frame_num in sampled_indices:
#             cur = cv2.cvtColor(cap.read()[1][self._roi], cv2.COLOR_BGR2GRAY)
#             flow = cv2.calcOpticalFlowFarneback(prev, cur, None, 0.5, 4, 15, 3, 5, 1.2, 0)
#             polars = np.asarray(cv2.cartToPolar(flow[...,0], flow[...,1], None, None, True))
#             yield polars.reshape(2, polars.shape[1] * polars.shape[2]).T
#             prev = cur
#         else:
#             cap.read()
#         frame_num += 1
#     cap.release()

max_stars_repo_name: nearj/mpvr-motionfiltering

max_issues_repo_name: nearj/mpvr-motionfiltering

max_forks_repo_name: nearj/mpvr-motionfiltering

reason: import numpy,from numba


text:
from cf_tools.core import PreferenceVector, matrix
from cf_tools.recommender import ItemItemCFRecommender
import numpy as np
import random

NUM_USERS = 1000
NUM_ITEMS = 500
POSSIBLE_RATINGS = range(1, 6)

def random_rating():
    # withold some ratings randomly
    return random.choice(POSSIBLE_RATINGS) * random.randint(0, 1)

def build_vectors(nu=NUM_USERS, ni=NUM_ITEMS):
    for u in xrange(nu):
        p = PreferenceVector(u)
        for i in xrange(ni):
            r = random_rating()
            if r: p.add(i, r)
        yield p

def test_run():
    vectors = list(build_vectors())
    recommender = ItemItemCFRecommender(matrix.build_user_item_matrix(vectors))
    r1 = recommender.recommendations_for_user(17, n=5)
    r2 = recommender.recommendations_for_pref_vector(vectors[17], n=5)
    assert len(r1) == 5
    np.testing.assert_array_equal(r1, r2)


text:
# -*- coding: utf-8 -*-
"""
Created on Wed Aug 26 10:51:06 2020

@author: kahdi
"""

# =============================================================================
# The following code will swipe the effect of noise level on SINDy
# =============================================================================

#%% Import packages
import numpy as np
from scipy.integrate import odeint
import matplotlib.pyplot as plt
from utils_NSS_SINDy import *
import time
from datetime import datetime
import os

#%% SoftStart?
softstart=0

#%% Define the parameters to swipe

# Noise level to use
NoiseLevelArray=np.linspace(2,10,17)
NoiseNum=len(NoiseLevelArray)

# Sparsity parameters to use
lamArray=np.linspace(0.01,0.9,100)
lamNum=len(lamArray)

# Set a pin to generate new noise every run
pinArray=np.linspace(0,4,5)
pinNum=len(pinArray)

#%% Simulate
# Define the random seed for the noise generation
np.random.seed(0)

# Define the parameters, the first value determines the number of states while the second one defines the forcing
p0=np.array([6,8])

# Define the initial conditions
x0=p0[1]*np.ones(p0[0])
x0[0]=1

x0_test=p0[1]*np.ones(p0[0])
x0_test[0]=2

# Define the time points
T=25.0
dt=0.01

t=np.linspace(0.0,T,int(T/dt))

# Now simulate the system
x=odeint(Lorenz96,x0,t,args=(p0,),rtol = 1e-12, atol = 1e-12)
dx=np.transpose(Lorenz96(np.transpose(x), 0, p0))

x_test=odeint(Lorenz96,x0_test,t,args=(p0,),rtol = 1e-12, atol = 1e-12)
dx_test=np.transpose(Lorenz96(np.transpose(x_test), 0, p0))

libOrder=3
Theta_test=Lib(x_test,libOrder)

# Get the data size info
stateVar,dataLen=np.transpose(x).shape

# Define the true parameters
Theta_base=Lib(x,libOrder)
Xi_base=SINDy(Theta_base,dx,0.2,20,0,0)
Xi_base[Xi_base!=0]=-1
Xi_base[0,:]=8
Xi_base[9,1]=1
Xi_base[17,0]=1
Xi_base[15,2]=1
Xi_base[20,3]=1
Xi_base[24,4]=1
Xi_base[11,5]=1

# Define the parameters for the SINDy
N_iter=15
disp=0
NormalizeLib=0

#%%
SuccessOrNot=np.zeros((NoiseNum,pinNum))
ParameterError=np.zeros((NoiseNum,pinNum))
Xi_Matrix=np.zeros((NoiseNum,pinNum,np.size(Xi_base,0),np.size(Xi_base,1)))

for i in range(NoiseNum):
    print("Using noise level ",NoiseLevelArray[i],"\n")
    # Define the Noise Mag
    NoiseMag=[np.std(x[:,ij])*NoiseLevelArray[i]*0.01 for ij in range(stateVar)]

    for j in range(pinNum):
        print("\t Using using random seed ",pinArray[j],"\n")
        # Define noise seed
        np.random.seed(int(pinArray[j]))

        # Define noise
        Noise=np.hstack([NoiseMag[ij]*np.random.randn(dataLen,1) for ij in range(stateVar)])

        xn=x+Noise

        # Process noise if needed
        if softstart==1:
            # Soft Start
            NoiseEs,xes=approximate_noise(np.transpose(xn), 20)
            NoiseEs=np.transpose(NoiseEs)
            xes=np.transpose(xes)
        else:
            # Hard Start
            xes=xn

        # Prepare the derivative and library
        dxes=CalDerivative(xes,dt,1)
        Theta=Lib(xes,libOrder)

        # Set dummy variables to store the variable
        Xi=[]
        Success_dum=np.zeros((lamNum,1))
        Evec_dum=np.zeros((lamNum,1))

        # Swipe the sparsity parameters
        for k in range(lamNum):
            print("\t\t Setting lambda as ",lamArray[k],"\n")
            Xi0=SINDy(Theta,dxes,lamArray[k],N_iter,disp,NormalizeLib)
            Xi.append(Xi0)

            # Calculate the testing error
            Evec_dum[k]=np.linalg.norm(dx_test-Theta_test@Xi0,'fro')**2/np.linalg.norm(dx_test,'fro')**2

            # Store whether it successed ot not
            if np.linalg.norm((Xi0!=0).astype(int)-(Xi_base!=0).astype(int))==0:
                Success_dum[k]=1

        if sum(Success_dum)>0:
            SuccessOrNot[i,j]=1
            Xi0=Xi[np.argmax(Success_dum)]
            Xi_Matrix[i,j,:,:]=Xi0
            ParameterError[i,j]=np.linalg.norm(Xi_base-Xi0)/np.linalg.norm(Xi_base)
        else:
            Xi0=Xi[np.argmin(Evec_dum)]
            Xi_Matrix[i,j,:,:]=Xi0
            ParameterError[i,j]=np.linalg.norm(Xi_base-Xi0)/np.linalg.norm(Xi_base)

max_stars_repo_name: MoSubaiei/modified-SINDy

max_issues_repo_name: MoSubaiei/modified-SINDy

max_forks_repo_name: MoSubaiei/modified-SINDy

reason: import numpy,from scipy


text:
from __future__ import print_function
import tensorflow as tf
import os
import numpy as np
import random as r
import json
import skimage.io as io
import skimage.transform as trans
from sklearn.model_selection import train_test_split
import cv2
# import logging
# logger = tf.get_logger()
# logger.setLevel(logging.ERROR)

rocks_limit = 0

def normalizeImage(imgB, normalization):
    # img=(np.array(imgB, 'float')-128)/128
    # img = (np.array(imgB, 'float')) / 255.0
    if normalization == 'jbdm_v0':
        img = (np.array(imgB, 'float') / 127.5) - 1.0
    elif normalization == 'vgg16':
        img = tf.keras.applications.vgg16.preprocess_input(imgB)  # model 3*
    elif normalization == 'vgg19':
        img = tf.keras.applications.vgg19.preprocess_input(imgB)  # model 3*
    elif normalization == 'resnet_v2':
        img = tf.keras.applications.resnet_v2.preprocess_input(imgB)  # model 3*
    elif normalization == 'inception_v3':
        img = tf.keras.applications.inception_v3.preprocess_input(imgB)
    elif normalization == 'inception_resnet_v2':
        img = tf.keras.applications.inception_resnet_v2.preprocess_input(imgB)  # model 3*
    elif normalization == 'mobilenet_v2':
        img = tf.keras.applications.mobilenet_v2.preprocess_input(imgB)  # model 2*
    elif normalization == 'mobilenet_v3':
        img = tf.keras.applications.mobilenet_v3.preprocess_input(imgB)  # model 2.5*
    elif normalization == 'densenet':
        img = tf.keras.applications.densenet.preprocess_input(imgB)  # model 4*
    elif normalization == 'nasnet':
        img = tf.keras.applications.nasnet.preprocess_input(imgB)  # model 5*
    elif normalization == 'efficientnet':
        img = tf.keras.applications.efficientnet.preprocess_input(imgB)  # model 6*
    return img

def prepare_dataset(datasetPath, rocks_db, classes_structure, classLevel):
    with open(rocks_db) as data_file:
        rocks = json.load(data_file)

    if rocks_limit > 0:
        del rocks[rocks_limit:]

    usableSet = []
    for pedra in rocks:
        # print("Checking stone " + str(pedra["ID"]))
        # img = io.imread(os.path.join(datasetPath, pedra['Diretorio Img']))

        if (pedra["Largura da Imagem"] == 780):
            if (pedra["Altura da Imagem"] == 480):
                # if (img.shape[0]==480):
                #     if (img.shape[1]==780):
                usableSet.append(pedra)

    # rocks=usableSet
    # totalN=len(rocks)
    # k=int(totalN*0.8)
    # r.seed(1)
    # trainSet = r.sample(rocks, k)
    # testSet = []
    # for pedra in rocks:
    #     if pedra not in trainSet:
    #         testSet.append(pedra)
    # return trainSet, testSet

    rocks = usableSet
    classes_list_L0 = classes_structure["classes_list_L0"]
    classes_list_L1 = classes_structure["classes_list_L1"]
    classes_list_L2 = classes_structure["classes_list_L2"]
    classes_L0_dict = dict(zip(classes_list_L0, list(range(0, len(classes_list_L0)))))
    classes_L1_dict = dict(zip(classes_list_L1, list(range(0, len(classes_list_L1)))))
    classes_L2_dict = dict(zip(classes_list_L2, list(range(0, len(classes_list_L2)))))

    classes_hierarchy_L0L1 = classes_structure["classes_hierarchy_L0L1"]
    classes_hierarchy_L1L2 = classes_structure["classes_hierarchy_L1L2"]

    datasetX = np.ndarray(len(usableSet))
    datasetY = np.ndarray(len(usableSet), dtype=int)

    i = 0
    for pedra in rocks:
        datasetX[i] = pedra["ID"]
        class_Name = pedra['Classe']
        class_ID = classes_L0_dict[class_Name]
        if classLevel > 0:
            superClassName = classes_hierarchy_L0L1[class_Name]
            superClassID = classes_L1_dict[superClassName]
            class_Name = superClassName
            class_ID = superClassID
            if classLevel > 1:
                superClassName = classes_hierarchy_L1L2[class_Name]
                superClassID = classes_L2_dict[superClassName]
                class_Name = superClassName
                class_ID = superClassID
        datasetY[i] = class_ID
        i = i + 1

    y_hist = np.zeros(len(classes_L0_dict), dtype=np.uint16)
    for i in range(len(datasetY)):
        y_hist[datasetY[i]] = y_hist[datasetY[i]] + 1
    # print(y_hist)

    filhos_que_so_tem_um_irmao=[]
    filhos_que_so_tem_um_irmao_class = []
    for i in range(datasetY.shape[0]):
        c = datasetY[i]
        if y_hist[datasetY[i]] == 2:
            filhos_que_so_tem_um_irmao.append(i)
            filhos_que_so_tem_um_irmao_class.append(c)
    if len(filhos_que_so_tem_um_irmao) > 0:
        newDatasetX = np.ndarray(datasetX.shape[0] + len(filhos_que_so_tem_um_irmao))
        newDatasetX[0:datasetX.shape[0]] = datasetX[:]
        i = datasetX.shape[0]
        for c in filhos_que_so_tem_um_irmao:
            newDatasetX[i] = c
            i = i + 1

        newDatasetY = np.ndarray(datasetY.shape[0] + len(filhos_que_so_tem_um_irmao_class), dtype=int)
        newDatasetY[0:datasetY.shape[0]] = datasetY[:]
        i = datasetY.shape[0]
        for c in filhos_que_so_tem_um_irmao_class:
            newDatasetY[i] = c
            i = i + 1

        datasetX = newDatasetX
        datasetY = newDatasetY

    y_hist = np.zeros(len(classes_L0_dict), dtype=np.uint16)
    for i in range(len(datasetY)):
        y_hist[datasetY[i]] = y_hist[datasetY[i]] + 1
    # print(y_hist)

    # triplicate examples that are the only samples for their class, so that we can do stratified split
    filhos_unicos = []
    filhos_unicos_class = []
    for i in range(datasetY.shape[0]):
        c = datasetY[i]
        if y_hist[datasetY[i]] == 1:
            filhos_unicos.append(i)
            filhos_unicos.append(i)
            filhos_unicos_class.append(c)
            filhos_unicos_class.append(c)

    if len(filhos_unicos) > 0:
        newDatasetX = np.ndarray(datasetX.shape[0] + len(filhos_unicos))
        newDatasetX[0:datasetX.shape[0]] = datasetX[:]
        i = datasetX.shape[0]
        for c in filhos_unicos:
            newDatasetX[i] = c
            i = i + 1

        newDatasetY = np.ndarray(datasetY.shape[0] + len(filhos_unicos_class), dtype=int)
        newDatasetY[0:datasetY.shape[0]] = datasetY[:]
        i = datasetY.shape[0]
        for c in filhos_unicos_class:
            newDatasetY[i] = c
            i = i + 1

        datasetX = newDatasetX
        datasetY = newDatasetY

    y_hist = np.zeros(len(classes_L0_dict), dtype=np.uint16)
    for i in range(len(datasetY)):
        y_hist[datasetY[i]] = y_hist[datasetY[i]] + 1
    # print(y_hist)

    '''Faz a separação do training set(75%) do test set(25%)'''
    X_train, X_test, y_train, y_test = train_test_split(
        datasetX,
        datasetY,
        test_size=0.25,
        random_state=1,
        stratify=datasetY,
        shuffle=True)

    y_test_hist = np.zeros(len(classes_L0_dict), dtype=np.uint16)
    for i in range(len(y_test)):
        y_test_hist[y_test[i]] = y_test_hist[y_test[i]] + 1
    # print(y_test_hist)

    '''Adiciona a variavel X_train à lista trainSet'''
    trainSet = []
    for i in range(0, len(X_train)):
        ID = X_train[i]
        for pedra in rocks:
            if (pedra['ID'] == ID):
                trainSet.append(pedra)
                break

    '''Adiciona a variavel X_test à lista testSet'''
    testSet = []
    for i in range(0, len(X_test)):
        ID = X_test[i]
        for pedra in rocks:
            if (pedra['ID'] == ID):
                testSet.append(pedra)
                break
    return trainSet, testSet

def augmentImages(aug_dict, img, input_size):
    if 'width_shift_range' in aug_dict:
        input_cropx = r.sample(aug_dict['width_shift_range'], 1)[0]
    else:
        input_cropx = 0
    if 'height_shift_range' in aug_dict:
        input_cropy = r.sample(aug_dict['height_shift_range'], 1)[0]
    else:
        input_cropy = 0
    if 'rotation_range' in aug_dict:
        rotation = r.sample(aug_dict['rotation_range'], 1)[0]
    else:
        rotation = 0
    if 'horizontal_flip' in aug_dict and aug_dict['horizontal_flip']:
        do_horizontal_flip = r.sample([False, True], 1)[0]
    else:
        do_horizontal_flip = False
    if 'vertical_flip' in aug_dict and aug_dict['vertical_flip']:
        do_vertical_flip = r.sample([False, True], 1)[0]
    else:
        do_vertical_flip = False

    img = img[input_cropy:input_cropy + input_size[0], input_cropx:input_cropx + input_size[1]]
    if rotation:
        img = trans.rotate(img, rotation)
    if do_horizontal_flip:
        img = img[:, ::-1]
    if do_vertical_flip:
        img = img[::-1, :]

    return img

def do_center_crop(img, input_size, inicial_size):
    input_cropx = int((inicial_size[1] - input_size[1]) / 2)
    input_cropy = int((160 + 188) / 2)

    img = img[input_cropy:input_cropy + input_size[0], input_cropx:input_cropx + input_size[1]]

    return img

def trainGeneratorStones(classes_structure, classLevel, batch_size, datasetPath, trainSet, aug_dict,
                         crop_size=(128, 128, 3), net_input_size=(128, 128, 3), normalization='jbdm_v0'):
    # i = 0
    classes_list_L0 = classes_structure["classes_list_L0"]
    classes_list_L1 = classes_structure["classes_list_L1"]
    classes_list_L2 = classes_structure["classes_list_L2"]
    classes_L0_dict = dict(zip(classes_list_L0, list(range(0, len(classes_list_L0)))))
    classes_L1_dict = dict(zip(classes_list_L1, list(range(0, len(classes_list_L1)))))
    classes_L2_dict = dict(zip(classes_list_L2, list(range(0, len(classes_list_L2)))))

    classes_hierarchy_L0L1 = classes_structure["classes_hierarchy_L0L1"]
    classes_hierarchy_L1L2 = classes_structure["classes_hierarchy_L1L2"]

    if classLevel == 0:
        class_count = len(classes_list_L0)
    elif classLevel == 1:
        class_count = len(classes_list_L1)
    else:
        class_count = len(classes_list_L2)

    if batch_size > 1:
        while 1:
            iRock = 0
            nBatches = int(np.ceil(len(trainSet) / batch_size))
            for batchID in range(nBatches):
                batch_images = np.zeros(((batch_size,) + net_input_size))
                batch_classes = np.zeros((batch_size, class_count))

                iRockInBatch = 0
                while iRockInBatch < batch_size:
                    if iRock < len(trainSet):
                        rock = trainSet[iRock]
                        img = io.imread(os.path.join(datasetPath, rock['Diretorio Img']))
                        img = normalizeImage(img, normalization)
                        class_Name = rock['Classe']
                        class_ID = classes_L0_dict[class_Name]
                        if classLevel > 0:
                            superClassName = classes_hierarchy_L0L1[class_Name]
                            superClassID = classes_L1_dict[superClassName]
                            class_Name = superClassName
                            class_ID = superClassID
                            if classLevel > 1:
                                superClassName = classes_hierarchy_L1L2[class_Name]
                                superClassID = classes_L2_dict[superClassName]
                                class_Name = superClassName
                                class_ID = superClassID
                        batch_classes[iRockInBatch][class_ID] = 1
                        img = augmentImages(aug_dict, img, crop_size)
                        if crop_size != net_input_size:
                            img = cv2.resize(img, dsize=(net_input_size[0], net_input_size[1]),
                                             interpolation=cv2.INTER_CUBIC)

                        batch_images[iRockInBatch, :, :, :] = img

                        iRock += 1
                        iRockInBatch += 1
                    else:
                        batch_images = batch_images[0:iRockInBatch, :, :, :]
                        batch_classes = batch_classes[0:iRockInBatch]
                        break
                yield batch_images, batch_classes
    else:
        while 1:
            for rock in trainSet:
                img = io.imread(os.path.join(datasetPath, rock['Diretorio Img']))
                img = normalizeImage(img, normalization)
                class_Name = rock['Classe']
                class_ID = classes_L0_dict[class_Name]
                if classLevel > 0:
                    superClassName = classes_hierarchy_L0L1[class_Name]
                    superClassID = classes_L1_dict[superClassName]
                    class_Name = superClassName
                    class_ID = superClassID
                    if classLevel > 1:
                        superClassName = classes_hierarchy_L1L2[class_Name]
                        superClassID = classes_L2_dict[superClassName]
                        class_Name = superClassName
                        class_ID = superClassID
                img = augmentImages(aug_dict, img, crop_size)
                if crop_size != net_input_size:
                    img = cv2.resize(img, dsize=(net_input_size[0], net_input_size[1]), interpolation=cv2.INTER_CUBIC)
                img = np.zeros(net_input_size)

                cls = np.zeros(class_count)
                cls[class_ID] = 1
                img = np.array([img])

                yield img, cls

def testGeneratorStones(datasetPath, testSet, input_size, inicial_size, normalization, augmentation):
    for rock in testSet:
        img = io.imread(os.path.join(datasetPath, rock['Diretorio Img']))
        img = normalizeImage(img, normalization)
        if augmentation == "center":
            img = do_center_crop(img, input_size, inicial_size)
        else:
            img = augmentImages(augmentation, img, input_size)
        img = np.array([img])
        yield img

def get_class_gt(set, classes_structure, classLevel):
    class_gt = np.zeros((len(set),), 'int64')

    classes_list_L0 = classes_structure["classes_list_L0"]
    classes_list_L1 = classes_structure["classes_list_L1"]
    classes_list_L2 = classes_structure["classes_list_L2"]
    classes_L0_dict = dict(zip(classes_list_L0, list(range(0, len(classes_list_L0)))))
    classes_L1_dict = dict(zip(classes_list_L1, list(range(0, len(classes_list_L1)))))
    classes_L2_dict = dict(zip(classes_list_L2, list(range(0, len(classes_list_L2)))))

    classes_hierarchy_L0L1 = classes_structure["classes_hierarchy_L0L1"]
    classes_hierarchy_L1L2 = classes_structure["classes_hierarchy_L1L2"]

    i = 0
    for rock in set:
        class_Name = rock['Classe']
        class_ID = classes_L0_dict[class_Name]
        if classLevel > 0:
            superClassName = classes_hierarchy_L0L1[class_Name]
            superClassID = classes_L1_dict[superClassName]
            class_Name = superClassName
            class_ID = superClassID
            if classLevel > 1:
                superClassName = classes_hierarchy_L1L2[class_Name]
                superClassID = classes_L2_dict[superClassName]
                class_Name = superClassName
                class_ID = superClassID
        class_gt[i] = int(class_ID)
        i = i + 1
    return class_gt


text:
# coding: utf-8

# --------------------------------------------------------------------------
# 2021
# --------------------------------------------------------------------------
"""
Classes and functions used in Fractal app.
"""

import io
import logging

import tensorflow as tf
import numpy as np
import PIL

logging.basicConfig(level=logging.DEBUG)
logger = logging.getLogger()

class Fractal:
    def __init__(self, frame, iterations=100, resolution=(7168, 7168)):
        self.resolution = resolution
        self.range_x = (-2.0, 0.5)
        self.range_y = (-1.3, 1.3)
        self.iterations = iterations
        self.frame = frame

    def _meshgrid(self):
        x_res, y_res = self.resolution
        x_min, x_max = self.range_x
        y_min, y_max = self.range_y
        x_min, x_max, y_min, y_max = self.frame
        h_x = (x_max - x_min) / x_res
        h_y = (y_max - y_min) / y_res
        return np.mgrid[y_min:y_max:h_y, x_min:x_max:h_x]

    @staticmethod
    def _export(a, fmt='png'):
        a = np.uint8(a)
        img_byte_arr = io.BytesIO()
        PIL.Image.fromarray(a).save(img_byte_arr, fmt)
        return img_byte_arr.getvalue()

    @staticmethod
    def step(xs_, zs_, ns_):
        zs_ = zs_*zs_ + xs_

        not_diverged = tf.abs(zs_) < 4
        ns_ = tf.add(ns_, tf.cast(not_diverged, tf.float32))

        return xs_, zs_, ns_

    def generate(self):
        Y, X = self._meshgrid()
        Z = X + 1j*Y
        xs = tf.constant(Z.astype(np.complex64))
        zs = tf.zeros_like(xs)
        ns = tf.Variable(tf.zeros_like(xs, tf.float32))
        for _ in range(self.iterations):
            xs, zs, ns = self.step(xs, zs, ns)
        fractal = np.log(np.array(ns))
        fractal = 255 * fractal / fractal.max()

        return self._export(fractal)