How to use _default_to_regular method in molecule

Best Python code snippet using molecule_python

collections.py

Source:collections.py Github

copy

Full Screen

...553 >>> expected = {'a': {'b': {'c': {True: None}}}, 'd': {'e': {'f': {True: None}}}}554 >>> trie.as_dict() == expected555 True556 """557 def _default_to_regular(d):558 """559 Source: http://stackoverflow.com/a/26496899/4760801560 :param d: Nested ``defaultdict`` to convert to regular ``dict``561 :type d: defaultdict(str -> defaultdict(...))562 :return: A dict representation of the defaultdict563 :rtype: dict(str -> dict(str -> ...))564 :Example:565 >>> from collections import defaultdict566 >>> d = defaultdict(defaultdict)567 >>> d["one"]["two"] = "three"568 >>> d569 defaultdict(<type 'collections.defaultdict'>, {'one': defaultdict(None, {'two': 'three'})})570 >>> _default_to_regular(d)571 {'one': {'two': 'three'}}572 """573 if isinstance(d, defaultdict):574 d = {k: _default_to_regular(v) for k, v in d.items()}575 return d...

Full Screen

Full Screen

_util.py

Source:_util.py Github

copy

Full Screen

...236 # intent, doesn't mean the intent should be denied as well.237 # sync up domain-intent238 if intents and all(intent.mask_state == MaskState.deny for intent in intents):239 domain.mask_state = MaskState.deny240 def _default_to_regular(self, d):241 if isinstance(d, defaultdict):242 d = {k: self._default_to_regular(v) for k, v in d.items()}243 return d244 def to_dict(self) -> dict:245 """246 This function serializes TreeNlp into a dict structure by only adding keys representing247 allow MaskState nodes and not adding keys for deny and unset MaskState nodes.248 """249 self._sync_nodes()250 # The results has three nested dicts: {domain: {intent: {entity: role: {}}}}251 result = defaultdict(lambda: defaultdict(lambda: defaultdict(dict)))252 for domain in self.get_domain_nodes():253 if domain.mask_state:254 result[domain.nlp_name] = defaultdict(lambda: defaultdict(dict))255 for intent in self.get_intent_nodes(domain.nlp_name):256 if intent.mask_state:257 result[domain.nlp_name][intent.nlp_name] = defaultdict(dict)258 for entity in self.get_entity_nodes(domain.nlp_name,259 intent.nlp_name):260 if entity.mask_state:261 result[domain.nlp_name][intent.nlp_name][entity.nlp_name] = {}262 for role in self.get_role_nodes(domain.nlp_name,263 intent.nlp_name,264 entity.nlp_name):265 if role.mask_state:266 result[domain.nlp_name][intent.nlp_name][267 entity.nlp_name][role.nlp_name] = {}268 serialize_results = self._default_to_regular(result)...

Full Screen

Full Screen

samples.py

Source:samples.py Github

copy

Full Screen

...33 return {34 _GLOBAL: defaultdict(new_qty_dict),35 _LOCAL: defaultdict(new_qdict),36 }37def _default_to_regular(d: dict | defaultdict) -> dict:38 """Helper function to convert defaultdicts to regular dicts."""39 if isinstance(d, dict):40 d = {k: _default_to_regular(v) for k, v in d.items()}41 return d42@dataclass43class _TargetSlot:44 """Auxiliary class to store target information.45 Recopy of the sequence._TimeSlot but without the unrelevant `type` field,46 unrelevant at the sample level.47 NOTE: While it store targets, targets themselves are insufficient to48 conclude on the addressing of the samples. Additional info is needed:49 compare against a known register or the original sequence information.50 """51 ti: int52 tf: int53 targets: set[QubitId]54@dataclass55class _SlmMask:56 """Auxiliary class to store the SLM mask configuration."""57 targets: set[QubitId] = field(default_factory=set)58 end: int = 059@dataclass60class ChannelSamples:61 """Gathers samples of a channel."""62 amp: np.ndarray63 det: np.ndarray64 phase: np.ndarray65 slots: list[_TargetSlot] = field(default_factory=list)66 def __post_init__(self) -> None:67 assert len(self.amp) == len(self.det) == len(self.phase)68 self.duration = len(self.amp)69 for t in self.slots:70 assert t.ti < t.tf # well ordered slots71 for t1, t2 in zip(self.slots, self.slots[1:]):72 assert t1.tf <= t2.ti # no overlaps on a given channel73 def extend_duration(self, new_duration: int) -> ChannelSamples:74 """Extends the duration of the samples.75 Pads the amplitude and detuning samples with zeros and the phase with76 its last value (or zero if empty).77 Args:78 new_duration: The new duration for the samples (in ns).79 Must be greater than or equal to the current duration.80 Returns:81 The extended channel samples.82 """83 extension = new_duration - self.duration84 if extension < 0:85 raise ValueError("Can't extend samples to a lower duration.")86 new_amp = np.pad(self.amp, (0, extension))87 new_detuning = np.pad(self.det, (0, extension))88 new_phase = np.pad(89 self.phase,90 (0, extension),91 mode="edge" if self.phase.size > 0 else "constant",92 )93 return ChannelSamples(new_amp, new_detuning, new_phase, self.slots)94 def is_empty(self) -> bool:95 """Whether the channel is effectively empty.96 The channel is considered empty if all amplitude and detuning97 samples are zero.98 """99 return np.count_nonzero(self.amp) + np.count_nonzero(self.det) == 0100 def modulate(101 self, channel_obj: Channel, max_duration: Optional[int] = None102 ) -> ChannelSamples:103 """Modulates the samples for a given channel.104 It assumes that the phase starts at its initial value and is kept at105 its final value. The same could potentially be done for the detuning,106 but it's not as safe of an assumption so it's not done for now.107 Args:108 channel_obj: The channel object for which to modulate the samples.109 max_duration: The maximum duration of the modulation samples. If110 defined, truncates them to have a duration less than or equal111 to the given value.112 Returns:113 The modulated channel samples.114 """115 times = slice(0, max_duration)116 new_amp = channel_obj.modulate(self.amp)[times]117 new_detuning = channel_obj.modulate(self.det)[times]118 new_phase = channel_obj.modulate(self.phase, keep_ends=True)[times]119 return ChannelSamples(new_amp, new_detuning, new_phase, self.slots)120@dataclass121class SequenceSamples:122 """Gather samples for each channel in a sequence."""123 channels: list[str]124 samples_list: list[ChannelSamples]125 _ch_objs: dict[str, Channel]126 _slm_mask: _SlmMask = field(default_factory=_SlmMask)127 @property128 def channel_samples(self) -> dict[str, ChannelSamples]:129 """Mapping between the channel name and its samples."""130 return dict(zip(self.channels, self.samples_list))131 @property132 def max_duration(self) -> int:133 """The maximum duration among the channel samples."""134 return max(samples.duration for samples in self.samples_list)135 def used_bases(self) -> set[str]:136 """The bases with non-zero pulses."""137 return {138 ch_obj.basis139 for ch_obj, ch_samples in zip(140 self._ch_objs.values(), self.samples_list141 )142 if not ch_samples.is_empty()143 }144 def to_nested_dict(self, all_local: bool = False) -> dict:145 """Format in the nested dictionary form.146 This is the format expected by `pulser_simulation.Simulation()`.147 Args:148 all_local: Forces all samples to be distributed by their149 individual targets, even when applied by a global channel.150 Returns:151 A nested dictionary splitting the samples according to their152 addressing ('Global' or 'Local'), the targeted basis153 and, in the 'Local' case, the targeted qubit.154 """155 bases = {ch_obj.basis for ch_obj in self._ch_objs.values()}156 in_xy = False157 if "XY" in bases:158 assert bases == {"XY"}159 in_xy = True160 d = _prepare_dict(self.max_duration, in_xy=in_xy)161 for chname, samples in zip(self.channels, self.samples_list):162 cs = (163 samples.extend_duration(self.max_duration)164 if samples.duration != self.max_duration165 else samples166 )167 addr = self._ch_objs[chname].addressing168 basis = self._ch_objs[chname].basis169 if addr == _GLOBAL and not all_local:170 start_t = self._slm_mask.end171 d[_GLOBAL][basis][_AMP][start_t:] += cs.amp[start_t:]172 d[_GLOBAL][basis][_DET][start_t:] += cs.det[start_t:]173 d[_GLOBAL][basis][_PHASE][start_t:] += cs.phase[start_t:]174 if start_t == 0:175 # Prevents lines below from running unnecessarily176 continue177 unmasked_targets = cs.slots[0].targets - self._slm_mask.targets178 for t in unmasked_targets:179 d[_LOCAL][basis][t][_AMP][:start_t] += cs.amp[:start_t]180 d[_LOCAL][basis][t][_DET][:start_t] += cs.det[:start_t]181 d[_LOCAL][basis][t][_PHASE][:start_t] += cs.phase[:start_t]182 else:183 for s in cs.slots:184 for t in s.targets:185 ti = s.ti186 if t in self._slm_mask.targets:187 ti = max(ti, self._slm_mask.end)188 times = slice(ti, s.tf)189 d[_LOCAL][basis][t][_AMP][times] += cs.amp[times]190 d[_LOCAL][basis][t][_DET][times] += cs.det[times]191 d[_LOCAL][basis][t][_PHASE][times] += cs.phase[times]192 return _default_to_regular(d)193 def __repr__(self) -> str:194 blocks = [195 f"{chname}:\n{cs!r}"196 for chname, cs in zip(self.channels, self.samples_list)197 ]...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run molecule automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful