def test_multiple_channels_mismatch(self) -> None:
        with self.assertRaises(ValueError):
            SequencePulseTemplate(DummyPulseTemplate(defined_channels={'A'}),
                                  DummyPulseTemplate(defined_channels={'B'}))

        with self.assertRaises(ValueError):
            SequencePulseTemplate(
                DummyPulseTemplate(defined_channels={'A'}),
                DummyPulseTemplate(defined_channels={'A', 'B'}),
                external_parameters=set())
    def test_build_sequence(self) -> None:
        sub1 = DummyPulseTemplate(requires_stop=False)
        sub2 = DummyPulseTemplate(requires_stop=True, parameter_names={'foo'})
        parameters = {'foo': DummyNoValueParameter()}

        sequencer = DummySequencer()
        block = DummyInstructionBlock()
        seq = SequencePulseTemplate(sub1, (sub2, {
            'foo': 'foo'
        }),
                                    external_parameters={'foo'},
                                    measurements=[('a', 0, 1)])
        seq.build_sequence(sequencer,
                           parameters,
                           conditions=dict(),
                           channel_mapping={'default': 'a'},
                           measurement_mapping={'a': 'b'},
                           instruction_block=block)
        self.assertEqual(2, len(sequencer.sequencing_stacks[block]))

        self.assertEqual(block.instructions[0], MEASInstruction([('b', 0, 1)]))

        sequencer = DummySequencer()
        block = DummyInstructionBlock()
        seq = SequencePulseTemplate((sub2, {
            'foo': 'foo'
        }),
                                    sub1,
                                    external_parameters={'foo'})
        seq.build_sequence(sequencer, parameters, {}, {}, {}, block)
        self.assertEqual(2, len(sequencer.sequencing_stacks[block]))
    def test_get_serialization_data(self) -> None:
        dummy1 = DummyPulseTemplate()
        dummy2 = DummyPulseTemplate()

        sequence = SequencePulseTemplate(dummy1,
                                         dummy2,
                                         parameter_constraints=['a<b'])
        serializer = DummySerializer(serialize_callback=lambda x: str(x))

        expected_data = dict(
            subtemplates=[str(dummy1), str(dummy2)],
            parameter_constraints=[ParameterConstraint('a<b')])
        data = sequence.get_serialization_data(serializer)
        self.assertEqual(expected_data, data)
    def test_crash(self) -> None:
        table = TablePulseTemplate(
            {
                'default': [('ta', 'va', 'hold'), ('tb', 'vb', 'linear'),
                            ('tend', 0, 'jump')]
            },
            identifier='foo')

        external_parameters = ['ta', 'tb', 'tc', 'td', 'va', 'vb', 'tend']
        first_mapping = {
            'ta': 'ta',
            'tb': 'tb',
            'va': 'va',
            'vb': 'vb',
            'tend': 'tend'
        }
        second_mapping = {
            'ta': 'tc',
            'tb': 'td',
            'va': 'vb',
            'vb': 'va + vb',
            'tend': '2 * tend'
        }
        sequence = SequencePulseTemplate(
            (table, first_mapping, {}), (table, second_mapping, {}),
            external_parameters=external_parameters)

        parameters = {
            'ta': ConstantParameter(2),
            'va': ConstantParameter(2),
            'tb': ConstantParameter(4),
            'vb': ConstantParameter(3),
            'tc': ConstantParameter(5),
            'td': ConstantParameter(11),
            'tend': ConstantParameter(6)
        }

        sequencer = DummySequencer()
        block = DummyInstructionBlock()
        self.assertFalse(sequence.requires_stop(parameters, {}))
        sequence.build_sequence(sequencer,
                                parameters=parameters,
                                conditions={},
                                measurement_mapping={},
                                channel_mapping={'default': 'default'},
                                instruction_block=block)
        from qctoolkit.pulses.sequencing import Sequencer
        s = Sequencer()
        s.push(sequence, parameters, channel_mapping={'default': 'EXAMPLE_A'})
        s.build()
    def test_is_interruptable(self):

        self.assertTrue(
            SequencePulseTemplate(
                DummyPulseTemplate(is_interruptable=True),
                DummyPulseTemplate(is_interruptable=True)).is_interruptable)
        self.assertTrue(
            SequencePulseTemplate(
                DummyPulseTemplate(is_interruptable=True),
                DummyPulseTemplate(is_interruptable=False)).is_interruptable)
        self.assertFalse(
            SequencePulseTemplate(
                DummyPulseTemplate(is_interruptable=False),
                DummyPulseTemplate(is_interruptable=False)).is_interruptable)
    def test_table_sequence_sequencer_integration(self) -> None:
        t1 = TablePulseTemplate()
        t1.add_entry(2, 'foo')
        t1.add_entry(5, 0)

        t2 = TablePulseTemplate()
        t2.add_entry(4, 0)
        t2.add_entry(4.5, 'bar', 'linear')
        t2.add_entry(5, 0)

        seqt = SequencePulseTemplate([(t1, {'foo': 'foo'}), (t2, {'bar': '2 * hugo'})], {'foo', 'hugo'})

        with self.assertRaises(ParameterNotProvidedException):
            t1.requires_stop(dict(), dict())
        with self.assertRaises(ParameterNotProvidedException):
            t2.requires_stop(dict(), dict())
        self.assertFalse(seqt.requires_stop({}, {}))

        foo = DummyNoValueParameter()
        bar = DummyNoValueParameter()
        sequencer = Sequencer()
        sequencer.push(seqt, {'foo': foo, 'hugo': bar})
        instructions = sequencer.build()
        self.assertFalse(sequencer.has_finished())
        self.assertEqual(1, len(instructions))

        foo = DummyParameter(value=1.1)
        bar = DummyNoValueParameter()
        sequencer = Sequencer()
        sequencer.push(seqt, {'foo': foo, 'hugo': bar})
        instructions = sequencer.build()
        self.assertFalse(sequencer.has_finished())
        self.assertEqual(2, len(instructions))

        foo = DummyParameter(value=1.1)
        bar = DummyNoValueParameter()
        sequencer = Sequencer()
        sequencer.push(seqt, {'foo': bar, 'hugo': foo})
        instructions = sequencer.build()
        self.assertFalse(sequencer.has_finished())
        self.assertEqual(1, len(instructions))

        foo = DummyParameter(value=1.1)
        bar = DummyParameter(value=-0.2)
        sequencer = Sequencer()
        sequencer.push(seqt, {'foo': foo, 'hugo': bar})
        instructions = sequencer.build()
        self.assertTrue(sequencer.has_finished())
        self.assertEqual(3, len(instructions))
    def test_init(self):
        with self.assertRaises(MissingParameterDeclarationException):
            SequencePulseTemplate(
                DummyPulseTemplate(parameter_names={'a', 'b'}),
                external_parameters={'a'})

        with self.assertRaises(MissingParameterDeclarationException):
            SequencePulseTemplate(DummyPulseTemplate(parameter_names={'a'}),
                                  parameter_constraints=['b < 4'],
                                  external_parameters={'a'})

        with self.assertRaises(MissingMappingException):
            SequencePulseTemplate(DummyPulseTemplate(parameter_names={'a'}),
                                  parameter_constraints=['b < 4'],
                                  external_parameters={'a', 'b', 'c'})
    def __rmatmul__(self, other: MappingTuple) -> 'SequencePulseTemplate':
        from qctoolkit.pulses.sequence_pulse_template import SequencePulseTemplate

        subtemplates = itertools.chain(
            [other], self.subtemplates
            if isinstance(self, SequencePulseTemplate) else [self])
        return SequencePulseTemplate(*subtemplates)
    def test_unnecessary_mapping(self) -> None:
        mapping = self.mapping1
        mapping['unnecessary'] = 'voltage'

        subtemplates = [(self.square, mapping)]
        with self.assertRaises(UnnecessaryMappingException):
            SequencePulseTemplate(subtemplates, self.outer_parameters)
Exemple #10
0
    def test_serialization_and_deserialization_combined(self) -> None:
        table_foo = TablePulseTemplate(
            identifier='foo',
            entries={'default': [('hugo', 2), ('albert', 'voltage')]},
            parameter_constraints=['albert<9.1'])
        table = TablePulseTemplate({'default': [('t', 0)]})

        foo_mappings = dict(hugo='ilse', albert='albert', voltage='voltage')
        sequence = SequencePulseTemplate(
            (table_foo, foo_mappings, dict()), (table, dict(t=0), dict()),
            external_parameters=['ilse', 'albert', 'voltage'],
            identifier=None)

        storage = DummyStorageBackend()
        serializer = Serializer(storage)
        serializer.serialize(sequence)

        serialized_foo = storage.stored_items['foo']
        serialized_sequence = storage.stored_items['main']

        deserialized_sequence = serializer.deserialize('main')
        storage.stored_items = dict()
        serializer.serialize(deserialized_sequence)

        self.assertEqual(serialized_foo, storage.stored_items['foo'])
        self.assertEqual(serialized_sequence, storage.stored_items['main'])
    def test_get_serialization_data(self) -> None:
        sequence = SequencePulseTemplate([(self.table_foo, self.foo_mappings), (self.table, {})],
                                         ['ilse', 'albert', 'voltage'],
                                         identifier='foo')

        expected_data = dict(
            type=self.serializer.get_type_identifier(sequence),
            external_parameters=['albert', 'ilse', 'voltage'],
            is_interruptable=True,
            subtemplates = [
                dict(template=str(id(self.table_foo)), mappings=self.foo_mappings),
                dict(template=str(id(self.table)), mappings=dict())
            ]
        )
        data = sequence.get_serialization_data(self.serializer)
        self.assertEqual(expected_data, data)
    def test_missing_mapping(self) -> None:
        mapping = self.mapping1
        mapping.pop('v')

        subtemplates = [(self.square, mapping)]
        with self.assertRaises(MissingMappingException):
            SequencePulseTemplate(subtemplates, self.outer_parameters)
    def test_missing_parameter_declaration_exception(self) -> None:
        mapping = copy.deepcopy(self.mapping1)
        mapping['up'] = "foo"

        subtemplates = [(self.square, mapping)]
        with self.assertRaises(MissingParameterDeclarationException):
            SequencePulseTemplate(subtemplates, self.outer_parameters)
    def test_deserialize(self) -> None:
        data = dict(
            external_parameters={'ilse', 'albert', 'voltage'},
            is_interruptable=True,
            subtemplates = [
                dict(template=str(id(self.table_foo)), mappings=self.foo_mappings),
                dict(template=str(id(self.table)), mappings=dict())
            ],
            identifier='foo'
        )

        # prepare dependencies for deserialization
        self.serializer.subelements[str(id(self.table_foo))] = self.table_foo
        self.serializer.subelements[str(id(self.table))] = self.table

        # deserialize
        sequence = SequencePulseTemplate.deserialize(self.serializer, **data)

        # compare!
        self.assertEqual(data['external_parameters'], sequence.parameter_names)
        self.assertEqual({ParameterDeclaration('ilse'), ParameterDeclaration('albert'), ParameterDeclaration('voltage')},
                         sequence.parameter_declarations)
        self.assertIs(self.table_foo, sequence.subtemplates[0][0])
        self.assertIs(self.table, sequence.subtemplates[1][0])
        self.assertEqual(self.foo_mappings, {k: m.string for k,m in sequence.subtemplates[0][1].items()})
        self.assertEqual(dict(), sequence.subtemplates[1][1])
        self.assertEqual(data['identifier'], sequence.identifier)
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        # Setup test data
        self.square = TablePulseTemplate()
        self.square.add_entry('up', 'v', 'hold')
        self.square.add_entry('down', 0, 'hold')
        self.square.add_entry('length', 0)

        self.mapping1 = {
            'up': 'uptime',
            'down': 'uptime + length',
            'v': 'voltage',
            'length': '0.5 * pulse_length'
        }

        self.outer_parameters = ['uptime', 'length', 'pulse_length', 'voltage']

        self.parameters = {}
        self.parameters['uptime'] = ConstantParameter(5)
        self.parameters['length'] = ConstantParameter(10)
        self.parameters['pulse_length'] = ConstantParameter(100)
        self.parameters['voltage'] = ConstantParameter(10)

        self.sequence = SequencePulseTemplate([(self.square, self.mapping1)],
                                              self.outer_parameters)
    def test_measurement_names(self):
        d1 = DummyPulseTemplate(measurement_names={'a'})
        d2 = DummyPulseTemplate(measurement_names={'b'})

        spt = SequencePulseTemplate(d1, d2, measurements=[('c', 0, 1)])

        self.assertEqual(spt.measurement_names, {'a', 'b', 'c'})
    def __init__(self, *args, **kwargs) -> None:
        super().__init__(*args, **kwargs)

        # Setup test data
        self.square = TablePulseTemplate(
            {
                'default': [(0, 0), ('up', 'v', 'hold'), ('down', 0, 'hold'),
                            ('length', 0)]
            },
            measurements=[('mw1', 'up', 'length-up')])
        self.mapping1 = {
            'up': 'uptime',
            'down': 'uptime + length',
            'v': 'voltage',
            'length': '0.5 * pulse_length'
        }

        self.window_name_mapping = {'mw1': 'test_window'}

        self.outer_parameters = {'uptime', 'length', 'pulse_length', 'voltage'}

        self.parameters = dict()
        self.parameters['uptime'] = ConstantParameter(5)
        self.parameters['length'] = ConstantParameter(10)
        self.parameters['pulse_length'] = ConstantParameter(100)
        self.parameters['voltage'] = ConstantParameter(10)

        self.sequence = SequencePulseTemplate(
            MappingPulseTemplate(self.square,
                                 parameter_mapping=self.mapping1,
                                 measurement_mapping=self.window_name_mapping),
            external_parameters=self.outer_parameters)
    def test_crash(self) -> None:
        table = TablePulseTemplate(identifier='foo')
        table.add_entry('ta', 'va', interpolation='hold')
        table.add_entry('tb', 'vb', interpolation='linear')
        table.add_entry('tend', 0, interpolation='jump')

        external_parameters = ['ta', 'tb', 'tc', 'td', 'va', 'vb', 'tend']
        first_mapping = {
            'ta': 'ta',
            'tb': 'tb',
            'va': 'va',
            'vb': 'vb',
            'tend': 'tend'
        }
        second_mapping = {
            'ta': 'tc',
            'tb': 'td',
            'va': 'vb',
            'vb': 'va + vb',
            'tend': '2 * tend'
        }
        sequence = SequencePulseTemplate([(table, first_mapping),
                                          (table, second_mapping)],
                                         external_parameters)

        parameters = {
            'ta': ConstantParameter(2),
            'va': ConstantParameter(2),
            'tb': ConstantParameter(4),
            'vb': ConstantParameter(3),
            'tc': ConstantParameter(5),
            'td': ConstantParameter(11),
            'tend': ConstantParameter(6)
        }

        sequencer = DummySequencer()
        block = DummyInstructionBlock()
        self.assertFalse(sequence.requires_stop(parameters, {}))
        sequence.build_sequence(sequencer, parameters, {}, block)
        from qctoolkit.pulses.sequencing import Sequencer
        s = Sequencer()
        s.push(sequence, parameters)
        s.build()
    def test_build_waveform(self):
        wfs = [DummyWaveform(), DummyWaveform()]
        pts = [DummyPulseTemplate(waveform=wf) for wf in wfs]

        spt = SequencePulseTemplate(*pts, parameter_constraints=['a < 3'])
        with self.assertRaises(ParameterConstraintViolation):
            spt.build_waveform(dict(a=4), dict())

        parameters = dict(a=2)
        channel_mapping = dict()
        wf = spt.build_waveform(parameters, channel_mapping=channel_mapping)

        for wfi, pt in zip(wfs, pts):
            self.assertEqual(pt.build_waveform_calls, [(parameters, dict())])
            self.assertIs(pt.build_waveform_calls[0][0], parameters)

        self.assertIsInstance(wf, SequenceWaveform)
        for wfa, wfb in zip(wf.compare_key, wfs):
            self.assertIs(wfa, wfb)
 def test_get_serialization_data(self) -> None:
     serializer = DummySerializer(serialize_callback=lambda x: str(x))
     foo_mappings = {k: Expression(v) for k, v in self.foo_mappings.items()}
     sequence = SequencePulseTemplate([(self.table_foo, self.foo_mappings),
                                       (self.table, {})],
                                      ['ilse', 'albert', 'voltage'],
                                      identifier='foo')
     expected_data = dict(
         type=serializer.get_type_identifier(sequence),
         external_parameters=['albert', 'ilse', 'voltage'],
         is_interruptable=True,
         subtemplates=[
             dict(template=str(self.table_foo),
                  mappings={k: str(v)
                            for k, v in foo_mappings.items()}),
             dict(template=str(self.table), mappings=dict())
         ])
     data = sequence.get_serialization_data(serializer)
     self.assertEqual(expected_data, data)
    def test_concatenation_sequence_table_pulse_double_parameter(self):
        a = TablePulseTemplate()
        a.add_entry('t', 'a')
        b = TablePulseTemplate()
        b.add_entry('t', 'a')

        subtemplates = [(b, {'t': 't', 'a': 'a'})]
        seq = SequencePulseTemplate(subtemplates, ['t', 'a'])

        with self.assertRaises(DoubleParameterNameException) as e:
            concat = seq @ a
 def test_multiple_channels(self) -> None:
     dummy = DummyPulseTemplate(parameter_names={'hugo'},
                                defined_channels={'A', 'B'})
     subtemplates = [(dummy, {
         'hugo': 'foo'
     }, {}), (dummy, {
         'hugo': '3'
     }, {})]
     sequence = SequencePulseTemplate(*subtemplates,
                                      external_parameters={'foo'})
     self.assertEqual({'A', 'B'}, sequence.defined_channels)
    def test_concatenation_sequence_table_pulse(self):
        a = TablePulseTemplate()
        a.add_entry('t', 'a')
        b = TablePulseTemplate()
        b.add_entry('t', 'a')

        subtemplates = [(b, {'t': 't_ext', 'a': 'a_ext'})]
        seq = SequencePulseTemplate(subtemplates, ['t_ext', 'a_ext'])

        concat = seq @ a
        subtemplates2 = [(seq, {
            't_ext': 't_ext',
            'a_ext': 'a_ext'
        }), (a, {
            't': 't',
            'a': 'a'
        })]
        seq2 = SequencePulseTemplate(subtemplates2,
                                     ['a', 'a_ext', 't', 't_ext'])
        self.assertEqual(concat.parameter_names, seq2.parameter_names)
        self.assertEqual(concat.subtemplates, seq2.subtemplates)
    def __matmul__(
        self, other: Union['PulseTemplate',
                           MappingTuple]) -> 'SequencePulseTemplate':
        """This method enables using the @-operator (intended for matrix multiplication) for
         concatenating pulses. If one of the pulses is a SequencePulseTemplate the other pulse gets merged into it"""

        from qctoolkit.pulses.sequence_pulse_template import SequencePulseTemplate

        subtemplates = itertools.chain(
            self.subtemplates if isinstance(self, SequencePulseTemplate)
            else [self], other.subtemplates if isinstance(
                other, SequencePulseTemplate) else [other])
        return SequencePulseTemplate(*subtemplates)
    def test_concatenation_sequence_table_pulse(self):
        a = DummyPulseTemplate(parameter_names={'foo'}, defined_channels={'A'})
        b = DummyPulseTemplate(parameter_names={'bar'}, defined_channels={'A'})
        c = DummyPulseTemplate(parameter_names={'snu'}, defined_channels={'A'})
        d = DummyPulseTemplate(parameter_names={'snu'}, defined_channels={'A'})

        seq1 = SequencePulseTemplate(a, b, external_parameters=['foo', 'bar'])
        seq2 = SequencePulseTemplate(c, d, external_parameters=['snu'])

        seq = seq1 @ c
        self.assertTrue(len(seq.subtemplates) == 3)
        for st, expected in zip(seq.subtemplates, [a, b, c]):
            self.assertTrue(st, expected)

        seq = c @ seq1
        self.assertTrue(len(seq.subtemplates) == 3)
        for st, expected in zip(seq.subtemplates, [c, a, b]):
            self.assertTrue(st, expected)

        seq = seq1 @ seq2
        self.assertTrue(len(seq.subtemplates) == 4)
        for st, expected in zip(seq.subtemplates, [a, b, c, d]):
            self.assertTrue(st, expected)
Exemple #26
0
 def __matmul__(self, other) -> 'SequencePulseTemplate':
     """This method enables us to use the @-operator (intended for matrix multiplication) for
      concatenating pulses"""
     from qctoolkit.pulses.sequence_pulse_template import SequencePulseTemplate
     # check if parameter names of the subpulses clash, otherwise construct a default mapping
     double_parameters = self.parameter_names & other.parameter_names  # intersection
     if double_parameters:
         # if there are parameter name conflicts, throw an exception
         raise DoubleParameterNameException(self, other, double_parameters)
     else:
         subtemplates = [(self, {p: p
                                 for p in self.parameter_names}),
                         (other, {p: p
                                  for p in other.parameter_names})]
         external_parameters = self.parameter_names | other.parameter_names  # union
         return SequencePulseTemplate(subtemplates, external_parameters)
    def test_deserialize(self) -> None:
        dummy1 = DummyPulseTemplate()
        dummy2 = DummyPulseTemplate()

        serializer = DummySerializer(serialize_callback=lambda x: str(id(x)))

        data = dict(subtemplates=[
            serializer.dictify(dummy1),
            serializer.dictify(dummy2)
        ],
                    identifier='foo',
                    parameter_constraints=['a<b'])

        template = SequencePulseTemplate.deserialize(serializer, **data)
        self.assertEqual(template.subtemplates, [dummy1, dummy2])
        self.assertEqual(template.parameter_constraints,
                         [ParameterConstraint('a<b')])
    def test_build_sequence(self) -> None:
        sub1 = DummyPulseTemplate(requires_stop=False)
        sub2 = DummyPulseTemplate(requires_stop=True, parameter_names={'foo'})
        parameters = {'foo': DummyNoValueParameter()}

        sequencer = DummySequencer()
        block = DummyInstructionBlock()
        seq = SequencePulseTemplate([(sub1, {}), (sub2, {
            'foo': 'foo'
        })], {'foo'})
        seq.build_sequence(sequencer, parameters, {}, block)
        self.assertEqual(2, len(sequencer.sequencing_stacks[block]))

        sequencer = DummySequencer()
        block = DummyInstructionBlock()
        seq = SequencePulseTemplate([(sub2, {
            'foo': 'foo'
        }), (sub1, {})], {'foo'})
        seq.build_sequence(sequencer, parameters, {}, block)
        self.assertEqual(2, len(sequencer.sequencing_stacks[block]))
    def integrated_test_with_sequencer_and_pulse_templates(self) -> None:
        # Setup test data
        square = TablePulseTemplate()
        square.add_entry('up', 'v', 'hold')
        square.add_entry('down', 0, 'hold')
        square.add_entry('length', 0)

        mapping1 = {
            'up': 'uptime',
            'down': 'uptime + length',
            'v': 'voltage',
            'length': '0.5 * pulse_length'
        }

        outer_parameters = ['uptime', 'length', 'pulse_length', 'voltage']

        parameters = {}
        parameters['uptime'] = 5
        parameters['length'] = 10
        parameters['pulse_length'] = 100
        parameters['voltage'] = 10

        sequence = SequencePulseTemplate([(square, mapping1),
                                          (square, mapping1)],
                                         outer_parameters)

        # run the sequencer and render the plot
        sample_rate = 20
        plotter = Plotter(sample_rate=sample_rate)
        sequencer = Sequencer(plotter)
        sequencer.push(sequence, parameters)
        block = sequencer.build()
        times, voltages = plotter.render(block)

        # compute expected values
        expected_times = numpy.linspace(0, 100, sample_rate)
        expected_voltages = numpy.zeros_like(expected_times)
        expected_voltages[100:300] = numpy.ones(200) * parameters['voltage']

        # compare
        self.assertEqual(expected_times, times)
        self.assertEqual(expected_voltages, voltages)
Exemple #30
0
    def test_serialization_and_deserialization_combined(self) -> None:
        table_foo = TablePulseTemplate(identifier='foo')
        table_foo.add_entry('hugo', 2)
        table_foo.add_entry(ParameterDeclaration('albert', max=9.1), 'voltage')
        table = TablePulseTemplate(measurement=True)
        foo_mappings = dict(hugo='ilse', albert='albert', voltage='voltage')
        sequence = SequencePulseTemplate([(table_foo, foo_mappings),
                                          (table, {})],
                                         ['ilse', 'albert', 'voltage'],
                                         identifier=None)

        storage = DummyStorageBackend()
        serializer = Serializer(storage)
        serializer.serialize(sequence)

        serialized_foo = storage.stored_items['foo']
        serialized_sequence = storage.stored_items['main']

        deserialized_sequence = serializer.deserialize('main')
        storage.stored_items = dict()
        serializer.serialize(deserialized_sequence)

        self.assertEqual(serialized_foo, storage.stored_items['foo'])
        self.assertEqual(serialized_sequence, storage.stored_items['main'])
    def test_deserialize(self) -> None:
        foo_mappings = {k: Expression(v) for k, v in self.foo_mappings.items()}
        data = dict(
            external_parameters={'ilse', 'albert', 'voltage'},
            is_interruptable=True,
            subtemplates=[
                dict(template=str(id(self.table_foo)),
                     mappings={k: str(id(v))
                               for k, v in foo_mappings.items()}),
                dict(template=str(id(self.table)), mappings=dict())
            ],
            identifier='foo')

        # prepare dependencies for deserialization
        self.serializer.subelements[str(id(self.table_foo))] = self.table_foo
        self.serializer.subelements[str(id(self.table))] = self.table
        for v in foo_mappings.values():
            self.serializer.subelements[str(id(v))] = v

        # deserialize
        sequence = SequencePulseTemplate.deserialize(self.serializer, **data)

        # compare!
        self.assertEqual(data['external_parameters'], sequence.parameter_names)
        self.assertEqual(
            {
                ParameterDeclaration('ilse'),
                ParameterDeclaration('albert'),
                ParameterDeclaration('voltage')
            }, sequence.parameter_declarations)
        self.assertIs(self.table_foo, sequence.subtemplates[0][0])
        self.assertIs(self.table, sequence.subtemplates[1][0])
        #self.assertEqual(self.foo_mappings, {k: m.string for k,m in sequence.subtemplates[0][1].items()})
        self.assertEqual(foo_mappings, sequence.subtemplates[0][1])
        self.assertEqual(dict(), sequence.subtemplates[1][1])
        self.assertEqual(data['identifier'], sequence.identifier)
Exemple #32
0
# with these parameters, we can plot the pulse:
plot(squarePulse, parameters)

# To re-parametrize we can simply wrap the pulse definition in a SequencePulseTemplate that provides functionality
# for mapping its own parameters onto children parameters.

mapping = {}
mapping['t_up'] = 'start'
mapping['t_down'] = 'start + length'
mapping['value1'] = 'value1'
mapping['value2'] = 'value2'
mapping['end'] = 'pulse_length * 0.5'

doubleSquare = SequencePulseTemplate(
    [
        (squarePulse, mapping), (squarePulse, mapping)
    ],  # dictionaries with mapping functions from external parameters to subtemplate parameters
    ['start', 'length', 'value1', 'value2', 'pulse_length'
     ])  # declare the new template's external parameters

params = dict(start=5, length=20, value1=10, value2=15, pulse_length=500)

plot(doubleSquare, params)

nested_mapping = dict(start='start',
                      length='length',
                      value1='10',
                      value2='20',
                      pulse_length='pulse_length * 0.5')

nested_pulse = SequencePulseTemplate([(doubleSquare, nested_mapping),
                                      (doubleSquare, nested_mapping)],
 def test_requires_stop(self):
     seq = SequencePulseTemplate([],[])
     self.assertFalse(seq.requires_stop({}, {}))