Ejemplo n.º 1
0
 def to_idle_state(self):
     session_state["state"] = "idle"
     params = exp.get_params()
     min_t, max_t = params["min_idle_time"], params["max_idle_time"]
     idle_time = self.rng.random() * (max_t - min_t) + min_t
     self.log.info(f"Waiting {idle_time:.2f} seconds.")
     schedule.once(exp.next_trial, idle_time)
    def is_in_area_changed(self, old, new):
        # TODO: make sure area changed continuously
        if not old and new:
            exp.event_logger.log(
                "loclearn/entered_area", {"cooldown": session_state["cooldown"]}
            )
            if session_state["cooldown"]:
                self.log.info("Animal entered the reinforced area during cooldown.")
                self.cancel_cooldown()
                session_state["cooldown"] = False
            else:
                self.log.info("Animal entered the reinforced area.")
                schedule.once(
                    self.maybe_end_trial, exp.get_params()["area_stay_duration"]
                )

        elif old and not new:
            exp.event_logger.log("loclearn/left_area", None)
            self.log.info("Animal left the reinforced area.")

            if session_state["reward_scheduled"]:
                session_state["cooldown"] = True
                self.cancel_cooldown = schedule.once(
                    self.maybe_end_cooldown, exp.get_params()["cooldown_duration"]
                )
 def dispatch_reward(self):
     params = exp.get_merged_params()
     if params["reward_delay"] == None:
         self.reward_delay = params["led_duration"] * params["led_blinks"]
     else:
         self.reward_delay = params["reward_delay"]
     schedule.once(self.dispatch_reward_actual, self.reward_delay)
Ejemplo n.º 4
0
 def dispatch_reward(self):
     params = exp.get_params()
     if params["stimulus"].lower() == "led":
         self.reward_delay = params["led_duration"] * params["led_blinks"]
     else:
         self.reward_delay = params.get("monitor_duration", 60)
     schedule.once(self.dispatch_reward_actual, self.reward_delay)
Ejemplo n.º 5
0
 def test_once(self):
     mock_job = make_mock_job()
     once().second.do(mock_job)
     once().day.at('10:30').do(mock_job)
     assert len(schedule.jobs) == 2
     schedule.run_all()
     assert mock_job.call_count == 2
     assert len(schedule.jobs) == 0
Ejemplo n.º 6
0
 def _connect(self):
     id_value = self.id_value()
     secret_value = self.secret_value()
     self.dapp.config.connection_args = (self.id_value(),
                                         self.secret_value())
     self.dapp.config.connection_strategy = self.dapp.connection_strategy
     #debug(); pdb.set_trace()
     schedule.once().do(self.dapp.node.poll)
     self.close()
    def end_trial(self, params):
        if self.in_trial:
            self.log.info("Logic trial wasnt finished!")
            if params.get("record_exp", True) and not params["record_all"]:
                schedule.once(lambda: video_system.stop_record(),
                              params.get("record_overhead", 0))
            if params["stimulus"] == "monitor":
                monitor.chnage_color("black")
            self.in_trial = False
            self.got_detection = False

        self.cur_trial = self.cur_trial - 1
    def maybe_end_trial(self):
        params = exp.get_params()
        if (session_state["is_in_area"] and self.in_out_time is not None and
                time.time() - self.in_out_time > params["area_stay_duration"]):
            self.log.info("Trial successful!")
            session_state.update(
                (),
                {
                    "reward_scheduled": True,
                    "cooldown_time": True,
                    "cooldown_dist": True,
                },
            )

            self.cancel_cooldown = schedule.once(
                self.end_time_cooldown,
                exp.get_params()["cooldown_duration"])

            if session_state["out_of_rewards"] is True:
                self.log.warning(
                    "Out of rewards. Can't reward successful trial.")
                return

            interface = params["cue"]["interface"]
            led_dur = params["cue"]["led_duration"]
            num_blinks = params["cue"]["num_blinks"]
            period_time = 1000 * led_dur / num_blinks // 2
            self.log.info(
                f"Starting blinking {interface}. {num_blinks} blinks in {led_dur}s (period {period_time}ms)"
            )
            start_blink(
                interface,
                period_time,
            )

            def stop():
                stop_blink(interface)
                self.log.info("Stopped blinking.")

            schedule.once(stop, led_dur)

            if random.random() <= params["reward"]["stochastic_delay_prob"]:
                delay = params["reward"]["stochastic_delay"]
                self.using_stochastic_delay = True
            else:
                delay = params["reward"]["delay"]
                self.using_stochastic_delay = False

            self.cancel_reward_delay = schedule.once(self.dispense_reward,
                                                     delay)
 def monitor_stimulus(self):
     params = exp.get_merged_params()
     monitor.chnage_color(params.get("monitor_color", "random"))
     self.stim_cancel = schedule.once(
         mqtt.client.publish(topic="monitor/color",
                             payload=params.get("monitor_color", "black")),
         params.get("monitor_duration", 60),
     )
    def end_logic_trial(self):
        params = exp.get_merged_params()
        self.stim_cancel()  # canceling stimulus, if active.
        if params["stimulus"] == "monitor":
            monitor.chnage_color("black")
        timestap = time.time()
        # logging trial data
        if self.in_trial and not self.got_detection:
            self.log.info("Logic trial ended, failure")
            exp.event_logger.log(
                "learn_exp/logical_trial_ended",
                {
                    "type": self.ex_type,
                    "success": False
                },
            )
        elif self.in_trial and self.got_detection:
            self.log.info("Logic trial ended, success")
            exp.event_logger.log("learn_exp/logical_trial_ended", {
                "type": self.ex_type,
                "success": True
            })
        else:
            self.log.info("Logic trial ended")

        # continuous trial: schedule the next.
        self.in_trial = False
        self.got_detection = False
        if params.get("continuous", False):
            if params["record_exp"] and not params["record_all"]:
                video_system.stop_record()
            self.cancel_trials()
            self.cancel_trials = schedule.repeat(self.period_call, interval,
                                                 self.cur_trial - 1)
        elif self.consecutive:
            if params["record_exp"] and not params["record_all"]:
                schedule.once(lambda: video_system.stop_record(),
                              params.get("record_overhead", 0))
            if self.cur_trial > 0:
                exp.next_trial()
        else:
            if params["record_exp"] and not params["record_all"]:
                schedule.once(lambda: video_system.stop_record(),
                              params.get("record_overhead", 0))
Ejemplo n.º 11
0
    def run_trial(self):
        if exp.get_params()["record_video"]:
            video_system.start_record()

        if exp.get_params()["media_url"] is not None:
            schedule.once(
                lambda: mqtt.client.publish_json(
                    "event/command/init_media", {"url": exp.get_params()["media_url"]}
                ),
                exp.get_params()["start_delay"],
            )

        else:
            schedule.once(
                lambda: mqtt.client.publish_json(
                    "event/command/init_bugs", exp.get_params()
                ),
                exp.get_params()["start_delay"],
            )
Ejemplo n.º 12
0
        def start_trial():
            session_state.update((), {"cur_block": block, "cur_trial": trial})

            if cur_block != block or force_run:
                cur_experiment.run_block()

            if cur_trial != trial or cur_block != block or force_run:
                cur_experiment.run_trial()

            block_duration = get_params().get("$block_duration", None)
            if block_duration is not None:
                schedule.once(next_block,
                              block_duration,
                              pool="experiment_phases")

            trial_duration = get_params().get("$trial_duration", None)
            if trial_duration is not None:
                schedule.once(next_trial,
                              trial_duration,
                              pool="experiment_phases")
    def is_in_area_changed(self, old, new):
        # TODO: make sure area changed continuously
        if not old and new:
            exp.event_logger.log(
                "loclearn/entered_area",
                {
                    "cooldown_time": session_state["cooldown_time"],
                    "cooldown_dist": session_state["cooldown_dist"],
                },
            )
            if session_state["cooldown_time"] or session_state["cooldown_dist"]:
                self.log.info(
                    "Animal entered the reinforced area during cooldown.")
            else:
                self.log.info("Animal entered the reinforced area.")
                schedule.once(self.maybe_end_trial,
                              exp.get_params()["area_stay_duration"])

        elif old and not new:
            exp.event_logger.log("loclearn/left_area", None)
            self.log.info("Animal left the reinforced area.")
Ejemplo n.º 14
0
    def show_cue(self, left):
        session_state["state"] = "cue"

        params = exp.get_params()
        blink_dur = params["blink_dur_left"] if left else params[
            "blink_dur_right"]
        arena.run_command("periodic", params["light"], [1, blink_dur], False)

        def stop_blink():
            arena.run_command("periodic", params["light"], [0], True)
            self.to_feed_state()

        self.cancel_stop_blink = schedule.once(
            stop_blink,
            params["cue_duration"],
        )
    def maybe_end_trial(self):
        params = exp.get_params()
        if (
            session_state["is_in_area"]
            and time.time() - self.in_out_time > params["area_stay_duration"]
        ):
            session_state["reward_scheduled"] = True
            self.cancel_blink = led_blink(
                params["cue"]["num_blinks"], params["cue"]["led_duration"]
            )

            if random.random() < params["stochastic_delay_prob"]:
                delay = params["stochastic_delay"]
                self.using_stochastic_delay = True
            else:
                delay = params["reward_delay"]
                self.using_stochastic_delay = False

            self.cancel_reward_delay = schedule.once(exp.next_trial, delay)
    def run_trial(self, params):

        self.in_trial = True

        if (params.get("record_exp", True)
                and not params["record_all"]):  # recording trials only
            video_system.start_record()

        self.log.info("Trial " + str(params["$num_trials"] - self.cur_trial) +
                      " started " + str(datetime.datetime.now()))

        if not self.consecutive:
            self.stim()  # present stimulus at trials start
            # giving a reward if bypass_detection enabled
            if params["bypass_detection"] and params["reward_detections"]:
                self.dispatch_reward()
                self.end_logic_trial()
            else:  # scheduling the logical end of trial
                self.cancel_logic_trial = schedule.once(
                    self.end_logic_trial, params["trial_length"])

        self.log.info("run trial procedure finished")
Ejemplo n.º 17
0
 def run_block(self):
     self.log.info("Playing video...")
     if len(exp.get_params()["vid_path"]) > 0:
         monitor.play_video(exp.get_params()["vid_path"])
     if exp.get_params()["block_duration"] is not None:
         schedule.once(exp.next_block, exp.get_params()["block_duration"])
Ejemplo n.º 18
0
def set_phase(block, trial, force_run=False):
    """
    Set the current block and trial numbers.
    Calls the run_block() and run_trial() experiment class hooks.

    block, trial: int indices (starting with 0).
    force_run: When True, the hooks will be called even when the parameters are
    the same as the current phase.
    """
    if blocks.exists(()):
        if len(blocks.get_self()) <= block and block != 0:
            raise ExperimentException(f"Block {block} is not defined.")
    else:
        raise ExperimentException(
            "Session doesn't have any block definitions.")

    if not session_state["is_running"]:
        session_state.update((), {"cur_block": block, "cur_trial": trial})
        return
    else:
        cur_trial = session_state.get("cur_trial", None)
        cur_block = session_state.get("cur_block", None)

        if cur_trial != trial or cur_block != block:
            cur_experiment.end_trial()

        if cur_block != block:
            cur_experiment.end_block()

        num_trials = get_params().get("$num_trials", None)
        if num_trials is not None and trial >= num_trials:
            raise ExperimentException(
                f"Trial {trial} is out of range for block {block}.")

        def start_trial():
            session_state.update((), {"cur_block": block, "cur_trial": trial})

            if cur_block != block or force_run:
                cur_experiment.run_block()

            if cur_trial != trial or cur_block != block or force_run:
                cur_experiment.run_trial()

            block_duration = get_params().get("$block_duration", None)
            if block_duration is not None:
                schedule.once(next_block,
                              block_duration,
                              pool="experiment_phases")

            trial_duration = get_params().get("$trial_duration", None)
            if trial_duration is not None:
                schedule.once(next_trial,
                              trial_duration,
                              pool="experiment_phases")

        try:
            schedule.cancel_all(pool="experiment_phases", wait=False)
        except ValueError:
            pass

        iti = get_params().get("$inter_trial_interval", None)
        if iti is not None and cur_block != block or cur_trial != trial:
            schedule.once(start_trial, iti)
        else:
            start_trial()
Ejemplo n.º 19
0
 def monitor_stimulus(self):
     monitor.set_color(exp.get_params().get("monitor_color", "random"))
     self.stim_cancel = schedule.once(
         mqtt.client.publish(topic="monitor/color", payload="black"),
         exp.get_params().get("monitor_duration", 60),
     )