P-unit_model/stimuli/StepStimulus.py

67 lines
2.1 KiB
Python

from stimuli.AbstractStimulus import AbstractStimulus
import numpy as np
class StepStimulus(AbstractStimulus):
def __init__(self, start, duration, value, base_value=0, seconds=True):
if duration < 0:
raise ValueError("Duration cannot be negative")
self.base_value = base_value
self.value = value
if seconds:
self.start = start
self.duration = duration
else:
self.start = start / 1000
self.duration = duration / 1000
def value_at_time_in_s(self, time_point):
if self.start <= time_point <= self.start + self.duration:
return self.value
else:
return self.base_value
def get_stimulus_start_s(self):
return self.start
def get_stimulus_duration_s(self):
return self.duration
def get_amplitude(self):
return self.value - self.base_value
def as_array(self, time_start, total_time, step_size):
values = np.full(int(total_time/step_size), self.base_value)
if self.start > time_start + self.duration or self.start + self.duration < time_start:
return values
else:
if self.start >= time_start:
am_start = self.start
else:
am_start = time_start
if time_start + total_time >= self.start + self.duration:
am_end = self.start + self.duration
else:
am_end = time_start + total_time
idx_start = (am_start - time_start) / step_size
idx_end = (am_end - time_start) / step_size
if idx_start != round(idx_start) or idx_end != round(idx_end):
raise ValueError("Didn't calculate integers when searching the start and end index. start:", idx_start,
"end:", idx_end)
# print("am_start: {:.0f}, am_end: {:.0f}, length: {:.0f}".format(am_start, am_end, am_end-am_start))
idx_start = int(idx_start)
idx_end = int(idx_end)
values[idx_start:idx_end+1] = self.value
return values