text
stringlengths
81
112k
ur"""Calculate the matrix of decay between states. This function calculates the matrix :math:`\gamma_{ij}` of decay rates between states :math:`|i\rangle` and :math:`|j\rangle` (in the units specified by the Omega argument). >>> import numpy as np >>> g = State("Rb", 87, 5, 0, 1/Integer(2)) >>...
r"""Return the reduced matrix element of the position operator in Bohr\ radii. We have two available conventions for this 1.- [Racah]_ and [Edmonds74]_ .. math:: \langle \gamma_i, J_i, M_i| \hat{T}^k_q| \gamma_j, J_j, M_j\rangle \ = (-1)^{J_i-M_i} \ \left(\begin{matrix}J_i & k...
r"""Calculate the reduced matrix elements for a list of fine states. This function calculates the reduced matrix elments .. math:: \langle N,L,J||T^1(r)||N',L',J'\rangle given a list of fine states. We calculate the reduced matrix elements found in [SteckRb87]_ for the \ D1 and D2 lines ...
r"""Calculate a matrix element of the electric dipole (in the helicity basis). We calculate the matrix element for the cyclical transition of the D2 line in Rb 87. >>> from sympy import symbols >>> red = symbols("r", positive=True) >>> half = 1/Integer(2) >>> II = 3*half >>> matrix_ele...
ur"""Calculate the matrix elements of the electric dipole (in the helicity basis). We calculate all matrix elements for the D2 line in Rb 87. >>> from sympy import symbols, pprint >>> red = symbols("r", positive=True) >>> reduced_matrix_elements = [[0, -red], [red, 0]] >>> g = State("Rb", 87, ...
r"""Calculate the matrices omega_ij, gamma_ij, r_pij. This function calculates the matrices omega_ij, gamma_ij and r_pij given a list of atomic states. The states can be arbitrarily in their fine, hyperfine or magnetic detail. def calculate_matrices(states, Omega=1): r"""Calculate the matrices omega_i...
r"""This function returns the density in a rubidium or cesium vapour in kg/m^-3. It receives as input the temperature in Kelvins, the name of the element, and optionally the isotope. If no isotope is specified, the density of a vapour with the natural abundances will be returned. This is calculated...
r"""Return the Doppler width of a transition at a given temperature (in angular frequency). The usual Doppler FWHM of the rubidium D2 line (in MHz). >>> g = State("Rb", 87, 5, 0, 1/Integer(2), 2) >>> e = State("Rb", 87, 5, 1, 3/Integer(2)) >>> t = Transition(e, g) >>> omega = doppler_width(t, ...
r"""Return a thermal state for a given set of levels. INPUT: - ``omega_level`` - The angular frequencies of each state. - ``T`` - The temperature of the ensemble (in Kelvin). - ``return_diagonal`` - Whether to return only the populations. >>> ground = State("Rb", 85, 5, 0, 1/Integer(2)) >>...
r"""Find all allowed transitions. This function finds all allowed transitions (by electric-dipole selection rules) in the atom. >>> atom=Atom("Rb",85) >>> transitions=atom.transitions() >>> print(len(transitions)) 270 Arguments omega_min and omega_max can be us...
r"""Return a fast function that returns the Doppler terms. >>> from sympy import Matrix, symbols >>> from scipy.constants import physical_constants >>> from fast import PlaneWave >>> from fast.bloch import phase_transformation >>> Ne = 2 >>> Nl = 1 >>> unfolding = Unfolding(Ne, True, True, ...
r"""Return a function that returns values of a Maxwell-Boltzmann distribution. >>> from fast import Atom >>> mass = Atom("Rb", 87).mass >>> f = fast_maxwell_boltzmann(mass) >>> print f(0, 273.15+20) 0.00238221482739 >>> import numpy as np >>> v = np.linspace(-600, 600, 101) >>> dis...
r"""Return a fast function that returns the numeric right-hand sides of \ inhomogeneous Bloch equations. 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 electri...
r"""Return a spectrum of time evolutions of the density matrix. We test a basic two-level system. >>> from fast.bloch import phase_transformation >>> from fast import PlaneWave, electric_field_amplitude_top, Atom >>> Ne = 2 >>> Nl = 1 >>> a0 = physical_constants["Bohr radius"][0] >>> rm = ...
r"""Return the average density matrix of an inhomogeneous ensemble. def average(self, rho): r"""Return the average density matrix of an inhomogeneous ensemble.""" def marginal(f, rho): remaining = len(f.shape) if remaining == 0: return rho rho = sum([...
r"""Recalculate the doppler broadening for a given temperature. def reset(self, T): r"""Recalculate the doppler broadening for a given temperature.""" self.__init__(self.shape, self.stds, T, self.mass, self.detuning_knob, self.k, self.omega_level, self.xi, se...
points = read_roi(fileobj) Read ImageJ's ROI format. Points are returned in a nx2 array. Each row is in [row, column] -- that is, (y,x) -- order. def read_roi(fileobj): ''' points = read_roi(fileobj) Read ImageJ's ROI format. Points are returned in a nx2 array. Each row is in [row, column] --...
r"""Calculate the allowed total angular momenta. >>> from sympy import Integer >>> L = 1 >>> S = 1/Integer(2) >>> perm_j(L, S) [1/2, 3/2] def perm_j(j1, j2): r"""Calculate the allowed total angular momenta. >>> from sympy import Integer >>> L = 1 >>> S = 1/Integer(2) >>> perm_...
ur"""For angular momenta $j_1, j_2$ the unitary transformation from the \ uncoupled basis into the $j = j_1 \oplus j_2$ coupled basis. >>> from sympy import Integer, pprint >>> L = 0 >>> S = 1/Integer(2) >>> pprint(coupling_matrix_2j(L, S)) ⎡1 0⎤ ⎢ ⎥ ⎣0 1⎦ >>> L = 1 >>> S ...
ur"""For angular momenta $j_1, j_2, j_3$ the unitary transformation from the \ uncoupled basis into the $j = (j_1 \oplus j_2)\oplus j_3$ coupled basis. >>> from sympy import Integer, pprint >>> L = 0 >>> S = 1/Integer(2) >>> II = 3/Integer(2) >>> pprint(coupling_matrix_3j(L, S, II)) ⎡ ...
ur"""Return the angular momentum operator matrix (divided by hbar) for a\ given J angular momentum. INPUT: - ``ind`` - A string ("x", "y", "z", "all") indicating which direction \ to calculate, or to return them all as :math:`(J_x, J_y, J_z)`. OUTPUT: - matrix forms of angular momentum oper...
ur"""Return the matrix representation of the orbita, electron-spin, and \ nuclear-spin angular momentum operators \ :math:`\hat{\vec{L}}, \hat{\vec{L}}, \hat{\vec{L}}` in the coupled basis \ :math:`[|J, -J\rangle, \cdot, |J, J\rangle]`. INPUT: - ``ind`` - A string ("x", "y", "z", "all") indicatin...
ur"""Return a matrix representation of the spherical tensor with quantum numbers $J_i, J_j, K, Q$. >>> from sympy import pprint >>> pprint(spherical_tensor(1, 1, 1, 0)) ⎡-√2 ⎤ ⎢──── 0 0 ⎥ ⎢ 2 ⎥ ⎢ ⎥ ⎢ 0 0 0 ⎥ ⎢ ⎥ ⎢ √2⎥ ⎢ 0 0...
u"""Return the small Wigner d matrix for angular momentum J. We use the general formula from [Edmonds74]_, equation 4.1.15. Some examples form [Edmonds74]_: >>> from sympy import Integer, symbols, pi >>> half = 1/Integer(2) >>> beta = symbols("beta", real=True) >>> wigner_d_small(half, beta) ...
u"""Return the Wigner D matrix for angular momentum J. We use the general formula from [Edmonds74]_, equation 4.1.12. The simplest possible example: >>> from sympy import Integer, symbols, pprint >>> half = 1/Integer(2) >>> alpha, beta, gamma = symbols("alpha, beta, gamma", real=True) >>> ppr...
r"""Return a block-wise diagonal Wigner D matrix for that rotates a density matrix of an ensemble of particles in definite total angular momentum states given by J_values. >>> from sympy import Integer, pi >>> half = 1/Integer(2) >>> J_values = [2*half, 0] >>> density_matrix_rotation(J_values, ...
Generate coordinates for a tiling of unit squares. def generate_unit_squares(image_width, image_height): """Generate coordinates for a tiling of unit squares.""" # Iterate over the required rows and cells. The for loops (x, y) # give the coordinates of the top left-hand corner of each square: # # ...
Generate coordinates for a tiling of unit triangles. def generate_unit_triangles(image_width, image_height): """Generate coordinates for a tiling of unit triangles.""" # Our triangles lie with one side parallel to the x-axis. Let s be # the length of one side, and h the height of the triangle. # #...
Restore settings to default values. def restore_default_settings(): """ Restore settings to default values. """ global __DEFAULTS __DEFAULTS.CACHE_DIR = defaults.CACHE_DIR __DEFAULTS.SET_SEED = defaults.SET_SEED __DEFAULTS.SEED = defaults.SEED logging.info('Settings reverted to their defau...
Load config file into default settings def load_config(config_file='~/.stancache.ini'): """ Load config file into default settings """ if not os.path.exists(config_file): logging.warning('Config file does not exist: {}. Using default settings.'.format(config_file)) return ## get user-le...
Shortcut function for EmailFromTemplate class @return: None def send_email(name, ctx_dict, send_to=None, subject=u'Subject', **kwargs): """ Shortcut function for EmailFromTemplate class @return: None """ eft = EmailFromTemplate(name=name) eft.subject = subject eft.context = ctx_dict ...
:raises: ValueError def set_level(cls, level): """ :raises: ValueError """ level = ( level if not is_str(level) else int(LOGGING_LEVELS.get(level.upper(), level)) ) for handler in root.handlers: handler.setLevel(level) ...
:raises: ValueError def load_config(cls, configfile="logging.yaml"): """ :raises: ValueError """ configfile = getenv(cls.CONFIGFILE_ENV_KEY, configfile) if isfile(configfile): with open(configfile, "r") as cf: # noinspection PyBroadException ...
Parse a string to remove and replace all wiki markup tags def __parse(self, string=''): ''' Parse a string to remove and replace all wiki markup tags ''' self.string = string self.string = self.wiki_re.sub('', self.string) # search for lists self.listmatch = re.s...
Parse a string object to de-wikified text def parse_string(self, string=''): ''' Parse a string object to de-wikified text ''' self.strings = string.splitlines(1) self.strings = [self.__parse(line) for line in self.strings] return ''.join(self.strings)
This function runs the Runge-Kutta method compiled in path+name... def run_evolution(path,name,E0,laser_frequencies, N_iter,dt,N_states, spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None, rho0=None,print_steps=False, integrate=False, save_systems=False,save_eigenvalues=False,r...
r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues`` is set to ``True``. It will return the oscillation periods, and the shortest and half lives. The results are lists ordered as: ``[detunings, oscillation_periods_1, oscillation_periods_N**2-1, half_lives_1, half_liv...
r'''This function can be called after calling ``run_diagonalization`` if the option ``save_eigenvalues`` is set to ``True``. It will return the shortest and longest oscillation period, and the shortest and longest half life. The results are lists ordered as: ``[detunings, shortest_oscillations, longest_oscillations, s...
This function returns the value of E0 (the amplitude of the electric field) at a given saturation parameter s0=I/I0, where I0=2.50399 mW/cm^2 is the saturation intensity of the D2 line of Rubidium for linearly polarized light. def electric_field_amplitude_intensity(s0,Omega=1.0e6): '''This function returns the v...
Retrieve unique hash in a cross-platform manner: this is how calculation identity is determined def get_checksum(self): ''' Retrieve unique hash in a cross-platform manner: this is how calculation identity is determined ''' if self._checksum: return self._che...
NB only used for perovskite_tilting app def refine_cell(self, tilde_obj): ''' NB only used for perovskite_tilting app ''' try: lattice, positions, numbers = spg.refine_cell(tilde_obj['structures'][-1], symprec=self.accuracy, angle_tolerance=self.angle_tolerance) except Exception...
Reads all lines from the current data source and yields each FileResult objects def parse(self): """ Reads all lines from the current data source and yields each FileResult objects """ if self.data is None: raise ValueError('No input data provided, unable to parse') ...
Get and return data from the API. :returns: A str, list, or dict, depending on the input values and API data. def _get(function, return_format=None): """Get and return data from the API. :returns: A str, list, or dict, depending on the input values and API data. """ if return_format: retu...
Returns possible backscatter data. This report only includes "syn ack" data and is summarized by source port. :param date: optional string (in Y-M-D format) or datetime.date() object :param rows: optional number of rows returned (default 1000) :returns: list -- backscatter data. def backscatter(date=...
Returns a summary of the information our database holds for a particular IP address (similar to /ipinfo.html). In the returned data: Count: (also reports or records) total number of packets blocked from this IP. Attacks: (also targets) number of unique destination IP addresses for these packet...
Summary information about a particular port. In the returned data: Records: Total number of records for a given date. Targets: Number of unique destination IP addresses. Sources: Number of unique originating IPs. :param port_number: a string or integer port number def port(port_number, return_fo...
Information about a particular port at a particular date. If the date is ommited, today's date is used. :param port_number: a string or integer port number :param date: an optional string in 'Y-M-D' format or datetime.date() object def portdate(port_number, date=None, return_format=None): """Informat...
Information about top ports for a particular date with return limit. :param sort_by: one of 'records', 'targets', 'sources' :param limit: number of records to be returned :param date: an optional string in 'Y-M-D' format or datetime.date() object def topports(sort_by='records', limit=10, date=None, return...
Returns port data for a range of dates. In the return data: Records: Total number of records for a given date range. Targets: Number of unique destination IP addresses. Sources: Number of unique originating IPs. :param port_number: a valid port number (required) :param start_date: string or d...
Returns a summary of the information our database holds for a particular ASNUM (similar to /asdetailsascii.html) with return limit. :param limit: number of records to be returned (max 2000) def asnum(number, limit=None, return_format=None): """Returns a summary of the information our database holds for a ...
Returns daily summary totals of targets, attacks and sources. Limit to 30 days at a time. (Query 2002-01-01 to present) In the return data: Sources: Distinct source IP addresses the packets originate from. Targets: Distinct target IP addresses the packets were sent to. Reports: Number of packets r...
Returns daily summary information of submitted 404 Error Page Information. :param date: string or datetime.date() (required) def daily404summary(date, return_format=None): """Returns daily summary information of submitted 404 Error Page Information. :param date: string or datetime.date() (require...
Returns detail information of submitted 404 Error Page Information. :param date: string or datetime.date() (required) :param limit: string or int, limit for number of returned items def daily404detail(date, limit=None, return_format=None): """Returns detail information of submitted 404 Error Page Informat...
List of glossary terms and definitions. :param term: a whole or parital word to "search" in the API def glossary(term=None, return_format=None): """List of glossary terms and definitions. :param term: a whole or parital word to "search" in the API """ uri = 'glossary' if term: uri = '...
API data for `Webhoneypot: Web Server Log Project <https://dshield.org/webhoneypot/>`_. :param date: string or datetime.date() (required) def webhoneypotsummary(date, return_format=None): """API data for `Webhoneypot: Web Server Log Project <https://dshield.org/webhoneypot/>`_. :param date: strin...
API data for `Webhoneypot: Attack By Type <https://isc.sans.edu/webhoneypot/types.html>`_. We currently use a set of regular expressions to determine the type of attack used to attack the honeypot. Output is the top 30 attacks for the last month. :param date: string or datetime.date() (required) def w...
Given a path string, append it to sys.path def _append_path(new_path): # type: (str) -> None """ Given a path string, append it to sys.path """ for path in sys.path: path = os.path.abspath(path) if new_path == path: return sys.path.append(new_path)
Get the caller's file path, by the index of the stack, does not work when the caller is stdin through a CLI python def _caller_path(index): # type: (int) -> str """ Get the caller's file path, by the index of the stack, does not work when the caller is stdin through a CLI python """ module = N...
Get the caller's path to sys.path If the caller is a CLI through stdin, the current working directory is used def get_current_path(index=2): # type: (int) -> str """ Get the caller's path to sys.path If the caller is a CLI through stdin, the current working directory is used """ try: p...
Get the path of the git root directory of the caller's file Raises a RuntimeError if a git repository cannot be found def get_git_root(index=3): # type: (int) -> str """ Get the path of the git root directory of the caller's file Raises a RuntimeError if a git repository cannot be found """ pa...
Get the caller's parent path to sys.path If the caller is a CLI through stdin, the parent of the current working directory is used def get_parent_path(index=2): # type: (int) -> str """ Get the caller's parent path to sys.path If the caller is a CLI through stdin, the parent of the current working...
r""" This function writes the Fortran code needed to calculate the time evolution of the density matrix elements `\rho_{ij}` using the Runge-Kutta method of order 4. INPUT: - ``path`` - A string with the working directory where all files will be stored. It must end with ``/``. - ``name`` - A stri...
This function runs the Runge-Kutta method compiled in path+name... def run_rk4(path,name,E0,laser_frequencies, N_iter,dt,N_states, spectrum_of_laser=None,N_delta=None,frequency_step=None,frequency_end=None, rho0=None,print_steps=False,integrate=False, save_systems=False): """This function runs the Runge-...
Sends email to recipient based on self object parameters. @param fail_silently: When it’s False, msg.send() will raise an smtplib.SMTPException if an error occurs. @param send_to: recipient email @param args: additional args passed to EmailMessage @param kwargs: kwargs passed to EmailMe...
This function does all the operations on eft object, that are necessary to send email. Usually one would use eft object like this: eft = EmailFromTemplate(name='sth/sth.html') eft.get_object() eft.render_message() eft.send_email(['email@example....
Return element.tag with xmlns stripped away. def _tag(element): """Return element.tag with xmlns stripped away.""" tag = element.tag if tag[0] == "{": uri, tag = tag[1:].split("}") return tag
Return xmlns prefix of the given element. def _uriPrefix(element): """Return xmlns prefix of the given element.""" i = element.tag.find('}') if i < 0: return "" return element.tag[:i+1]
Read REQUIRED_ELEMENTS and OPTIONAL_ELEMENTS and returns the rest of the children. Every read child element's text value will be filled into an attribute of the same name, i.e. <description>Test</description> will lead to 'Test' being assigned to self.description. Missing REQUIRED_ELEMENTS result ...
Return (arguments, options, outputs) tuple. Together, the three lists contain all parameters (recursively fetched from all parameter groups), classified into optional parameters, required ones (with an index), and simple output parameters (that would get written to a file using ...
Parse the given value and return result. def parseValue(self, value): """Parse the given value and return result.""" if self.isVector(): return list(map(self._pythonType, value.split(','))) if self.typ == 'boolean': return _parseBool(value) return self._pythonTyp...
Return default extension for this parameter type, checked against supported fileExtensions. If the default extension is not within `fileExtensions`, return the first supported extension. def defaultExtension(self): """Return default extension for this parameter type, checked ag...
Given a string ``X``, returns ``unrank(X[:n]) || X[n:]`` where ``n`` is the the maximum number of bytes that can be unranked w.r.t. the capacity of the input ``dfa`` and ``unrank`` is w.r.t. to the input ``dfa``. def encode(self, X, seed=None): """Given a string ``X``, returns ``unrank(...
Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. def decode(self, covertext): """Given an input string ``unrank(X[:n]) || X[n:]`` returns ``X``. """ if not isinstance(covertext, str): raise InvalidInputException('Input must be of type string.') insufficient ...
r"""Define a nice symbol with matrix indices. >>> name = "rho" >>> from sympy import symbols >>> t, x, y, z = symbols("t, x, y, z", positive=True) >>> variables = [t, x, y, z] >>> open_brace = "" >>> comma = "" >>> close_brace = "" >>> i = 0 >>> j = 1 >>> f = define_symbol(name,...
This function returns a unitary vector describing the polarization of plane waves.: INPUT: - ``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. ...
r"""This function takes vectors from the cartesian basis to the helicity basis. For instance, we can check what are the vectors of the helicity basis. >>> from sympy import pi >>> em=polarization_vector(phi=0, theta= 0, alpha=0, beta=-pi/8,p= 1) >>> em Matrix([ [ sqrt(2)/2], [-sqrt(2)*I/2...
r"""Define the components of the position operators. In general, these are representations of the position operators x, y, z >>> define_r_components(2) [Matrix([ [ 0, x_{12}], [x_{21}, 0]]), Matrix([ [ 0, y_{12}], [y_{21}, 0]]), Matrix([ [ 0, z_{12}], [z_{21},...
r"""Extract an matrix element of a vector operator. >>> r = define_r_components(2) >>> vector_element(r, 1, 0) Matrix([ [x_{21}], [y_{21}], [z_{21}]]) def vector_element(r, i, j): r"""Extract an matrix element of a vector operator. >>> r = define_r_components(2) >>> vector_element...
u"""Define all frequencies omega_level, omega, gamma. >>> from sympy import pprint >>> pprint(define_frequencies(2), use_unicode=True) ⎛ ⎡ 0 ω₁₂⎤ ⎡ 0 γ₁₂⎤⎞ ⎜[ω₁, ω₂], ⎢ ⎥, ⎢ ⎥⎟ ⎝ ⎣ω₂₁ 0 ⎦ ⎣γ₂₁ 0 ⎦⎠ We can make these matrices explicitly antisymmetric. ...
r"""This function returns the transpose of the i-th element of the canonical basis of a Hilbert space of dimension Ne (in the form of a row vector). >>> bra(2,4) Matrix([[0, 1, 0, 0]]) This will return an error if i is not in [1 .. Ne]: >>> bra(5,3) Traceback (most recent call last): ...
r"""This function returns the i-th element of the canonical basis of a Hilbert space of dimension Ne (in the form of a column vector). >>> ket(2,4) Matrix([ [0], [1], [0], [0]]) This will return an error if i is not in [1 .. Ne]: >>> ket(5,3) Traceback (most recent call last):...
This function returns the outer product :math:`|i><j|` where\ :math:`|i>` and :math:`|j>` are elements of the canonical basis of an\ Ne-dimensional Hilbert space (in matrix form). >>> ketbra(2, 3, 3) Matrix([ [0, 0, 0], [0, 0, 1], [0, 0, 0]]) def ketbra(i, j, Ne): """This function returns th...
r"""If A is an outer-product type operator |a><b| return a, b. >>> sig = ket(2, 3)*bra(1, 3) >>> sigma_operator_indices(sig) (1, 0) >>> sigma_operator_indices(sig+sig.adjoint()) (None, None) def sigma_operator_indices(A): r"""If A is an outer-product type operator |a><b| return a, b. >>> ...
r"""This function returns the action of a Lindblad operator A on a density\ matrix rho. This is defined as : .. math:: \mathcal{L}(A, \rho) = A \rho A^\dagger - (A^\dagger A \rho + \rho A^\dagger A)/2. >>> rho=define_density_matrix(3) >>> lindblad_operator( ketbra(1,2,3) ,rho ) Matrix...
u"""Return the Lindblad terms for decays gamma in matrix form. >>> from sympy import pprint >>> aux = define_frequencies(4, explicitly_antisymmetric=True) >>> omega_level, omega, gamma = aux >>> gamma = gamma.subs({gamma[2, 0]:0, gamma[3, 0]:0, gamma[3, 1]:0}) >>> pprint(gamma, use_unicode=True) ...
u"""Define the vectorized density matrix. >>> from sympy import pprint >>> rho = define_density_matrix(3) >>> pprint(define_rho_vector(rho, 3), use_unicode=True) ⎡ ρ₂₂ ⎤ ⎢ ⎥ ⎢ ρ₃₃ ⎥ ⎢ ⎥ ⎢re(ρ₂₁)⎥ ⎢ ⎥ ⎢re(ρ₃₁)⎥ ⎢ ⎥ ⎢re(ρ₃₂)⎥ ⎢ ⎥ ⎢...
u"""Calculate the equations in matrix form. >>> from sympy import symbols, pprint, I >>> rho = define_density_matrix(2, explicitly_hermitian=True, ... normalized=True) >>> Omega = symbols("Omega") >>> delta = symbols("delta", real=True) >>> hbar = symbols("hbar", po...
r"""Obtain a phase transformation to eliminate explicit time dependence. >>> Ne = 2 def phase_transformation(Ne, Nl, r, Lij, omega_laser, phase): r"""Obtain a phase transformation to eliminate explicit time dependence. >>> Ne = 2 """ ph = find_phase_transformation(Ne, Nl, r, Lij) return {ph...
r"""Return symbolic Hamiltonian. >>> from sympy import zeros, pi, pprint, symbols >>> Ne = 3 >>> Nl = 2 >>> Ep, omega_laser = define_laser_variables(Nl) >>> epsilonp = [polarization_vector(0, -pi/2, 0, 0, 1) for l in range(Nl)] >>> detuning_knob = symbols("delta1 delta2", real=True) >>> xi...
r"""Dot product of two 3d vectors. def dot(a, b): r"""Dot product of two 3d vectors.""" if isinstance(a, Mul): a = a.expand() avect = 1 aivect = -1 for ai, fact in enumerate(a.args): if isinstance(fact, Vector3D): avect = fact aivect =...
r"""Cross product of two 3d vectors. def cross(a, b): r"""Cross product of two 3d vectors.""" if isinstance(a, Mul): a = a.expand() avect = 1 aivect = -1 for ai, fact in enumerate(a.args): if isinstance(fact, Vector3D): avect = fact ai...
Saves user's settings @returns True on success @returns False on failure def write_settings(settings): ''' Saves user's settings @returns True on success @returns False on failure ''' if not os.access(DATA_DIR, os.W_OK): return False try: f = open(DATA_DIR + os.sep + SETTING...
Gets main mapping source according to what a data classification is made Gets the hierarchy groups (only for GUI) Gets the hierarchy values def get_hierarchy(settings): ''' Gets main mapping source according to what a data classification is made Gets the hierarchy groups (only for GUI) Gets the...
Determine if field is constant by group in df def is_field_unique_by_group(df, field_col, group_col): ''' Determine if field is constant by group in df ''' def num_unique(x): return len(pd.unique(x)) num_distinct = df.groupby(group_col)[field_col].agg(num_unique) return all(num_distinct == ...
indexes a directory of stan files returns as dictionary containing contents of files def _list_files_in_path(path, pattern="*.stan"): """ indexes a directory of stan files returns as dictionary containing contents of files """ results = [] for dirname, subdirs, files in os.walk(path): ...
This generates a random valid perovskite structure in ASE format. Useful for testing. Binary and organic perovskites are not considered. def generate_random_perovskite(lat=None): ''' This generates a random valid perovskite structure in ASE format. Useful for testing. Binary and organic perovsk...
Check a value is a positive integer. Returns the value if so, raises ValueError otherwise. def check_positive_integer(name, value): """Check a value is a positive integer. Returns the value if so, raises ValueError otherwise. """ try: value = int(value) is_positive = (value > 0) ...
Check a value is a valid colour input. Returns a parsed `RGBColor` instance if so, raises ValueError otherwise. def check_color_input(value): """Check a value is a valid colour input. Returns a parsed `RGBColor` instance if so, raises ValueError otherwise. """ value = value.lower() #...
Extract octahedra as lists of sequence numbers of corner atoms def get_octahedra(self, atoms, periodicity=3): ''' Extract octahedra as lists of sequence numbers of corner atoms ''' octahedra = [] for n, i in enumerate(atoms): found = [] if i.symbol in Per...
Extract the main tilting plane basing on Z coordinate def get_tiltplane(self, sequence): ''' 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): ...