repository_name
stringlengths
7
55
func_path_in_repository
stringlengths
4
223
func_name
stringlengths
1
134
whole_func_string
stringlengths
75
104k
language
stringclasses
1 value
func_code_string
stringlengths
75
104k
func_code_tokens
listlengths
19
28.4k
func_documentation_string
stringlengths
1
46.9k
func_documentation_tokens
listlengths
1
1.97k
split_name
stringclasses
1 value
func_code_url
stringlengths
87
315
tilde-lab/tilde
tilde/apps/perovskite_tilting/perovskite_tilting.py
Perovskite_tilting.get_tiltplanes
def get_tiltplanes(self, sequence): ''' Extract tilting planes basing on distance map ''' tilting_planes = [] distance_map = [] for i in range(1, len(sequence)): distance_map.append([ sequence[i], self.virtual_atoms.get_distance( sequence[0], sequence[i] ) ]) distance_map = sorted(distance_map, key=lambda x: x[1]) if len(distance_map) == 4: # surface edge case # semi-octahedron at surface edge has only one tilting plane to consider sorted_dist = [i[0] for i in distance_map] if distance_map[-1][1] - distance_map[-2][1] < 0.5: # 1st case: max diff < 0.5 Angstrom, # meaning all distances to reference atom are similar, # therefore the reference atom is above the searched plane # and the searched plane consists of other atoms tilting_planes.append( [ i[0] for i in distance_map ] ) else: # 2nd case: reference atom belongs to the searched plane, # procedure needs to be repeated with the next atom as reference atom candidates = [sequence[0], sorted_dist[-1]] next_distance_map = [] next_distance_map.append([ sorted_dist[1], self.virtual_atoms.get_distance( sorted_dist[0], sorted_dist[1] ) ]) next_distance_map.append([ sorted_dist[2], self.virtual_atoms.get_distance( sorted_dist[0], sorted_dist[2] ) ]) next_distance_map = sorted(next_distance_map, key=lambda x: x[1]) next_sorted_dist = [i[0] for i in next_distance_map] # the next reference atom is taken above the plane (distances are similar) if next_distance_map[1][1] - next_distance_map[0][1] < 0.5: candidates.extend([ next_sorted_dist[0], next_sorted_dist[1] ]) # the next reference atom is taken in the plane (distances are different) else: candidates.extend([ sorted_dist[0], next_sorted_dist[1] ]) tilting_planes.append(candidates) elif len(distance_map) == 5: # full octahedron case # full octahedron has 3 different tilting planes (perpendicular in ideal case) sorted_dist = [i[0] for i in distance_map] # 1st plane is found as: first_plane = sorted_dist[0:4] tilting_planes.append(first_plane) distance_map_first_plane = [] for i in range(1, 4): distance_map_first_plane.append([ first_plane[i], self.virtual_atoms.get_distance( first_plane[0], first_plane[i] ) ]) distance_map_first_plane = sorted(distance_map_first_plane, key=lambda x: x[1]) sorted_first_plane = [i[0] for i in distance_map_first_plane] # 2nd and 3rd planes are found as: tilting_planes.append([ sequence[0], sorted_dist[4], first_plane[0], sorted_first_plane[2] ]) tilting_planes.append([ sequence[0], sorted_dist[4], sorted_first_plane[0], sorted_first_plane[1] ]) # filter planes by Z according to octahedral spatial compound filtered = list(filter(lambda x: abs(self.virtual_atoms[ x[0] ].z - self.virtual_atoms[ x[1] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \ abs(self.virtual_atoms[ x[1] ].z - self.virtual_atoms[ x[2] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \ abs(self.virtual_atoms[ x[2] ].z - self.virtual_atoms[ x[3] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE, tilting_planes )) # Py3 if len(filtered): tilting_planes = filtered return tilting_planes
python
def get_tiltplanes(self, sequence): ''' Extract tilting planes basing on distance map ''' tilting_planes = [] distance_map = [] for i in range(1, len(sequence)): distance_map.append([ sequence[i], self.virtual_atoms.get_distance( sequence[0], sequence[i] ) ]) distance_map = sorted(distance_map, key=lambda x: x[1]) if len(distance_map) == 4: # surface edge case # semi-octahedron at surface edge has only one tilting plane to consider sorted_dist = [i[0] for i in distance_map] if distance_map[-1][1] - distance_map[-2][1] < 0.5: # 1st case: max diff < 0.5 Angstrom, # meaning all distances to reference atom are similar, # therefore the reference atom is above the searched plane # and the searched plane consists of other atoms tilting_planes.append( [ i[0] for i in distance_map ] ) else: # 2nd case: reference atom belongs to the searched plane, # procedure needs to be repeated with the next atom as reference atom candidates = [sequence[0], sorted_dist[-1]] next_distance_map = [] next_distance_map.append([ sorted_dist[1], self.virtual_atoms.get_distance( sorted_dist[0], sorted_dist[1] ) ]) next_distance_map.append([ sorted_dist[2], self.virtual_atoms.get_distance( sorted_dist[0], sorted_dist[2] ) ]) next_distance_map = sorted(next_distance_map, key=lambda x: x[1]) next_sorted_dist = [i[0] for i in next_distance_map] # the next reference atom is taken above the plane (distances are similar) if next_distance_map[1][1] - next_distance_map[0][1] < 0.5: candidates.extend([ next_sorted_dist[0], next_sorted_dist[1] ]) # the next reference atom is taken in the plane (distances are different) else: candidates.extend([ sorted_dist[0], next_sorted_dist[1] ]) tilting_planes.append(candidates) elif len(distance_map) == 5: # full octahedron case # full octahedron has 3 different tilting planes (perpendicular in ideal case) sorted_dist = [i[0] for i in distance_map] # 1st plane is found as: first_plane = sorted_dist[0:4] tilting_planes.append(first_plane) distance_map_first_plane = [] for i in range(1, 4): distance_map_first_plane.append([ first_plane[i], self.virtual_atoms.get_distance( first_plane[0], first_plane[i] ) ]) distance_map_first_plane = sorted(distance_map_first_plane, key=lambda x: x[1]) sorted_first_plane = [i[0] for i in distance_map_first_plane] # 2nd and 3rd planes are found as: tilting_planes.append([ sequence[0], sorted_dist[4], first_plane[0], sorted_first_plane[2] ]) tilting_planes.append([ sequence[0], sorted_dist[4], sorted_first_plane[0], sorted_first_plane[1] ]) # filter planes by Z according to octahedral spatial compound filtered = list(filter(lambda x: abs(self.virtual_atoms[ x[0] ].z - self.virtual_atoms[ x[1] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \ abs(self.virtual_atoms[ x[1] ].z - self.virtual_atoms[ x[2] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE and \ abs(self.virtual_atoms[ x[2] ].z - self.virtual_atoms[ x[3] ].z) < self.OCTAHEDRON_ATOMS_Z_DIFFERENCE, tilting_planes )) # Py3 if len(filtered): tilting_planes = filtered return tilting_planes
[ "def", "get_tiltplanes", "(", "self", ",", "sequence", ")", ":", "tilting_planes", "=", "[", "]", "distance_map", "=", "[", "]", "for", "i", "in", "range", "(", "1", ",", "len", "(", "sequence", ")", ")", ":", "distance_map", ".", "append", "(", "[",...
Extract tilting planes basing on distance map
[ "Extract", "tilting", "planes", "basing", "on", "distance", "map" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/apps/perovskite_tilting/perovskite_tilting.py#L172-L238
tilde-lab/tilde
tilde/apps/perovskite_tilting/perovskite_tilting.py
Perovskite_tilting.get_tilting
def get_tilting(self, oplane): ''' Main procedure ''' surf_atom1, surf_atom2, surf_atom3, surf_atom4 = oplane # divide surface atoms into groups by distance between them compare = [surf_atom2, surf_atom3, surf_atom4] distance_map = [] for i in range(0, 3): distance_map.append([ compare[i], self.virtual_atoms.get_distance(surf_atom1, compare[i]) ]) distance_map = sorted(distance_map, key=lambda x: x[1]) distance_map_keys = [i[0] for i in distance_map] surf_atom3 = distance_map_keys[2] surf_atom2 = distance_map_keys[1] surf_atom4 = distance_map_keys[0] if self.virtual_atoms[surf_atom1].z == self.virtual_atoms[surf_atom2].z and \ self.virtual_atoms[surf_atom2].z == self.virtual_atoms[surf_atom3].z and \ self.virtual_atoms[surf_atom3].z == self.virtual_atoms[surf_atom4].z: # this is done to prevent false zero tilting self.virtual_atoms[surf_atom1].z += 1E-10 self.virtual_atoms[surf_atom2].z += 1E-10 self.virtual_atoms[surf_atom3].z -= 1E-10 self.virtual_atoms[surf_atom4].z -= 1E-10 # new axes will be defined simply as vectors standing on 1 - 3 and 2 - 4 (they are moved to the point of origin) self.virtual_atoms.append(Atom('X', (self.virtual_atoms[surf_atom1].x - self.virtual_atoms[surf_atom3].x, self.virtual_atoms[surf_atom1].y - self.virtual_atoms[surf_atom3].y, self.virtual_atoms[surf_atom1].z - self.virtual_atoms[surf_atom3].z))) self.virtual_atoms.append(Atom('X', (self.virtual_atoms[surf_atom2].x - self.virtual_atoms[surf_atom4].x, self.virtual_atoms[surf_atom2].y - self.virtual_atoms[surf_atom4].y, self.virtual_atoms[surf_atom2].z - self.virtual_atoms[surf_atom4].z))) self.virtual_atoms.append(Atom('X', (0, 0, 0))) # redefine tilted axes surf_atom_first = len(self.virtual_atoms)-3 surf_atom_second = len(self.virtual_atoms)-2 center = len(self.virtual_atoms)-1 # inverse arbitrary atom self.virtual_atoms.append(Atom('X', (-self.virtual_atoms[surf_atom_first].x, -self.virtual_atoms[surf_atom_first].y, -self.virtual_atoms[surf_atom_first].z))) inversed_one = len(self.virtual_atoms)-1 # find and add bisectors, silly swapping first_bisector = self.get_bisector_point(surf_atom_first, center, surf_atom_second, self.virtual_atoms) sec_bisector = self.get_bisector_point(surf_atom_second, center, inversed_one, self.virtual_atoms) swap = True if first_bisector[0] < 0 and sec_bisector[0] < 0: swap = False if first_bisector[0] < 0: first_bisector[0] *= -1 first_bisector[1] *= -1 first_bisector[2] *= -1 if sec_bisector[0] < 0: sec_bisector[0] *= -1 sec_bisector[1] *= -1 sec_bisector[2] *= -1 if swap: first_bisector, sec_bisector = sec_bisector, first_bisector swap = False if first_bisector[0] < sec_bisector[0] and first_bisector[1] < 0: first_bisector[0] *= -1 first_bisector[1] *= -1 first_bisector[2] *= -1 swap = True if first_bisector[0] < sec_bisector[0] and first_bisector[1] > 0: swap = True if first_bisector[0] > sec_bisector[0] and sec_bisector[1] < 0: sec_bisector[0] *= -1 sec_bisector[1] *= -1 sec_bisector[2] *= -1 if swap: first_bisector, sec_bisector = sec_bisector, first_bisector self.virtual_atoms.append(Atom('X', (first_bisector[0], first_bisector[1], first_bisector[2]))) self.virtual_atoms.append(Atom('X', (sec_bisector[0], sec_bisector[1], sec_bisector[2]))) first_bisector = len(self.virtual_atoms)-2 sec_bisector = len(self.virtual_atoms)-1 # use vector cross product to define normal which will play Z axis role self.virtual_atoms.append(Atom('X', ( self.virtual_atoms[first_bisector].y*self.virtual_atoms[sec_bisector].z - self.virtual_atoms[first_bisector].z*self.virtual_atoms[sec_bisector].y, self.virtual_atoms[first_bisector].z*self.virtual_atoms[sec_bisector].x - self.virtual_atoms[first_bisector].x*self.virtual_atoms[sec_bisector].z, self.virtual_atoms[first_bisector].x*self.virtual_atoms[sec_bisector].y - self.virtual_atoms[first_bisector].y*self.virtual_atoms[sec_bisector].x ))) tilt_z = len(self.virtual_atoms)-1 # Euler angles ZYZ alpha = math.degrees(math.atan2(self.virtual_atoms[sec_bisector].z, self.virtual_atoms[first_bisector].z)) beta = math.degrees(math.atan2(math.sqrt(self.virtual_atoms[tilt_z].x**2 + self.virtual_atoms[tilt_z].y**2), self.virtual_atoms[tilt_z].z)) gamma = math.degrees(math.atan2(self.virtual_atoms[tilt_z].y, -self.virtual_atoms[tilt_z].x)) # angles adjusting adjust_angles = [45, 90, 135, 180, 225, 270, 315, 360] tilting = [alpha, beta, gamma] for i in range(0, 3): tilting[i] = abs(tilting[i]) if tilting[i] in adjust_angles: tilting[i] = 0.0 continue if tilting[i] > self.MAX_TILTING_DEGREE: for checkpoint in adjust_angles: if checkpoint - self.MAX_TILTING_DEGREE < tilting[i] < checkpoint + self.MAX_TILTING_DEGREE: tilting[i] = abs(tilting[i] - checkpoint) break return tilting
python
def get_tilting(self, oplane): ''' Main procedure ''' surf_atom1, surf_atom2, surf_atom3, surf_atom4 = oplane # divide surface atoms into groups by distance between them compare = [surf_atom2, surf_atom3, surf_atom4] distance_map = [] for i in range(0, 3): distance_map.append([ compare[i], self.virtual_atoms.get_distance(surf_atom1, compare[i]) ]) distance_map = sorted(distance_map, key=lambda x: x[1]) distance_map_keys = [i[0] for i in distance_map] surf_atom3 = distance_map_keys[2] surf_atom2 = distance_map_keys[1] surf_atom4 = distance_map_keys[0] if self.virtual_atoms[surf_atom1].z == self.virtual_atoms[surf_atom2].z and \ self.virtual_atoms[surf_atom2].z == self.virtual_atoms[surf_atom3].z and \ self.virtual_atoms[surf_atom3].z == self.virtual_atoms[surf_atom4].z: # this is done to prevent false zero tilting self.virtual_atoms[surf_atom1].z += 1E-10 self.virtual_atoms[surf_atom2].z += 1E-10 self.virtual_atoms[surf_atom3].z -= 1E-10 self.virtual_atoms[surf_atom4].z -= 1E-10 # new axes will be defined simply as vectors standing on 1 - 3 and 2 - 4 (they are moved to the point of origin) self.virtual_atoms.append(Atom('X', (self.virtual_atoms[surf_atom1].x - self.virtual_atoms[surf_atom3].x, self.virtual_atoms[surf_atom1].y - self.virtual_atoms[surf_atom3].y, self.virtual_atoms[surf_atom1].z - self.virtual_atoms[surf_atom3].z))) self.virtual_atoms.append(Atom('X', (self.virtual_atoms[surf_atom2].x - self.virtual_atoms[surf_atom4].x, self.virtual_atoms[surf_atom2].y - self.virtual_atoms[surf_atom4].y, self.virtual_atoms[surf_atom2].z - self.virtual_atoms[surf_atom4].z))) self.virtual_atoms.append(Atom('X', (0, 0, 0))) # redefine tilted axes surf_atom_first = len(self.virtual_atoms)-3 surf_atom_second = len(self.virtual_atoms)-2 center = len(self.virtual_atoms)-1 # inverse arbitrary atom self.virtual_atoms.append(Atom('X', (-self.virtual_atoms[surf_atom_first].x, -self.virtual_atoms[surf_atom_first].y, -self.virtual_atoms[surf_atom_first].z))) inversed_one = len(self.virtual_atoms)-1 # find and add bisectors, silly swapping first_bisector = self.get_bisector_point(surf_atom_first, center, surf_atom_second, self.virtual_atoms) sec_bisector = self.get_bisector_point(surf_atom_second, center, inversed_one, self.virtual_atoms) swap = True if first_bisector[0] < 0 and sec_bisector[0] < 0: swap = False if first_bisector[0] < 0: first_bisector[0] *= -1 first_bisector[1] *= -1 first_bisector[2] *= -1 if sec_bisector[0] < 0: sec_bisector[0] *= -1 sec_bisector[1] *= -1 sec_bisector[2] *= -1 if swap: first_bisector, sec_bisector = sec_bisector, first_bisector swap = False if first_bisector[0] < sec_bisector[0] and first_bisector[1] < 0: first_bisector[0] *= -1 first_bisector[1] *= -1 first_bisector[2] *= -1 swap = True if first_bisector[0] < sec_bisector[0] and first_bisector[1] > 0: swap = True if first_bisector[0] > sec_bisector[0] and sec_bisector[1] < 0: sec_bisector[0] *= -1 sec_bisector[1] *= -1 sec_bisector[2] *= -1 if swap: first_bisector, sec_bisector = sec_bisector, first_bisector self.virtual_atoms.append(Atom('X', (first_bisector[0], first_bisector[1], first_bisector[2]))) self.virtual_atoms.append(Atom('X', (sec_bisector[0], sec_bisector[1], sec_bisector[2]))) first_bisector = len(self.virtual_atoms)-2 sec_bisector = len(self.virtual_atoms)-1 # use vector cross product to define normal which will play Z axis role self.virtual_atoms.append(Atom('X', ( self.virtual_atoms[first_bisector].y*self.virtual_atoms[sec_bisector].z - self.virtual_atoms[first_bisector].z*self.virtual_atoms[sec_bisector].y, self.virtual_atoms[first_bisector].z*self.virtual_atoms[sec_bisector].x - self.virtual_atoms[first_bisector].x*self.virtual_atoms[sec_bisector].z, self.virtual_atoms[first_bisector].x*self.virtual_atoms[sec_bisector].y - self.virtual_atoms[first_bisector].y*self.virtual_atoms[sec_bisector].x ))) tilt_z = len(self.virtual_atoms)-1 # Euler angles ZYZ alpha = math.degrees(math.atan2(self.virtual_atoms[sec_bisector].z, self.virtual_atoms[first_bisector].z)) beta = math.degrees(math.atan2(math.sqrt(self.virtual_atoms[tilt_z].x**2 + self.virtual_atoms[tilt_z].y**2), self.virtual_atoms[tilt_z].z)) gamma = math.degrees(math.atan2(self.virtual_atoms[tilt_z].y, -self.virtual_atoms[tilt_z].x)) # angles adjusting adjust_angles = [45, 90, 135, 180, 225, 270, 315, 360] tilting = [alpha, beta, gamma] for i in range(0, 3): tilting[i] = abs(tilting[i]) if tilting[i] in adjust_angles: tilting[i] = 0.0 continue if tilting[i] > self.MAX_TILTING_DEGREE: for checkpoint in adjust_angles: if checkpoint - self.MAX_TILTING_DEGREE < tilting[i] < checkpoint + self.MAX_TILTING_DEGREE: tilting[i] = abs(tilting[i] - checkpoint) break return tilting
[ "def", "get_tilting", "(", "self", ",", "oplane", ")", ":", "surf_atom1", ",", "surf_atom2", ",", "surf_atom3", ",", "surf_atom4", "=", "oplane", "# divide surface atoms into groups by distance between them", "compare", "=", "[", "surf_atom2", ",", "surf_atom3", ",", ...
Main procedure
[ "Main", "procedure" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/apps/perovskite_tilting/perovskite_tilting.py#L240-L348
deployed/django-emailtemplates
emailtemplates/registry.py
HelpContext.get_help_keys
def get_help_keys(self): """ Returns dict of help_context keys (description texts used in `EmailRegistry.register()` method). """ help_keys = {} for k, v in self.help_context.items(): if isinstance(v, tuple): help_keys[k] = v[0] else: help_keys[k] = v return help_keys
python
def get_help_keys(self): """ Returns dict of help_context keys (description texts used in `EmailRegistry.register()` method). """ help_keys = {} for k, v in self.help_context.items(): if isinstance(v, tuple): help_keys[k] = v[0] else: help_keys[k] = v return help_keys
[ "def", "get_help_keys", "(", "self", ")", ":", "help_keys", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "help_context", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "tuple", ")", ":", "help_keys", "[", "k", "]", "="...
Returns dict of help_context keys (description texts used in `EmailRegistry.register()` method).
[ "Returns", "dict", "of", "help_context", "keys", "(", "description", "texts", "used", "in", "EmailRegistry", ".", "register", "()", "method", ")", "." ]
train
https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/registry.py#L24-L34
deployed/django-emailtemplates
emailtemplates/registry.py
HelpContext.get_help_values
def get_help_values(self): """ Returns dict of help_context values (example values submitted in `EmailRegistry.register()` method). """ help_values = {} for k, v in self.help_context.items(): if isinstance(v, tuple) and len(v) == 2: help_values[k] = v[1] else: help_values[k] = u"<%s>" % k return help_values
python
def get_help_values(self): """ Returns dict of help_context values (example values submitted in `EmailRegistry.register()` method). """ help_values = {} for k, v in self.help_context.items(): if isinstance(v, tuple) and len(v) == 2: help_values[k] = v[1] else: help_values[k] = u"<%s>" % k return help_values
[ "def", "get_help_values", "(", "self", ")", ":", "help_values", "=", "{", "}", "for", "k", ",", "v", "in", "self", ".", "help_context", ".", "items", "(", ")", ":", "if", "isinstance", "(", "v", ",", "tuple", ")", "and", "len", "(", "v", ")", "==...
Returns dict of help_context values (example values submitted in `EmailRegistry.register()` method).
[ "Returns", "dict", "of", "help_context", "values", "(", "example", "values", "submitted", "in", "EmailRegistry", ".", "register", "()", "method", ")", "." ]
train
https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/registry.py#L36-L46
deployed/django-emailtemplates
emailtemplates/registry.py
EmailTemplateRegistry.register
def register(self, path, help_text=None, help_context=None): """ Registers email template. Example usage: email_templates.register('hello_template.html', help_text=u'Hello template', help_context={'username': u'Name of user in hello expression'}) :param path: Template file path. It will become immutable registry lookup key. :param help_text: Help text to describe template in admin site :param help_context: Dictionary of possible keys used in the context and description of their content `help_context` items values may be strings or tuples of two strings. If strings, then email template preview will use variable names to fill context, otherwise the second tuple element will become example value. If an email template is already registered, this will raise AlreadyRegistered. """ if path in self._registry: raise AlreadyRegistered('The template %s is already registered' % path) self._registry[path] = RegistrationItem(path, help_text, help_context) logger.debug("Registered email template %s", path)
python
def register(self, path, help_text=None, help_context=None): """ Registers email template. Example usage: email_templates.register('hello_template.html', help_text=u'Hello template', help_context={'username': u'Name of user in hello expression'}) :param path: Template file path. It will become immutable registry lookup key. :param help_text: Help text to describe template in admin site :param help_context: Dictionary of possible keys used in the context and description of their content `help_context` items values may be strings or tuples of two strings. If strings, then email template preview will use variable names to fill context, otherwise the second tuple element will become example value. If an email template is already registered, this will raise AlreadyRegistered. """ if path in self._registry: raise AlreadyRegistered('The template %s is already registered' % path) self._registry[path] = RegistrationItem(path, help_text, help_context) logger.debug("Registered email template %s", path)
[ "def", "register", "(", "self", ",", "path", ",", "help_text", "=", "None", ",", "help_context", "=", "None", ")", ":", "if", "path", "in", "self", ".", "_registry", ":", "raise", "AlreadyRegistered", "(", "'The template %s is already registered'", "%", "path"...
Registers email template. Example usage: email_templates.register('hello_template.html', help_text=u'Hello template', help_context={'username': u'Name of user in hello expression'}) :param path: Template file path. It will become immutable registry lookup key. :param help_text: Help text to describe template in admin site :param help_context: Dictionary of possible keys used in the context and description of their content `help_context` items values may be strings or tuples of two strings. If strings, then email template preview will use variable names to fill context, otherwise the second tuple element will become example value. If an email template is already registered, this will raise AlreadyRegistered.
[ "Registers", "email", "template", "." ]
train
https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/registry.py#L84-L104
deployed/django-emailtemplates
emailtemplates/registry.py
EmailTemplateRegistry.get_registration
def get_registration(self, path): """ Returns registration item for specified path. If an email template is not registered, this will raise NotRegistered. """ if not self.is_registered(path): raise NotRegistered("Email template not registered") return self._registry[path]
python
def get_registration(self, path): """ Returns registration item for specified path. If an email template is not registered, this will raise NotRegistered. """ if not self.is_registered(path): raise NotRegistered("Email template not registered") return self._registry[path]
[ "def", "get_registration", "(", "self", ",", "path", ")", ":", "if", "not", "self", ".", "is_registered", "(", "path", ")", ":", "raise", "NotRegistered", "(", "\"Email template not registered\"", ")", "return", "self", ".", "_registry", "[", "path", "]" ]
Returns registration item for specified path. If an email template is not registered, this will raise NotRegistered.
[ "Returns", "registration", "item", "for", "specified", "path", "." ]
train
https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/registry.py#L109-L117
deployed/django-emailtemplates
emailtemplates/registry.py
EmailTemplateRegistry.get_form_help_text
def get_form_help_text(self, path): """ Returns text that can be used as form help text for creating email templates. """ try: form_help_text = self.get_registration(path).as_form_help_text() except NotRegistered: form_help_text = u"" return form_help_text
python
def get_form_help_text(self, path): """ Returns text that can be used as form help text for creating email templates. """ try: form_help_text = self.get_registration(path).as_form_help_text() except NotRegistered: form_help_text = u"" return form_help_text
[ "def", "get_form_help_text", "(", "self", ",", "path", ")", ":", "try", ":", "form_help_text", "=", "self", ".", "get_registration", "(", "path", ")", ".", "as_form_help_text", "(", ")", "except", "NotRegistered", ":", "form_help_text", "=", "u\"\"", "return",...
Returns text that can be used as form help text for creating email templates.
[ "Returns", "text", "that", "can", "be", "used", "as", "form", "help", "text", "for", "creating", "email", "templates", "." ]
train
https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/registry.py#L137-L145
myth/pepper8
pepper8/generator.py
HtmlGenerator.analyze
def analyze(self, output_file=None): """ Analyzes the parsed results from Flake8 or PEP 8 output and creates FileResult instances :param output_file: If specified, output will be written to this file instead of stdout. """ fr = None for path, code, line, char, desc in self.parser.parse(): # Create a new FileResult and register it if we have changed to a new file if path not in self.files: # Update statistics if fr: self.update_stats(fr) fr = FileResult(path) self.files[path] = fr # Add line to the FileResult fr.add_error(code, line, char, desc) # Add final FileResult to statistics, if any were parsed if fr: self.update_stats(fr) # Generate HTML file self.generate(output_file=output_file)
python
def analyze(self, output_file=None): """ Analyzes the parsed results from Flake8 or PEP 8 output and creates FileResult instances :param output_file: If specified, output will be written to this file instead of stdout. """ fr = None for path, code, line, char, desc in self.parser.parse(): # Create a new FileResult and register it if we have changed to a new file if path not in self.files: # Update statistics if fr: self.update_stats(fr) fr = FileResult(path) self.files[path] = fr # Add line to the FileResult fr.add_error(code, line, char, desc) # Add final FileResult to statistics, if any were parsed if fr: self.update_stats(fr) # Generate HTML file self.generate(output_file=output_file)
[ "def", "analyze", "(", "self", ",", "output_file", "=", "None", ")", ":", "fr", "=", "None", "for", "path", ",", "code", ",", "line", ",", "char", ",", "desc", "in", "self", ".", "parser", ".", "parse", "(", ")", ":", "# Create a new FileResult and reg...
Analyzes the parsed results from Flake8 or PEP 8 output and creates FileResult instances :param output_file: If specified, output will be written to this file instead of stdout.
[ "Analyzes", "the", "parsed", "results", "from", "Flake8", "or", "PEP", "8", "output", "and", "creates", "FileResult", "instances", ":", "param", "output_file", ":", "If", "specified", "output", "will", "be", "written", "to", "this", "file", "instead", "of", ...
train
https://github.com/myth/pepper8/blob/98ffed4089241d8d3c1048995bc6777a2f3abdda/pepper8/generator.py#L37-L62
myth/pepper8
pepper8/generator.py
HtmlGenerator.generate
def generate(self, output_file=None): """ Generates an HTML file based on data from the Parser object and Jinja2 templates :param output_file: If specified, output will be written to this file instead of stdout. """ fd = output_file # Write to stdout if we do not have a file to write to if not fd: fd = stdout else: try: fd = open(output_file, 'w') except IOError as e: stderr.write('Unable to open outputfile %s: %s' % (output_file, e)) with open(os.path.join(os.path.dirname(__file__), 'templates/base.html')) as template: html = Template(template.read()) # Write potential build messages to stdout if we are writing to HTML file # If dest is stdout and supposed to be piped or redirected, build messages like TeamCity's will # have no effect, since they require to read from stdin. if output_file: self.report_build_messages() # Write our rendered template to the file descriptor fd.write( html.render( files=sorted(self.files.values(), key=lambda x: x.path), total_warnings=self.total_warnings, total_errors=self.total_errors, total_other=self.total_other, violations=sorted( ((code, count) for code, count in self.violations.items()), key=lambda x: x[1], reverse=True, ) ) ) # If file descriptor is stdout if not output_file: fd.flush() else: fd.close()
python
def generate(self, output_file=None): """ Generates an HTML file based on data from the Parser object and Jinja2 templates :param output_file: If specified, output will be written to this file instead of stdout. """ fd = output_file # Write to stdout if we do not have a file to write to if not fd: fd = stdout else: try: fd = open(output_file, 'w') except IOError as e: stderr.write('Unable to open outputfile %s: %s' % (output_file, e)) with open(os.path.join(os.path.dirname(__file__), 'templates/base.html')) as template: html = Template(template.read()) # Write potential build messages to stdout if we are writing to HTML file # If dest is stdout and supposed to be piped or redirected, build messages like TeamCity's will # have no effect, since they require to read from stdin. if output_file: self.report_build_messages() # Write our rendered template to the file descriptor fd.write( html.render( files=sorted(self.files.values(), key=lambda x: x.path), total_warnings=self.total_warnings, total_errors=self.total_errors, total_other=self.total_other, violations=sorted( ((code, count) for code, count in self.violations.items()), key=lambda x: x[1], reverse=True, ) ) ) # If file descriptor is stdout if not output_file: fd.flush() else: fd.close()
[ "def", "generate", "(", "self", ",", "output_file", "=", "None", ")", ":", "fd", "=", "output_file", "# Write to stdout if we do not have a file to write to", "if", "not", "fd", ":", "fd", "=", "stdout", "else", ":", "try", ":", "fd", "=", "open", "(", "outp...
Generates an HTML file based on data from the Parser object and Jinja2 templates :param output_file: If specified, output will be written to this file instead of stdout.
[ "Generates", "an", "HTML", "file", "based", "on", "data", "from", "the", "Parser", "object", "and", "Jinja2", "templates", ":", "param", "output_file", ":", "If", "specified", "output", "will", "be", "written", "to", "this", "file", "instead", "of", "stdout"...
train
https://github.com/myth/pepper8/blob/98ffed4089241d8d3c1048995bc6777a2f3abdda/pepper8/generator.py#L64-L109
myth/pepper8
pepper8/generator.py
HtmlGenerator.update_stats
def update_stats(self, file_result): """ Reads the data from a FileResult and updates overall statistics :param file_result: A FileResult instance """ for code, count in file_result.violations.items(): if code not in self.violations: self.violations[code] = 0 self.violations[code] += file_result.violations[code] if 'E' in code.upper(): self.total_errors += file_result.violations[code] elif 'W' in code.upper(): self.total_warnings += file_result.violations[code] else: self.total_other += file_result.violations[code]
python
def update_stats(self, file_result): """ Reads the data from a FileResult and updates overall statistics :param file_result: A FileResult instance """ for code, count in file_result.violations.items(): if code not in self.violations: self.violations[code] = 0 self.violations[code] += file_result.violations[code] if 'E' in code.upper(): self.total_errors += file_result.violations[code] elif 'W' in code.upper(): self.total_warnings += file_result.violations[code] else: self.total_other += file_result.violations[code]
[ "def", "update_stats", "(", "self", ",", "file_result", ")", ":", "for", "code", ",", "count", "in", "file_result", ".", "violations", ".", "items", "(", ")", ":", "if", "code", "not", "in", "self", ".", "violations", ":", "self", ".", "violations", "[...
Reads the data from a FileResult and updates overall statistics :param file_result: A FileResult instance
[ "Reads", "the", "data", "from", "a", "FileResult", "and", "updates", "overall", "statistics", ":", "param", "file_result", ":", "A", "FileResult", "instance" ]
train
https://github.com/myth/pepper8/blob/98ffed4089241d8d3c1048995bc6777a2f3abdda/pepper8/generator.py#L111-L127
myth/pepper8
pepper8/generator.py
HtmlGenerator.report_build_messages
def report_build_messages(self): """ Checks environment variables to see whether pepper8 is run under a build agent such as TeamCity and performs the adequate actions to report statistics. Will not perform any action if HTML output is written to OUTPUT_FILE and not stdout. Currently only supports TeamCity. :return: A list of build message strings destined for stdout """ if os.getenv('TEAMCITY_VERSION'): tc_build_message_warning = "##teamcity[buildStatisticValue key='pepper8warnings' value='{}']\n" tc_build_message_error = "##teamcity[buildStatisticValue key='pepper8errors' value='{}']\n" stdout.write(tc_build_message_warning.format(self.total_warnings)) stdout.write(tc_build_message_error.format(self.total_errors)) stdout.flush()
python
def report_build_messages(self): """ Checks environment variables to see whether pepper8 is run under a build agent such as TeamCity and performs the adequate actions to report statistics. Will not perform any action if HTML output is written to OUTPUT_FILE and not stdout. Currently only supports TeamCity. :return: A list of build message strings destined for stdout """ if os.getenv('TEAMCITY_VERSION'): tc_build_message_warning = "##teamcity[buildStatisticValue key='pepper8warnings' value='{}']\n" tc_build_message_error = "##teamcity[buildStatisticValue key='pepper8errors' value='{}']\n" stdout.write(tc_build_message_warning.format(self.total_warnings)) stdout.write(tc_build_message_error.format(self.total_errors)) stdout.flush()
[ "def", "report_build_messages", "(", "self", ")", ":", "if", "os", ".", "getenv", "(", "'TEAMCITY_VERSION'", ")", ":", "tc_build_message_warning", "=", "\"##teamcity[buildStatisticValue key='pepper8warnings' value='{}']\\n\"", "tc_build_message_error", "=", "\"##teamcity[buildS...
Checks environment variables to see whether pepper8 is run under a build agent such as TeamCity and performs the adequate actions to report statistics. Will not perform any action if HTML output is written to OUTPUT_FILE and not stdout. Currently only supports TeamCity. :return: A list of build message strings destined for stdout
[ "Checks", "environment", "variables", "to", "see", "whether", "pepper8", "is", "run", "under", "a", "build", "agent", "such", "as", "TeamCity", "and", "performs", "the", "adequate", "actions", "to", "report", "statistics", "." ]
train
https://github.com/myth/pepper8/blob/98ffed4089241d8d3c1048995bc6777a2f3abdda/pepper8/generator.py#L129-L146
oscarlazoarjona/fast
fast/bloch.py
phase_transformation
def phase_transformation(Ne, Nl, rm, xi, return_equations=False): """Returns a phase transformation theta_i. The phase transformation is defined in a way such that theta1 + omega_level1 = 0. >>> xi = np.zeros((1, 2, 2)) >>> xi[0, 1, 0] = 1.0 >>> xi[0, 0, 1] = 1.0 >>> rm = np.zeros((3, 2, 2)) >>> rm[0, 1, 0] = 1.0 >>> rm[1, 1, 0] = 1.0 >>> rm[2, 1, 0] = 1.0 >>> phase_transformation(2, 1, rm, xi) [-omega_1, -omega_1 - varpi_1] """ # We first define the needed variables E0, omega_laser = define_laser_variables(Nl) theta = [Symbol('theta'+str(i+1)) for i in range(Ne)] # We check for the case of xi being a list of matrices. if type(xi) == list: xi = np.array([[[xi[l][i, j] for j in range(Ne)] for i in range(Ne)] for l in range(Nl)]) # We find all the equations that the specified problem has to fulfil. eqs = [] for i in range(Ne): for j in range(0, i): if (rm[0][i, j] != 0) or \ (rm[1][i, j] != 0) or \ (rm[2][i, j] != 0): for l in range(Nl): if xi[l, i, j] == 1: eqs += [-omega_laser[l] + theta[j] - theta[i]] if return_equations: return eqs # We solve the system of equations. sol = sympy.solve(eqs, theta, dict=True) sol = sol[0] # We add any missing theta that may be left outside if the system is # under determined. extra_thetas = [] for i in range(Ne): if theta[i] not in sol.keys(): sol.update({theta[i]: theta[i]}) extra_thetas += [theta[i]] # We make the solution such that theta1 + omega_level1 = 0. omega_level, omega, gamma = define_frequencies(Ne) eq_crit = sol[theta[0]] + omega_level[0] ss = sympy.solve(eq_crit, extra_thetas[0])[0] ss = {extra_thetas[0]: ss} sol_simple = [sol[theta[i]].subs(ss) for i in range(Ne)] # sol = [] # for i in range(Ne): # soli = [] # for l in range(Nl): # soli += [sympy.diff(sol_simple[theta[i]], omega_laser[l])] # sol += [soli] return sol_simple
python
def phase_transformation(Ne, Nl, rm, xi, return_equations=False): """Returns a phase transformation theta_i. The phase transformation is defined in a way such that theta1 + omega_level1 = 0. >>> xi = np.zeros((1, 2, 2)) >>> xi[0, 1, 0] = 1.0 >>> xi[0, 0, 1] = 1.0 >>> rm = np.zeros((3, 2, 2)) >>> rm[0, 1, 0] = 1.0 >>> rm[1, 1, 0] = 1.0 >>> rm[2, 1, 0] = 1.0 >>> phase_transformation(2, 1, rm, xi) [-omega_1, -omega_1 - varpi_1] """ # We first define the needed variables E0, omega_laser = define_laser_variables(Nl) theta = [Symbol('theta'+str(i+1)) for i in range(Ne)] # We check for the case of xi being a list of matrices. if type(xi) == list: xi = np.array([[[xi[l][i, j] for j in range(Ne)] for i in range(Ne)] for l in range(Nl)]) # We find all the equations that the specified problem has to fulfil. eqs = [] for i in range(Ne): for j in range(0, i): if (rm[0][i, j] != 0) or \ (rm[1][i, j] != 0) or \ (rm[2][i, j] != 0): for l in range(Nl): if xi[l, i, j] == 1: eqs += [-omega_laser[l] + theta[j] - theta[i]] if return_equations: return eqs # We solve the system of equations. sol = sympy.solve(eqs, theta, dict=True) sol = sol[0] # We add any missing theta that may be left outside if the system is # under determined. extra_thetas = [] for i in range(Ne): if theta[i] not in sol.keys(): sol.update({theta[i]: theta[i]}) extra_thetas += [theta[i]] # We make the solution such that theta1 + omega_level1 = 0. omega_level, omega, gamma = define_frequencies(Ne) eq_crit = sol[theta[0]] + omega_level[0] ss = sympy.solve(eq_crit, extra_thetas[0])[0] ss = {extra_thetas[0]: ss} sol_simple = [sol[theta[i]].subs(ss) for i in range(Ne)] # sol = [] # for i in range(Ne): # soli = [] # for l in range(Nl): # soli += [sympy.diff(sol_simple[theta[i]], omega_laser[l])] # sol += [soli] return sol_simple
[ "def", "phase_transformation", "(", "Ne", ",", "Nl", ",", "rm", ",", "xi", ",", "return_equations", "=", "False", ")", ":", "# We first define the needed variables", "E0", ",", "omega_laser", "=", "define_laser_variables", "(", "Nl", ")", "theta", "=", "[", "S...
Returns a phase transformation theta_i. The phase transformation is defined in a way such that theta1 + omega_level1 = 0. >>> xi = np.zeros((1, 2, 2)) >>> xi[0, 1, 0] = 1.0 >>> xi[0, 0, 1] = 1.0 >>> rm = np.zeros((3, 2, 2)) >>> rm[0, 1, 0] = 1.0 >>> rm[1, 1, 0] = 1.0 >>> rm[2, 1, 0] = 1.0 >>> phase_transformation(2, 1, rm, xi) [-omega_1, -omega_1 - varpi_1]
[ "Returns", "a", "phase", "transformation", "theta_i", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L242-L311
oscarlazoarjona/fast
fast/bloch.py
define_simplification
def define_simplification(omega_level, xi, Nl): """Return a simplifying function, its inverse, and simplified frequencies. This implements an index iu that labels energies in a non-degenerate way. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> print(omega_levelu) [0.0, 100.0, 200.0, 300.0] >>> print(Neu) 4 >>> print(xiu) [[[0. 1. 0. 0.] [1. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] <BLANKLINE> [[0. 0. 1. 1.] [0. 0. 0. 0.] [1. 0. 0. 0.] [1. 0. 0. 0.]]] """ try: Ne = len(omega_level) except: Ne = omega_level.shape[0] ##################################### # 1 We calculate the symplifying functions. om = omega_level[0] iu = 0; Neu = 1 omega_levelu = [om] d = {}; di = {0: 0} for i in range(Ne): if omega_level[i] != om: iu += 1 om = omega_level[i] Neu += 1 omega_levelu += [om] di.update({iu: i}) d.update({i: iu}) def u(i): return d[i] def invu(iu): return di[iu] ##################################### # 2 We build the simplified xi. Neu = len(omega_levelu) xiu = np.array([[[xi[l, invu(i), invu(j)] for j in range(Neu)] for i in range(Neu)] for l in range(Nl)]) ##################################### return u, invu, omega_levelu, Neu, xiu
python
def define_simplification(omega_level, xi, Nl): """Return a simplifying function, its inverse, and simplified frequencies. This implements an index iu that labels energies in a non-degenerate way. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> print(omega_levelu) [0.0, 100.0, 200.0, 300.0] >>> print(Neu) 4 >>> print(xiu) [[[0. 1. 0. 0.] [1. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] <BLANKLINE> [[0. 0. 1. 1.] [0. 0. 0. 0.] [1. 0. 0. 0.] [1. 0. 0. 0.]]] """ try: Ne = len(omega_level) except: Ne = omega_level.shape[0] ##################################### # 1 We calculate the symplifying functions. om = omega_level[0] iu = 0; Neu = 1 omega_levelu = [om] d = {}; di = {0: 0} for i in range(Ne): if omega_level[i] != om: iu += 1 om = omega_level[i] Neu += 1 omega_levelu += [om] di.update({iu: i}) d.update({i: iu}) def u(i): return d[i] def invu(iu): return di[iu] ##################################### # 2 We build the simplified xi. Neu = len(omega_levelu) xiu = np.array([[[xi[l, invu(i), invu(j)] for j in range(Neu)] for i in range(Neu)] for l in range(Nl)]) ##################################### return u, invu, omega_levelu, Neu, xiu
[ "def", "define_simplification", "(", "omega_level", ",", "xi", ",", "Nl", ")", ":", "try", ":", "Ne", "=", "len", "(", "omega_level", ")", "except", ":", "Ne", "=", "omega_level", ".", "shape", "[", "0", "]", "#####################################", "# 1 We ...
Return a simplifying function, its inverse, and simplified frequencies. This implements an index iu that labels energies in a non-degenerate way. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> print(omega_levelu) [0.0, 100.0, 200.0, 300.0] >>> print(Neu) 4 >>> print(xiu) [[[0. 1. 0. 0.] [1. 0. 0. 0.] [0. 0. 0. 0.] [0. 0. 0. 0.]] <BLANKLINE> [[0. 0. 1. 1.] [0. 0. 0. 0.] [1. 0. 0. 0.] [1. 0. 0. 0.]]]
[ "Return", "a", "simplifying", "function", "its", "inverse", "and", "simplified", "frequencies", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L314-L380
oscarlazoarjona/fast
fast/bloch.py
find_omega_min
def find_omega_min(omega_levelu, Neu, Nl, xiu): r"""Find the smallest transition frequency for each field. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> find_omega_min(omega_levelu, Neu, Nl, xiu) ([100.0, 200.0], [1, 2], [0, 0]) """ omega_min = []; iu0 = []; ju0 = [] for l in range(Nl): omegasl = [] for iu in range(Neu): for ju in range(iu): if xiu[l, iu, ju] == 1: omegasl += [(omega_levelu[iu]-omega_levelu[ju], iu, ju)] omegasl = list(sorted(omegasl)) omega_min += [omegasl[0][0]] iu0 += [omegasl[0][1]] ju0 += [omegasl[0][2]] return omega_min, iu0, ju0
python
def find_omega_min(omega_levelu, Neu, Nl, xiu): r"""Find the smallest transition frequency for each field. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> find_omega_min(omega_levelu, Neu, Nl, xiu) ([100.0, 200.0], [1, 2], [0, 0]) """ omega_min = []; iu0 = []; ju0 = [] for l in range(Nl): omegasl = [] for iu in range(Neu): for ju in range(iu): if xiu[l, iu, ju] == 1: omegasl += [(omega_levelu[iu]-omega_levelu[ju], iu, ju)] omegasl = list(sorted(omegasl)) omega_min += [omegasl[0][0]] iu0 += [omegasl[0][1]] ju0 += [omegasl[0][2]] return omega_min, iu0, ju0
[ "def", "find_omega_min", "(", "omega_levelu", ",", "Neu", ",", "Nl", ",", "xiu", ")", ":", "omega_min", "=", "[", "]", "iu0", "=", "[", "]", "ju0", "=", "[", "]", "for", "l", "in", "range", "(", "Nl", ")", ":", "omegasl", "=", "[", "]", "for", ...
r"""Find the smallest transition frequency for each field. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> find_omega_min(omega_levelu, Neu, Nl, xiu) ([100.0, 200.0], [1, 2], [0, 0])
[ "r", "Find", "the", "smallest", "transition", "frequency", "for", "each", "field", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L383-L414
oscarlazoarjona/fast
fast/bloch.py
detunings_indices
def detunings_indices(Neu, Nl, xiu): r"""Get the indices of the transitions of all fields. They are returned in the form [[(i1, j1), (i2, j2)], ...,[(i1, j1)]]. that is, one list of pairs of indices for each field. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> detunings_indices(Neu, Nl, xiu) [[(1, 0)], [(2, 0), (3, 0)]] """ pairs = [] for l in range(Nl): ind = [] for iu in range(Neu): for ju in range(iu): if xiu[l, iu, ju] == 1: ind += [(iu, ju)] pairs += [ind] return pairs
python
def detunings_indices(Neu, Nl, xiu): r"""Get the indices of the transitions of all fields. They are returned in the form [[(i1, j1), (i2, j2)], ...,[(i1, j1)]]. that is, one list of pairs of indices for each field. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> detunings_indices(Neu, Nl, xiu) [[(1, 0)], [(2, 0), (3, 0)]] """ pairs = [] for l in range(Nl): ind = [] for iu in range(Neu): for ju in range(iu): if xiu[l, iu, ju] == 1: ind += [(iu, ju)] pairs += [ind] return pairs
[ "def", "detunings_indices", "(", "Neu", ",", "Nl", ",", "xiu", ")", ":", "pairs", "=", "[", "]", "for", "l", "in", "range", "(", "Nl", ")", ":", "ind", "=", "[", "]", "for", "iu", "in", "range", "(", "Neu", ")", ":", "for", "ju", "in", "range...
r"""Get the indices of the transitions of all fields. They are returned in the form [[(i1, j1), (i2, j2)], ...,[(i1, j1)]]. that is, one list of pairs of indices for each field. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> detunings_indices(Neu, Nl, xiu) [[(1, 0)], [(2, 0), (3, 0)]]
[ "r", "Get", "the", "indices", "of", "the", "transitions", "of", "all", "fields", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L417-L448
oscarlazoarjona/fast
fast/bloch.py
detunings_code
def detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0): r"""Get the code to calculate the simplified detunings. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu) >>> pairs = detunings_indices(Neu, Nl, xiu) >>> print(detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0)) delta1_2_1 = detuning_knob[0] delta2_3_1 = detuning_knob[1] delta2_4_1 = detuning_knob[1] + (-100.0) <BLANKLINE> """ code_det = "" for l in range(Nl): for pair in pairs[l]: iu, ju = pair code_det += " delta"+str(l+1) code_det += "_"+str(iu+1) code_det += "_"+str(ju+1) code_det += " = detuning_knob["+str(l)+"]" corr = -omega_levelu[iu]+omega_levelu[iu0[l]] corr = -omega_levelu[ju0[l]]+omega_levelu[ju] + corr if corr != 0: code_det += " + ("+str(corr)+")" code_det += "\n" return code_det
python
def detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0): r"""Get the code to calculate the simplified detunings. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu) >>> pairs = detunings_indices(Neu, Nl, xiu) >>> print(detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0)) delta1_2_1 = detuning_knob[0] delta2_3_1 = detuning_knob[1] delta2_4_1 = detuning_knob[1] + (-100.0) <BLANKLINE> """ code_det = "" for l in range(Nl): for pair in pairs[l]: iu, ju = pair code_det += " delta"+str(l+1) code_det += "_"+str(iu+1) code_det += "_"+str(ju+1) code_det += " = detuning_knob["+str(l)+"]" corr = -omega_levelu[iu]+omega_levelu[iu0[l]] corr = -omega_levelu[ju0[l]]+omega_levelu[ju] + corr if corr != 0: code_det += " + ("+str(corr)+")" code_det += "\n" return code_det
[ "def", "detunings_code", "(", "Neu", ",", "Nl", ",", "pairs", ",", "omega_levelu", ",", "iu0", ",", "ju0", ")", ":", "code_det", "=", "\"\"", "for", "l", "in", "range", "(", "Nl", ")", ":", "for", "pair", "in", "pairs", "[", "l", "]", ":", "iu", ...
r"""Get the code to calculate the simplified detunings. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu) >>> pairs = detunings_indices(Neu, Nl, xiu) >>> print(detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0)) delta1_2_1 = detuning_knob[0] delta2_3_1 = detuning_knob[1] delta2_4_1 = detuning_knob[1] + (-100.0) <BLANKLINE>
[ "r", "Get", "the", "code", "to", "calculate", "the", "simplified", "detunings", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L451-L489
oscarlazoarjona/fast
fast/bloch.py
detunings_combinations
def detunings_combinations(pairs): r"""Return all combinations of detunings. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> pairs = detunings_indices(Neu, Nl, xiu) >>> detunings_combinations(pairs) [[(1, 0), (2, 0)], [(1, 0), (3, 0)]] """ def iter(pairs, combs, l): combs_n = [] for i in range(len(combs)): for j in range(len(pairs[l])): combs_n += [combs[i] + [pairs[l][j]]] return combs_n Nl = len(pairs) combs = [[pairs[0][k]] for k in range(len(pairs[0]))] for l in range(1, Nl): combs = iter(pairs, combs, 1) return combs
python
def detunings_combinations(pairs): r"""Return all combinations of detunings. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> pairs = detunings_indices(Neu, Nl, xiu) >>> detunings_combinations(pairs) [[(1, 0), (2, 0)], [(1, 0), (3, 0)]] """ def iter(pairs, combs, l): combs_n = [] for i in range(len(combs)): for j in range(len(pairs[l])): combs_n += [combs[i] + [pairs[l][j]]] return combs_n Nl = len(pairs) combs = [[pairs[0][k]] for k in range(len(pairs[0]))] for l in range(1, Nl): combs = iter(pairs, combs, 1) return combs
[ "def", "detunings_combinations", "(", "pairs", ")", ":", "def", "iter", "(", "pairs", ",", "combs", ",", "l", ")", ":", "combs_n", "=", "[", "]", "for", "i", "in", "range", "(", "len", "(", "combs", ")", ")", ":", "for", "j", "in", "range", "(", ...
r"""Return all combinations of detunings. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> pairs = detunings_indices(Neu, Nl, xiu) >>> detunings_combinations(pairs) [[(1, 0), (2, 0)], [(1, 0), (3, 0)]]
[ "r", "Return", "all", "combinations", "of", "detunings", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L492-L524
oscarlazoarjona/fast
fast/bloch.py
detunings_rewrite
def detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu, omega_levelu, iu0, ju0): r"""Rewrite a symbolic expression in terms of allowed transition detunings. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu) >>> pairs = detunings_indices(Neu, Nl, xiu) >>> combs = detunings_combinations(pairs) >>> symb_omega_levelu, omega, gamma = define_frequencies(Neu) >>> E0, omega_laser = define_laser_variables(Nl) Most times it is possible to express these combinations of optical frequencies in terms of allowed transition detunings. >>> expr = +(omega_laser[0]-(symb_omega_levelu[1]-symb_omega_levelu[0])) >>> expr += -(omega_laser[1]-(symb_omega_levelu[3]-symb_omega_levelu[0])) >>> expr -omega_2 + omega_4 + varpi_1 - varpi_2 >>> detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu, ... omega_levelu, iu0, ju0) '+delta1_2_1-delta2_4_1' But some times it is not possible: >>> expr = +(omega_laser[1]-(symb_omega_levelu[1]-symb_omega_levelu[0])) >>> expr += -(omega_laser[0]-(symb_omega_levelu[3]-symb_omega_levelu[0])) >>> expr -omega_2 + omega_4 - varpi_1 + varpi_2 >>> detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu, ... omega_levelu, iu0, ju0) '300.000000000000-detuning_knob[0]+detuning_knob[1]' """ Nl = len(omega_laser) Neu = len(symb_omega_levelu) # We find the coefficients a_i of the field frequencies. a = [diff(expr, omega_laser[l]) for l in range(Nl)] # We look for a combination of the detunings obtained with the # function detunings_code. For each combination we sum the # detunings weighed by a_i. success = False for comb in combs: expr_try = 0 for l in range(Nl): expr_try += a[l]*(omega_laser[l] - symb_omega_levelu[comb[l][0]] + symb_omega_levelu[comb[l][1]]) if expr-expr_try == 0: success = True break assign = "" if success: for l in range(Nl): if a[l] != 0: if a[l] == 1: assign += "+" elif a[l] == -1: assign += "-" assign += "delta"+str(l+1) assign += "_"+str(comb[l][0]+1) assign += "_"+str(comb[l][1]+1) else: # We get the code for Hii using detuning knobs. # We find out the remainder terms. _remainder = expr - sum([a[l]*omega_laser[l] for l in range(Nl)]) # We find the coefficients of the remainder. b = [diff(_remainder, symb_omega_levelu[j]) for j in range(Neu)] # We calculate the remainder numerically. remainder = sum([b[j]*omega_levelu[j] for j in range(Neu)]) # We add the contributions from the detuning knobs. remainder += sum([a[l]*(omega_levelu[iu0[l]] - omega_levelu[ju0[l]]) for l in range(Nl)]) assign = str(remainder) # We get the code for Hii using detuning knobs. for l in range(Nl): if a[l] != 0: if a[l] == 1: assign += "+" elif a[l] == -1: assign += "-" assign += "detuning_knob["+str(l)+"]" return assign
python
def detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu, omega_levelu, iu0, ju0): r"""Rewrite a symbolic expression in terms of allowed transition detunings. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu) >>> pairs = detunings_indices(Neu, Nl, xiu) >>> combs = detunings_combinations(pairs) >>> symb_omega_levelu, omega, gamma = define_frequencies(Neu) >>> E0, omega_laser = define_laser_variables(Nl) Most times it is possible to express these combinations of optical frequencies in terms of allowed transition detunings. >>> expr = +(omega_laser[0]-(symb_omega_levelu[1]-symb_omega_levelu[0])) >>> expr += -(omega_laser[1]-(symb_omega_levelu[3]-symb_omega_levelu[0])) >>> expr -omega_2 + omega_4 + varpi_1 - varpi_2 >>> detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu, ... omega_levelu, iu0, ju0) '+delta1_2_1-delta2_4_1' But some times it is not possible: >>> expr = +(omega_laser[1]-(symb_omega_levelu[1]-symb_omega_levelu[0])) >>> expr += -(omega_laser[0]-(symb_omega_levelu[3]-symb_omega_levelu[0])) >>> expr -omega_2 + omega_4 - varpi_1 + varpi_2 >>> detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu, ... omega_levelu, iu0, ju0) '300.000000000000-detuning_knob[0]+detuning_knob[1]' """ Nl = len(omega_laser) Neu = len(symb_omega_levelu) # We find the coefficients a_i of the field frequencies. a = [diff(expr, omega_laser[l]) for l in range(Nl)] # We look for a combination of the detunings obtained with the # function detunings_code. For each combination we sum the # detunings weighed by a_i. success = False for comb in combs: expr_try = 0 for l in range(Nl): expr_try += a[l]*(omega_laser[l] - symb_omega_levelu[comb[l][0]] + symb_omega_levelu[comb[l][1]]) if expr-expr_try == 0: success = True break assign = "" if success: for l in range(Nl): if a[l] != 0: if a[l] == 1: assign += "+" elif a[l] == -1: assign += "-" assign += "delta"+str(l+1) assign += "_"+str(comb[l][0]+1) assign += "_"+str(comb[l][1]+1) else: # We get the code for Hii using detuning knobs. # We find out the remainder terms. _remainder = expr - sum([a[l]*omega_laser[l] for l in range(Nl)]) # We find the coefficients of the remainder. b = [diff(_remainder, symb_omega_levelu[j]) for j in range(Neu)] # We calculate the remainder numerically. remainder = sum([b[j]*omega_levelu[j] for j in range(Neu)]) # We add the contributions from the detuning knobs. remainder += sum([a[l]*(omega_levelu[iu0[l]] - omega_levelu[ju0[l]]) for l in range(Nl)]) assign = str(remainder) # We get the code for Hii using detuning knobs. for l in range(Nl): if a[l] != 0: if a[l] == 1: assign += "+" elif a[l] == -1: assign += "-" assign += "detuning_knob["+str(l)+"]" return assign
[ "def", "detunings_rewrite", "(", "expr", ",", "combs", ",", "omega_laser", ",", "symb_omega_levelu", ",", "omega_levelu", ",", "iu0", ",", "ju0", ")", ":", "Nl", "=", "len", "(", "omega_laser", ")", "Neu", "=", "len", "(", "symb_omega_levelu", ")", "# We f...
r"""Rewrite a symbolic expression in terms of allowed transition detunings. >>> Ne = 6 >>> Nl = 2 >>> omega_level = [0.0, 100.0, 100.0, 200.0, 200.0, 300.0] >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 >>> aux = define_simplification(omega_level, xi, Nl) >>> u, invu, omega_levelu, Neu, xiu = aux >>> omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu) >>> pairs = detunings_indices(Neu, Nl, xiu) >>> combs = detunings_combinations(pairs) >>> symb_omega_levelu, omega, gamma = define_frequencies(Neu) >>> E0, omega_laser = define_laser_variables(Nl) Most times it is possible to express these combinations of optical frequencies in terms of allowed transition detunings. >>> expr = +(omega_laser[0]-(symb_omega_levelu[1]-symb_omega_levelu[0])) >>> expr += -(omega_laser[1]-(symb_omega_levelu[3]-symb_omega_levelu[0])) >>> expr -omega_2 + omega_4 + varpi_1 - varpi_2 >>> detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu, ... omega_levelu, iu0, ju0) '+delta1_2_1-delta2_4_1' But some times it is not possible: >>> expr = +(omega_laser[1]-(symb_omega_levelu[1]-symb_omega_levelu[0])) >>> expr += -(omega_laser[0]-(symb_omega_levelu[3]-symb_omega_levelu[0])) >>> expr -omega_2 + omega_4 - varpi_1 + varpi_2 >>> detunings_rewrite(expr, combs, omega_laser, symb_omega_levelu, ... omega_levelu, iu0, ju0) '300.000000000000-detuning_knob[0]+detuning_knob[1]'
[ "r", "Rewrite", "a", "symbolic", "expression", "in", "terms", "of", "allowed", "transition", "detunings", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L527-L624
oscarlazoarjona/fast
fast/bloch.py
fast_hamiltonian
def fast_hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, xi, theta, file_name=None): r"""Return a fast function that returns a Hamiltonian as an array. INPUT: - ``Ep`` - A list with the electric field amplitudes (real or complex). - ``epsilonp`` - A list of the polarization vectors of the fields \ (real or complex). - ``detuning_knob`` - A list of the detunings of each field (relative \ to the transition of lowest energy). - ``rm`` - The below-diagonal components of the position operator in the cartesian basis: .. math:: \vec{r}^{(-)}_{i j} = [ x_{ij}, y_{ij}, z_{ij} ] \hspace{1cm} \forall \hspace{1cm} 0 < j < i - ``omega_level`` - The angular frequencies of each state. - ``xi`` - An array whose ``xi[l, i, j]`` element is 1 if the \ transition :math:`|i\rangle \rightarrow |j\rangle`\ is driven by field \ ``l`` and 0 otherwise. - ``theta`` - A list of symbolic expressions representing a phase \ transformation. - ``file_name`` - A string indicating a file to save the function's \ code. If the arguments Ep, epsilonp, and detuning_knob are symbolic amounts, \ the returned function will accept numeric values of Ep, epsilonp, and \ detuning_knob as arguments. All quantities should be in SI units. EXAMPLES: We build an example using states coupled like this: --- |4> --- |5> --- |6> ^ ^ ^ | | | | --- |2> | --- |3> | 2 | ^ 2 | ^ | 2 | 1 | | 1 | | | | | | | ------------------------------------- |1> With the numbers on kets labeling states and the plain numbers labeling fields. The number of states and fields: >>> Ne = 6 >>> Nl = 2 We invent some energy levels: >>> omega_level = np.array([0.0, 100.0, 100.0, 200.0, 200.0, 300.0]) >>> omega_level = omega_level*1e6*2*np.pi We build the symbol xi, that chooses which laser couples which transition. >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 We invent some electric dipole matrix elements: >>> from scipy.constants import physical_constants >>> a0 = physical_constants["Bohr radius"][0] >>> rm = np.zeros((3, Ne, Ne)) >>> for l in range(Nl): ... for i in range(Ne): ... for j in range(i): ... if xi[l, i, j] != 0: ... rm[2, i, j] = float(i)*a0 The phase transformation: >>> theta = phase_transformation(Ne, Nl, rm, xi) We define the possible arguments: >>> from sympy import symbols, pi >>> from fast.symbolic import polarization_vector >>> detuning_knob = symbols("delta1 delta2") >>> detuning_knob_vals = np.array([-1.0, 3.0])*1e6*2*np.pi >>> Ep, omega_laser = define_laser_variables(Nl) >>> Ep_vals = [1e2, 1e2] >>> alpha = symbols("alpha") >>> epsilon = polarization_vector(0, pi/2, alpha, 0, 1) >>> epsilonp = [epsilon, epsilon] >>> epsilonp_vals = [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0]] There are 8 ways to call fast_hamiltonian: 1 .- Get a function of detunings, field amplitudes, polarizations: >>> H1 = fast_hamiltonian(Ep, epsilonp, detuning_knob, rm, ... omega_level, xi, theta) 2 .- Get a function of field amplitudes, polarizations: >>> H2 = fast_hamiltonian(Ep, epsilonp, detuning_knob_vals, rm, ... omega_level, xi, theta) 3 .- Get a function of detunings, polarizations: >>> H3 = fast_hamiltonian(Ep_vals, epsilonp, detuning_knob, rm, ... omega_level, xi, theta) 4 .- Get a function of detunings, field amplitudes: >>> H4 = fast_hamiltonian(Ep, epsilonp_vals, detuning_knob, rm, ... omega_level, xi, theta) 5 .- Get a function of detunings: >>> H5 = fast_hamiltonian(Ep_vals, epsilonp_vals, detuning_knob, rm, ... omega_level, xi, theta) 6 .- Get a function of field amplitudes: >>> H6 = fast_hamiltonian(Ep, epsilonp_vals, detuning_knob_vals, rm, ... omega_level, xi, theta) 7 .- Get a function of polarizations: >>> H7 = fast_hamiltonian(Ep_vals, epsilonp, detuning_knob_vals, rm, ... omega_level, xi, theta) 8 .- Get a function of nothing: >>> H8 = fast_hamiltonian(Ep_vals, epsilonp_vals, detuning_knob_vals, rm, ... omega_level, xi, theta) We test all of these combinations. >>> print(H1(Ep_vals, epsilonp_vals, detuning_knob_vals) \ ... /hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H2(Ep_vals, epsilonp_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H3(epsilonp_vals, detuning_knob_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H4(Ep_vals, detuning_knob_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H5(detuning_knob_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H6(Ep_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H7(epsilonp_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H8()/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] """ # We determine which arguments are constants. if True: Nl = len(Ep) Ne = np.array(rm[0]).shape[0] try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True try: detuning_knob = np.array([float(detuning_knob[l]) for l in range(Nl)]) variable_detuning_knob = False except: variable_detuning_knob = True # We convert rm to a numpy array rm = np.array([[[complex(rm[k][i, j]) for j in range(Ne)] for i in range(Ne)] for k in range(3)]) # We establish the arguments of the output function. if True: code = "" code += "def hamiltonian(" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if variable_detuning_knob: code += "detuning_knob, " if code[-2:] == ", ": code = code[:-2] code += "):\n" code += ' r"""A fast calculation of the hamiltonian."""\n' code += " H = np.zeros(("+str(Ne)+", "+str(Ne)+"), complex)\n\n" # We get the code for the below-diagonal elements # (Rabi frequencies). if True: code += " # We calculate the below-diagonal elements.\n" for i in range(Ne): for j in range(i): for l in range(Nl): if xi[l, i, j] == 1.0: # We get the below-diagonal terms. code += " H["+str(i)+", "+str(j)+"] = " # We get the code for Ep. if variable_Ep: code += "0.5*Ep["+str(l)+"]" else: code += str(0.5*Ep[l]) # We get the code for epsilonp dot rm rmij = rm[:, i, j] if variable_epsilonp: code += "*cartesian_dot_product(" code += "epsilonp["+str(l)+"]," code += str(list(rmij*e_num))+" )" else: dp = cartesian_dot_product(epsilonp[l], rmij) dp = dp*e_num code += "*("+str(dp)+")" code += "\n" # We get the code for the above-diagonal elements # (Conjugate Rabi frequencies). if True: code += "\n" code += """ # We calculate the above-diagonal elements.\n""" code += """ for i in range("""+str(Ne)+"""):\n""" code += """ for j in range(i+1, """+str(Ne)+"""):\n""" code += """ H[i, j] = H[j, i].conjugate()\n\n""" # We get the code for the diagonal elements (detunings). if True: code += " # We calculate the diagonal elements.\n" # We build the degeneration simplification and is inverse (to avoid # large combinatorics). aux = define_simplification(omega_level, xi, Nl) u, invu, omega_levelu, Neu, xiu = aux # For each field we find the smallest transition frequency, and its # simplified indices. omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu) ##################################### # We get the code to calculate the non degenerate detunings. pairs = detunings_indices(Neu, Nl, xiu) if not variable_detuning_knob: code += " detuning_knob = np.zeros("+str(Nl)+")\n" for l in range(Nl): code += " detuning_knob["+str(l)+"] = " +\ str(detuning_knob[l])+"\n" code_det = detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0) code += code_det code += "\n" ##################################### # We find the coefficients a_l that multiply omega_laser_l in # H_ii = omega_level_iu + theta_iu = \sum_i a_i varpi_i + remainder _omega_level, omega, gamma = define_frequencies(Ne) _omega_levelu, omega, gamma = define_frequencies(Neu) E0, omega_laser = define_laser_variables(Nl) # So we build all combinations. combs = detunings_combinations(pairs) for i in range(Ne): _Hii = theta[i] + _omega_levelu[u(i)] aux = (_Hii, combs, omega_laser, _omega_levelu, omega_levelu, iu0, ju0) assign = detunings_rewrite(*aux) if assign != "": code += " H["+str(i)+", "+str(i)+"] = "+assign+"\n" code += "\n" code += """ for i in range("""+str(Ne)+"""):\n""" code += """ H[i, i] = H[i, i]*"""+str(hbar_num)+"\n" code += " return H\n" if file_name is not None: f = file(file_name, "w") f.write(code) f.close() hamiltonian = code exec hamiltonian return hamiltonian
python
def fast_hamiltonian(Ep, epsilonp, detuning_knob, rm, omega_level, xi, theta, file_name=None): r"""Return a fast function that returns a Hamiltonian as an array. INPUT: - ``Ep`` - A list with the electric field amplitudes (real or complex). - ``epsilonp`` - A list of the polarization vectors of the fields \ (real or complex). - ``detuning_knob`` - A list of the detunings of each field (relative \ to the transition of lowest energy). - ``rm`` - The below-diagonal components of the position operator in the cartesian basis: .. math:: \vec{r}^{(-)}_{i j} = [ x_{ij}, y_{ij}, z_{ij} ] \hspace{1cm} \forall \hspace{1cm} 0 < j < i - ``omega_level`` - The angular frequencies of each state. - ``xi`` - An array whose ``xi[l, i, j]`` element is 1 if the \ transition :math:`|i\rangle \rightarrow |j\rangle`\ is driven by field \ ``l`` and 0 otherwise. - ``theta`` - A list of symbolic expressions representing a phase \ transformation. - ``file_name`` - A string indicating a file to save the function's \ code. If the arguments Ep, epsilonp, and detuning_knob are symbolic amounts, \ the returned function will accept numeric values of Ep, epsilonp, and \ detuning_knob as arguments. All quantities should be in SI units. EXAMPLES: We build an example using states coupled like this: --- |4> --- |5> --- |6> ^ ^ ^ | | | | --- |2> | --- |3> | 2 | ^ 2 | ^ | 2 | 1 | | 1 | | | | | | | ------------------------------------- |1> With the numbers on kets labeling states and the plain numbers labeling fields. The number of states and fields: >>> Ne = 6 >>> Nl = 2 We invent some energy levels: >>> omega_level = np.array([0.0, 100.0, 100.0, 200.0, 200.0, 300.0]) >>> omega_level = omega_level*1e6*2*np.pi We build the symbol xi, that chooses which laser couples which transition. >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 We invent some electric dipole matrix elements: >>> from scipy.constants import physical_constants >>> a0 = physical_constants["Bohr radius"][0] >>> rm = np.zeros((3, Ne, Ne)) >>> for l in range(Nl): ... for i in range(Ne): ... for j in range(i): ... if xi[l, i, j] != 0: ... rm[2, i, j] = float(i)*a0 The phase transformation: >>> theta = phase_transformation(Ne, Nl, rm, xi) We define the possible arguments: >>> from sympy import symbols, pi >>> from fast.symbolic import polarization_vector >>> detuning_knob = symbols("delta1 delta2") >>> detuning_knob_vals = np.array([-1.0, 3.0])*1e6*2*np.pi >>> Ep, omega_laser = define_laser_variables(Nl) >>> Ep_vals = [1e2, 1e2] >>> alpha = symbols("alpha") >>> epsilon = polarization_vector(0, pi/2, alpha, 0, 1) >>> epsilonp = [epsilon, epsilon] >>> epsilonp_vals = [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0]] There are 8 ways to call fast_hamiltonian: 1 .- Get a function of detunings, field amplitudes, polarizations: >>> H1 = fast_hamiltonian(Ep, epsilonp, detuning_knob, rm, ... omega_level, xi, theta) 2 .- Get a function of field amplitudes, polarizations: >>> H2 = fast_hamiltonian(Ep, epsilonp, detuning_knob_vals, rm, ... omega_level, xi, theta) 3 .- Get a function of detunings, polarizations: >>> H3 = fast_hamiltonian(Ep_vals, epsilonp, detuning_knob, rm, ... omega_level, xi, theta) 4 .- Get a function of detunings, field amplitudes: >>> H4 = fast_hamiltonian(Ep, epsilonp_vals, detuning_knob, rm, ... omega_level, xi, theta) 5 .- Get a function of detunings: >>> H5 = fast_hamiltonian(Ep_vals, epsilonp_vals, detuning_knob, rm, ... omega_level, xi, theta) 6 .- Get a function of field amplitudes: >>> H6 = fast_hamiltonian(Ep, epsilonp_vals, detuning_knob_vals, rm, ... omega_level, xi, theta) 7 .- Get a function of polarizations: >>> H7 = fast_hamiltonian(Ep_vals, epsilonp, detuning_knob_vals, rm, ... omega_level, xi, theta) 8 .- Get a function of nothing: >>> H8 = fast_hamiltonian(Ep_vals, epsilonp_vals, detuning_knob_vals, rm, ... omega_level, xi, theta) We test all of these combinations. >>> print(H1(Ep_vals, epsilonp_vals, detuning_knob_vals) \ ... /hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H2(Ep_vals, epsilonp_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H3(epsilonp_vals, detuning_knob_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H4(Ep_vals, detuning_knob_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H5(detuning_knob_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H6(Ep_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H7(epsilonp_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H8()/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] """ # We determine which arguments are constants. if True: Nl = len(Ep) Ne = np.array(rm[0]).shape[0] try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True try: detuning_knob = np.array([float(detuning_knob[l]) for l in range(Nl)]) variable_detuning_knob = False except: variable_detuning_knob = True # We convert rm to a numpy array rm = np.array([[[complex(rm[k][i, j]) for j in range(Ne)] for i in range(Ne)] for k in range(3)]) # We establish the arguments of the output function. if True: code = "" code += "def hamiltonian(" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if variable_detuning_knob: code += "detuning_knob, " if code[-2:] == ", ": code = code[:-2] code += "):\n" code += ' r"""A fast calculation of the hamiltonian."""\n' code += " H = np.zeros(("+str(Ne)+", "+str(Ne)+"), complex)\n\n" # We get the code for the below-diagonal elements # (Rabi frequencies). if True: code += " # We calculate the below-diagonal elements.\n" for i in range(Ne): for j in range(i): for l in range(Nl): if xi[l, i, j] == 1.0: # We get the below-diagonal terms. code += " H["+str(i)+", "+str(j)+"] = " # We get the code for Ep. if variable_Ep: code += "0.5*Ep["+str(l)+"]" else: code += str(0.5*Ep[l]) # We get the code for epsilonp dot rm rmij = rm[:, i, j] if variable_epsilonp: code += "*cartesian_dot_product(" code += "epsilonp["+str(l)+"]," code += str(list(rmij*e_num))+" )" else: dp = cartesian_dot_product(epsilonp[l], rmij) dp = dp*e_num code += "*("+str(dp)+")" code += "\n" # We get the code for the above-diagonal elements # (Conjugate Rabi frequencies). if True: code += "\n" code += """ # We calculate the above-diagonal elements.\n""" code += """ for i in range("""+str(Ne)+"""):\n""" code += """ for j in range(i+1, """+str(Ne)+"""):\n""" code += """ H[i, j] = H[j, i].conjugate()\n\n""" # We get the code for the diagonal elements (detunings). if True: code += " # We calculate the diagonal elements.\n" # We build the degeneration simplification and is inverse (to avoid # large combinatorics). aux = define_simplification(omega_level, xi, Nl) u, invu, omega_levelu, Neu, xiu = aux # For each field we find the smallest transition frequency, and its # simplified indices. omega_min, iu0, ju0 = find_omega_min(omega_levelu, Neu, Nl, xiu) ##################################### # We get the code to calculate the non degenerate detunings. pairs = detunings_indices(Neu, Nl, xiu) if not variable_detuning_knob: code += " detuning_knob = np.zeros("+str(Nl)+")\n" for l in range(Nl): code += " detuning_knob["+str(l)+"] = " +\ str(detuning_knob[l])+"\n" code_det = detunings_code(Neu, Nl, pairs, omega_levelu, iu0, ju0) code += code_det code += "\n" ##################################### # We find the coefficients a_l that multiply omega_laser_l in # H_ii = omega_level_iu + theta_iu = \sum_i a_i varpi_i + remainder _omega_level, omega, gamma = define_frequencies(Ne) _omega_levelu, omega, gamma = define_frequencies(Neu) E0, omega_laser = define_laser_variables(Nl) # So we build all combinations. combs = detunings_combinations(pairs) for i in range(Ne): _Hii = theta[i] + _omega_levelu[u(i)] aux = (_Hii, combs, omega_laser, _omega_levelu, omega_levelu, iu0, ju0) assign = detunings_rewrite(*aux) if assign != "": code += " H["+str(i)+", "+str(i)+"] = "+assign+"\n" code += "\n" code += """ for i in range("""+str(Ne)+"""):\n""" code += """ H[i, i] = H[i, i]*"""+str(hbar_num)+"\n" code += " return H\n" if file_name is not None: f = file(file_name, "w") f.write(code) f.close() hamiltonian = code exec hamiltonian return hamiltonian
[ "def", "fast_hamiltonian", "(", "Ep", ",", "epsilonp", ",", "detuning_knob", ",", "rm", ",", "omega_level", ",", "xi", ",", "theta", ",", "file_name", "=", "None", ")", ":", "# We determine which arguments are constants.", "if", "True", ":", "Nl", "=", "len", ...
r"""Return a fast function that returns a Hamiltonian as an array. INPUT: - ``Ep`` - A list with the electric field amplitudes (real or complex). - ``epsilonp`` - A list of the polarization vectors of the fields \ (real or complex). - ``detuning_knob`` - A list of the detunings of each field (relative \ to the transition of lowest energy). - ``rm`` - The below-diagonal components of the position operator in the cartesian basis: .. math:: \vec{r}^{(-)}_{i j} = [ x_{ij}, y_{ij}, z_{ij} ] \hspace{1cm} \forall \hspace{1cm} 0 < j < i - ``omega_level`` - The angular frequencies of each state. - ``xi`` - An array whose ``xi[l, i, j]`` element is 1 if the \ transition :math:`|i\rangle \rightarrow |j\rangle`\ is driven by field \ ``l`` and 0 otherwise. - ``theta`` - A list of symbolic expressions representing a phase \ transformation. - ``file_name`` - A string indicating a file to save the function's \ code. If the arguments Ep, epsilonp, and detuning_knob are symbolic amounts, \ the returned function will accept numeric values of Ep, epsilonp, and \ detuning_knob as arguments. All quantities should be in SI units. EXAMPLES: We build an example using states coupled like this: --- |4> --- |5> --- |6> ^ ^ ^ | | | | --- |2> | --- |3> | 2 | ^ 2 | ^ | 2 | 1 | | 1 | | | | | | | ------------------------------------- |1> With the numbers on kets labeling states and the plain numbers labeling fields. The number of states and fields: >>> Ne = 6 >>> Nl = 2 We invent some energy levels: >>> omega_level = np.array([0.0, 100.0, 100.0, 200.0, 200.0, 300.0]) >>> omega_level = omega_level*1e6*2*np.pi We build the symbol xi, that chooses which laser couples which transition. >>> xi = np.zeros((Nl, Ne, Ne)) >>> coup = [[(1, 0), (2, 0)], [(3, 0), (4, 0), (5, 0)]] >>> for l in range(Nl): ... for pair in coup[l]: ... xi[l, pair[0], pair[1]] = 1.0 ... xi[l, pair[1], pair[0]] = 1.0 We invent some electric dipole matrix elements: >>> from scipy.constants import physical_constants >>> a0 = physical_constants["Bohr radius"][0] >>> rm = np.zeros((3, Ne, Ne)) >>> for l in range(Nl): ... for i in range(Ne): ... for j in range(i): ... if xi[l, i, j] != 0: ... rm[2, i, j] = float(i)*a0 The phase transformation: >>> theta = phase_transformation(Ne, Nl, rm, xi) We define the possible arguments: >>> from sympy import symbols, pi >>> from fast.symbolic import polarization_vector >>> detuning_knob = symbols("delta1 delta2") >>> detuning_knob_vals = np.array([-1.0, 3.0])*1e6*2*np.pi >>> Ep, omega_laser = define_laser_variables(Nl) >>> Ep_vals = [1e2, 1e2] >>> alpha = symbols("alpha") >>> epsilon = polarization_vector(0, pi/2, alpha, 0, 1) >>> epsilonp = [epsilon, epsilon] >>> epsilonp_vals = [[0.0, 0.0, 1.0], [0.0, 0.0, 1.0]] There are 8 ways to call fast_hamiltonian: 1 .- Get a function of detunings, field amplitudes, polarizations: >>> H1 = fast_hamiltonian(Ep, epsilonp, detuning_knob, rm, ... omega_level, xi, theta) 2 .- Get a function of field amplitudes, polarizations: >>> H2 = fast_hamiltonian(Ep, epsilonp, detuning_knob_vals, rm, ... omega_level, xi, theta) 3 .- Get a function of detunings, polarizations: >>> H3 = fast_hamiltonian(Ep_vals, epsilonp, detuning_knob, rm, ... omega_level, xi, theta) 4 .- Get a function of detunings, field amplitudes: >>> H4 = fast_hamiltonian(Ep, epsilonp_vals, detuning_knob, rm, ... omega_level, xi, theta) 5 .- Get a function of detunings: >>> H5 = fast_hamiltonian(Ep_vals, epsilonp_vals, detuning_knob, rm, ... omega_level, xi, theta) 6 .- Get a function of field amplitudes: >>> H6 = fast_hamiltonian(Ep, epsilonp_vals, detuning_knob_vals, rm, ... omega_level, xi, theta) 7 .- Get a function of polarizations: >>> H7 = fast_hamiltonian(Ep_vals, epsilonp, detuning_knob_vals, rm, ... omega_level, xi, theta) 8 .- Get a function of nothing: >>> H8 = fast_hamiltonian(Ep_vals, epsilonp_vals, detuning_knob_vals, rm, ... omega_level, xi, theta) We test all of these combinations. >>> print(H1(Ep_vals, epsilonp_vals, detuning_knob_vals) \ ... /hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H2(Ep_vals, epsilonp_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H3(epsilonp_vals, detuning_knob_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H4(Ep_vals, detuning_knob_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H5(detuning_knob_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H6(Ep_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H7(epsilonp_vals)/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]] >>> print(H8()/hbar_num/2/np.pi*1e-6) [[ 0. +0.j 0.6398+0.j 1.2795+0.j 1.9193+0.j 2.5591+0.j 3.1989+0.j] [ 0.6398+0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.2795+0.j 0. +0.j 1. +0.j 0. +0.j 0. +0.j 0. +0.j] [ 1.9193+0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j 0. +0.j] [ 2.5591+0.j 0. +0.j 0. +0.j 0. +0.j -3. +0.j 0. +0.j] [ 3.1989+0.j 0. +0.j 0. +0.j 0. +0.j 0. +0.j 97. +0.j]]
[ "r", "Return", "a", "fast", "function", "that", "returns", "a", "Hamiltonian", "as", "an", "array", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L627-L949
oscarlazoarjona/fast
fast/bloch.py
independent_get_coefficients
def independent_get_coefficients(coef, rhouv, s, i, j, k, u, v, unfolding, matrix_form): r"""Get the indices mu, nu, and term coefficients for linear terms. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_matrix(Ne)[1, 1] >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1) >>> unfolding = Unfolding(Ne, real=True, normalized=True) >>> independent_get_coefficients(coef, rhouv, s, i, j, k, u, v, ... unfolding, False) [[1, None, -2.00000000000000, False, False]] """ if matrix_form: coef = -coef Mu = unfolding.Mu mu = Mu(s, i, j) rhouv_isconjugated = False if s == 1: coef_list = [[mu, None, -im(coef), matrix_form, rhouv_isconjugated]] elif s == -1: coef_list = [[mu, None, re(coef), matrix_form, rhouv_isconjugated]] else: coef_list = [[mu, None, coef, matrix_form, rhouv_isconjugated]] return coef_list
python
def independent_get_coefficients(coef, rhouv, s, i, j, k, u, v, unfolding, matrix_form): r"""Get the indices mu, nu, and term coefficients for linear terms. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_matrix(Ne)[1, 1] >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1) >>> unfolding = Unfolding(Ne, real=True, normalized=True) >>> independent_get_coefficients(coef, rhouv, s, i, j, k, u, v, ... unfolding, False) [[1, None, -2.00000000000000, False, False]] """ if matrix_form: coef = -coef Mu = unfolding.Mu mu = Mu(s, i, j) rhouv_isconjugated = False if s == 1: coef_list = [[mu, None, -im(coef), matrix_form, rhouv_isconjugated]] elif s == -1: coef_list = [[mu, None, re(coef), matrix_form, rhouv_isconjugated]] else: coef_list = [[mu, None, coef, matrix_form, rhouv_isconjugated]] return coef_list
[ "def", "independent_get_coefficients", "(", "coef", ",", "rhouv", ",", "s", ",", "i", ",", "j", ",", "k", ",", "u", ",", "v", ",", "unfolding", ",", "matrix_form", ")", ":", "if", "matrix_form", ":", "coef", "=", "-", "coef", "Mu", "=", "unfolding", ...
r"""Get the indices mu, nu, and term coefficients for linear terms. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_matrix(Ne)[1, 1] >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1) >>> unfolding = Unfolding(Ne, real=True, normalized=True) >>> independent_get_coefficients(coef, rhouv, s, i, j, k, u, v, ... unfolding, False) [[1, None, -2.00000000000000, False, False]]
[ "r", "Get", "the", "indices", "mu", "nu", "and", "term", "coefficients", "for", "linear", "terms", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L1354-L1381
oscarlazoarjona/fast
fast/bloch.py
linear_get_coefficients
def linear_get_coefficients(coef, rhouv, s, i, j, k, u, v, unfolding, matrix_form): r"""Get the indices mu, nu, and term coefficients for linear terms. We determine mu and nu, the indices labeling the density matrix components d rho[mu] /dt = sum_nu A[mu, nu]*rho[nu] for this complex and rho_u,v. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_matrix(Ne)[1, 1] >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1) >>> unfolding = Unfolding(Ne, real=True, normalized=True) >>> linear_get_coefficients(coef, rhouv, s, i, j, k, u, v, ... unfolding, False) [[1, 0, -2.00000000000000, False, False]] """ Ne = unfolding.Ne Mu = unfolding.Mu # We determine mu, the index labeling the equation. mu = Mu(s, i, j) if unfolding.normalized and u == 0 and v == 0: # We find the nu and coefficients for a term of the form. # coef*rho_{00} = coef*(1-sum_{i=1}^{Ne-1} rho_{ii}) if unfolding.real: ss = 1 else: ss = 0 mu11 = Mu(ss, 1, 1) muNeNe = Mu(ss, Ne-1, Ne-1) rhouv_isconjugated = False if s == 1: coef_list = [[mu, nu, im(coef), matrix_form, rhouv_isconjugated] for nu in range(mu11, muNeNe+1)] elif s == -1: coef_list = [[mu, nu, -re(coef), matrix_form, rhouv_isconjugated] for nu in range(mu11, muNeNe+1)] elif s == 0: coef_list = [[mu, nu, -coef, matrix_form, rhouv_isconjugated] for nu in range(mu11, muNeNe+1)] return coef_list ##################################################################### if (unfolding.lower_triangular and isinstance(rhouv, sympy.conjugate)): u, v = (v, u) rhouv_isconjugated = True else: rhouv_isconjugated = False # If the unfolding is real, there are two terms for this # component rhouv of equation mu. if unfolding.real: nur = Mu(1, u, v) nui = Mu(-1, u, v) else: nu = Mu(0, u, v) ##################################################################### # We determine the coefficients for each term. if unfolding.real: # There are two sets of forumas for the coefficients depending # on whether rhouv_isconjugated. # re(I*x*conjugate(y)) = -im(x)*re(y) + re(x)*im(y) # re(I*x*y) = -im(x)*re(y) - re(x)*im(y) # im(I*x*conjugate(y)) = +re(x)*re(y) + im(x)*im(y) # im(I*x*y) = +re(x)*re(y) - im(x)*im(y) if s == 1: # The real part if rhouv_isconjugated: coef_rerhouv = -im(coef) coef_imrhouv = re(coef) else: coef_rerhouv = -im(coef) coef_imrhouv = -re(coef) elif s == -1: if rhouv_isconjugated: coef_rerhouv = re(coef) coef_imrhouv = im(coef) else: coef_rerhouv = re(coef) coef_imrhouv = -im(coef) coef_list = [[mu, nur, coef_rerhouv, matrix_form, rhouv_isconjugated]] if nui is not None: coef_list += [[mu, nui, coef_imrhouv, matrix_form, rhouv_isconjugated]] else: coef_list = [[mu, nu, coef, matrix_form, rhouv_isconjugated]] return coef_list
python
def linear_get_coefficients(coef, rhouv, s, i, j, k, u, v, unfolding, matrix_form): r"""Get the indices mu, nu, and term coefficients for linear terms. We determine mu and nu, the indices labeling the density matrix components d rho[mu] /dt = sum_nu A[mu, nu]*rho[nu] for this complex and rho_u,v. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_matrix(Ne)[1, 1] >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1) >>> unfolding = Unfolding(Ne, real=True, normalized=True) >>> linear_get_coefficients(coef, rhouv, s, i, j, k, u, v, ... unfolding, False) [[1, 0, -2.00000000000000, False, False]] """ Ne = unfolding.Ne Mu = unfolding.Mu # We determine mu, the index labeling the equation. mu = Mu(s, i, j) if unfolding.normalized and u == 0 and v == 0: # We find the nu and coefficients for a term of the form. # coef*rho_{00} = coef*(1-sum_{i=1}^{Ne-1} rho_{ii}) if unfolding.real: ss = 1 else: ss = 0 mu11 = Mu(ss, 1, 1) muNeNe = Mu(ss, Ne-1, Ne-1) rhouv_isconjugated = False if s == 1: coef_list = [[mu, nu, im(coef), matrix_form, rhouv_isconjugated] for nu in range(mu11, muNeNe+1)] elif s == -1: coef_list = [[mu, nu, -re(coef), matrix_form, rhouv_isconjugated] for nu in range(mu11, muNeNe+1)] elif s == 0: coef_list = [[mu, nu, -coef, matrix_form, rhouv_isconjugated] for nu in range(mu11, muNeNe+1)] return coef_list ##################################################################### if (unfolding.lower_triangular and isinstance(rhouv, sympy.conjugate)): u, v = (v, u) rhouv_isconjugated = True else: rhouv_isconjugated = False # If the unfolding is real, there are two terms for this # component rhouv of equation mu. if unfolding.real: nur = Mu(1, u, v) nui = Mu(-1, u, v) else: nu = Mu(0, u, v) ##################################################################### # We determine the coefficients for each term. if unfolding.real: # There are two sets of forumas for the coefficients depending # on whether rhouv_isconjugated. # re(I*x*conjugate(y)) = -im(x)*re(y) + re(x)*im(y) # re(I*x*y) = -im(x)*re(y) - re(x)*im(y) # im(I*x*conjugate(y)) = +re(x)*re(y) + im(x)*im(y) # im(I*x*y) = +re(x)*re(y) - im(x)*im(y) if s == 1: # The real part if rhouv_isconjugated: coef_rerhouv = -im(coef) coef_imrhouv = re(coef) else: coef_rerhouv = -im(coef) coef_imrhouv = -re(coef) elif s == -1: if rhouv_isconjugated: coef_rerhouv = re(coef) coef_imrhouv = im(coef) else: coef_rerhouv = re(coef) coef_imrhouv = -im(coef) coef_list = [[mu, nur, coef_rerhouv, matrix_form, rhouv_isconjugated]] if nui is not None: coef_list += [[mu, nui, coef_imrhouv, matrix_form, rhouv_isconjugated]] else: coef_list = [[mu, nu, coef, matrix_form, rhouv_isconjugated]] return coef_list
[ "def", "linear_get_coefficients", "(", "coef", ",", "rhouv", ",", "s", ",", "i", ",", "j", ",", "k", ",", "u", ",", "v", ",", "unfolding", ",", "matrix_form", ")", ":", "Ne", "=", "unfolding", ".", "Ne", "Mu", "=", "unfolding", ".", "Mu", "# We det...
r"""Get the indices mu, nu, and term coefficients for linear terms. We determine mu and nu, the indices labeling the density matrix components d rho[mu] /dt = sum_nu A[mu, nu]*rho[nu] for this complex and rho_u,v. >>> from fast.symbolic import define_density_matrix >>> Ne = 2 >>> coef = 1+2j >>> rhouv = define_density_matrix(Ne)[1, 1] >>> s, i, j, k, u, v = (1, 1, 0, 1, 1, 1) >>> unfolding = Unfolding(Ne, real=True, normalized=True) >>> linear_get_coefficients(coef, rhouv, s, i, j, k, u, v, ... unfolding, False) [[1, 0, -2.00000000000000, False, False]]
[ "r", "Get", "the", "indices", "mu", "nu", "and", "term", "coefficients", "for", "linear", "terms", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L1384-L1478
oscarlazoarjona/fast
fast/bloch.py
term_code
def term_code(mu, nu, coef, matrix_form, rhouv_isconjugated, linear=True): r"""Get code to calculate a linear term. >>> term_code(1, 0, 33, False, False, True) ' rhs[1] += (33)*rho[0]\n' """ if coef == 0: return "" coef = str(coef) # We change E_{0i} -> E0[i-1] ini = coef.find("E_{0") fin = coef.find("}") if ini != -1: l = int(coef[ini+4: fin]) coef = coef[:ini]+"Ep["+str(l-1)+"]"+coef[fin+1:] # We change r[i, j] -> r[:, i, j] coef = coef.replace("rp[", "rp[:, ") coef = coef.replace("rm[", "rm[:, ") # We change symbolic complex-operations into fast numpy functions. coef = coef.replace("conjugate(", "np.conjugate(") coef = coef.replace("re(", "np.real(") coef = coef.replace("im(", "np.imag(") coef = coef.replace("*I", "j") if not linear: if matrix_form: s = " b["+str(mu)+"] += "+coef+"\n" else: s = " rhs["+str(mu)+"] += "+coef+"\n" return s # We add the syntax to calculate the term and store it in memory. s = " " if matrix_form: s += "A["+str(mu)+", "+str(nu)+"] += "+coef+"\n" else: s += "rhs["+str(mu)+"] += ("+coef+")" if rhouv_isconjugated: s += "*np.conjugate(rho["+str(nu)+'])\n' else: s += "*rho["+str(nu)+']\n' return s
python
def term_code(mu, nu, coef, matrix_form, rhouv_isconjugated, linear=True): r"""Get code to calculate a linear term. >>> term_code(1, 0, 33, False, False, True) ' rhs[1] += (33)*rho[0]\n' """ if coef == 0: return "" coef = str(coef) # We change E_{0i} -> E0[i-1] ini = coef.find("E_{0") fin = coef.find("}") if ini != -1: l = int(coef[ini+4: fin]) coef = coef[:ini]+"Ep["+str(l-1)+"]"+coef[fin+1:] # We change r[i, j] -> r[:, i, j] coef = coef.replace("rp[", "rp[:, ") coef = coef.replace("rm[", "rm[:, ") # We change symbolic complex-operations into fast numpy functions. coef = coef.replace("conjugate(", "np.conjugate(") coef = coef.replace("re(", "np.real(") coef = coef.replace("im(", "np.imag(") coef = coef.replace("*I", "j") if not linear: if matrix_form: s = " b["+str(mu)+"] += "+coef+"\n" else: s = " rhs["+str(mu)+"] += "+coef+"\n" return s # We add the syntax to calculate the term and store it in memory. s = " " if matrix_form: s += "A["+str(mu)+", "+str(nu)+"] += "+coef+"\n" else: s += "rhs["+str(mu)+"] += ("+coef+")" if rhouv_isconjugated: s += "*np.conjugate(rho["+str(nu)+'])\n' else: s += "*rho["+str(nu)+']\n' return s
[ "def", "term_code", "(", "mu", ",", "nu", ",", "coef", ",", "matrix_form", ",", "rhouv_isconjugated", ",", "linear", "=", "True", ")", ":", "if", "coef", "==", "0", ":", "return", "\"\"", "coef", "=", "str", "(", "coef", ")", "# We change E_{0i} -> E0[i-...
r"""Get code to calculate a linear term. >>> term_code(1, 0, 33, False, False, True) ' rhs[1] += (33)*rho[0]\n'
[ "r", "Get", "code", "to", "calculate", "a", "linear", "term", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L1481-L1528
oscarlazoarjona/fast
fast/bloch.py
fast_rabi_terms
def fast_rabi_terms(Ep, epsilonp, rm, xi, theta, unfolding, matrix_form=False, file_name=None, return_code=False): r"""Return a fast function that returns the Rabi frequency terms. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import define_laser_variables, polarization_vector >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Eps = [electric_field_amplitude_top(1e-3, 1e-3, 1, "SI")] >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Rabi frequency terms. >>> rabi_terms = fast_rabi_terms(Ep, epsilonps, rm, xi, theta, unfolding) Apply this to a density matrix. >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) >>> rhosv = unfolding(rhos) >>> rhs_rabi = rabi_terms(rhosv, Eps) >>> print(rhs_rabi) [-55680831.474 0. 2784041.5737] """ if not unfolding.lower_triangular: mes = "It is very inefficient to solve using all components of the " mes += "density matrix. Better set lower_triangular=True in Unfolding." raise NotImplementedError(mes) if matrix_form and (not unfolding.real) and (unfolding.lower_triangular): mes = "It is not possible to express the equations in matrix form " mes += "for complex lower triangular components only." raise ValueError(mes) Nl = len(Ep) Ne = unfolding.Ne # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True # We unpack variables. if True: Nrho = unfolding.Nrho # Mu = unfolding.Mu IJ = unfolding.IJ normalized = unfolding.normalized lower_triangular = unfolding.lower_triangular # The conjugate stuff. Em = [ii.conjugate() for ii in Ep] if variable_epsilonp: epsilonm = Vector3D(epsilonp.args[0].conjugate()) else: epsilonm = [ii.conjugate() for ii in epsilonp] # We convert rm to a numpy array rm = np.array([[[complex(rm[k][i, j]) for j in range(Ne)] for i in range(Ne)] for k in range(3)]) rp = np.array([rm[ii].T.conjugate() for ii in range(3)]) rm_aux = Vector3D(IndexedBase("rm", shape=(Ne, Ne))) rp_aux = Vector3D(IndexedBase("rp", shape=(Ne, Ne))) # We define needed matrices. rho = define_density_matrix(Ne, explicitly_hermitian=lower_triangular, normalized=normalized) if variable_epsilonp: Omega = [[sum([xi[l, i, j] * (Ep[l]*dot(epsilonp[l], rm_aux[i, j]) * delta_greater(i, j) + Em[l]*dot(epsilonm[l], rp_aux[i, j]) * delta_lesser(i, j)) for l in range(Nl)]) for j in range(Ne)] for i in range(Ne)] else: Omega = [[sum([xi[l, i, j] * (Ep[l]*dot(epsilonp[l], rm[:, i, j]) + Em[l]*dot(epsilonm[l], rp[:, i, j])) for l in range(Nl)]) for j in range(Ne)] for i in range(Ne)] # We establish the arguments of the output function. if True: code = "" code += "def rabi_terms(" if not matrix_form: code += "rho, " if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if code[-2:] == ", ": code = code[:-2] code += "):\n" code += ' r"""A fast calculation of the Rabi terms."""\n' # We initialize the output and auxiliaries. if True: # We introduce the factor that multiplies all terms. if unfolding.real: code += " fact = "+str(e_num/hbar_num)+"\n\n" else: code += " fact = "+str(1j*e_num/hbar_num)+"\n\n" if variable_epsilonp: # We put rm and rp into the code np.set_printoptions(threshold=np.nan) code += " rm = np."+rm.__repr__()+"\n\n" code += " rp = np."+rp.__repr__()+"\n\n" code += " def dot(epsilon, rij):\n" code += " return epsilon[0]*rij[0]" code += " + epsilon[1]*rij[1]" code += " + epsilon[2]*rij[2]\n\n" np.set_printoptions(threshold=1000) if matrix_form: code += " A = np.zeros(("+str(Nrho)+", "+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" if unfolding.normalized: code += " b = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" else: code += " rhs = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" # We write code for the linear terms. rho00_terms = [] for mu in range(Nrho): s, i, j = IJ(mu) for l in range(Nl): for k in range(Ne): if xi[l, i, k] == 1: # There is a I* Omega_l,i,k * rho_k,j term. u = k; v = j args = (0.5*Omega[i][k], rho[k, j], s, i, j, k, u, v, unfolding, matrix_form) term_list = linear_get_coefficients(*args) for term in term_list: code += term_code(*term) # We keep note that there was a term with rho00. if k == 0 and j == 0: rho00_terms += [args] if xi[l, k, j] == 1: # There is a -I * Omega_l,k,j * rho_i,k term. u = i; v = k args = (-0.5*Omega[k][j], rho[i, k], s, i, j, k, u, v, unfolding, matrix_form) term_list = linear_get_coefficients(*args) for term in term_list: code += term_code(*term) # We keep note that there was a term with rho00. if i == 0 and k == 0: rho00_terms += [args] # We write code for the independent terms. if unfolding.normalized: code += "\n # Independent terms:\n" for term in rho00_terms: coef_list = independent_get_coefficients(*term) for coef in coef_list: code += term_code(*coef, linear=False) # We finish the code. if True: if matrix_form: if unfolding.normalized: code += " A *= fact\n" code += " b *= fact\n" code += " return A, b\n" else: code += " A *= fact\n" code += " return A\n" else: code += " rhs *= fact\n" code += " return rhs\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() rabi_terms = code if not return_code: exec rabi_terms return rabi_terms
python
def fast_rabi_terms(Ep, epsilonp, rm, xi, theta, unfolding, matrix_form=False, file_name=None, return_code=False): r"""Return a fast function that returns the Rabi frequency terms. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import define_laser_variables, polarization_vector >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Eps = [electric_field_amplitude_top(1e-3, 1e-3, 1, "SI")] >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Rabi frequency terms. >>> rabi_terms = fast_rabi_terms(Ep, epsilonps, rm, xi, theta, unfolding) Apply this to a density matrix. >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) >>> rhosv = unfolding(rhos) >>> rhs_rabi = rabi_terms(rhosv, Eps) >>> print(rhs_rabi) [-55680831.474 0. 2784041.5737] """ if not unfolding.lower_triangular: mes = "It is very inefficient to solve using all components of the " mes += "density matrix. Better set lower_triangular=True in Unfolding." raise NotImplementedError(mes) if matrix_form and (not unfolding.real) and (unfolding.lower_triangular): mes = "It is not possible to express the equations in matrix form " mes += "for complex lower triangular components only." raise ValueError(mes) Nl = len(Ep) Ne = unfolding.Ne # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True # We unpack variables. if True: Nrho = unfolding.Nrho # Mu = unfolding.Mu IJ = unfolding.IJ normalized = unfolding.normalized lower_triangular = unfolding.lower_triangular # The conjugate stuff. Em = [ii.conjugate() for ii in Ep] if variable_epsilonp: epsilonm = Vector3D(epsilonp.args[0].conjugate()) else: epsilonm = [ii.conjugate() for ii in epsilonp] # We convert rm to a numpy array rm = np.array([[[complex(rm[k][i, j]) for j in range(Ne)] for i in range(Ne)] for k in range(3)]) rp = np.array([rm[ii].T.conjugate() for ii in range(3)]) rm_aux = Vector3D(IndexedBase("rm", shape=(Ne, Ne))) rp_aux = Vector3D(IndexedBase("rp", shape=(Ne, Ne))) # We define needed matrices. rho = define_density_matrix(Ne, explicitly_hermitian=lower_triangular, normalized=normalized) if variable_epsilonp: Omega = [[sum([xi[l, i, j] * (Ep[l]*dot(epsilonp[l], rm_aux[i, j]) * delta_greater(i, j) + Em[l]*dot(epsilonm[l], rp_aux[i, j]) * delta_lesser(i, j)) for l in range(Nl)]) for j in range(Ne)] for i in range(Ne)] else: Omega = [[sum([xi[l, i, j] * (Ep[l]*dot(epsilonp[l], rm[:, i, j]) + Em[l]*dot(epsilonm[l], rp[:, i, j])) for l in range(Nl)]) for j in range(Ne)] for i in range(Ne)] # We establish the arguments of the output function. if True: code = "" code += "def rabi_terms(" if not matrix_form: code += "rho, " if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if code[-2:] == ", ": code = code[:-2] code += "):\n" code += ' r"""A fast calculation of the Rabi terms."""\n' # We initialize the output and auxiliaries. if True: # We introduce the factor that multiplies all terms. if unfolding.real: code += " fact = "+str(e_num/hbar_num)+"\n\n" else: code += " fact = "+str(1j*e_num/hbar_num)+"\n\n" if variable_epsilonp: # We put rm and rp into the code np.set_printoptions(threshold=np.nan) code += " rm = np."+rm.__repr__()+"\n\n" code += " rp = np."+rp.__repr__()+"\n\n" code += " def dot(epsilon, rij):\n" code += " return epsilon[0]*rij[0]" code += " + epsilon[1]*rij[1]" code += " + epsilon[2]*rij[2]\n\n" np.set_printoptions(threshold=1000) if matrix_form: code += " A = np.zeros(("+str(Nrho)+", "+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" if unfolding.normalized: code += " b = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" else: code += " rhs = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" # We write code for the linear terms. rho00_terms = [] for mu in range(Nrho): s, i, j = IJ(mu) for l in range(Nl): for k in range(Ne): if xi[l, i, k] == 1: # There is a I* Omega_l,i,k * rho_k,j term. u = k; v = j args = (0.5*Omega[i][k], rho[k, j], s, i, j, k, u, v, unfolding, matrix_form) term_list = linear_get_coefficients(*args) for term in term_list: code += term_code(*term) # We keep note that there was a term with rho00. if k == 0 and j == 0: rho00_terms += [args] if xi[l, k, j] == 1: # There is a -I * Omega_l,k,j * rho_i,k term. u = i; v = k args = (-0.5*Omega[k][j], rho[i, k], s, i, j, k, u, v, unfolding, matrix_form) term_list = linear_get_coefficients(*args) for term in term_list: code += term_code(*term) # We keep note that there was a term with rho00. if i == 0 and k == 0: rho00_terms += [args] # We write code for the independent terms. if unfolding.normalized: code += "\n # Independent terms:\n" for term in rho00_terms: coef_list = independent_get_coefficients(*term) for coef in coef_list: code += term_code(*coef, linear=False) # We finish the code. if True: if matrix_form: if unfolding.normalized: code += " A *= fact\n" code += " b *= fact\n" code += " return A, b\n" else: code += " A *= fact\n" code += " return A\n" else: code += " rhs *= fact\n" code += " return rhs\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() rabi_terms = code if not return_code: exec rabi_terms return rabi_terms
[ "def", "fast_rabi_terms", "(", "Ep", ",", "epsilonp", ",", "rm", ",", "xi", ",", "theta", ",", "unfolding", ",", "matrix_form", "=", "False", ",", "file_name", "=", "None", ",", "return_code", "=", "False", ")", ":", "if", "not", "unfolding", ".", "low...
r"""Return a fast function that returns the Rabi frequency terms. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import define_laser_variables, polarization_vector >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Eps = [electric_field_amplitude_top(1e-3, 1e-3, 1, "SI")] >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Rabi frequency terms. >>> rabi_terms = fast_rabi_terms(Ep, epsilonps, rm, xi, theta, unfolding) Apply this to a density matrix. >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) >>> rhosv = unfolding(rhos) >>> rhs_rabi = rabi_terms(rhosv, Eps) >>> print(rhs_rabi) [-55680831.474 0. 2784041.5737]
[ "r", "Return", "a", "fast", "function", "that", "returns", "the", "Rabi", "frequency", "terms", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L1531-L1745
oscarlazoarjona/fast
fast/bloch.py
fast_lindblad_terms
def fast_lindblad_terms(gamma, unfolding, matrix_form=False, file_name=None, return_code=False): r"""Return a fast function that returns the Lindblad terms. We test a basic two-level system. >>> import numpy as np >>> Ne = 2 >>> gamma21 = 2*np.pi*6e6 >>> gamma = np.array([[0.0, -gamma21], ... [gamma21, 0.0]]) >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Lindblad terms. >>> lindblad_terms = fast_lindblad_terms(gamma, unfolding) Apply this to a density matrix. >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) >>> rhosv = unfolding(rhos) >>> rhs_lindblad = lindblad_terms(rhosv) >>> print(rhs_lindblad) [-15079644.7372 -56548667.7646 37699111.8431] """ Ne = unfolding.Ne Nrho = unfolding.Nrho Mu = unfolding.Mu # We establish the arguments of the output function. if True: code = "" code += "def lindblad_terms(" if not matrix_form: code += "rho, " if code[-2:] == ", ": code = code[:-2] code += "):\n" # We initialize the output and auxiliaries. if True: # We introduce the factor that multiplies all terms. if matrix_form: code += " A = np.zeros(("+str(Nrho)+", "+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" if unfolding.normalized: code += " b = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" else: code += " rhs = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" for a in range(Ne): for b in range(a): # The first term is of the from # gamma_ab * rho_aa |b><b| if not (unfolding.normalized and b == 0): coef = gamma[a, b] if unfolding.real: mu = Mu(1, b, b) nu = Mu(1, a, a) else: mu = Mu(0, b, b) nu = Mu(0, a, a) code += term_code(mu, nu, coef, matrix_form, False) # The second term is of the form # sum_j -gamma_ab/2 rho_aj |a><j| # for a lower triangular unfolding, this j runs from 1 to a. for j in range(a): coef = -gamma[a, b]*0.5 if unfolding.real: mur = Mu(1, a, j) code += term_code(mur, mur, coef, matrix_form, False) mui = Mu(-1, a, j) code += term_code(mui, mui, coef, matrix_form, False) else: mu = Mu(0, a, j) code += term_code(mu, mu, coef, matrix_form, False) # The third term is of the form # - sum_i 1/2 rho_ia |i><a| # for a lower triangular unfolding, this i runs from a to Ne. for i in range(a+1, Ne): coef = -gamma[a, b]*0.5 if unfolding.real: mur = Mu(1, i, a) code += term_code(mur, mur, coef, matrix_form, False) mui = Mu(-1, i, a) code += term_code(mui, mui, coef, matrix_form, False) else: mu = Mu(0, i, a) code += term_code(mu, mu, coef, matrix_form, False) # We missed one term in each of the previous fors, that together # correspond to # -gamma_ab * rho_aa |a><a| coef = -gamma[a, b] if unfolding.real: mu = Mu(1, a, a) else: mu = Mu(0, a, a) code += term_code(mu, mu, coef, matrix_form, False) # We finish the code. if True: if matrix_form: if unfolding.normalized: code += " return A, b\n" else: code += " return A\n" else: code += " return rhs\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() lindblad_terms = code if not return_code: exec lindblad_terms return lindblad_terms
python
def fast_lindblad_terms(gamma, unfolding, matrix_form=False, file_name=None, return_code=False): r"""Return a fast function that returns the Lindblad terms. We test a basic two-level system. >>> import numpy as np >>> Ne = 2 >>> gamma21 = 2*np.pi*6e6 >>> gamma = np.array([[0.0, -gamma21], ... [gamma21, 0.0]]) >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Lindblad terms. >>> lindblad_terms = fast_lindblad_terms(gamma, unfolding) Apply this to a density matrix. >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) >>> rhosv = unfolding(rhos) >>> rhs_lindblad = lindblad_terms(rhosv) >>> print(rhs_lindblad) [-15079644.7372 -56548667.7646 37699111.8431] """ Ne = unfolding.Ne Nrho = unfolding.Nrho Mu = unfolding.Mu # We establish the arguments of the output function. if True: code = "" code += "def lindblad_terms(" if not matrix_form: code += "rho, " if code[-2:] == ", ": code = code[:-2] code += "):\n" # We initialize the output and auxiliaries. if True: # We introduce the factor that multiplies all terms. if matrix_form: code += " A = np.zeros(("+str(Nrho)+", "+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" if unfolding.normalized: code += " b = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" else: code += " rhs = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" for a in range(Ne): for b in range(a): # The first term is of the from # gamma_ab * rho_aa |b><b| if not (unfolding.normalized and b == 0): coef = gamma[a, b] if unfolding.real: mu = Mu(1, b, b) nu = Mu(1, a, a) else: mu = Mu(0, b, b) nu = Mu(0, a, a) code += term_code(mu, nu, coef, matrix_form, False) # The second term is of the form # sum_j -gamma_ab/2 rho_aj |a><j| # for a lower triangular unfolding, this j runs from 1 to a. for j in range(a): coef = -gamma[a, b]*0.5 if unfolding.real: mur = Mu(1, a, j) code += term_code(mur, mur, coef, matrix_form, False) mui = Mu(-1, a, j) code += term_code(mui, mui, coef, matrix_form, False) else: mu = Mu(0, a, j) code += term_code(mu, mu, coef, matrix_form, False) # The third term is of the form # - sum_i 1/2 rho_ia |i><a| # for a lower triangular unfolding, this i runs from a to Ne. for i in range(a+1, Ne): coef = -gamma[a, b]*0.5 if unfolding.real: mur = Mu(1, i, a) code += term_code(mur, mur, coef, matrix_form, False) mui = Mu(-1, i, a) code += term_code(mui, mui, coef, matrix_form, False) else: mu = Mu(0, i, a) code += term_code(mu, mu, coef, matrix_form, False) # We missed one term in each of the previous fors, that together # correspond to # -gamma_ab * rho_aa |a><a| coef = -gamma[a, b] if unfolding.real: mu = Mu(1, a, a) else: mu = Mu(0, a, a) code += term_code(mu, mu, coef, matrix_form, False) # We finish the code. if True: if matrix_form: if unfolding.normalized: code += " return A, b\n" else: code += " return A\n" else: code += " return rhs\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() lindblad_terms = code if not return_code: exec lindblad_terms return lindblad_terms
[ "def", "fast_lindblad_terms", "(", "gamma", ",", "unfolding", ",", "matrix_form", "=", "False", ",", "file_name", "=", "None", ",", "return_code", "=", "False", ")", ":", "Ne", "=", "unfolding", ".", "Ne", "Nrho", "=", "unfolding", ".", "Nrho", "Mu", "="...
r"""Return a fast function that returns the Lindblad terms. We test a basic two-level system. >>> import numpy as np >>> Ne = 2 >>> gamma21 = 2*np.pi*6e6 >>> gamma = np.array([[0.0, -gamma21], ... [gamma21, 0.0]]) >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Lindblad terms. >>> lindblad_terms = fast_lindblad_terms(gamma, unfolding) Apply this to a density matrix. >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) >>> rhosv = unfolding(rhos) >>> rhs_lindblad = lindblad_terms(rhosv) >>> print(rhs_lindblad) [-15079644.7372 -56548667.7646 37699111.8431]
[ "r", "Return", "a", "fast", "function", "that", "returns", "the", "Lindblad", "terms", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L1920-L2053
oscarlazoarjona/fast
fast/bloch.py
fast_hamiltonian_terms
def fast_hamiltonian_terms(Ep, epsilonp, detuning_knob, omega_level, rm, xi, theta, unfolding, matrix_form=False, file_name=None, return_code=False): r"""Return a fast function that returns the Hamiltonian terms. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import define_laser_variables, polarization_vector >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> omega_level = [0, 1.0e9] >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] >>> detuning_knob = [symbols("delta1", real=True)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Hamiltonian terms. >>> aux = (Ep, epsilonps, detuning_knob, omega_level, rm, xi, theta, ... unfolding, False, None) >>> hamiltonian_terms = fast_hamiltonian_terms(*aux) Apply this to a density matrix. >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) >>> rhosv = unfolding(rhos) We specify values for the variables >>> detuning_knobs = [100e6] >>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI") >>> Eps *= np.exp(1j*np.pi) >>> Eps = [Eps] >>> print(hamiltonian_terms(rhosv, Eps, detuning_knobs)) [5.5681e+07 2.0000e+08 2.9722e+08] """ if not unfolding.lower_triangular: mes = "It is very inefficient to solve using all components of the " mes += "density matrix. Better set lower_triangular=True in Unfolding." raise NotImplementedError(mes) if matrix_form and (not unfolding.real) and (unfolding.lower_triangular): mes = "It is not possible to express the equations in matrix form " mes += "for complex lower triangular components only." raise ValueError(mes) Nl = len(Ep) Nrho = unfolding.Nrho # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True try: detuning_knob = np.array([float(detuning_knob[l]) for l in range(Nl)]) variable_detuning_knob = False except: variable_detuning_knob = True # We obtain code for the two parts. if True: if file_name is not None: file_name_rabi = file_name+"_rabi" file_name_detuning = file_name+"_detuning" else: file_name_rabi = file_name file_name_detuning = file_name rabi_terms = fast_rabi_terms(Ep, epsilonp, rm, xi, theta, unfolding, matrix_form=matrix_form, file_name=file_name_rabi, return_code=True) detuning_terms = fast_detuning_terms(detuning_knob, omega_level, xi, theta, unfolding, matrix_form=matrix_form, file_name=file_name_detuning, return_code=True) code = rabi_terms + "\n\n" + detuning_terms + "\n\n" # If these functions have 0 arguments, we call them only once! if not variable_Ep and not variable_epsilonp and matrix_form: code += "rabi_terms = rabi_terms()\n\n" if not variable_detuning_knob and matrix_form: code += "detuning_terms = detuning_terms()\n\n" # We establish the arguments of the output function. if True: code += "def hamiltonian_terms(" if not matrix_form: code += "rho, " if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if variable_detuning_knob: code += "detuning_knob, " code += "rabi_terms=rabi_terms, detuning_terms=detuning_terms" # if code[-2:] == ", ": code = code[:-2] code += "):\n" code += ' r"""A fast calculation of the hamiltonian terms."""\n' # if not variable_Ep and not varia # We initialize the output and auxiliaries. if True: # We introduce the factor that multiplies all terms. if matrix_form: code += " A = np.zeros(("+str(Nrho)+", "+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" if unfolding.normalized: code += " b = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" else: code += " rhs = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" # We call the Rabi terms. if True: if not variable_Ep and not variable_epsilonp and matrix_form: aux_code = "rabi_terms\n" else: aux_code = "rabi_terms(" if not matrix_form: aux_code += "rho, " if variable_Ep: aux_code += "Ep, " if variable_epsilonp: aux_code += "epsilonp, " if aux_code[-2:] == ", ": aux_code = aux_code[:-2] aux_code += ")\n" if matrix_form: if unfolding.normalized: code += " aux = " + aux_code code += " A += aux[0]\n" code += " b += aux[1]\n" else: code += " A = " + aux_code else: code += " rhs = " + aux_code # We call the detuning terms. if True: if not variable_detuning_knob and matrix_form: aux_code = "detuning_terms\n" else: aux_code = "detuning_terms(" if not matrix_form: aux_code += "rho, " if variable_detuning_knob: aux_code += "detuning_knob, " if aux_code[-2:] == ", ": aux_code = aux_code[:-2] aux_code += ")\n" if matrix_form: if unfolding.normalized: code += " aux = " + aux_code code += " A += aux[0]\n" code += " b += aux[1]\n" else: code += " A += " + aux_code else: code += " rhs += " + aux_code # We finish the code. if True: # code = rabi_code + "\n\n" + code if matrix_form: if unfolding.normalized: code += " return A, b\n" else: code += " return A\n" else: code += " return rhs\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() hamiltonian_terms = code if not return_code: exec hamiltonian_terms return hamiltonian_terms
python
def fast_hamiltonian_terms(Ep, epsilonp, detuning_knob, omega_level, rm, xi, theta, unfolding, matrix_form=False, file_name=None, return_code=False): r"""Return a fast function that returns the Hamiltonian terms. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import define_laser_variables, polarization_vector >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> omega_level = [0, 1.0e9] >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] >>> detuning_knob = [symbols("delta1", real=True)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Hamiltonian terms. >>> aux = (Ep, epsilonps, detuning_knob, omega_level, rm, xi, theta, ... unfolding, False, None) >>> hamiltonian_terms = fast_hamiltonian_terms(*aux) Apply this to a density matrix. >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) >>> rhosv = unfolding(rhos) We specify values for the variables >>> detuning_knobs = [100e6] >>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI") >>> Eps *= np.exp(1j*np.pi) >>> Eps = [Eps] >>> print(hamiltonian_terms(rhosv, Eps, detuning_knobs)) [5.5681e+07 2.0000e+08 2.9722e+08] """ if not unfolding.lower_triangular: mes = "It is very inefficient to solve using all components of the " mes += "density matrix. Better set lower_triangular=True in Unfolding." raise NotImplementedError(mes) if matrix_form and (not unfolding.real) and (unfolding.lower_triangular): mes = "It is not possible to express the equations in matrix form " mes += "for complex lower triangular components only." raise ValueError(mes) Nl = len(Ep) Nrho = unfolding.Nrho # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True try: detuning_knob = np.array([float(detuning_knob[l]) for l in range(Nl)]) variable_detuning_knob = False except: variable_detuning_knob = True # We obtain code for the two parts. if True: if file_name is not None: file_name_rabi = file_name+"_rabi" file_name_detuning = file_name+"_detuning" else: file_name_rabi = file_name file_name_detuning = file_name rabi_terms = fast_rabi_terms(Ep, epsilonp, rm, xi, theta, unfolding, matrix_form=matrix_form, file_name=file_name_rabi, return_code=True) detuning_terms = fast_detuning_terms(detuning_knob, omega_level, xi, theta, unfolding, matrix_form=matrix_form, file_name=file_name_detuning, return_code=True) code = rabi_terms + "\n\n" + detuning_terms + "\n\n" # If these functions have 0 arguments, we call them only once! if not variable_Ep and not variable_epsilonp and matrix_form: code += "rabi_terms = rabi_terms()\n\n" if not variable_detuning_knob and matrix_form: code += "detuning_terms = detuning_terms()\n\n" # We establish the arguments of the output function. if True: code += "def hamiltonian_terms(" if not matrix_form: code += "rho, " if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if variable_detuning_knob: code += "detuning_knob, " code += "rabi_terms=rabi_terms, detuning_terms=detuning_terms" # if code[-2:] == ", ": code = code[:-2] code += "):\n" code += ' r"""A fast calculation of the hamiltonian terms."""\n' # if not variable_Ep and not varia # We initialize the output and auxiliaries. if True: # We introduce the factor that multiplies all terms. if matrix_form: code += " A = np.zeros(("+str(Nrho)+", "+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" if unfolding.normalized: code += " b = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" else: code += " rhs = np.zeros(("+str(Nrho) if not unfolding.real: code += "), complex)\n\n" else: code += "))\n\n" # We call the Rabi terms. if True: if not variable_Ep and not variable_epsilonp and matrix_form: aux_code = "rabi_terms\n" else: aux_code = "rabi_terms(" if not matrix_form: aux_code += "rho, " if variable_Ep: aux_code += "Ep, " if variable_epsilonp: aux_code += "epsilonp, " if aux_code[-2:] == ", ": aux_code = aux_code[:-2] aux_code += ")\n" if matrix_form: if unfolding.normalized: code += " aux = " + aux_code code += " A += aux[0]\n" code += " b += aux[1]\n" else: code += " A = " + aux_code else: code += " rhs = " + aux_code # We call the detuning terms. if True: if not variable_detuning_knob and matrix_form: aux_code = "detuning_terms\n" else: aux_code = "detuning_terms(" if not matrix_form: aux_code += "rho, " if variable_detuning_knob: aux_code += "detuning_knob, " if aux_code[-2:] == ", ": aux_code = aux_code[:-2] aux_code += ")\n" if matrix_form: if unfolding.normalized: code += " aux = " + aux_code code += " A += aux[0]\n" code += " b += aux[1]\n" else: code += " A += " + aux_code else: code += " rhs += " + aux_code # We finish the code. if True: # code = rabi_code + "\n\n" + code if matrix_form: if unfolding.normalized: code += " return A, b\n" else: code += " return A\n" else: code += " return rhs\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() hamiltonian_terms = code if not return_code: exec hamiltonian_terms return hamiltonian_terms
[ "def", "fast_hamiltonian_terms", "(", "Ep", ",", "epsilonp", ",", "detuning_knob", ",", "omega_level", ",", "rm", ",", "xi", ",", "theta", ",", "unfolding", ",", "matrix_form", "=", "False", ",", "file_name", "=", "None", ",", "return_code", "=", "False", ...
r"""Return a fast function that returns the Hamiltonian terms. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import define_laser_variables, polarization_vector >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> omega_level = [0, 1.0e9] >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] >>> detuning_knob = [symbols("delta1", real=True)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Hamiltonian terms. >>> aux = (Ep, epsilonps, detuning_knob, omega_level, rm, xi, theta, ... unfolding, False, None) >>> hamiltonian_terms = fast_hamiltonian_terms(*aux) Apply this to a density matrix. >>> rhos = np.array([[0.6, 3+2j], ... [3-2j, 0.4]]) >>> rhosv = unfolding(rhos) We specify values for the variables >>> detuning_knobs = [100e6] >>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI") >>> Eps *= np.exp(1j*np.pi) >>> Eps = [Eps] >>> print(hamiltonian_terms(rhosv, Eps, detuning_knobs)) [5.5681e+07 2.0000e+08 2.9722e+08]
[ "r", "Return", "a", "fast", "function", "that", "returns", "the", "Hamiltonian", "terms", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L2056-L2259
oscarlazoarjona/fast
fast/bloch.py
fast_steady_state
def fast_steady_state(Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, file_name=None, return_code=False): r"""Return a fast function that returns a steady state. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import (define_laser_variables, ... polarization_vector) >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> omega_level = [0, 1.0e9] >>> gamma21 = 2*np.pi*6e6 >>> gamma = np.array([[0, -gamma21], [gamma21, 0]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] >>> detuning_knob = [symbols("delta1", real=True)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Hamiltonian terms. >>> aux = (Ep, epsilonps, detuning_knob, gamma, ... omega_level, rm, xi, theta) >>> steady_state = fast_steady_state(*aux) We specify values for the variables >>> detuning_knobs = [100e6] >>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI") >>> Eps *= np.exp(1j*np.pi) >>> Eps = [Eps] >>> print(steady_state(Eps, detuning_knobs)) [ 0.018 0.1296 -0.0244] """ # We unpack variables. if True: Ne = len(omega_level) Nl = xi.shape[0] unfolding = Unfolding(Ne, True, True, True) # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True try: detuning_knob = np.array([float(detuning_knob[l]) for l in range(Nl)]) variable_detuning_knob = False except: variable_detuning_knob = True # We obtain code for the three parts. if True: args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, unfolding, True, None, True) bloch_equations = fast_bloch_equations(*args) code = bloch_equations+"\n\n" if ((not variable_Ep) and (not variable_epsilonp) and (not variable_detuning_knob)): # We can call bloch_equations here! code += "bloch_equations = bloch_equations()\n" # We establish the arguments of the output function. if True: code += "def steady_state(" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if variable_detuning_knob: code += "detuning_knob, " code += "bloch_equations=bloch_equations):\n" code += ' r"""A fast calculation of the steady state."""\n' # We call the Bloch equations. if True: code += r""" A, b = bloch_equations""" if ((not variable_Ep) and (not variable_epsilonp) and (not variable_detuning_knob)): code += "\n" else: code += "(" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if variable_detuning_knob: code += "detuning_knob, " if code[-2:] == ", ": code = code[:-2] code += ")\n" code += """ rhox = np.linalg.solve(A, b)\n""" code += """ return rhox\n""" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() steady_state = code if not return_code: exec steady_state return steady_state
python
def fast_steady_state(Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, file_name=None, return_code=False): r"""Return a fast function that returns a steady state. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import (define_laser_variables, ... polarization_vector) >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> omega_level = [0, 1.0e9] >>> gamma21 = 2*np.pi*6e6 >>> gamma = np.array([[0, -gamma21], [gamma21, 0]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] >>> detuning_knob = [symbols("delta1", real=True)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Hamiltonian terms. >>> aux = (Ep, epsilonps, detuning_knob, gamma, ... omega_level, rm, xi, theta) >>> steady_state = fast_steady_state(*aux) We specify values for the variables >>> detuning_knobs = [100e6] >>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI") >>> Eps *= np.exp(1j*np.pi) >>> Eps = [Eps] >>> print(steady_state(Eps, detuning_knobs)) [ 0.018 0.1296 -0.0244] """ # We unpack variables. if True: Ne = len(omega_level) Nl = xi.shape[0] unfolding = Unfolding(Ne, True, True, True) # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True try: detuning_knob = np.array([float(detuning_knob[l]) for l in range(Nl)]) variable_detuning_knob = False except: variable_detuning_knob = True # We obtain code for the three parts. if True: args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, unfolding, True, None, True) bloch_equations = fast_bloch_equations(*args) code = bloch_equations+"\n\n" if ((not variable_Ep) and (not variable_epsilonp) and (not variable_detuning_knob)): # We can call bloch_equations here! code += "bloch_equations = bloch_equations()\n" # We establish the arguments of the output function. if True: code += "def steady_state(" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if variable_detuning_knob: code += "detuning_knob, " code += "bloch_equations=bloch_equations):\n" code += ' r"""A fast calculation of the steady state."""\n' # We call the Bloch equations. if True: code += r""" A, b = bloch_equations""" if ((not variable_Ep) and (not variable_epsilonp) and (not variable_detuning_knob)): code += "\n" else: code += "(" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " if variable_detuning_knob: code += "detuning_knob, " if code[-2:] == ", ": code = code[:-2] code += ")\n" code += """ rhox = np.linalg.solve(A, b)\n""" code += """ return rhox\n""" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() steady_state = code if not return_code: exec steady_state return steady_state
[ "def", "fast_steady_state", "(", "Ep", ",", "epsilonp", ",", "detuning_knob", ",", "gamma", ",", "omega_level", ",", "rm", ",", "xi", ",", "theta", ",", "file_name", "=", "None", ",", "return_code", "=", "False", ")", ":", "# We unpack variables.", "if", "...
r"""Return a fast function that returns a steady state. We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import (define_laser_variables, ... polarization_vector) >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> omega_level = [0, 1.0e9] >>> gamma21 = 2*np.pi*6e6 >>> gamma = np.array([[0, -gamma21], [gamma21, 0]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] >>> detuning_knob = [symbols("delta1", real=True)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Hamiltonian terms. >>> aux = (Ep, epsilonps, detuning_knob, gamma, ... omega_level, rm, xi, theta) >>> steady_state = fast_steady_state(*aux) We specify values for the variables >>> detuning_knobs = [100e6] >>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI") >>> Eps *= np.exp(1j*np.pi) >>> Eps = [Eps] >>> print(steady_state(Eps, detuning_knobs)) [ 0.018 0.1296 -0.0244]
[ "r", "Return", "a", "fast", "function", "that", "returns", "a", "steady", "state", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L2496-L2620
oscarlazoarjona/fast
fast/bloch.py
time_average
def time_average(rho, t): r"""Return a time-averaged density matrix (using trapezium rule). We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import (define_laser_variables, ... polarization_vector) >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> omega_level = [0, 1.0e9] >>> gamma21 = 2*np.pi*6e6 >>> gamma = np.array([[0, -gamma21], [gamma21, 0]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] >>> detuning_knob = [symbols("delta1", real=True)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Hamiltonian terms. >>> aux = (Ep, epsilonps, detuning_knob, gamma, ... omega_level, rm, xi, theta) >>> time_evolution = fast_time_evolution(*aux) We specify values for the variables >>> detuning_knobs = [100e6] >>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI") >>> Eps *= np.exp(1j*np.pi) >>> Eps = [Eps] >>> t = np.linspace(0, 1e-6, 11) >>> rho0 = np.array([[1, 0], [0, 0]]) >>> rho0 = unfolding(rho0) >>> rho = time_evolution(t, rho0, Eps, detuning_knobs) >>> print(time_average(rho, t)) [ 0.0175 0.1244 -0.0222] """ T = t[-1]-t[0] dt = t[1]-t[0] rhoav = np.sum(rho[1:-1], axis=0) + 0.5*(rho[0]+rho[-1]) rhoav = dt/T*rhoav return rhoav
python
def time_average(rho, t): r"""Return a time-averaged density matrix (using trapezium rule). We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import (define_laser_variables, ... polarization_vector) >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> omega_level = [0, 1.0e9] >>> gamma21 = 2*np.pi*6e6 >>> gamma = np.array([[0, -gamma21], [gamma21, 0]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] >>> detuning_knob = [symbols("delta1", real=True)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Hamiltonian terms. >>> aux = (Ep, epsilonps, detuning_knob, gamma, ... omega_level, rm, xi, theta) >>> time_evolution = fast_time_evolution(*aux) We specify values for the variables >>> detuning_knobs = [100e6] >>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI") >>> Eps *= np.exp(1j*np.pi) >>> Eps = [Eps] >>> t = np.linspace(0, 1e-6, 11) >>> rho0 = np.array([[1, 0], [0, 0]]) >>> rho0 = unfolding(rho0) >>> rho = time_evolution(t, rho0, Eps, detuning_knobs) >>> print(time_average(rho, t)) [ 0.0175 0.1244 -0.0222] """ T = t[-1]-t[0] dt = t[1]-t[0] rhoav = np.sum(rho[1:-1], axis=0) + 0.5*(rho[0]+rho[-1]) rhoav = dt/T*rhoav return rhoav
[ "def", "time_average", "(", "rho", ",", "t", ")", ":", "T", "=", "t", "[", "-", "1", "]", "-", "t", "[", "0", "]", "dt", "=", "t", "[", "1", "]", "-", "t", "[", "0", "]", "rhoav", "=", "np", ".", "sum", "(", "rho", "[", "1", ":", "-",...
r"""Return a time-averaged density matrix (using trapezium rule). We test a basic two-level system. >>> import numpy as np >>> from scipy.constants import physical_constants >>> from sympy import Matrix, symbols >>> from fast.electric_field import electric_field_amplitude_top >>> from fast.symbolic import (define_laser_variables, ... polarization_vector) >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = [np.array([[0, 0], [a0, 0]]), ... np.array([[0, 0], [0, 0]]), ... np.array([[0, 0], [0, 0]])] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> omega_level = [0, 1.0e9] >>> gamma21 = 2*np.pi*6e6 >>> gamma = np.array([[0, -gamma21], [gamma21, 0]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) We define symbolic variables to be used as token arguments. >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonps = [polarization_vector(0, 0, 0, 0, 1)] >>> detuning_knob = [symbols("delta1", real=True)] An map to unfold the density matrix. >>> unfolding = Unfolding(Ne, True, True, True) We obtain a function to calculate Hamiltonian terms. >>> aux = (Ep, epsilonps, detuning_knob, gamma, ... omega_level, rm, xi, theta) >>> time_evolution = fast_time_evolution(*aux) We specify values for the variables >>> detuning_knobs = [100e6] >>> Eps = electric_field_amplitude_top(1e-3, 1e-3, 1, "SI") >>> Eps *= np.exp(1j*np.pi) >>> Eps = [Eps] >>> t = np.linspace(0, 1e-6, 11) >>> rho0 = np.array([[1, 0], [0, 0]]) >>> rho0 = unfolding(rho0) >>> rho = time_evolution(t, rho0, Eps, detuning_knobs) >>> print(time_average(rho, t)) [ 0.0175 0.1244 -0.0222]
[ "r", "Return", "a", "time", "-", "averaged", "density", "matrix", "(", "using", "trapezium", "rule", ")", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L2786-L2842
oscarlazoarjona/fast
fast/bloch.py
fast_sweep_steady_state
def fast_sweep_steady_state(Ep, epsilonp, gamma, omega_level, rm, xi, theta, file_name=None, return_code=False): r"""Return an spectrum of density matrices in the steady state. We test a basic two-level system. >>> import numpy as np >>> from sympy import symbols >>> from scipy.constants import physical_constants >>> e_num = physical_constants["elementary charge"][0] >>> hbar_num = physical_constants["Planck constant over 2 pi"][0] >>> Ne = 2 >>> Nl = 1 >>> Ep = [-1.0] >>> epsilonp = [np.array([0, 0, 1.0])] >>> delta = symbols("delta") >>> detuning_knob = [delta] >>> gamma = np.array([[0.0, -1.0], [1.0, 0.0]]) >>> omega_level = np.array([0.0, 100.0]) >>> rm = [np.array([[0.0, 0.0], [1.0, 0.0]])*hbar_num/e_num ... for p in range(3)] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) >>> sweep_steady_state = fast_sweep_steady_state(Ep, epsilonp, gamma, ... omega_level, rm, xi, ... theta) >>> deltas, rho = sweep_steady_state([[-20, 20, 11]]) >>> print(rho) [[ 0.0006 -0.025 -0.0006] [ 0.001 -0.0312 -0.001 ] [ 0.0017 -0.0415 -0.0017] [ 0.0039 -0.0618 -0.0039] [ 0.0149 -0.1194 -0.0149] [ 0.3333 -0. -0.3333] [ 0.0149 0.1194 -0.0149] [ 0.0039 0.0618 -0.0039] [ 0.0017 0.0415 -0.0017] [ 0.001 0.0312 -0.001 ] [ 0.0006 0.025 -0.0006]] """ # We unpack variables. if True: Nl = xi.shape[0] # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True # We obtain code for the steady state. if True: detuning_knob = symbols("delta1:"+str(Nl)) args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, file_name, True) steady_state = fast_steady_state(*args) code = steady_state+"\n\n" # We establish the arguments of the output function. if True: code += "def sweep_steady_state(" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " code += "detuning_knob, " code += "steady_state=steady_state):\n" code += ' r"""A fast frequency sweep of the steady state."""\n' # Code to determine the sweep range. if True: code += """ sweepN = -1\n""" code += """ for i, delta in enumerate(detuning_knob):\n""" code += """ if hasattr(delta, "__getitem__"):\n""" code += """ sweepN = i\n""" code += """ delta0 = delta[0]\n""" code += """ deltaf = delta[1]\n""" code += """ Ndelta = delta[2]\n""" code += """ break\n\n""" code += """ if sweepN == -1:\n""" code += """ s = 'One of the detuning knobs '\n""" code += """ s += 'must be of the form '\n""" code += """ s += '(start, stop, Nsteps)'\n""" code += """ raise ValueError(s)\n\n""" code += """ deltas = np.linspace(delta0, deltaf, Ndelta)\n\n""" # We call steady_state. if True: code += " args = [[" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " code += """list(detuning_knob[:sweepN]) +\n""" code += """ [deltas[i]] +\n""" code += """ list(detuning_knob[sweepN+1:])]\n""" code += """ for i in range(Ndelta)]\n\n""" code += " rho = np.array([steady_state(*argsi)\n" code += " for argsi in args])\n\n" # We finish the code. if True: code += " return deltas, rho\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() sweep_steady_state = code if not return_code: exec sweep_steady_state return sweep_steady_state
python
def fast_sweep_steady_state(Ep, epsilonp, gamma, omega_level, rm, xi, theta, file_name=None, return_code=False): r"""Return an spectrum of density matrices in the steady state. We test a basic two-level system. >>> import numpy as np >>> from sympy import symbols >>> from scipy.constants import physical_constants >>> e_num = physical_constants["elementary charge"][0] >>> hbar_num = physical_constants["Planck constant over 2 pi"][0] >>> Ne = 2 >>> Nl = 1 >>> Ep = [-1.0] >>> epsilonp = [np.array([0, 0, 1.0])] >>> delta = symbols("delta") >>> detuning_knob = [delta] >>> gamma = np.array([[0.0, -1.0], [1.0, 0.0]]) >>> omega_level = np.array([0.0, 100.0]) >>> rm = [np.array([[0.0, 0.0], [1.0, 0.0]])*hbar_num/e_num ... for p in range(3)] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) >>> sweep_steady_state = fast_sweep_steady_state(Ep, epsilonp, gamma, ... omega_level, rm, xi, ... theta) >>> deltas, rho = sweep_steady_state([[-20, 20, 11]]) >>> print(rho) [[ 0.0006 -0.025 -0.0006] [ 0.001 -0.0312 -0.001 ] [ 0.0017 -0.0415 -0.0017] [ 0.0039 -0.0618 -0.0039] [ 0.0149 -0.1194 -0.0149] [ 0.3333 -0. -0.3333] [ 0.0149 0.1194 -0.0149] [ 0.0039 0.0618 -0.0039] [ 0.0017 0.0415 -0.0017] [ 0.001 0.0312 -0.001 ] [ 0.0006 0.025 -0.0006]] """ # We unpack variables. if True: Nl = xi.shape[0] # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True # We obtain code for the steady state. if True: detuning_knob = symbols("delta1:"+str(Nl)) args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, file_name, True) steady_state = fast_steady_state(*args) code = steady_state+"\n\n" # We establish the arguments of the output function. if True: code += "def sweep_steady_state(" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " code += "detuning_knob, " code += "steady_state=steady_state):\n" code += ' r"""A fast frequency sweep of the steady state."""\n' # Code to determine the sweep range. if True: code += """ sweepN = -1\n""" code += """ for i, delta in enumerate(detuning_knob):\n""" code += """ if hasattr(delta, "__getitem__"):\n""" code += """ sweepN = i\n""" code += """ delta0 = delta[0]\n""" code += """ deltaf = delta[1]\n""" code += """ Ndelta = delta[2]\n""" code += """ break\n\n""" code += """ if sweepN == -1:\n""" code += """ s = 'One of the detuning knobs '\n""" code += """ s += 'must be of the form '\n""" code += """ s += '(start, stop, Nsteps)'\n""" code += """ raise ValueError(s)\n\n""" code += """ deltas = np.linspace(delta0, deltaf, Ndelta)\n\n""" # We call steady_state. if True: code += " args = [[" if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " code += """list(detuning_knob[:sweepN]) +\n""" code += """ [deltas[i]] +\n""" code += """ list(detuning_knob[sweepN+1:])]\n""" code += """ for i in range(Ndelta)]\n\n""" code += " rho = np.array([steady_state(*argsi)\n" code += " for argsi in args])\n\n" # We finish the code. if True: code += " return deltas, rho\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() sweep_steady_state = code if not return_code: exec sweep_steady_state return sweep_steady_state
[ "def", "fast_sweep_steady_state", "(", "Ep", ",", "epsilonp", ",", "gamma", ",", "omega_level", ",", "rm", ",", "xi", ",", "theta", ",", "file_name", "=", "None", ",", "return_code", "=", "False", ")", ":", "# We unpack variables.", "if", "True", ":", "Nl"...
r"""Return an spectrum of density matrices in the steady state. We test a basic two-level system. >>> import numpy as np >>> from sympy import symbols >>> from scipy.constants import physical_constants >>> e_num = physical_constants["elementary charge"][0] >>> hbar_num = physical_constants["Planck constant over 2 pi"][0] >>> Ne = 2 >>> Nl = 1 >>> Ep = [-1.0] >>> epsilonp = [np.array([0, 0, 1.0])] >>> delta = symbols("delta") >>> detuning_knob = [delta] >>> gamma = np.array([[0.0, -1.0], [1.0, 0.0]]) >>> omega_level = np.array([0.0, 100.0]) >>> rm = [np.array([[0.0, 0.0], [1.0, 0.0]])*hbar_num/e_num ... for p in range(3)] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) >>> sweep_steady_state = fast_sweep_steady_state(Ep, epsilonp, gamma, ... omega_level, rm, xi, ... theta) >>> deltas, rho = sweep_steady_state([[-20, 20, 11]]) >>> print(rho) [[ 0.0006 -0.025 -0.0006] [ 0.001 -0.0312 -0.001 ] [ 0.0017 -0.0415 -0.0017] [ 0.0039 -0.0618 -0.0039] [ 0.0149 -0.1194 -0.0149] [ 0.3333 -0. -0.3333] [ 0.0149 0.1194 -0.0149] [ 0.0039 0.0618 -0.0039] [ 0.0017 0.0415 -0.0017] [ 0.001 0.0312 -0.001 ] [ 0.0006 0.025 -0.0006]]
[ "r", "Return", "an", "spectrum", "of", "density", "matrices", "in", "the", "steady", "state", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L2845-L2963
oscarlazoarjona/fast
fast/bloch.py
fast_sweep_time_evolution
def fast_sweep_time_evolution(Ep, epsilonp, gamma, omega_level, rm, xi, theta, semi_analytic=True, file_name=None, return_code=False): r"""Return a spectrum of time evolutions of the density matrix. We test a basic two-level system. >>> import numpy as np >>> from sympy import symbols >>> from scipy.constants import physical_constants >>> e_num = physical_constants["elementary charge"][0] >>> hbar_num = physical_constants["Planck constant over 2 pi"][0] >>> Ne = 2 >>> Nl = 1 >>> Ep = [-1.0] >>> epsilonp = [np.array([0, 0, 1.0])] >>> delta = symbols("delta") >>> detuning_knob = [delta] >>> gamma = np.array([[0.0, -1.0], [1.0, 0.0]]) >>> omega_level = np.array([0.0, 100.0]) >>> rm = [np.array([[0.0, 0.0], [1.0, 0.0]])*hbar_num/e_num ... for p in range(3)] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) >>> sweep_time_evolution = fast_sweep_time_evolution(Ep, epsilonp, gamma, ... omega_level, rm, xi, ... theta) >>> t = np.linspace(0, 1e1, 11) >>> unfolding = Unfolding(Ne, True, True, True) >>> rho0 = np.array([[1, 0], [0, 0]]) >>> rho0 = unfolding(rho0) >>> deltas, rho = sweep_time_evolution(t, rho0, [[-20, 20, 5]]) >>> print(rho.shape) (5, 11, 3) >>> print(rho) [[[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.6205e-04 -1.8774e-02 -1.4437e-02] [ 1.0302e-03 -3.1226e-02 -7.3031e-03] [ 9.1218e-04 -3.0149e-02 1.3325e-03] [ 6.3711e-04 -2.5073e-02 2.7437e-03] [ 5.3438e-04 -2.3100e-02 2.2977e-04] [ 5.8098e-04 -2.4044e-02 -1.4626e-03] [ 6.3808e-04 -2.5209e-02 -1.3291e-03] [ 6.4675e-04 -2.5407e-02 -6.4498e-04] [ 6.2948e-04 -2.5071e-02 -3.7457e-04] [ 6.1812e-04 -2.4841e-02 -4.9967e-04]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.8142e-03 -7.4650e-02 1.3859e-02] [ 2.2458e-03 -4.3027e-02 -1.9436e-02] [ 2.2788e-03 -4.6867e-02 8.1709e-03] [ 3.0571e-03 -5.4724e-02 -6.7300e-03] [ 2.0980e-03 -4.5626e-02 -2.2121e-03] [ 2.6866e-03 -5.1685e-02 -1.1906e-03] [ 2.4351e-03 -4.9072e-02 -3.8467e-03] [ 2.4572e-03 -4.9419e-02 -1.6141e-03] [ 2.5241e-03 -5.0036e-02 -2.8327e-03] [ 2.4491e-03 -4.9304e-02 -2.4541e-03]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 1.4361e-01 0.0000e+00 -3.4458e-01] [ 3.0613e-01 0.0000e+00 -4.1373e-01] [ 3.6110e-01 0.0000e+00 -3.7387e-01] [ 3.5427e-01 0.0000e+00 -3.3710e-01] [ 3.3835e-01 0.0000e+00 -3.2630e-01] [ 3.3135e-01 0.0000e+00 -3.2873e-01] [ 3.3115e-01 0.0000e+00 -3.3244e-01] [ 3.3261e-01 0.0000e+00 -3.3388e-01] [ 3.3343e-01 0.0000e+00 -3.3383e-01] [ 3.3355e-01 0.0000e+00 -3.3348e-01]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.8142e-03 7.4650e-02 1.3859e-02] [ 2.2458e-03 4.3027e-02 -1.9436e-02] [ 2.2788e-03 4.6867e-02 8.1709e-03] [ 3.0571e-03 5.4724e-02 -6.7300e-03] [ 2.0980e-03 4.5626e-02 -2.2121e-03] [ 2.6866e-03 5.1685e-02 -1.1906e-03] [ 2.4351e-03 4.9072e-02 -3.8467e-03] [ 2.4572e-03 4.9419e-02 -1.6141e-03] [ 2.5241e-03 5.0036e-02 -2.8327e-03] [ 2.4491e-03 4.9304e-02 -2.4541e-03]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.6205e-04 1.8774e-02 -1.4437e-02] [ 1.0302e-03 3.1226e-02 -7.3031e-03] [ 9.1218e-04 3.0149e-02 1.3325e-03] [ 6.3711e-04 2.5073e-02 2.7437e-03] [ 5.3438e-04 2.3100e-02 2.2977e-04] [ 5.8098e-04 2.4044e-02 -1.4626e-03] [ 6.3808e-04 2.5209e-02 -1.3291e-03] [ 6.4675e-04 2.5407e-02 -6.4498e-04] [ 6.2948e-04 2.5071e-02 -3.7457e-04] [ 6.1812e-04 2.4841e-02 -4.9967e-04]]] >>> deltas, rho = sweep_time_evolution(t, rho0, [[-20, 20, 11]], ... average=True) >>> print(rho) [[ 0.0006 -0.024 -0.0021] [ 0.0011 -0.0308 -0.0007] [ 0.0016 -0.0375 0.0024] [ 0.0041 -0.0604 -0.0061] [ 0.016 -0.1175 -0.0118] [ 0.2999 0. -0.3291] [ 0.016 0.1175 -0.0118] [ 0.0041 0.0604 -0.0061] [ 0.0016 0.0375 0.0024] [ 0.0011 0.0308 -0.0007] [ 0.0006 0.024 -0.0021]] """ # We unpack variables. if True: Nl = xi.shape[0] # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True # We obtain code for the time evolution. if True: detuning_knob = symbols("delta1:"+str(Nl)) args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, file_name, True) args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, True, file_name, True) time_evolution = fast_time_evolution(*args) code = time_evolution+"\n\n" # We establish the arguments of the output function. if True: code += "def sweep_time_evolution(t, rho0, " if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " code += "detuning_knob, average=False, " code += "time_evolution=time_evolution):\n" code += ' r"""A fast frequency sweep of the steady state."""\n' # Code to determine the sweep range. if True: code += """ sweepN = -1\n""" code += """ for i, delta in enumerate(detuning_knob):\n""" code += """ if hasattr(delta, "__getitem__"):\n""" code += """ sweepN = i\n""" code += """ delta0 = delta[0]\n""" code += """ deltaf = delta[1]\n""" code += """ Ndelta = delta[2]\n""" code += """ break\n\n""" code += """ if sweepN == -1:\n""" code += """ s = 'One of the detuning knobs '\n""" code += """ s += 'must be of the form '\n""" code += """ s += '(start, stop, Nsteps)'\n""" code += """ raise ValueError(s)\n\n""" code += """ deltas = np.linspace(delta0, deltaf, Ndelta)\n\n""" # We call time_evolution. if True: code += " args = [[t, rho0, " if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " code += """list(detuning_knob[:sweepN]) +\n""" code += """ [deltas[i]] +\n""" code += """ list(detuning_knob[sweepN+1:]), average]\n""" code += """ for i in range(Ndelta)]\n\n""" code += " rho = np.array([time_evolution(*argsi)\n" code += " for argsi in args])\n\n" # We finish the code. if True: code += " return deltas, rho\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() sweep_time_evolution = code if not return_code: exec sweep_time_evolution return sweep_time_evolution
python
def fast_sweep_time_evolution(Ep, epsilonp, gamma, omega_level, rm, xi, theta, semi_analytic=True, file_name=None, return_code=False): r"""Return a spectrum of time evolutions of the density matrix. We test a basic two-level system. >>> import numpy as np >>> from sympy import symbols >>> from scipy.constants import physical_constants >>> e_num = physical_constants["elementary charge"][0] >>> hbar_num = physical_constants["Planck constant over 2 pi"][0] >>> Ne = 2 >>> Nl = 1 >>> Ep = [-1.0] >>> epsilonp = [np.array([0, 0, 1.0])] >>> delta = symbols("delta") >>> detuning_knob = [delta] >>> gamma = np.array([[0.0, -1.0], [1.0, 0.0]]) >>> omega_level = np.array([0.0, 100.0]) >>> rm = [np.array([[0.0, 0.0], [1.0, 0.0]])*hbar_num/e_num ... for p in range(3)] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) >>> sweep_time_evolution = fast_sweep_time_evolution(Ep, epsilonp, gamma, ... omega_level, rm, xi, ... theta) >>> t = np.linspace(0, 1e1, 11) >>> unfolding = Unfolding(Ne, True, True, True) >>> rho0 = np.array([[1, 0], [0, 0]]) >>> rho0 = unfolding(rho0) >>> deltas, rho = sweep_time_evolution(t, rho0, [[-20, 20, 5]]) >>> print(rho.shape) (5, 11, 3) >>> print(rho) [[[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.6205e-04 -1.8774e-02 -1.4437e-02] [ 1.0302e-03 -3.1226e-02 -7.3031e-03] [ 9.1218e-04 -3.0149e-02 1.3325e-03] [ 6.3711e-04 -2.5073e-02 2.7437e-03] [ 5.3438e-04 -2.3100e-02 2.2977e-04] [ 5.8098e-04 -2.4044e-02 -1.4626e-03] [ 6.3808e-04 -2.5209e-02 -1.3291e-03] [ 6.4675e-04 -2.5407e-02 -6.4498e-04] [ 6.2948e-04 -2.5071e-02 -3.7457e-04] [ 6.1812e-04 -2.4841e-02 -4.9967e-04]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.8142e-03 -7.4650e-02 1.3859e-02] [ 2.2458e-03 -4.3027e-02 -1.9436e-02] [ 2.2788e-03 -4.6867e-02 8.1709e-03] [ 3.0571e-03 -5.4724e-02 -6.7300e-03] [ 2.0980e-03 -4.5626e-02 -2.2121e-03] [ 2.6866e-03 -5.1685e-02 -1.1906e-03] [ 2.4351e-03 -4.9072e-02 -3.8467e-03] [ 2.4572e-03 -4.9419e-02 -1.6141e-03] [ 2.5241e-03 -5.0036e-02 -2.8327e-03] [ 2.4491e-03 -4.9304e-02 -2.4541e-03]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 1.4361e-01 0.0000e+00 -3.4458e-01] [ 3.0613e-01 0.0000e+00 -4.1373e-01] [ 3.6110e-01 0.0000e+00 -3.7387e-01] [ 3.5427e-01 0.0000e+00 -3.3710e-01] [ 3.3835e-01 0.0000e+00 -3.2630e-01] [ 3.3135e-01 0.0000e+00 -3.2873e-01] [ 3.3115e-01 0.0000e+00 -3.3244e-01] [ 3.3261e-01 0.0000e+00 -3.3388e-01] [ 3.3343e-01 0.0000e+00 -3.3383e-01] [ 3.3355e-01 0.0000e+00 -3.3348e-01]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.8142e-03 7.4650e-02 1.3859e-02] [ 2.2458e-03 4.3027e-02 -1.9436e-02] [ 2.2788e-03 4.6867e-02 8.1709e-03] [ 3.0571e-03 5.4724e-02 -6.7300e-03] [ 2.0980e-03 4.5626e-02 -2.2121e-03] [ 2.6866e-03 5.1685e-02 -1.1906e-03] [ 2.4351e-03 4.9072e-02 -3.8467e-03] [ 2.4572e-03 4.9419e-02 -1.6141e-03] [ 2.5241e-03 5.0036e-02 -2.8327e-03] [ 2.4491e-03 4.9304e-02 -2.4541e-03]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.6205e-04 1.8774e-02 -1.4437e-02] [ 1.0302e-03 3.1226e-02 -7.3031e-03] [ 9.1218e-04 3.0149e-02 1.3325e-03] [ 6.3711e-04 2.5073e-02 2.7437e-03] [ 5.3438e-04 2.3100e-02 2.2977e-04] [ 5.8098e-04 2.4044e-02 -1.4626e-03] [ 6.3808e-04 2.5209e-02 -1.3291e-03] [ 6.4675e-04 2.5407e-02 -6.4498e-04] [ 6.2948e-04 2.5071e-02 -3.7457e-04] [ 6.1812e-04 2.4841e-02 -4.9967e-04]]] >>> deltas, rho = sweep_time_evolution(t, rho0, [[-20, 20, 11]], ... average=True) >>> print(rho) [[ 0.0006 -0.024 -0.0021] [ 0.0011 -0.0308 -0.0007] [ 0.0016 -0.0375 0.0024] [ 0.0041 -0.0604 -0.0061] [ 0.016 -0.1175 -0.0118] [ 0.2999 0. -0.3291] [ 0.016 0.1175 -0.0118] [ 0.0041 0.0604 -0.0061] [ 0.0016 0.0375 0.0024] [ 0.0011 0.0308 -0.0007] [ 0.0006 0.024 -0.0021]] """ # We unpack variables. if True: Nl = xi.shape[0] # We determine which arguments are constants. if True: try: Ep = np.array([complex(Ep[l]) for l in range(Nl)]) variable_Ep = False except: variable_Ep = True try: epsilonp = [np.array([complex(epsilonp[l][i]) for i in range(3)]) for l in range(Nl)] variable_epsilonp = False except: variable_epsilonp = True # We obtain code for the time evolution. if True: detuning_knob = symbols("delta1:"+str(Nl)) args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, file_name, True) args = (Ep, epsilonp, detuning_knob, gamma, omega_level, rm, xi, theta, True, file_name, True) time_evolution = fast_time_evolution(*args) code = time_evolution+"\n\n" # We establish the arguments of the output function. if True: code += "def sweep_time_evolution(t, rho0, " if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " code += "detuning_knob, average=False, " code += "time_evolution=time_evolution):\n" code += ' r"""A fast frequency sweep of the steady state."""\n' # Code to determine the sweep range. if True: code += """ sweepN = -1\n""" code += """ for i, delta in enumerate(detuning_knob):\n""" code += """ if hasattr(delta, "__getitem__"):\n""" code += """ sweepN = i\n""" code += """ delta0 = delta[0]\n""" code += """ deltaf = delta[1]\n""" code += """ Ndelta = delta[2]\n""" code += """ break\n\n""" code += """ if sweepN == -1:\n""" code += """ s = 'One of the detuning knobs '\n""" code += """ s += 'must be of the form '\n""" code += """ s += '(start, stop, Nsteps)'\n""" code += """ raise ValueError(s)\n\n""" code += """ deltas = np.linspace(delta0, deltaf, Ndelta)\n\n""" # We call time_evolution. if True: code += " args = [[t, rho0, " if variable_Ep: code += "Ep, " if variable_epsilonp: code += "epsilonp, " code += """list(detuning_knob[:sweepN]) +\n""" code += """ [deltas[i]] +\n""" code += """ list(detuning_knob[sweepN+1:]), average]\n""" code += """ for i in range(Ndelta)]\n\n""" code += " rho = np.array([time_evolution(*argsi)\n" code += " for argsi in args])\n\n" # We finish the code. if True: code += " return deltas, rho\n" # We write the code to file if provided, and execute it. if True: if file_name is not None: f = file(file_name+".py", "w") f.write(code) f.close() sweep_time_evolution = code if not return_code: exec sweep_time_evolution return sweep_time_evolution
[ "def", "fast_sweep_time_evolution", "(", "Ep", ",", "epsilonp", ",", "gamma", ",", "omega_level", ",", "rm", ",", "xi", ",", "theta", ",", "semi_analytic", "=", "True", ",", "file_name", "=", "None", ",", "return_code", "=", "False", ")", ":", "# We unpack...
r"""Return a spectrum of time evolutions of the density matrix. We test a basic two-level system. >>> import numpy as np >>> from sympy import symbols >>> from scipy.constants import physical_constants >>> e_num = physical_constants["elementary charge"][0] >>> hbar_num = physical_constants["Planck constant over 2 pi"][0] >>> Ne = 2 >>> Nl = 1 >>> Ep = [-1.0] >>> epsilonp = [np.array([0, 0, 1.0])] >>> delta = symbols("delta") >>> detuning_knob = [delta] >>> gamma = np.array([[0.0, -1.0], [1.0, 0.0]]) >>> omega_level = np.array([0.0, 100.0]) >>> rm = [np.array([[0.0, 0.0], [1.0, 0.0]])*hbar_num/e_num ... for p in range(3)] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) >>> sweep_time_evolution = fast_sweep_time_evolution(Ep, epsilonp, gamma, ... omega_level, rm, xi, ... theta) >>> t = np.linspace(0, 1e1, 11) >>> unfolding = Unfolding(Ne, True, True, True) >>> rho0 = np.array([[1, 0], [0, 0]]) >>> rho0 = unfolding(rho0) >>> deltas, rho = sweep_time_evolution(t, rho0, [[-20, 20, 5]]) >>> print(rho.shape) (5, 11, 3) >>> print(rho) [[[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.6205e-04 -1.8774e-02 -1.4437e-02] [ 1.0302e-03 -3.1226e-02 -7.3031e-03] [ 9.1218e-04 -3.0149e-02 1.3325e-03] [ 6.3711e-04 -2.5073e-02 2.7437e-03] [ 5.3438e-04 -2.3100e-02 2.2977e-04] [ 5.8098e-04 -2.4044e-02 -1.4626e-03] [ 6.3808e-04 -2.5209e-02 -1.3291e-03] [ 6.4675e-04 -2.5407e-02 -6.4498e-04] [ 6.2948e-04 -2.5071e-02 -3.7457e-04] [ 6.1812e-04 -2.4841e-02 -4.9967e-04]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.8142e-03 -7.4650e-02 1.3859e-02] [ 2.2458e-03 -4.3027e-02 -1.9436e-02] [ 2.2788e-03 -4.6867e-02 8.1709e-03] [ 3.0571e-03 -5.4724e-02 -6.7300e-03] [ 2.0980e-03 -4.5626e-02 -2.2121e-03] [ 2.6866e-03 -5.1685e-02 -1.1906e-03] [ 2.4351e-03 -4.9072e-02 -3.8467e-03] [ 2.4572e-03 -4.9419e-02 -1.6141e-03] [ 2.5241e-03 -5.0036e-02 -2.8327e-03] [ 2.4491e-03 -4.9304e-02 -2.4541e-03]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 1.4361e-01 0.0000e+00 -3.4458e-01] [ 3.0613e-01 0.0000e+00 -4.1373e-01] [ 3.6110e-01 0.0000e+00 -3.7387e-01] [ 3.5427e-01 0.0000e+00 -3.3710e-01] [ 3.3835e-01 0.0000e+00 -3.2630e-01] [ 3.3135e-01 0.0000e+00 -3.2873e-01] [ 3.3115e-01 0.0000e+00 -3.3244e-01] [ 3.3261e-01 0.0000e+00 -3.3388e-01] [ 3.3343e-01 0.0000e+00 -3.3383e-01] [ 3.3355e-01 0.0000e+00 -3.3348e-01]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.8142e-03 7.4650e-02 1.3859e-02] [ 2.2458e-03 4.3027e-02 -1.9436e-02] [ 2.2788e-03 4.6867e-02 8.1709e-03] [ 3.0571e-03 5.4724e-02 -6.7300e-03] [ 2.0980e-03 4.5626e-02 -2.2121e-03] [ 2.6866e-03 5.1685e-02 -1.1906e-03] [ 2.4351e-03 4.9072e-02 -3.8467e-03] [ 2.4572e-03 4.9419e-02 -1.6141e-03] [ 2.5241e-03 5.0036e-02 -2.8327e-03] [ 2.4491e-03 4.9304e-02 -2.4541e-03]] <BLANKLINE> [[ 0.0000e+00 0.0000e+00 0.0000e+00] [ 5.6205e-04 1.8774e-02 -1.4437e-02] [ 1.0302e-03 3.1226e-02 -7.3031e-03] [ 9.1218e-04 3.0149e-02 1.3325e-03] [ 6.3711e-04 2.5073e-02 2.7437e-03] [ 5.3438e-04 2.3100e-02 2.2977e-04] [ 5.8098e-04 2.4044e-02 -1.4626e-03] [ 6.3808e-04 2.5209e-02 -1.3291e-03] [ 6.4675e-04 2.5407e-02 -6.4498e-04] [ 6.2948e-04 2.5071e-02 -3.7457e-04] [ 6.1812e-04 2.4841e-02 -4.9967e-04]]] >>> deltas, rho = sweep_time_evolution(t, rho0, [[-20, 20, 11]], ... average=True) >>> print(rho) [[ 0.0006 -0.024 -0.0021] [ 0.0011 -0.0308 -0.0007] [ 0.0016 -0.0375 0.0024] [ 0.0041 -0.0604 -0.0061] [ 0.016 -0.1175 -0.0118] [ 0.2999 0. -0.3291] [ 0.016 0.1175 -0.0118] [ 0.0041 0.0604 -0.0061] [ 0.0016 0.0375 0.0024] [ 0.0011 0.0308 -0.0007] [ 0.0006 0.024 -0.0021]]
[ "r", "Return", "a", "spectrum", "of", "time", "evolutions", "of", "the", "density", "matrix", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L2966-L3158
oscarlazoarjona/fast
fast/bloch.py
observable
def observable(operator, rho, unfolding, complex=False): r"""Return an observable ammount. INPUT: - ``operator`` - An square matrix representing a hermitian operator \ in thesame basis as the density matrix. - ``rho`` - A density matrix in unfolded format, or a list of such \ density matrices. - ``unfolding`` - A mapping from matrix element indices to unfolded \ indices. >>> Ne = 2 >>> unfolding = Unfolding(Ne, True, True, True) >>> rho = np.array([[0.6, 1+2j], [1-2j, 0.4]]) >>> rho = unfolding(rho) >>> sx = np.array([[0, 1], [1, 0]]) >>> print(observable(sx, rho, unfolding)) 2.0 """ if len(rho.shape) == 2: return np.array([observable(operator, i, unfolding) for i in rho]) Ne = unfolding.Ne Mu = unfolding.Mu obs = 0 if unfolding.normalized: rho11 = 1 - sum([rho[Mu(1, i, i)] for i in range(1, Ne)]) for i in range(Ne): for k in range(Ne): if unfolding.real: if k == 0 and i == 0: obs += operator[i, k]*rho11 else: if k < i: u, v = (i, k) else: u, v = (k, i) obs += operator[i, k]*rho[Mu(1, u, v)] if k != i: if k < i: obs += 1j*operator[i, k]*rho[Mu(-1, u, v)] else: obs += -1j*operator[i, k]*rho[Mu(-1, u, v)] else: if k == 0 and i == 0: obs += operator[i, k]*rho11 else: obs += operator[i, k]*rho[Mu(0, k, i)] if not complex: obs = np.real(obs) return obs
python
def observable(operator, rho, unfolding, complex=False): r"""Return an observable ammount. INPUT: - ``operator`` - An square matrix representing a hermitian operator \ in thesame basis as the density matrix. - ``rho`` - A density matrix in unfolded format, or a list of such \ density matrices. - ``unfolding`` - A mapping from matrix element indices to unfolded \ indices. >>> Ne = 2 >>> unfolding = Unfolding(Ne, True, True, True) >>> rho = np.array([[0.6, 1+2j], [1-2j, 0.4]]) >>> rho = unfolding(rho) >>> sx = np.array([[0, 1], [1, 0]]) >>> print(observable(sx, rho, unfolding)) 2.0 """ if len(rho.shape) == 2: return np.array([observable(operator, i, unfolding) for i in rho]) Ne = unfolding.Ne Mu = unfolding.Mu obs = 0 if unfolding.normalized: rho11 = 1 - sum([rho[Mu(1, i, i)] for i in range(1, Ne)]) for i in range(Ne): for k in range(Ne): if unfolding.real: if k == 0 and i == 0: obs += operator[i, k]*rho11 else: if k < i: u, v = (i, k) else: u, v = (k, i) obs += operator[i, k]*rho[Mu(1, u, v)] if k != i: if k < i: obs += 1j*operator[i, k]*rho[Mu(-1, u, v)] else: obs += -1j*operator[i, k]*rho[Mu(-1, u, v)] else: if k == 0 and i == 0: obs += operator[i, k]*rho11 else: obs += operator[i, k]*rho[Mu(0, k, i)] if not complex: obs = np.real(obs) return obs
[ "def", "observable", "(", "operator", ",", "rho", ",", "unfolding", ",", "complex", "=", "False", ")", ":", "if", "len", "(", "rho", ".", "shape", ")", "==", "2", ":", "return", "np", ".", "array", "(", "[", "observable", "(", "operator", ",", "i",...
r"""Return an observable ammount. INPUT: - ``operator`` - An square matrix representing a hermitian operator \ in thesame basis as the density matrix. - ``rho`` - A density matrix in unfolded format, or a list of such \ density matrices. - ``unfolding`` - A mapping from matrix element indices to unfolded \ indices. >>> Ne = 2 >>> unfolding = Unfolding(Ne, True, True, True) >>> rho = np.array([[0.6, 1+2j], [1-2j, 0.4]]) >>> rho = unfolding(rho) >>> sx = np.array([[0, 1], [1, 0]]) >>> print(observable(sx, rho, unfolding)) 2.0
[ "r", "Return", "an", "observable", "ammount", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L3161-L3217
oscarlazoarjona/fast
fast/bloch.py
electric_succeptibility
def electric_succeptibility(l, Ep, epsilonp, rm, n, rho, unfolding, part=0): r"""Return the electric succeptibility for a given field. INPUT: - ``l`` - The index labeling the probe field. - ``Ep`` - A list of the amplitudes of all pump fields. - ``epsilonp`` - The polarization vector of the probe field. - ``rm`` - The below-diagonal components of the position operator \ in the cartesian basis: - ``n`` - The number density of atoms. - ``rho`` - A density matrix in unfolded format, or a list of such \ density matrices. - ``unfolding`` - A mapping from matrix element indices to unfolded \ indices. >>> import numpy as np >>> from sympy import symbols >>> from scipy.constants import physical_constants >>> from fast import vapour_number_density >>> e_num = physical_constants["elementary charge"][0] >>> hbar_num = physical_constants["Planck constant over 2 pi"][0] >>> Ne = 2 >>> Nl = 1 >>> Ep = [-1.0] >>> epsilonp = np.array([[0, 0, 1.0]]) >>> delta = symbols("delta") >>> detuning_knob = [delta] >>> gamma = np.array([[0.0, -1.0], [1.0, 0.0]]) >>> omega_level = np.array([0.0, 100.0]) >>> rm = [np.array([[0.0, 0.0], [1.0, 0.0]])*hbar_num/e_num ... for p in range(3)] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) >>> sweep_steady_state = fast_sweep_steady_state(Ep, epsilonp, gamma, ... omega_level, rm, xi, ... theta) >>> deltas, rho = sweep_steady_state([[-20, 20, 11]]) >>> n = vapour_number_density(273.15+20, "Rb") >>> unfolding = Unfolding(Ne, True, True, True) >>> chire = electric_succeptibility(0, Ep, epsilonp, rm, n, ... rho, unfolding) >>> print(chire) [ 4.4824e-09-1.1206e-10j 5.5971e-09-1.7491e-10j 7.4459e-09-3.1024e-10j 1.1097e-08-6.9356e-10j 2.1449e-08-2.6811e-09j 0.0000e+00-5.9877e-08j -2.1449e-08-2.6811e-09j -1.1097e-08-6.9356e-10j -7.4459e-09-3.1024e-10j -5.5971e-09-1.7491e-10j -4.4824e-09-1.1206e-10j] """ epsilonm = epsilonp.conjugate() rp = np.array([rm[i].transpose().conjugate() for i in range(3)]) if part == 1: op = cartesian_dot_product(rp, epsilonm[0]) op += cartesian_dot_product(rm, epsilonp[0]) op = -e_num*n/epsilon_0_num/np.abs(Ep[0])*op elif part == -1: op = cartesian_dot_product(rm, epsilonp[0]) op += - cartesian_dot_product(rp, epsilonm[0]) op = -1j*e_num*n/epsilon_0_num/np.abs(Ep[0])*op elif part == 0: chire = electric_succeptibility(l, Ep, epsilonp, rm, n, rho, unfolding, +1) chiim = electric_succeptibility(l, Ep, epsilonp, rm, n, rho, unfolding, -1) return chire + 1j*chiim return np.real(observable(op, rho, unfolding))
python
def electric_succeptibility(l, Ep, epsilonp, rm, n, rho, unfolding, part=0): r"""Return the electric succeptibility for a given field. INPUT: - ``l`` - The index labeling the probe field. - ``Ep`` - A list of the amplitudes of all pump fields. - ``epsilonp`` - The polarization vector of the probe field. - ``rm`` - The below-diagonal components of the position operator \ in the cartesian basis: - ``n`` - The number density of atoms. - ``rho`` - A density matrix in unfolded format, or a list of such \ density matrices. - ``unfolding`` - A mapping from matrix element indices to unfolded \ indices. >>> import numpy as np >>> from sympy import symbols >>> from scipy.constants import physical_constants >>> from fast import vapour_number_density >>> e_num = physical_constants["elementary charge"][0] >>> hbar_num = physical_constants["Planck constant over 2 pi"][0] >>> Ne = 2 >>> Nl = 1 >>> Ep = [-1.0] >>> epsilonp = np.array([[0, 0, 1.0]]) >>> delta = symbols("delta") >>> detuning_knob = [delta] >>> gamma = np.array([[0.0, -1.0], [1.0, 0.0]]) >>> omega_level = np.array([0.0, 100.0]) >>> rm = [np.array([[0.0, 0.0], [1.0, 0.0]])*hbar_num/e_num ... for p in range(3)] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) >>> sweep_steady_state = fast_sweep_steady_state(Ep, epsilonp, gamma, ... omega_level, rm, xi, ... theta) >>> deltas, rho = sweep_steady_state([[-20, 20, 11]]) >>> n = vapour_number_density(273.15+20, "Rb") >>> unfolding = Unfolding(Ne, True, True, True) >>> chire = electric_succeptibility(0, Ep, epsilonp, rm, n, ... rho, unfolding) >>> print(chire) [ 4.4824e-09-1.1206e-10j 5.5971e-09-1.7491e-10j 7.4459e-09-3.1024e-10j 1.1097e-08-6.9356e-10j 2.1449e-08-2.6811e-09j 0.0000e+00-5.9877e-08j -2.1449e-08-2.6811e-09j -1.1097e-08-6.9356e-10j -7.4459e-09-3.1024e-10j -5.5971e-09-1.7491e-10j -4.4824e-09-1.1206e-10j] """ epsilonm = epsilonp.conjugate() rp = np.array([rm[i].transpose().conjugate() for i in range(3)]) if part == 1: op = cartesian_dot_product(rp, epsilonm[0]) op += cartesian_dot_product(rm, epsilonp[0]) op = -e_num*n/epsilon_0_num/np.abs(Ep[0])*op elif part == -1: op = cartesian_dot_product(rm, epsilonp[0]) op += - cartesian_dot_product(rp, epsilonm[0]) op = -1j*e_num*n/epsilon_0_num/np.abs(Ep[0])*op elif part == 0: chire = electric_succeptibility(l, Ep, epsilonp, rm, n, rho, unfolding, +1) chiim = electric_succeptibility(l, Ep, epsilonp, rm, n, rho, unfolding, -1) return chire + 1j*chiim return np.real(observable(op, rho, unfolding))
[ "def", "electric_succeptibility", "(", "l", ",", "Ep", ",", "epsilonp", ",", "rm", ",", "n", ",", "rho", ",", "unfolding", ",", "part", "=", "0", ")", ":", "epsilonm", "=", "epsilonp", ".", "conjugate", "(", ")", "rp", "=", "np", ".", "array", "(",...
r"""Return the electric succeptibility for a given field. INPUT: - ``l`` - The index labeling the probe field. - ``Ep`` - A list of the amplitudes of all pump fields. - ``epsilonp`` - The polarization vector of the probe field. - ``rm`` - The below-diagonal components of the position operator \ in the cartesian basis: - ``n`` - The number density of atoms. - ``rho`` - A density matrix in unfolded format, or a list of such \ density matrices. - ``unfolding`` - A mapping from matrix element indices to unfolded \ indices. >>> import numpy as np >>> from sympy import symbols >>> from scipy.constants import physical_constants >>> from fast import vapour_number_density >>> e_num = physical_constants["elementary charge"][0] >>> hbar_num = physical_constants["Planck constant over 2 pi"][0] >>> Ne = 2 >>> Nl = 1 >>> Ep = [-1.0] >>> epsilonp = np.array([[0, 0, 1.0]]) >>> delta = symbols("delta") >>> detuning_knob = [delta] >>> gamma = np.array([[0.0, -1.0], [1.0, 0.0]]) >>> omega_level = np.array([0.0, 100.0]) >>> rm = [np.array([[0.0, 0.0], [1.0, 0.0]])*hbar_num/e_num ... for p in range(3)] >>> xi = np.array([[[0, 1], [1, 0]]]) >>> theta = phase_transformation(Ne, Nl, rm, xi) >>> sweep_steady_state = fast_sweep_steady_state(Ep, epsilonp, gamma, ... omega_level, rm, xi, ... theta) >>> deltas, rho = sweep_steady_state([[-20, 20, 11]]) >>> n = vapour_number_density(273.15+20, "Rb") >>> unfolding = Unfolding(Ne, True, True, True) >>> chire = electric_succeptibility(0, Ep, epsilonp, rm, n, ... rho, unfolding) >>> print(chire) [ 4.4824e-09-1.1206e-10j 5.5971e-09-1.7491e-10j 7.4459e-09-3.1024e-10j 1.1097e-08-6.9356e-10j 2.1449e-08-2.6811e-09j 0.0000e+00-5.9877e-08j -2.1449e-08-2.6811e-09j -1.1097e-08-6.9356e-10j -7.4459e-09-3.1024e-10j -5.5971e-09-1.7491e-10j -4.4824e-09-1.1206e-10j]
[ "r", "Return", "the", "electric", "succeptibility", "for", "a", "given", "field", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L3220-L3290
oscarlazoarjona/fast
fast/bloch.py
radiated_intensity
def radiated_intensity(rho, i, j, epsilonp, rm, omega_level, xi, N, D, unfolding): r"""Return the radiated intensity in a given direction. >>> from fast import State, Integer, split_hyperfine_to_magnetic >>> g = State("Rb", 87, 5, 1, 3/Integer(2), 0) >>> e = State("Rb", 87, 4, 2, 5/Integer(2), 1) >>> magnetic_states = split_hyperfine_to_magnetic([g, e]) >>> omega0 = magnetic_states[0].omega >>> omega_level = [ei.omega - omega0 for ei in magnetic_states] >>> Ne = len(magnetic_states) >>> N = 4e6 >>> D = 0.1 >>> unfolding = Unfolding(Ne, True, True, True) >>> rho = np.zeros((Ne, Ne)) >>> rho[0, 0] = 0.8 >>> rho[3, 3] = 0.2 >>> rho[3, 0] = 0.3 >>> rho[0, 3] = 0.3 >>> rho = unfolding(rho) >>> ep = np.array([1, 1j, 0])/np.sqrt(2.0) >>> ex = np.array([1, 0, 0]) >>> r0 = 4.75278521538619e-11 >>> rm = np.zeros((3, Ne, Ne), complex) >>> rm[0, 1, 0] = -r0 >>> rm[0, 3, 0] = r0 >>> rm[1, 1, 0] = -1j*r0 >>> rm[1, 3, 0] = -1j*r0 >>> rm[1, 2, 0] = -np.sqrt(2)*r0 >>> xi = np.zeros((1, Ne, Ne)) >>> xi[0, 1, 0] = 1 >>> xi[0, 2, 0] = 1 >>> xi[0, 3, 0] = 1 >>> xi[0, :, :] += xi[0, :, :].transpose() >>> print(radiated_intensity(rho, 1, 0, ex, rm, ... omega_level, xi, N, D, unfolding)) 4.60125990174e-22 """ def inij(i, j, ilist, jlist): if (i in ilist) and (j in jlist): return 1 else: return 0 rm = np.array(rm) Nl = xi.shape[0] Ne = xi.shape[1] aux = define_simplification(omega_level, xi, Nl) u = aux[0] omega_levelu = aux[2] ui = u(i) uj = u(j) omegaij = omega_levelu[ui] - omega_levelu[uj] ilist = [ii for ii in range(Ne) if u(ii) == ui] jlist = [jj for jj in range(Ne) if u(jj) == uj] rp = np.array([rm[ii].conjugate().transpose() for ii in range(3)]) rm = np.array([[[rm[p, ii, jj]*inij(ii, jj, ilist, jlist) for jj in range(Ne)] for ii in range(Ne)] for p in range(3)]) rp = np.array([[[rp[p, ii, jj]*inij(jj, ii, ilist, jlist) for jj in range(Ne)] for ii in range(Ne)] for p in range(3)]) epsilonm = epsilonp.conjugate() Adag = cartesian_dot_product(rm, epsilonp) A = cartesian_dot_product(rp, epsilonm) fact = alpha_num*N*hbar_num*omegaij**3/2/np.pi/c_num**2/D**2 Iop = fact * np.dot(Adag, A) intensity = observable(Iop, rho, unfolding) intensity = float(np.real(intensity)) return intensity
python
def radiated_intensity(rho, i, j, epsilonp, rm, omega_level, xi, N, D, unfolding): r"""Return the radiated intensity in a given direction. >>> from fast import State, Integer, split_hyperfine_to_magnetic >>> g = State("Rb", 87, 5, 1, 3/Integer(2), 0) >>> e = State("Rb", 87, 4, 2, 5/Integer(2), 1) >>> magnetic_states = split_hyperfine_to_magnetic([g, e]) >>> omega0 = magnetic_states[0].omega >>> omega_level = [ei.omega - omega0 for ei in magnetic_states] >>> Ne = len(magnetic_states) >>> N = 4e6 >>> D = 0.1 >>> unfolding = Unfolding(Ne, True, True, True) >>> rho = np.zeros((Ne, Ne)) >>> rho[0, 0] = 0.8 >>> rho[3, 3] = 0.2 >>> rho[3, 0] = 0.3 >>> rho[0, 3] = 0.3 >>> rho = unfolding(rho) >>> ep = np.array([1, 1j, 0])/np.sqrt(2.0) >>> ex = np.array([1, 0, 0]) >>> r0 = 4.75278521538619e-11 >>> rm = np.zeros((3, Ne, Ne), complex) >>> rm[0, 1, 0] = -r0 >>> rm[0, 3, 0] = r0 >>> rm[1, 1, 0] = -1j*r0 >>> rm[1, 3, 0] = -1j*r0 >>> rm[1, 2, 0] = -np.sqrt(2)*r0 >>> xi = np.zeros((1, Ne, Ne)) >>> xi[0, 1, 0] = 1 >>> xi[0, 2, 0] = 1 >>> xi[0, 3, 0] = 1 >>> xi[0, :, :] += xi[0, :, :].transpose() >>> print(radiated_intensity(rho, 1, 0, ex, rm, ... omega_level, xi, N, D, unfolding)) 4.60125990174e-22 """ def inij(i, j, ilist, jlist): if (i in ilist) and (j in jlist): return 1 else: return 0 rm = np.array(rm) Nl = xi.shape[0] Ne = xi.shape[1] aux = define_simplification(omega_level, xi, Nl) u = aux[0] omega_levelu = aux[2] ui = u(i) uj = u(j) omegaij = omega_levelu[ui] - omega_levelu[uj] ilist = [ii for ii in range(Ne) if u(ii) == ui] jlist = [jj for jj in range(Ne) if u(jj) == uj] rp = np.array([rm[ii].conjugate().transpose() for ii in range(3)]) rm = np.array([[[rm[p, ii, jj]*inij(ii, jj, ilist, jlist) for jj in range(Ne)] for ii in range(Ne)] for p in range(3)]) rp = np.array([[[rp[p, ii, jj]*inij(jj, ii, ilist, jlist) for jj in range(Ne)] for ii in range(Ne)] for p in range(3)]) epsilonm = epsilonp.conjugate() Adag = cartesian_dot_product(rm, epsilonp) A = cartesian_dot_product(rp, epsilonm) fact = alpha_num*N*hbar_num*omegaij**3/2/np.pi/c_num**2/D**2 Iop = fact * np.dot(Adag, A) intensity = observable(Iop, rho, unfolding) intensity = float(np.real(intensity)) return intensity
[ "def", "radiated_intensity", "(", "rho", ",", "i", ",", "j", ",", "epsilonp", ",", "rm", ",", "omega_level", ",", "xi", ",", "N", ",", "D", ",", "unfolding", ")", ":", "def", "inij", "(", "i", ",", "j", ",", "ilist", ",", "jlist", ")", ":", "if...
r"""Return the radiated intensity in a given direction. >>> from fast import State, Integer, split_hyperfine_to_magnetic >>> g = State("Rb", 87, 5, 1, 3/Integer(2), 0) >>> e = State("Rb", 87, 4, 2, 5/Integer(2), 1) >>> magnetic_states = split_hyperfine_to_magnetic([g, e]) >>> omega0 = magnetic_states[0].omega >>> omega_level = [ei.omega - omega0 for ei in magnetic_states] >>> Ne = len(magnetic_states) >>> N = 4e6 >>> D = 0.1 >>> unfolding = Unfolding(Ne, True, True, True) >>> rho = np.zeros((Ne, Ne)) >>> rho[0, 0] = 0.8 >>> rho[3, 3] = 0.2 >>> rho[3, 0] = 0.3 >>> rho[0, 3] = 0.3 >>> rho = unfolding(rho) >>> ep = np.array([1, 1j, 0])/np.sqrt(2.0) >>> ex = np.array([1, 0, 0]) >>> r0 = 4.75278521538619e-11 >>> rm = np.zeros((3, Ne, Ne), complex) >>> rm[0, 1, 0] = -r0 >>> rm[0, 3, 0] = r0 >>> rm[1, 1, 0] = -1j*r0 >>> rm[1, 3, 0] = -1j*r0 >>> rm[1, 2, 0] = -np.sqrt(2)*r0 >>> xi = np.zeros((1, Ne, Ne)) >>> xi[0, 1, 0] = 1 >>> xi[0, 2, 0] = 1 >>> xi[0, 3, 0] = 1 >>> xi[0, :, :] += xi[0, :, :].transpose() >>> print(radiated_intensity(rho, 1, 0, ex, rm, ... omega_level, xi, N, D, unfolding)) 4.60125990174e-22
[ "r", "Return", "the", "radiated", "intensity", "in", "a", "given", "direction", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L3293-L3378
oscarlazoarjona/fast
fast/bloch.py
Unfolding.inverse
def inverse(self, rhov, time_derivative=False): r"""Fold a vector into a matrix. The input of this function can be a numpy array or a sympy Matrix. If the input is understood to represent the time derivative of a density matrix, then the flag time_derivative must be set to True. >>> unfolding = Unfolding(2, real=True, lower_triangular=True, ... normalized=True) >>> rhos = np.array([[0.6, 1+2j], [1-2j, 0.4]]) >>> print(rhos == unfolding.inverse(unfolding(rhos))) [[ True True] [ True True]] >>> from fast import define_density_matrix >>> from sympy import pprint >>> rho = define_density_matrix(2) >>> pprint(unfolding.inverse(unfolding(rho)), use_unicode=False) [ -rho22 + 1 re(rho21) - I*im(rho21)] [ ] [re(rho21) + I*im(rho21) rho22 ] >>> rhops = np.array([[0.0, 0.0], ... [0.0, 0.0]]) >>> print(unfolding.inverse(unfolding(rhops), True)) [[-0.-0.j 0.-0.j] [ 0.+0.j 0.+0.j]] """ Ne = self.Ne Nrho = self.Nrho IJ = self.IJ if isinstance(rhov, np.ndarray): rho = np.zeros((Ne, Ne), complex) numeric = True elif isinstance(rhov, sympy.Matrix): rho = sympy.zeros(Ne, Ne) numeric = False for mu in range(Nrho): s, i, j = IJ(mu) if numeric: if s == 1: rho[i, j] += rhov[mu] elif s == -1: rho[i, j] += 1j*rhov[mu] elif s == 0: rho[i, j] += rhov[mu] else: if s == 1: rho[i, j] += rhov[mu] elif s == -1: rho[i, j] += sympy.I*rhov[mu] elif s == 0: rho[i, j] += rhov[mu] if self.lower_triangular: for i in range(Ne): for j in range(i): rho[j, i] = rho[i, j].conjugate() if self.normalized: if time_derivative: rho[0, 0] = -sum([rho[i, i] for i in range(1, Ne)]) else: rho[0, 0] = 1-sum([rho[i, i] for i in range(1, Ne)]) return rho
python
def inverse(self, rhov, time_derivative=False): r"""Fold a vector into a matrix. The input of this function can be a numpy array or a sympy Matrix. If the input is understood to represent the time derivative of a density matrix, then the flag time_derivative must be set to True. >>> unfolding = Unfolding(2, real=True, lower_triangular=True, ... normalized=True) >>> rhos = np.array([[0.6, 1+2j], [1-2j, 0.4]]) >>> print(rhos == unfolding.inverse(unfolding(rhos))) [[ True True] [ True True]] >>> from fast import define_density_matrix >>> from sympy import pprint >>> rho = define_density_matrix(2) >>> pprint(unfolding.inverse(unfolding(rho)), use_unicode=False) [ -rho22 + 1 re(rho21) - I*im(rho21)] [ ] [re(rho21) + I*im(rho21) rho22 ] >>> rhops = np.array([[0.0, 0.0], ... [0.0, 0.0]]) >>> print(unfolding.inverse(unfolding(rhops), True)) [[-0.-0.j 0.-0.j] [ 0.+0.j 0.+0.j]] """ Ne = self.Ne Nrho = self.Nrho IJ = self.IJ if isinstance(rhov, np.ndarray): rho = np.zeros((Ne, Ne), complex) numeric = True elif isinstance(rhov, sympy.Matrix): rho = sympy.zeros(Ne, Ne) numeric = False for mu in range(Nrho): s, i, j = IJ(mu) if numeric: if s == 1: rho[i, j] += rhov[mu] elif s == -1: rho[i, j] += 1j*rhov[mu] elif s == 0: rho[i, j] += rhov[mu] else: if s == 1: rho[i, j] += rhov[mu] elif s == -1: rho[i, j] += sympy.I*rhov[mu] elif s == 0: rho[i, j] += rhov[mu] if self.lower_triangular: for i in range(Ne): for j in range(i): rho[j, i] = rho[i, j].conjugate() if self.normalized: if time_derivative: rho[0, 0] = -sum([rho[i, i] for i in range(1, Ne)]) else: rho[0, 0] = 1-sum([rho[i, i] for i in range(1, Ne)]) return rho
[ "def", "inverse", "(", "self", ",", "rhov", ",", "time_derivative", "=", "False", ")", ":", "Ne", "=", "self", ".", "Ne", "Nrho", "=", "self", ".", "Nrho", "IJ", "=", "self", ".", "IJ", "if", "isinstance", "(", "rhov", ",", "np", ".", "ndarray", ...
r"""Fold a vector into a matrix. The input of this function can be a numpy array or a sympy Matrix. If the input is understood to represent the time derivative of a density matrix, then the flag time_derivative must be set to True. >>> unfolding = Unfolding(2, real=True, lower_triangular=True, ... normalized=True) >>> rhos = np.array([[0.6, 1+2j], [1-2j, 0.4]]) >>> print(rhos == unfolding.inverse(unfolding(rhos))) [[ True True] [ True True]] >>> from fast import define_density_matrix >>> from sympy import pprint >>> rho = define_density_matrix(2) >>> pprint(unfolding.inverse(unfolding(rho)), use_unicode=False) [ -rho22 + 1 re(rho21) - I*im(rho21)] [ ] [re(rho21) + I*im(rho21) rho22 ] >>> rhops = np.array([[0.0, 0.0], ... [0.0, 0.0]]) >>> print(unfolding.inverse(unfolding(rhops), True)) [[-0.-0.j 0.-0.j] [ 0.+0.j 0.+0.j]]
[ "r", "Fold", "a", "vector", "into", "a", "matrix", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/bloch.py#L1280-L1351
tilde-lab/tilde
tilde/berlinium/plotter.py
bdplotter
def bdplotter(task, **kwargs): ''' bdplotter is based on the fact that phonon DOS/bands and electron DOS/bands are the objects of the same kind. 1) DOS is formatted precomputed / smeared according to a normal distribution 2) bands are formatted precomputed / interpolated through natural cubic spline function ''' if task == 'bands': # CRYSTAL, "VASP", EXCITING results = [] if 'precomputed' in kwargs: for n in range(len(kwargs['precomputed']['ticks'])): if kwargs['precomputed']['ticks'][n][1] == 'GAMMA': kwargs['precomputed']['ticks'][n][1] = '&#915;' for stripe in kwargs['precomputed']['stripes']: results.append({'color':'#000000', 'data':[], 'ticks':kwargs['precomputed']['ticks']}) for n, val in enumerate(stripe): results[-1]['data'].append([ kwargs['precomputed']['abscissa'][n], val]) else: if not 'order' in kwargs: order = sorted( kwargs['values'].keys() ) # TODO else: order = kwargs['order'] nullstand = '0 0 0' if not '0 0 0' in kwargs['values']: # possible case when there is shifted Gamma point nullstand = order[0] # reduce k if too much if len(order)>20: red_order = [] for i in range(0, len(order), int(math.floor(len(order)/10))): red_order.append(order[i]) order = red_order for N in range(len( kwargs['values'][nullstand] )): # interpolate for each curve throughout the BZ results.append({'color':'#000000', 'data':[], 'ticks':[]}) d = 0.0 x = [] y = [] bz_vec_ref = [0, 0, 0] for bz in order: y.append( kwargs['values'][bz][N] ) bz_coords = map(frac2float, bz.split() ) bz_vec_cur = dot( bz_coords, linalg.inv( kwargs['xyz_matrix'] ).transpose() ) bz_vec_dir = map(sum, zip(bz_vec_cur, bz_vec_ref)) bz_vec_ref = bz_vec_cur d += linalg.norm( bz_vec_dir ) x.append(d) results[-1]['ticks'].append( [d, bz.replace(' ', '')] ) # end in nullstand point (normally, Gamma) #y.append(kwargs['values'][nullstand][N]) #if d == 0: d+=0.5 #else: d += linalg.norm( bz_vec_ref ) #x.append(d) #results[-1]['ticks'].append( [d, nullstand.replace(' ', '')] ) divider = 10 if len(order)<10 else 1.5 step = (max(x)-min(x)) / len(kwargs['values']) / divider xnew = arange(min(x), max(x)+step/2, step).tolist() ynew = [] f = NaturalCubicSpline( array(x), array(y) ) for i in xnew: results[-1]['data'].append([ round( i, 3 ), round( f(i), 3 ) ]) # round to reduce output return results elif task == 'dos': # CRYSTAL, VASP, EXCITING results = [] if 'precomputed' in kwargs: total_dos = [[i, kwargs['precomputed']['total'][n]] for n, i in enumerate(kwargs['precomputed']['x'])] else: tdos = TotalDos( kwargs['eigenvalues'], sigma=kwargs['sigma'] ) tdos.set_draw_area(omega_min=kwargs['omega_min'], omega_max=kwargs['omega_max'], omega_pitch=kwargs['omega_pitch']) total_dos = tdos.calculate() results.append({'label':'total', 'color': '#000000', 'data': total_dos}) if 'precomputed' in kwargs: partial_doses = [] for k in kwargs['precomputed'].keys(): if k in ['x', 'total']: continue partial_doses.append({ 'label': k, 'data': [[i, kwargs['precomputed'][k][n]] for n, i in enumerate(kwargs['precomputed']['x'])] }) elif 'impacts' in kwargs and 'atomtypes' in kwargs: # get the order of atoms to evaluate their partial impact labels = {} types = [] index, subtractor = 0, 0 for k, atom in enumerate(kwargs['atomtypes']): # determine the order of atoms for the partial impact of every type if atom not in labels: #if atom == 'X' and not calc.phonons: # artificial GHOST case for phonons, decrease atomic index # subtractor += 1 # continue labels[atom] = index types.append([k+1-subtractor]) index += 1 else: types[ labels[atom] ].append(k+1-subtractor) pdos = PartialDos( kwargs['eigenvalues'], kwargs['impacts'], sigma=kwargs['sigma'] ) pdos.set_draw_area(omega_min=kwargs['omega_min'], omega_max=kwargs['omega_max'], omega_pitch=kwargs['omega_pitch']) partial_doses = pdos.calculate( types, labels ) # add colors to partials for i in range(len(partial_doses)): if partial_doses[i]['label'] == 'X': color = '#000000' elif partial_doses[i]['label'] == 'H': color = '#CCCCCC' else: try: color = jmol_to_hex( jmol_colors[ chemical_symbols.index(partial_doses[i]['label']) ] ) except ValueError: color = '#FFCC66' partial_doses[i].update({'color': color}) results.extend(partial_doses) return results
python
def bdplotter(task, **kwargs): ''' bdplotter is based on the fact that phonon DOS/bands and electron DOS/bands are the objects of the same kind. 1) DOS is formatted precomputed / smeared according to a normal distribution 2) bands are formatted precomputed / interpolated through natural cubic spline function ''' if task == 'bands': # CRYSTAL, "VASP", EXCITING results = [] if 'precomputed' in kwargs: for n in range(len(kwargs['precomputed']['ticks'])): if kwargs['precomputed']['ticks'][n][1] == 'GAMMA': kwargs['precomputed']['ticks'][n][1] = '&#915;' for stripe in kwargs['precomputed']['stripes']: results.append({'color':'#000000', 'data':[], 'ticks':kwargs['precomputed']['ticks']}) for n, val in enumerate(stripe): results[-1]['data'].append([ kwargs['precomputed']['abscissa'][n], val]) else: if not 'order' in kwargs: order = sorted( kwargs['values'].keys() ) # TODO else: order = kwargs['order'] nullstand = '0 0 0' if not '0 0 0' in kwargs['values']: # possible case when there is shifted Gamma point nullstand = order[0] # reduce k if too much if len(order)>20: red_order = [] for i in range(0, len(order), int(math.floor(len(order)/10))): red_order.append(order[i]) order = red_order for N in range(len( kwargs['values'][nullstand] )): # interpolate for each curve throughout the BZ results.append({'color':'#000000', 'data':[], 'ticks':[]}) d = 0.0 x = [] y = [] bz_vec_ref = [0, 0, 0] for bz in order: y.append( kwargs['values'][bz][N] ) bz_coords = map(frac2float, bz.split() ) bz_vec_cur = dot( bz_coords, linalg.inv( kwargs['xyz_matrix'] ).transpose() ) bz_vec_dir = map(sum, zip(bz_vec_cur, bz_vec_ref)) bz_vec_ref = bz_vec_cur d += linalg.norm( bz_vec_dir ) x.append(d) results[-1]['ticks'].append( [d, bz.replace(' ', '')] ) # end in nullstand point (normally, Gamma) #y.append(kwargs['values'][nullstand][N]) #if d == 0: d+=0.5 #else: d += linalg.norm( bz_vec_ref ) #x.append(d) #results[-1]['ticks'].append( [d, nullstand.replace(' ', '')] ) divider = 10 if len(order)<10 else 1.5 step = (max(x)-min(x)) / len(kwargs['values']) / divider xnew = arange(min(x), max(x)+step/2, step).tolist() ynew = [] f = NaturalCubicSpline( array(x), array(y) ) for i in xnew: results[-1]['data'].append([ round( i, 3 ), round( f(i), 3 ) ]) # round to reduce output return results elif task == 'dos': # CRYSTAL, VASP, EXCITING results = [] if 'precomputed' in kwargs: total_dos = [[i, kwargs['precomputed']['total'][n]] for n, i in enumerate(kwargs['precomputed']['x'])] else: tdos = TotalDos( kwargs['eigenvalues'], sigma=kwargs['sigma'] ) tdos.set_draw_area(omega_min=kwargs['omega_min'], omega_max=kwargs['omega_max'], omega_pitch=kwargs['omega_pitch']) total_dos = tdos.calculate() results.append({'label':'total', 'color': '#000000', 'data': total_dos}) if 'precomputed' in kwargs: partial_doses = [] for k in kwargs['precomputed'].keys(): if k in ['x', 'total']: continue partial_doses.append({ 'label': k, 'data': [[i, kwargs['precomputed'][k][n]] for n, i in enumerate(kwargs['precomputed']['x'])] }) elif 'impacts' in kwargs and 'atomtypes' in kwargs: # get the order of atoms to evaluate their partial impact labels = {} types = [] index, subtractor = 0, 0 for k, atom in enumerate(kwargs['atomtypes']): # determine the order of atoms for the partial impact of every type if atom not in labels: #if atom == 'X' and not calc.phonons: # artificial GHOST case for phonons, decrease atomic index # subtractor += 1 # continue labels[atom] = index types.append([k+1-subtractor]) index += 1 else: types[ labels[atom] ].append(k+1-subtractor) pdos = PartialDos( kwargs['eigenvalues'], kwargs['impacts'], sigma=kwargs['sigma'] ) pdos.set_draw_area(omega_min=kwargs['omega_min'], omega_max=kwargs['omega_max'], omega_pitch=kwargs['omega_pitch']) partial_doses = pdos.calculate( types, labels ) # add colors to partials for i in range(len(partial_doses)): if partial_doses[i]['label'] == 'X': color = '#000000' elif partial_doses[i]['label'] == 'H': color = '#CCCCCC' else: try: color = jmol_to_hex( jmol_colors[ chemical_symbols.index(partial_doses[i]['label']) ] ) except ValueError: color = '#FFCC66' partial_doses[i].update({'color': color}) results.extend(partial_doses) return results
[ "def", "bdplotter", "(", "task", ",", "*", "*", "kwargs", ")", ":", "if", "task", "==", "'bands'", ":", "# CRYSTAL, \"VASP\", EXCITING", "results", "=", "[", "]", "if", "'precomputed'", "in", "kwargs", ":", "for", "n", "in", "range", "(", "len", "(", "...
bdplotter is based on the fact that phonon DOS/bands and electron DOS/bands are the objects of the same kind. 1) DOS is formatted precomputed / smeared according to a normal distribution 2) bands are formatted precomputed / interpolated through natural cubic spline function
[ "bdplotter", "is", "based", "on", "the", "fact", "that", "phonon", "DOS", "/", "bands", "and", "electron", "DOS", "/", "bands", "are", "the", "objects", "of", "the", "same", "kind", ".", "1", ")", "DOS", "is", "formatted", "precomputed", "/", "smeared", ...
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/plotter.py#L27-L148
tilde-lab/tilde
tilde/berlinium/plotter.py
eplotter
def eplotter(task, data): # CRYSTAL, VASP, EXCITING ''' eplotter is like bdplotter but less complicated ''' results, color, fdata = [], None, [] if task == 'optstory': color = '#CC0000' clickable = True for n, i in enumerate(data): fdata.append([n, i[4]]) fdata = array(fdata) fdata[:,1] -= min(fdata[:,1]) # this normalizes values to minimum (by 2nd col) fdata = fdata.tolist() elif task == 'convergence': color = '#0066CC' clickable = False for n, i in enumerate(data): fdata.append([n, i]) for n in range(len(fdata)): #fdata[n][1] = "%10.5f" % fdata[n][1] fdata[n][1] = round(fdata[n][1], 5) results.append({'color': color, 'clickable:': clickable, 'data': fdata}) return results
python
def eplotter(task, data): # CRYSTAL, VASP, EXCITING ''' eplotter is like bdplotter but less complicated ''' results, color, fdata = [], None, [] if task == 'optstory': color = '#CC0000' clickable = True for n, i in enumerate(data): fdata.append([n, i[4]]) fdata = array(fdata) fdata[:,1] -= min(fdata[:,1]) # this normalizes values to minimum (by 2nd col) fdata = fdata.tolist() elif task == 'convergence': color = '#0066CC' clickable = False for n, i in enumerate(data): fdata.append([n, i]) for n in range(len(fdata)): #fdata[n][1] = "%10.5f" % fdata[n][1] fdata[n][1] = round(fdata[n][1], 5) results.append({'color': color, 'clickable:': clickable, 'data': fdata}) return results
[ "def", "eplotter", "(", "task", ",", "data", ")", ":", "# CRYSTAL, VASP, EXCITING", "results", ",", "color", ",", "fdata", "=", "[", "]", ",", "None", ",", "[", "]", "if", "task", "==", "'optstory'", ":", "color", "=", "'#CC0000'", "clickable", "=", "T...
eplotter is like bdplotter but less complicated
[ "eplotter", "is", "like", "bdplotter", "but", "less", "complicated" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/berlinium/plotter.py#L151-L177
oscarlazoarjona/fast
fast/magnetic_field.py
lande_g_factors
def lande_g_factors(element, isotope, L=None, J=None, F=None): r"""Return the Lande g-factors for a given atom or level. >>> element = "Rb" >>> isotope = 87 >>> print(lande_g_factors(element, isotope)) [ 9.9999e-01 2.0023e+00 -9.9514e-04] The spin-orbit g-factor for a certain J >>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2))) [0.9999936864200584 2.0023193043622 -0.0009951414 2.00231930436220] The nuclear-coupled g-factor for a certain F >>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2), F=1)) [0.9999936864200584 2.0023193043622 -0.0009951414 2.00231930436220 -0.501823752840550] """ atom = Atom(element, isotope) gL = atom.gL gS = atom.gS gI = atom.gI res = [gL, gS, gI] if J is not None: if L is None: raise ValueError("A value of L must be specified.") S = 1/Integer(2) gJ = gL*(J*(J+1)-S*(S+1)+L*(L+1))/(2*J*(J+1)) gJ += gS*(J*(J+1)+S*(S+1)-L*(L+1))/(2*J*(J+1)) res += [gJ] if F is not None: II = atom.nuclear_spin if F == 0: gF = gJ else: gF = gJ*(F*(F+1)-II*(II+1)+J*(J+1))/(2*F*(F+1)) gF += gI*(F*(F+1)+II*(II+1)-J*(J+1))/(2*F*(F+1)) res += [gF] return array(res)
python
def lande_g_factors(element, isotope, L=None, J=None, F=None): r"""Return the Lande g-factors for a given atom or level. >>> element = "Rb" >>> isotope = 87 >>> print(lande_g_factors(element, isotope)) [ 9.9999e-01 2.0023e+00 -9.9514e-04] The spin-orbit g-factor for a certain J >>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2))) [0.9999936864200584 2.0023193043622 -0.0009951414 2.00231930436220] The nuclear-coupled g-factor for a certain F >>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2), F=1)) [0.9999936864200584 2.0023193043622 -0.0009951414 2.00231930436220 -0.501823752840550] """ atom = Atom(element, isotope) gL = atom.gL gS = atom.gS gI = atom.gI res = [gL, gS, gI] if J is not None: if L is None: raise ValueError("A value of L must be specified.") S = 1/Integer(2) gJ = gL*(J*(J+1)-S*(S+1)+L*(L+1))/(2*J*(J+1)) gJ += gS*(J*(J+1)+S*(S+1)-L*(L+1))/(2*J*(J+1)) res += [gJ] if F is not None: II = atom.nuclear_spin if F == 0: gF = gJ else: gF = gJ*(F*(F+1)-II*(II+1)+J*(J+1))/(2*F*(F+1)) gF += gI*(F*(F+1)+II*(II+1)-J*(J+1))/(2*F*(F+1)) res += [gF] return array(res)
[ "def", "lande_g_factors", "(", "element", ",", "isotope", ",", "L", "=", "None", ",", "J", "=", "None", ",", "F", "=", "None", ")", ":", "atom", "=", "Atom", "(", "element", ",", "isotope", ")", "gL", "=", "atom", ".", "gL", "gS", "=", "atom", ...
r"""Return the Lande g-factors for a given atom or level. >>> element = "Rb" >>> isotope = 87 >>> print(lande_g_factors(element, isotope)) [ 9.9999e-01 2.0023e+00 -9.9514e-04] The spin-orbit g-factor for a certain J >>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2))) [0.9999936864200584 2.0023193043622 -0.0009951414 2.00231930436220] The nuclear-coupled g-factor for a certain F >>> print(lande_g_factors(element, isotope, L=0, J=1/Integer(2), F=1)) [0.9999936864200584 2.0023193043622 -0.0009951414 2.00231930436220 -0.501823752840550]
[ "r", "Return", "the", "Lande", "g", "-", "factors", "for", "a", "given", "atom", "or", "level", ".", ">>>", "element", "=", "Rb", ">>>", "isotope", "=", "87", ">>>", "print", "(", "lande_g_factors", "(", "element", "isotope", "))", "[", "9", ".", "99...
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/magnetic_field.py#L37-L77
oscarlazoarjona/fast
fast/magnetic_field.py
zeeman_energies
def zeeman_energies(fine_state, Bz): r"""Return Zeeman effect energies for a given fine state and\ magnetic field. >>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2)) >>> Bz = 200.0 >>> Bz = Bz/10000 >>> for f_group in zeeman_energies(ground_state, Bz): ... print(f_group) [-2.73736448508248e-24 -2.83044285506388e-24 -2.92352122504527e-24] [1.51284728917866e-24 1.60555650110849e-24 1.69826571303833e-24 1.79097492496816e-24 1.88368413689800e-24] """ element = fine_state.element isotope = fine_state.isotope N = fine_state.n L = fine_state.l J = fine_state.j energiesZeeman = [] for i, F in enumerate(fine_state.fperm): gL, gS, gI, gJ, gF = lande_g_factors(element, isotope, L, J, F) energiesF = [] hyperfine_level = State(element, isotope, N, L, J, F) for MF in range(-F, F+1): unperturbed_energy = hbar*hyperfine_level.omega energyMF = unperturbed_energy + muB*gF*MF*Bz energiesF += [energyMF] energiesZeeman += [array(energiesF)] return energiesZeeman
python
def zeeman_energies(fine_state, Bz): r"""Return Zeeman effect energies for a given fine state and\ magnetic field. >>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2)) >>> Bz = 200.0 >>> Bz = Bz/10000 >>> for f_group in zeeman_energies(ground_state, Bz): ... print(f_group) [-2.73736448508248e-24 -2.83044285506388e-24 -2.92352122504527e-24] [1.51284728917866e-24 1.60555650110849e-24 1.69826571303833e-24 1.79097492496816e-24 1.88368413689800e-24] """ element = fine_state.element isotope = fine_state.isotope N = fine_state.n L = fine_state.l J = fine_state.j energiesZeeman = [] for i, F in enumerate(fine_state.fperm): gL, gS, gI, gJ, gF = lande_g_factors(element, isotope, L, J, F) energiesF = [] hyperfine_level = State(element, isotope, N, L, J, F) for MF in range(-F, F+1): unperturbed_energy = hbar*hyperfine_level.omega energyMF = unperturbed_energy + muB*gF*MF*Bz energiesF += [energyMF] energiesZeeman += [array(energiesF)] return energiesZeeman
[ "def", "zeeman_energies", "(", "fine_state", ",", "Bz", ")", ":", "element", "=", "fine_state", ".", "element", "isotope", "=", "fine_state", ".", "isotope", "N", "=", "fine_state", ".", "n", "L", "=", "fine_state", ".", "l", "J", "=", "fine_state", ".",...
r"""Return Zeeman effect energies for a given fine state and\ magnetic field. >>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2)) >>> Bz = 200.0 >>> Bz = Bz/10000 >>> for f_group in zeeman_energies(ground_state, Bz): ... print(f_group) [-2.73736448508248e-24 -2.83044285506388e-24 -2.92352122504527e-24] [1.51284728917866e-24 1.60555650110849e-24 1.69826571303833e-24 1.79097492496816e-24 1.88368413689800e-24]
[ "r", "Return", "Zeeman", "effect", "energies", "for", "a", "given", "fine", "state", "and", "\\", "magnetic", "field", ".", ">>>", "ground_state", "=", "State", "(", "Rb", "87", "5", "0", "1", "/", "Integer", "(", "2", "))", ">>>", "Bz", "=", "200", ...
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/magnetic_field.py#L80-L111
oscarlazoarjona/fast
fast/magnetic_field.py
paschen_back_energies
def paschen_back_energies(fine_state, Bz): r"""Return Paschen-Back regime energies for a given fine state and\ magnetic field. >>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2)) >>> Bz = 200.0 >>> Bz = Bz/10000 >>> for f_group in paschen_back_energies(ground_state, Bz): ... print(f_group) [1.51284728917866e-24 3.80485568127324e-25 -7.51876152924007e-25 -1.88423787397534e-24] [-1.51229355210131e-24 -3.80300989101543e-25 7.51691573898227e-25 1.88368413689800e-24] """ element = fine_state.element isotope = fine_state.isotope N = fine_state.n L = fine_state.l J = fine_state.j II = Atom(element, isotope).nuclear_spin MJ = [-J+i for i in range(2*J+1)] MI = [-II+i for i in range(2*II+1)] Ahfs = fine_state.Ahfs Bhfs = fine_state.Bhfs gL, gS, gI, gJ = lande_g_factors(element, isotope, L, J) energiesPBack = [] for mj in MJ: energiesMJ = [] unperturbed_energy = hbar*State(element, isotope, N, L, J).omega for mi in MI: energyMI = unperturbed_energy energyMI += 2*pi*hbar*Ahfs*mi*mj if J != 1/Integer(2) and II != 1/Integer(2): num = 9*(mi*mj)**2 - 3*J*(J+1)*mi**2 num += -3*II*(II+1)*mj**2 + II*(II+1)*J*(J+1) den = 4*J*(2*J-1)*II*(2*II-1) energyMI += 2*pi*hbar*Bhfs*num/den energyMI += muB*(gJ*mj+gI*mi)*Bz energiesMJ += [energyMI] energiesPBack += [energiesMJ] return array(energiesPBack)
python
def paschen_back_energies(fine_state, Bz): r"""Return Paschen-Back regime energies for a given fine state and\ magnetic field. >>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2)) >>> Bz = 200.0 >>> Bz = Bz/10000 >>> for f_group in paschen_back_energies(ground_state, Bz): ... print(f_group) [1.51284728917866e-24 3.80485568127324e-25 -7.51876152924007e-25 -1.88423787397534e-24] [-1.51229355210131e-24 -3.80300989101543e-25 7.51691573898227e-25 1.88368413689800e-24] """ element = fine_state.element isotope = fine_state.isotope N = fine_state.n L = fine_state.l J = fine_state.j II = Atom(element, isotope).nuclear_spin MJ = [-J+i for i in range(2*J+1)] MI = [-II+i for i in range(2*II+1)] Ahfs = fine_state.Ahfs Bhfs = fine_state.Bhfs gL, gS, gI, gJ = lande_g_factors(element, isotope, L, J) energiesPBack = [] for mj in MJ: energiesMJ = [] unperturbed_energy = hbar*State(element, isotope, N, L, J).omega for mi in MI: energyMI = unperturbed_energy energyMI += 2*pi*hbar*Ahfs*mi*mj if J != 1/Integer(2) and II != 1/Integer(2): num = 9*(mi*mj)**2 - 3*J*(J+1)*mi**2 num += -3*II*(II+1)*mj**2 + II*(II+1)*J*(J+1) den = 4*J*(2*J-1)*II*(2*II-1) energyMI += 2*pi*hbar*Bhfs*num/den energyMI += muB*(gJ*mj+gI*mi)*Bz energiesMJ += [energyMI] energiesPBack += [energiesMJ] return array(energiesPBack)
[ "def", "paschen_back_energies", "(", "fine_state", ",", "Bz", ")", ":", "element", "=", "fine_state", ".", "element", "isotope", "=", "fine_state", ".", "isotope", "N", "=", "fine_state", ".", "n", "L", "=", "fine_state", ".", "l", "J", "=", "fine_state", ...
r"""Return Paschen-Back regime energies for a given fine state and\ magnetic field. >>> ground_state = State("Rb", 87, 5, 0, 1/Integer(2)) >>> Bz = 200.0 >>> Bz = Bz/10000 >>> for f_group in paschen_back_energies(ground_state, Bz): ... print(f_group) [1.51284728917866e-24 3.80485568127324e-25 -7.51876152924007e-25 -1.88423787397534e-24] [-1.51229355210131e-24 -3.80300989101543e-25 7.51691573898227e-25 1.88368413689800e-24]
[ "r", "Return", "Paschen", "-", "Back", "regime", "energies", "for", "a", "given", "fine", "state", "and", "\\", "magnetic", "field", ".", ">>>", "ground_state", "=", "State", "(", "Rb", "87", "5", "0", "1", "/", "Integer", "(", "2", "))", ">>>", "Bz"...
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/magnetic_field.py#L114-L160
tilde-lab/tilde
tilde/core/api.py
API.assign_parser
def assign_parser(self, name): ''' Restricts parsing **name** is a name of the parser class NB: this is the PUBLIC method @procedure ''' for n, p in list(self.Parsers.items()): if n != name: del self.Parsers[n] if len(self.Parsers) != 1: raise RuntimeError('Parser cannot be assigned!')
python
def assign_parser(self, name): ''' Restricts parsing **name** is a name of the parser class NB: this is the PUBLIC method @procedure ''' for n, p in list(self.Parsers.items()): if n != name: del self.Parsers[n] if len(self.Parsers) != 1: raise RuntimeError('Parser cannot be assigned!')
[ "def", "assign_parser", "(", "self", ",", "name", ")", ":", "for", "n", ",", "p", "in", "list", "(", "self", ".", "Parsers", ".", "items", "(", ")", ")", ":", "if", "n", "!=", "name", ":", "del", "self", ".", "Parsers", "[", "n", "]", "if", "...
Restricts parsing **name** is a name of the parser class NB: this is the PUBLIC method @procedure
[ "Restricts", "parsing", "**", "name", "**", "is", "a", "name", "of", "the", "parser", "class", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L158-L169
tilde-lab/tilde
tilde/core/api.py
API.formula
def formula(self, atom_sequence): ''' Constructs standardized chemical formula NB: this is the PUBLIC method @returns formula_str ''' labels = {} types = [] y = 0 for k, atomi in enumerate(atom_sequence): lbl = re.sub("[0-9]+", "", atomi).capitalize() if lbl not in labels: labels[lbl] = y types.append([k+1]) y += 1 else: types[ labels[lbl] ].append(k+1) atoms = list(labels.keys()) atoms = [x for x in self.formula_sequence if x in atoms] + [x for x in atoms if x not in self.formula_sequence] # accordingly formula = '' for atom in atoms: n = len(types[labels[atom]]) if n==1: n = '' else: n = str(n) formula += atom + n return formula
python
def formula(self, atom_sequence): ''' Constructs standardized chemical formula NB: this is the PUBLIC method @returns formula_str ''' labels = {} types = [] y = 0 for k, atomi in enumerate(atom_sequence): lbl = re.sub("[0-9]+", "", atomi).capitalize() if lbl not in labels: labels[lbl] = y types.append([k+1]) y += 1 else: types[ labels[lbl] ].append(k+1) atoms = list(labels.keys()) atoms = [x for x in self.formula_sequence if x in atoms] + [x for x in atoms if x not in self.formula_sequence] # accordingly formula = '' for atom in atoms: n = len(types[labels[atom]]) if n==1: n = '' else: n = str(n) formula += atom + n return formula
[ "def", "formula", "(", "self", ",", "atom_sequence", ")", ":", "labels", "=", "{", "}", "types", "=", "[", "]", "y", "=", "0", "for", "k", ",", "atomi", "in", "enumerate", "(", "atom_sequence", ")", ":", "lbl", "=", "re", ".", "sub", "(", "\"[0-9...
Constructs standardized chemical formula NB: this is the PUBLIC method @returns formula_str
[ "Constructs", "standardized", "chemical", "formula", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L171-L196
tilde-lab/tilde
tilde/core/api.py
API.savvyize
def savvyize(self, input_string, recursive=False, stemma=False): ''' Determines which files should be processed NB: this is the PUBLIC method @returns filenames_list ''' input_string = os.path.abspath(input_string) tasks = [] restricted = [ symbol for symbol in self.settings['skip_if_path'] ] if self.settings['skip_if_path'] else [] # given folder if os.path.isdir(input_string): if recursive: for root, dirs, files in os.walk(input_string): # beware of broken links on unix! (NB find ~ -type l -exec rm -f {} \;) # skip_if_path directive to_filter = [] for dir in dirs: dir = u(dir) for rs in restricted: if dir.startswith(rs) or dir.endswith(rs): to_filter.append(dir) break dirs[:] = [x for x in dirs if x not in to_filter] for filename in files: # skip_if_path directive filename = u(filename) if restricted: for rs in restricted: if filename.startswith(rs) or filename.endswith(rs): break else: tasks.append(root + os.sep + filename) else: tasks.append(root + os.sep + filename) else: for filename in os.listdir(input_string): filename = u(filename) if os.path.isfile(input_string + os.sep + filename): # skip_if_path directive if restricted: for rs in restricted: if filename.startswith(rs) or filename.endswith(rs): break else: tasks.append(input_string + os.sep + filename) else: tasks.append(input_string + os.sep + filename) # given full filename elif os.path.isfile(input_string): tasks.append(input_string) # skip_if_path directive is not applicable here # given filename stemma else: if stemma: parent = os.path.dirname(input_string) for filename in os.listdir(parent): filename = u(filename) if input_string in parent + os.sep + filename and not os.path.isdir(parent + os.sep + filename): # skip_if_path directive if restricted: for rs in restricted: if filename.startswith(rs) or filename.endswith(rs): break else: tasks.append(parent + os.sep + filename) else: tasks.append(parent + os.sep + filename) return tasks
python
def savvyize(self, input_string, recursive=False, stemma=False): ''' Determines which files should be processed NB: this is the PUBLIC method @returns filenames_list ''' input_string = os.path.abspath(input_string) tasks = [] restricted = [ symbol for symbol in self.settings['skip_if_path'] ] if self.settings['skip_if_path'] else [] # given folder if os.path.isdir(input_string): if recursive: for root, dirs, files in os.walk(input_string): # beware of broken links on unix! (NB find ~ -type l -exec rm -f {} \;) # skip_if_path directive to_filter = [] for dir in dirs: dir = u(dir) for rs in restricted: if dir.startswith(rs) or dir.endswith(rs): to_filter.append(dir) break dirs[:] = [x for x in dirs if x not in to_filter] for filename in files: # skip_if_path directive filename = u(filename) if restricted: for rs in restricted: if filename.startswith(rs) or filename.endswith(rs): break else: tasks.append(root + os.sep + filename) else: tasks.append(root + os.sep + filename) else: for filename in os.listdir(input_string): filename = u(filename) if os.path.isfile(input_string + os.sep + filename): # skip_if_path directive if restricted: for rs in restricted: if filename.startswith(rs) or filename.endswith(rs): break else: tasks.append(input_string + os.sep + filename) else: tasks.append(input_string + os.sep + filename) # given full filename elif os.path.isfile(input_string): tasks.append(input_string) # skip_if_path directive is not applicable here # given filename stemma else: if stemma: parent = os.path.dirname(input_string) for filename in os.listdir(parent): filename = u(filename) if input_string in parent + os.sep + filename and not os.path.isdir(parent + os.sep + filename): # skip_if_path directive if restricted: for rs in restricted: if filename.startswith(rs) or filename.endswith(rs): break else: tasks.append(parent + os.sep + filename) else: tasks.append(parent + os.sep + filename) return tasks
[ "def", "savvyize", "(", "self", ",", "input_string", ",", "recursive", "=", "False", ",", "stemma", "=", "False", ")", ":", "input_string", "=", "os", ".", "path", ".", "abspath", "(", "input_string", ")", "tasks", "=", "[", "]", "restricted", "=", "["...
Determines which files should be processed NB: this is the PUBLIC method @returns filenames_list
[ "Determines", "which", "files", "should", "be", "processed", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L201-L270
tilde-lab/tilde
tilde/core/api.py
API._parse
def _parse(self, parsable, parser_name): ''' Low-level parsing NB: this is the PRIVATE method @returns tilde_obj, error ''' calc, error = None, None try: for calc in self.Parsers[parser_name].iparse(parsable): yield calc, None return except RuntimeError as e: error = "routine %s parser error in %s: %s" % ( parser_name, parsable, e ) except: exc_type, exc_value, exc_tb = sys.exc_info() error = "unexpected %s parser error in %s:\n %s" % ( parser_name, parsable, "".join(traceback.format_exception( exc_type, exc_value, exc_tb )) ) yield None, error
python
def _parse(self, parsable, parser_name): ''' Low-level parsing NB: this is the PRIVATE method @returns tilde_obj, error ''' calc, error = None, None try: for calc in self.Parsers[parser_name].iparse(parsable): yield calc, None return except RuntimeError as e: error = "routine %s parser error in %s: %s" % ( parser_name, parsable, e ) except: exc_type, exc_value, exc_tb = sys.exc_info() error = "unexpected %s parser error in %s:\n %s" % ( parser_name, parsable, "".join(traceback.format_exception( exc_type, exc_value, exc_tb )) ) yield None, error
[ "def", "_parse", "(", "self", ",", "parsable", ",", "parser_name", ")", ":", "calc", ",", "error", "=", "None", ",", "None", "try", ":", "for", "calc", "in", "self", ".", "Parsers", "[", "parser_name", "]", ".", "iparse", "(", "parsable", ")", ":", ...
Low-level parsing NB: this is the PRIVATE method @returns tilde_obj, error
[ "Low", "-", "level", "parsing", "NB", ":", "this", "is", "the", "PRIVATE", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L272-L288
tilde-lab/tilde
tilde/core/api.py
API.parse
def parse(self, parsable): ''' High-level parsing: determines the data format and combines parent-children outputs NB: this is the PUBLIC method @returns tilde_obj, error ''' calc, error = None, None try: f = open(parsable, 'rb') if is_binary_string(f.read(2048)): yield None, 'was read (binary data)...' return f.close() except IOError: yield None, 'read error!' return f = open(parsable, 'r', errors='surrogateescape') if six.PY3 else open(parsable, 'r') # open the file once again with right mode f.seek(0) counter, detected = 0, False while not detected: if counter > 700: break # criterion: parser must detect its working format until here fingerprint = f.readline() if not fingerprint: break for name, Parser in self.Parsers.items(): if Parser.fingerprints(fingerprint): for calc, error in self._parse(parsable, name): detected = True # check if we parsed something reasonable if not error and calc: if not len(calc.structures) or not len(calc.structures[-1]): error = 'Valid structure is not present!' if calc.info['finished'] == 0x1: calc.warning( 'This calculation is not correctly finished!' ) if not calc.info['H']: error = 'XC potential is not present!' yield calc, error if detected: break counter += 1 f.close() # unsupported data occured if not detected: yield None, 'was read...'
python
def parse(self, parsable): ''' High-level parsing: determines the data format and combines parent-children outputs NB: this is the PUBLIC method @returns tilde_obj, error ''' calc, error = None, None try: f = open(parsable, 'rb') if is_binary_string(f.read(2048)): yield None, 'was read (binary data)...' return f.close() except IOError: yield None, 'read error!' return f = open(parsable, 'r', errors='surrogateescape') if six.PY3 else open(parsable, 'r') # open the file once again with right mode f.seek(0) counter, detected = 0, False while not detected: if counter > 700: break # criterion: parser must detect its working format until here fingerprint = f.readline() if not fingerprint: break for name, Parser in self.Parsers.items(): if Parser.fingerprints(fingerprint): for calc, error in self._parse(parsable, name): detected = True # check if we parsed something reasonable if not error and calc: if not len(calc.structures) or not len(calc.structures[-1]): error = 'Valid structure is not present!' if calc.info['finished'] == 0x1: calc.warning( 'This calculation is not correctly finished!' ) if not calc.info['H']: error = 'XC potential is not present!' yield calc, error if detected: break counter += 1 f.close() # unsupported data occured if not detected: yield None, 'was read...'
[ "def", "parse", "(", "self", ",", "parsable", ")", ":", "calc", ",", "error", "=", "None", ",", "None", "try", ":", "f", "=", "open", "(", "parsable", ",", "'rb'", ")", "if", "is_binary_string", "(", "f", ".", "read", "(", "2048", ")", ")", ":", ...
High-level parsing: determines the data format and combines parent-children outputs NB: this is the PUBLIC method @returns tilde_obj, error
[ "High", "-", "level", "parsing", ":", "determines", "the", "data", "format", "and", "combines", "parent", "-", "children", "outputs", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L290-L345
tilde-lab/tilde
tilde/core/api.py
API.classify
def classify(self, calc, symprec=None): ''' Reasons on normalization, invokes hierarchy API and prepares calc for saving NB: this is the PUBLIC method @returns tilde_obj, error ''' error = None symbols = calc.structures[-1].get_chemical_symbols() calc.info['formula'] = self.formula(symbols) calc.info['cellpar'] = cell_to_cellpar(calc.structures[-1].cell).tolist() if calc.info['input']: try: calc.info['input'] = str(calc.info['input'], errors='ignore') except: pass # applying filter: todo if (calc.info['finished'] == 0x1 and self.settings['skip_unfinished']) or \ (not calc.info['energy'] and self.settings['skip_notenergy']): return None, 'data do not satisfy the active filter' # naive elements extraction fragments = re.findall(r'([A-Z][a-z]?)(\d*[?:.\d+]*)?', calc.info['formula']) for fragment in fragments: if fragment[0] == 'X': continue calc.info['elements'].append(fragment[0]) calc.info['contents'].append(int(fragment[1])) if fragment[1] else calc.info['contents'].append(1) # extend hierarchy with modules for C_obj in self.Classifiers: try: calc = C_obj['classify'](calc) except: exc_type, exc_value, exc_tb = sys.exc_info() error = "Fatal error during classification:\n %s" % "".join(traceback.format_exception( exc_type, exc_value, exc_tb )) return None, error # chemical ratios if not len(calc.info['standard']): if len(calc.info['elements']) == 1: calc.info['expanded'] = 1 if not calc.info['expanded']: calc.info['expanded'] = reduce(gcd, calc.info['contents']) for n, i in enumerate([x//calc.info['expanded'] for x in calc.info['contents']]): if i == 1: calc.info['standard'] += calc.info['elements'][n] else: calc.info['standard'] += calc.info['elements'][n] + str(i) if not calc.info['expanded']: del calc.info['expanded'] calc.info['nelem'] = len(calc.info['elements']) if calc.info['nelem'] > 13: calc.info['nelem'] = 13 calc.info['natom'] = len(symbols) # periodicity if calc.info['periodicity'] == 0: calc.info['periodicity'] = 0x4 elif calc.info['periodicity'] == -1: calc.info['periodicity'] = 0x5 # general calculation type reasoning if (calc.structures[-1].get_initial_charges() != 0).sum(): calc.info['calctypes'].append(0x4) # numpy count_nonzero implementation if (calc.structures[-1].get_initial_magnetic_moments() != 0).sum(): calc.info['calctypes'].append(0x5) if calc.phonons['modes']: calc.info['calctypes'].append(0x6) if calc.phonons['ph_k_degeneracy']: calc.info['calctypes'].append(0x7) if calc.phonons['dielectric_tensor']: calc.info['calctypes'].append(0x8) # CRYSTAL-only! if len(calc.tresholds) > 1: calc.info['calctypes'].append(0x3) calc.info['optgeom'] = True if calc.electrons['dos'] or calc.electrons['bands']: calc.info['calctypes'].append(0x2) if calc.info['energy']: calc.info['calctypes'].append(0x1) calc.info['spin'] = 0x2 if calc.info['spin'] else 0x1 # TODO: standardize if 'vac' in calc.info: if 'X' in symbols: calc.info['techs'].append('vacancy defect: ghost') else: calc.info['techs'].append('vacancy defect: void space') calc.info['lata'] = round(calc.info['cellpar'][0], 3) calc.info['latb'] = round(calc.info['cellpar'][1], 3) calc.info['latc'] = round(calc.info['cellpar'][2], 3) calc.info['latalpha'] = round(calc.info['cellpar'][3], 2) calc.info['latbeta'] = round(calc.info['cellpar'][4], 2) calc.info['latgamma'] = round(calc.info['cellpar'][5], 2) # invoke symmetry finder found = SymmetryHandler(calc, symprec) if found.error: return None, found.error calc.info['sg'] = found.i calc.info['ng'] = found.n calc.info['symmetry'] = found.symmetry calc.info['spg'] = "%s &mdash; %s" % (found.n, found.i) calc.info['pg'] = found.pg calc.info['dg'] = found.dg # phonons if calc.phonons['dfp_magnitude']: calc.info['dfp_magnitude'] = round(calc.phonons['dfp_magnitude'], 3) if calc.phonons['dfp_disps']: calc.info['dfp_disps'] = len(calc.phonons['dfp_disps']) if calc.phonons['modes']: calc.info['n_ph_k'] = len(calc.phonons['ph_k_degeneracy']) if calc.phonons['ph_k_degeneracy'] else 1 #calc.info['rgkmax'] = calc.electrons['rgkmax'] # LAPW # electronic properties reasoning by bands if calc.electrons['bands']: if calc.electrons['bands'].is_conductor(): calc.info['etype'] = 0x2 calc.info['bandgap'] = 0.0 calc.info['bandgaptype'] = 0x1 else: try: gap, is_direct = calc.electrons['bands'].get_bandgap() except ElectronStructureError as e: calc.electrons['bands'] = None calc.warning(e.value) else: calc.info['etype'] = 0x1 calc.info['bandgap'] = round(gap, 2) calc.info['bandgaptype'] = 0x2 if is_direct else 0x3 # electronic properties reasoning by DOS if calc.electrons['dos']: try: gap = round(calc.electrons['dos'].get_bandgap(), 2) except ElectronStructureError as e: calc.electrons['dos'] = None calc.warning(e.value) else: if calc.electrons['bands']: # check coincidence if abs(calc.info['bandgap'] - gap) > 0.2: calc.warning('Bans gaps in DOS and bands data differ considerably! The latter will be considered.') else: calc.info['bandgap'] = gap if gap: calc.info['etype'] = 0x1 else: calc.info['etype'] = 0x2 calc.info['bandgaptype'] = 0x1 # TODO: beware to add something new to an existing item! # TODO2: unknown or absent? for entity in self.hierarchy: if entity['creates_topic'] and not entity['optional'] and not calc.info.get(entity['source']): if entity['enumerated']: calc.info[ entity['source'] ] = [0x0] if entity['multiple'] else 0x0 else: calc.info[ entity['source'] ] = ['none'] if entity['multiple'] else 'none' calc.benchmark() # this call must be at the very end of parsing return calc, error
python
def classify(self, calc, symprec=None): ''' Reasons on normalization, invokes hierarchy API and prepares calc for saving NB: this is the PUBLIC method @returns tilde_obj, error ''' error = None symbols = calc.structures[-1].get_chemical_symbols() calc.info['formula'] = self.formula(symbols) calc.info['cellpar'] = cell_to_cellpar(calc.structures[-1].cell).tolist() if calc.info['input']: try: calc.info['input'] = str(calc.info['input'], errors='ignore') except: pass # applying filter: todo if (calc.info['finished'] == 0x1 and self.settings['skip_unfinished']) or \ (not calc.info['energy'] and self.settings['skip_notenergy']): return None, 'data do not satisfy the active filter' # naive elements extraction fragments = re.findall(r'([A-Z][a-z]?)(\d*[?:.\d+]*)?', calc.info['formula']) for fragment in fragments: if fragment[0] == 'X': continue calc.info['elements'].append(fragment[0]) calc.info['contents'].append(int(fragment[1])) if fragment[1] else calc.info['contents'].append(1) # extend hierarchy with modules for C_obj in self.Classifiers: try: calc = C_obj['classify'](calc) except: exc_type, exc_value, exc_tb = sys.exc_info() error = "Fatal error during classification:\n %s" % "".join(traceback.format_exception( exc_type, exc_value, exc_tb )) return None, error # chemical ratios if not len(calc.info['standard']): if len(calc.info['elements']) == 1: calc.info['expanded'] = 1 if not calc.info['expanded']: calc.info['expanded'] = reduce(gcd, calc.info['contents']) for n, i in enumerate([x//calc.info['expanded'] for x in calc.info['contents']]): if i == 1: calc.info['standard'] += calc.info['elements'][n] else: calc.info['standard'] += calc.info['elements'][n] + str(i) if not calc.info['expanded']: del calc.info['expanded'] calc.info['nelem'] = len(calc.info['elements']) if calc.info['nelem'] > 13: calc.info['nelem'] = 13 calc.info['natom'] = len(symbols) # periodicity if calc.info['periodicity'] == 0: calc.info['periodicity'] = 0x4 elif calc.info['periodicity'] == -1: calc.info['periodicity'] = 0x5 # general calculation type reasoning if (calc.structures[-1].get_initial_charges() != 0).sum(): calc.info['calctypes'].append(0x4) # numpy count_nonzero implementation if (calc.structures[-1].get_initial_magnetic_moments() != 0).sum(): calc.info['calctypes'].append(0x5) if calc.phonons['modes']: calc.info['calctypes'].append(0x6) if calc.phonons['ph_k_degeneracy']: calc.info['calctypes'].append(0x7) if calc.phonons['dielectric_tensor']: calc.info['calctypes'].append(0x8) # CRYSTAL-only! if len(calc.tresholds) > 1: calc.info['calctypes'].append(0x3) calc.info['optgeom'] = True if calc.electrons['dos'] or calc.electrons['bands']: calc.info['calctypes'].append(0x2) if calc.info['energy']: calc.info['calctypes'].append(0x1) calc.info['spin'] = 0x2 if calc.info['spin'] else 0x1 # TODO: standardize if 'vac' in calc.info: if 'X' in symbols: calc.info['techs'].append('vacancy defect: ghost') else: calc.info['techs'].append('vacancy defect: void space') calc.info['lata'] = round(calc.info['cellpar'][0], 3) calc.info['latb'] = round(calc.info['cellpar'][1], 3) calc.info['latc'] = round(calc.info['cellpar'][2], 3) calc.info['latalpha'] = round(calc.info['cellpar'][3], 2) calc.info['latbeta'] = round(calc.info['cellpar'][4], 2) calc.info['latgamma'] = round(calc.info['cellpar'][5], 2) # invoke symmetry finder found = SymmetryHandler(calc, symprec) if found.error: return None, found.error calc.info['sg'] = found.i calc.info['ng'] = found.n calc.info['symmetry'] = found.symmetry calc.info['spg'] = "%s &mdash; %s" % (found.n, found.i) calc.info['pg'] = found.pg calc.info['dg'] = found.dg # phonons if calc.phonons['dfp_magnitude']: calc.info['dfp_magnitude'] = round(calc.phonons['dfp_magnitude'], 3) if calc.phonons['dfp_disps']: calc.info['dfp_disps'] = len(calc.phonons['dfp_disps']) if calc.phonons['modes']: calc.info['n_ph_k'] = len(calc.phonons['ph_k_degeneracy']) if calc.phonons['ph_k_degeneracy'] else 1 #calc.info['rgkmax'] = calc.electrons['rgkmax'] # LAPW # electronic properties reasoning by bands if calc.electrons['bands']: if calc.electrons['bands'].is_conductor(): calc.info['etype'] = 0x2 calc.info['bandgap'] = 0.0 calc.info['bandgaptype'] = 0x1 else: try: gap, is_direct = calc.electrons['bands'].get_bandgap() except ElectronStructureError as e: calc.electrons['bands'] = None calc.warning(e.value) else: calc.info['etype'] = 0x1 calc.info['bandgap'] = round(gap, 2) calc.info['bandgaptype'] = 0x2 if is_direct else 0x3 # electronic properties reasoning by DOS if calc.electrons['dos']: try: gap = round(calc.electrons['dos'].get_bandgap(), 2) except ElectronStructureError as e: calc.electrons['dos'] = None calc.warning(e.value) else: if calc.electrons['bands']: # check coincidence if abs(calc.info['bandgap'] - gap) > 0.2: calc.warning('Bans gaps in DOS and bands data differ considerably! The latter will be considered.') else: calc.info['bandgap'] = gap if gap: calc.info['etype'] = 0x1 else: calc.info['etype'] = 0x2 calc.info['bandgaptype'] = 0x1 # TODO: beware to add something new to an existing item! # TODO2: unknown or absent? for entity in self.hierarchy: if entity['creates_topic'] and not entity['optional'] and not calc.info.get(entity['source']): if entity['enumerated']: calc.info[ entity['source'] ] = [0x0] if entity['multiple'] else 0x0 else: calc.info[ entity['source'] ] = ['none'] if entity['multiple'] else 'none' calc.benchmark() # this call must be at the very end of parsing return calc, error
[ "def", "classify", "(", "self", ",", "calc", ",", "symprec", "=", "None", ")", ":", "error", "=", "None", "symbols", "=", "calc", ".", "structures", "[", "-", "1", "]", ".", "get_chemical_symbols", "(", ")", "calc", ".", "info", "[", "'formula'", "]"...
Reasons on normalization, invokes hierarchy API and prepares calc for saving NB: this is the PUBLIC method @returns tilde_obj, error
[ "Reasons", "on", "normalization", "invokes", "hierarchy", "API", "and", "prepares", "calc", "for", "saving", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L347-L509
tilde-lab/tilde
tilde/core/api.py
API.postprocess
def postprocess(self, calc, with_module=None, dry_run=None): ''' Invokes module(s) API NB: this is the PUBLIC method @returns apps_dict ''' for appname, appclass in self.Apps.items(): if with_module and with_module != appname: continue run_permitted = False # scope-conditions if appclass['apptarget']: for key in appclass['apptarget']: negative = False if str(appclass['apptarget'][key]).startswith('!'): negative = True scope_prop = appclass['apptarget'][key][1:] else: scope_prop = appclass['apptarget'][key] if key in calc.info: # non-strict comparison ("CRYSTAL" matches "CRYSTAL09 v2.0") if (str(scope_prop) in str(calc.info[key]) or scope_prop == calc.info[key]) != negative: # true if only one, but not both run_permitted = True else: run_permitted = False break else: run_permitted = True # module code running if run_permitted: calc.apps[appname] = {'error': None, 'data': None} if dry_run: continue try: AppInstance = appclass['appmodule'](calc) except: exc_type, exc_value, exc_tb = sys.exc_info() errmsg = "Fatal error in %s module:\n %s" % ( appname, " ".join(traceback.format_exception( exc_type, exc_value, exc_tb )) ) calc.apps[appname]['error'] = errmsg calc.warning( errmsg ) else: try: calc.apps[appname]['data'] = getattr(AppInstance, appclass['appdata']) except AttributeError: errmsg = 'No appdata-defined property found for %s module!' % appname calc.apps[appname]['error'] = errmsg calc.warning( errmsg ) return calc
python
def postprocess(self, calc, with_module=None, dry_run=None): ''' Invokes module(s) API NB: this is the PUBLIC method @returns apps_dict ''' for appname, appclass in self.Apps.items(): if with_module and with_module != appname: continue run_permitted = False # scope-conditions if appclass['apptarget']: for key in appclass['apptarget']: negative = False if str(appclass['apptarget'][key]).startswith('!'): negative = True scope_prop = appclass['apptarget'][key][1:] else: scope_prop = appclass['apptarget'][key] if key in calc.info: # non-strict comparison ("CRYSTAL" matches "CRYSTAL09 v2.0") if (str(scope_prop) in str(calc.info[key]) or scope_prop == calc.info[key]) != negative: # true if only one, but not both run_permitted = True else: run_permitted = False break else: run_permitted = True # module code running if run_permitted: calc.apps[appname] = {'error': None, 'data': None} if dry_run: continue try: AppInstance = appclass['appmodule'](calc) except: exc_type, exc_value, exc_tb = sys.exc_info() errmsg = "Fatal error in %s module:\n %s" % ( appname, " ".join(traceback.format_exception( exc_type, exc_value, exc_tb )) ) calc.apps[appname]['error'] = errmsg calc.warning( errmsg ) else: try: calc.apps[appname]['data'] = getattr(AppInstance, appclass['appdata']) except AttributeError: errmsg = 'No appdata-defined property found for %s module!' % appname calc.apps[appname]['error'] = errmsg calc.warning( errmsg ) return calc
[ "def", "postprocess", "(", "self", ",", "calc", ",", "with_module", "=", "None", ",", "dry_run", "=", "None", ")", ":", "for", "appname", ",", "appclass", "in", "self", ".", "Apps", ".", "items", "(", ")", ":", "if", "with_module", "and", "with_module"...
Invokes module(s) API NB: this is the PUBLIC method @returns apps_dict
[ "Invokes", "module", "(", "s", ")", "API", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L511-L561
tilde-lab/tilde
tilde/core/api.py
API.save
def save(self, calc, session): ''' Saves tilde_obj into the database NB: this is the PUBLIC method @returns checksum, error ''' checksum = calc.get_checksum() try: existing_calc = session.query(model.Calculation).filter(model.Calculation.checksum == checksum).one() except NoResultFound: pass else: del calc return None, "This calculation already exists!" if not calc.download_size: for f in calc.related_files: calc.download_size += os.stat(f).st_size ormcalc = model.Calculation(checksum = checksum) if calc._calcset: ormcalc.meta_data = model.Metadata(chemical_formula = calc.info['standard'], download_size = calc.download_size) for child in session.query(model.Calculation).filter(model.Calculation.checksum.in_(calc._calcset)).all(): ormcalc.children.append(child) ormcalc.siblings_count = len(ormcalc.children) ormcalc.nested_depth = calc._nested_depth else: # prepare phonon data for saving # this is actually a dict to list conversion TODO re-structure this if calc.phonons['modes']: phonons_json = [] for bzpoint, frqset in calc.phonons['modes'].items(): # re-orientate eigenvectors for i in range(0, len(calc.phonons['ph_eigvecs'][bzpoint])): for j in range(0, len(calc.phonons['ph_eigvecs'][bzpoint][i])//3): eigv = array([calc.phonons['ph_eigvecs'][bzpoint][i][j*3], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+1], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+2]]) R = dot( eigv, calc.structures[-1].cell ).tolist() calc.phonons['ph_eigvecs'][bzpoint][i][j*3], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+1], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+2] = [round(x, 3) for x in R] try: irreps = calc.phonons['irreps'][bzpoint] except KeyError: empty = [] for i in range(len(frqset)): empty.append('') irreps = empty phonons_json.append({ 'bzpoint':bzpoint, 'freqs':frqset, 'irreps':irreps, 'ph_eigvecs':calc.phonons['ph_eigvecs'][bzpoint] }) if bzpoint == '0 0 0': phonons_json[-1]['ir_active'] = calc.phonons['ir_active'] phonons_json[-1]['raman_active'] = calc.phonons['raman_active'] if calc.phonons['ph_k_degeneracy']: phonons_json[-1]['ph_k_degeneracy'] = calc.phonons['ph_k_degeneracy'][bzpoint] ormcalc.phonons = model.Phonons() ormcalc.spectra.append( model.Spectra(kind = model.Spectra.PHONON, eigenvalues = json.dumps(phonons_json)) ) # prepare electron data for saving TODO re-structure this for task in ['dos', 'bands']: # projected? if calc.electrons[task]: calc.electrons[task] = calc.electrons[task].todict() if calc.electrons['dos'] or calc.electrons['bands']: ormcalc.electrons = model.Electrons(gap = calc.info['bandgap']) if 'bandgaptype' in calc.info: ormcalc.electrons.is_direct = 1 if calc.info['bandgaptype'] == 'direct' else -1 ormcalc.spectra.append(model.Spectra( kind = model.Spectra.ELECTRON, dos = json.dumps(calc.electrons['dos']), bands = json.dumps(calc.electrons['bands']), projected = json.dumps(calc.electrons['projected']), eigenvalues = json.dumps(calc.electrons['eigvals']) )) # construct ORM for other props calc.related_files = list(map(virtualize_path, calc.related_files)) ormcalc.meta_data = model.Metadata(location = calc.info['location'], finished = calc.info['finished'], raw_input = calc.info['input'], modeling_time = calc.info['duration'], chemical_formula = html_formula(calc.info['standard']), download_size = calc.download_size, filenames = json.dumps(calc.related_files)) codefamily = model.Codefamily.as_unique(session, content = calc.info['framework']) codeversion = model.Codeversion.as_unique(session, content = calc.info['prog']) codeversion.instances.append( ormcalc.meta_data ) codefamily.versions.append( codeversion ) pot = model.Pottype.as_unique(session, name = calc.info['H']) pot.instances.append(ormcalc) ormcalc.recipinteg = model.Recipinteg(kgrid = calc.info['k'], kshift = calc.info['kshift'], smearing = calc.info['smear'], smeartype = calc.info['smeartype']) ormcalc.basis = model.Basis(kind = calc.info['ansatz'], content = json.dumps(calc.electrons['basis_set']) if calc.electrons['basis_set'] else None) ormcalc.energy = model.Energy(convergence = json.dumps(calc.convergence), total = calc.info['energy']) ormcalc.spacegroup = model.Spacegroup(n=calc.info['ng']) ormcalc.struct_ratios = model.Struct_ratios(chemical_formula=calc.info['standard'], formula_units=calc.info['expanded'], nelem=calc.info['nelem'], dimensions=calc.info['dims']) if len(calc.tresholds) > 1: ormcalc.struct_optimisation = model.Struct_optimisation(tresholds=json.dumps(calc.tresholds), ncycles=json.dumps(calc.ncycles)) for n, ase_repr in enumerate(calc.structures): is_final = True if n == len(calc.structures)-1 else False struct = model.Structure(step = n, final = is_final) s = cell_to_cellpar(ase_repr.cell) struct.lattice = model.Lattice(a=s[0], b=s[1], c=s[2], alpha=s[3], beta=s[4], gamma=s[5], a11=ase_repr.cell[0][0], a12=ase_repr.cell[0][1], a13=ase_repr.cell[0][2], a21=ase_repr.cell[1][0], a22=ase_repr.cell[1][1], a23=ase_repr.cell[1][2], a31=ase_repr.cell[2][0], a32=ase_repr.cell[2][1], a33=ase_repr.cell[2][2]) #rmts = ase_repr.get_array('rmts') if 'rmts' in ase_repr.arrays else [None for j in range(len(ase_repr))] charges = ase_repr.get_array('charges') if 'charges' in ase_repr.arrays else [None for j in range(len(ase_repr))] magmoms = ase_repr.get_array('magmoms') if 'magmoms' in ase_repr.arrays else [None for j in range(len(ase_repr))] for n, i in enumerate(ase_repr): struct.atoms.append( model.Atom( number=chemical_symbols.index(i.symbol), x=i.x, y=i.y, z=i.z, charge=charges[n], magmom=magmoms[n] ) ) ormcalc.structures.append(struct) # TODO Forces ormcalc.uigrid = model.Grid(info=json.dumps(calc.info)) # tags ORM uitopics = [] for entity in self.hierarchy: if not entity['creates_topic']: continue if entity['multiple'] or calc._calcset: for item in calc.info.get( entity['source'], [] ): uitopics.append( model.topic(cid=entity['cid'], topic=item) ) else: topic = calc.info.get(entity['source']) if topic or not entity['optional']: uitopics.append( model.topic(cid=entity['cid'], topic=topic) ) uitopics = [model.Topic.as_unique(session, cid=x.cid, topic="%s" % x.topic) for x in uitopics] ormcalc.uitopics.extend(uitopics) if calc._calcset: session.add(ormcalc) else: session.add_all([codefamily, codeversion, pot, ormcalc]) session.commit() del calc, ormcalc return checksum, None
python
def save(self, calc, session): ''' Saves tilde_obj into the database NB: this is the PUBLIC method @returns checksum, error ''' checksum = calc.get_checksum() try: existing_calc = session.query(model.Calculation).filter(model.Calculation.checksum == checksum).one() except NoResultFound: pass else: del calc return None, "This calculation already exists!" if not calc.download_size: for f in calc.related_files: calc.download_size += os.stat(f).st_size ormcalc = model.Calculation(checksum = checksum) if calc._calcset: ormcalc.meta_data = model.Metadata(chemical_formula = calc.info['standard'], download_size = calc.download_size) for child in session.query(model.Calculation).filter(model.Calculation.checksum.in_(calc._calcset)).all(): ormcalc.children.append(child) ormcalc.siblings_count = len(ormcalc.children) ormcalc.nested_depth = calc._nested_depth else: # prepare phonon data for saving # this is actually a dict to list conversion TODO re-structure this if calc.phonons['modes']: phonons_json = [] for bzpoint, frqset in calc.phonons['modes'].items(): # re-orientate eigenvectors for i in range(0, len(calc.phonons['ph_eigvecs'][bzpoint])): for j in range(0, len(calc.phonons['ph_eigvecs'][bzpoint][i])//3): eigv = array([calc.phonons['ph_eigvecs'][bzpoint][i][j*3], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+1], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+2]]) R = dot( eigv, calc.structures[-1].cell ).tolist() calc.phonons['ph_eigvecs'][bzpoint][i][j*3], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+1], calc.phonons['ph_eigvecs'][bzpoint][i][j*3+2] = [round(x, 3) for x in R] try: irreps = calc.phonons['irreps'][bzpoint] except KeyError: empty = [] for i in range(len(frqset)): empty.append('') irreps = empty phonons_json.append({ 'bzpoint':bzpoint, 'freqs':frqset, 'irreps':irreps, 'ph_eigvecs':calc.phonons['ph_eigvecs'][bzpoint] }) if bzpoint == '0 0 0': phonons_json[-1]['ir_active'] = calc.phonons['ir_active'] phonons_json[-1]['raman_active'] = calc.phonons['raman_active'] if calc.phonons['ph_k_degeneracy']: phonons_json[-1]['ph_k_degeneracy'] = calc.phonons['ph_k_degeneracy'][bzpoint] ormcalc.phonons = model.Phonons() ormcalc.spectra.append( model.Spectra(kind = model.Spectra.PHONON, eigenvalues = json.dumps(phonons_json)) ) # prepare electron data for saving TODO re-structure this for task in ['dos', 'bands']: # projected? if calc.electrons[task]: calc.electrons[task] = calc.electrons[task].todict() if calc.electrons['dos'] or calc.electrons['bands']: ormcalc.electrons = model.Electrons(gap = calc.info['bandgap']) if 'bandgaptype' in calc.info: ormcalc.electrons.is_direct = 1 if calc.info['bandgaptype'] == 'direct' else -1 ormcalc.spectra.append(model.Spectra( kind = model.Spectra.ELECTRON, dos = json.dumps(calc.electrons['dos']), bands = json.dumps(calc.electrons['bands']), projected = json.dumps(calc.electrons['projected']), eigenvalues = json.dumps(calc.electrons['eigvals']) )) # construct ORM for other props calc.related_files = list(map(virtualize_path, calc.related_files)) ormcalc.meta_data = model.Metadata(location = calc.info['location'], finished = calc.info['finished'], raw_input = calc.info['input'], modeling_time = calc.info['duration'], chemical_formula = html_formula(calc.info['standard']), download_size = calc.download_size, filenames = json.dumps(calc.related_files)) codefamily = model.Codefamily.as_unique(session, content = calc.info['framework']) codeversion = model.Codeversion.as_unique(session, content = calc.info['prog']) codeversion.instances.append( ormcalc.meta_data ) codefamily.versions.append( codeversion ) pot = model.Pottype.as_unique(session, name = calc.info['H']) pot.instances.append(ormcalc) ormcalc.recipinteg = model.Recipinteg(kgrid = calc.info['k'], kshift = calc.info['kshift'], smearing = calc.info['smear'], smeartype = calc.info['smeartype']) ormcalc.basis = model.Basis(kind = calc.info['ansatz'], content = json.dumps(calc.electrons['basis_set']) if calc.electrons['basis_set'] else None) ormcalc.energy = model.Energy(convergence = json.dumps(calc.convergence), total = calc.info['energy']) ormcalc.spacegroup = model.Spacegroup(n=calc.info['ng']) ormcalc.struct_ratios = model.Struct_ratios(chemical_formula=calc.info['standard'], formula_units=calc.info['expanded'], nelem=calc.info['nelem'], dimensions=calc.info['dims']) if len(calc.tresholds) > 1: ormcalc.struct_optimisation = model.Struct_optimisation(tresholds=json.dumps(calc.tresholds), ncycles=json.dumps(calc.ncycles)) for n, ase_repr in enumerate(calc.structures): is_final = True if n == len(calc.structures)-1 else False struct = model.Structure(step = n, final = is_final) s = cell_to_cellpar(ase_repr.cell) struct.lattice = model.Lattice(a=s[0], b=s[1], c=s[2], alpha=s[3], beta=s[4], gamma=s[5], a11=ase_repr.cell[0][0], a12=ase_repr.cell[0][1], a13=ase_repr.cell[0][2], a21=ase_repr.cell[1][0], a22=ase_repr.cell[1][1], a23=ase_repr.cell[1][2], a31=ase_repr.cell[2][0], a32=ase_repr.cell[2][1], a33=ase_repr.cell[2][2]) #rmts = ase_repr.get_array('rmts') if 'rmts' in ase_repr.arrays else [None for j in range(len(ase_repr))] charges = ase_repr.get_array('charges') if 'charges' in ase_repr.arrays else [None for j in range(len(ase_repr))] magmoms = ase_repr.get_array('magmoms') if 'magmoms' in ase_repr.arrays else [None for j in range(len(ase_repr))] for n, i in enumerate(ase_repr): struct.atoms.append( model.Atom( number=chemical_symbols.index(i.symbol), x=i.x, y=i.y, z=i.z, charge=charges[n], magmom=magmoms[n] ) ) ormcalc.structures.append(struct) # TODO Forces ormcalc.uigrid = model.Grid(info=json.dumps(calc.info)) # tags ORM uitopics = [] for entity in self.hierarchy: if not entity['creates_topic']: continue if entity['multiple'] or calc._calcset: for item in calc.info.get( entity['source'], [] ): uitopics.append( model.topic(cid=entity['cid'], topic=item) ) else: topic = calc.info.get(entity['source']) if topic or not entity['optional']: uitopics.append( model.topic(cid=entity['cid'], topic=topic) ) uitopics = [model.Topic.as_unique(session, cid=x.cid, topic="%s" % x.topic) for x in uitopics] ormcalc.uitopics.extend(uitopics) if calc._calcset: session.add(ormcalc) else: session.add_all([codefamily, codeversion, pot, ormcalc]) session.commit() del calc, ormcalc return checksum, None
[ "def", "save", "(", "self", ",", "calc", ",", "session", ")", ":", "checksum", "=", "calc", ".", "get_checksum", "(", ")", "try", ":", "existing_calc", "=", "session", ".", "query", "(", "model", ".", "Calculation", ")", ".", "filter", "(", "model", ...
Saves tilde_obj into the database NB: this is the PUBLIC method @returns checksum, error
[ "Saves", "tilde_obj", "into", "the", "database", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L563-L706
tilde-lab/tilde
tilde/core/api.py
API.purge
def purge(self, session, checksum): ''' Deletes calc entry by checksum entirely from the database NB source files on disk are not deleted NB: this is the PUBLIC method @returns error ''' C = session.query(model.Calculation).get(checksum) if not C: return 'Calculation does not exist!' # dataset deletion includes editing the whole dataset hierarchical tree (if any) if C.siblings_count: C_meta = session.query(model.Metadata).get(checksum) higher_lookup = {} more = C.parent distance = 0 while True: distance += 1 higher, more = more, [] if not higher: break for item in higher: try: higher_lookup[distance].add(item) except KeyError: higher_lookup[distance] = set([item]) if item.parent: more += item.parent for distance, members in higher_lookup.items(): for member in members: if distance == 1: member.siblings_count -= 1 if not member.siblings_count: return 'The parent dataset contains only one (current) item, please, delete parent dataset first!' member.meta_data.download_size -= C_meta.download_size session.add(member) # low-level entry deletion deals with additional tables else: session.execute( model.delete( model.Spectra ).where( model.Spectra.checksum == checksum) ) session.execute( model.delete( model.Electrons ).where( model.Electrons.checksum == checksum ) ) session.execute( model.delete( model.Phonons ).where( model.Phonons.checksum == checksum ) ) session.execute( model.delete( model.Recipinteg ).where( model.Recipinteg.checksum == checksum ) ) session.execute( model.delete( model.Basis ).where( model.Basis.checksum == checksum ) ) session.execute( model.delete( model.Energy ).where( model.Energy.checksum == checksum ) ) session.execute( model.delete( model.Spacegroup ).where( model.Spacegroup.checksum == checksum ) ) session.execute( model.delete( model.Struct_ratios ).where( model.Struct_ratios.checksum == checksum ) ) session.execute( model.delete( model.Struct_optimisation ).where( model.Struct_optimisation.checksum == checksum ) ) struct_ids = [ int(i[0]) for i in session.query(model.Structure.struct_id).filter(model.Structure.checksum == checksum).all() ] for struct_id in struct_ids: session.execute( model.delete( model.Atom ).where( model.Atom.struct_id == struct_id ) ) session.execute( model.delete( model.Lattice ).where( model.Lattice.struct_id == struct_id ) ) session.execute( model.delete( model.Structure ).where( model.Structure.checksum == checksum ) ) # for all types of entries if len(C.references): left_references = [ int(i[0]) for i in session.query(model.Reference.reference_id).join(model.metadata_references, model.Reference.reference_id == model.metadata_references.c.reference_id).filter(model.metadata_references.c.checksum == checksum).all() ] session.execute( model.delete( model.metadata_references ).where( model.metadata_references.c.checksum == checksum ) ) # remove the whole citation? for lc in left_references: if not (session.query(model.metadata_references.c.checksum).filter(model.metadata_references.c.reference_id == lc).count()): session.execute( model.delete( model.Reference ).where(model.Reference.reference_id == lc) ) # TODO rewrite with cascading session.execute( model.delete( model.Metadata ).where( model.Metadata.checksum == checksum ) ) session.execute( model.delete( model.Grid ).where( model.Grid.checksum == checksum ) ) session.execute( model.delete( model.tags ).where( model.tags.c.checksum == checksum ) ) session.execute( model.delete( model.calcsets ).where( model.calcsets.c.children_checksum == checksum ) ) session.execute( model.delete( model.calcsets ).where( model.calcsets.c.parent_checksum == checksum ) ) session.execute( model.delete( model.Calculation ).where( model.Calculation.checksum == checksum ) ) session.commit() # NB tables topics, codefamily, codeversion, pottype are mostly irrelevant and, if needed, should be cleaned manually return False
python
def purge(self, session, checksum): ''' Deletes calc entry by checksum entirely from the database NB source files on disk are not deleted NB: this is the PUBLIC method @returns error ''' C = session.query(model.Calculation).get(checksum) if not C: return 'Calculation does not exist!' # dataset deletion includes editing the whole dataset hierarchical tree (if any) if C.siblings_count: C_meta = session.query(model.Metadata).get(checksum) higher_lookup = {} more = C.parent distance = 0 while True: distance += 1 higher, more = more, [] if not higher: break for item in higher: try: higher_lookup[distance].add(item) except KeyError: higher_lookup[distance] = set([item]) if item.parent: more += item.parent for distance, members in higher_lookup.items(): for member in members: if distance == 1: member.siblings_count -= 1 if not member.siblings_count: return 'The parent dataset contains only one (current) item, please, delete parent dataset first!' member.meta_data.download_size -= C_meta.download_size session.add(member) # low-level entry deletion deals with additional tables else: session.execute( model.delete( model.Spectra ).where( model.Spectra.checksum == checksum) ) session.execute( model.delete( model.Electrons ).where( model.Electrons.checksum == checksum ) ) session.execute( model.delete( model.Phonons ).where( model.Phonons.checksum == checksum ) ) session.execute( model.delete( model.Recipinteg ).where( model.Recipinteg.checksum == checksum ) ) session.execute( model.delete( model.Basis ).where( model.Basis.checksum == checksum ) ) session.execute( model.delete( model.Energy ).where( model.Energy.checksum == checksum ) ) session.execute( model.delete( model.Spacegroup ).where( model.Spacegroup.checksum == checksum ) ) session.execute( model.delete( model.Struct_ratios ).where( model.Struct_ratios.checksum == checksum ) ) session.execute( model.delete( model.Struct_optimisation ).where( model.Struct_optimisation.checksum == checksum ) ) struct_ids = [ int(i[0]) for i in session.query(model.Structure.struct_id).filter(model.Structure.checksum == checksum).all() ] for struct_id in struct_ids: session.execute( model.delete( model.Atom ).where( model.Atom.struct_id == struct_id ) ) session.execute( model.delete( model.Lattice ).where( model.Lattice.struct_id == struct_id ) ) session.execute( model.delete( model.Structure ).where( model.Structure.checksum == checksum ) ) # for all types of entries if len(C.references): left_references = [ int(i[0]) for i in session.query(model.Reference.reference_id).join(model.metadata_references, model.Reference.reference_id == model.metadata_references.c.reference_id).filter(model.metadata_references.c.checksum == checksum).all() ] session.execute( model.delete( model.metadata_references ).where( model.metadata_references.c.checksum == checksum ) ) # remove the whole citation? for lc in left_references: if not (session.query(model.metadata_references.c.checksum).filter(model.metadata_references.c.reference_id == lc).count()): session.execute( model.delete( model.Reference ).where(model.Reference.reference_id == lc) ) # TODO rewrite with cascading session.execute( model.delete( model.Metadata ).where( model.Metadata.checksum == checksum ) ) session.execute( model.delete( model.Grid ).where( model.Grid.checksum == checksum ) ) session.execute( model.delete( model.tags ).where( model.tags.c.checksum == checksum ) ) session.execute( model.delete( model.calcsets ).where( model.calcsets.c.children_checksum == checksum ) ) session.execute( model.delete( model.calcsets ).where( model.calcsets.c.parent_checksum == checksum ) ) session.execute( model.delete( model.Calculation ).where( model.Calculation.checksum == checksum ) ) session.commit() # NB tables topics, codefamily, codeversion, pottype are mostly irrelevant and, if needed, should be cleaned manually return False
[ "def", "purge", "(", "self", ",", "session", ",", "checksum", ")", ":", "C", "=", "session", ".", "query", "(", "model", ".", "Calculation", ")", ".", "get", "(", "checksum", ")", "if", "not", "C", ":", "return", "'Calculation does not exist!'", "# datas...
Deletes calc entry by checksum entirely from the database NB source files on disk are not deleted NB: this is the PUBLIC method @returns error
[ "Deletes", "calc", "entry", "by", "checksum", "entirely", "from", "the", "database", "NB", "source", "files", "on", "disk", "are", "not", "deleted", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L708-L787
tilde-lab/tilde
tilde/core/api.py
API.merge
def merge(self, session, checksums, title): ''' Merges calcs into a new calc called DATASET NB: this is the PUBLIC method @returns DATASET, error ''' calc = Output(calcset=checksums) cur_depth = 0 for nested_depth, grid_item, download_size in session.query(model.Calculation.nested_depth, model.Grid.info, model.Metadata.download_size).filter(model.Calculation.checksum == model.Grid.checksum, model.Grid.checksum == model.Metadata.checksum, model.Calculation.checksum.in_(checksums)).all(): if nested_depth > cur_depth: cur_depth = nested_depth grid_item = json.loads(grid_item) for entity in self.hierarchy: topic = grid_item.get(entity['source']) if not topic: continue if not isinstance(topic, list): topic = [ topic ] calc.info[ entity['source'] ] = list(set( calc.info.get(entity['source'], []) + topic )) calc.download_size += download_size if not calc.download_size: return None, 'Wrong parameters provided!' calc._nested_depth = cur_depth + 1 calc.info['standard'] = title # generate fake checksum calc._checksum = calc.get_collective_checksum() return calc, None
python
def merge(self, session, checksums, title): ''' Merges calcs into a new calc called DATASET NB: this is the PUBLIC method @returns DATASET, error ''' calc = Output(calcset=checksums) cur_depth = 0 for nested_depth, grid_item, download_size in session.query(model.Calculation.nested_depth, model.Grid.info, model.Metadata.download_size).filter(model.Calculation.checksum == model.Grid.checksum, model.Grid.checksum == model.Metadata.checksum, model.Calculation.checksum.in_(checksums)).all(): if nested_depth > cur_depth: cur_depth = nested_depth grid_item = json.loads(grid_item) for entity in self.hierarchy: topic = grid_item.get(entity['source']) if not topic: continue if not isinstance(topic, list): topic = [ topic ] calc.info[ entity['source'] ] = list(set( calc.info.get(entity['source'], []) + topic )) calc.download_size += download_size if not calc.download_size: return None, 'Wrong parameters provided!' calc._nested_depth = cur_depth + 1 calc.info['standard'] = title # generate fake checksum calc._checksum = calc.get_collective_checksum() return calc, None
[ "def", "merge", "(", "self", ",", "session", ",", "checksums", ",", "title", ")", ":", "calc", "=", "Output", "(", "calcset", "=", "checksums", ")", "cur_depth", "=", "0", "for", "nested_depth", ",", "grid_item", ",", "download_size", "in", "session", "....
Merges calcs into a new calc called DATASET NB: this is the PUBLIC method @returns DATASET, error
[ "Merges", "calcs", "into", "a", "new", "calc", "called", "DATASET", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L789-L828
tilde-lab/tilde
tilde/core/api.py
API.augment
def augment(self, session, parent, addendum): ''' Augments a DATASET with some calcs NB: this is the PUBLIC method @returns error ''' parent_calc = session.query(model.Calculation).get(parent) if not parent_calc or not parent_calc.siblings_count: return 'Dataset is erroneously selected!' existing_children, filtered_addendum = [child.checksum for child in parent_calc.children], [] for child in addendum: if not child in existing_children: filtered_addendum.append(child) if not filtered_addendum: return 'All these data are already present in this dataset.' if parent_calc.checksum in filtered_addendum: return 'A dataset cannot be added into itself.' higher_lookup = {} more = parent_calc.parent distance = 0 while True: distance += 1 higher, more = more, [] if not higher: break for item in higher: try: higher_lookup[distance].add(item) except KeyError: higher_lookup[distance] = set([item]) if item.parent: more += item.parent for members in list(higher_lookup.values()): for member in members: if member.checksum in filtered_addendum: return 'A parent dataset cannot be added to its children dataset.' parent_meta = session.query(model.Metadata).get(parent) parent_grid = session.query(model.Grid).get(parent) info_obj = json.loads(parent_grid.info) for nested_depth, grid_item, download_size in session.query(model.Calculation.nested_depth, model.Grid.info, model.Metadata.download_size).filter(model.Calculation.checksum == model.Grid.checksum, model.Grid.checksum == model.Metadata.checksum, model.Calculation.checksum.in_(filtered_addendum)).all(): if nested_depth >= parent_calc.nested_depth: parent_calc.nested_depth = nested_depth + 1 grid_item = json.loads(grid_item) for entity in self.hierarchy: topic = grid_item.get(entity['source']) if not topic: continue if entity['source'] == 'standard': topic = [] if not isinstance(topic, list): topic = [ topic ] existing_term = info_obj.get(entity['source'], []) if not isinstance(existing_term, list): existing_term = [ existing_term ] # TODO info_obj[ entity['source'] ] = list(set( existing_term + topic )) parent_meta.download_size += download_size info_obj['standard'] = info_obj['standard'][0] # TODO parent_grid.info = json.dumps(info_obj) # tags ORM for entity in self.hierarchy: if not entity['creates_topic']: continue for item in info_obj.get( entity['source'], [] ): parent_calc.uitopics.append( model.Topic.as_unique(session, cid=entity['cid'], topic="%s" % item) ) for child in session.query(model.Calculation).filter(model.Calculation.checksum.in_(filtered_addendum)).all(): parent_calc.children.append(child) parent_calc.siblings_count = len(parent_calc.children) for distance, members in higher_lookup.items(): for member in members: d = parent_calc.nested_depth - member.nested_depth + distance if d > 0: member.nested_depth += d member.meta_data.download_size += parent_meta.download_size # FIXME session.add(member) session.add_all([parent_calc, parent_meta, parent_grid]) session.commit() return False
python
def augment(self, session, parent, addendum): ''' Augments a DATASET with some calcs NB: this is the PUBLIC method @returns error ''' parent_calc = session.query(model.Calculation).get(parent) if not parent_calc or not parent_calc.siblings_count: return 'Dataset is erroneously selected!' existing_children, filtered_addendum = [child.checksum for child in parent_calc.children], [] for child in addendum: if not child in existing_children: filtered_addendum.append(child) if not filtered_addendum: return 'All these data are already present in this dataset.' if parent_calc.checksum in filtered_addendum: return 'A dataset cannot be added into itself.' higher_lookup = {} more = parent_calc.parent distance = 0 while True: distance += 1 higher, more = more, [] if not higher: break for item in higher: try: higher_lookup[distance].add(item) except KeyError: higher_lookup[distance] = set([item]) if item.parent: more += item.parent for members in list(higher_lookup.values()): for member in members: if member.checksum in filtered_addendum: return 'A parent dataset cannot be added to its children dataset.' parent_meta = session.query(model.Metadata).get(parent) parent_grid = session.query(model.Grid).get(parent) info_obj = json.loads(parent_grid.info) for nested_depth, grid_item, download_size in session.query(model.Calculation.nested_depth, model.Grid.info, model.Metadata.download_size).filter(model.Calculation.checksum == model.Grid.checksum, model.Grid.checksum == model.Metadata.checksum, model.Calculation.checksum.in_(filtered_addendum)).all(): if nested_depth >= parent_calc.nested_depth: parent_calc.nested_depth = nested_depth + 1 grid_item = json.loads(grid_item) for entity in self.hierarchy: topic = grid_item.get(entity['source']) if not topic: continue if entity['source'] == 'standard': topic = [] if not isinstance(topic, list): topic = [ topic ] existing_term = info_obj.get(entity['source'], []) if not isinstance(existing_term, list): existing_term = [ existing_term ] # TODO info_obj[ entity['source'] ] = list(set( existing_term + topic )) parent_meta.download_size += download_size info_obj['standard'] = info_obj['standard'][0] # TODO parent_grid.info = json.dumps(info_obj) # tags ORM for entity in self.hierarchy: if not entity['creates_topic']: continue for item in info_obj.get( entity['source'], [] ): parent_calc.uitopics.append( model.Topic.as_unique(session, cid=entity['cid'], topic="%s" % item) ) for child in session.query(model.Calculation).filter(model.Calculation.checksum.in_(filtered_addendum)).all(): parent_calc.children.append(child) parent_calc.siblings_count = len(parent_calc.children) for distance, members in higher_lookup.items(): for member in members: d = parent_calc.nested_depth - member.nested_depth + distance if d > 0: member.nested_depth += d member.meta_data.download_size += parent_meta.download_size # FIXME session.add(member) session.add_all([parent_calc, parent_meta, parent_grid]) session.commit() return False
[ "def", "augment", "(", "self", ",", "session", ",", "parent", ",", "addendum", ")", ":", "parent_calc", "=", "session", ".", "query", "(", "model", ".", "Calculation", ")", ".", "get", "(", "parent", ")", "if", "not", "parent_calc", "or", "not", "paren...
Augments a DATASET with some calcs NB: this is the PUBLIC method @returns error
[ "Augments", "a", "DATASET", "with", "some", "calcs", "NB", ":", "this", "is", "the", "PUBLIC", "method" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/api.py#L830-L931
commontk/ctk-cli
ctk_cli/execution.py
isCLIExecutable
def isCLIExecutable(filePath): """Test whether given `filePath` is an executable. Does not really check whether the executable is a CLI (e.g. whether it supports --xml), but can be used to filter out non-executables within a directory with CLI modules. """ # see qSlicerUtils::isCLIExecutable # e.g. https://github.com/Slicer/Slicer/blob/master/Base/QTCore/qSlicerUtils.cxx if not os.path.isfile(filePath): return False if sys.platform.startswith('win'): filePath = filePath.lower() # be case insensitive return filePath.endswith(".exe") or filePath.endswith(".bat") else: # differing from qSlicerUtils here, which does not check for executable bits # (this way we can differentiate between XML files saved with the same name # as the executables and the executables themselves) if not os.access(filePath, os.X_OK): return False return not '.' in os.path.basename(filePath)
python
def isCLIExecutable(filePath): """Test whether given `filePath` is an executable. Does not really check whether the executable is a CLI (e.g. whether it supports --xml), but can be used to filter out non-executables within a directory with CLI modules. """ # see qSlicerUtils::isCLIExecutable # e.g. https://github.com/Slicer/Slicer/blob/master/Base/QTCore/qSlicerUtils.cxx if not os.path.isfile(filePath): return False if sys.platform.startswith('win'): filePath = filePath.lower() # be case insensitive return filePath.endswith(".exe") or filePath.endswith(".bat") else: # differing from qSlicerUtils here, which does not check for executable bits # (this way we can differentiate between XML files saved with the same name # as the executables and the executables themselves) if not os.access(filePath, os.X_OK): return False return not '.' in os.path.basename(filePath)
[ "def", "isCLIExecutable", "(", "filePath", ")", ":", "# see qSlicerUtils::isCLIExecutable", "# e.g. https://github.com/Slicer/Slicer/blob/master/Base/QTCore/qSlicerUtils.cxx", "if", "not", "os", ".", "path", ".", "isfile", "(", "filePath", ")", ":", "return", "False", "if",...
Test whether given `filePath` is an executable. Does not really check whether the executable is a CLI (e.g. whether it supports --xml), but can be used to filter out non-executables within a directory with CLI modules.
[ "Test", "whether", "given", "filePath", "is", "an", "executable", ".", "Does", "not", "really", "check", "whether", "the", "executable", "is", "a", "CLI", "(", "e", ".", "g", ".", "whether", "it", "supports", "--", "xml", ")", "but", "can", "be", "used...
train
https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/execution.py#L7-L26
commontk/ctk-cli
ctk_cli/execution.py
listCLIExecutables
def listCLIExecutables(baseDir): """Return list of paths to valid CLI executables within baseDir (non-recursively). This calls `isCLIExecutable()` on all files within `baseDir`.""" return [path for path in glob.glob(os.path.join(os.path.normpath(baseDir), '*')) if isCLIExecutable(path)]
python
def listCLIExecutables(baseDir): """Return list of paths to valid CLI executables within baseDir (non-recursively). This calls `isCLIExecutable()` on all files within `baseDir`.""" return [path for path in glob.glob(os.path.join(os.path.normpath(baseDir), '*')) if isCLIExecutable(path)]
[ "def", "listCLIExecutables", "(", "baseDir", ")", ":", "return", "[", "path", "for", "path", "in", "glob", ".", "glob", "(", "os", ".", "path", ".", "join", "(", "os", ".", "path", ".", "normpath", "(", "baseDir", ")", ",", "'*'", ")", ")", "if", ...
Return list of paths to valid CLI executables within baseDir (non-recursively). This calls `isCLIExecutable()` on all files within `baseDir`.
[ "Return", "list", "of", "paths", "to", "valid", "CLI", "executables", "within", "baseDir", "(", "non", "-", "recursively", ")", ".", "This", "calls", "isCLIExecutable", "()", "on", "all", "files", "within", "baseDir", "." ]
train
https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/execution.py#L29-L33
commontk/ctk-cli
ctk_cli/execution.py
popenCLIExecutable
def popenCLIExecutable(command, **kwargs): """Wrapper around subprocess.Popen constructor that tries to detect Slicer CLI modules and launches them through the Slicer launcher in order to prevent potential DLL dependency issues. Any kwargs are passed on to subprocess.Popen(). If you ever try to use this function to run a CLI, you might want to take a look at https://github.com/hmeine/MeVisLab-CLI/blob/master/Modules/Macros/CTK_CLI/CLIModuleBackend.py (in particular, the CLIExecution class.) Ideally, more of that code would be extracted and moved here, but I have not gotten around to doing that yet. """ cliExecutable = command[0] # hack (at least, this does not scale to other module sources): # detect Slicer modules and run through wrapper script setting up # appropriate runtime environment ma = re_slicerSubPath.search(cliExecutable) if ma: wrapper = os.path.join(cliExecutable[:ma.start()], 'Slicer') if sys.platform.startswith('win'): wrapper += '.exe' if os.path.exists(wrapper): command = [wrapper, '--launcher-no-splash', '--launch'] + command return subprocess.Popen(command, **kwargs)
python
def popenCLIExecutable(command, **kwargs): """Wrapper around subprocess.Popen constructor that tries to detect Slicer CLI modules and launches them through the Slicer launcher in order to prevent potential DLL dependency issues. Any kwargs are passed on to subprocess.Popen(). If you ever try to use this function to run a CLI, you might want to take a look at https://github.com/hmeine/MeVisLab-CLI/blob/master/Modules/Macros/CTK_CLI/CLIModuleBackend.py (in particular, the CLIExecution class.) Ideally, more of that code would be extracted and moved here, but I have not gotten around to doing that yet. """ cliExecutable = command[0] # hack (at least, this does not scale to other module sources): # detect Slicer modules and run through wrapper script setting up # appropriate runtime environment ma = re_slicerSubPath.search(cliExecutable) if ma: wrapper = os.path.join(cliExecutable[:ma.start()], 'Slicer') if sys.platform.startswith('win'): wrapper += '.exe' if os.path.exists(wrapper): command = [wrapper, '--launcher-no-splash', '--launch'] + command return subprocess.Popen(command, **kwargs)
[ "def", "popenCLIExecutable", "(", "command", ",", "*", "*", "kwargs", ")", ":", "cliExecutable", "=", "command", "[", "0", "]", "# hack (at least, this does not scale to other module sources):", "# detect Slicer modules and run through wrapper script setting up", "# appropriate r...
Wrapper around subprocess.Popen constructor that tries to detect Slicer CLI modules and launches them through the Slicer launcher in order to prevent potential DLL dependency issues. Any kwargs are passed on to subprocess.Popen(). If you ever try to use this function to run a CLI, you might want to take a look at https://github.com/hmeine/MeVisLab-CLI/blob/master/Modules/Macros/CTK_CLI/CLIModuleBackend.py (in particular, the CLIExecution class.) Ideally, more of that code would be extracted and moved here, but I have not gotten around to doing that yet.
[ "Wrapper", "around", "subprocess", ".", "Popen", "constructor", "that", "tries", "to", "detect", "Slicer", "CLI", "modules", "and", "launches", "them", "through", "the", "Slicer", "launcher", "in", "order", "to", "prevent", "potential", "DLL", "dependency", "iss...
train
https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/execution.py#L41-L69
commontk/ctk-cli
ctk_cli/execution.py
getXMLDescription
def getXMLDescription(cliExecutable, **kwargs): """Call given cliExecutable with --xml and return xml ElementTree representation of standard output. Any kwargs are passed on to subprocess.Popen() (via popenCLIExecutable()).""" command = [cliExecutable, '--xml'] stdout, stdoutFilename = tempfile.mkstemp('.stdout') stderr, stderrFilename = tempfile.mkstemp('.stderr') try: p = popenCLIExecutable(command, stdout = stdout, stderr = stderr, **kwargs) ec = p.wait() with open(stderrFilename) as f: for line in f: logger.warning('%s: %s' % (os.path.basename(cliExecutable), line[:-1])) if ec: raise RuntimeError("Calling %s failed (exit code %d)" % (cliExecutable, ec)) with open(stdoutFilename) as f: return ET.parse(f) finally: os.close(stdout) os.close(stderr) os.unlink(stdoutFilename) os.unlink(stderrFilename)
python
def getXMLDescription(cliExecutable, **kwargs): """Call given cliExecutable with --xml and return xml ElementTree representation of standard output. Any kwargs are passed on to subprocess.Popen() (via popenCLIExecutable()).""" command = [cliExecutable, '--xml'] stdout, stdoutFilename = tempfile.mkstemp('.stdout') stderr, stderrFilename = tempfile.mkstemp('.stderr') try: p = popenCLIExecutable(command, stdout = stdout, stderr = stderr, **kwargs) ec = p.wait() with open(stderrFilename) as f: for line in f: logger.warning('%s: %s' % (os.path.basename(cliExecutable), line[:-1])) if ec: raise RuntimeError("Calling %s failed (exit code %d)" % (cliExecutable, ec)) with open(stdoutFilename) as f: return ET.parse(f) finally: os.close(stdout) os.close(stderr) os.unlink(stdoutFilename) os.unlink(stderrFilename)
[ "def", "getXMLDescription", "(", "cliExecutable", ",", "*", "*", "kwargs", ")", ":", "command", "=", "[", "cliExecutable", ",", "'--xml'", "]", "stdout", ",", "stdoutFilename", "=", "tempfile", ".", "mkstemp", "(", "'.stdout'", ")", "stderr", ",", "stderrFil...
Call given cliExecutable with --xml and return xml ElementTree representation of standard output. Any kwargs are passed on to subprocess.Popen() (via popenCLIExecutable()).
[ "Call", "given", "cliExecutable", "with", "--", "xml", "and", "return", "xml", "ElementTree", "representation", "of", "standard", "output", "." ]
train
https://github.com/commontk/ctk-cli/blob/ddd8de62b586491ad6e6750133cc1f0e11f37b11/ctk_cli/execution.py#L72-L96
alexwlchan/specktre
src/specktre/utils.py
_candidate_filenames
def _candidate_filenames(): """Generates filenames of the form 'specktre_123AB.png'. The random noise is five characters long, which allows for 62^5 = 916 million possible filenames. """ while True: random_stub = ''.join([ random.choice(string.ascii_letters + string.digits) for _ in range(5) ]) yield 'specktre_%s.png' % random_stub
python
def _candidate_filenames(): """Generates filenames of the form 'specktre_123AB.png'. The random noise is five characters long, which allows for 62^5 = 916 million possible filenames. """ while True: random_stub = ''.join([ random.choice(string.ascii_letters + string.digits) for _ in range(5) ]) yield 'specktre_%s.png' % random_stub
[ "def", "_candidate_filenames", "(", ")", ":", "while", "True", ":", "random_stub", "=", "''", ".", "join", "(", "[", "random", ".", "choice", "(", "string", ".", "ascii_letters", "+", "string", ".", "digits", ")", "for", "_", "in", "range", "(", "5", ...
Generates filenames of the form 'specktre_123AB.png'. The random noise is five characters long, which allows for 62^5 = 916 million possible filenames.
[ "Generates", "filenames", "of", "the", "form", "specktre_123AB", ".", "png", "." ]
train
https://github.com/alexwlchan/specktre/blob/dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc/src/specktre/utils.py#L9-L21
alexwlchan/specktre
examples/draw_tilings.py
draw_tiling
def draw_tiling(coord_generator, filename): """Given a coordinate generator and a filename, render those coordinates in a new image and save them to the file.""" im = Image.new('L', size=(CANVAS_WIDTH, CANVAS_HEIGHT)) for shape in coord_generator(CANVAS_WIDTH, CANVAS_HEIGHT): ImageDraw.Draw(im).polygon(shape, outline='white') im.save(filename)
python
def draw_tiling(coord_generator, filename): """Given a coordinate generator and a filename, render those coordinates in a new image and save them to the file.""" im = Image.new('L', size=(CANVAS_WIDTH, CANVAS_HEIGHT)) for shape in coord_generator(CANVAS_WIDTH, CANVAS_HEIGHT): ImageDraw.Draw(im).polygon(shape, outline='white') im.save(filename)
[ "def", "draw_tiling", "(", "coord_generator", ",", "filename", ")", ":", "im", "=", "Image", ".", "new", "(", "'L'", ",", "size", "=", "(", "CANVAS_WIDTH", ",", "CANVAS_HEIGHT", ")", ")", "for", "shape", "in", "coord_generator", "(", "CANVAS_WIDTH", ",", ...
Given a coordinate generator and a filename, render those coordinates in a new image and save them to the file.
[ "Given", "a", "coordinate", "generator", "and", "a", "filename", "render", "those", "coordinates", "in", "a", "new", "image", "and", "save", "them", "to", "the", "file", "." ]
train
https://github.com/alexwlchan/specktre/blob/dcdd0d5486e5c3f612f64221b2e0dbc6fb7adafc/examples/draw_tilings.py#L20-L26
abn/cafeteria
cafeteria/logging/trace.py
trace
def trace(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'TRACE'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.trace("Houston, we have a %s", "thorny problem", exc_info=1) """ if self.isEnabledFor(TRACE): self._log(TRACE, msg, args, **kwargs)
python
def trace(self, msg, *args, **kwargs): """ Log 'msg % args' with severity 'TRACE'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.trace("Houston, we have a %s", "thorny problem", exc_info=1) """ if self.isEnabledFor(TRACE): self._log(TRACE, msg, args, **kwargs)
[ "def", "trace", "(", "self", ",", "msg", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "isEnabledFor", "(", "TRACE", ")", ":", "self", ".", "_log", "(", "TRACE", ",", "msg", ",", "args", ",", "*", "*", "kwargs", ")" ]
Log 'msg % args' with severity 'TRACE'. To pass exception information, use the keyword argument exc_info with a true value, e.g. logger.trace("Houston, we have a %s", "thorny problem", exc_info=1)
[ "Log", "msg", "%", "args", "with", "severity", "TRACE", "." ]
train
https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/logging/trace.py#L8-L18
myth/pepper8
pepper8/models.py
ResultContainer.add_error
def add_error(self, code, line, char, description): """ Registers an error for this container with code on line at char. :param code: The PEP 8 error code :param line: The line number of the reported error :param char: Line location of first offending character :param description: The human readable description of the thrown error/warning """ if code not in self.violations: self.violations[code] = 0 self.violations[code] += 1 self.lines.append((code, line, char, description))
python
def add_error(self, code, line, char, description): """ Registers an error for this container with code on line at char. :param code: The PEP 8 error code :param line: The line number of the reported error :param char: Line location of first offending character :param description: The human readable description of the thrown error/warning """ if code not in self.violations: self.violations[code] = 0 self.violations[code] += 1 self.lines.append((code, line, char, description))
[ "def", "add_error", "(", "self", ",", "code", ",", "line", ",", "char", ",", "description", ")", ":", "if", "code", "not", "in", "self", ".", "violations", ":", "self", ".", "violations", "[", "code", "]", "=", "0", "self", ".", "violations", "[", ...
Registers an error for this container with code on line at char. :param code: The PEP 8 error code :param line: The line number of the reported error :param char: Line location of first offending character :param description: The human readable description of the thrown error/warning
[ "Registers", "an", "error", "for", "this", "container", "with", "code", "on", "line", "at", "char", ".", ":", "param", "code", ":", "The", "PEP", "8", "error", "code", ":", "param", "line", ":", "The", "line", "number", "of", "the", "reported", "error"...
train
https://github.com/myth/pepper8/blob/98ffed4089241d8d3c1048995bc6777a2f3abdda/pepper8/models.py#L16-L28
abn/cafeteria
cafeteria/utilities.py
listify
def listify(arg): """ Simple utility method to ensure an argument provided is a list. If the provider argument is not an instance of `list`, then we return [arg], else arg is returned. :type arg: list :rtype: list """ if isinstance(arg, (set, tuple)): # if it is a set or tuple make it a list return list(arg) if not isinstance(arg, list): return [arg] return arg
python
def listify(arg): """ Simple utility method to ensure an argument provided is a list. If the provider argument is not an instance of `list`, then we return [arg], else arg is returned. :type arg: list :rtype: list """ if isinstance(arg, (set, tuple)): # if it is a set or tuple make it a list return list(arg) if not isinstance(arg, list): return [arg] return arg
[ "def", "listify", "(", "arg", ")", ":", "if", "isinstance", "(", "arg", ",", "(", "set", ",", "tuple", ")", ")", ":", "# if it is a set or tuple make it a list", "return", "list", "(", "arg", ")", "if", "not", "isinstance", "(", "arg", ",", "list", ")", ...
Simple utility method to ensure an argument provided is a list. If the provider argument is not an instance of `list`, then we return [arg], else arg is returned. :type arg: list :rtype: list
[ "Simple", "utility", "method", "to", "ensure", "an", "argument", "provided", "is", "a", "list", ".", "If", "the", "provider", "argument", "is", "not", "an", "instance", "of", "list", "then", "we", "return", "[", "arg", "]", "else", "arg", "is", "returned...
train
https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/utilities.py#L7-L21
abn/cafeteria
cafeteria/utilities.py
resolve_setting
def resolve_setting(default, arg_value=None, env_var=None, config_value=None): """ Resolves a setting for a configuration option. The winning value is chosen from multiple methods of configuration, in the following order of priority (top first): - Explicitly passed argument - Environment variable - Configuration file entry - Default :param arg_value: Explicitly passed value :param env_var: Environment variable name :type env_var: string or None :param config_value: Configuration entry :param default: Default value to if there are no overriding options :return: Configuration value """ if arg_value is not None: return arg_value else: env_value = getenv(env_var) if env_value is not None: return env_value else: if config_value is not None: return config_value else: return default
python
def resolve_setting(default, arg_value=None, env_var=None, config_value=None): """ Resolves a setting for a configuration option. The winning value is chosen from multiple methods of configuration, in the following order of priority (top first): - Explicitly passed argument - Environment variable - Configuration file entry - Default :param arg_value: Explicitly passed value :param env_var: Environment variable name :type env_var: string or None :param config_value: Configuration entry :param default: Default value to if there are no overriding options :return: Configuration value """ if arg_value is not None: return arg_value else: env_value = getenv(env_var) if env_value is not None: return env_value else: if config_value is not None: return config_value else: return default
[ "def", "resolve_setting", "(", "default", ",", "arg_value", "=", "None", ",", "env_var", "=", "None", ",", "config_value", "=", "None", ")", ":", "if", "arg_value", "is", "not", "None", ":", "return", "arg_value", "else", ":", "env_value", "=", "getenv", ...
Resolves a setting for a configuration option. The winning value is chosen from multiple methods of configuration, in the following order of priority (top first): - Explicitly passed argument - Environment variable - Configuration file entry - Default :param arg_value: Explicitly passed value :param env_var: Environment variable name :type env_var: string or None :param config_value: Configuration entry :param default: Default value to if there are no overriding options :return: Configuration value
[ "Resolves", "a", "setting", "for", "a", "configuration", "option", ".", "The", "winning", "value", "is", "chosen", "from", "multiple", "methods", "of", "configuration", "in", "the", "following", "order", "of", "priority", "(", "top", "first", ")", ":" ]
train
https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/utilities.py#L34-L62
abn/cafeteria
cafeteria/patterns/borg.py
BorgStateManager.get_state
def get_state(cls, clz): """ Retrieve the state of a given Class. :param clz: types.ClassType :return: Class state. :rtype: dict """ if clz not in cls.__shared_state: cls.__shared_state[clz] = ( clz.init_state() if hasattr(clz, "init_state") else {} ) return cls.__shared_state[clz]
python
def get_state(cls, clz): """ Retrieve the state of a given Class. :param clz: types.ClassType :return: Class state. :rtype: dict """ if clz not in cls.__shared_state: cls.__shared_state[clz] = ( clz.init_state() if hasattr(clz, "init_state") else {} ) return cls.__shared_state[clz]
[ "def", "get_state", "(", "cls", ",", "clz", ")", ":", "if", "clz", "not", "in", "cls", ".", "__shared_state", ":", "cls", ".", "__shared_state", "[", "clz", "]", "=", "(", "clz", ".", "init_state", "(", ")", "if", "hasattr", "(", "clz", ",", "\"ini...
Retrieve the state of a given Class. :param clz: types.ClassType :return: Class state. :rtype: dict
[ "Retrieve", "the", "state", "of", "a", "given", "Class", "." ]
train
https://github.com/abn/cafeteria/blob/0a2efb0529484d6da08568f4364daff77f734dfd/cafeteria/patterns/borg.py#L19-L31
tilde-lab/tilde
tilde/core/orm_tools.py
_unique
def _unique(session, cls, queryfunc, constructor, arg, kw): ''' https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/UniqueObject Checks if ORM entity exists according to criteria, if yes, returns it, if no, creates ''' with session.no_autoflush: q = session.query(cls) q = queryfunc(q, *arg, **kw) obj = q.first() if not obj: obj = constructor(*arg, **kw) session.add(obj) return obj
python
def _unique(session, cls, queryfunc, constructor, arg, kw): ''' https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/UniqueObject Checks if ORM entity exists according to criteria, if yes, returns it, if no, creates ''' with session.no_autoflush: q = session.query(cls) q = queryfunc(q, *arg, **kw) obj = q.first() if not obj: obj = constructor(*arg, **kw) session.add(obj) return obj
[ "def", "_unique", "(", "session", ",", "cls", ",", "queryfunc", ",", "constructor", ",", "arg", ",", "kw", ")", ":", "with", "session", ".", "no_autoflush", ":", "q", "=", "session", ".", "query", "(", "cls", ")", "q", "=", "queryfunc", "(", "q", "...
https://bitbucket.org/zzzeek/sqlalchemy/wiki/UsageRecipes/UniqueObject Checks if ORM entity exists according to criteria, if yes, returns it, if no, creates
[ "https", ":", "//", "bitbucket", ".", "org", "/", "zzzeek", "/", "sqlalchemy", "/", "wiki", "/", "UsageRecipes", "/", "UniqueObject", "Checks", "if", "ORM", "entity", "exists", "according", "to", "criteria", "if", "yes", "returns", "it", "if", "no", "creat...
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/orm_tools.py#L19-L32
tilde-lab/tilde
tilde/core/orm_tools.py
_unique_todict
def _unique_todict(session, cls, queryfunc, arg, kw): ''' Checks if ORM entity exists according to criteria, if yes, returns it, if no, returns dict representation (required for further DB replication and syncing) ''' q = session.query(cls) q = queryfunc(q, *arg, **kw) obj = q.first() if not obj: obj = kw obj['__cls__'] = cls.__mapper__.class_.__name__ return obj
python
def _unique_todict(session, cls, queryfunc, arg, kw): ''' Checks if ORM entity exists according to criteria, if yes, returns it, if no, returns dict representation (required for further DB replication and syncing) ''' q = session.query(cls) q = queryfunc(q, *arg, **kw) obj = q.first() if not obj: obj = kw obj['__cls__'] = cls.__mapper__.class_.__name__ return obj
[ "def", "_unique_todict", "(", "session", ",", "cls", ",", "queryfunc", ",", "arg", ",", "kw", ")", ":", "q", "=", "session", ".", "query", "(", "cls", ")", "q", "=", "queryfunc", "(", "q", ",", "*", "arg", ",", "*", "*", "kw", ")", "obj", "=", ...
Checks if ORM entity exists according to criteria, if yes, returns it, if no, returns dict representation (required for further DB replication and syncing)
[ "Checks", "if", "ORM", "entity", "exists", "according", "to", "criteria", "if", "yes", "returns", "it", "if", "no", "returns", "dict", "representation", "(", "required", "for", "further", "DB", "replication", "and", "syncing", ")" ]
train
https://github.com/tilde-lab/tilde/blob/59841578b3503075aa85c76f9ae647b3ff92b0a3/tilde/core/orm_tools.py#L34-L46
oscarlazoarjona/fast
build/lib/fast/symbolic.py
define_density_matrix
def define_density_matrix(Ne, explicitly_hermitian=False, normalized=False, variables=None): r"""Return a symbolic density matrix. The arguments are Ne (integer): The number of atomic states. explicitly_hermitian (boolean): Whether to make $\rho_{ij}=\bar{\rho}_{ij}$ for $i<j$ normalized (boolean): Whether to make $\rho_{11}=1-\sum_{i>1} \rho_{ii}$ A very simple example: >>> define_density_matrix(2) Matrix([ [rho11, rho12], [rho21, rho22]]) The density matrix can be made explicitly hermitian >>> define_density_matrix(2, explicitly_hermitian=True) Matrix([ [rho11, conjugate(rho21)], [rho21, rho22]]) or normalized >>> define_density_matrix(2, normalized=True) Matrix([ [-rho22 + 1, rho12], [ rho21, rho22]]) or it can be made an explicit function of given variables >>> from sympy import symbols >>> t, z = symbols("t, z", positive=True) >>> define_density_matrix(2, variables=[t, z]) Matrix([ [rho11(t, z), rho12(t, z)], [rho21(t, z), rho22(t, z)]]) """ if Ne > 9: comma = "," name = r"\rho" open_brace = "_{" close_brace = "}" else: comma = "" name = "rho" open_brace = "" close_brace = "" rho = [] for i in range(Ne): row_rho = [] for j in range(Ne): if i == j: row_rho += [define_symbol(name, open_brace, comma, i, j, close_brace, variables, positive=True)] elif i > j: row_rho += [define_symbol(name, open_brace, comma, i, j, close_brace, variables)] else: if explicitly_hermitian: row_rho += [conjugate(define_symbol(name, open_brace, comma, j, i, close_brace, variables))] else: row_rho += [define_symbol(name, open_brace, comma, i, j, close_brace, variables)] rho += [row_rho] if normalized: rho11 = 1-sum([rho[i][i] for i in range(1, Ne)]) rho[0][0] = rho11 rho = Matrix(rho) return rho
python
def define_density_matrix(Ne, explicitly_hermitian=False, normalized=False, variables=None): r"""Return a symbolic density matrix. The arguments are Ne (integer): The number of atomic states. explicitly_hermitian (boolean): Whether to make $\rho_{ij}=\bar{\rho}_{ij}$ for $i<j$ normalized (boolean): Whether to make $\rho_{11}=1-\sum_{i>1} \rho_{ii}$ A very simple example: >>> define_density_matrix(2) Matrix([ [rho11, rho12], [rho21, rho22]]) The density matrix can be made explicitly hermitian >>> define_density_matrix(2, explicitly_hermitian=True) Matrix([ [rho11, conjugate(rho21)], [rho21, rho22]]) or normalized >>> define_density_matrix(2, normalized=True) Matrix([ [-rho22 + 1, rho12], [ rho21, rho22]]) or it can be made an explicit function of given variables >>> from sympy import symbols >>> t, z = symbols("t, z", positive=True) >>> define_density_matrix(2, variables=[t, z]) Matrix([ [rho11(t, z), rho12(t, z)], [rho21(t, z), rho22(t, z)]]) """ if Ne > 9: comma = "," name = r"\rho" open_brace = "_{" close_brace = "}" else: comma = "" name = "rho" open_brace = "" close_brace = "" rho = [] for i in range(Ne): row_rho = [] for j in range(Ne): if i == j: row_rho += [define_symbol(name, open_brace, comma, i, j, close_brace, variables, positive=True)] elif i > j: row_rho += [define_symbol(name, open_brace, comma, i, j, close_brace, variables)] else: if explicitly_hermitian: row_rho += [conjugate(define_symbol(name, open_brace, comma, j, i, close_brace, variables))] else: row_rho += [define_symbol(name, open_brace, comma, i, j, close_brace, variables)] rho += [row_rho] if normalized: rho11 = 1-sum([rho[i][i] for i in range(1, Ne)]) rho[0][0] = rho11 rho = Matrix(rho) return rho
[ "def", "define_density_matrix", "(", "Ne", ",", "explicitly_hermitian", "=", "False", ",", "normalized", "=", "False", ",", "variables", "=", "None", ")", ":", "if", "Ne", ">", "9", ":", "comma", "=", "\",\"", "name", "=", "r\"\\rho\"", "open_brace", "=", ...
r"""Return a symbolic density matrix. The arguments are Ne (integer): The number of atomic states. explicitly_hermitian (boolean): Whether to make $\rho_{ij}=\bar{\rho}_{ij}$ for $i<j$ normalized (boolean): Whether to make $\rho_{11}=1-\sum_{i>1} \rho_{ii}$ A very simple example: >>> define_density_matrix(2) Matrix([ [rho11, rho12], [rho21, rho22]]) The density matrix can be made explicitly hermitian >>> define_density_matrix(2, explicitly_hermitian=True) Matrix([ [rho11, conjugate(rho21)], [rho21, rho22]]) or normalized >>> define_density_matrix(2, normalized=True) Matrix([ [-rho22 + 1, rho12], [ rho21, rho22]]) or it can be made an explicit function of given variables >>> from sympy import symbols >>> t, z = symbols("t, z", positive=True) >>> define_density_matrix(2, variables=[t, z]) Matrix([ [rho11(t, z), rho12(t, z)], [rho21(t, z), rho22(t, z)]])
[ "r", "Return", "a", "symbolic", "density", "matrix", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/symbolic.py#L72-L150
oscarlazoarjona/fast
build/lib/fast/symbolic.py
define_laser_variables
def define_laser_variables(Nl, real_amplitudes=False, variables=None): r"""Return the amplitudes and frequencies of Nl fields. >>> E0, omega_laser = define_laser_variables(2) >>> E0, omega_laser ([E_0^1, E_0^2], [varpi_1, varpi_2]) The amplitudes are complex by default: >>> conjugate(E0[0]) conjugate(E_0^1) But they can optionally be made real: >>> E0, omega_laser = define_laser_variables(2, real_amplitudes=True) >>> conjugate(E0[0]) E_0^1 They can also be made explicit functions of given variables: >>> from sympy import symbols >>> t, z = symbols("t, z", real=True) >>> E0, omega_laser = define_laser_variables(2, variables=[t, z]) >>> E0 [E_0^1(t, z), E_0^2(t, z)] """ if variables is None: E0 = [Symbol(r"E_0^"+str(l+1), real=real_amplitudes) for l in range(Nl)] else: E0 = [Function(r"E_0^"+str(l+1), real=real_amplitudes)(*variables) for l in range(Nl)] omega_laser = [Symbol(r"varpi_"+str(l+1), positive=True) for l in range(Nl)] return E0, omega_laser
python
def define_laser_variables(Nl, real_amplitudes=False, variables=None): r"""Return the amplitudes and frequencies of Nl fields. >>> E0, omega_laser = define_laser_variables(2) >>> E0, omega_laser ([E_0^1, E_0^2], [varpi_1, varpi_2]) The amplitudes are complex by default: >>> conjugate(E0[0]) conjugate(E_0^1) But they can optionally be made real: >>> E0, omega_laser = define_laser_variables(2, real_amplitudes=True) >>> conjugate(E0[0]) E_0^1 They can also be made explicit functions of given variables: >>> from sympy import symbols >>> t, z = symbols("t, z", real=True) >>> E0, omega_laser = define_laser_variables(2, variables=[t, z]) >>> E0 [E_0^1(t, z), E_0^2(t, z)] """ if variables is None: E0 = [Symbol(r"E_0^"+str(l+1), real=real_amplitudes) for l in range(Nl)] else: E0 = [Function(r"E_0^"+str(l+1), real=real_amplitudes)(*variables) for l in range(Nl)] omega_laser = [Symbol(r"varpi_"+str(l+1), positive=True) for l in range(Nl)] return E0, omega_laser
[ "def", "define_laser_variables", "(", "Nl", ",", "real_amplitudes", "=", "False", ",", "variables", "=", "None", ")", ":", "if", "variables", "is", "None", ":", "E0", "=", "[", "Symbol", "(", "r\"E_0^\"", "+", "str", "(", "l", "+", "1", ")", ",", "re...
r"""Return the amplitudes and frequencies of Nl fields. >>> E0, omega_laser = define_laser_variables(2) >>> E0, omega_laser ([E_0^1, E_0^2], [varpi_1, varpi_2]) The amplitudes are complex by default: >>> conjugate(E0[0]) conjugate(E_0^1) But they can optionally be made real: >>> E0, omega_laser = define_laser_variables(2, real_amplitudes=True) >>> conjugate(E0[0]) E_0^1 They can also be made explicit functions of given variables: >>> from sympy import symbols >>> t, z = symbols("t, z", real=True) >>> E0, omega_laser = define_laser_variables(2, variables=[t, z]) >>> E0 [E_0^1(t, z), E_0^2(t, z)]
[ "r", "Return", "the", "amplitudes", "and", "frequencies", "of", "Nl", "fields", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/symbolic.py#L153-L186
oscarlazoarjona/fast
build/lib/fast/symbolic.py
polarization_vector
def polarization_vector(phi, theta, alpha, beta, p): r"""This function returns a unitary vector describing the polarization of plane waves. It recieves as arguments: phi .- The spherical coordinates azimuthal angle of the wave vector k. theta .- The spherical coordinates polar angle of the wave vector k. alpha .- The rotation of a half-wave plate. beta .- The rotation of a quarter-wave plate. p .- either 1 or -1 to indicate whether to return epsilon^(+) or epsilon^(-) respectively. If alpha and beta are zero, the result will be linearly polarized light along some fast axis. alpha and beta are measured from that fast axis. Propagation towards y, linear polarization (for pi transitions): >>> from sympy import pi >>> polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta= 0,p=1) Matrix([ [0], [0], [1]]) Propagation towards +z, circular polarization (for sigma + transitions): >>> polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p=1) Matrix([ [ -sqrt(2)/2], [-sqrt(2)*I/2], [ 0]]) Propagation towards -z, circular polarization for sigma + transitions: >>> polarization_vector(phi=0, theta=pi, alpha= 0, beta=-pi/8,p=1) Matrix([ [ -sqrt(2)/2], [-sqrt(2)*I/2], [ 0]]) Components + and - are complex conjugates of each other >>> from sympy import symbols >>> phi, theta, alpha, beta = symbols("phi theta alpha beta", real=True) >>> ep = polarization_vector(phi,theta,alpha,beta, 1) >>> em = polarization_vector(phi,theta,alpha,beta,-1) >>> ep-em.conjugate() Matrix([ [0], [0], [0]]) """ epsilon = Matrix([cos(2*beta), p*I*sin(2*beta), 0]) R1 = Matrix([[cos(2*alpha), -sin(2*alpha), 0], [sin(2*alpha), cos(2*alpha), 0], [0, 0, 1]]) R2 = Matrix([[cos(theta), 0, sin(theta)], [0, 1, 0], [-sin(theta), 0, cos(theta)]]) R3 = Matrix([[cos(phi), -sin(phi), 0], [sin(phi), cos(phi), 0], [0, 0, 1]]) return R3*R2*R1*epsilon
python
def polarization_vector(phi, theta, alpha, beta, p): r"""This function returns a unitary vector describing the polarization of plane waves. It recieves as arguments: phi .- The spherical coordinates azimuthal angle of the wave vector k. theta .- The spherical coordinates polar angle of the wave vector k. alpha .- The rotation of a half-wave plate. beta .- The rotation of a quarter-wave plate. p .- either 1 or -1 to indicate whether to return epsilon^(+) or epsilon^(-) respectively. If alpha and beta are zero, the result will be linearly polarized light along some fast axis. alpha and beta are measured from that fast axis. Propagation towards y, linear polarization (for pi transitions): >>> from sympy import pi >>> polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta= 0,p=1) Matrix([ [0], [0], [1]]) Propagation towards +z, circular polarization (for sigma + transitions): >>> polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p=1) Matrix([ [ -sqrt(2)/2], [-sqrt(2)*I/2], [ 0]]) Propagation towards -z, circular polarization for sigma + transitions: >>> polarization_vector(phi=0, theta=pi, alpha= 0, beta=-pi/8,p=1) Matrix([ [ -sqrt(2)/2], [-sqrt(2)*I/2], [ 0]]) Components + and - are complex conjugates of each other >>> from sympy import symbols >>> phi, theta, alpha, beta = symbols("phi theta alpha beta", real=True) >>> ep = polarization_vector(phi,theta,alpha,beta, 1) >>> em = polarization_vector(phi,theta,alpha,beta,-1) >>> ep-em.conjugate() Matrix([ [0], [0], [0]]) """ epsilon = Matrix([cos(2*beta), p*I*sin(2*beta), 0]) R1 = Matrix([[cos(2*alpha), -sin(2*alpha), 0], [sin(2*alpha), cos(2*alpha), 0], [0, 0, 1]]) R2 = Matrix([[cos(theta), 0, sin(theta)], [0, 1, 0], [-sin(theta), 0, cos(theta)]]) R3 = Matrix([[cos(phi), -sin(phi), 0], [sin(phi), cos(phi), 0], [0, 0, 1]]) return R3*R2*R1*epsilon
[ "def", "polarization_vector", "(", "phi", ",", "theta", ",", "alpha", ",", "beta", ",", "p", ")", ":", "epsilon", "=", "Matrix", "(", "[", "cos", "(", "2", "*", "beta", ")", ",", "p", "*", "I", "*", "sin", "(", "2", "*", "beta", ")", ",", "0"...
r"""This function returns a unitary vector describing the polarization of plane waves. It recieves as arguments: phi .- The spherical coordinates azimuthal angle of the wave vector k. theta .- The spherical coordinates polar angle of the wave vector k. alpha .- The rotation of a half-wave plate. beta .- The rotation of a quarter-wave plate. p .- either 1 or -1 to indicate whether to return epsilon^(+) or epsilon^(-) respectively. If alpha and beta are zero, the result will be linearly polarized light along some fast axis. alpha and beta are measured from that fast axis. Propagation towards y, linear polarization (for pi transitions): >>> from sympy import pi >>> polarization_vector(phi=pi/2, theta=pi/2, alpha=pi/2, beta= 0,p=1) Matrix([ [0], [0], [1]]) Propagation towards +z, circular polarization (for sigma + transitions): >>> polarization_vector(phi=0, theta= 0, alpha=pi/2, beta= pi/8,p=1) Matrix([ [ -sqrt(2)/2], [-sqrt(2)*I/2], [ 0]]) Propagation towards -z, circular polarization for sigma + transitions: >>> polarization_vector(phi=0, theta=pi, alpha= 0, beta=-pi/8,p=1) Matrix([ [ -sqrt(2)/2], [-sqrt(2)*I/2], [ 0]]) Components + and - are complex conjugates of each other >>> from sympy import symbols >>> phi, theta, alpha, beta = symbols("phi theta alpha beta", real=True) >>> ep = polarization_vector(phi,theta,alpha,beta, 1) >>> em = polarization_vector(phi,theta,alpha,beta,-1) >>> ep-em.conjugate() Matrix([ [0], [0], [0]])
[ "r", "This", "function", "returns", "a", "unitary", "vector", "describing", "the", "polarization", "of", "plane", "waves", ".", "It", "recieves", "as", "arguments", ":" ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/symbolic.py#L189-L251
oscarlazoarjona/fast
build/lib/fast/symbolic.py
lindblad_operator
def lindblad_operator(A, rho): r"""This function returns the action of a Lindblad operator A on a density matrix rho. This is defined as : L(A,rho) = A*rho*A.adjoint() - (A.adjoint()*A*rho + rho*A.adjoint()*A)/2. >>> rho=define_density_matrix(3) >>> lindblad_operator( ketbra(1,2,3) ,rho ) Matrix([ [ rho22, -rho12/2, 0], [-rho21/2, -rho22, -rho23/2], [ 0, -rho32/2, 0]]) """ return A*rho*A.adjoint() - (A.adjoint()*A*rho + rho*A.adjoint()*A)/2
python
def lindblad_operator(A, rho): r"""This function returns the action of a Lindblad operator A on a density matrix rho. This is defined as : L(A,rho) = A*rho*A.adjoint() - (A.adjoint()*A*rho + rho*A.adjoint()*A)/2. >>> rho=define_density_matrix(3) >>> lindblad_operator( ketbra(1,2,3) ,rho ) Matrix([ [ rho22, -rho12/2, 0], [-rho21/2, -rho22, -rho23/2], [ 0, -rho32/2, 0]]) """ return A*rho*A.adjoint() - (A.adjoint()*A*rho + rho*A.adjoint()*A)/2
[ "def", "lindblad_operator", "(", "A", ",", "rho", ")", ":", "return", "A", "*", "rho", "*", "A", ".", "adjoint", "(", ")", "-", "(", "A", ".", "adjoint", "(", ")", "*", "A", "*", "rho", "+", "rho", "*", "A", ".", "adjoint", "(", ")", "*", "...
r"""This function returns the action of a Lindblad operator A on a density matrix rho. This is defined as : L(A,rho) = A*rho*A.adjoint() - (A.adjoint()*A*rho + rho*A.adjoint()*A)/2. >>> rho=define_density_matrix(3) >>> lindblad_operator( ketbra(1,2,3) ,rho ) Matrix([ [ rho22, -rho12/2, 0], [-rho21/2, -rho22, -rho23/2], [ 0, -rho32/2, 0]])
[ "r", "This", "function", "returns", "the", "action", "of", "a", "Lindblad", "operator", "A", "on", "a", "density", "matrix", "rho", ".", "This", "is", "defined", "as", ":", "L", "(", "A", "rho", ")", "=", "A", "*", "rho", "*", "A", ".", "adjoint", ...
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/build/lib/fast/symbolic.py#L551-L565
deployed/django-emailtemplates
emailtemplates/helpers.py
mass_mailing_recipients
def mass_mailing_recipients(): """ Returns iterable of all mass email recipients. Default behavior will be to return list of all active users' emails. This can be changed by providing callback in settings return some other list of users, when user emails are stored in many, non default models. To accomplish that add constant MASS_EMAIL_RECIPIENTS to settings. It should contain path to function, e.g. >>> MASS_EMAIL_RECIPIENTS = 'emailtemplates.helpers.mass_mailing_recipients' :rtype iterable """ if hasattr(settings, 'MASS_EMAIL_RECIPIENTS'): callback_name = settings.MASS_EMAIL_RECIPIENTS.split('.') module_name = '.'.join(callback_name[:-1]) func_name = callback_name[-1] module = import_module(module_name) func = getattr(module, func_name, lambda: []) return func() User = get_user_model() if hasattr(User, 'is_active') and hasattr(User, 'email'): filtered_users = User.objects.filter(is_active=True).exclude(email__isnull=True).exclude(email__exact='') return filtered_users.values_list('email', flat=True).distinct() return []
python
def mass_mailing_recipients(): """ Returns iterable of all mass email recipients. Default behavior will be to return list of all active users' emails. This can be changed by providing callback in settings return some other list of users, when user emails are stored in many, non default models. To accomplish that add constant MASS_EMAIL_RECIPIENTS to settings. It should contain path to function, e.g. >>> MASS_EMAIL_RECIPIENTS = 'emailtemplates.helpers.mass_mailing_recipients' :rtype iterable """ if hasattr(settings, 'MASS_EMAIL_RECIPIENTS'): callback_name = settings.MASS_EMAIL_RECIPIENTS.split('.') module_name = '.'.join(callback_name[:-1]) func_name = callback_name[-1] module = import_module(module_name) func = getattr(module, func_name, lambda: []) return func() User = get_user_model() if hasattr(User, 'is_active') and hasattr(User, 'email'): filtered_users = User.objects.filter(is_active=True).exclude(email__isnull=True).exclude(email__exact='') return filtered_users.values_list('email', flat=True).distinct() return []
[ "def", "mass_mailing_recipients", "(", ")", ":", "if", "hasattr", "(", "settings", ",", "'MASS_EMAIL_RECIPIENTS'", ")", ":", "callback_name", "=", "settings", ".", "MASS_EMAIL_RECIPIENTS", ".", "split", "(", "'.'", ")", "module_name", "=", "'.'", ".", "join", ...
Returns iterable of all mass email recipients. Default behavior will be to return list of all active users' emails. This can be changed by providing callback in settings return some other list of users, when user emails are stored in many, non default models. To accomplish that add constant MASS_EMAIL_RECIPIENTS to settings. It should contain path to function, e.g. >>> MASS_EMAIL_RECIPIENTS = 'emailtemplates.helpers.mass_mailing_recipients' :rtype iterable
[ "Returns", "iterable", "of", "all", "mass", "email", "recipients", ".", "Default", "behavior", "will", "be", "to", "return", "list", "of", "all", "active", "users", "emails", ".", "This", "can", "be", "changed", "by", "providing", "callback", "in", "settings...
train
https://github.com/deployed/django-emailtemplates/blob/0e95139989dbcf7e624153ddcd7b5b66b48eb6eb/emailtemplates/helpers.py#L47-L69
oscarlazoarjona/fast
fast/graphic.py
complex_matrix_plot
def complex_matrix_plot(A, logA=False, normalize=False, plot=True, **kwds): r"""A function to plot complex matrices.""" N = len(A[0]) if logA: Anew = [] for i in range(N): row = [] for j in range(N): if A[i][j] != 0: row += [log(log(A[i][j]))] else: row += [0.0] Anew += [row] A = Anew[:] # A=[[log(A[i][j]) for j in range(N)] for i in range(N)] if normalize: norm = 1 for i in range(N): for j in range(N): if abs(A[i][j]) > norm: norm = abs(A[i][j]) A = [[A[i][j]/norm for j in range(N)]for i in range(N)] # print A color_matrix = [] lmax = -1 for i in range(N): row = [] for j in range(N): rgb, l = complex_to_color(A[i][j]) row += [rgb] if l > lmax: lmax = l color_matrix += [row] if normalize: color_matrix = [[tuple([k/lmax for k in color_matrix[i][j]]) for j in range(N)] for i in range(N)] if plot: pyplot.imshow(color_matrix, interpolation='none') pyplot.savefig('a.png', bbox_inches='tight') pyplot.close('all') else: return color_matrix
python
def complex_matrix_plot(A, logA=False, normalize=False, plot=True, **kwds): r"""A function to plot complex matrices.""" N = len(A[0]) if logA: Anew = [] for i in range(N): row = [] for j in range(N): if A[i][j] != 0: row += [log(log(A[i][j]))] else: row += [0.0] Anew += [row] A = Anew[:] # A=[[log(A[i][j]) for j in range(N)] for i in range(N)] if normalize: norm = 1 for i in range(N): for j in range(N): if abs(A[i][j]) > norm: norm = abs(A[i][j]) A = [[A[i][j]/norm for j in range(N)]for i in range(N)] # print A color_matrix = [] lmax = -1 for i in range(N): row = [] for j in range(N): rgb, l = complex_to_color(A[i][j]) row += [rgb] if l > lmax: lmax = l color_matrix += [row] if normalize: color_matrix = [[tuple([k/lmax for k in color_matrix[i][j]]) for j in range(N)] for i in range(N)] if plot: pyplot.imshow(color_matrix, interpolation='none') pyplot.savefig('a.png', bbox_inches='tight') pyplot.close('all') else: return color_matrix
[ "def", "complex_matrix_plot", "(", "A", ",", "logA", "=", "False", ",", "normalize", "=", "False", ",", "plot", "=", "True", ",", "*", "*", "kwds", ")", ":", "N", "=", "len", "(", "A", "[", "0", "]", ")", "if", "logA", ":", "Anew", "=", "[", ...
r"""A function to plot complex matrices.
[ "r", "A", "function", "to", "plot", "complex", "matrices", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L64-L109
oscarlazoarjona/fast
fast/graphic.py
bar_chart_mf
def bar_chart_mf(data, path_name): """Make a bar chart for data on MF quantities.""" N = len(data) ind = np.arange(N) # the x locations for the groups width = 0.8 # the width of the bars fig, ax = pyplot.subplots() rects1 = ax.bar(ind, data, width, color='g') # add some text for labels, title and axes ticks ax.set_ylabel('Population') ax.set_xticks(ind+width/2) labs = ['m='+str(i) for i in range(-N/2+1, N/2+1)] ax.set_xticklabels(labs) def autolabel(rects): # attach some text labels for rect in rects: rect.get_height() autolabel(rects1) pyplot.savefig(path_name) pyplot.close()
python
def bar_chart_mf(data, path_name): """Make a bar chart for data on MF quantities.""" N = len(data) ind = np.arange(N) # the x locations for the groups width = 0.8 # the width of the bars fig, ax = pyplot.subplots() rects1 = ax.bar(ind, data, width, color='g') # add some text for labels, title and axes ticks ax.set_ylabel('Population') ax.set_xticks(ind+width/2) labs = ['m='+str(i) for i in range(-N/2+1, N/2+1)] ax.set_xticklabels(labs) def autolabel(rects): # attach some text labels for rect in rects: rect.get_height() autolabel(rects1) pyplot.savefig(path_name) pyplot.close()
[ "def", "bar_chart_mf", "(", "data", ",", "path_name", ")", ":", "N", "=", "len", "(", "data", ")", "ind", "=", "np", ".", "arange", "(", "N", ")", "# the x locations for the groups\r", "width", "=", "0.8", "# the width of the bars\r", "fig", ",", "ax", "="...
Make a bar chart for data on MF quantities.
[ "Make", "a", "bar", "chart", "for", "data", "on", "MF", "quantities", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L476-L499
oscarlazoarjona/fast
fast/graphic.py
draw_plane_wave_3d
def draw_plane_wave_3d(ax, beam, dist_to_center=0): """Draw the polarization of a plane wave.""" Ex = []; Ey = []; Ez = [] k = [cos(beam.phi)*sin(beam.theta), sin(beam.phi)*sin(beam.theta), cos(beam.theta)] kx, ky, kz = k Nt = 1000 tstep = 7*pi/4/(Nt-1) alpha = beam.alpha beta = beam.beta phi = beam.phi theta = beam.theta omega = 1 for i in range(Nt): t = i*tstep Ex += [(cos(2*alpha)*cos(phi)*cos(theta) - sin(2*alpha)*sin(phi))*cos(omega*t)*cos(2*beta) - (cos(phi)*cos(theta)*sin(2*alpha) + cos(2*alpha)*sin(phi))*sin(omega*t)*sin(2*beta) - dist_to_center*kx] Ey += [(cos(2*alpha)*cos(theta)*sin(phi) + cos(phi)*sin(2*alpha))*cos(omega*t)*cos(2*beta) - (cos(theta)*sin(2*alpha)*sin(phi) - cos(2*alpha)*cos(phi))*sin(omega*t)*sin(2*beta) - dist_to_center*ky] Ez += [-cos(omega*t)*cos(2*alpha)*cos(2*beta)*sin(theta) + sin(omega*t)*sin(2*alpha)*sin(2*beta)*sin(theta) - dist_to_center*kz] ax.plot(Ex, Ey, Ez, beam.color+'-') ff = dist_to_center-1.0 arrx = [-kx*dist_to_center, -kx*ff] arry = [-ky*dist_to_center, -ky*ff] arrz = [-kz*dist_to_center, -kz*ff] arrow = Arrow3D(arrx, arry, arrz, mutation_scale=20, lw=1, arrowstyle="-|>", color=beam.color) ax.add_artist(arrow) ax.plot([Ex[-1]], [Ey[-1]], [Ez[-1]], '.', markersize=8, color=beam.color)
python
def draw_plane_wave_3d(ax, beam, dist_to_center=0): """Draw the polarization of a plane wave.""" Ex = []; Ey = []; Ez = [] k = [cos(beam.phi)*sin(beam.theta), sin(beam.phi)*sin(beam.theta), cos(beam.theta)] kx, ky, kz = k Nt = 1000 tstep = 7*pi/4/(Nt-1) alpha = beam.alpha beta = beam.beta phi = beam.phi theta = beam.theta omega = 1 for i in range(Nt): t = i*tstep Ex += [(cos(2*alpha)*cos(phi)*cos(theta) - sin(2*alpha)*sin(phi))*cos(omega*t)*cos(2*beta) - (cos(phi)*cos(theta)*sin(2*alpha) + cos(2*alpha)*sin(phi))*sin(omega*t)*sin(2*beta) - dist_to_center*kx] Ey += [(cos(2*alpha)*cos(theta)*sin(phi) + cos(phi)*sin(2*alpha))*cos(omega*t)*cos(2*beta) - (cos(theta)*sin(2*alpha)*sin(phi) - cos(2*alpha)*cos(phi))*sin(omega*t)*sin(2*beta) - dist_to_center*ky] Ez += [-cos(omega*t)*cos(2*alpha)*cos(2*beta)*sin(theta) + sin(omega*t)*sin(2*alpha)*sin(2*beta)*sin(theta) - dist_to_center*kz] ax.plot(Ex, Ey, Ez, beam.color+'-') ff = dist_to_center-1.0 arrx = [-kx*dist_to_center, -kx*ff] arry = [-ky*dist_to_center, -ky*ff] arrz = [-kz*dist_to_center, -kz*ff] arrow = Arrow3D(arrx, arry, arrz, mutation_scale=20, lw=1, arrowstyle="-|>", color=beam.color) ax.add_artist(arrow) ax.plot([Ex[-1]], [Ey[-1]], [Ez[-1]], '.', markersize=8, color=beam.color)
[ "def", "draw_plane_wave_3d", "(", "ax", ",", "beam", ",", "dist_to_center", "=", "0", ")", ":", "Ex", "=", "[", "]", "Ey", "=", "[", "]", "Ez", "=", "[", "]", "k", "=", "[", "cos", "(", "beam", ".", "phi", ")", "*", "sin", "(", "beam", ".", ...
Draw the polarization of a plane wave.
[ "Draw", "the", "polarization", "of", "a", "plane", "wave", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L528-L574
oscarlazoarjona/fast
fast/graphic.py
draw_lasers_3d
def draw_lasers_3d(ax, lasers, name=None, distances=None, lim=None): """Draw MOT lasers in 3d.""" if distances is None: distances = [1.0 for i in range(len(lasers))] for i in range(len(lasers)): if type(lasers[i]) == PlaneWave: draw_plane_wave_3d(ax, lasers[i], distances[i]) elif type(lasers[i]) == MotField: draw_mot_field_3d(ax, lasers[i], distances[i]) ax.set_xlabel(r"$x$", fontsize=20) ax.set_ylabel(r"$y$", fontsize=20) ax.set_zlabel(r"$z$", fontsize=20) if lim is None: lim = sqrt(2.0) ax.set_xlim(-lim, lim) ax.set_ylim(-lim, lim) ax.set_zlim(-lim, lim) ax.set_aspect("equal") if name is not None: pyplot.savefig(name, bbox_inches='tight')
python
def draw_lasers_3d(ax, lasers, name=None, distances=None, lim=None): """Draw MOT lasers in 3d.""" if distances is None: distances = [1.0 for i in range(len(lasers))] for i in range(len(lasers)): if type(lasers[i]) == PlaneWave: draw_plane_wave_3d(ax, lasers[i], distances[i]) elif type(lasers[i]) == MotField: draw_mot_field_3d(ax, lasers[i], distances[i]) ax.set_xlabel(r"$x$", fontsize=20) ax.set_ylabel(r"$y$", fontsize=20) ax.set_zlabel(r"$z$", fontsize=20) if lim is None: lim = sqrt(2.0) ax.set_xlim(-lim, lim) ax.set_ylim(-lim, lim) ax.set_zlim(-lim, lim) ax.set_aspect("equal") if name is not None: pyplot.savefig(name, bbox_inches='tight')
[ "def", "draw_lasers_3d", "(", "ax", ",", "lasers", ",", "name", "=", "None", ",", "distances", "=", "None", ",", "lim", "=", "None", ")", ":", "if", "distances", "is", "None", ":", "distances", "=", "[", "1.0", "for", "i", "in", "range", "(", "len"...
Draw MOT lasers in 3d.
[ "Draw", "MOT", "lasers", "in", "3d", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L583-L604
oscarlazoarjona/fast
fast/graphic.py
plot_populations
def plot_populations(path, name, Ne, states=None, filename='a.png', fontsize=12, absolute_frequency=True, save_path='', use_netcdf=True): r"""Plot the populations of a density matrix.""" pyplot.close("all") dat = read_result(path, name, N=Ne, use_netcdf=use_netcdf) x = dat[0] if absolute_frequency: x = [xi/2/pi for xi in x] pop = dat[1:Ne] Nd = len(pop[0]) pop1 = [1-sum([pop[j][i] for j in range(Ne-1)]) for i in range(Nd)] pop = [pop1]+pop # We do different things depending on what states we are given. if states is None: # If we recieve no states all populations are ploted. for i in range(Ne): lab = r"$\mathrm{Poblaci\'on} \ " + str(i+1)+"$" pyplot.plot(x, pop[i], label=lab) pyplot.legend(fontsize=fontsize) pyplot.savefig(save_path+filename, bbox_inches='tight') pyplot.close('all') elif len(states[0].quantum_numbers) >= 5: # If we recieve magnetic states we make a plot # for each hyperfine state. magnetic_plots = len(states[0].quantum_numbers) == 6 if not magnetic_plots: N_plots = len(states) states = split_hyperfine_to_magnetic(states) aux = [hsv_to_rgb(m*0.8/(N_plots-1), 1.0, 1.0) for m in range(N_plots)] hyperfine_colors = list(reversed(aux)) conta = 0 fine_states = find_fine_states(states) boundaries = reversed(calculate_boundaries(fine_states, states)[1]) boundaries = list(boundaries) for pair in boundaries: f = states[pair[0]].f if f == 0: colors = [(0.8, 0.0, 1.0)] else: aux = [hsv_to_rgb(m*0.8/f, 1.0, 1.0) for m in range(f+1)] colors = list(reversed(aux)) for i in range(pair[0], pair[1]): m = states[i].m if m < 0: color = colors[-m] style = ':' else: color = colors[m] style = '-' if magnetic_plots: aux = r"$\mathrm{Poblaci\'on} \ M_F=" aux += str(states[i].m)+"$" pyplot.plot(x, pop[i], style, label=aux, color=color) if magnetic_plots: if f != 0: suma = [sum([pop[i][j] for i in range(pair[0], pair[1])]) for j in range(len(pop[0]))] pyplot.plot(x, suma, 'k-', label=r'$\mathrm{suma}$') aux = str(states[i]).split()[1].replace('_', '') filenamei = aux.replace('/', '_').replace('^', 'F=') s = filenamei.find(',') filenamei = filenamei[:s] filenamei = name+'_'+filenamei+'.png' aux = find_fine_states([states[i]])[0] title = aux._latex_()+'\ F='+str(states[i].f) pyplot.title(r"$"+title+"$") pyplot.ylim([0, None]) pyplot.xlim([x[0], x[-1]]) pyplot.legend(fontsize=fontsize, loc=0) pyplot.savefig(save_path+filenamei, bbox_inches='tight') pyplot.close('all') else: suma = [sum([pop[i][j] for i in range(pair[0], pair[1])]) for j in range(len(pop[0]))] label = states[i]._latex_() label = label[label.find(' ')+1:] label = label[:label.find('^')] label += r"\ F="+str(states[i].f) label = "$"+label+"$" pyplot.plot(x, suma, '-', color=hyperfine_colors[conta], label=label) conta += 1 if not magnetic_plots: title = states[0]._latex_() title = "$"+title[:title.find(' ')-1]+"$" pyplot.title(title, fontsize=20) pyplot.xlim([x[0], x[-1]]) pyplot.legend(fontsize=fontsize, loc=0) pyplot.savefig(save_path+name+'_pops.png', bbox_inches='tight') pyplot.close('all')
python
def plot_populations(path, name, Ne, states=None, filename='a.png', fontsize=12, absolute_frequency=True, save_path='', use_netcdf=True): r"""Plot the populations of a density matrix.""" pyplot.close("all") dat = read_result(path, name, N=Ne, use_netcdf=use_netcdf) x = dat[0] if absolute_frequency: x = [xi/2/pi for xi in x] pop = dat[1:Ne] Nd = len(pop[0]) pop1 = [1-sum([pop[j][i] for j in range(Ne-1)]) for i in range(Nd)] pop = [pop1]+pop # We do different things depending on what states we are given. if states is None: # If we recieve no states all populations are ploted. for i in range(Ne): lab = r"$\mathrm{Poblaci\'on} \ " + str(i+1)+"$" pyplot.plot(x, pop[i], label=lab) pyplot.legend(fontsize=fontsize) pyplot.savefig(save_path+filename, bbox_inches='tight') pyplot.close('all') elif len(states[0].quantum_numbers) >= 5: # If we recieve magnetic states we make a plot # for each hyperfine state. magnetic_plots = len(states[0].quantum_numbers) == 6 if not magnetic_plots: N_plots = len(states) states = split_hyperfine_to_magnetic(states) aux = [hsv_to_rgb(m*0.8/(N_plots-1), 1.0, 1.0) for m in range(N_plots)] hyperfine_colors = list(reversed(aux)) conta = 0 fine_states = find_fine_states(states) boundaries = reversed(calculate_boundaries(fine_states, states)[1]) boundaries = list(boundaries) for pair in boundaries: f = states[pair[0]].f if f == 0: colors = [(0.8, 0.0, 1.0)] else: aux = [hsv_to_rgb(m*0.8/f, 1.0, 1.0) for m in range(f+1)] colors = list(reversed(aux)) for i in range(pair[0], pair[1]): m = states[i].m if m < 0: color = colors[-m] style = ':' else: color = colors[m] style = '-' if magnetic_plots: aux = r"$\mathrm{Poblaci\'on} \ M_F=" aux += str(states[i].m)+"$" pyplot.plot(x, pop[i], style, label=aux, color=color) if magnetic_plots: if f != 0: suma = [sum([pop[i][j] for i in range(pair[0], pair[1])]) for j in range(len(pop[0]))] pyplot.plot(x, suma, 'k-', label=r'$\mathrm{suma}$') aux = str(states[i]).split()[1].replace('_', '') filenamei = aux.replace('/', '_').replace('^', 'F=') s = filenamei.find(',') filenamei = filenamei[:s] filenamei = name+'_'+filenamei+'.png' aux = find_fine_states([states[i]])[0] title = aux._latex_()+'\ F='+str(states[i].f) pyplot.title(r"$"+title+"$") pyplot.ylim([0, None]) pyplot.xlim([x[0], x[-1]]) pyplot.legend(fontsize=fontsize, loc=0) pyplot.savefig(save_path+filenamei, bbox_inches='tight') pyplot.close('all') else: suma = [sum([pop[i][j] for i in range(pair[0], pair[1])]) for j in range(len(pop[0]))] label = states[i]._latex_() label = label[label.find(' ')+1:] label = label[:label.find('^')] label += r"\ F="+str(states[i].f) label = "$"+label+"$" pyplot.plot(x, suma, '-', color=hyperfine_colors[conta], label=label) conta += 1 if not magnetic_plots: title = states[0]._latex_() title = "$"+title[:title.find(' ')-1]+"$" pyplot.title(title, fontsize=20) pyplot.xlim([x[0], x[-1]]) pyplot.legend(fontsize=fontsize, loc=0) pyplot.savefig(save_path+name+'_pops.png', bbox_inches='tight') pyplot.close('all')
[ "def", "plot_populations", "(", "path", ",", "name", ",", "Ne", ",", "states", "=", "None", ",", "filename", "=", "'a.png'", ",", "fontsize", "=", "12", ",", "absolute_frequency", "=", "True", ",", "save_path", "=", "''", ",", "use_netcdf", "=", "True", ...
r"""Plot the populations of a density matrix.
[ "r", "Plot", "the", "populations", "of", "a", "density", "matrix", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L624-L729
oscarlazoarjona/fast
fast/graphic.py
rotate_and_traslate
def rotate_and_traslate(cur, alpha, v0): r"""Rotate and translate a curve.""" if len(cur) > 2 or (type(cur[0][0]) in [list, tuple]): cur_list = cur[:] for i in range(len(cur_list)): curi = cur_list[i] curi = rotate_and_traslate(curi, alpha, v0) cur_list[i] = curi return cur_list else: x0, y0 = cur rot = np.matrix([[cos(alpha), -sin(alpha)], [sin(alpha), cos(alpha)]]) xn = []; yn = [] for i in range(len(x0)): v = np.matrix([[x0[i]], [y0[i]]]) vi = np.dot(rot, v) xn += [float(vi[0][0])+v0[0]]; yn += [float(vi[1][0])+v0[1]] return xn, yn
python
def rotate_and_traslate(cur, alpha, v0): r"""Rotate and translate a curve.""" if len(cur) > 2 or (type(cur[0][0]) in [list, tuple]): cur_list = cur[:] for i in range(len(cur_list)): curi = cur_list[i] curi = rotate_and_traslate(curi, alpha, v0) cur_list[i] = curi return cur_list else: x0, y0 = cur rot = np.matrix([[cos(alpha), -sin(alpha)], [sin(alpha), cos(alpha)]]) xn = []; yn = [] for i in range(len(x0)): v = np.matrix([[x0[i]], [y0[i]]]) vi = np.dot(rot, v) xn += [float(vi[0][0])+v0[0]]; yn += [float(vi[1][0])+v0[1]] return xn, yn
[ "def", "rotate_and_traslate", "(", "cur", ",", "alpha", ",", "v0", ")", ":", "if", "len", "(", "cur", ")", ">", "2", "or", "(", "type", "(", "cur", "[", "0", "]", "[", "0", "]", ")", "in", "[", "list", ",", "tuple", "]", ")", ":", "cur_list",...
r"""Rotate and translate a curve.
[ "r", "Rotate", "and", "translate", "a", "curve", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L736-L755
oscarlazoarjona/fast
fast/graphic.py
mirror
def mirror(ax, p0, alpha=0, size=2.54, width=0.5, format=None): r"""Draw a mirror.""" if format is None: format = 'k-' x0 = [size/2, -size/2, -size/2, size/2, size/2] y0 = [0, 0, -width, -width, 0] x1 = [size/2, size/2-width]; y1 = [0, -width] x2 = [-size/2+width, -size/2]; y2 = [0, -width] x3 = [(size/2-size/2+width)/2, (size/2-width-size/2)/2]; y3 = [0, -width] cur_list = [(x0, y0), (x1, y1), (x2, y2), (x3, y3)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format)
python
def mirror(ax, p0, alpha=0, size=2.54, width=0.5, format=None): r"""Draw a mirror.""" if format is None: format = 'k-' x0 = [size/2, -size/2, -size/2, size/2, size/2] y0 = [0, 0, -width, -width, 0] x1 = [size/2, size/2-width]; y1 = [0, -width] x2 = [-size/2+width, -size/2]; y2 = [0, -width] x3 = [(size/2-size/2+width)/2, (size/2-width-size/2)/2]; y3 = [0, -width] cur_list = [(x0, y0), (x1, y1), (x2, y2), (x3, y3)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format)
[ "def", "mirror", "(", "ax", ",", "p0", ",", "alpha", "=", "0", ",", "size", "=", "2.54", ",", "width", "=", "0.5", ",", "format", "=", "None", ")", ":", "if", "format", "is", "None", ":", "format", "=", "'k-'", "x0", "=", "[", "size", "/", "2...
r"""Draw a mirror.
[ "r", "Draw", "a", "mirror", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L758-L771
oscarlazoarjona/fast
fast/graphic.py
eye
def eye(ax, p0, size=1.0, alpha=0, format=None, **kwds): r"""Draw an eye.""" if format is None: format = 'k-' N = 100 ang0 = pi-3*pi/16; angf = pi+3*pi/16 angstep = (angf-ang0)/(N-1) x1 = [size*(cos(i*angstep+ang0)+1) for i in range(N)] y1 = [size*sin(i*angstep+ang0) for i in range(N)] ang2 = ang0+pi/16 x2 = [size, size*(1.2*cos(ang2)+1)] y2 = [0, 1.2*size*(sin(ang2))] y3 = [0, -1.2*size*(sin(ang2))] N = 100 ang0 = ang2; angf = ang2+4*pi/16 angstep = (angf-ang0)/(N-1) x4 = [size*(0.85*cos(i*angstep+ang0)+1) for i in range(N)] y4 = [size*0.85*sin(i*angstep+ang0) for i in range(N)] cur_list = [(x1, y1), (x2, y2), (x2, y3), (x4, y4)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)
python
def eye(ax, p0, size=1.0, alpha=0, format=None, **kwds): r"""Draw an eye.""" if format is None: format = 'k-' N = 100 ang0 = pi-3*pi/16; angf = pi+3*pi/16 angstep = (angf-ang0)/(N-1) x1 = [size*(cos(i*angstep+ang0)+1) for i in range(N)] y1 = [size*sin(i*angstep+ang0) for i in range(N)] ang2 = ang0+pi/16 x2 = [size, size*(1.2*cos(ang2)+1)] y2 = [0, 1.2*size*(sin(ang2))] y3 = [0, -1.2*size*(sin(ang2))] N = 100 ang0 = ang2; angf = ang2+4*pi/16 angstep = (angf-ang0)/(N-1) x4 = [size*(0.85*cos(i*angstep+ang0)+1) for i in range(N)] y4 = [size*0.85*sin(i*angstep+ang0) for i in range(N)] cur_list = [(x1, y1), (x2, y2), (x2, y3), (x4, y4)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)
[ "def", "eye", "(", "ax", ",", "p0", ",", "size", "=", "1.0", ",", "alpha", "=", "0", ",", "format", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "format", "is", "None", ":", "format", "=", "'k-'", "N", "=", "100", "ang0", "=", "pi", ...
r"""Draw an eye.
[ "r", "Draw", "an", "eye", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L853-L877
oscarlazoarjona/fast
fast/graphic.py
beam_splitter
def beam_splitter(ax, p0, size=2.54, alpha=0, format=None, **kwds): r"""Draw a beam splitter.""" if format is None: format = 'k-' a = size/2 x0 = [a, -a, -a, a, a, -a] y0 = [a, a, -a, -a, a, -a] cur_list = [(x0, y0)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)
python
def beam_splitter(ax, p0, size=2.54, alpha=0, format=None, **kwds): r"""Draw a beam splitter.""" if format is None: format = 'k-' a = size/2 x0 = [a, -a, -a, a, a, -a] y0 = [a, a, -a, -a, a, -a] cur_list = [(x0, y0)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)
[ "def", "beam_splitter", "(", "ax", ",", "p0", ",", "size", "=", "2.54", ",", "alpha", "=", "0", ",", "format", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "format", "is", "None", ":", "format", "=", "'k-'", "a", "=", "size", "/", "2", ...
r"""Draw a beam splitter.
[ "r", "Draw", "a", "beam", "splitter", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L880-L890
oscarlazoarjona/fast
fast/graphic.py
draw_beam
def draw_beam(ax, p1, p2, width=0, beta1=None, beta2=None, format=None, **kwds): r"""Draw a laser beam.""" if format is None: format = 'k-' if width == 0: x0 = [p1[0], p2[0]] y0 = [p1[1], p2[1]] ax.plot(x0, y0, format, **kwds) else: a = width/2 x1, y1 = p1 x2, y2 = p2 x11 = (a*x1**2*cos(beta1) - 2*a*x1*x2*cos(beta1) + a*x2**2*cos(beta1) + a*y1**2*cos(beta1) + a*y2**2*cos(beta1) - (2*a*y1*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*x1*cos(beta1))*y2 - (x1*y1*cos(beta1) - x1**2*sin(beta1) + x1*x2*sin(beta1))*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta1) - x1*sin(beta1) + x2*sin(beta1))) y11 = (a*x1**2*sin(beta1) - 2*a*x1*x2*sin(beta1) + a*x2**2*sin(beta1) + a*y1**2*sin(beta1) + a*y2**2*sin(beta1) - (2*a*y1*sin(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*y1*cos(beta1))*y2 - (y1**2*cos(beta1) - (x1*sin(beta1) - x2*sin(beta1))*y1)*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta1) - x1*sin(beta1) + x2*sin(beta1))) x21 = (a*x1**2*cos(beta2) - 2*a*x1*x2*cos(beta2) + a*x2**2*cos(beta2) + a*y1**2*cos(beta2) + a*y2**2*cos(beta2) - (2*a*y1*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*x2*cos(beta2))*y2 - (x2*y1*cos(beta2) - x1*x2*sin(beta2) + x2**2*sin(beta2))*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2))) y21 = (a*x1**2*sin(beta2) - 2*a*x1*x2*sin(beta2) + a*x2**2*sin(beta2) + a*y1**2*sin(beta2) + (a*sin(beta2) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*cos(beta2))*y2**2 - (2*a*y1*sin(beta2) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2)))*y2)/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2))) ax.plot([x11, x21], [y11, y21], format, **kwds) x12 = -(a*x1**2*cos(beta2) - 2*a*x1*x2*cos(beta2) + a*x2**2*cos(beta2) + a*y1**2*cos(beta2) + a*y2**2*cos(beta2) - (2*a*y1*cos(beta2) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*x2*cos(beta2))*y2 + (x2*y1*cos(beta2) - x1*x2*sin(beta2) + x2**2*sin(beta2))*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2))) y12 = -(a*x1**2*sin(beta2) - 2*a*x1*x2*sin(beta2) + a*x2**2*sin(beta2) + a*y1**2*sin(beta2) + (a*sin(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*cos(beta2))*y2**2 - (2*a*y1*sin(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2)))*y2)/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2))) x22 = -(a*x1**2*cos(beta1) - 2*a*x1*x2*cos(beta1) + a*x2**2*cos(beta1) + a*y1**2*cos(beta1) + a*y2**2*cos(beta1) - (2*a*y1*cos(beta1) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*x1*cos(beta1))*y2 + (x1*y1*cos(beta1) - x1**2*sin(beta1) + x1*x2*sin(beta1))*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta1) - x1*sin(beta1) + x2*sin(beta1))) y22 = -(a*x1**2*sin(beta1) - 2*a*x1*x2*sin(beta1) + a*x2**2*sin(beta1) + a*y1**2*sin(beta1) + a*y2**2*sin(beta1) - (2*a*y1*sin(beta1) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*y1*cos(beta1))*y2 + (y1**2*cos(beta1) - (x1*sin(beta1) - x2*sin(beta1))*y1)*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta1) - x1*sin(beta1) + x2*sin(beta1))) ax.plot([x12, x22], [y12, y22], format, **kwds)
python
def draw_beam(ax, p1, p2, width=0, beta1=None, beta2=None, format=None, **kwds): r"""Draw a laser beam.""" if format is None: format = 'k-' if width == 0: x0 = [p1[0], p2[0]] y0 = [p1[1], p2[1]] ax.plot(x0, y0, format, **kwds) else: a = width/2 x1, y1 = p1 x2, y2 = p2 x11 = (a*x1**2*cos(beta1) - 2*a*x1*x2*cos(beta1) + a*x2**2*cos(beta1) + a*y1**2*cos(beta1) + a*y2**2*cos(beta1) - (2*a*y1*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*x1*cos(beta1))*y2 - (x1*y1*cos(beta1) - x1**2*sin(beta1) + x1*x2*sin(beta1))*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta1) - x1*sin(beta1) + x2*sin(beta1))) y11 = (a*x1**2*sin(beta1) - 2*a*x1*x2*sin(beta1) + a*x2**2*sin(beta1) + a*y1**2*sin(beta1) + a*y2**2*sin(beta1) - (2*a*y1*sin(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*y1*cos(beta1))*y2 - (y1**2*cos(beta1) - (x1*sin(beta1) - x2*sin(beta1))*y1)*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta1) - x1*sin(beta1) + x2*sin(beta1))) x21 = (a*x1**2*cos(beta2) - 2*a*x1*x2*cos(beta2) + a*x2**2*cos(beta2) + a*y1**2*cos(beta2) + a*y2**2*cos(beta2) - (2*a*y1*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*x2*cos(beta2))*y2 - (x2*y1*cos(beta2) - x1*x2*sin(beta2) + x2**2*sin(beta2))*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2))) y21 = (a*x1**2*sin(beta2) - 2*a*x1*x2*sin(beta2) + a*x2**2*sin(beta2) + a*y1**2*sin(beta2) + (a*sin(beta2) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*cos(beta2))*y2**2 - (2*a*y1*sin(beta2) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2)))*y2)/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2))) ax.plot([x11, x21], [y11, y21], format, **kwds) x12 = -(a*x1**2*cos(beta2) - 2*a*x1*x2*cos(beta2) + a*x2**2*cos(beta2) + a*y1**2*cos(beta2) + a*y2**2*cos(beta2) - (2*a*y1*cos(beta2) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*x2*cos(beta2))*y2 + (x2*y1*cos(beta2) - x1*x2*sin(beta2) + x2**2*sin(beta2))*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2))) y12 = -(a*x1**2*sin(beta2) - 2*a*x1*x2*sin(beta2) + a*x2**2*sin(beta2) + a*y1**2*sin(beta2) + (a*sin(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*cos(beta2))*y2**2 - (2*a*y1*sin(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2)))*y2)/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta2) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta2) - x1*sin(beta2) + x2*sin(beta2))) x22 = -(a*x1**2*cos(beta1) - 2*a*x1*x2*cos(beta1) + a*x2**2*cos(beta1) + a*y1**2*cos(beta1) + a*y2**2*cos(beta1) - (2*a*y1*cos(beta1) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*x1*cos(beta1))*y2 + (x1*y1*cos(beta1) - x1**2*sin(beta1) + x1*x2*sin(beta1))*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta1) - x1*sin(beta1) + x2*sin(beta1))) y22 = -(a*x1**2*sin(beta1) - 2*a*x1*x2*sin(beta1) + a*x2**2*sin(beta1) + a*y1**2*sin(beta1) + a*y2**2*sin(beta1) - (2*a*y1*sin(beta1) + sqrt((x1 - x2)**2 + (y1 - y2)**2)*y1*cos(beta1))*y2 + (y1**2*cos(beta1) - (x1*sin(beta1) - x2*sin(beta1))*y1)*sqrt((x1 - x2)**2 + (y1 - y2)**2))/(sqrt((x1 - x2)**2 + (y1 - y2)**2)*y2*cos(beta1) - sqrt((x1 - x2)**2 + (y1 - y2)**2)*(y1*cos(beta1) - x1*sin(beta1) + x2*sin(beta1))) ax.plot([x12, x22], [y12, y22], format, **kwds)
[ "def", "draw_beam", "(", "ax", ",", "p1", ",", "p2", ",", "width", "=", "0", ",", "beta1", "=", "None", ",", "beta2", "=", "None", ",", "format", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "format", "is", "None", ":", "format", "=", ...
r"""Draw a laser beam.
[ "r", "Draw", "a", "laser", "beam", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L893-L922
oscarlazoarjona/fast
fast/graphic.py
simple_beam_splitter
def simple_beam_splitter(ax, p0, size=2.54, width=0.1, alpha=0, format=None, **kwds): r"""Draw a simple beam splitter.""" if format is None: format = 'k-' a = size/2 b = width/2 x0 = [a, -a, -a, a, a] y0 = [b, b, -b, -b, b] cur_list = [(x0, y0)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)
python
def simple_beam_splitter(ax, p0, size=2.54, width=0.1, alpha=0, format=None, **kwds): r"""Draw a simple beam splitter.""" if format is None: format = 'k-' a = size/2 b = width/2 x0 = [a, -a, -a, a, a] y0 = [b, b, -b, -b, b] cur_list = [(x0, y0)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)
[ "def", "simple_beam_splitter", "(", "ax", ",", "p0", ",", "size", "=", "2.54", ",", "width", "=", "0.1", ",", "alpha", "=", "0", ",", "format", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "format", "is", "None", ":", "format", "=", "'k-'"...
r"""Draw a simple beam splitter.
[ "r", "Draw", "a", "simple", "beam", "splitter", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L925-L937
oscarlazoarjona/fast
fast/graphic.py
draw_arith
def draw_arith(ax, p0, size=1, alpha=0, arith=None, format=None, fontsize=10, **kwds): r"""Draw an arithmetic operator.""" if format is None: format = 'k-' a = size/2.0 x0 = [0, 2.5*a, 0, 0] y0 = [a, 0, -a, a] cur_list = [(x0, y0)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds) if arith is not None: pyplot.text(p0[0]+0.75*a, p0[1], arith, horizontalalignment='center', verticalalignment='center', fontsize=fontsize)
python
def draw_arith(ax, p0, size=1, alpha=0, arith=None, format=None, fontsize=10, **kwds): r"""Draw an arithmetic operator.""" if format is None: format = 'k-' a = size/2.0 x0 = [0, 2.5*a, 0, 0] y0 = [a, 0, -a, a] cur_list = [(x0, y0)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds) if arith is not None: pyplot.text(p0[0]+0.75*a, p0[1], arith, horizontalalignment='center', verticalalignment='center', fontsize=fontsize)
[ "def", "draw_arith", "(", "ax", ",", "p0", ",", "size", "=", "1", ",", "alpha", "=", "0", ",", "arith", "=", "None", ",", "format", "=", "None", ",", "fontsize", "=", "10", ",", "*", "*", "kwds", ")", ":", "if", "format", "is", "None", ":", "...
r"""Draw an arithmetic operator.
[ "r", "Draw", "an", "arithmetic", "operator", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L1018-L1033
oscarlazoarjona/fast
fast/graphic.py
draw_state
def draw_state(ax, p, text='', l=0.5, alignment='left', label_displacement=1.0, fontsize=25, atoms=None, atoms_h=0.125, atoms_size=5, **kwds): r"""Draw a quantum state for energy level diagrams.""" ax.plot([p[0]-l/2.0, p[0]+l/2.0], [p[1], p[1]], color='black', **kwds) if text != '': if alignment == 'left': ax.text(p[0] - l/2.0 - label_displacement, p[1], text, horizontalalignment='right', verticalalignment='center', color='black', fontsize=fontsize) elif alignment == 'right': ax.text(p[0] + l/2.0 + label_displacement, p[1], text, horizontalalignment='left', color='black', fontsize=fontsize) # We draw atoms. if atoms is not None: atoms_x = np.linspace(p[0]-l*0.5, p[0]+l*0.5, atoms) atoms_y = [p[1] + atoms_h for i in range(atoms)] # print l, atoms_x ax.plot(atoms_x, atoms_y, "ko", ms=atoms_size)
python
def draw_state(ax, p, text='', l=0.5, alignment='left', label_displacement=1.0, fontsize=25, atoms=None, atoms_h=0.125, atoms_size=5, **kwds): r"""Draw a quantum state for energy level diagrams.""" ax.plot([p[0]-l/2.0, p[0]+l/2.0], [p[1], p[1]], color='black', **kwds) if text != '': if alignment == 'left': ax.text(p[0] - l/2.0 - label_displacement, p[1], text, horizontalalignment='right', verticalalignment='center', color='black', fontsize=fontsize) elif alignment == 'right': ax.text(p[0] + l/2.0 + label_displacement, p[1], text, horizontalalignment='left', color='black', fontsize=fontsize) # We draw atoms. if atoms is not None: atoms_x = np.linspace(p[0]-l*0.5, p[0]+l*0.5, atoms) atoms_y = [p[1] + atoms_h for i in range(atoms)] # print l, atoms_x ax.plot(atoms_x, atoms_y, "ko", ms=atoms_size)
[ "def", "draw_state", "(", "ax", ",", "p", ",", "text", "=", "''", ",", "l", "=", "0.5", ",", "alignment", "=", "'left'", ",", "label_displacement", "=", "1.0", ",", "fontsize", "=", "25", ",", "atoms", "=", "None", ",", "atoms_h", "=", "0.125", ","...
r"""Draw a quantum state for energy level diagrams.
[ "r", "Draw", "a", "quantum", "state", "for", "energy", "level", "diagrams", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L1041-L1061
oscarlazoarjona/fast
fast/graphic.py
draw_multiplet
def draw_multiplet(ax, fine_state, p, hmin, w, fside='right', label_separation=1, label_fontsize=15, fsize=10, deltanu_fontsize=6, proportional=False, text='', text_pos='top', magnetic_lines=False, **kwds): r"""We draw a multiplet.""" # We determine the vertical positions, calculated from p[1] up. hyperfine_states = make_list_of_states([fine_state], 'hyperfine') h_list = [ei.nu - hyperfine_states[0].nu for ei in hyperfine_states] h_list = [i/h_list[-1] for i in h_list] h_min = min([h_list[i+1]-h_list[i] for i in range(len(h_list)-1)]) h_list = [hmin*i/h_min + p[1] for i in h_list] if proportional: h_list = [p[1]+i*hmin for i in range(len(hyperfine_states))] omegaij = [(hyperfine_states[i+1].nu-hyperfine_states[i].nu)/1e6 for i in range(len(hyperfine_states)-1)] for i in range(len(h_list)): label = '$\mathrm{F}='+str(hyperfine_states[i].f)+'$' if magnetic_lines: maxf = max([eee.f for eee in hyperfine_states]) f = hyperfine_states[i].f nm = 2*maxf+1 for mf in range(-f, f+1): draw_state(ax, [p[0]+mf*w/nm, h_list[i]], "", w/nm*0.5, alignment=fside, fontsize=fsize) if fside == 'right': ax.text(p[0]+w+label_separation, h_list[i], label, fontsize=fsize, horizontalalignment="right", verticalalignment="center") elif fside == 'left': ax.text(p[0]-w-label_separation, h_list[i], label, fontsize=fsize, horizontalalignment="left", verticalalignment="center") else: draw_state(ax, [p[0], h_list[i]], label, w, alignment=fside, fontsize=fsize) for i in range(len(h_list)-1): hmid = (h_list[i+1]+h_list[i])/2.0-0.5 nu = str(omegaij[i])[:5] if fside == 'left': ax.text(p[0]-w/2.0, hmid, r'$'+nu+' \ \mathrm{MHz}$', fontsize=deltanu_fontsize, horizontalalignment=fside, verticalalignment='bottom') else: ax.text(p[0]+w/2.0, hmid, r'$'+nu+' \ \mathrm{MHz}$', fontsize=deltanu_fontsize, horizontalalignment=fside, verticalalignment='bottom') a = label_separation if text != '': if text_pos == 'top': labelx = p[0] labely = h_list[-1]+a ax.text(labelx, labely, '$'+text+'$', verticalalignment='bottom', horizontalalignment='center', fontsize=label_fontsize) elif text_pos == 'right': labelx = p[0]+w/2+2.0*a if fside == 'right': labelx = labelx+a*5.0 labely = (h_list[-1]+h_list[0])/2.0 ax.text(labelx, labely, '$'+text+'$', verticalalignment='center', horizontalalignment='left', fontsize=label_fontsize) elif text_pos == 'left': labelx = p[0]-w/2-2.0*a if fside == 'left': labelx = labelx-a*5.0 labely = (h_list[-1]+h_list[0])/2.0 ax.text(labelx, labely, '$'+text+'$', verticalalignment='center', horizontalalignment='right', fontsize=label_fontsize) return [[p[0], i] for i in h_list]
python
def draw_multiplet(ax, fine_state, p, hmin, w, fside='right', label_separation=1, label_fontsize=15, fsize=10, deltanu_fontsize=6, proportional=False, text='', text_pos='top', magnetic_lines=False, **kwds): r"""We draw a multiplet.""" # We determine the vertical positions, calculated from p[1] up. hyperfine_states = make_list_of_states([fine_state], 'hyperfine') h_list = [ei.nu - hyperfine_states[0].nu for ei in hyperfine_states] h_list = [i/h_list[-1] for i in h_list] h_min = min([h_list[i+1]-h_list[i] for i in range(len(h_list)-1)]) h_list = [hmin*i/h_min + p[1] for i in h_list] if proportional: h_list = [p[1]+i*hmin for i in range(len(hyperfine_states))] omegaij = [(hyperfine_states[i+1].nu-hyperfine_states[i].nu)/1e6 for i in range(len(hyperfine_states)-1)] for i in range(len(h_list)): label = '$\mathrm{F}='+str(hyperfine_states[i].f)+'$' if magnetic_lines: maxf = max([eee.f for eee in hyperfine_states]) f = hyperfine_states[i].f nm = 2*maxf+1 for mf in range(-f, f+1): draw_state(ax, [p[0]+mf*w/nm, h_list[i]], "", w/nm*0.5, alignment=fside, fontsize=fsize) if fside == 'right': ax.text(p[0]+w+label_separation, h_list[i], label, fontsize=fsize, horizontalalignment="right", verticalalignment="center") elif fside == 'left': ax.text(p[0]-w-label_separation, h_list[i], label, fontsize=fsize, horizontalalignment="left", verticalalignment="center") else: draw_state(ax, [p[0], h_list[i]], label, w, alignment=fside, fontsize=fsize) for i in range(len(h_list)-1): hmid = (h_list[i+1]+h_list[i])/2.0-0.5 nu = str(omegaij[i])[:5] if fside == 'left': ax.text(p[0]-w/2.0, hmid, r'$'+nu+' \ \mathrm{MHz}$', fontsize=deltanu_fontsize, horizontalalignment=fside, verticalalignment='bottom') else: ax.text(p[0]+w/2.0, hmid, r'$'+nu+' \ \mathrm{MHz}$', fontsize=deltanu_fontsize, horizontalalignment=fside, verticalalignment='bottom') a = label_separation if text != '': if text_pos == 'top': labelx = p[0] labely = h_list[-1]+a ax.text(labelx, labely, '$'+text+'$', verticalalignment='bottom', horizontalalignment='center', fontsize=label_fontsize) elif text_pos == 'right': labelx = p[0]+w/2+2.0*a if fside == 'right': labelx = labelx+a*5.0 labely = (h_list[-1]+h_list[0])/2.0 ax.text(labelx, labely, '$'+text+'$', verticalalignment='center', horizontalalignment='left', fontsize=label_fontsize) elif text_pos == 'left': labelx = p[0]-w/2-2.0*a if fside == 'left': labelx = labelx-a*5.0 labely = (h_list[-1]+h_list[0])/2.0 ax.text(labelx, labely, '$'+text+'$', verticalalignment='center', horizontalalignment='right', fontsize=label_fontsize) return [[p[0], i] for i in h_list]
[ "def", "draw_multiplet", "(", "ax", ",", "fine_state", ",", "p", ",", "hmin", ",", "w", ",", "fside", "=", "'right'", ",", "label_separation", "=", "1", ",", "label_fontsize", "=", "15", ",", "fsize", "=", "10", ",", "deltanu_fontsize", "=", "6", ",", ...
r"""We draw a multiplet.
[ "r", "We", "draw", "a", "multiplet", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L1064-L1145
oscarlazoarjona/fast
fast/graphic.py
decay
def decay(ax, p0, pf, A, n, format=None, **kwds): r"""Draw a spontaneous decay as a wavy line.""" if format is None: format = 'k-' T = sqrt((p0[0]-pf[0])**2+(p0[1]-pf[1])**2) alpha = atan2(pf[1]-p0[1], pf[0]-p0[0]) x = [i*T/400.0 for i in range(401)] y = [A*sin(xi * 2*pi*n/T) for xi in x] cur_list = [(x, y)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)
python
def decay(ax, p0, pf, A, n, format=None, **kwds): r"""Draw a spontaneous decay as a wavy line.""" if format is None: format = 'k-' T = sqrt((p0[0]-pf[0])**2+(p0[1]-pf[1])**2) alpha = atan2(pf[1]-p0[1], pf[0]-p0[0]) x = [i*T/400.0 for i in range(401)] y = [A*sin(xi * 2*pi*n/T) for xi in x] cur_list = [(x, y)] cur_list = rotate_and_traslate(cur_list, alpha, p0) for curi in cur_list: ax.plot(curi[0], curi[1], format, **kwds)
[ "def", "decay", "(", "ax", ",", "p0", ",", "pf", ",", "A", ",", "n", ",", "format", "=", "None", ",", "*", "*", "kwds", ")", ":", "if", "format", "is", "None", ":", "format", "=", "'k-'", "T", "=", "sqrt", "(", "(", "p0", "[", "0", "]", "...
r"""Draw a spontaneous decay as a wavy line.
[ "r", "Draw", "a", "spontaneous", "decay", "as", "a", "wavy", "line", "." ]
train
https://github.com/oscarlazoarjona/fast/blob/3e5400672af2a7b7cc616e7f4aa10d7672720222/fast/graphic.py#L1159-L1172
minrk/wurlitzer
wurlitzer.py
dup2
def dup2(a, b, timeout=3): """Like os.dup2, but retry on EBUSY""" dup_err = None # give FDs 3 seconds to not be busy anymore for i in range(int(10 * timeout)): try: return os.dup2(a, b) except OSError as e: dup_err = e if e.errno == errno.EBUSY: time.sleep(0.1) else: raise if dup_err: raise dup_err
python
def dup2(a, b, timeout=3): """Like os.dup2, but retry on EBUSY""" dup_err = None # give FDs 3 seconds to not be busy anymore for i in range(int(10 * timeout)): try: return os.dup2(a, b) except OSError as e: dup_err = e if e.errno == errno.EBUSY: time.sleep(0.1) else: raise if dup_err: raise dup_err
[ "def", "dup2", "(", "a", ",", "b", ",", "timeout", "=", "3", ")", ":", "dup_err", "=", "None", "# give FDs 3 seconds to not be busy anymore", "for", "i", "in", "range", "(", "int", "(", "10", "*", "timeout", ")", ")", ":", "try", ":", "return", "os", ...
Like os.dup2, but retry on EBUSY
[ "Like", "os", ".", "dup2", "but", "retry", "on", "EBUSY" ]
train
https://github.com/minrk/wurlitzer/blob/088bb9957396afea21a88b35999267a9c6e239d5/wurlitzer.py#L52-L66
minrk/wurlitzer
wurlitzer.py
pipes
def pipes(stdout=PIPE, stderr=PIPE, encoding=_default_encoding): """Capture C-level stdout/stderr in a context manager. The return value for the context manager is (stdout, stderr). Examples -------- >>> with capture() as (stdout, stderr): ... printf("C-level stdout") ... output = stdout.read() """ stdout_pipe = stderr_pipe = False # setup stdout if stdout == PIPE: stdout_r, stdout_w = os.pipe() stdout_w = os.fdopen(stdout_w, 'wb') if encoding: stdout_r = io.open(stdout_r, 'r', encoding=encoding) else: stdout_r = os.fdopen(stdout_r, 'rb') stdout_pipe = True else: stdout_r = stdout_w = stdout # setup stderr if stderr == STDOUT: stderr_r = None stderr_w = stdout_w elif stderr == PIPE: stderr_r, stderr_w = os.pipe() stderr_w = os.fdopen(stderr_w, 'wb') if encoding: stderr_r = io.open(stderr_r, 'r', encoding=encoding) else: stderr_r = os.fdopen(stderr_r, 'rb') stderr_pipe = True else: stderr_r = stderr_w = stderr if stdout_pipe or stderr_pipe: capture_encoding = None else: capture_encoding = encoding w = Wurlitzer(stdout=stdout_w, stderr=stderr_w, encoding=capture_encoding) try: with w: yield stdout_r, stderr_r finally: # close pipes if stdout_pipe: stdout_w.close() if stderr_pipe: stderr_w.close()
python
def pipes(stdout=PIPE, stderr=PIPE, encoding=_default_encoding): """Capture C-level stdout/stderr in a context manager. The return value for the context manager is (stdout, stderr). Examples -------- >>> with capture() as (stdout, stderr): ... printf("C-level stdout") ... output = stdout.read() """ stdout_pipe = stderr_pipe = False # setup stdout if stdout == PIPE: stdout_r, stdout_w = os.pipe() stdout_w = os.fdopen(stdout_w, 'wb') if encoding: stdout_r = io.open(stdout_r, 'r', encoding=encoding) else: stdout_r = os.fdopen(stdout_r, 'rb') stdout_pipe = True else: stdout_r = stdout_w = stdout # setup stderr if stderr == STDOUT: stderr_r = None stderr_w = stdout_w elif stderr == PIPE: stderr_r, stderr_w = os.pipe() stderr_w = os.fdopen(stderr_w, 'wb') if encoding: stderr_r = io.open(stderr_r, 'r', encoding=encoding) else: stderr_r = os.fdopen(stderr_r, 'rb') stderr_pipe = True else: stderr_r = stderr_w = stderr if stdout_pipe or stderr_pipe: capture_encoding = None else: capture_encoding = encoding w = Wurlitzer(stdout=stdout_w, stderr=stderr_w, encoding=capture_encoding) try: with w: yield stdout_r, stderr_r finally: # close pipes if stdout_pipe: stdout_w.close() if stderr_pipe: stderr_w.close()
[ "def", "pipes", "(", "stdout", "=", "PIPE", ",", "stderr", "=", "PIPE", ",", "encoding", "=", "_default_encoding", ")", ":", "stdout_pipe", "=", "stderr_pipe", "=", "False", "# setup stdout", "if", "stdout", "==", "PIPE", ":", "stdout_r", ",", "stdout_w", ...
Capture C-level stdout/stderr in a context manager. The return value for the context manager is (stdout, stderr). Examples -------- >>> with capture() as (stdout, stderr): ... printf("C-level stdout") ... output = stdout.read()
[ "Capture", "C", "-", "level", "stdout", "/", "stderr", "in", "a", "context", "manager", "." ]
train
https://github.com/minrk/wurlitzer/blob/088bb9957396afea21a88b35999267a9c6e239d5/wurlitzer.py#L254-L305
minrk/wurlitzer
wurlitzer.py
sys_pipes
def sys_pipes(encoding=_default_encoding): """Redirect C-level stdout/stderr to sys.stdout/stderr This is useful of sys.sdout/stderr are already being forwarded somewhere. DO NOT USE THIS if sys.stdout and sys.stderr are not already being forwarded. """ return pipes(sys.stdout, sys.stderr, encoding=encoding)
python
def sys_pipes(encoding=_default_encoding): """Redirect C-level stdout/stderr to sys.stdout/stderr This is useful of sys.sdout/stderr are already being forwarded somewhere. DO NOT USE THIS if sys.stdout and sys.stderr are not already being forwarded. """ return pipes(sys.stdout, sys.stderr, encoding=encoding)
[ "def", "sys_pipes", "(", "encoding", "=", "_default_encoding", ")", ":", "return", "pipes", "(", "sys", ".", "stdout", ",", "sys", ".", "stderr", ",", "encoding", "=", "encoding", ")" ]
Redirect C-level stdout/stderr to sys.stdout/stderr This is useful of sys.sdout/stderr are already being forwarded somewhere. DO NOT USE THIS if sys.stdout and sys.stderr are not already being forwarded.
[ "Redirect", "C", "-", "level", "stdout", "/", "stderr", "to", "sys", ".", "stdout", "/", "stderr", "This", "is", "useful", "of", "sys", ".", "sdout", "/", "stderr", "are", "already", "being", "forwarded", "somewhere", ".", "DO", "NOT", "USE", "THIS", "...
train
https://github.com/minrk/wurlitzer/blob/088bb9957396afea21a88b35999267a9c6e239d5/wurlitzer.py#L308-L315
minrk/wurlitzer
wurlitzer.py
sys_pipes_forever
def sys_pipes_forever(encoding=_default_encoding): """Redirect all C output to sys.stdout/err This is not a context manager; it turns on C-forwarding permanently. """ global _mighty_wurlitzer if _mighty_wurlitzer is None: _mighty_wurlitzer = sys_pipes(encoding) _mighty_wurlitzer.__enter__()
python
def sys_pipes_forever(encoding=_default_encoding): """Redirect all C output to sys.stdout/err This is not a context manager; it turns on C-forwarding permanently. """ global _mighty_wurlitzer if _mighty_wurlitzer is None: _mighty_wurlitzer = sys_pipes(encoding) _mighty_wurlitzer.__enter__()
[ "def", "sys_pipes_forever", "(", "encoding", "=", "_default_encoding", ")", ":", "global", "_mighty_wurlitzer", "if", "_mighty_wurlitzer", "is", "None", ":", "_mighty_wurlitzer", "=", "sys_pipes", "(", "encoding", ")", "_mighty_wurlitzer", ".", "__enter__", "(", ")"...
Redirect all C output to sys.stdout/err This is not a context manager; it turns on C-forwarding permanently.
[ "Redirect", "all", "C", "output", "to", "sys", ".", "stdout", "/", "err", "This", "is", "not", "a", "context", "manager", ";", "it", "turns", "on", "C", "-", "forwarding", "permanently", "." ]
train
https://github.com/minrk/wurlitzer/blob/088bb9957396afea21a88b35999267a9c6e239d5/wurlitzer.py#L320-L328
minrk/wurlitzer
wurlitzer.py
load_ipython_extension
def load_ipython_extension(ip): """Register me as an IPython extension Captures all C output during execution and forwards to sys. Does nothing on terminal IPython. Use: %load_ext wurlitzer """ if not getattr(ip, 'kernel'): warnings.warn( "wurlitzer extension doesn't do anything in terminal IPython" ) return ip.events.register('pre_execute', sys_pipes_forever) ip.events.register('post_execute', stop_sys_pipes)
python
def load_ipython_extension(ip): """Register me as an IPython extension Captures all C output during execution and forwards to sys. Does nothing on terminal IPython. Use: %load_ext wurlitzer """ if not getattr(ip, 'kernel'): warnings.warn( "wurlitzer extension doesn't do anything in terminal IPython" ) return ip.events.register('pre_execute', sys_pipes_forever) ip.events.register('post_execute', stop_sys_pipes)
[ "def", "load_ipython_extension", "(", "ip", ")", ":", "if", "not", "getattr", "(", "ip", ",", "'kernel'", ")", ":", "warnings", ".", "warn", "(", "\"wurlitzer extension doesn't do anything in terminal IPython\"", ")", "return", "ip", ".", "events", ".", "register"...
Register me as an IPython extension Captures all C output during execution and forwards to sys. Does nothing on terminal IPython. Use: %load_ext wurlitzer
[ "Register", "me", "as", "an", "IPython", "extension", "Captures", "all", "C", "output", "during", "execution", "and", "forwards", "to", "sys", ".", "Does", "nothing", "on", "terminal", "IPython", ".", "Use", ":", "%load_ext", "wurlitzer" ]
train
https://github.com/minrk/wurlitzer/blob/088bb9957396afea21a88b35999267a9c6e239d5/wurlitzer.py#L339-L354
minrk/wurlitzer
wurlitzer.py
unload_ipython_extension
def unload_ipython_extension(ip): """Unload me as an IPython extension Use: %unload_ext wurlitzer """ if not getattr(ip, 'kernel'): return ip.events.unregister('pre_execute', sys_pipes_forever) ip.events.unregister('post_execute', stop_sys_pipes)
python
def unload_ipython_extension(ip): """Unload me as an IPython extension Use: %unload_ext wurlitzer """ if not getattr(ip, 'kernel'): return ip.events.unregister('pre_execute', sys_pipes_forever) ip.events.unregister('post_execute', stop_sys_pipes)
[ "def", "unload_ipython_extension", "(", "ip", ")", ":", "if", "not", "getattr", "(", "ip", ",", "'kernel'", ")", ":", "return", "ip", ".", "events", ".", "unregister", "(", "'pre_execute'", ",", "sys_pipes_forever", ")", "ip", ".", "events", ".", "unregist...
Unload me as an IPython extension Use: %unload_ext wurlitzer
[ "Unload", "me", "as", "an", "IPython", "extension", "Use", ":", "%unload_ext", "wurlitzer" ]
train
https://github.com/minrk/wurlitzer/blob/088bb9957396afea21a88b35999267a9c6e239d5/wurlitzer.py#L357-L365
minrk/wurlitzer
wurlitzer.py
Wurlitzer._decode
def _decode(self, data): """Decode data, if any Called before passing to stdout/stderr streams """ if self.encoding: data = data.decode(self.encoding, 'replace') return data
python
def _decode(self, data): """Decode data, if any Called before passing to stdout/stderr streams """ if self.encoding: data = data.decode(self.encoding, 'replace') return data
[ "def", "_decode", "(", "self", ",", "data", ")", ":", "if", "self", ".", "encoding", ":", "data", "=", "data", ".", "decode", "(", "self", ".", "encoding", ",", "'replace'", ")", "return", "data" ]
Decode data, if any Called before passing to stdout/stderr streams
[ "Decode", "data", "if", "any", "Called", "before", "passing", "to", "stdout", "/", "stderr", "streams" ]
train
https://github.com/minrk/wurlitzer/blob/088bb9957396afea21a88b35999267a9c6e239d5/wurlitzer.py#L114-L121
sphinx-contrib/spelling
sphinxcontrib/spelling/checker.py
SpellingChecker.push_filters
def push_filters(self, new_filters): """Add a filter to the tokenizer chain. """ t = self.tokenizer for f in new_filters: t = f(t) self.tokenizer = t
python
def push_filters(self, new_filters): """Add a filter to the tokenizer chain. """ t = self.tokenizer for f in new_filters: t = f(t) self.tokenizer = t
[ "def", "push_filters", "(", "self", ",", "new_filters", ")", ":", "t", "=", "self", ".", "tokenizer", "for", "f", "in", "new_filters", ":", "t", "=", "f", "(", "t", ")", "self", ".", "tokenizer", "=", "t" ]
Add a filter to the tokenizer chain.
[ "Add", "a", "filter", "to", "the", "tokenizer", "chain", "." ]
train
https://github.com/sphinx-contrib/spelling/blob/3108cd86b5935f458ec80e87f8e37f924725d15f/sphinxcontrib/spelling/checker.py#L28-L34
sphinx-contrib/spelling
sphinxcontrib/spelling/checker.py
SpellingChecker.check
def check(self, text): """Yields bad words and suggested alternate spellings. """ for word, pos in self.tokenizer(text): correct = self.dictionary.check(word) if correct: continue yield word, self.dictionary.suggest(word) if self.suggest else [] return
python
def check(self, text): """Yields bad words and suggested alternate spellings. """ for word, pos in self.tokenizer(text): correct = self.dictionary.check(word) if correct: continue yield word, self.dictionary.suggest(word) if self.suggest else [] return
[ "def", "check", "(", "self", ",", "text", ")", ":", "for", "word", ",", "pos", "in", "self", ".", "tokenizer", "(", "text", ")", ":", "correct", "=", "self", ".", "dictionary", ".", "check", "(", "word", ")", "if", "correct", ":", "continue", "yiel...
Yields bad words and suggested alternate spellings.
[ "Yields", "bad", "words", "and", "suggested", "alternate", "spellings", "." ]
train
https://github.com/sphinx-contrib/spelling/blob/3108cd86b5935f458ec80e87f8e37f924725d15f/sphinxcontrib/spelling/checker.py#L41-L49
Yelp/service_configuration_lib
service_configuration_lib/__init__.py
get_service_from_port
def get_service_from_port(port, all_services=None): """Gets the name of the service from the port all_services allows you to feed in the services to look through, pass in a dict of service names to service information eg. { 'service_name': { 'port': port_number } } Returns the name of the service """ if port is None or not isinstance(port, int): return None if all_services is None: all_services = read_services_configuration() for name, info in all_services.items(): srv_port = info.get('port') if srv_port is not None and port == int(srv_port): return name for elem in info.get('smartstack', {}).values(): elem_port = elem.get('proxy_port') if elem_port is not None and port == int(elem_port): return name
python
def get_service_from_port(port, all_services=None): """Gets the name of the service from the port all_services allows you to feed in the services to look through, pass in a dict of service names to service information eg. { 'service_name': { 'port': port_number } } Returns the name of the service """ if port is None or not isinstance(port, int): return None if all_services is None: all_services = read_services_configuration() for name, info in all_services.items(): srv_port = info.get('port') if srv_port is not None and port == int(srv_port): return name for elem in info.get('smartstack', {}).values(): elem_port = elem.get('proxy_port') if elem_port is not None and port == int(elem_port): return name
[ "def", "get_service_from_port", "(", "port", ",", "all_services", "=", "None", ")", ":", "if", "port", "is", "None", "or", "not", "isinstance", "(", "port", ",", "int", ")", ":", "return", "None", "if", "all_services", "is", "None", ":", "all_services", ...
Gets the name of the service from the port all_services allows you to feed in the services to look through, pass in a dict of service names to service information eg. { 'service_name': { 'port': port_number } } Returns the name of the service
[ "Gets", "the", "name", "of", "the", "service", "from", "the", "port", "all_services", "allows", "you", "to", "feed", "in", "the", "services", "to", "look", "through", "pass", "in", "a", "dict", "of", "service", "names", "to", "service", "information", "eg"...
train
https://github.com/Yelp/service_configuration_lib/blob/83ac2872f95dd204e9f83ec95b4296a9501bf82d/service_configuration_lib/__init__.py#L165-L191
Yelp/service_configuration_lib
service_configuration_lib/__init__.py
all_nodes_that_receive
def all_nodes_that_receive(service, service_configuration=None, run_only=False, deploy_to_only=False): """If run_only, returns only the services that are in the runs_on list. If deploy_to_only, returns only the services in the deployed_to list. If neither, both are returned, duplicates stripped. Results are always sorted. """ assert not (run_only and deploy_to_only) if service_configuration is None: service_configuration = read_services_configuration() runs_on = service_configuration[service]['runs_on'] deployed_to = service_configuration[service].get('deployed_to') if deployed_to is None: deployed_to = [] if run_only: result = runs_on elif deploy_to_only: result = deployed_to else: result = set(runs_on) | set(deployed_to) return list(sorted(result))
python
def all_nodes_that_receive(service, service_configuration=None, run_only=False, deploy_to_only=False): """If run_only, returns only the services that are in the runs_on list. If deploy_to_only, returns only the services in the deployed_to list. If neither, both are returned, duplicates stripped. Results are always sorted. """ assert not (run_only and deploy_to_only) if service_configuration is None: service_configuration = read_services_configuration() runs_on = service_configuration[service]['runs_on'] deployed_to = service_configuration[service].get('deployed_to') if deployed_to is None: deployed_to = [] if run_only: result = runs_on elif deploy_to_only: result = deployed_to else: result = set(runs_on) | set(deployed_to) return list(sorted(result))
[ "def", "all_nodes_that_receive", "(", "service", ",", "service_configuration", "=", "None", ",", "run_only", "=", "False", ",", "deploy_to_only", "=", "False", ")", ":", "assert", "not", "(", "run_only", "and", "deploy_to_only", ")", "if", "service_configuration",...
If run_only, returns only the services that are in the runs_on list. If deploy_to_only, returns only the services in the deployed_to list. If neither, both are returned, duplicates stripped. Results are always sorted.
[ "If", "run_only", "returns", "only", "the", "services", "that", "are", "in", "the", "runs_on", "list", ".", "If", "deploy_to_only", "returns", "only", "the", "services", "in", "the", "deployed_to", "list", ".", "If", "neither", "both", "are", "returned", "du...
train
https://github.com/Yelp/service_configuration_lib/blob/83ac2872f95dd204e9f83ec95b4296a9501bf82d/service_configuration_lib/__init__.py#L246-L268
Yelp/service_configuration_lib
service_configuration_lib/__init__.py
all_nodes_that_run_in_env
def all_nodes_that_run_in_env(service, env, service_configuration=None): """ Returns all nodes that run in an environment. This needs to be specified in field named 'env_runs_on' one level under services in the configuration, and needs to contain an object which maps strings to lists (environments to nodes). :param service: A string specifying which service to look up nodes for :param env: A string specifying which environment's nodes should be returned :param service_configuration: A service_configuration dict to look in or None to use the default dict. :returns: list of all nodes running in a certain environment """ if service_configuration is None: service_configuration = read_services_configuration() env_runs_on = service_configuration[service]['env_runs_on'] if env in env_runs_on: return list(sorted(env_runs_on[env])) else: return []
python
def all_nodes_that_run_in_env(service, env, service_configuration=None): """ Returns all nodes that run in an environment. This needs to be specified in field named 'env_runs_on' one level under services in the configuration, and needs to contain an object which maps strings to lists (environments to nodes). :param service: A string specifying which service to look up nodes for :param env: A string specifying which environment's nodes should be returned :param service_configuration: A service_configuration dict to look in or None to use the default dict. :returns: list of all nodes running in a certain environment """ if service_configuration is None: service_configuration = read_services_configuration() env_runs_on = service_configuration[service]['env_runs_on'] if env in env_runs_on: return list(sorted(env_runs_on[env])) else: return []
[ "def", "all_nodes_that_run_in_env", "(", "service", ",", "env", ",", "service_configuration", "=", "None", ")", ":", "if", "service_configuration", "is", "None", ":", "service_configuration", "=", "read_services_configuration", "(", ")", "env_runs_on", "=", "service_c...
Returns all nodes that run in an environment. This needs to be specified in field named 'env_runs_on' one level under services in the configuration, and needs to contain an object which maps strings to lists (environments to nodes). :param service: A string specifying which service to look up nodes for :param env: A string specifying which environment's nodes should be returned :param service_configuration: A service_configuration dict to look in or None to use the default dict. :returns: list of all nodes running in a certain environment
[ "Returns", "all", "nodes", "that", "run", "in", "an", "environment", ".", "This", "needs", "to", "be", "specified", "in", "field", "named", "env_runs_on", "one", "level", "under", "services", "in", "the", "configuration", "and", "needs", "to", "contain", "an...
train
https://github.com/Yelp/service_configuration_lib/blob/83ac2872f95dd204e9f83ec95b4296a9501bf82d/service_configuration_lib/__init__.py#L270-L290
catherinedevlin/ddl-generator
ddlgenerator/typehelpers.py
precision_and_scale
def precision_and_scale(x): """ From a float, decide what precision and scale are needed to represent it. >>> precision_and_scale(54.2) (3, 1) >>> precision_and_scale(9) (1, 0) Thanks to Mark Ransom, http://stackoverflow.com/questions/3018758/determine-precision-and-scale-of-particular-number-in-python """ if isinstance(x, Decimal): precision = len(x.as_tuple().digits) scale = -1 * x.as_tuple().exponent if scale < 0: precision -= scale scale = 0 return (precision, scale) max_digits = 14 int_part = int(abs(x)) magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1 if magnitude >= max_digits: return (magnitude, 0) frac_part = abs(x) - int_part multiplier = 10 ** (max_digits - magnitude) frac_digits = multiplier + int(multiplier * frac_part + 0.5) while frac_digits % 10 == 0: frac_digits /= 10 scale = int(math.log10(frac_digits)) return (magnitude + scale, scale)
python
def precision_and_scale(x): """ From a float, decide what precision and scale are needed to represent it. >>> precision_and_scale(54.2) (3, 1) >>> precision_and_scale(9) (1, 0) Thanks to Mark Ransom, http://stackoverflow.com/questions/3018758/determine-precision-and-scale-of-particular-number-in-python """ if isinstance(x, Decimal): precision = len(x.as_tuple().digits) scale = -1 * x.as_tuple().exponent if scale < 0: precision -= scale scale = 0 return (precision, scale) max_digits = 14 int_part = int(abs(x)) magnitude = 1 if int_part == 0 else int(math.log10(int_part)) + 1 if magnitude >= max_digits: return (magnitude, 0) frac_part = abs(x) - int_part multiplier = 10 ** (max_digits - magnitude) frac_digits = multiplier + int(multiplier * frac_part + 0.5) while frac_digits % 10 == 0: frac_digits /= 10 scale = int(math.log10(frac_digits)) return (magnitude + scale, scale)
[ "def", "precision_and_scale", "(", "x", ")", ":", "if", "isinstance", "(", "x", ",", "Decimal", ")", ":", "precision", "=", "len", "(", "x", ".", "as_tuple", "(", ")", ".", "digits", ")", "scale", "=", "-", "1", "*", "x", ".", "as_tuple", "(", ")...
From a float, decide what precision and scale are needed to represent it. >>> precision_and_scale(54.2) (3, 1) >>> precision_and_scale(9) (1, 0) Thanks to Mark Ransom, http://stackoverflow.com/questions/3018758/determine-precision-and-scale-of-particular-number-in-python
[ "From", "a", "float", "decide", "what", "precision", "and", "scale", "are", "needed", "to", "represent", "it", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L17-L47
catherinedevlin/ddl-generator
ddlgenerator/typehelpers.py
coerce_to_specific
def coerce_to_specific(datum): """ Coerces datum to the most specific data type possible Order of preference: datetime, boolean, integer, decimal, float, string >>> coerce_to_specific('-000000001854.60') Decimal('-1854.60') >>> coerce_to_specific(7.2) Decimal('7.2') >>> coerce_to_specific("Jan 17 2012") datetime.datetime(2012, 1, 17, 0, 0) >>> coerce_to_specific("something else") 'something else' >>> coerce_to_specific("20141010") datetime.datetime(2014, 10, 10, 0, 0) >>> coerce_to_specific("001210107") 1210107 >>> coerce_to_specific("010") 10 """ if datum is None: return None try: result = dateutil.parser.parse(datum) # but even if this does not raise an exception, may # not be a date -- dateutil's parser is very aggressive # check for nonsense unprintable date str(result) # most false date hits will be interpreted as times today # or as unlikely far-future or far-past years clean_datum = datum.strip().lstrip('-').lstrip('0').rstrip('.') if len(_complex_enough_to_be_date.findall(clean_datum)) < 2: digits = _digits_only.search(clean_datum) if (not digits) or (len(digits.group(0)) not in (4, 6, 8, 12, 14, 17)): raise Exception("false date hit for %s" % datum) if result.date() == datetime.datetime.now().date(): raise Exception("false date hit (%s) for %s" % ( str(result), datum)) if not (1700 < result.year < 2150): raise Exception("false date hit (%s) for %s" % ( str(result), datum)) return result except Exception as e: pass if str(datum).strip().lower() in ('0', 'false', 'f', 'n', 'no'): return False elif str(datum).strip().lower() in ('1', 'true', 't', 'y', 'yes'): return True try: return int(str(datum)) except ValueError: pass try: return Decimal(str(datum)) except InvalidOperation: pass try: return float(str(datum)) except ValueError: pass return str(datum)
python
def coerce_to_specific(datum): """ Coerces datum to the most specific data type possible Order of preference: datetime, boolean, integer, decimal, float, string >>> coerce_to_specific('-000000001854.60') Decimal('-1854.60') >>> coerce_to_specific(7.2) Decimal('7.2') >>> coerce_to_specific("Jan 17 2012") datetime.datetime(2012, 1, 17, 0, 0) >>> coerce_to_specific("something else") 'something else' >>> coerce_to_specific("20141010") datetime.datetime(2014, 10, 10, 0, 0) >>> coerce_to_specific("001210107") 1210107 >>> coerce_to_specific("010") 10 """ if datum is None: return None try: result = dateutil.parser.parse(datum) # but even if this does not raise an exception, may # not be a date -- dateutil's parser is very aggressive # check for nonsense unprintable date str(result) # most false date hits will be interpreted as times today # or as unlikely far-future or far-past years clean_datum = datum.strip().lstrip('-').lstrip('0').rstrip('.') if len(_complex_enough_to_be_date.findall(clean_datum)) < 2: digits = _digits_only.search(clean_datum) if (not digits) or (len(digits.group(0)) not in (4, 6, 8, 12, 14, 17)): raise Exception("false date hit for %s" % datum) if result.date() == datetime.datetime.now().date(): raise Exception("false date hit (%s) for %s" % ( str(result), datum)) if not (1700 < result.year < 2150): raise Exception("false date hit (%s) for %s" % ( str(result), datum)) return result except Exception as e: pass if str(datum).strip().lower() in ('0', 'false', 'f', 'n', 'no'): return False elif str(datum).strip().lower() in ('1', 'true', 't', 'y', 'yes'): return True try: return int(str(datum)) except ValueError: pass try: return Decimal(str(datum)) except InvalidOperation: pass try: return float(str(datum)) except ValueError: pass return str(datum)
[ "def", "coerce_to_specific", "(", "datum", ")", ":", "if", "datum", "is", "None", ":", "return", "None", "try", ":", "result", "=", "dateutil", ".", "parser", ".", "parse", "(", "datum", ")", "# but even if this does not raise an exception, may", "# not be a date ...
Coerces datum to the most specific data type possible Order of preference: datetime, boolean, integer, decimal, float, string >>> coerce_to_specific('-000000001854.60') Decimal('-1854.60') >>> coerce_to_specific(7.2) Decimal('7.2') >>> coerce_to_specific("Jan 17 2012") datetime.datetime(2012, 1, 17, 0, 0) >>> coerce_to_specific("something else") 'something else' >>> coerce_to_specific("20141010") datetime.datetime(2014, 10, 10, 0, 0) >>> coerce_to_specific("001210107") 1210107 >>> coerce_to_specific("010") 10
[ "Coerces", "datum", "to", "the", "most", "specific", "data", "type", "possible", "Order", "of", "preference", ":", "datetime", "boolean", "integer", "decimal", "float", "string" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L51-L112
catherinedevlin/ddl-generator
ddlgenerator/typehelpers.py
_places_b4_and_after_decimal
def _places_b4_and_after_decimal(d): """ >>> _places_b4_and_after_decimal(Decimal('54.212')) (2, 3) """ tup = d.as_tuple() return (len(tup.digits) + tup.exponent, max(-1*tup.exponent, 0))
python
def _places_b4_and_after_decimal(d): """ >>> _places_b4_and_after_decimal(Decimal('54.212')) (2, 3) """ tup = d.as_tuple() return (len(tup.digits) + tup.exponent, max(-1*tup.exponent, 0))
[ "def", "_places_b4_and_after_decimal", "(", "d", ")", ":", "tup", "=", "d", ".", "as_tuple", "(", ")", "return", "(", "len", "(", "tup", ".", "digits", ")", "+", "tup", ".", "exponent", ",", "max", "(", "-", "1", "*", "tup", ".", "exponent", ",", ...
>>> _places_b4_and_after_decimal(Decimal('54.212')) (2, 3)
[ ">>>", "_places_b4_and_after_decimal", "(", "Decimal", "(", "54", ".", "212", "))", "(", "2", "3", ")" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L114-L120
catherinedevlin/ddl-generator
ddlgenerator/typehelpers.py
worst_decimal
def worst_decimal(d1, d2): """ Given two Decimals, return a 9-filled decimal representing both enough > 0 digits and enough < 0 digits (scale) to accomodate numbers like either. >>> worst_decimal(Decimal('762.1'), Decimal('-1.983')) Decimal('999.999') """ (d1b4, d1after) = _places_b4_and_after_decimal(d1) (d2b4, d2after) = _places_b4_and_after_decimal(d2) return Decimal('9' * max(d1b4, d2b4) + '.' + '9' * max(d1after, d2after))
python
def worst_decimal(d1, d2): """ Given two Decimals, return a 9-filled decimal representing both enough > 0 digits and enough < 0 digits (scale) to accomodate numbers like either. >>> worst_decimal(Decimal('762.1'), Decimal('-1.983')) Decimal('999.999') """ (d1b4, d1after) = _places_b4_and_after_decimal(d1) (d2b4, d2after) = _places_b4_and_after_decimal(d2) return Decimal('9' * max(d1b4, d2b4) + '.' + '9' * max(d1after, d2after))
[ "def", "worst_decimal", "(", "d1", ",", "d2", ")", ":", "(", "d1b4", ",", "d1after", ")", "=", "_places_b4_and_after_decimal", "(", "d1", ")", "(", "d2b4", ",", "d2after", ")", "=", "_places_b4_and_after_decimal", "(", "d2", ")", "return", "Decimal", "(", ...
Given two Decimals, return a 9-filled decimal representing both enough > 0 digits and enough < 0 digits (scale) to accomodate numbers like either. >>> worst_decimal(Decimal('762.1'), Decimal('-1.983')) Decimal('999.999')
[ "Given", "two", "Decimals", "return", "a", "9", "-", "filled", "decimal", "representing", "both", "enough", ">", "0", "digits", "and", "enough", "<", "0", "digits", "(", "scale", ")", "to", "accomodate", "numbers", "like", "either", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L122-L132
catherinedevlin/ddl-generator
ddlgenerator/typehelpers.py
set_worst
def set_worst(old_worst, new_worst): """ Pad new_worst with zeroes to prevent it being shorter than old_worst. >>> set_worst(311920, '48-49') '48-490' >>> set_worst(98, -2) -20 """ if isinstance(new_worst, bool): return new_worst # Negative numbers confuse the length calculation. negative = ( (hasattr(old_worst, '__neg__') and old_worst < 0) or (hasattr(new_worst, '__neg__') and new_worst < 0) ) try: old_worst = abs(old_worst) new_worst = abs(new_worst) except TypeError: pass # now go by length new_len = len(str(new_worst)) old_len = len(str(old_worst)) if new_len < old_len: new_type = type(new_worst) new_worst = str(new_worst).ljust(old_len, '0') new_worst = new_type(new_worst) # now put the removed negative back if negative: try: new_worst = -1 * abs(new_worst) except: pass return new_worst
python
def set_worst(old_worst, new_worst): """ Pad new_worst with zeroes to prevent it being shorter than old_worst. >>> set_worst(311920, '48-49') '48-490' >>> set_worst(98, -2) -20 """ if isinstance(new_worst, bool): return new_worst # Negative numbers confuse the length calculation. negative = ( (hasattr(old_worst, '__neg__') and old_worst < 0) or (hasattr(new_worst, '__neg__') and new_worst < 0) ) try: old_worst = abs(old_worst) new_worst = abs(new_worst) except TypeError: pass # now go by length new_len = len(str(new_worst)) old_len = len(str(old_worst)) if new_len < old_len: new_type = type(new_worst) new_worst = str(new_worst).ljust(old_len, '0') new_worst = new_type(new_worst) # now put the removed negative back if negative: try: new_worst = -1 * abs(new_worst) except: pass return new_worst
[ "def", "set_worst", "(", "old_worst", ",", "new_worst", ")", ":", "if", "isinstance", "(", "new_worst", ",", "bool", ")", ":", "return", "new_worst", "# Negative numbers confuse the length calculation. ", "negative", "=", "(", "(", "hasattr", "(", "old_worst", ","...
Pad new_worst with zeroes to prevent it being shorter than old_worst. >>> set_worst(311920, '48-49') '48-490' >>> set_worst(98, -2) -20
[ "Pad", "new_worst", "with", "zeroes", "to", "prevent", "it", "being", "shorter", "than", "old_worst", ".", ">>>", "set_worst", "(", "311920", "48", "-", "49", ")", "48", "-", "490", ">>>", "set_worst", "(", "98", "-", "2", ")", "-", "20" ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L134-L170
catherinedevlin/ddl-generator
ddlgenerator/typehelpers.py
best_representative
def best_representative(d1, d2): """ Given two objects each coerced to the most specific type possible, return the one of the least restrictive type. >>> best_representative(Decimal('-37.5'), Decimal('0.9999')) Decimal('-99.9999') >>> best_representative(None, Decimal('6.1')) Decimal('6.1') >>> best_representative(311920, '48-49') '48-490' >>> best_representative(6, 'foo') 'foo' >>> best_representative(Decimal('4.95'), Decimal('6.1')) Decimal('9.99') >>> best_representative(Decimal('-1.9'), Decimal('6.1')) Decimal('-9.9') """ if hasattr(d2, 'strip') and not d2.strip(): return d1 if d1 is None: return d2 elif d2 is None: return d1 preference = (datetime.datetime, bool, int, Decimal, float, str) worst_pref = 0 worst = '' for coerced in (d1, d2): pref = preference.index(type(coerced)) if pref > worst_pref: worst_pref = pref worst = set_worst(worst, coerced) elif pref == worst_pref: if isinstance(coerced, Decimal): worst = set_worst(worst, worst_decimal(coerced, worst)) elif isinstance(coerced, float): worst = set_worst(worst, max(coerced, worst)) else: # int, str if len(str(coerced)) > len(str(worst)): worst = set_worst(worst, coerced) return worst
python
def best_representative(d1, d2): """ Given two objects each coerced to the most specific type possible, return the one of the least restrictive type. >>> best_representative(Decimal('-37.5'), Decimal('0.9999')) Decimal('-99.9999') >>> best_representative(None, Decimal('6.1')) Decimal('6.1') >>> best_representative(311920, '48-49') '48-490' >>> best_representative(6, 'foo') 'foo' >>> best_representative(Decimal('4.95'), Decimal('6.1')) Decimal('9.99') >>> best_representative(Decimal('-1.9'), Decimal('6.1')) Decimal('-9.9') """ if hasattr(d2, 'strip') and not d2.strip(): return d1 if d1 is None: return d2 elif d2 is None: return d1 preference = (datetime.datetime, bool, int, Decimal, float, str) worst_pref = 0 worst = '' for coerced in (d1, d2): pref = preference.index(type(coerced)) if pref > worst_pref: worst_pref = pref worst = set_worst(worst, coerced) elif pref == worst_pref: if isinstance(coerced, Decimal): worst = set_worst(worst, worst_decimal(coerced, worst)) elif isinstance(coerced, float): worst = set_worst(worst, max(coerced, worst)) else: # int, str if len(str(coerced)) > len(str(worst)): worst = set_worst(worst, coerced) return worst
[ "def", "best_representative", "(", "d1", ",", "d2", ")", ":", "if", "hasattr", "(", "d2", ",", "'strip'", ")", "and", "not", "d2", ".", "strip", "(", ")", ":", "return", "d1", "if", "d1", "is", "None", ":", "return", "d2", "elif", "d2", "is", "No...
Given two objects each coerced to the most specific type possible, return the one of the least restrictive type. >>> best_representative(Decimal('-37.5'), Decimal('0.9999')) Decimal('-99.9999') >>> best_representative(None, Decimal('6.1')) Decimal('6.1') >>> best_representative(311920, '48-49') '48-490' >>> best_representative(6, 'foo') 'foo' >>> best_representative(Decimal('4.95'), Decimal('6.1')) Decimal('9.99') >>> best_representative(Decimal('-1.9'), Decimal('6.1')) Decimal('-9.9')
[ "Given", "two", "objects", "each", "coerced", "to", "the", "most", "specific", "type", "possible", "return", "the", "one", "of", "the", "least", "restrictive", "type", "." ]
train
https://github.com/catherinedevlin/ddl-generator/blob/db6741216d1e9ad84b07d4ad281bfff021d344ea/ddlgenerator/typehelpers.py#L172-L213