def test_create_program_internal(self) -> None:
        sub1 = DummyPulseTemplate(duration=3,
                                  waveform=DummyWaveform(duration=3),
                                  measurements=[('b', 1, 2)],
                                  defined_channels={'A'})
        sub2 = DummyPulseTemplate(duration=2,
                                  waveform=DummyWaveform(duration=2),
                                  parameter_names={'foo'},
                                  defined_channels={'A'})
        scope = DictScope.from_kwargs()
        measurement_mapping = {'a': 'a', 'b': 'b'}
        channel_mapping = dict()
        seq = SequencePulseTemplate(sub1, sub2, measurements=[('a', 0, 1)])
        loop = Loop()
        seq._internal_create_program(scope=scope,
                                     measurement_mapping=measurement_mapping,
                                     channel_mapping=channel_mapping,
                                     global_transformation=None,
                                     to_single_waveform=set(),
                                     parent_loop=loop)
        self.assertEqual(1, loop.repetition_count)
        self.assertIsNone(loop.waveform)
        self.assertEqual([
            Loop(repetition_count=1, waveform=sub1.waveform),
            Loop(repetition_count=1, waveform=sub2.waveform)
        ], list(loop.children))
        self.assert_measurement_windows_equal(
            {
                'a': ([0], [1]),
                'b': ([1], [2])
            }, loop.get_measurement_windows())

        ### test again with inverted sequence
        seq = SequencePulseTemplate(sub2, sub1, measurements=[('a', 0, 1)])
        loop = Loop()
        seq._internal_create_program(scope=scope,
                                     measurement_mapping=measurement_mapping,
                                     channel_mapping=channel_mapping,
                                     global_transformation=None,
                                     to_single_waveform=set(),
                                     parent_loop=loop)
        self.assertEqual(1, loop.repetition_count)
        self.assertIsNone(loop.waveform)
        self.assertEqual([
            Loop(repetition_count=1, waveform=sub2.waveform),
            Loop(repetition_count=1, waveform=sub1.waveform)
        ], list(loop.children))
        self.assert_measurement_windows_equal(
            {
                'a': ([0], [1]),
                'b': ([3], [2])
            }, loop.get_measurement_windows())
Exemplo n.º 2
0
    def test_advanced_sequence_exceptions(self):
        temp_properties = self.instr_props.copy()
        temp_properties['max_seq_len'] = 5

        program = Loop(children=[
            Loop(waveform=DummyWaveform(defined_channels={'A'}, duration=1),
                 repetition_count=1)
            for _ in range(temp_properties['max_seq_len'] + 1)
        ],
                       repetition_count=2)
        with self.assertRaises(TaborException):
            TaborProgram(program.copy_tree_structure(),
                         channels=(None, 'A'),
                         markers=(None, None),
                         device_properties=temp_properties,
                         **self.program_entry_kwargs)

        temp_properties['min_seq_len'] = 100
        temp_properties['max_seq_len'] = 120
        with self.assertRaises(TaborException) as exception:
            TaborProgram(program.copy_tree_structure(),
                         channels=(None, 'A'),
                         markers=(None, None),
                         device_properties=temp_properties,
                         **self.program_entry_kwargs)
        self.assertEqual(
            str(exception.exception), 'The algorithm is not smart enough '
            'to make this sequence table longer')

        program = Loop(children=[
            Loop(children=[
                Loop(waveform=DummyWaveform(defined_channels={'A'},
                                            duration=1)),
                Loop(
                    waveform=DummyWaveform(defined_channels={'A'}, duration=1))
            ]),
            Loop(children=[
                Loop(waveform=DummyWaveform(defined_channels={'A'},
                                            duration=1)),
                Loop(
                    waveform=DummyWaveform(defined_channels={'A'}, duration=1))
            ])
        ])
        with self.assertRaises(TaborException) as exception:
            TaborProgram(program.copy_tree_structure(),
                         channels=(None, 'A'),
                         markers=(None, None),
                         device_properties=temp_properties,
                         **self.program_entry_kwargs)
        self.assertEqual(
            str(exception.exception), 'The algorithm is not smart enough '
            'to make this sequence table longer')
 def test_internal_create_program_parameter_constraint_violations(self) -> None:
     sub1 = DummyPulseTemplate(duration=3, waveform=DummyWaveform(duration=3), measurements=[('b', 1, 2)])
     sub2 = DummyPulseTemplate(duration=2, waveform=DummyWaveform(duration=2), parameter_names={'foo'})
     parameters = {'foo': ConstantParameter(7)}
     seq = SequencePulseTemplate(sub1, sub2, measurements=[('a', 0, 1)], parameter_constraints={'foo < 2'})
     loop = Loop()
     with self.assertRaises(ParameterConstraintViolation):
         seq._internal_create_program(parameters=parameters,
                                      measurement_mapping={'a': 'a', 'b': 'b'},
                                      channel_mapping=dict(),
                                      global_transformation=None,
                                      to_single_waveform=set(),
                                      parent_loop=loop)
Exemplo n.º 4
0
    def test_simple_properties(self):
        lhs = DummyWaveform(duration=1.5, defined_channels={'a', 'b', 'c'})
        rhs = DummyWaveform(duration=1.5, defined_channels={'a', 'b', 'd'})

        arith = ArithmeticWaveform(lhs, '-', rhs)

        self.assertEqual(set('abcd'), arith.defined_channels)
        self.assertIs(lhs, arith.lhs)
        self.assertIs(rhs, arith.rhs)
        self.assertEqual('-', arith.arithmetic_operator)
        self.assertEqual(lhs.duration, arith.duration)

        self.assertEqual(('-', lhs, rhs), arith.compare_key)
Exemplo n.º 5
0
    def test_get_item(self):
        dwf_a = DummyWaveform(duration=2.2, defined_channels={'A'})
        dwf_b = DummyWaveform(duration=2.2, defined_channels={'B'})
        dwf_c = DummyWaveform(duration=2.2, defined_channels={'C'})

        wf = MultiChannelWaveform([dwf_a, dwf_b, dwf_c])

        self.assertIs(wf['A'], dwf_a)
        self.assertIs(wf['B'], dwf_b)
        self.assertIs(wf['C'], dwf_c)

        with self.assertRaises(KeyError):
            wf['D']
Exemplo n.º 6
0
 def test_equality(self):
     wf1 = DummyWaveform()
     wf2 = DummyWaveform()
     instr11 = EXECInstruction(wf1)
     instr12 = EXECInstruction(wf1)
     instr20 = EXECInstruction(wf2)
     self.assertEqual(instr11, instr11)
     self.assertEqual(instr11, instr12)
     self.assertEqual(instr12, instr11)
     self.assertNotEqual(instr11, instr20)
     self.assertNotEqual(instr20, instr11)
     self.assertEqual(hash(instr11), hash(instr12))
     self.assertNotEqual(hash(instr11), hash(instr20))
Exemplo n.º 7
0
    def test_render_block_time_slice(self) -> None:
        with self.assertWarnsRegex(DeprecationWarning, ".*InstructionBlock.*"):
            with self.assertRaises(ValueError):
                wf1 = DummyWaveform(duration=19)
                wf2 = DummyWaveform(duration=21)

                block = InstructionBlock()
                block.add_instruction_exec(wf1)
                block.add_instruction_exec(wf2)

                times, voltages, _ = render(block,
                                            sample_rate=0.5,
                                            time_slice=(1, 16))
Exemplo n.º 8
0
    def test_internal_create_program_parameter_missing(self) -> None:
        sub1 = DummyPulseTemplate(duration=3,
                                  waveform=DummyWaveform(duration=3),
                                  measurements=[('b', 1, 2)])
        sub2 = DummyPulseTemplate(duration='d',
                                  waveform=DummyWaveform(duration=2),
                                  parameter_names={'foo'})
        seq = SequencePulseTemplate(sub1,
                                    sub2,
                                    measurements=[('a', 'bar', 1)],
                                    parameter_constraints={'foo < 2'})
        loop = Loop()

        # test parameter from constraints
        scope = DictScope.from_kwargs()
        with self.assertRaises(ParameterNotProvidedException):
            seq._internal_create_program(scope=scope,
                                         measurement_mapping={
                                             'a': 'a',
                                             'b': 'b'
                                         },
                                         channel_mapping=dict(),
                                         global_transformation=None,
                                         to_single_waveform=set(),
                                         parent_loop=loop)

        # test parameter from measurements
        scope = DictScope.from_mapping({'foo': 1})
        with self.assertRaises(ParameterNotProvidedException):
            seq._internal_create_program(scope=scope,
                                         measurement_mapping={
                                             'a': 'a',
                                             'b': 'b'
                                         },
                                         channel_mapping=dict(),
                                         global_transformation=None,
                                         to_single_waveform=set(),
                                         parent_loop=loop)

        # test parameter from duration
        scope = DictScope.from_mapping({'foo': 1, 'bar': 0})
        with self.assertRaises(ParameterNotProvidedException):
            seq._internal_create_program(scope=scope,
                                         measurement_mapping={
                                             'a': 'a',
                                             'b': 'b'
                                         },
                                         channel_mapping=dict(),
                                         global_transformation=None,
                                         to_single_waveform=set(),
                                         parent_loop=loop)
Exemplo n.º 9
0
    def test_from_operator(self):
        lhs = DummyWaveform(duration=1.5, defined_channels={'a', 'b', 'c'})
        rhs = DummyWaveform(duration=1.5, defined_channels={'a', 'b', 'd'})

        lhs_const = ConstantWaveform.from_mapping(1.5, {'a': 1.1, 'b': 2.2, 'c': 3.3})
        rhs_const = ConstantWaveform.from_mapping(1.5, {'a': 1.2, 'b': 2.4, 'd': 3.4})

        self.assertEqual(ArithmeticWaveform(lhs, '+', rhs), ArithmeticWaveform.from_operator(lhs, '+', rhs))
        self.assertEqual(ArithmeticWaveform(lhs_const, '+', rhs), ArithmeticWaveform.from_operator(lhs_const, '+', rhs))
        self.assertEqual(ArithmeticWaveform(lhs, '+', rhs_const), ArithmeticWaveform.from_operator(lhs, '+', rhs_const))

        expected = ConstantWaveform.from_mapping(1.5, {'a': 1.1-1.2, 'b': 2.2-2.4, 'c': 3.3, 'd': -3.4})
        consted = ArithmeticWaveform.from_operator(lhs_const, '-', rhs_const)
        self.assertEqual(expected, consted)
Exemplo n.º 10
0
    def test_build_waveform(self):
        a = DummyPulseTemplate(duration=4, defined_channels={'a', 'b'}, parameter_names={'x', 'y'})
        b = DummyPulseTemplate(duration=4, defined_channels={'a', 'c'}, parameter_names={'x', 'z'})

        wf_a = DummyWaveform(duration=4)
        wf_b = DummyWaveform(duration=4)
        wf_arith = DummyWaveform(duration=4)
        wf_rhs_only = DummyWaveform(duration=4)

        arith = ArithmeticAtomicPulseTemplate(a, '-', b)

        parameters = dict(foo=8.)
        channel_mapping = dict(x='y', u='v')

        # channel a in both
        with mock.patch.object(a, 'build_waveform', return_value=wf_a) as build_a, mock.patch.object(b, 'build_waveform', return_value=wf_b) as build_b:
            with mock.patch('qupulse.pulses.arithmetic_pulse_template.ArithmeticWaveform', return_value=wf_arith) as wf_init:
                wf_init.rhs_only_map.__getitem__.return_value.return_value = wf_rhs_only
                self.assertIs(wf_arith, arith.build_waveform(parameters=parameters, channel_mapping=channel_mapping))
                wf_init.assert_called_once_with(wf_a, '-', wf_b)
                wf_init.rhs_only_map.__getitem__.assert_not_called()

            build_a.assert_called_once_with(parameters=parameters, channel_mapping=channel_mapping)
            build_b.assert_called_once_with(parameters=parameters, channel_mapping=channel_mapping)

        # only lhs
        with mock.patch.object(a, 'build_waveform', return_value=wf_a) as build_a, mock.patch.object(b, 'build_waveform', return_value=None) as build_b:
            with mock.patch('qupulse.pulses.arithmetic_pulse_template.ArithmeticWaveform', return_value=wf_arith) as wf_init:
                wf_init.rhs_only_map.__getitem__.return_value.return_value = wf_rhs_only
                self.assertIs(wf_a, arith.build_waveform(parameters=parameters, channel_mapping=channel_mapping))
                wf_init.assert_not_called()
                wf_init.rhs_only_map.__getitem__.assert_not_called()

            build_a.assert_called_once_with(parameters=parameters, channel_mapping=channel_mapping)
            build_b.assert_called_once_with(parameters=parameters, channel_mapping=channel_mapping)

        # only rhs
        with mock.patch.object(a, 'build_waveform', return_value=None) as build_a, mock.patch.object(b,
                                                                                                     'build_waveform',
                                                                                                     return_value=wf_b) as build_b:
            with mock.patch('qupulse.pulses.arithmetic_pulse_template.ArithmeticWaveform',
                            return_value=wf_arith) as wf_init:
                wf_init.rhs_only_map.__getitem__.return_value.return_value = wf_rhs_only
                self.assertIs(wf_rhs_only, arith.build_waveform(parameters=parameters, channel_mapping=channel_mapping))
                wf_init.assert_not_called()
                wf_init.rhs_only_map.__getitem__.assert_called_once_with('-')
                wf_init.rhs_only_map.__getitem__.return_value.assert_called_once_with(wf_b)

            build_a.assert_called_once_with(parameters=parameters, channel_mapping=channel_mapping)
            build_b.assert_called_once_with(parameters=parameters, channel_mapping=channel_mapping)
    def test_create_program_internal(self) -> None:
        sub1 = DummyPulseTemplate(duration=3, waveform=DummyWaveform(duration=3), measurements=[('b', 1, 2)], defined_channels={'A'})
        sub2 = DummyPulseTemplate(duration=2, waveform=DummyWaveform(duration=2), parameter_names={'foo'}, defined_channels={'A'})
        parameters = {'foo': DummyNoValueParameter()}
        measurement_mapping = {'a': 'a', 'b': 'b'}
        channel_mapping = dict()
        seq = SequencePulseTemplate(sub1, sub2, measurements=[('a', 0, 1)])
        loop = Loop()
        seq._internal_create_program(parameters=parameters,
                                     measurement_mapping=measurement_mapping,
                                     channel_mapping=channel_mapping,
                                     global_transformation=None,
                                     to_single_waveform=set(),
                                     parent_loop=loop)
        self.assertEqual(1, loop.repetition_count)
        self.assertIsNone(loop.waveform)
        self.assertEqual([Loop(repetition_count=1, waveform=sub1.waveform),
                          Loop(repetition_count=1, waveform=sub2.waveform)],
                         loop.children)
        self.assert_measurement_windows_equal({'a': ([0], [1]), 'b': ([1], [2])}, loop.get_measurement_windows())

        # ensure same result as from Sequencer
        sequencer = Sequencer()
        sequencer.push(seq, parameters=parameters, conditions={}, window_mapping=measurement_mapping, channel_mapping=channel_mapping)
        block = sequencer.build()
        old_program = MultiChannelProgram(block, channels={'A'})
        self.assertEqual(old_program.programs[frozenset({'A'})], loop)

        ### test again with inverted sequence
        seq = SequencePulseTemplate(sub2, sub1, measurements=[('a', 0, 1)])
        loop = Loop()
        seq._internal_create_program(parameters=parameters,
                                     measurement_mapping=measurement_mapping,
                                     channel_mapping=channel_mapping,
                                     global_transformation=None,
                                     to_single_waveform=set(),
                                     parent_loop=loop)
        self.assertEqual(1, loop.repetition_count)
        self.assertIsNone(loop.waveform)
        self.assertEqual([Loop(repetition_count=1, waveform=sub2.waveform),
                          Loop(repetition_count=1, waveform=sub1.waveform)],
                         loop.children)
        self.assert_measurement_windows_equal({'a': ([0], [1]), 'b': ([3], [2])}, loop.get_measurement_windows())

        # ensure same result as from Sequencer
        sequencer = Sequencer()
        sequencer.push(seq, parameters=parameters, conditions={}, window_mapping=measurement_mapping, channel_mapping=channel_mapping)
        block = sequencer.build()
        old_program = MultiChannelProgram(block, channels={'A'})
        self.assertEqual(old_program.programs[frozenset({'A'})], loop)
Exemplo n.º 12
0
    def test_get_sampled_argument_forwarding(self):
        wf = DummyWaveform(duration=2.,
                           sample_output=[1, 2],
                           defined_channels={'A', 'B'})

        out_expected = numpy.empty(2)

        out_received = wf.get_sampled('A',
                                      sample_times=numpy.arange(2),
                                      output_array=out_expected)

        self.assertIs(out_expected, out_received)
        self.assertEqual(len(wf.sample_calls), 1)
        self.assertIs(wf.sample_calls[0][-1], out_expected)
        self.assertEqual(out_received.tolist(), [1, 2])
Exemplo n.º 13
0
    def test_unsafe_sample(self):
        dwfs = (DummyWaveform(duration=1.),
                DummyWaveform(duration=3.),
                DummyWaveform(duration=2.))

        swf = SequenceWaveform(dwfs)

        sample_times = np.arange(0, 60)*0.1
        expected_output = np.concatenate((sample_times[:10], sample_times[10:40]-1, sample_times[40:]-4))

        output = swf.unsafe_sample('A', sample_times=sample_times)
        np.testing.assert_equal(expected_output, output)

        output_2 = swf.unsafe_sample('A', sample_times=sample_times, output_array=output)
        self.assertIs(output_2, output)
Exemplo n.º 14
0
    def test_create_program_declaration_success(self) -> None:
        repetitions = "foo"
        body = DummyPulseTemplate(duration=2.0,
                                  waveform=DummyWaveform(
                                      duration=2, defined_channels={'A'}))
        t = RepetitionPulseTemplate(body,
                                    repetitions,
                                    parameter_constraints=['foo<9'])
        scope = DictScope.from_kwargs(foo=3)
        measurement_mapping = dict(moth='fire')
        channel_mapping = dict(asd='f')
        program = Loop()
        t._internal_create_program(scope=scope,
                                   measurement_mapping=measurement_mapping,
                                   channel_mapping=channel_mapping,
                                   to_single_waveform=set(),
                                   global_transformation=None,
                                   parent_loop=program)

        self.assertEqual(1, program.repetition_count)
        self.assertEqual(1, len(program.children))
        internal_loop = program.children[0]  # type: Loop
        self.assertEqual(scope[repetitions], internal_loop.repetition_count)

        self.assertEqual(1, len(internal_loop))
        self.assertEqual(
            (scope, measurement_mapping, channel_mapping, internal_loop),
            body.create_program_calls[-1])
        self.assertEqual(body.waveform, internal_loop[0].waveform)

        self.assert_measurement_windows_equal(
            {}, program.get_measurement_windows())
Exemplo n.º 15
0
    def test_create_program_rep_count_neg_declaration_with_measurements(
            self) -> None:
        repetitions = "foo"
        body_program = Loop(waveform=DummyWaveform(duration=1.0))
        body = DummyPulseTemplate(duration=2.0, program=body_program)

        # suppress warning about 0 repetitions on construction here, we are only interested in correct behavior during sequencing (i.e., do nothing)
        with warnings.catch_warnings(record=True):
            t = RepetitionPulseTemplate(body,
                                        repetitions,
                                        measurements=[('moth', 0, 'meas_end')])

        scope = DictScope.from_kwargs(foo=-1, meas_end=7.1)
        measurement_mapping = dict(moth='fire')
        channel_mapping = dict(asd='f')

        program = Loop()
        t._internal_create_program(scope=scope,
                                   measurement_mapping=measurement_mapping,
                                   channel_mapping=channel_mapping,
                                   to_single_waveform=set(),
                                   global_transformation=None,
                                   parent_loop=program)
        self.assertFalse(body.create_program_calls)
        self.assertFalse(program.children)
        self.assertEqual(1, program.repetition_count)
        self.assertEqual(None, program._measurements)
Exemplo n.º 16
0
    def test_create_program_invalid_measurement_mapping(self) -> None:
        measurement_mapping = {'meas1': 'meas2'}
        parameter_mapping = {'t': 'k'}
        channel_mapping = {'B': 'default'}

        template = DummyPulseTemplate(measurements=[('meas1', 0, 1)], measurement_names={'meas1'},
                                      defined_channels={'B'},
                                      waveform=DummyWaveform(duration=2.0),
                                      duration=2,
                                      parameter_names={'t'})
        st = MappingPulseTemplate(template, parameter_mapping=parameter_mapping,
                                  measurement_mapping=measurement_mapping, channel_mapping=channel_mapping)

        pre_scope = DictScope.from_kwargs(k=5)
        pre_measurement_mapping = {}
        pre_channel_mapping = {'default': 'A'}

        program = Loop()
        with self.assertRaises(KeyError):
            st._internal_create_program(scope=pre_scope,
                                        measurement_mapping=pre_measurement_mapping,
                                        channel_mapping=pre_channel_mapping,
                                        to_single_waveform=set(),
                                        global_transformation=None,
                                        parent_loop=program)
Exemplo n.º 17
0
    def test_create_program_defaults(self) -> None:
        template = PulseTemplateStub(defined_channels={'A', 'B'},
                                     parameter_names={'foo'},
                                     measurement_names={'hugo', 'foo'})

        expected_internal_kwargs = dict(scope=DictScope.from_kwargs(),
                                        measurement_mapping={
                                            'hugo': 'hugo',
                                            'foo': 'foo'
                                        },
                                        channel_mapping={
                                            'A': 'A',
                                            'B': 'B'
                                        },
                                        global_transformation=None,
                                        to_single_waveform=set())

        dummy_waveform = DummyWaveform()
        expected_program = Loop(children=[Loop(waveform=dummy_waveform)])

        with mock.patch.object(template,
                               '_internal_create_program',
                               wraps=get_appending_internal_create_program(
                                   dummy_waveform,
                                   True)) as _internal_create_program:
            program = template.create_program()
            _internal_create_program.assert_called_once_with(
                **expected_internal_kwargs, parent_loop=program)
        self.assertEqual(expected_program, program)
Exemplo n.º 18
0
    def test_get_sampled_exceptions(self):
        wf = DummyWaveform(duration=2., sample_output=[1, 2], defined_channels={'A', 'B'})

        with self.assertRaises(ValueError):
            wf.get_sampled(channel='A',
                           sample_times=numpy.asarray([2, 1], dtype=float))
        with self.assertRaises(ValueError):
            wf.get_sampled(channel='A',
                           sample_times=numpy.asarray([-12, 1], dtype=float))
        with self.assertRaises(KeyError):
                wf.get_sampled(channel='C',
                               sample_times=numpy.asarray([0.5, 1], dtype=float))
        with self.assertRaises(ValueError):
            wf.get_sampled(channel='A',
                           sample_times=numpy.asarray([0.5, 1], dtype=float),
                           output_array=numpy.empty(1))
Exemplo n.º 19
0
    def test_is_compatible_leaf(self):
        self.assertEqual(
            _is_compatible(Loop(waveform=DummyWaveform(duration=1.1),
                                repetition_count=10),
                           min_len=11,
                           quantum=1,
                           sample_rate=time_from_float(1.)),
            _CompatibilityLevel.action_required)

        self.assertEqual(
            _is_compatible(Loop(waveform=DummyWaveform(duration=1.1),
                                repetition_count=10),
                           min_len=11,
                           quantum=1,
                           sample_rate=time_from_float(10.)),
            _CompatibilityLevel.compatible)
    def test_internal_create_program(self):
        template = DummyPulseTemplate(duration='t1', defined_channels={'X', 'Y'}, parameter_names={'a', 'b'},
                                      measurement_names={'M'}, waveform=DummyWaveform())
        overwritten_channels = {'Y': 'c', 'Z': 'a'}

        parent_loop = object()
        measurement_mapping = object()
        channel_mapping = object()
        to_single_waveform = object()

        other_kwargs = dict(measurement_mapping=measurement_mapping,
                            channel_mapping=channel_mapping,
                            to_single_waveform=to_single_waveform,
                            parent_loop=parent_loop)
        pccpt = ParallelConstantChannelPulseTemplate(template, overwritten_channels)

        scope = DictScope.from_kwargs(c=1.2, a=3.4)
        kwargs = {**other_kwargs, 'scope': scope, 'global_transformation': None}

        expected_overwritten_channels = {'Y': 1.2, 'Z': 3.4}
        expected_transformation = ParallelConstantChannelTransformation(expected_overwritten_channels)
        expected_kwargs = {**kwargs, 'global_transformation': expected_transformation}

        with mock.patch.object(template, '_create_program', spec=template._create_program) as cp_mock:
            pccpt._internal_create_program(**kwargs)
            cp_mock.assert_called_once_with(**expected_kwargs)

        global_transformation = LinearTransformation(numpy.zeros((0, 0)), [], [])
        expected_transformation = chain_transformations(global_transformation, expected_transformation)
        kwargs = {**other_kwargs, 'scope': scope, 'global_transformation': global_transformation}
        expected_kwargs = {**kwargs, 'global_transformation': expected_transformation}

        with mock.patch.object(template, '_create_program', spec=template._create_program) as cp_mock:
            pccpt._internal_create_program(**kwargs)
            cp_mock.assert_called_once_with(**expected_kwargs)
    def test_create_program_parameter_constraint_violation(self) -> None:
        measurement_mapping = {'meas1': 'meas2'}
        parameter_mapping = {'t': 'k'}
        channel_mapping = {'B': 'default'}

        template = DummyPulseTemplate(measurements=[('meas1', 0, 1)],
                                      measurement_names={'meas1'},
                                      defined_channels={'B'},
                                      waveform=DummyWaveform(duration=2.0),
                                      duration=2,
                                      parameter_names={'t'})
        st = MappingPulseTemplate(template,
                                  parameter_mapping=parameter_mapping,
                                  measurement_mapping=measurement_mapping,
                                  channel_mapping=channel_mapping,
                                  parameter_constraints={'k > 6'})

        pre_parameters = {'k': ConstantParameter(5)}
        pre_measurement_mapping = {'meas2': 'meas3'}
        pre_channel_mapping = {'default': 'A'}

        program = Loop()
        with self.assertRaises(ParameterConstraintViolation):
            st._internal_create_program(
                parameters=pre_parameters,
                measurement_mapping=pre_measurement_mapping,
                channel_mapping=pre_channel_mapping,
                to_single_waveform=set(),
                global_transformation=None,
                parent_loop=program)
Exemplo n.º 22
0
    def test_loop_to_seqc_leaf(self):
        """Test the translation of leaves"""
        # we use None because it is not used in this test
        user_registers = None

        wf = DummyWaveform(duration=32)
        loop = Loop(waveform=wf)

        # with wrapping repetition
        loop.repetition_count = 15
        waveform_to_bin = mock.Mock(wraps=make_binary_waveform)
        expected = Repeat(loop.repetition_count,
                          WaveformPlayback(waveform=make_binary_waveform(wf)))
        result = loop_to_seqc(loop,
                              1,
                              1,
                              waveform_to_bin,
                              user_registers=user_registers)
        waveform_to_bin.assert_called_once_with(wf)
        self.assertEqual(expected, result)

        # without wrapping repetition
        loop.repetition_count = 1
        waveform_to_bin = mock.Mock(wraps=make_binary_waveform)
        expected = WaveformPlayback(waveform=make_binary_waveform(wf))
        result = loop_to_seqc(loop,
                              1,
                              1,
                              waveform_to_bin,
                              user_registers=user_registers)
        waveform_to_bin.assert_called_once_with(wf)
        self.assertEqual(expected, result)
Exemplo n.º 23
0
    def setUp(self) -> None:
        self.channels = ('A', None, 'C')
        self.marker = (None, 'M')
        self.amplitudes = (1., 1., .5)
        self.offset = (0., .5, .0)
        self.voltage_transformations = (mock.Mock(wraps=lambda x: x),
                                        mock.Mock(wraps=lambda x: x),
                                        mock.Mock(wraps=lambda x: x))
        self.sample_rate = TimeType.from_float(1)

        N = 100
        t = np.arange(N)

        self.sampled = [
            dict(A=np.linspace(-.1, .1, num=N),
                 C=.1 * np.sin(t),
                 M=np.arange(N) % 2),
            dict(A=np.linspace(.1, -.1, num=N // 2),
                 C=.1 * np.cos(t[::2]),
                 M=np.arange(N // 2) % 3)
        ]
        self.waveforms = [
            wf for wf in (DummyWaveform(sample_output=sampled,
                                        duration=sampled['A'].size)
                          for sampled in self.sampled)
        ]
        self.loop = Loop(children=[Loop(waveform=wf)
                                   for wf in self.waveforms] * 2)
Exemplo n.º 24
0
    def test_unsafe_get_subset_for_channels(self):
        dwf_1 = DummyWaveform(duration=2.2, defined_channels={'A', 'B', 'C'})
        dwf_2 = DummyWaveform(duration=3.3, defined_channels={'A', 'B', 'C'})

        wf = SequenceWaveform([dwf_1, dwf_2])

        subset = {'A', 'C'}
        sub_wf = wf.unsafe_get_subset_for_channels(subset)
        self.assertIsInstance(sub_wf, SequenceWaveform)

        self.assertEqual(len(sub_wf.compare_key), 2)
        self.assertEqual(sub_wf.compare_key[0].defined_channels, subset)
        self.assertEqual(sub_wf.compare_key[1].defined_channels, subset)

        self.assertEqual(sub_wf.compare_key[0].duration, TimeType.from_float(2.2))
        self.assertEqual(sub_wf.compare_key[1].duration, TimeType.from_float(3.3))
    def test_build_waveform(self):
        template = DummyPulseTemplate(duration='t1',
                                      defined_channels={'X', 'Y'},
                                      parameter_names={'a', 'b'},
                                      measurement_names={'M'},
                                      waveform=DummyWaveform())
        overwritten_channels = {'Y': 'c', 'Z': 'a'}
        channel_mapping = {'X': 'X', 'Y': 'K'}
        pccpt = ParallelConstantChannelPulseTemplate(template,
                                                     overwritten_channels)

        parameters = {'c': 1.2, 'a': 3.4}
        expected_overwritten_channels = {'Y': 1.2, 'Z': 3.4}
        expected_transformation = ParallelConstantChannelTransformation(
            expected_overwritten_channels)
        expected_waveform = TransformingWaveform(template.waveform,
                                                 expected_transformation)

        resulting_waveform = pccpt.build_waveform(parameters.copy(),
                                                  channel_mapping.copy())
        self.assertEqual(expected_waveform, resulting_waveform)

        self.assertEqual([(parameters, channel_mapping)],
                         template.build_waveform_calls)

        template.waveform = None
        resulting_waveform = pccpt.build_waveform(parameters.copy(),
                                                  channel_mapping.copy())
        self.assertEqual(None, resulting_waveform)
        self.assertEqual([(parameters, channel_mapping),
                          (parameters, channel_mapping)],
                         template.build_waveform_calls)
Exemplo n.º 26
0
    def test_unsafe_sample(self):
        time = np.linspace(10, 20, num=25)
        ch_a = np.exp(time)
        ch_b = np.exp(-time)
        ch_c = np.sinh(time)
        ch_d = np.cosh(time)
        ch_e = np.arctan(time)

        sample_output = {'a': ch_a, 'b': ch_b}
        expected_call_data = sample_output

        transformed = {'c': ch_c, 'd': ch_d, 'e': ch_e}

        trafo = TransformationDummy(transformed=transformed, input_channels={'a', 'b'})
        inner_wf = DummyWaveform(duration=1.5, defined_channels={'a', 'b'}, sample_output=sample_output)
        trafo_wf = TransformingWaveform(inner_waveform=inner_wf, transformation=trafo)

        np.testing.assert_equal(ch_c, trafo_wf.unsafe_sample('c', time))
        np.testing.assert_equal(ch_d, trafo_wf.unsafe_sample('d', time))
        np.testing.assert_equal(ch_e, trafo_wf.unsafe_sample('e', time))

        output = np.empty_like(time)
        ch_d_out = trafo_wf.unsafe_sample('d', time, output_array=output)
        self.assertIs(output, ch_d_out)
        np.testing.assert_equal(ch_d_out, ch_d)

        call_list = TransformationDummy.__call__.call_args_list
        self.assertEqual(len(call_list), 1)

        (pos_args, kw_args), = call_list
        self.assertEqual(kw_args, {})

        c_time, c_data = pos_args
        np.testing.assert_equal((time, expected_call_data), pos_args)
Exemplo n.º 27
0
    def test_internal_create_program(self) -> None:
        measurement_windows = [('M', 0, 5)]
        single_wf = DummyWaveform(duration=6, defined_channels={'A'})
        wf = MultiChannelWaveform([single_wf])

        template = AtomicPulseTemplateStub(measurements=measurement_windows,
                                           parameter_names={'foo'})
        scope = DictScope.from_kwargs(foo=7.2, volatile={'gutes_zeuch'})
        measurement_mapping = {'M': 'N'}
        channel_mapping = {'B': 'A'}
        program = Loop()

        expected_program = Loop(children=[Loop(waveform=wf)],
                                measurements=[('N', 0, 5)])

        with mock.patch.object(template, 'build_waveform',
                               return_value=wf) as build_waveform:
            template._internal_create_program(
                scope=scope,
                measurement_mapping=measurement_mapping,
                channel_mapping=channel_mapping,
                parent_loop=program,
                to_single_waveform=set(),
                global_transformation=None)
            build_waveform.assert_called_once_with(
                parameters=scope, channel_mapping=channel_mapping)

        self.assertEqual(expected_program, program)

        # MultiChannelProgram calls cleanup
        program.cleanup()
Exemplo n.º 28
0
    def test_create_program_constraint_on_loop_var_exception(self):
        """This test is to assure the status-quo behavior of ForLoopPT handling parameter constraints affecting the loop index
        variable. Please see https://github.com/qutech/qupulse/issues/232 ."""

        with self.assertWarnsRegex(UserWarning, "constraint on a variable shadowing the loop index",
                                   msg="ForLoopPT did not issue a warning when constraining the loop index"):
            flt = ForLoopPulseTemplate(body=DummyPulseTemplate(parameter_names={'k', 'i'}), loop_index='i',
                                       loop_range=('a', 'b', 'c',), parameter_constraints=['k<=f', 'k>i'])

        # loop index showing up in parameter_names because it appears in consraints
        self.assertEqual(flt.parameter_names, {'f', 'k', 'a', 'b', 'c', 'i'})

        scope = DictScope.from_kwargs(k=1, a=0, b=2, c=1, f=2)

        # loop index not accessible in current build_sequence -> Exception
        children = [Loop(waveform=DummyWaveform(duration=2.0))]
        program = Loop(children=children)

        with self.assertRaises(ParameterNotProvidedException):
            flt._internal_create_program(scope=scope,
                                         measurement_mapping=dict(),
                                         channel_mapping=dict(),
                                         parent_loop=program,
                                         to_single_waveform=set(),
                                         global_transformation=None)
        self.assertEqual(children, list(program.children))
        self.assertEqual(1, program.repetition_count)
        self.assertIsNone(program._measurements)
        self.assert_measurement_windows_equal({}, program.get_measurement_windows())
Exemplo n.º 29
0
    def test_sample_times_type(self) -> None:
        with mock.patch.object(DummyWaveform, 'unsafe_sample') as unsafe_sample_patch:
            dwfs = (DummyWaveform(duration=1.),
                    DummyWaveform(duration=3.),
                    DummyWaveform(duration=2.))

            swf = SequenceWaveform(dwfs)

            sample_times = np.arange(0, 60) * 0.1
            expected_output = np.concatenate((sample_times[:10], sample_times[10:40] - 1, sample_times[40:] - 4))
            expected_inputs = sample_times[0:10], sample_times[10:40] - 1, sample_times[40:] - 4

            swf.unsafe_sample('A', sample_times=sample_times)
            inputs = [call_args[1]['sample_times'] for call_args in unsafe_sample_patch.call_args_list] # type: List[np.ndarray]
            np.testing.assert_equal(expected_inputs, inputs)
            self.assertEqual([input.dtype for input in inputs], [np.float64 for _ in inputs])
Exemplo n.º 30
0
    def test_add_instruction_exec(self) -> None:
        block = InstructionBlock()
        expected_instructions = []

        waveforms = [DummyWaveform(), DummyWaveform(), DummyWaveform()]
        LOOKUP = [0, 1, 1, 0, 2, 1, 0, 0, 0, 1, 2, 2]
        for id in LOOKUP:
            waveform = waveforms[id]
            instruction = EXECInstruction(waveform)
            expected_instructions.append(instruction)
            block.add_instruction_exec(waveform)

        expected_compiled_instructions = expected_instructions.copy()
        expected_compiled_instructions.append(STOPInstruction())
        self.__verify_block(block, expected_instructions,
                            expected_compiled_instructions, None)