def __init__(self, root, subplots, title=''): ttk.Frame.__init__(self, root) self.signal_mouse_press = Signal() self.signal_mouse_release = Signal() self._fig = Figure() self._subplots = [] self._canvas = FigureCanvas(self._fig, self) self._canvas.get_tk_widget().pack(expand=tk.YES, fill=tk.BOTH) self._canvas.mpl_connect('button_press_event', self.signal_mouse_press) self._canvas.mpl_connect('button_release_event', self.signal_mouse_release) toolbar = NavigationToolbar2Tk(self._canvas, self) toolbar.update() num_rows = len(subplots) num_columns = max(len(graphs) for graphs in subplots) for i in range(num_rows): for j in range(num_columns): subplot = subplots[i][j] if subplot is not None: index = (i * num_columns) + j + 1 ax = self._fig.add_subplot(num_rows, num_columns, index) subplot.set_axis(ax) self._subplots.append(subplot) self._fig.suptitle(title, fontweight='bold', fontsize=self.DEFAULT_TITLE_SIZE) self._fig.subplots_adjust(hspace=.6, wspace=.3)
def __init__(self, text, action, pos=(0, 0), size=(100, 40)): super(Button, self).__init__(pos, size) self.click = Signal() self.unclick = Signal() self.font = Font('Arial') self.bgcolor = (110, 110, 110, 255) self.hmargin = 5 self.vmargin = 5 self.pressed = False self.label = Label(text, self.font) self.label.resize((self.width - 2 * self.hmargin, self.height - 2 * self.vmargin)) self.label.move_to(self.pos) self.label.move((self.hmargin, self.vmargin)) self.queue.add(self.label) self.click.connect(self._clicked) self.unclick.connect(self._unclicked) self.click.connect(action)
class TasklistEvents(sublime_plugin.EventListener): def filter_events(mth): from functools import wraps @wraps(mth) def wrapped(self, view): if view.window() and view.file_name(): return mth(self, view) return wrapped loaded = Signal() @filter_events def on_load(self, view): self.loaded(view) closed = Signal() @filter_events def on_close(self, view): self.closed(view) activated = Signal() @filter_events def on_activated(self, view): self.activated(view)
def __init__(self, parent=None, **kwargs): ttk.Frame.__init__(self, parent) self.signal_delete = Signal() self.signal_up = Signal() self.signal_down = Signal() self.signal_select = Signal() frm = ttk.Frame(self) self.lbox = tk.Listbox(frm, selectmode=tk.SINGLE, **kwargs) self.sbar = ttk.Scrollbar(frm) self.hsbar = ttk.Scrollbar(self, orient=tk.HORIZONTAL) self.hsbar.config(command=self.lbox.xview) self.sbar.config(command=self.lbox.yview) self.lbox.config(xscrollcommand=self.hsbar.set) self.lbox.config(yscrollcommand=self.sbar.set) self.lbox.config(selectmode=tk.SINGLE) self.sbar.pack(side=tk.RIGHT, fill=tk.Y) self.hsbar.pack(side=tk.BOTTOM, fill=tk.X) self.lbox.pack(side=tk.LEFT, expand=tk.YES, fill=tk.BOTH) frm.pack(expand=tk.YES, fill=tk.BOTH) self.lbox.bind( '<Delete>', lambda event: self.signal_delete() if self.lbox.size() >= 1 else None) self.lbox.bind('<Button-1>', lambda event: self.after(20, self._click)) self.lbox.bind('<Up>', lambda event: self.signal_up()) self.lbox.bind('<Down>', lambda event: self.signal_down())
def get_imag_test_signal(show=True): w = 2 * np.pi * np.array([-0.4, -0.26, -0.18, -0.1, 0.15, 0.36]) alpha = np.array([1.83, 1.87, 1.65, 1.55, 1.12, 1.1]) y = generate_signal(w=w, sigma_n=0.5) sig = Signal(y=y, n=len(w), w=w, alpha=alpha, sigma_n=0.5) sig.plot_spectar(plt) if show else None return sig
def get_real_test_signal(show=True): w = 2 * np.pi * np.array([-0.4, -0.2, -0.15, 0, 0.15, 0.2, 0.4]) alpha = np.array([1, 0.7, 1.2, 0.5, 1.2, 0.7, 1]) y = generate_signal(w=w, alpha=alpha, sigma_n=1) sig = Signal(y=y, n=len(w), w=w, alpha=alpha, sigma_n=1) sig.plot_spectar(plt) if show else None return sig
def test_get_frequencies_valid_signal(self): cosine_signal = Signal.generate_cosine(4, 60) cosine_frequencies = cosine_signal.get_frequencies() self.assertTrue(cosine_frequencies.size == 240) random_signal = Signal.generate_random(2, 100) random_frequencies = random_signal.get_frequencies() self.assertTrue(random_frequencies.size == 200)
def get_signal_with_large_n(show=True): n = 50 w = 2 * np.pi * (np.arange(n) / n - 0.5) alpha = np.random.uniform(low=0.1, high=2, size=(n, )) y = generate_signal(w=w, alpha=alpha, sigma_n=1, N=400) sig = Signal(y=y, n=n, w=w, alpha=alpha, sigma_n=1) sig.plot_spectar(plt) if show else None return sig
def test_get_frequencies_invalid_signal(self): empty_signal = Signal() with self.assertRaises(TypeError): empty_signal.get_frequencies() with self.assertRaises(ValueError): empty_signal.signal = np.array([]) empty_signal.get_frequencies() with self.assertRaises(TypeError): empty_signal.signal = 1 empty_signal.get_frequencies()
def test_re_discretise_signal_valid_signal_up_sample(self): random_signal = Signal.generate_random(2, 60) cosine_signal = Signal.generate_cosine(3, 60) random_resampled, cosine_resampled = random_signal.get_re_discretised_signal( cosine_signal) self.assertEqual(len(cosine_resampled), 180) self.assertEqual(len(random_resampled), len(cosine_resampled)) self.assertFalse(np.array_equal(random_signal.signal, random_resampled)) self.assertTrue(np.array_equal(cosine_signal.signal, cosine_resampled))
def test_re_discretise_signal_valid_signal_down_sample(self): random_signal = Signal.generate_random(2, 60) cosine_signal = Signal.generate_cosine(3, 60) random_resampled, cosine_resampled = random_signal.get_re_discretised_signal( cosine_signal, ResamplingType.DOWN_SAMPLE) self.assertEqual(len(cosine_resampled), 120) self.assertEqual(len(random_resampled), len(cosine_resampled)) self.assertTrue(np.array_equal(random_signal.signal, random_resampled)) self.assertFalse(np.array_equal(cosine_signal.signal, cosine_resampled))
def test_generate_cosine_invalid_sample_time(self): with self.assertRaises(ValueError): Signal.generate_cosine(0, 60) with self.assertRaises(ValueError): Signal.generate_cosine(-2, 60) with self.assertRaises(TypeError): Signal.generate_cosine(2.0, 60) with self.assertRaises(TypeError): Signal.generate_cosine(None, 60) with self.assertRaises(TypeError): Signal.generate_cosine("I shouldn't be a string", 60)
def test_generate_cosine_invalid_sampling_rate(self): with self.assertRaises(ValueError): Signal.generate_cosine(2, -60) with self.assertRaises(ValueError): Signal.generate_cosine(2, 0) with self.assertRaises(TypeError): Signal.generate_cosine(2, 60.0) with self.assertRaises(TypeError): Signal.generate_cosine(2, None) with self.assertRaises(TypeError): Signal.generate_cosine(2, "I shouldn't be a string either")
def ReInitUI(self): if self.layoutData is None: return if 'layoutName' in self.layoutData: self.SetTitle(self.layoutData['layoutName']) if "gridOn" in self.layoutData.keys(): if 1 == self.layoutData['gridOn']: self.gridOn = True if "fastClockAddress" in self.layoutData.keys(): self.fcAddress = int(str(self.layoutData['fastClockAddress']), 0) for text in self.layoutData['text']: newCell = TextCell() newCell.setText(text['value']) x = int(text['x']) y = int(text['y']) newCell.setXY(x, y) if text['type'] == 'blockname': newCell.setColor('#ccffff') self.cells.append(newCell) for signalconfig in self.layoutData['signals']: newSignal = Signal(signalconfig, self.txPacket) self.signals.append(newSignal) self.cells = self.cells + newSignal.getCells() self.clickables[newSignal.getClickXY()] = newSignal.onLeftClick for switchconfig in self.layoutData['switches']: newSwitch = Switch(switchconfig, self.txPacket) self.switches.append(newSwitch) self.cells = self.cells + newSwitch.getCells() self.clickables[newSwitch.getClickXY()] = newSwitch.onLeftClick for blockconfig in self.layoutData['blocks']: newBlock = Block(blockconfig, self.txPacket, self.cellXY) self.blocks.append(newBlock) self.cells = self.cells + newBlock.getCells() for cell in self.cells: # Build a cell finder self.cellXY[(cell.cell_x, cell.cell_y)] = cell for cpconfig in self.layoutData['controlPoints']: if cpconfig['type'] == 'cp3': newCP = ControlPoint_CP3(cpconfig, self.txPacket, self.getRailroadObject) else: newCP = ControlPoint(cpconfig, self.txPacket, self.getRailroadObject) self.controlpoints.append(newCP)
def create_signals(self, inputs, outputs): # This took way to long to perfect... for i in range(self.height): if i % (self.height // (inputs + 1)) == 0 and i != 0 and len( self.inputs) < inputs: self.inputs.append( Signal(self.pos.x, self.pos.y + i, constants.CHIP_SIGNAL_RADIUS)) if i % (self.height // (outputs + 1)) == 0 and i != 0 and len( self.outputs) < outputs: self.outputs.append( Signal(self.pos.x + self.width, self.pos.y + i, constants.CHIP_SIGNAL_RADIUS))
def test_re_discretise_signal_does_not_change_if_same_length(self): random_signal = Signal.generate_random(2, 60) cosine_signal = Signal.generate_cosine(2, 60) random_resampled, cosine_resampled = random_signal.get_re_discretised_signal( cosine_signal) self.assertEqual(random_signal.signal.shape[0], len(cosine_resampled)) self.assertTrue(np.array_equal(cosine_signal.signal, cosine_resampled)) self.assertTrue(np.array_equal(random_signal.signal, random_resampled)) random_resampled, cosine_resampled = random_signal.get_re_discretised_signal( cosine_signal, ResamplingType.DOWN_SAMPLE) self.assertEqual(random_signal.signal.shape[0], len(cosine_resampled)) self.assertTrue(np.array_equal(cosine_signal.signal, cosine_resampled)) self.assertTrue(np.array_equal(random_signal.signal, random_resampled))
def __init__(self, parent=None, **kwargs): self.signal_select = Signal() self.signal_delete = Signal() self._cur_selection = None self._unsorted_to_sorted_index = [] self._sorted_to_unsorted_index = [] self._data = [] self._sorted_data = [] self._wrapper = KeyWrapper(self._sorted_data) self._gui = ListChoiceGUI(parent, **kwargs) self._gui.signal_select.connect(self._on_select) self._gui.signal_delete.connect(self.signal_delete) self._gui.signal_up.connect(self._up) self._gui.signal_down.connect(self._down)
def __getattr__(self, name): if name == 'signal': self.signal = Signal(request) else: raise Exception('Attribute not found %s' % name) return self.__getattribute__(name)
class LineEdit(Widget): def __init__(self, pos=(0, 0), size=(100, 40)): super(LineEdit, self).__init__(pos, size) self.keydown = Signal() self.font = Font('Arial') self.bgcolor = (80, 80, 80, 255) self.blinktime = 700 self.hmargin = 2 self.vmargin = 2 self.label = Label('', self.font) self.label.resize((self.width - 2 * self.hmargin, self.height - 2 * self.vmargin)) self.label.move_to(self.pos) self.label.move((self.hmargin, self.vmargin)) self.queue.add(self.label) self.keydown.connect(self.on_keyDown) def on_keyDown(self, key, mod, u): if key == pygame.K_BACKSPACE: self.remove() else: self.add(u) def add(self, letter): if self.label.get_font_width(self.label.text + letter) <= \ self.width - 2 * self.hmargin: self.label.text += letter def remove(self): self.label.text = self.label.text[:-1] def draw(self, surf): super(LineEdit, self).draw(surf) if ((pygame.time.get_ticks() / self.blinktime % 2 == 0) or (not self.focus)): x = self.label.pos[0] + self.label.get_font_width() y1 = self.label.pos[1] y2 = y1 + self.label.height - self.vmargin pygame.draw.line(surf, (0, 0, 0, 255), (x, y1), (x, y2))
def event(self, name): if name in self._events: return self._events[name] signal = Signal() signal += lambda *a, **k: self.send(name, *a, **k) self._events[name] = signal return signal
def test_compute_distance_compatible(self): # Test cosine vs cosine cosine_signal = Signal.generate_cosine(2, 60) cosine_signal2 = Signal.generate_cosine(7, 43) self.assertAlmostEqual(cosine_signal.compute_distance(cosine_signal), 0.0) self.assertAlmostEqual(cosine_signal.compute_distance(cosine_signal2), 244.05038, 5) # Test random vs random random_signal = Signal.generate_random(2, 60) random_signal2 = Signal.generate_random(2, 120) self.assertAlmostEqual(random_signal.compute_distance(random_signal), 0.0) self.assertTrue(random_signal.compute_distance(random_signal2) > 0.0) # Test cosine vs random self.assertTrue(cosine_signal.compute_distance(random_signal) > 0.0)
def create_scenario(self): """ Create the scenrario here, some of this could be moved to an __init__ """ road_data = Road.generate_random_road_data() self.road = Road(**road_data) # determine number of signals to create num_signals = int(self.road.length / 4) self.signals = [] for x in range(1, num_signals): data = Signal.generate_random_signal_data(x, self.road.length) signal = Signal(**data) self.signals.append(signal) vehicle_data = Vehicle.generate_random_vehicle_data() self.vehicle = Vehicle(**vehicle_data)
def __init__(self, index, source, cam_config): self.cam_is_run = False self.__cam_index = index self.cfg = cam_config if type(source) == unicode: source = source.encode("UTF-8") source = source.encode("UTF-8") self.__source = source self._notify_list = [] self.cam_thread = c.CamStream() self.cam_thread.onCaptureUpdate(self._onCapUpdate) self.cam_thread.onThreadEvent(self._onThreadEvents) self.cam_thread.start(source) self.last_triggered = 0 self.cam_thread.schedule(3, 0) self.stack_frame = StackFrame(40) self.last_frame = None self._events = collections.defaultdict(set) self.signal_mdetect_trig = Signal()
def from_config(cls, city_config_path): cars_filepath = Path(city_config_path) / cls.CARS_FILE with open(cars_filepath, 'r') as f: car_records = json.load(f) layout_filepath = Path(city_config_path) / cls.LAYOUT_FILE with open(layout_filepath, 'r') as f: layout = json.load(f) schedule_filepath = Path(city_config_path) / cls.SCHEDULE_FILE with open(schedule_filepath, 'r') as f: schedule = json.load(f) lights = {} roads = {} cars = {} for road_record in layout['roads']: id = road_record['id'] length = road_record['length'] roads[id] = Road(id, length) for light_record in layout['lights']: id = light_record['id'] roads_in_ids = light_record['roads_in'] roads_out_ids = light_record['roads_out'] for road_in in roads_in_ids: roads[road_in].light_out = id for road_out in roads_out_ids: roads[road_out].light_in = id lights[id] = Light(id, roads_in_ids, roads_out_ids) for car_record in car_records: id = car_record['id'] road_ids = car_record['roads'] # TODO: Check that the order of roads is possible cars[id] = Car(id, road_ids) time_allocated = layout['time_allocated'] for light_record in schedule: light_id = light_record['light'] signals = [] for signal_record in light_record['signals']: road_id = signal_record['road'] time = signal_record['time'] signal = Signal(road_id, time) signals.append(signal) lights[light_id].signals = signals return cls(roads, lights, cars, time_allocated)
def test_similarity_fourrier_transform(self): # Test 1: Two equal cosine signals should be 100% similar cosine_signal = Signal.generate_cosine(2, 30) cosine_similarity = cosine_signal.get_similarity_fourrier_transform( cosine_signal) self.assertAlmostEqual(cosine_similarity, 1.0) # Test 2: Cosine signals are pretty similar. Due to resampling and the fact that this method measures difference # in frequency, two different ones should still be similar cosine_signal = Signal.generate_cosine(2, 30) cosine_signal2 = Signal.generate_cosine(4, 433) cosine_similarity = cosine_signal.get_similarity_fourrier_transform( cosine_signal2) self.assertAlmostEqual(cosine_similarity, 1) # Test 3: Random signals should probably not be too similar or dissimilar random_signal = Signal.generate_random(2, 60) random_signal2 = Signal.generate_random(3, 105) random_similarity = random_signal.get_similarity_fourrier_transform( random_signal2) self.assertTrue(0 < random_similarity < 1)
def from_dict(cls, data: dict): signals = [] if "signals" in data: for signal in data["signals"]: signals.append(Signal.from_dict(signal)) return cls( name=data["name"], id=data["id"], bus_id=data["bus_id"], length=data["length"], signals=signals, )
class EventManager(Sender, Receiver): quiet = False def __init__(self): super(EventManager, self).__init__() self._events = {} self.on_any_event = Signal() def notify(self, name, *args, **kw): if not self.quiet: if name in self._events: self._events[name].notify(*args, **kw) else: self.send(name, *args, **kw) receive = notify def send(self, name, *a, **k): self.on_any_event.notify(name, a, k) super(EventManager, self).send(name, *a, **k) def event(self, name): if name in self._events: return self._events[name] signal = Signal() signal += lambda *a, **k: self.send(name, *a, **k) self._events[name] = signal return signal def clear_events(self, name=None): if name: del self._events[name] else: self._events.clear()
def test_similarity_distance_time_warping(self): # Test 1: Two equal signals should be 100% similar random_signal = Signal.generate_random(2, 30) random_similarity = random_signal.get_similarity_distance_time_warping( random_signal) self.assertAlmostEqual(random_similarity, 1.0) cosine_signal = Signal.generate_cosine(2, 30) cosine_similarity = cosine_signal.get_similarity_distance_time_warping( cosine_signal) self.assertAlmostEqual(cosine_similarity, 1.0) # Test 2: Cosine signals are pretty similar. Due to resampling, two different ones should still be similar but # not measured as being the same cosine_signal = Signal.generate_cosine(2, 40) cosine_signal2 = Signal.generate_cosine(4, 40) cosine_similarity = cosine_signal.get_similarity_distance_time_warping( cosine_signal2) self.assertTrue(cosine_similarity > 0.80) cosine_signal = Signal.generate_cosine(2, 40) cosine_signal2 = Signal.generate_cosine(2, 80) cosine_similarity = cosine_signal.get_similarity_distance_time_warping( cosine_signal2) self.assertTrue(cosine_similarity > 0.80) cosine_signal = Signal.generate_cosine(2, 40) cosine_signal2 = Signal.generate_cosine(4, 80) cosine_similarity = cosine_signal.get_similarity_distance_time_warping( cosine_signal2) self.assertTrue(cosine_similarity > 0.80) # Test 3: Random signals should probably not be too similar or dissimilar random_signal = Signal.generate_random(2, 60) random_signal2 = Signal.generate_random(3, 105) random_similarity = random_signal.get_similarity_distance_time_warping( random_signal2) self.assertTrue(0 < random_similarity < 1)
def activate_on_window(self, window): if self.active: return self.window = window self.active = True if self.take_context: # Import all current views into this task self.take_context = False else: # close all current views while self.window.active_view(): self.window.run_command('close') # open new views into current files map(self.dict_to_view, self._views) # Async, post-load actions (wait until all views are loaded) loaded = Signal() def load_wait(): loading = any(v.is_loading() for v in window.views()) if loading: sublime.set_timeout(load_wait, 100) else: loaded() sublime.set_timeout(load_wait, 100) if self._active_view_ix != -1: def activate_active_view(): self.window.focus_view(self.window.views()[self._active_view_ix]) loaded.connect(activate_active_view) def connect_events(): TasklistEvents.loaded.connect(self.add_view) TasklistEvents.closed.connect(self.remove_view) TasklistEvents.activated.connect(self.set_active_view) loaded.connect(connect_events)
def create_signals(self, inputs, outputs): self.signal_inputs.clear() self.signal_outputs.clear() inputs_radius = constants.SIGNAL_RADIUS outputs_radius = constants.SIGNAL_RADIUS # Code that resizes radius when the signals are divisible by 8 for i in range(1, inputs): if i % 8 == 0: inputs_radius /= 1.5 for i in range(1, outputs): if i % 8 == 0: outputs_radius /= 1.5 # This took way to long to perfect... for i in range(self.area.height): if i % (self.area.height // (inputs + 1)) == 0 and i != 0 and len(self.signal_inputs) < inputs: self.signal_inputs.append(Signal(constants.MARGIN, self.area.top + i, inputs_radius)) if i % (self.area.height // (outputs + 1)) == 0 and i != 0 and len(self.signal_outputs) < outputs: self.signal_outputs.append(Signal(constants.WIDTH - constants.MARGIN, self.area.top + i, outputs_radius)) self.wires.clear() # TEMPORARY
def parse(data: str, *args): model = cantools.database.load_string(data) packets = [] for message in model.messages: signals = [] for signal in message.signals: signals.append(Signal.from_signal(signal)) packet = Packet.from_message(message, signals) ecu_type = [] if all(not packet.bus_id.startswith(name) or ecu_type.append(name) for name in args): packets.append(packet) # There should be only one ecu type assert len(ecu_type) == 1 return DBC(packets=packets), ecu_type[0]
class EventManager (Sender, Receiver): quiet = False def __init__ (self): super (EventManager, self).__init__ () self._events = {} self.on_any_event = Signal () def notify (self, name, *args, **kw): if not self.quiet: if name in self._events: self._events [name].notify (*args, **kw) else: self.send (name, *args, **kw) receive = notify def send (self, name, *a, **k): self.on_any_event.notify (name, a, k) super (EventManager, self).send (name, *a, **k) def event (self, name): if name in self._events: return self._events [name] signal = Signal () signal += lambda *a, **k: self.send (name, *a, **k) self._events [name] = signal return signal def clear_events (self, name = None): if name: del self._events [name] else: self._events.clear ()
def __init__(self, scheduler, inputs, output, name = None, prop_delay = 0): super().__init__(scheduler) self.debug = False self.inputs = [i.bind(self) for i in inputs] if output is None: output = Signal(scheduler) self.output = output if name is None: NAND.__serial__ += 1 name = "NAND%d" % NAND.__serial__ self.name = name self.prop_delay = prop_delay
def __init__(self, pos=(0, 0), size=(100, 40)): super(LineEdit, self).__init__(pos, size) self.keydown = Signal() self.font = Font('Arial') self.bgcolor = (80, 80, 80, 255) self.blinktime = 700 self.hmargin = 2 self.vmargin = 2 self.label = Label('', self.font) self.label.resize((self.width - 2 * self.hmargin, self.height - 2 * self.vmargin)) self.label.move_to(self.pos) self.label.move((self.hmargin, self.vmargin)) self.queue.add(self.label) self.keydown.connect(self.on_keyDown)
def getKeySequenceSignal(self, key, modifiers=[]): # Parse modifiers mods = {"alt": False, "ctrl": False, "shift": False, "meta": False} for m in modifiers: m = m.lower() if m in mods: mods[m] = True else: print "Unknown modifier:", m # Check if signal for keysequence has been created for k in self.keysequences: if k.key == key and k.modifiers == mods: return k.signal # Create keysequence and signal keysequence = KeySequence() keysequence.key = key keysequence.modifiers = mods keysequence.signal = Signal(providing_args=["event"]) self.keysequences.append(keysequence) return keysequence.signal
def integrate(dop_0, H, Lk, tstep, tf, integrator='euler', dt_func=None, dt_func_data=None): """ integrate the Lindblad Master Equation dop_0 system's initial state as a density operator H system's Hamiltonian Lk the sequence of Lindblad operators tstep simulation step time tf simulation finish time integrator 'euler' or 'rk4' for runge-kutta' 4th order method dt_func a function returning the LME time derivative; if defined it will be used in place of the dafult one. Use it to hook different control algorithms into the integrator (ie. a controller modulating some Hamiltonian terms). ! You can still use the {hamiltonian,lindbladian}_dt functions defined in this module if you need them. dt_func_data accessory data that wil be passed to dt_func """ # check matrices orders assert dop_0.ndim == H.ndim == 2 assert dop_0.shape[0] == dop_0.shape[1] == H.shape[0] == H.shape[1] for L in Lk: assert L.ndim == dop_0.ndim assert L.shape[0] == L.shape[1] == dop_0.shape[0] # check matrices props assert (dop_0 == dop_0.conj().transpose()).all() assert numpy.abs(1. - numpy.trace(dop_0)) < 0.000000001 assert (H == H.conj().transpose()).all() # check timing params assert (tstep > 0) and (tf >= tstep) # select integrator assert integrator in ('euler', 'rk4') Delta_func = ({'euler' : _Delta_euler, 'rk4' : _Delta_rk4})[integrator] # default to _dt for calculating LME's time derivative if not dt_func: dt_func = _dt # init simulation loop max_delta_dop = 0. algo_start_time = time.time() algo_last_time = algo_start_time evo = Signal('Density op. evolution') integrator_time = 0. evo.append(integrator_time, dop_0) integrator_time = integrator_time + tstep dop = dop_0 while integrator_time <= tf: # integrator_time may be needed in state tracking controller delta_dop = Delta_func(dt_func, dt_func_data, integrator_time, dop, H, Lk, tstep) new_max_delta_dop = numpy.max(numpy.abs(delta_dop)) if new_max_delta_dop > max_delta_dop: max_delta_dop = new_max_delta_dop dop = dop + delta_dop #TODO: should print out a measure of the 'drift' from 'hermitianicity' #assert (dop == dop.conj().transpose()).all() #assert numpy.trace(dop) == 1 evo.append(integrator_time,dop) integrator_time = integrator_time + tstep if (time.time() - algo_last_time) > 20.: algo_last_time = time.time() progress = integrator_time/float(tf)*100. ETA_min = (algo_last_time - algo_start_time) \ /integrator_time*(tf - integrator_time)/60. print 'in lme.sim: %d%%, ETA: %.1fmin' % (progress, ETA_min) if max_delta_dop > 0.001: print ' ! warning in lme.sim, max_delta_dop: ', max_delta_dop return evo
def notify (self, *args, **kws): name = self._observer_signal_name obj = self._observer_signal_obj obj.send (name, *args, **kws) return Signal.notify (self, *args, **kws)
def __init__ (self): super (EventManager, self).__init__ () self._events = {} self.on_any_event = Signal ()