def grid(field_grid: int, plant_grid: int):
        """
        Create the grids

        Args:
            field_grid: field grid parameters
            plant_grid: plant grid parameters

        Returns:
            grid setup
        """
        return [graph.graph(field_grid), graph.graph(plant_grid)]
Example #2
0
 def addarduino(self, controlunit):
     canvas = Canvas(self.frame, bg='#ccc')
     g = graph(canvas,controlunit, self)
     self.canvasList.append({
         'graph': g,
         'canvas':canvas
     })
     f = Frame(width=135, height=40)
     d = {
         'frame': f,
         'graph': g,
         'v_temp': Label(f),
         'v_light': Label(f),
         'c_temp': BooleanVar(),
         'c_light': BooleanVar()
     }
     d['c_temp'].set(True)
     d['c_light'].set(True)
     d['b_light'] = Checkbutton(d['frame'], text="Light", variable=d['c_light'], onvalue=True, offvalue=False)
     d['b_temp'] = Checkbutton(d['frame'], text="Temperature", variable=d['c_temp'], onvalue=True, offvalue=False)
     d['b_light'].place(x=-3,y=-3)
     d['b_temp'].place(x=-3,y=17)
     d['v_light'].place(x=90,y=0)
     d['v_temp'].place(x=90,y=20)
     self.canvasOptions.append(d)
     self.drawframe()
Example #3
0
    def __init__(self, root, controlunit):
        self.root = root
        self.controlunit = controlunit
        self.frame = Frame(width=0, height=0, bg='#eee')
        self.tempCanvas = Canvas(self.frame, bg='#ccc')
        self.lightCanvas = Canvas(self.frame, bg='#ccc')
        self.tempGraph = graph(self.tempCanvas, controlunit)
        self.lightGraph = graph(self.lightCanvas, controlunit)
        self.lightGraph.drawtemp = False
        self.tempGraph.drawlight = False

        #Labels
        self.l_temp = Label(self.frame, text="Temperatuur: {} C".format(0))
        self.l_light = Label(self.frame,
                             text="Lichtintensiteit: {} Lux".format(0))
        self.l_state = Label(self.frame, text="Status: {}".format("Onbekend"))

        #Radio
        self.statusValue = IntVar(self.frame)
        self.statuslabel = Label(self.frame, text="Rolluik besturing")
        self.statusradio = [
            Radiobutton(self.frame,
                        text="Automatisch",
                        variable=self.statusValue,
                        value=0),
            Radiobutton(self.frame,
                        text="Opgerold",
                        variable=self.statusValue,
                        value=1),
            Radiobutton(self.frame,
                        text="Uitgerold",
                        variable=self.statusValue,
                        value=2)
        ]
        self.optionbutton = Button(self.frame, text="Send", command=self.send)
        self.drawframe()
        pass
Example #4
0
class Simulator(object):
    """
    Class to setup and run a simulation of only biomass growth:

    Variables:
        nums:   initial population numbers
        forage: the plant forage model
    """

    grid = [(keyword.hexagon, 1, 1, True), graph.graph(10)]
    attrs = {1: tracking.genotype_attrs}
    data = (np.inf, )
    steps = [({
        keyword.larva: [keyword.move, keyword.consume]
    }, param.forage_steps), ({
        keyword.larva: [keyword.grow, keyword.reset]
    }, )]
    emigration = []
    immigration = []

    input_models = [
        growth.max_gut(),
        growth.growth(param.alpha_ss, param.alpha_rr, param.beta_ss,
                      param.beta_rr, dominance),
        init_bio.init_num(param.lam_0_egg),
        init_bio.init_mass(param.mu_0_egg_ss, param.mu_0_egg_rr,
                           param.sig_0_egg_ss, param.sig_0_egg_rr, dominance),
        init_bio.init_juvenile(44.194, 18.947, 0.552, 0.17, dominance),
        init_bio.init_mature(param.mu_0_mature_ss, param.mu_0_mature_rr,
                             param.sig_0_mature_ss, param.sig_0_mature_rr,
                             dominance),
        init_bio.init_plant(param.mu_leaf, param.sig_leaf),
        repro.init_sex(param.female_prob),
        move.larva(param.larva_scale, param.larva_shape),
        forage.adlibitum(param.forage_steps),
        forage.egg(param.egg_factor),
        forage.larva(param.larva_factor),
        forage.fight(param.fight_slope),
        forage.radius(param.cannibalism_radius),
        # forage.loss(param.loss_slope,
        #             param.mid,
        #             param.egg_factor,
        #             param.larva_factor)
    ]
    input_variables = param.repro_values

    nums: hint.init_pops
    bt_prop: float
    encounter: float
    simulation: hint.simulation = None

    def __post_init__(self):

        input_models = self.input_models.copy()
        input_models.append(forage.encounter(self.encounter))

        self.simulation = main_simulation.Simulation. \
            setup(self.nums,
                  self.grid,
                  self.attrs,
                  self.data,
                  self.bt_prop,
                  self.steps,
                  self.emigration,
                  self.immigration,
                  *input_models,
                  **self.input_variables)

    def run_sim(self, times: list) -> None:
        """
        Run the simulation for each time

        Args:
            times: the times for the simulation

        Returns:
            biomass data
        """

        for _ in times[1:]:
            self.simulation.step()

    def get_start_data(self, data_key: str) -> int:
        """
        Get the start population of larvae

        Args:
            data_key: the genotype table key

        Returns:
            the number of larvae at start
        """

        dataframes = self.simulation.agents.dataframes()

        larva = dataframes['(0, 0)_larva']
        column = larva[data_key]

        return int(column[0])

    def get_final_data(self, data_key: str) -> int:
        """
        Get the final population of larvae

        Args:
            data_key: the genotype table key

        Returns:
            the number of larvae at the end
        """

        dataframes = self.simulation.agents.dataframes()

        timestep = self.simulation.timestep
        pupa = dataframes['(0, 0)_larva']
        column = pupa[data_key]
        value = column[timestep]

        return int(value)

    @classmethod
    def run(cls, rho: float, times: list, data_key: str,
            nums: hint.init_pops) -> tuple:
        """
        Run a bunch of trials
        Args:
            rho:        encounter constant
            times:      time interval
            data_key:   column key
            nums:       init_population

        Returns:
            value of cannibalism rate constant
        """

        print('    {} Starting run for rho: {}'.format(datetime.datetime.now(),
                                                       rho))
        start_data = []
        end_data = []
        for trial_num in range(trials):
            print('        {} running trial: {}'.format(
                datetime.datetime.now(), trial_num))
            sim = cls(nums, 1, rho)
            sim.run_sim(times)
            start_data.append(sim.get_start_data(data_key))
            end_data.append(sim.get_final_data(data_key))

        start_pop = np.mean(start_data)
        end_pop = np.mean(end_data)

        start_lower = np.percentile(start_data, 2.5)
        start_upper = np.percentile(start_data, 97.5)
        end_lower = np.percentile(end_data, 2.5)
        end_upper = np.percentile(end_data, 97.5)

        prop = end_pop / start_pop
        prop_lower = end_lower / start_lower
        prop_upper = end_upper / start_upper

        rate = 1 - prop
        rate_lower = 1 - prop_lower
        rate_upper = 1 - prop_upper

        return prop, prop_lower, prop_upper, rate, rate_lower, rate_upper

    @classmethod
    def rho(cls, rhos: np.array, times: list, data_key: str,
            nums: hint.init_pops) -> tuple:
        """
        Run trials for each rho value

        Args:
            rhos:     list of encounter constants
            times:    time interval
            data_key: data key
            nums:     init population

        Returns:
            list of corresponding values for cannibalism
        """

        prop = []
        prop_lower = []
        prop_upper = []
        rate = []
        rate_lower = []
        rate_upper = []
        for rho in rhos:
            rho_prop, rho_prop_lower, rho_prop_upper, \
                rho_rate, rho_rate_lower, rho_rate_upper = \
                cls.run(rho, times, data_key, nums)

            prop.append(rho_prop)
            prop_lower.append(rho_prop_lower)
            prop_upper.append(rho_prop_upper)
            rate.append(rho_rate)
            rate_lower.append(rho_rate_lower)
            rate_upper.append(rho_rate_upper)

        return prop, prop_lower, prop_upper, rate, rate_lower, rate_upper
        plant_arrow, leaf_arrow = convert_xy_location(agent_data, side_p, side_l)
        plant_arrows.append(plant_arrow)
        leaf_arrows.append(leaf_arrow)

    return plant_arrows, leaf_arrows


t            = list(range(num_steps))
print('Running Larva')
initial_pops = ((0,          0,          0),
                (num_larvae, num_larvae, num_larvae),
                (0,          0,          0),
                (0,          0,          0),
                (0,          0,          0))
grid         = [(keyword.hexagon, 1, 1, True),
                graph.graph(larva_grid)]
simulator_larva = Simulator(initial_pops, grid, 1)
larva_larva, adult_larva = simulator_larva.run(t)

larva_plant, larva_leaf = convert(larva_larva, 3*num_larvae, 1, larva_grid)


plt.output_file('larva_' + save_file)
larva_plot = plt.figure(plot_width=plot_width,
                        plot_height=plot_height,
                        x_range=(0, larva_grid),
                        y_range=(0, larva_grid))
larva_plot.title.text = 'Larva Movement, ' \
                        '(x_m={}, a={})'.format(param.larva_scale,
                                                param.larva_shape)
larva_plot.yaxis.axis_label = 'distance (~cm)'
class Simulator(object):
    """
    Class to setup and run a simulation of only biomass growth:

    Variables:
        nums:    initial population numbers
        bt_prop: bt proportion
    """

    grid = [graph.graph(field_grid), (keyword.hexagon, 1, 1, True)]
    attrs = {0: tracking.genotype_attrs}
    data = (np.inf, )
    steps = [({
        keyword.female: [keyword.move, keyword.reproduce],
        keyword.male: [keyword.move]
    }, param.forage_steps),
             ({
                 keyword.female: [keyword.advance_age, keyword.reset],
                 keyword.male: [keyword.advance_age, keyword.reset]
             }, )]
    emigration = []
    immigration = []

    input_models = [
        growth.max_gut(),
        growth.growth(param.alpha_ss, param.alpha_rr, param.beta_ss,
                      param.beta_rr, dominance),
        init_bio.init_num(param.lam_0_egg),
        init_bio.init_mass(param.mu_0_egg_ss, param.mu_0_egg_rr,
                           param.sig_0_egg_ss, param.sig_0_egg_rr, dominance),
        init_bio.init_juvenile(param.mu_0_larva_ss, param.mu_0_larva_rr,
                               param.sig_0_larva_ss, param.sig_0_larva_rr,
                               dominance),
        init_bio.init_mature(param.mu_0_mature_ss, param.mu_0_mature_rr,
                             param.sig_0_mature_ss, param.sig_0_mature_rr,
                             dominance),
        init_bio.init_plant(param.mu_leaf, param.sig_leaf),
        move.adult(param.adult_scale, param.adult_shape),
        repro.mating(param.mate_encounter),
        repro.radius(param.mate_radius),
        repro.density(param.eta, param.gamma),
        repro.init_sex(param.female_prob)
    ]
    input_variables = param.repro_values

    nums: hint.init_pops
    bt_prop: float
    simulation: hint.simulation = None

    def __post_init__(self):

        self.simulation = main_simulation.Simulation. \
            setup(self.nums,
                  self.grid,
                  self.attrs,
                  self.data,
                  self.bt_prop,
                  self.steps,
                  self.emigration,
                  self.immigration,
                  *self.input_models,
                  **self.input_variables)

    def collect(self) -> tuple:
        """
        Collect the number of egg_masses

        Returns:
            number of egg_masses
        """

        females = self.simulation.agents.agents(keyword.female)

        mated = []
        for female in females:
            if female.mate is not None:
                mated.append(female)

        return len(females), len(mated)

    def run(self, times: list) -> tuple:
        """
        Run the simulation for each time

        Args:
            times: the times for the simulation

        Returns:
            num egg_mass, densities
        """

        females, mated = self.collect()

        data_females = [females]
        data_mated = [mated]
        data_prop = [mated / females]
        for time in times[1:]:
            print('        {} Running step: {}'.format(datetime.datetime.now(),
                                                       time))
            self.simulation.step()
            females, mated = self.collect()

            data_females.append(females)
            data_mated.append(mated)
            data_prop.append(mated / females)

        return data_females, data_mated, data_prop
Example #7
0
class Simulator(object):
    """
    Class to setup and run a simulation of only biomass growth:

    Variables:
        nums:    initial population numbers
        bt_prop: bt proportion
    """

    grid = [graph.graph(param.field_grid), graph.graph(param.plant_grid)]
    attrs = {0: tracking.genotype_attrs}

    steps = [({
        keyword.female: [keyword.reproduce, keyword.move],
        keyword.male: [keyword.move],
        keyword.mated: [keyword.move],
        keyword.larva: [keyword.consume, keyword.move]
    }, param.forage_steps, True),
             ({
                 keyword.female:
                 [keyword.survive, keyword.advance_age, keyword.reset],
                 keyword.male:
                 [keyword.survive, keyword.advance_age, keyword.reset],
                 keyword.mated:
                 [keyword.survive, keyword.advance_age, keyword.reset],
                 keyword.larva: [
                     keyword.grow, keyword.survive, keyword.develop,
                     keyword.advance_age, keyword.reset
                 ],
                 keyword.pupa:
                 [keyword.survive, keyword.develop, keyword.advance_age],
                 keyword.egg:
                 [keyword.survive, keyword.develop, keyword.advance_age],
                 keyword.egg_mass: [keyword.reset]
             }, )]

    emigration = [
        migration.emigration_adult(param.mean_adult, param.sigma_adult)
    ]
    immigration = []
    input_variables = param.repro_values
    timesteps = param.timesteps

    run_number: int
    nums: hint.init_pops
    bt_prop: float
    input_models: list

    path_save: str
    base_save: str

    data: tuple = ()
    simulation: hint.simulation = None
    step: int = 1

    def __post_init__(self):
        save_name = '{}_{}{}'.format(self.base_save, self.run_number,
                                     '.sqlite')
        self.data = (100, save_name, self.path_save)

        self.simulation = main_simulation.Simulation. \
            setup(self.nums,
                  self.grid,
                  self.attrs,
                  self.data,
                  self.bt_prop,
                  self.steps,
                  self.emigration,
                  self.immigration,
                  *self.input_models,
                  **self.input_variables)

    def execute(self) -> None:
        """
        Run the simulation

        """

        start_time = datetime.datetime.now()
        times = list(range(self.timesteps))
        run_times = times[self.step:].copy()

        for time in run_times:
            self.step = time
            print('     {} Simulation {}, Running step: {}'.format(
                datetime.datetime.now(), self.run_number, time))
            self.simulation.step()

        print('     {} Simulation {}, Complete Starting save'.format(
            datetime.datetime.now(), self.run_number))
        self.simulation.database.dump(self.simulation)
        end_time = datetime.datetime.now()
        print('Total elapsed time: {}'.format(end_time - start_time))

    @classmethod
    def run(cls, run_number: int, nums: hint.init_pops, bt_prop: float,
            input_models: list, path_save: str, base_save: str) -> None:
        """
        Create and tun the simulation

        Args:
            run_number:    the simulation run id
            nums:          initial population
            bt_prop:       proportion of bt
            input_models:  list of input data
            path_save:     path to save the data
            base_save:     base for saving the data

        Effects:
            runs simulation creating data files
        """

        print('{} Run {} Setting Up Long Time Simulations'.format(
            datetime.datetime.now(), run_number))
        sim = cls(run_number, nums, bt_prop, input_models, path_save,
                  base_save)
        print('{} Run {} Running Long Time Simulations'.format(
            datetime.datetime.now(), run_number))
        sim.execute()
class Simulator(object):
    """
    Class to setup and run a simulation of only biomass growth:

    Variables:
        nums:    initial population numbers
        bt_prop: bt proportion
    """

    grid = [graph.graph(field_grid), graph.graph(plant_grid)]
    attrs = {0: tracking.genotype_attrs}
    data = (np.inf, )
    steps = [({
        keyword.female: [keyword.move, keyword.reproduce],
        keyword.male: [keyword.move]
    }, param.forage_steps),
             ({
                 keyword.female: [keyword.advance_age, keyword.reset],
                 keyword.male: [keyword.advance_age, keyword.reset]
             }, )]
    emigration = []
    immigration = []

    input_variables = param.repro_values

    nums: hint.init_pops
    bt_prop: float
    mate_encounter: float
    mate_radius: float
    simulation: hint.simulation = None

    def __post_init__(self):
        inputs = self.input_models(self.mate_encounter, self.mate_radius)
        inputs = tuple(inputs)

        self.simulation = main_simulation.Simulation. \
            setup(self.nums,
                  self.grid,
                  self.attrs,
                  self.data,
                  self.bt_prop,
                  self.steps,
                  self.emigration,
                  self.immigration,
                  *inputs,
                  **self.input_variables)

    @staticmethod
    def input_models(mate_encounter: float, mate_radius: float):
        """
        Create all the input models

        Args:
            mate_encounter: mate encounter constant
            mate_radius:    mate radius

        Returns:
            input models
        """

        return [
            growth.max_gut(),
            growth.growth(param.alpha_ss, param.alpha_rr, param.beta_ss,
                          param.beta_rr, dominance),
            init_bio.init_num(param.lam_0_egg),
            init_bio.init_mass(param.mu_0_egg_ss, param.mu_0_egg_rr,
                               param.sig_0_egg_ss, param.sig_0_egg_rr,
                               dominance),
            init_bio.init_juvenile(param.mu_0_larva_ss, param.mu_0_larva_rr,
                                   param.sig_0_larva_ss, param.sig_0_larva_rr,
                                   dominance),
            init_bio.init_mature(param.mu_0_mature_ss, param.mu_0_mature_rr,
                                 param.sig_0_mature_ss, param.sig_0_mature_rr,
                                 dominance),
            init_bio.init_plant(param.mu_leaf, param.sig_leaf),
            move.adult(param.adult_scale, param.adult_shape),
            repro.mating(mate_encounter),
            repro.radius(mate_radius),
            repro.fecundity(param.fecundity_maximum, param.fecundity_decay),
            repro.density(param.eta, param.gamma),
            repro.init_sex(param.female_prob)
        ]

    @staticmethod
    def percent(dataframe: hint.dataframe) -> None:
        """
        Add percent resist column

        Args:
            dataframe: dataframe to process

        Effects:
            add percent column
        """
        def resist(row) -> float:
            """
            Percent resistant of row value

            Args:
                row: row of dataframe

            Returns:
                percent resistant
            """

            ss = row['genotype_susceptible']
            sr = row['genotype_heterozygous']
            rr = row['genotype_resistant']

            total = 2 * (ss + sr + rr)

            if total == 0:
                return np.nan
            else:
                r = 2 * rr + sr

                return r / total

        dataframe['percent'] = dataframe.apply(lambda row: resist(row), axis=1)

    @staticmethod
    def ratios(dataframe: hint.dataframe) -> None:
        """
        Add ratio of genotype columns

        Args:
            dataframe: dataframe to process

        Effects:
            add ratio columns
        """
        def resist(row) -> float:
            """
            Percent resistant of row value

            Args:
                row: row of dataframe

            Returns:
                percent resistant
            """

            ss = row['genotype_susceptible']
            sr = row['genotype_heterozygous']
            rr = row['genotype_resistant']

            total = ss + sr + rr

            if total == 0:
                return 0
            else:
                return rr / total

        def suscept(row) -> float:
            """
            Percent susceptible of row value

            Args:
                row: row of dataframe

            Returns:
                percent resistant
            """

            ss = row['genotype_susceptible']
            sr = row['genotype_heterozygous']
            rr = row['genotype_resistant']

            total = ss + sr + rr

            if total == 0:
                return 0
            else:
                return ss / total

        def hetero(row) -> float:
            """
            Percent hetero of row value

            Args:
                row: row of dataframe

            Returns:
                percent resistant
            """

            ss = row['genotype_susceptible']
            sr = row['genotype_heterozygous']
            rr = row['genotype_resistant']

            total = ss + sr + rr

            if total == 0:
                return 0
            else:
                return sr / total

        dataframe['percent_resist'] = \
            dataframe.apply(lambda row: resist(row), axis=1)

        dataframe['percent_suscept'] = \
            dataframe.apply(lambda row: suscept(row), axis=1)

        dataframe['percent_hetero'] = \
            dataframe.apply(lambda row: hetero(row), axis=1)

    def run(self, times: list) -> hint.dataframe:
        """
        Run the simulation for each time

        Args:
            times: the times for the simulation

        Returns:
            num egg_mass, densities
        """

        for time in times[1:]:
            print('        {} Running step: {}'.format(datetime.datetime.now(),
                                                       time))
            self.simulation.step()

        print('        {} Getting data'.format(datetime.datetime.now()))
        dataframes = self.simulation.agents.dataframes()
        dataframe = dataframes['(0,)_egg']
        print('        {} Calculating Percent'.format(datetime.datetime.now()))
        self.percent(dataframe)
        self.ratios(dataframe)

        return dataframe