code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
try: value = int(value) is_positive = (value > 0) except ValueError: raise ValueError('%s should be an integer; got %r' % (name, value)) if is_positive: return value else: raise ValueError('%s should be positive; got %r' % (name, value))
def check_positive_integer(name, value)
Check a value is a positive integer. Returns the value if so, raises ValueError otherwise.
2.22155
2.218116
1.001548
value = value.lower() # Trim a leading hash if value.startswith('#'): value = value[1:] if len(value) != 6: raise ValueError( 'Color should be six hexadecimal digits, got %r (%s)' % (value, len(value))) if re.sub(r'[a-f0-9]', '', value): raise V...
def check_color_input(value)
Check a value is a valid colour input. Returns a parsed `RGBColor` instance if so, raises ValueError otherwise.
2.445081
2.316513
1.055501
''' Extract octahedra as lists of sequence numbers of corner atoms ''' octahedra = [] for n, i in enumerate(atoms): found = [] if i.symbol in Perovskite_Structure.B: for m, j in enumerate(self.virtual_atoms): if j.symbol...
def get_octahedra(self, atoms, periodicity=3)
Extract octahedra as lists of sequence numbers of corner atoms
4.58088
3.826454
1.197161
''' Extract the main tilting plane basing on Z coordinate ''' sequence = sorted(sequence, key=lambda x: self.virtual_atoms[ x ].z) in_plane = [] for i in range(0, len(sequence)-4): if abs(self.virtual_atoms[ sequence[i] ].z - self.virtual_atoms[ sequence[i+1] ...
def get_tiltplane(self, sequence)
Extract the main tilting plane basing on Z coordinate
2.406447
2.012722
1.195618
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)
Returns dict of help_context keys (description texts used in `EmailRegistry.register()` method).
2.366831
1.805762
1.310711
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)
Returns dict of help_context values (example values submitted in `EmailRegistry.register()` method).
2.603175
2.206338
1.179862
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)
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. :para...
3.961097
3.392277
1.167681
if not self.is_registered(path): raise NotRegistered("Email template not registered") return self._registry[path]
def get_registration(self, path)
Returns registration item for specified path. If an email template is not registered, this will raise NotRegistered.
7.440567
3.694653
2.013875
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)
Returns text that can be used as form help text for creating email templates.
3.983676
3.885698
1.025215
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)...
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.
4.956377
4.587227
1.080473
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' % (out...
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.
4.313684
4.154452
1.038328
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[co...
def update_stats(self, file_result)
Reads the data from a FileResult and updates overall statistics :param file_result: A FileResult instance
2.046226
2.010142
1.017951
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.forma...
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...
2.983048
2.336475
1.27673
# 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)]...
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, ...
3.73973
3.547989
1.054042
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...
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)], [...
4.027982
3.184187
1.264995
r 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)) om...
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]: ... ...
2.549807
2.740178
0.930526
r 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)
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))...
3.982085
3.915694
1.016955
r 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]+ome...
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]: ... ...
3.496605
2.79646
1.250368
r 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): ...
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[...
3.183617
3.146385
1.011833
r 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: ...
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) ...
3.781535
3.517853
1.074955
r 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.repl...
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'
3.552701
3.354699
1.059022
r 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)
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.sym...
3.777449
5.429496
0.695727
r 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): ...
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 indic...
2.656746
2.804202
0.947416
r 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 i...
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_triangu...
2.250213
2.240191
1.004474
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 = ...
def eplotter(task, data): # CRYSTAL, VASP, EXCITING ''' eplotter is like bdplotter but less complicated ''' results, color, fdata = [], None, [] if task == 'optstory'
eplotter is like bdplotter but less complicated
3.383385
3.307087
1.023071
def lande_g_factors(element, isotope, L=None, J=None, F=None): r 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...
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))) ...
null
null
null
def zeeman_energies(fine_state, Bz): r 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,...
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.83044285506388...
null
null
null
def paschen_back_energies(fine_state, Bz): r 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)] A...
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.8048...
null
null
null
''' 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 Run...
def assign_parser(self, name)
Restricts parsing **name** is a name of the parser class NB: this is the PUBLIC method @procedure
10.303885
3.962873
2.600105
''' 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...
def formula(self, atom_sequence)
Constructs standardized chemical formula NB: this is the PUBLIC method @returns formula_str
4.572168
3.47893
1.314246
''' 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_...
def savvyize(self, input_string, recursive=False, stemma=False)
Determines which files should be processed NB: this is the PUBLIC method @returns filenames_list
2.479768
2.237358
1.108347
''' 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 ...
def _parse(self, parsable, parser_name)
Low-level parsing NB: this is the PRIVATE method @returns tilde_obj, error
4.764866
3.200439
1.488816
''' 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...
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
9.262054
6.452307
1.435464
''' 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 app...
def postprocess(self, calc, with_module=None, dry_run=None)
Invokes module(s) API NB: this is the PUBLIC method @returns apps_dict
4.173883
3.511737
1.188552
''' 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.Gri...
def merge(self, session, checksums, title)
Merges calcs into a new calc called DATASET NB: this is the PUBLIC method @returns DATASET, error
6.090228
4.470754
1.362237
''' 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!' ...
def augment(self, session, parent, addendum)
Augments a DATASET with some calcs NB: this is the PUBLIC method @returns error
3.74753
3.436017
1.090661
# 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("....
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.
4.840651
4.903696
0.987143
return [path for path in glob.glob(os.path.join(os.path.normpath(baseDir), '*')) if isCLIExecutable(path)]
def listCLIExecutables(baseDir)
Return list of paths to valid CLI executables within baseDir (non-recursively). This calls `isCLIExecutable()` on all files within `baseDir`.
3.602046
2.703553
1.332338
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[:m...
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 ...
8.814901
7.10114
1.241336
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: ...
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()).
2.629686
2.304779
1.140971
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()
Generates filenames of the form 'specktre_123AB.png'. The random noise is five characters long, which allows for 62^5 = 916 million possible filenames.
5.977121
2.871867
2.081267
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)
Given a coordinate generator and a filename, render those coordinates in a new image and save them to the file.
2.669787
2.797505
0.954346
if self.isEnabledFor(TRACE): self._log(TRACE, msg, args, **kwargs)
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)
3.15869
3.123666
1.011213
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)
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
2.863827
3.243449
0.882957
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)
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
2.96096
3.441355
0.860405
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)
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 va...
1.871622
2.074331
0.902277
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)
Retrieve the state of a given Class. :param clz: types.ClassType :return: Class state. :rtype: dict
2.814572
3.2638
0.86236
''' 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 n...
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
3.352118
1.85565
1.806438
''' 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__'] ...
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)
6.557625
2.255055
2.907966
r 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 =...
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 e...
2.563199
2.435486
1.052438
r 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) ...
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, o...
3.237044
2.832139
1.142968
r 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)]]) R...
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. ...
2.013403
2.141922
0.939999
r return A*rho*A.adjoint() - (A.adjoint()*A*rho + rho*A.adjoint()*A)/2
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([ [ rh...
7.212574
3.036146
2.375569
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: []) ret...
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_R...
2.360871
2.078141
1.136049
def complex_matrix_plot(A, logA=False, normalize=False, plot=True, **kwds): r 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...
r"""A function to plot complex matrices.
null
null
null
def bar_chart_mf(data, path_name): 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_...
Make a bar chart for data on MF quantities.
null
null
null
def draw_plane_wave_3d(ax, beam, dist_to_center=0): 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...
Draw the polarization of a plane wave.
null
null
null
def draw_lasers_3d(ax, lasers, name=None, distances=None, lim=None): 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]) == Mo...
Draw MOT lasers in 3d.
null
null
null
def rotate_and_traslate(cur, alpha, v0): r 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...
r"""Rotate and translate a curve.
null
null
null
def mirror(ax, p0, alpha=0, size=2.54, width=0.5, format=None): r 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 = [(si...
r"""Draw a mirror.
null
null
null
def eye(ax, p0, size=1.0, alpha=0, format=None, **kwds): r 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 = ...
r"""Draw an eye.
null
null
null
def beam_splitter(ax, p0, size=2.54, alpha=0, format=None, **kwds): r 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...
r"""Draw a beam splitter.
null
null
null
def simple_beam_splitter(ax, p0, size=2.54, width=0.1, alpha=0, format=None, **kwds): r 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,...
r"""Draw a simple beam splitter.
null
null
null
def draw_arith(ax, p0, size=1, alpha=0, arith=None, format=None, fontsize=10, **kwds): r 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 i...
r"""Draw an arithmetic operator.
null
null
null
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 ax.plot([p[0]-l/2.0, p[0]+l/2.0], [p[1], p[1]], color='black', **kwds) if text != '': if alignment == 'left': ...
r"""Draw a quantum state for energy level diagrams.
null
null
null
def decay(ax, p0, pf, A, n, format=None, **kwds): r 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 = r...
r"""Draw a spontaneous decay as a wavy line.
null
null
null
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...
def dup2(a, b, timeout=3)
Like os.dup2, but retry on EBUSY
3.311341
2.829122
1.170448
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') ...
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()
1.827051
1.979118
0.923164
return pipes(sys.stdout, sys.stderr, encoding=encoding)
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.
5.047145
5.901331
0.855255
global _mighty_wurlitzer if _mighty_wurlitzer is None: _mighty_wurlitzer = sys_pipes(encoding) _mighty_wurlitzer.__enter__()
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.
4.076057
4.072845
1.000789
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)
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
6.886117
6.089506
1.130817
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)
Unload me as an IPython extension Use: %unload_ext wurlitzer
6.256025
7.514984
0.832473
if self.encoding: data = data.decode(self.encoding, 'replace') return data
def _decode(self, data)
Decode data, if any Called before passing to stdout/stderr streams
3.837687
3.41885
1.122508
t = self.tokenizer for f in new_filters: t = f(t) self.tokenizer = t
def push_filters(self, new_filters)
Add a filter to the tokenizer chain.
6.363364
2.940361
2.164144
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)
Yields bad words and suggested alternate spellings.
6.164481
4.404745
1.399509
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 nam...
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
2.823414
2.815432
1.002835
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_...
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.
2.288028
2.056353
1.112663
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)
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...
2.994893
2.201692
1.360269
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 ...
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
2.248225
2.253185
0.997799
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 ...
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(201...
4.062983
4.011055
1.012946
tup = d.as_tuple() return (len(tup.digits) + tup.exponent, max(-1*tup.exponent, 0))
def _places_b4_and_after_decimal(d)
>>> _places_b4_and_after_decimal(Decimal('54.212')) (2, 3)
6.763465
6.006312
1.126059
(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)
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')
3.351076
3.568464
0.939081
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) ne...
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
2.93006
2.925526
1.00155
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(c...
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')...
2.866378
2.899512
0.988572
preference = (datetime.datetime, bool, int, Decimal, float, str) worst_pref = 0 worst = '' for datum in data: coerced = coerce_to_specific(datum) pref = preference.index(type(coerced)) if pref > worst_pref: worst_pref = pref worst = coerced el...
def best_coercable(data)
Given an iterable of scalar data, returns the datum representing the most specific data type the list overall can be coerced into, preferring datetimes, then bools, then integers, then decimals, then floats, then strings. >>> best_coercable((6, '2', 9)) 6 >>> best_coercable((Decimal('6.1'), 2, 9)) ...
2.999654
2.647821
1.132876
try: if len(_complex_enough_to_be_date.findall(datum)) > 1: dateutil.parser.parse(datum) return sa.DATETIME except (TypeError, ValueError): pass try: (prec, scale) = precision_and_scale(datum) return sa.DECIMAL(prec, scale) except TypeError: ...
def sqla_datatype_for(datum)
Given a scalar Python value, picks an appropriate SQLAlchemy data type. >>> sqla_datatype_for(7.2) DECIMAL(precision=2, scale=1) >>> sqla_datatype_for("Jan 17 2012") <class 'sqlalchemy.sql.sqltypes.DATETIME'> >>> sqla_datatype_for("something else") Unicode(length=14)
5.350575
5.569588
0.960677
table = Table(tbl, table_name=table_name, varying_length_text=args.text, uniques=args.uniques, pk_name = args.key, force_pk=args.force_key, reorder=args.reorder, data_size_cushion=args.cushion, save_metadata_to=args.save_metadata_to, metadata_source=args.use_metadata_from, ...
def generate_one(tbl, args, table_name=None, file=None)
Prints code (SQL, SQLAlchemy, etc.) to define a table.
4.557473
4.362067
1.044797
if hasattr(args, 'split'): args = args.split() args = parser.parse_args(args, namespace) set_logging(args) logging.info(str(args)) if args.dialect in ('pg', 'pgsql', 'postgres'): args.dialect = 'postgresql' if args.dialect.startswith('dj'): args.dialect = 'django' ...
def generate(args=None, namespace=None, file=None)
Genereate DDL from data sources named. :args: String or list of strings to be parsed for arguments :namespace: Namespace to extract arguments from :file: Write to this open file object (default stdout)
3.801243
3.737684
1.017005
if engine and engine.name == 'postgresql': # not implemented for other RDBMS; necessity unknown conn = engine.connect() qry = for (qry, qual_name) in list(conn.execute(qry)): (lastval, ) = conn.execute(qry).first() nextval = int(lastval) + 1 ...
def emit_db_sequence_updates(engine)
Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.
6.742002
6.3908
1.054954
dialect = self._dialect(dialect) creator = CreateTable(self.table).compile(mock_engines[dialect]) creator = "\n".join(l for l in str(creator).splitlines() if l.strip()) # remove empty lines comments = "\n\n".join(self._comment_wrapper.fill("in %s: %s" % ...
def ddl(self, dialect=None, creates=True, drops=True)
Returns SQL to define the table.
4.407841
4.202994
1.048738
table_def = self.table_backref_remover.sub('', self.table.__repr__()) # inject UNIQUE constraints into table definition constraint_defs = [] for constraint in self.table.constraints: if isinstance(constraint, sa.sql.schema.UniqueConstraint): col_list...
def sqlalchemy(self, is_top=True)
Dumps Python code to set up the table's SQLAlchemy model
3.501619
3.425947
1.022088
if datum is None or (needs_conversion and not str(datum).strip()): return 'NULL' pytype = self.columns[col]['pytype'] if needs_conversion: if pytype == datetime.datetime: datum = dateutil.parser.parse(datum) elif pytype == bool: ...
def _prep_datum(self, datum, dialect, col, needs_conversion)
Puts a value in proper format for a SQL string
3.504213
3.402173
1.029993
if self.source.db_engine and self.source.db_engine.name != 'postgresql': # not implemented for other RDBMS; necessity unknown conn = self.source.db_engine.connect() qry = result = [] for (sequence, ) in list(conn.execute(qry)): ...
def emit_db_sequence_updates(self)
Set database sequence objects to match the source db Relevant only when generated from SQLAlchemy connection. Needed to avoid subsequent unique key violations after DB build.
5.651749
5.180165
1.091037
result = [self.ddl(dialect, creates=creates, drops=drops)] if inserts: for row in self.inserts(dialect): result.append(row) return '\n'.join(result)
def sql(self, dialect=None, inserts=False, creates=True, drops=True, metadata_source=None)
Combined results of ``.ddl(dialect)`` and, if ``inserts==True``, ``.inserts(dialect)``.
3.246185
2.770831
1.171556
result = _illegal_in_column_name.sub("_", key.strip()) if result[0].isdigit(): result = '_%s' % result if result.upper() in sql_reserved_words: result = '_%s' % key return result.lower()
def clean_key_name(key)
Makes ``key`` a valid and appropriate SQL column name: 1. Replaces illegal characters in column names with ``_`` 2. Prevents name from beginning with a digit (prepends ``_``) 3. Lowercases name. If you want case-sensitive table or column names, you are a bad person and you should feel bad.
4.890246
4.720593
1.035939
# transform namedtuples to OrderedDicts if hasattr(data, '_fields'): data = OrderedDict((k,v) for (k,v) in zip(data._fields, data)) # Recursively clean up child dicts and lists if hasattr(data, 'items') and hasattr(data, '__setitem__'): for (key, val) in data.items(): da...
def walk_and_clean(data)
Recursively walks list of dicts (which may themselves embed lists and dicts), transforming namedtuples to OrderedDicts and using ``clean_key_name(k)`` to make keys into SQL-safe column names >>> data = [{'a': 1}, [{'B': 2}, {'B': 3}], {'F': {'G': 4}}] >>> pprint(walk_and_clean(data)) [OrderedDi...
3.330218
3.076073
1.08262
templates = ['%s_%%s' % table_name, '%s', '_%s'] for stub in ['id', 'num', 'no', 'number']: for t in templates: if t % stub in fieldnames: return t % stub
def _id_fieldname(fieldnames, table_name = '')
Finds the field name from a dict likeliest to be its unique ID >>> _id_fieldname({'bar': True, 'id': 1}, 'foo') 'id' >>> _id_fieldname({'bar': True, 'foo_id': 1, 'goo_id': 2}, 'foo') 'foo_id' >>> _id_fieldname({'bar': True, 'baz': 1, 'baz_id': 3}, 'foo')
5.438345
8.793625
0.618442
val = parent[key] name = "%s['%s']" % (parent_name, key) logging.debug("Unnesting dict %s" % name) id = _id_fieldname(val, parent_name) if id: logging.debug("%s is %s's ID" % (id, key)) if len(val) <= 2: logging.debug('Removing ID column %s.%s' % (key, id)) ...
def unnest_child_dict(parent, key, parent_name='')
If ``parent`` dictionary has a ``key`` whose ``val`` is a dict, unnest ``val``'s fields into ``parent`` and remove ``key``. >>> parent = {'province': 'Québec', 'capital': {'name': 'Québec City', 'pop': 491140}} >>> unnest_child_dict(parent, 'capital', 'provinces') >>> pprint(parent) {'capital_name'...
2.993746
3.120849
0.959273
possible_fk_names = ['%s_id' % parent_name, '_%s_id' % parent_name, 'parent_id', ] if pk_name: possible_fk_names.insert(0, '%s_%s' % (parent_name, pk_name.strip('_'))) children = defaultdict(list) field_names_used_by_children = defaultdict(set) child_fk_names = {} parent = ParentTab...
def unnest_children(data, parent_name='', pk_name=None, force_pk=False)
For each ``key`` in each row of ``data`` (which must be a list of dicts), unnest any dict values into ``parent``, and remove list values into separate lists. Return (``data``, ``pk_name``, ``children``, ``child_fk_names``) where ``data`` the transformed input list ``pk_name`` field name of...
2.811517
2.691225
1.044698
pk_values = all_values_for(self, key_name) if not pk_values: return ('absent', int) # could still use it key_type = type(th.best_coercable(pk_values)) num_unique_values = len(set(pk_values)) if num_unique_values < len(pk_values): return (False, N...
def suitability_as_key(self, key_name)
Returns: (result, key_type) ``result`` is True, False, or 'absent' or 'partial' (both still usable) ``key_type`` is ``int`` for integer keys or ``str`` for hash keys
5.864645
4.509116
1.30062