def __init__(self, n_qubit=5): self.n_qubit = n_qubit self.dt = 10E-9 self.local_xy = True self.simultaneous_pulses = True # waveform parameter self.sample_rate = 1.2E9 self.n_pts = 240E3 self.first_delay = 100E-9 self.trim_to_sequence = True self.align_to_end = False self.sequences = [] self.qubits = [Qubit() for n in range(MAX_QUBIT)] # waveforms self._wave_xy = [ np.zeros(0, dtype=np.complex) for n in range(MAX_QUBIT) ] self._wave_z = [np.zeros(0) for n in range(MAX_QUBIT)] self._wave_gate = [np.zeros(0) for n in range(MAX_QUBIT)] # waveform delays self.wave_xy_delays = np.zeros(MAX_QUBIT) self.wave_z_delays = np.zeros(MAX_QUBIT) # define pulses self.pulses_1qb_xy = [Pulse() for n in range(MAX_QUBIT)] self.pulses_1qb_z = [Pulse() for n in range(MAX_QUBIT)] self.pulses_2qb = [Pulse() for n in range(MAX_QUBIT - 1)] self.pulses_readout = [ Pulse(pulse_type=PulseType.READOUT) for n in range(MAX_QUBIT) ] # cross-talk self.compensate_crosstalk = False self._crosstalk = Crosstalk() # predistortion self.perform_predistortion = False self._predistortions = [Predistortion(n) for n in range(MAX_QUBIT)] self._predistortions_z = [ ExponentialPredistortion(n) for n in range(MAX_QUBIT) ] # gate switch waveform self.generate_gate_switch = False self.uniform_gate = False self.gate_delay = 0.0 self.gate_overlap = 20E-9 self.minimal_gate_time = 20E-9 # readout trig settings self.readout_trig_generate = False # readout wave object and settings self.readout = Readout(max_qubit=MAX_QUBIT) self.readout_trig = np.array([], dtype=float) self.readout_iq = np.array([], dtype=np.complex)
def _add_pulse(self, element, offset, pulse, waveforms, element_time_offset): chan_idx = self.find_channel(pulse['channel']) chan = self.channels[chan_idx] cable_delay = chan['cable_delay'] AWG_chan_idx, AWG_subchan_idx = self._AWG_chan_indices(chan) # where we actually put the wfs depends on the cable delay # of the involved channels sidx = int(self.start_index(pulse['name'], element['name']) + offset - \ cable_delay) eidx = int(self.end_index(pulse['name'], element['name']) + offset - \ cable_delay) stime = (sidx/self.clock + element_time_offset) if \ pulse['element_phase'] else 0 samples = eidx-sidx duration = samples/self.clock # print "pulse '%s' has offset %d (=%.3f us)" % (pulse['name'], sidx+of, stime*1e6) p = Pulse(pulse, samples, stime, self.clock) waveforms[AWG_chan_idx][AWG_subchan_idx][sidx:eidx] += p.wform() return waveforms
def _add_pulse(self, element, offset, pulse, waveforms, element_time_offset): chan_idx = self.find_channel(pulse['channel']) chan = self.channels[chan_idx] cable_delay = chan['cable_delay'] AWG_chan_idx, AWG_subchan_idx = self._AWG_chan_indices(chan) # where we actually put the wfs depends on the cable delay # of the involved channels sidx = int(self.start_index(pulse['name'], element['name']) + offset - \ cable_delay) eidx = int(self.end_index(pulse['name'], element['name']) + offset - \ cable_delay) stime = (sidx/self.clock + element_time_offset) if \ pulse['element_phase'] else 0 samples = eidx-sidx duration = samples/self.clock if pulse['duration'] < 0 : print 'ERROR: pulse ', pulse['name'], 'in element',pulse['element'],'has duration', pulse['duration'] # print "pulse '%s' has offset %d (=%.3f us)" % (pulse['name'], sidx+of, stime*1e6) p = Pulse(pulse, samples, stime, self.clock) waveforms[AWG_chan_idx][AWG_subchan_idx][sidx:eidx] += p.wform() return waveforms
def __init__(self, n_qubit=5, period_1qb=30E-9, period_2qb=30E-9, sample_rate=1.2E9, n_pts=240E3, first_delay=100E-9, local_xy=True): # define parameters self.n_qubit = n_qubit self.period_1qb = period_1qb self.period_2qb = period_2qb self.local_xy = local_xy # waveform parameter self.sample_rate = sample_rate self.n_pts = n_pts self.first_delay = first_delay self.trim_to_sequence = True self.trim_start = False self.align_to_end = False # parameter for keeping track of current gate pulse time self.time_pulse = 0.0 # waveforms self.wave_xy = [np.zeros(0, dtype=np.complex) for n in range(MAX_QUBIT)] self.wave_z = [np.zeros(0) for n in range(MAX_QUBIT)] self.wave_gate = [np.zeros(0) for n in range(MAX_QUBIT)] # define pulses self.pulses_1qb = [Pulse() for n in range(MAX_QUBIT)] self.pulses_2qb = [Pulse() for n in range(MAX_QUBIT - 1)] # tomography self.perform_tomography = False self.tomography = Tomography() # cross-talk object self.compensate_crosstalk = False self.crosstalk = Crosstalk() # predistortion objects self.perform_predistortion = False self.predistortions = [Predistortion(n) for n in range(MAX_QUBIT)] # gate switch waveform self.generate_gate_switch = False self.uniform_gate = False self.gate_delay = 0.0 self.gate_overlap = 20E-9 self.minimal_gate_time = 20E-9 # readout trig settings self.generate_readout_trig = False self.readout_delay = 0.0 self.readout_amplitude = 1.0 self.readout_duration = 20E-9 # readout wave object and settings self.generate_readout_iq = False self.readout = Readout(max_qubit=MAX_QUBIT) self.readout_trig = np.array([], dtype=float) self.readout_iq = np.array([], dtype=np.complex)
def __init__(self, sz=270, fs=30, bs=30, size=256): print('init') self.stop = False self.masked_batches = [] self.batch_mean = [] self.signal_size = sz self.batch_size = bs self.signal = np.zeros((sz, 3)) self.pulse = Pulse(fs, sz, bs, size) self.hrs = [] self.save_results = True
def __init__(self, sz=270, fs=30, bs=30, save_key=None, size=256): print('init') self.stop = False self.masked_batches = [] self.batch_mean = [] self.signal_size = sz self.batch_size = bs self.signal = np.zeros((sz, 3)) self.pulse = Pulse(fs, sz, bs, size) self.hrs = [] self.save_key = save_key self.save_root = '/data2/datasets_origin/' self.save_results = True
def generate_readout(self): """Create read-out trig and waveform signals """ # get positon of readout if self.generate_readout_trig or self.generate_readout_iq: t = self.find_range_of_sequence()[1] + self.readout_delay # start with readout trig signal if self.generate_readout_trig: # create pulse object and insert into trig waveform trig = Pulse(amplitude=self.readout_amplitude, width=0.0, plateau=self.readout_duration, shape=PulseShape.SQUARE) self.add_single_pulse(self.readout_trig, trig, t, align_left=True) # readout I/Q waveform if self.generate_readout_iq: wave = self.readout.create_waveform(t) # if not matching wave sizes, simply replace initialized waveform if not self.readout.match_main_size: self.readout_iq = wave else: i0 = int(t * self.sample_rate) i1 = min(len(self.readout_iq), i0 + len(wave)) self.readout_iq[i0:i1] = wave[:(i1 - i0)]
def activate_pulse(self): if (self.pulse_charge >= 1.0) and (self.power > 0.1): if (engine.key.get_mods() & engine.KMOD_CTRL) or self.identity != 'Avatar': pulse_aim = self.pulse_aim else: pulse_aim = 'u' if pulse_aim == 'u': x = self.x y = self.y - (self.height / 2) if pulse_aim == 'd': x = self.x y = self.y + (self.height / 2) if pulse_aim == 'l': x = self.x - (self.width / 2) y = self.y if pulse_aim == 'r': x = self.x + (self.width / 2) y = self.y self.matrix.pulses.add( Pulse(self.matrix, x, y, pulse_aim, self.targets)) self.power -= 0.01 if env.sound: self.sound['pulse'].play() self.pulse_charge = 0.0
def init_db(): connection = SQLEngine.connect() context = MigrationContext.configure(connection) current_revision = context.get_current_revision() logger.boot('Database revision: %s', current_revision) if current_revision is None: DataBase.metadata.create_all(SQLEngine) config = Config(ALEMBIC_CONFIG) script = ScriptDirectory.from_config(config) head_revision = script.get_current_head() if current_revision is None or current_revision != head_revision: logger.boot('Upgrading database to version %s.', head_revision) command.upgrade(config, 'head') from option import Option session = Session() options = session.query(Option).first() if options is None: options = Option() options.version = head_revision session.add(options) from pulse import Pulse pulse = session.query(Pulse).first() if pulse is None: pulse = Pulse() session.add(pulse) session.commit()
def __init__(self): self.node_name = rospy.get_name() rospy.loginfo("[%s] Initializing " % (self.node_name)) self.config_path = rospy.get_param("~config_path") self.veh_name = rospy.get_param("~veh_name") self.ps = Pulse([5, 6, 13, 19]) self.fname = None self.v = 0 self.omega = 0 self.readParamFromFile() self.shutdown = False self.kRadius = self.setup_parameter('~kRadius', 8.5) self.kEncRes = self.setup_parameter('~kEncRes', 1024) self.kSmpTime = self.setup_parameter('~kSmpTime', 10) self.kMaxVel = self.setup_parameter('~kMaxVel', 40) self.updatekMaxPPMS() #Publisher self.pub_wheelcmd = rospy.Publisher("~wheel_cmd", WheelsCmdStamped, queue_size=1) #open new thread self.thread = threading.Thread(target=self.counter) self.thread.start() time.sleep(0.2) self.srv_kRadius = rospy.Service("~set_kRadius", SetValue, self.cbSrvSetkRadius) self.srv_kEncRes = rospy.Service("~set_kEncRes", SetValue, self.cbSrvSetkEncRes) self.srv_kSmpTime = rospy.Service('~set_kSmpTime', SetValue, self.cbSrvSetkSmpTime) self.srv_kMaxVel = rospy.Service('~set_kMaxVel', SetValue, self.cbSrvSetkMaxVel) self.srv_save_param = rospy.Service('~save_param', Empty, self.cbSrvSaveParam) #Subsriber self.sub_carcmd = rospy.Subscriber("~car_cmd", Twist2DStamped, self.cbCarcmd, queue_size=1)
def generate_sequence(self, config): """Generate sequence by adding gates/pulses to waveforms.""" pulse1 = Pulse(shape=PulseShape.SQUARE) pulse1.amplitude = config['Parameter #1'] pulse1.width = float(config['Number of points']) / float( config['Sample rate']) pulse3 = Pulse(shape=PulseShape.SQUARE) pulse3.amplitude = config['Parameter #1'] pulse3.width = config['Readout duration'] + float( config['Parameter #2']) self.add_gate_to_all(CustomGate(pulse1), t0=0) self.add_gate_to_all(Gate.Xp, dt=0) self.add_gate_to_all(CustomGate(pulse3), dt=0)
def __init__(self, ems, gui): super(ReachModel, self).__init__() self.verbose = config.getboolean('Reach Control', 'console_stats') self.brake_channel = config.get("Extra EMS Channels", "brake_active") self.ems = ems self.gui = gui self.left = Pulse(1) self.right = Pulse(2) self.penup = Pulse(3) self.brake = Pulse(4) self.last_index = 0 self.brake_zone = config.getint('Reach Control', 'brake_zone') self.fixed_delay = config.getfloat('Reach Control', 'fixed_delay') pulse_period = config.getfloat('EMS Machine', 'ems_period') self.reach_repetitions = int(self.fixed_delay / pulse_period) self.CONTROL_ON = False self.BRAKE_MODE = False """Establishes state transfer from execute_repetions """ self.stats = ReachStats()
def __init__(self, matrix, x, y): direction = 'd' targets = [matrix.avatars] if not self.images: self.images = {} color = (100, 100, 200) image = engine.Surface((22, 22), engine.SRCALPHA) points = [ (p[0] * 2, p[1] * 2) for p in [(5, 0), (9, 1), (10, 5), (9, 9), (5, 10), (1, 9), (0, 5), (1, 1)] ] engine.draw.polygon(image, color, points, 0) engine.draw.polygon(image, color, points, 1) self.images['hibit'] = image image = engine.Surface((22, 22), engine.SRCALPHA) points = [ (p[0] * 2, p[1] * 2) for p in [(5, 2), (7, 3), (8, 5), (7, 7), (5, 8), (3, 7), (2, 5), (3, 3)] ] engine.draw.polygon(image, color, points, 0) engine.draw.polygon(image, color, points, 1) self.images['lobit'] = image if self.masks is None: self.masks = {} self.masks['hibit'] = engine.mask.from_surface( self.images['hibit']) self.masks['lobit'] = engine.mask.from_surface( self.images['lobit']) self.radius = (image.get_width() // 2) Pulse.__init__(self, matrix, x, y, direction, targets) self.level = 0.5
def __init__(self, matrix, x, y): direction = 'd' targets = [matrix.avatars] if not self.images: self.images = {} color = (100,100,200) image = engine.Surface((22,22), engine.SRCALPHA) points = [(p[0]*2,p[1]*2) for p in [(5,0),(9,1),(10,5),(9,9),(5,10),(1,9),(0,5),(1,1)]] engine.draw.polygon(image, color, points, 0) engine.draw.polygon(image, color, points, 1) self.images['hibit'] = image image = engine.Surface((22,22), engine.SRCALPHA) points = [(p[0]*2,p[1]*2) for p in [(5,2),(7,3),(8,5),(7,7),(5,8),(3,7),(2,5),(3,3)]] engine.draw.polygon(image, color, points, 0) engine.draw.polygon(image, color, points, 1) self.images['lobit'] = image if self.masks is None: self.masks = {} self.masks['hibit'] = engine.mask.from_surface(self.images['hibit']) self.masks['lobit'] = engine.mask.from_surface(self.images['lobit']) self.radius = (image.get_width()//2) Pulse.__init__(self, matrix, x, y, direction, targets) self.level = 0.5
def generate_sequence(self, config): """Generate sequence by adding gates/pulses to waveforms""" frequency = config.get('Parameter #1') amplitude = config.get('Parameter #2') width = config.get('Parameter #3') plateau = config.get('Parameter #4') self.add_gate_to_all(Gate.Xp) pulse12 = Pulse() pulse12.truncation_range = 3 pulse12.width = width pulse12.plateau = plateau pulse12.amplitude = amplitude pulse12.frequency = frequency gate = CustomGate(pulse12) self.add_gate_to_all(gate)
def generate_sequence(self, config): """Generate sequence by adding gates/pulses to waveforms""" frequency = config.get('Parameter #1') amplitude = config.get('Parameter #2') width = config.get('Parameter #3') plateau = config.get('Parameter #4') shapeID=config.get('Parameter #5') # (0) gaussian, (1) cosine waitTime=config.get('Parameter #10') self.add_gate_to_all(Gate.Xp) pulse12 = Pulse() pulse12.width = width pulse12.plateau = plateau pulse12.amplitude = amplitude pulse12.frequency = frequency if shapeID==0: pulse12.shape=PulseShape.GAUSSIAN if shapeID==1: pulse12.shape=PulseShape.COSINE pulse12.pulse_type=PulseType.XY pulse12.phase = 0 gateP = CustomGate(pulse12) wait=Pulse() wait.shape=PulseShape.COSINE wait.width = 0 wait.plateau = waitTime wait.amplitude = 0 wait.frequency = 0 gateWait=CustomGate(wait) self.add_gate_to_all(gateP) self.add_gate_to_all(gateWait) self.add_gate_to_all(gateP)
# -*- coding: utf-8 -*- import numpy as np import matplotlib matplotlib.use("GTKAgg") from matplotlib import pyplot as plt import os import time from pulse import Pulse from koheron import connect host = os.getenv("HOST", "192.168.1.7") client = connect(host, name="pulse_generator") driver = Pulse(client) pulse_width = 128 n_pulse = 64 pulse_frequency = 1000 pulse_period = np.uint32(driver.fs / pulse_frequency) # Send Gaussian pulses to DACs t = np.arange(driver.n_pts) / driver.fs # time grid (s) driver.dac[0, :] = 0.6 * np.exp(-(t - 500e-9) ** 2 / (150e-9) ** 2) driver.dac[1, :] = 0.6 * np.exp(-(t - 500e-9) ** 2 / (150e-9) ** 2) driver.set_dac() driver.set_pulse_generator(pulse_width, pulse_period)
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib matplotlib.use('TKAgg') from matplotlib import pyplot as plt import os import time from pulse import Pulse from koheron import connect host = os.getenv('HOST', '192.168.1.7') client = connect(host, name='pulse-generator') driver = Pulse(client) pulse_width = 256 n_pulse = 64 pulse_frequency = 2000 pulse_period = np.uint32(driver.fs / pulse_frequency) # Send Gaussian pulses to DACs t = np.arange(driver.n_pts) / driver.fs # time grid (s) driver.dac[0,:] = 0.6 * np.exp(-(t - 500e-9)**2/(150e-9)**2) driver.dac[1,:] = 0.6 * np.exp(-(t - 500e-9)**2/(150e-9)**2) driver.set_dac() driver.set_pulse_width(pulse_width) driver.set_pulse_period(pulse_period)
#!/usr/bin/env python # -*- coding: utf-8 -*- import numpy as np import matplotlib matplotlib.use('GTKAgg') from matplotlib import pyplot as plt import os import time from pulse import Pulse from koheron import connect host = os.getenv('HOST', '192.168.1.7') client = connect(host, name='pulse-generator') driver = Pulse(client) pulse_width = 128 n_pulse = 64 pulse_frequency = 1000 pulse_period = np.uint32(driver.fs / pulse_frequency) # Send Gaussian pulses to DACs t = np.arange(driver.n_pts) / driver.fs # time grid (s) driver.dac[0,:] = 0.6 * np.exp(-(t - 500e-9)**2/(150e-9)**2) driver.dac[1,:] = 0.6 * np.exp(-(t - 500e-9)**2/(150e-9)**2) driver.set_dac() driver.set_pulse_width(pulse_width) driver.set_pulse_period(pulse_period)
from fiber import Fiber from pulse import Pulse #from fftw_transforms import fftcomputer as fftw #from scipy import fftpack plt.close('all') steps = 100 centerwl = 850.0 gamma = 0.045 fiber_length = 0.1 P0 = 10e3 T0 = 28.4e-3 init = Pulse(n = 2**13) init.gen_sech(P0, T0, centerwl) fiber1 = Fiber() fiber1.generate_fiber(fiber_length ,centerwl, [-1.276e-2, 8.119e-5, -1.321e-7, 3.032e-10, -4.196e-13, 2.570e-16], gamma, 0) evol = SSFM(disable_Raman = False, disable_self_steepening = False, local_error = 0.1, suppress_iteration = True) y = np.zeros(steps) AW = np.complex64(np.zeros((init.n, steps))) AT = np.complex64(np.copy(AW)) y, AW, AT, pulse1, = evol.Fiber_propagate(pulse_in = init, fiber = fiber1,
from fiber import Fiber from pulse import Pulse #from fftw_transforms import fftcomputer as fftw #from scipy import fftpack plt.close('all') steps = 100 centerwl = 850.0 gamma = 0.045 fiber_length = 0.1 P0 = 10e3 T0 = 28.4e-3 init = Pulse(n = 2**13) init.gen_sech(P0, T0, centerwl) fiber1 = Fiber() fiber1.generate_fiber(fiber_length ,centerwl, [-1.276e-2, 8.119e-5, -1.321e-7, 3.032e-10, -4.196e-13, 2.570e-16], gamma, 0) evol = SSFM(disable_Raman = False, disable_self_steepening = False, local_error = 0.1, suppress_iteration = True) y = np.zeros(steps) AW = np.complex64(np.zeros((init.n, steps))) AT = np.complex64(np.copy(AW)) y, AW, AT, pulse1, = evol.propagate(pulse_in = init, fiber = fiber1,
class ProcessMasks(): def __init__(self, sz=270, fs=30, bs=30, size=256): print('init') self.stop = False self.masked_batches = [] self.batch_mean = [] self.signal_size = sz self.batch_size = bs self.signal = np.zeros((sz, 3)) self.pulse = Pulse(fs, sz, bs, size) self.hrs = [] self.save_results = True def __call__(self, pipe, plot_pipe, source): self.pipe = pipe self.plot_pipe = plot_pipe self.source = source compute_mean_thread = Thread(target=self.compute_mean) compute_mean_thread.start() extract_signal_thread = Thread(target=self.extract_signal) extract_signal_thread.start() self.rec_frames() compute_mean_thread.join() extract_signal_thread.join() def rec_frames(self): while True and not self.stop: data = self.pipe.recv() if data is None: self.terminate() break batch = data[0] self.masked_batches.append(batch) def process_signal(self, batch_mean): size = self.signal.shape[0] b_size = batch_mean.shape[0] self.signal[0:size - b_size] = self.signal[b_size:size] self.signal[size - b_size:] = batch_mean p = self.pulse.get_pulse(self.signal) p = moving_avg(p, 6) self.p = p hr = self.pulse.get_rfft_hr(p) if len(self.hrs) > 3000: self.hrs.pop(0) self.hrs.append(hr) if self.plot_pipe is not None and self.stop: self.plot_pipe.send(None) elif self.plot_pipe is not None: self.plot_pipe.send([p, self.hrs]) else: hr_fft = moving_avg(self.hrs, 3)[-1] if len(self.hrs) > 5 else self.hrs[-1] sys.stdout.write(f'\rHr: {round(hr_fft, 0)}') sys.stdout.flush() def extract_signal(self): signal_extracted = 0 while True and not self.stop: if len(self.batch_mean) == 0: time.sleep(0.01) continue mean_dict = self.batch_mean.pop(0) mean = mean_dict['mean'] if mean_dict['face_detected'] == False: if self.plot_pipe is not None: self.plot_pipe.send('no face detected') continue if signal_extracted >= self.signal_size: self.process_signal(mean) else: self.signal[signal_extracted:signal_extracted + mean.shape[0]] = mean signal_extracted += mean.shape[0] def compute_mean(self): curr_batch_size = 0 batch = None while True and not self.stop: if len(self.masked_batches) == 0: time.sleep(0.01) continue mask = self.masked_batches.pop(0) if batch is None: batch = np.zeros((self.batch_size, mask.shape[0], mask.shape[1], mask.shape[2])) if curr_batch_size < (self.batch_size - 1): batch[curr_batch_size] = mask curr_batch_size += 1 continue batch[curr_batch_size] = mask curr_batch_size = 0 non_zero_pixels = (batch != 0).sum(axis=(1, 2)) total_pixels = batch.shape[1] * batch.shape[2] avg_skin_pixels = non_zero_pixels.mean() m = {'face_detected': True, 'mean': np.zeros((self.batch_size, 3))} if (avg_skin_pixels + 1) / (total_pixels) < 0.05: m['face_detected'] = False else: m['mean'] = np.true_divide(batch.sum(axis=(1, 2)), non_zero_pixels + 1e-6) self.batch_mean.append(m) def terminate(self): if self.plot_pipe is not None: self.plot_pipe.send(None) self.savePlot(self.source) self.saveresults() self.stop = True def saveresults(self): """ saves numpy array of heart rates as hrs saves numpy array of power spectrum as fft_spec """ np.save('hrs', np.array(self.hrs)) np.save('fft_spec', np.array(self.pulse.fft_spec)) # np.save('p', np.array(self.p)) # np.save('hr', np.array(self.hr)) def savePlot(self, path): if self.save_results == False: return # path = path.replace ('/media/munawar/','/munawar-desktop/') # fig_path = path[40:].replace("/","_") # file_path = path.replace('video.avi','gt_HR.csv') # gt_HR = pd.read_csv(file_path, index_col=False).values if len(self.hrs) == 0: return ax1 = plt.subplot(1, 1, 1) ax1.set_title('HR') ax1.set_ylim([20, 180]) ax1.plot(moving_avg(self.hrs, 6)) plt.tight_layout() plt.savefig(f'hr.png') plt.close() ax3 = plt.subplot(1, 2, 2) ax3.set_title('GT') ax3.set_ylim([20, 180]) ax3.plot(self.pulse.fft_spec) plt.tight_layout() plt.savefig(f'results.png') plt.close()
import matplotlib.pyplot as plt from SSFM import SSFM from fiber import Fiber from pulse import Pulse plt.close('all') dz = 1e-3 steps = 500 range1 = np.arange(steps) centerwl = 835.0 fiber_length = 0.15 init = Pulse(n = 2**13) init.gen_sech(1e4, 28.4e-3, centerwl) fiber1 = Fiber() fiber1.load_from_db( fiber_length, 'dudley') evoladv = SSFM(dz = 1e-6, local_error = 0.001, USE_SIMPLE_RAMAN = False) yadv = np.zeros(steps) AWadv = np.zeros((init.n, steps)) ATadv = np.copy(AWadv) yadv, AWadv, ATadv, pulse1adv = evoladv.propagate(pulse_in = init, fiber = fiber1, n_steps = steps) evolsimp = SSFM(dz = 1e-6, local_error = 0.001, USE_SIMPLE_RAMAN = True)
fiber1 = Fiber() steps = 250 centerwl = 1550.0 gamma = 2e-3 fiber_length = 100.0 T0 = 50e-3 D = 4 # ps / km / nm beta2 = -2 * np.pi * fiber1.c / centerwl**2 * D beta3 = 0.1 betas = [beta2, beta3] print betas P0 = abs(betas[0] * 1e-3) / gamma / T0**2 init = Pulse(n = 2**14) init.gen_sech(P0, T0, centerwl, time_window=25) fiber1.generate_fiber(fiber_length, centerwl, betas, gamma, 0, "ps^n/km") evol = SSFM(disable_Raman = False, disable_self_steepening = False, local_error = 0.001, suppress_iteration = True, USE_SIMPLE_RAMAN = True) y = np.zeros(steps) AW = np.complex64(np.zeros((init.n, steps))) AT = np.complex64(np.copy(AW)) wl = 2 * np.pi * init.c / (init.W) shift = np.zeros((len(y), 3)) fwhm = np.copy(shift) chirps = np.array([0.0])*-1
def on_pulse(self, p: pulse.Pulse) -> Sequence[pulse.Pulse]: p.move() return [p]
fiber1 = Fiber() steps = 250 centerwl = 1550.0 gamma = 2e-3 fiber_length = 100.0 T0 = 50e-3 D = 4 # ps / km / nm beta2 = -2 * np.pi * fiber1.c / centerwl**2 * D beta3 = 0.1 betas = [beta2, beta3] print betas P0 = abs(betas[0] * 1e-3) / gamma / T0**2 init = Pulse(n=2**14) init.gen_sech(P0, T0, centerwl, time_window=25) fiber1.generate_fiber(fiber_length, centerwl, betas, gamma, 0, "ps^n/km") evol = SSFM(disable_Raman=False, disable_self_steepening=False, local_error=0.001, suppress_iteration=True, USE_SIMPLE_RAMAN=True) y = np.zeros(steps) AW = np.complex64(np.zeros((init.n, steps))) AT = np.complex64(np.copy(AW)) wl = 2 * np.pi * init.c / (init.W) shift = np.zeros((len(y), 3))
class ReachModel(object): """Reach model instructs left and right pulse objects. Pulse objects are orchestrated according to the new reach model. """ def __init__(self, ems, gui): super(ReachModel, self).__init__() self.verbose = config.getboolean('Reach Control', 'console_stats') self.brake_channel = config.get("Extra EMS Channels", "brake_active") self.ems = ems self.gui = gui self.left = Pulse(1) self.right = Pulse(2) self.penup = Pulse(3) self.brake = Pulse(4) self.last_index = 0 self.brake_zone = config.getint('Reach Control', 'brake_zone') self.fixed_delay = config.getfloat('Reach Control', 'fixed_delay') pulse_period = config.getfloat('EMS Machine', 'ems_period') self.reach_repetitions = int(self.fixed_delay / pulse_period) self.CONTROL_ON = False self.BRAKE_MODE = False """Establishes state transfer from execute_repetions """ self.stats = ReachStats() def create_target(self, canvas): self.target = Target(canvas) self.gui.draw_targets(canvas.target_points) def get_ready_for_next_one(self): self.last_index = 0 self.stats = ReachStats() def start_control(self): """Waits for the suitable time to start the control strategies. """ self.CONTROL_ON = True while self.CONTROL_ON: plot_state = self._control_repetions() if plot_state == 'done': print('PLOT: ended') for i in range(50): self.ems.pulsate(self.penup) print('ACTION: Pen Up') break elif (plot_state == 'no sample' or plot_state == 'no target' or plot_state == 'nudged'): time.sleep(self.fixed_delay / 2) def end_control(self): self.CONTROL_ON = False def restart_plot(self): self.end_control() time.sleep(self.fixed_delay * 2) self.last_index = 0 self.stats = ReachStats(self.config) self.result.refresh_for_next() def terminate_control(self): self.end_control() time.sleep(self.fixed_delay * 2) self.stats.pause_timer() duration = self.stats.total_time print('PLOT: Duration {0:5.1f} seconds.'.format(duration)) # save to file: duration self.stats.print_timing_analysis() self.ems.print_timing_analysis() def handle_penup(self): self.left.end_boost() self.right.end_boost() self.stats.reset_for_pen_up() def project_speed_to_tilted_axis(self, speed): if speed[0] == 0: return (0, 0) speed_vector_theata = atan(speed[1] / speed[0]) speed_vector_amp = ((speed[0]**2) + (speed[1]**2))**0.5 axis_tilt = radians(-1 * self.target.canvas.major_axis_tilt) tilted_vector_theata = speed_vector_theata - axis_tilt projected_x = cos(tilted_vector_theata) * speed_vector_amp projected_y = sin(tilted_vector_theata) * speed_vector_amp return (projected_x, projected_y) def _control_repetions(self): """Using speed and location calculate target and distance. Determine required reach repetions based on parameters and execute accordingly. """ if not self.ems.EMS_ON: return 'no sample' current_stats = self.stats.get_last() if not current_stats: return 'no sample' location, speed = current_stats tilted_speed = self.project_speed_to_tilted_axis(speed) target_params = self.target.get_target_slope(location, speed) if target_params == 'done': return 'done' elif target_params == 'nudge': self._execute_nudge() return 'nudged' elif target_params: self.stats.star_timer() estimate, target, target_slope = target_params else: return 'no target' if len(self.stats.decisions) == 0: target_slope = 0 if len(self.stats.decisions) == 1: if abs(target_slope) > 0.3: if target_slope > 0: target_slope = 0.3 elif target_slope < 0: target_slope = -0.3 slope_code = self.left.target_slope(target_slope) slope_code = self.right.target_slope(target_slope) self.stats.register_decision(location, estimate, target) nodes = self.stats.get_targeting() self.gui.draw_targeting_nodes(nodes) result = self.stats.analyze_distance_to_target() brake_repetions = 0 if not result: pass elif self.BRAKE_MODE: result = 'brake' self.left.end_boost() self.right.end_boost() brake_repetions = remap_speed_to_brake(abs(tilted_speed[1])) self.left.apply_brake() self.right.apply_brake() elif result > 0: if not self.target.canvas.no_boost: self.right.boost_amp() self.left.end_boost() elif result < 0: if not self.target.canvas.no_boost: self.left.boost_amp() self.right.end_boost() else: self.left.end_boost() self.right.end_boost() # index for decisions to anoto events index = len(self.stats.events) samples_between = index - self.last_index self.last_index = index if self.verbose: print(' {0:3d}#'.format(len(self.stats.decisions)), end='') print(' Slope: {0:6.1f}'.format(target_slope), end='') indicator = str(int(1000 * 10**-slope_code)).zfill(7) print(' |{0:3}| '.format(indicator), end='') print('L: {0:2} '.format(self.left.boost_indicator()), end='') print('R: {0:2} '.format(self.right.boost_indicator()), end='') print(' Brake: {0:2}'.format(brake_repetions), end='') print(' Anoto: {0:2d}'.format(samples_between)) if result == 'brake': self._execute_repetions(brake_repetions, mode='brake') else: self._execute_repetions(self.reach_repetitions, mode='travel') def _execute_repetions(self, cycles, mode): """Pulsates and observes current way to the target. """ for cycle in range(cycles): if not self.ems.EMS_ON: return if not mode == 'brake' or not self.brake_channel: self.ems.pulsate(self.left, self.right) elif self.brake_channel: self.ems.pulsate(self.brake) distances = self.stats.get_distance_to_target() if distances: distance, _, _ = distances if mode == 'brake': last_speed = self.stats.speed[-1] tilted_speed = self.project_speed_to_tilted_axis(last_speed) if (abs(tilted_speed[1]) < 0.1 and not cycles == self.reach_repetitions): print('BRAKE: ended') self.BRAKE_MODE = False return elif mode == 'travel': if self.stats.check_target_crossing(): self.BRAKE_MODE = True print('TRAVEL: ended') return if self.BRAKE_MODE: self.BRAKE_MODE = False def _execute_nudge(self): repeat = 9 print('NUDGE: nudging') self.left.target_slope(20) for i in range(repeat): self.ems.pulsate(self.left) self.right.target_slope(20) for i in range(repeat): self.ems.pulsate(self.right)
process[j] = Process(target=srf.init_kernel, args=(kernel, arr[j], X0[j], Y0[j], host_constants)) process[j].start() data_p = pd.Series(dtype='object') data_m = pd.Series(dtype='object') fig_p, ax_p = plt.subplots() fig_m, ax_m = plt.subplots() for i in range(len(kernels)): # wait until process funished process[i].join() surf = arr[i] x = X0[i] y = Y0[i] pulse = Pulse(surf, x, y, const) # Calculate Probality Dencity Function of mirrored dots Z, W, f = pulse.pdf(surf) P = np.zeros(T.size) # Calculate impulse form for j in range(T.size): P[j] += pulse.power1(T[j]) ax_p.plot(T, P, label=labels[i]) dT = pd.Series(T - z0 / c, name='t_%s' % (labels[i])) dP = pd.Series(P / P.max(), name='P_%s' % (labels[i])) data_p = pd.concat([data_p, dT, dP], axis=1) Z = pd.Series(Z, name='Z_%s' % (labels[i])) W = pd.Series(W, name='W_%s' % (labels[i]))
class AgvWheelDriverNode(object): def __init__(self): self.node_name = rospy.get_name() rospy.loginfo("[%s] Initializing " % (self.node_name)) self.config_path = rospy.get_param("~config_path") self.veh_name = rospy.get_param("~veh_name") self.ps = Pulse([5, 6, 13, 19]) self.fname = None self.v = 0 self.omega = 0 self.readParamFromFile() self.shutdown = False self.kRadius = self.setup_parameter('~kRadius', 8.5) self.kEncRes = self.setup_parameter('~kEncRes', 1024) self.kSmpTime = self.setup_parameter('~kSmpTime', 10) self.kMaxVel = self.setup_parameter('~kMaxVel', 40) self.updatekMaxPPMS() #Publisher self.pub_wheelcmd = rospy.Publisher("~wheel_cmd", WheelsCmdStamped, queue_size=1) #open new thread rospy.Timer(rospy.Duration(0.2), self.threadSetSpeed) time.sleep(0.2) self.srv_kRadius = rospy.Service("~set_kRadius", SetValue, self.cbSrvSetkRadius) self.srv_kEncRes = rospy.Service("~set_kEncRes", SetValue, self.cbSrvSetkEncRes) self.srv_kSmpTime = rospy.Service('~set_kSmpTime', SetValue, self.cbSrvSetkSmpTime) self.srv_kMaxVel = rospy.Service('~set_kMaxVel', SetValue, self.cbSrvSetkMaxVel) self.srv_save_param = rospy.Service('~save_param', Empty, self.cbSrvSaveParam) #Subsriber self.sub_carcmd = rospy.Subscriber("~car_cmd", Twist2DStamped, self.cbCarcmd, queue_size=1) def threadSetSpeed(self, event): #rospy.loginfo("[%s] Set speed " %(self.node_name)) left = int(-(self.v + self.omega) * self.kMaxPPMS) right = int((self.v - self.omega) * self.kMaxPPMS) self.ps.set_speed([left, right]) wheelcmd = WheelsCmdStamped() wheelcmd.header.stamp = rospy.Time.now() wheelcmd.vel_left = -left wheelcmd.vel_right = right self.pub_wheelcmd.publish(wheelcmd) def cbCarcmd(self, msg): rospy.loginfo("velocity: [%f] omega: [%f] source: [%d]" % (msg.v, msg.omega, msg.source)) self.v = msg.v self.omega = msg.omega def readParamFromFile(self): #check the file fname_ = self.config_path + self.veh_name + ".yaml" self.fname = fname_ if not os.path.isfile(fname_): rospy.logwarn("[%s] %s does not exist. Using default.yaml." % (self.node_name, fname_)) fname_ = self.config_path + "default.yaml" with open(fname_, 'r') as in_file: try: yaml_ = yaml.load(in_file) except yaml.YAMLError as exc: rospy.logfatal( "[%s] YAML syntax error. File: %s fname. Exc: %s" % (self.node_name, fname_, exc)) rospy.signal_shutdown() return if yaml_ is None: return for param_name in ["kRadius", "kEncRes", "kSmpTime", "kMaxVel"]: value = yaml_.get(param_name) if param_name is not None: rospy.set_param("~" + param_name, value) def cbSrvSaveParam(self, req): data = { "kRadius": self.kRadius, "kEncRes": self.kEncRes, "kSmpTime": self.kSmpTime, "kMaxVel": self.kMaxVel, } fname_ = self.fname with open(fname_, "w") as out_file: out_file.write(yaml.dump(data, default_flow_style=False)) self.printValues() rospy.loginfo("[%s] Saved to %s" % (self.node_name, fname_)) return EmptyResponse() def cbSrvSetkRadius(self, req): self.kRadius = req.value self.updatekMaxPPMS() return SetValueResponse() def cbSrvSetkEncRes(self, req): self.kEncRes = req.value self.updatekMaxPPMS() return SetValueResponse() def cbSrvSetkSmpTime(self, req): self.kSmpTime = req.value self.updatekMaxPPMS() self.ps.updatekSmpTime(self.kSmpTime) return SetValueResponse() def cbSrvSetkMaxVel(self, req): self.kMaxVel = req.value self.updatekMaxPPMS() return SetValueResponse() def updatekMaxPPMS(self): self.kMaxPPMS = self.kMaxVel * self.kSmpTime / 36.0 / ( 2 * math.pi * self.kRadius) * self.kEncRes self.ps.updatekMaxPPMS(self.kMaxPPMS) self.printValues() def printValues(self): rospy.loginfo( "[%s] kRadius: %s kEncRes: %s kSmpTime: %s kMaxVel: %s kMaxPPMS: %s" % (self.node_name, self.kRadius, self.kEncRes, self.kSmpTime, self.kMaxVel, self.kMaxPPMS)) def setup_parameter(self, param_name, default_value): value = rospy.get_param(param_name, default_value) rospy.set_param(param_name, value) rospy.loginfo("[%s] %s = %s" % (self.node_name, param_name, value)) return value def onShutdown(self): self.shutdown = True rospy.loginfo('[%s] Closing Control Node.' % (self.node_name)) self.is_shutdown = True rospy.loginfo("[%s] Shutdown." % (self.node_name))
kernel_ku[blockspergrid, threadsperblock](band_ku, x, y, k, offset, phi, A, F, psi) x0 = x0 - offsetx y0 = y0 - offsety z0 = 3e6 c = 3e8 omega = 2 * np.pi * 12e9 k = omega / c timp = 3e-9 T0 = z0 / c T = np.linspace(T0 - timp, np.sqrt(z0**2 + Xmax**2) / c, 200) P = np.zeros(T.size) pulse = Pulse(band_c, 'C', x0, y0, [0, 0, z0], timp=timp) theta0_c = pulse.main() theta0_c = theta0_c.reshape((x.size, y.size)) pulse = Pulse(band_ku, 'Ku', x0, y0, [0, 0, z0], timp=timp) theta0_ku = pulse.main() theta0_ku = theta0_c.reshape((x.size, y.size)) data.export(x0, y0, surface, ku_band=band_ku, c_band=band_c, theta0_c=theta0_c, theta0_ku=theta0_ku) # print(surface.U10)
p.set_parameters(config) # crosstalk self.compensate_crosstalk = config.get('Compensate cross-talk', False) self.crosstalk.set_parameters(config) # gate switch waveform self.generate_gate_switch = config.get('Generate gate') self.uniform_gate = config.get('Uniform gate') self.gate_delay = config.get('Gate delay') self.gate_overlap = config.get('Gate overlap') self.minimal_gate_time = config.get('Minimal gate time') # readout, trig settings self.generate_readout_trig = config.get('Generate readout trig') self.readout_delay = config.get('Readout delay') self.readout_amplitude = config.get('Readout trig amplitude') self.readout_duration = config.get('Readout trig duration') self.iq_skew = config.get('Readout IQ skew') self.i_offset = config.get('Readout offset - I') self.q_offset = config.get('Readout offset - Q') # readout, wave settings self.generate_readout_iq = config.get('Generate readout waveform') self.readout.set_parameters(config) if __name__ == '__main__': pass Pulse()
def generate_sequence(self, config): """Generate sequence by adding gates/pulses to waveforms""" frequency = config.get('Parameter #1') amplitude = config.get('Parameter #2') width = config.get('Parameter #3') plateau = config.get('Parameter #4') drag_coeff = config.get('Parameter #5') #(drag coefficient) shapeID = config.get('Parameter #6') # (0) gaussian, (1) cosine pulse_train = config.get( 'Parameter #7' ) #yes (1) or no (0) for multiple alternate pulses for optimizing drag and Pi pulse N_pulses = config.get('Parameter #8') #ignored if pulse_train == 0 self.add_gate_to_all(Gate.Xp) pulse12 = Pulse() pulse12n = Pulse() pulse12.width = width pulse12n.width = width pulse12.plateau = plateau pulse12n.plateau = plateau pulse12.amplitude = amplitude pulse12n.amplitude = amplitude pulse12.frequency = frequency pulse12n.frequency = frequency if shapeID == 0: pulse12.shape = PulseShape.GAUSSIAN pulse12n.shape = PulseShape.GAUSSIAN if shapeID == 1: pulse12.shape = PulseShape.COSINE pulse12n.shape = PulseShape.COSINE pulse12.use_drag = True pulse12n.use_drag = True pulse12.drag_coefficient = drag_coeff pulse12n.drag_coefficient = drag_coeff pulse12.pulse_type = PulseType.XY pulse12n.pulse_type = PulseType.XY pulse12.phase = 0 pulse12n.phase = -np.pi gateP = CustomGate(pulse12) gateN = CustomGate(pulse12n) if pulse_train: for i in range(int(N_pulses)): if ((i % 2) == 0): self.add_gate_to_all(gateP) else: self.add_gate_to_all(gateN) else: self.add_gate_to_all(gateP)
timp = 40e-6 T0 = z0 / c T = np.linspace(0.0199, np.sqrt(z0**2 + Xmax**2) / c, 256) count = 0 while count < 100: x0 = np.random.uniform(-Xmax, Xmax, size=25) y0 = np.random.uniform(-Xmax, Xmax, size=25) x, y = np.meshgrid(x0, y0) band_c, band_ku = surface.surfaces_band([x, y], 0) pulse = Pulse(band_ku, 'Ku', x0, y0, [0, 0, z0], timp=timp, c=c, projection='polar') theta0 = pulse.main() index = pulse.index[0] count += index.size print(count) P = np.zeros(T.size) for i in range(T.size): P[i] += pulse.power(T[i], omega, timp, pulse.Rabs, pulse.theta) plt.ion() plt.clf() plt.plot(T, P)
xmax = 500 gridsize = 250 x0 = np.linspace(-xmax, xmax, gridsize) y0 = np.linspace(-xmax, xmax, gridsize) z0 = 1e3 x, y = np.meshgrid(x0, y0) phi0 = np.linspace(0, 2 * np.pi, gridsize) r0 = np.linspace(0, xmax, gridsize) phi, r = np.meshgrid(phi0, r0) surface = [np.zeros(x.size), np.zeros(x.size), np.zeros(x.size)] pulse = Pulse(surface, 'Ku', x=x0, y=y0, r0=[0, 0, z0]) theta0 = pulse.main() plt.figure() plt.contourf(x, y, theta0.reshape(x.shape)) plt.colorbar() fig, ax = plt.subplots(subplot_kw=dict(projection='polar')) pulse = Pulse(surface, 'Ku', x=r * np.cos(phi), y=r * np.sin(phi), r0=[0, 0, z0]) theta0 = pulse.main() im = ax.contourf(phi, r, theta0.reshape(x.shape)) fig.colorbar(im)
class ProcessRppg(): def __init__(self, sz=270, fs=25, bs=30, save_key=None, size=256): print('init') self.stop = False self.masked_batches = [] self.batch_mean = [] self.signal_size = sz self.batch_size = bs self.signal = np.zeros((sz, 3)) self.pulse = Pulse(fs, sz, bs, size) self.hrs = [] self.save_key = save_key self.save_root = '/data2/datasets_origin/' self.save_result = True self.signal_extracted = 0 self.curr_batch_size = 0 self.batch = None def __call__(self, data): self.rec_frames(data) def rec_frames(self, data): batch = data[0] self.masked_batches.append(batch) self.compute_mean() self.extract_signal() def process_signal(self, batch_mean): size = self.signal.shape[0] b_size = batch_mean.shape[0] self.signal[0:size - b_size] = self.signal[b_size:size] self.signal[size - b_size:] = batch_mean p = self.pulse.get_pulse(self.signal) p = moving_avg(p, 6) hr = self.pulse.get_rfft_hr(p) if len(self.hrs) > 300: self.hrs.pop(0) self.hrs.append(hr) # if self.plot_pipe is not None and self.stop: # self.plot_pipe.send(None) # elif self.plot_pipe is not None: # self.plot_pipe.send([p, self.hrs]) # else: # hr_fft = moving_avg(self.hrs, 3)[-1] if len(self.hrs) > 5 else self.hrs[-1] # sys.stdout.write(f'\rHr: {round(hr_fft, 0)}') # sys.stdout.flush() def extract_signal(self): if len(self.batch_mean) == 0: return mean_dict = self.batch_mean.pop(0) mean = mean_dict['mean'] if mean_dict['face_detected'] == False: # if self.plot_pipe is not None: # self.plot_pipe.send('no face detected') return if self.signal_extracted >= self.signal_size: self.process_signal(mean) else: self.signal[self.signal_extracted:self.signal_extracted + mean.shape[0]] = mean self.signal_extracted += mean.shape[0] def compute_mean(self): if len(self.masked_batches) == 0: return mask = self.masked_batches.pop(0) if self.batch is None: self.batch = np.zeros( (self.batch_size, mask.shape[0], mask.shape[1], mask.shape[2])) if self.curr_batch_size < (self.batch_size - 1): self.batch[self.curr_batch_size] = mask self.curr_batch_size += 1 return self.batch[self.curr_batch_size] = mask self.curr_batch_size = 0 non_zero_pixels = (self.batch != 0).sum(axis=(1, 2)) total_pixels = self.batch.shape[1] * self.batch.shape[2] avg_skin_pixels = non_zero_pixels.mean() m = {'face_detected': True, 'mean': np.zeros((self.batch_size, 3))} if (avg_skin_pixels + 1) / (total_pixels) < 0.005: m['face_detected'] = False else: m['mean'] = np.true_divide(self.batch.sum(axis=(1, 2)), non_zero_pixels + 1e-6) self.batch_mean.append(m) def terminate(self): if self.plot_pipe is not None: self.plot_pipe.send(None) self.savePlot(self.source) self.saveresults() self.stop = True def saveresults(self): """ saves numpy array of heart rates as hrs saves numpy array of power spectrum as fft_spec """ if len(self.pulse.fft_spec) > 0: if self.save_key is not None: det_save_key = self.save_key else: det_save_key = './' save_path = os.path.join(self.save_root, det_save_key) if not os.path.exists(save_path): os.makedirs(save_path) fft_path = os.path.join(save_path, 'fft_spec') # np.save('hrs', np.array(self.hrs)) np.save(fft_path, np.array(self.pulse.fft_spec)) def savePlot(self, path): if self.save_result == False: return # path = path.replace ('/media/munawar/','/munawar-desktop/') # fig_path = path[40:].replace("/","_") # file_path = path.replace('video.avi','gt_HR.csv') # gt_HR = pd.read_csv(file_path, index_col=False).values if len(self.hrs) == 0: return ax1 = plt.subplot(1, 1, 1) ax1.set_title('HR') ax1.set_ylim([20, 180]) ax1.plot(moving_avg(self.hrs, 6)) # ax3 = plt.subplot(1,2,2) # ax3.set_title('GT') # ax3.set_ylim([20, 180]) # ax3.plot(gt_HR[8:]) plt.tight_layout() plt.savefig(f'results.png') plt.close()