def test_sample_pulses_with_tolerance(self): """Test sample pulses with tolerance.""" schedule = Schedule() schedule += Play(Waveform([0.0, 0.1001], epsilon=1e-3), DriveChannel(0)) schedule += Play(Waveform([0.0, 0.1], epsilon=1e-3), DriveChannel(1)) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 2) self.assertEqual(len(compressed_pulse_ids), 1)
def test_add(self): """Test `add`, `has`, `get`, `cmdss`.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.device.drives[0])) cmd_def = CmdDef() cmd_def.add('tmp', 1, sched) cmd_def.add('tmp', 0, sched) self.assertEqual(sched.instructions, cmd_def.get('tmp', (0,)).instructions) self.assertIn('tmp', cmd_def.cmds()) self.assertEqual(cmd_def.cmd_qubits('tmp'), [(0,), (1,)])
def test_check_user_cals(self): """Test if schedules provided by user is distinguishable.""" instmap = FakeOpenPulse2Q().defaults().instruction_schedule_map test_u1 = Schedule() test_u1 += ShiftPhase(Parameter("P0"), DriveChannel(0)) instmap.add("u1", (0,), test_u1, arguments=["P0"]) publisher = instmap.get("u1", (0,), P0=0).metadata["publisher"] self.assertEqual(publisher, CalibrationPublisher.QISKIT)
def test_instructions(self): """Test `instructions`.""" sched = Schedule() inst_map = InstructionScheduleMap() inst_map.add("u1", 1, sched) inst_map.add("u3", 0, sched) instructions = inst_map.instructions for inst in ["u1", "u3"]: self.assertTrue(inst in instructions)
def test_instructions(self): """Test `instructions`.""" sched = Schedule() inst_map = InstructionScheduleMap() inst_map.add('u1', 1, sched) inst_map.add('u3', 0, sched) instructions = inst_map.instructions for inst in ['u1', 'u3']: self.assertTrue(inst in instructions)
def test_remove_gate(self): """Test removing a defined operation and removing an undefined operation.""" sched = Schedule() inst_map = InstructionScheduleMap() inst_map.add("tmp", 0, sched) inst_map.remove("tmp", 0) self.assertFalse(inst_map.has("tmp", 0)) with self.assertRaises(PulseError): inst_map.remove("not_there", (0,)) self.assertFalse("tmp" in inst_map.qubit_instructions(0))
def test_pop(self): """Test pop with default.""" sched = Schedule() sched.append(SamplePulse(np.ones(5))(self.config.drive(0))) cmd_def = CmdDef() cmd_def.add('tmp', 0, sched) cmd_def.pop('tmp', 0) self.assertFalse(cmd_def.has('tmp', 0)) with self.assertRaises(PulseError): cmd_def.pop('not_there', (0, ))
def test_measure_sched_with_qubit_mem_slots(self): """Test measure with custom qubit_mem_slots.""" sched = macros.measure(qubits=[0], backend=self.backend, qubit_mem_slots={0: 1}) expected = Schedule( self.inst_map.get("measure", [0, 1]).filter(channels=[MeasureChannel(0)]), Acquire(10, AcquireChannel(0), MemorySlot(1)), ) self.assertEqual(sched.instructions, expected.instructions)
def convert_acquire(self, instruction): """Return converted `AcquireInstruction`. Args: instruction (PulseQobjInstruction): acquire qobj Returns: Schedule: Converted and scheduled Instruction """ t0 = instruction.t0 duration = instruction.duration qubits = instruction.qubits discriminators = (instruction.discriminators if hasattr( instruction, 'discriminators') else None) kernels = (instruction.kernels if hasattr(instruction, 'kernels') else None) mem_slots = instruction.memory_slot reg_slots = (instruction.register_slot if hasattr( instruction, 'register_slot') else None) if not isinstance(discriminators, list): discriminators = [discriminators for _ in range(len(qubits))] if not isinstance(kernels, list): kernels = [kernels for _ in range(len(qubits))] schedule = Schedule() for i, qubit in enumerate(qubits): kernel = kernels[i] if kernel: kernel = commands.Kernel(name=kernel.name, params=kernel.params) discriminator = discriminators[i] if discriminator: discriminator = commands.Discriminator( name=discriminator.name, params=discriminator.params) channel = channels.AcquireChannel(qubit, buffer=self.buffer) if reg_slots: register_slot = channels.RegisterSlot(reg_slots[i]) else: register_slot = None memory_slot = channels.MemorySlot(mem_slots[i]) cmd = commands.Acquire(duration, discriminator=discriminator, kernel=kernel) schedule |= commands.AcquireInstruction(cmd, channel, memory_slot, register_slot) << t0 return schedule
def test_with_different_channels(self): """Test with different channels.""" schedule = Schedule() schedule += Play(Waveform([0.0, 0.1]), DriveChannel(0)) schedule += Play(Waveform([0.0, 0.1]), DriveChannel(1)) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), 2) self.assertEqual(len(compressed_pulse_ids), 1)
def test_binding_too_many_parameters(self): """Test getting schedule with too many parameter binding.""" param = Parameter('param') target_sched = Schedule() target_sched.insert(0, ShiftPhase(param, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add('target_sched', (0,), target_sched) with self.assertRaises(PulseError): inst_map.get('target_sched', (0,), 0, 1, 2, 3)
def test_no_duplicates(self): """Test with no pulse duplicates.""" schedule = Schedule() drive_channel = DriveChannel(0) schedule += Play(Waveform([0.0, 1.0]), drive_channel) schedule += Play(Waveform([0.0, 0.9]), drive_channel) schedule += Play(Waveform([0.0, 0.3]), drive_channel) compressed_schedule = transforms.compress_pulses([schedule]) original_pulse_ids = get_pulse_ids([schedule]) compressed_pulse_ids = get_pulse_ids(compressed_schedule) self.assertEqual(len(original_pulse_ids), len(compressed_pulse_ids))
def test_measure_sched_with_qubit_mem_slots(self): """Test measure with custom qubit_mem_slots.""" acquire = Acquire(duration=10) sched = measure(qubits=[0], backend=self.backend, qubit_mem_slots={0: 1}) expected = Schedule( self.inst_map.get('measure', [0, 1]).filter(channels=[MeasureChannel(0)]), acquire(AcquireChannel(0), MemorySlot(1)), acquire(AcquireChannel(1), MemorySlot(0))) self.assertEqual(sched.instructions, expected.instructions)
def test_get_schedule_with_unbound_parameter(self): """Test get schedule with partial binding.""" param1 = Parameter("param1") param2 = Parameter("param2") target_sched = Schedule() target_sched.insert(0, ShiftPhase(param1, DriveChannel(0)), inplace=True) target_sched.insert(10, ShiftPhase(param2, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add("target_sched", (0,), target_sched) ref_sched = Schedule() ref_sched.insert(0, ShiftPhase(param1, DriveChannel(0)), inplace=True) ref_sched.insert(10, ShiftPhase(1.23, DriveChannel(0)), inplace=True) test_sched = inst_map.get("target_sched", (0,), param2=1.23) for test_inst, ref_inst in zip(test_sched.instructions, ref_sched.instructions): self.assertEqual(test_inst[0], ref_inst[0]) self.assertAlmostEqual(test_inst[1], ref_inst[1])
def test_binding_unassigned_parameters(self): """Test getting schedule with unassigned parameter binding.""" param = Parameter("param") target_sched = Schedule() target_sched.insert(0, ShiftPhase(param, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add("target_sched", (0,), target_sched) with self.assertRaises(PulseError): inst_map.get("target_sched", (0,), P0=0)
def test_carriers_and_dt(self): """Test that the carriers go into the signals.""" sched = Schedule(name="Schedule") sched += Play(Gaussian(duration=20, amp=0.5, sigma=4), DriveChannel(0)) converter = InstructionToSignals(dt=0.222, carriers=[5.5e9]) signals = converter.get_signals(sched) self.assertEqual(signals[0].carrier_freq, 5.5e9) # pylint: disable=protected-access self.assertEqual(signals[0]._dt, 0.222)
def test_qubits_with_instruction(self): """Test `qubits_with_instruction`.""" sched = Schedule() inst_map = InstructionScheduleMap() inst_map.add("u1", (0, ), sched) inst_map.add("u1", (1, ), sched) inst_map.add("cx", [0, 1], sched) self.assertEqual(inst_map.qubits_with_instruction("u1"), [0, 1]) self.assertEqual(inst_map.qubits_with_instruction("cx"), [(0, 1)]) self.assertEqual(inst_map.qubits_with_instruction("none"), [])
def test_qubits_with_instruction(self): """Test `qubits_with_instruction`.""" sched = Schedule() inst_map = InstructionScheduleMap() inst_map.add('u1', (0, ), sched) inst_map.add('u1', (1, ), sched) inst_map.add('cx', [0, 1], sched) self.assertEqual(inst_map.qubits_with_instruction('u1'), [0, 1]) self.assertEqual(inst_map.qubits_with_instruction('cx'), [(0, 1)]) self.assertEqual(inst_map.qubits_with_instruction('none'), [])
def test_qubits_with_instruction_gate(self): """Test `qubits_with_instruction`.""" sched = Schedule() inst_map = InstructionScheduleMap() inst_map.add(U1Gate(0), (0, ), sched) inst_map.add(U1Gate(0), (1, ), sched) inst_map.add(CXGate(), [0, 1], sched) self.assertEqual(inst_map.qubits_with_instruction(U1Gate(0)), [0, 1]) self.assertEqual(inst_map.qubits_with_instruction(CXGate()), [(0, 1)]) self.assertEqual(inst_map.qubits_with_instruction('none'), [])
def add_implicit_acquires(schedule: ScheduleComponent, meas_map: List[List[int]]) -> Schedule: """Return a new schedule with implicit acquires from the measurement mapping replaced by explicit ones. .. warning:: Since new acquires are being added, Memory Slots will be set to match the qubit index. This may overwrite your specification. Args: schedule: Schedule to be aligned. meas_map: List of lists of qubits that are measured together. Returns: A ``Schedule`` with the additional acquisition commands. """ new_schedule = Schedule(name=schedule.name) acquire_map = dict() for time, inst in schedule.instructions: if isinstance(inst, (Acquire, AcquireInstruction)): if any([ acq.index != mem.index for acq, mem in zip(inst.acquires, inst.mem_slots) ]): warnings.warn( "One of your acquires was mapped to a memory slot which didn't match" " the qubit index. I'm relabeling them to match.") # Get the label of all qubits that are measured with the qubit(s) in this instruction existing_qubits = {chan.index for chan in inst.acquires} all_qubits = [] for sublist in meas_map: if existing_qubits.intersection(set(sublist)): all_qubits.extend(sublist) # Replace the old acquire instruction by a new one explicitly acquiring all qubits in # the measurement group. for i in all_qubits: explicit_inst = Acquire( inst.duration, AcquireChannel(i), mem_slot=MemorySlot(i), kernel=inst.kernel, discriminator=inst.discriminator) << time if time not in acquire_map: new_schedule |= explicit_inst acquire_map = {time: {i}} elif i not in acquire_map[time]: new_schedule |= explicit_inst acquire_map[time].add(i) else: new_schedule |= inst << time return new_schedule
def test_has_custom_gate(self): """Test method to check custom gate.""" backend = FakeOpenPulse2Q() instmap = backend.defaults().instruction_schedule_map self.assertFalse(instmap.has_custom_gate()) # add something some_sched = Schedule() instmap.add("u3", (0, ), some_sched) self.assertTrue(instmap.has_custom_gate())
def test_scheduler_with_params_bound(self): """Test scheduler with parameters defined and bound""" x = Parameter("x") qc = QuantumCircuit(2) qc.append(Gate("pulse_gate", 1, [x]), [0]) expected_schedule = Schedule() qc.add_calibration(gate="pulse_gate", qubits=[0], schedule=expected_schedule, params=[x]) qc = qc.assign_parameters({x: 1}) sched = schedule(qc, self.backend) self.assertEqual(sched, expected_schedule)
def build_parametric_pulse_schedule(number_of_unique_pulses, number_of_channels): sched = Schedule() for _ in range(number_of_unique_pulses): for channel in range(number_of_channels): sched.append( Play( Gaussian(duration=25, sigma=4, amp=0.5j), DriveChannel(channel), ), inplace=True, ) return sched
def test_pop(self): """Test pop with default.""" sched = Schedule() inst_map = InstructionScheduleMap() inst_map.add('tmp', 100, sched) self.assertEqual(inst_map.pop('tmp', 100), sched) self.assertFalse(inst_map.has('tmp', 100)) self.assertEqual(inst_map.qubit_instructions(100), []) self.assertEqual(inst_map.qubits_with_instruction('tmp'), []) with self.assertRaises(PulseError): inst_map.pop('not_there', (0, ))
def test_qubit_instructions(self): """Test `qubit_instructions`.""" sched = Schedule() inst_map = InstructionScheduleMap() inst_map.add('u1', (0, ), sched) inst_map.add('u1', (1, ), sched) inst_map.add('cx', [0, 1], sched) self.assertEqual(inst_map.qubit_instructions(0), ['u1']) self.assertEqual(inst_map.qubit_instructions(1), ['u1']) self.assertEqual(inst_map.qubit_instructions((0, 1)), ['cx']) self.assertEqual(inst_map.qubit_instructions(10), [])
def test_schedule_with_non_alphanumeric_ordering(self): """Test adding and getting schedule with non obvious parameter ordering.""" theta = Parameter('theta') phi = Parameter('phi') lamb = Parameter('lambda') target_sched = Schedule() target_sched.insert(0, ShiftPhase(theta, DriveChannel(0)), inplace=True) target_sched.insert(10, ShiftPhase(phi, DriveChannel(0)), inplace=True) target_sched.insert(20, ShiftPhase(lamb, DriveChannel(0)), inplace=True) inst_map = InstructionScheduleMap() inst_map.add('target_sched', (0, ), target_sched, arguments=['theta', 'phi', 'lambda']) ref_sched = Schedule() ref_sched.insert(0, ShiftPhase(0, DriveChannel(0)), inplace=True) ref_sched.insert(10, ShiftPhase(1, DriveChannel(0)), inplace=True) ref_sched.insert(20, ShiftPhase(2, DriveChannel(0)), inplace=True) # if parameter is alphanumerical ordering this maps to # theta -> 2 # phi -> 1 # lamb -> 0 # however non alphanumerical ordering is specified in add method thus mapping should be # theta -> 0 # phi -> 1 # lamb -> 2 test_sched = inst_map.get('target_sched', (0, ), 0, 1, 2) for test_inst, ref_inst in zip(test_sched.instructions, ref_sched.instructions): self.assertEqual(test_inst[0], ref_inst[0]) self.assertEqual(test_inst[1], ref_inst[1])
def test_qubit_instructions_gate(self): """Test `qubit_instructions`.""" sched = Schedule() inst_map = InstructionScheduleMap() inst_map.add(U1Gate(0), (0, ), sched) inst_map.add(U1Gate(0), (1, ), sched) inst_map.add(CXGate(), [0, 1], sched) self.assertEqual(inst_map.qubit_instructions(0), ["u1"]) self.assertEqual(inst_map.qubit_instructions(1), ["u1"]) self.assertEqual(inst_map.qubit_instructions((0, 1)), ["cx"]) self.assertEqual(inst_map.qubit_instructions(10), [])
def test_shift_frequency(self): """Test that the frequency is properly taken into account.""" sched = Schedule() sched += ShiftFrequency(1.0, DriveChannel(0)) sched += Play(Constant(duration=10, amp=1.0), DriveChannel(0)) converter = InstructionToSignals(dt=0.222, carriers=[5.0]) signals = converter.get_signals(sched) for idx in range(10): self.assertEqual(signals[0].samples[idx], np.exp(2.0j * idx * np.pi * 1.0 * 0.222))
def test_single_and_deprecated_acquire_styles(self): """Test that acquires are identically combined with Acquires that take a single channel.""" backend = FakeOpenPulse2Q() new_style_schedule = Schedule() acq = Acquire(1200) for i in range(5): new_style_schedule += acq(AcquireChannel(i), MemorySlot(i)) deprecated_style_schedule = Schedule() deprecated_style_schedule += acq([AcquireChannel(i) for i in range(5)], [MemorySlot(i) for i in range(5)]) # The Qobj IDs will be different n_qobj = assemble(new_style_schedule, backend) n_qobj.qobj_id = None d_qobj = assemble(deprecated_style_schedule, backend) d_qobj.qobj_id = None self.assertEqual(n_qobj, d_qobj) assembled_acquire = n_qobj.experiments[0].instructions[0] self.assertEqual(assembled_acquire.qubits, [0, 1, 2, 3, 4]) self.assertEqual(assembled_acquire.memory_slot, [0, 1, 2, 3, 4])
def test_set_phase(self): """Test SetPhase command. Similar to the ShiftPhase test but includes a mixing of ShiftPhase and SetPhase instructions to test relative vs absolute changes""" omega_0 = 1.3981 r = 1. system_model = self._system_model_1Q(omega_0, r) # intermix shift and set phase instructions to verify absolute v.s. relative changes sched = Schedule() amp1 = 0.12 sched += Play(Waveform([amp1]), DriveChannel(0)) phi1 = 0.12374 * np.pi sched += ShiftPhase(phi1, DriveChannel(0)) amp2 = 0.492 sched += Play(Waveform([amp2]), DriveChannel(0)) phi2 = 0.5839 * np.pi sched += SetPhase(phi2, DriveChannel(0)) amp3 = 0.12 + 0.21 * 1j sched += Play(Waveform([amp3]), DriveChannel(0)) phi3 = 0.1 * np.pi sched += ShiftPhase(phi3, DriveChannel(0)) amp4 = 0.2 + 0.3 * 1j sched += Play(Waveform([amp4]), DriveChannel(0)) sched |= Acquire(1, AcquireChannel(0), MemorySlot(0)) << sched.duration y0 = np.array([1., 0.]) pulse_sim = PulseSimulator(system_model=system_model, initial_state=y0) qobj = assemble([sched], backend=pulse_sim, meas_level=2, meas_return='single', meas_map=[[0]], qubit_lo_freq=[omega_0], memory_slots=2, shots=1) results = pulse_sim.run(qobj).result() pulse_sim_yf = results.get_statevector() #run independent simulation samples = np.array([[amp1], [amp2 * np.exp(1j * phi1)], [amp3 * np.exp(1j * phi2)], [amp4 * np.exp(1j * (phi2 + phi3))]]) indep_yf = simulate_1q_model(y0, omega_0, r, np.array([omega_0]), samples, 1.) self.assertGreaterEqual(state_fidelity(pulse_sim_yf, indep_yf), 1 - (10**-5))