INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Add ``pyny.Spaces`` to the current space. In other words, it merges multiple ``pyny.Spaces`` in this instance. :param places: ``pyny.Spaces`` to add. :type places: list of pyny.Spaces :param ret: If True, returns the whole updated Space. :type ret: bool :retur...
def add_spaces(self, spaces, ret=False): """ Add ``pyny.Spaces`` to the current space. In other words, it merges multiple ``pyny.Spaces`` in this instance. :param places: ``pyny.Spaces`` to add. :type places: list of pyny.Spaces :param ret: If True, returns the...
:returns: opposite vertices of the bounding prism for this object. :rtype: ndarray([min], [max])
def get_domain(self): """ :returns: opposite vertices of the bounding prism for this object. :rtype: ndarray([min], [max]) """ points = np.vstack([place.get_domain() for place in self]) return np.array([points.min(axis=0), points.max(axis=0)])
Collects the required information to generate a data estructure that can be used to recreate exactly the same geometry object via *\*\*kwargs*. :returns: Object's sufficient info to initialize it. :rtype: dict .. seealso:: * :...
def get_seed(self): """ Collects the required information to generate a data estructure that can be used to recreate exactly the same geometry object via *\*\*kwargs*. :returns: Object's sufficient info to initialize it. :rtype: dict .....
Returns a one dimension array with the Place where the points belong. :returns: The ``pyny.Place`` where the points belong. :rtype: list of int
def get_sets_index(self): """ Returns a one dimension array with the Place where the points belong. :returns: The ``pyny.Place`` where the points belong. :rtype: list of int """ index = [] for i, place in enumerate(self): in...
Collects all the points coordinates from this ``pyny.Space`` instance. In order to keep the reference, it returns an index with the following key: * The first column is the Place. * The second column is the body (-1: points, 0: surface, ...
def get_map(self): """ Collects all the points coordinates from this ``pyny.Space`` instance. In order to keep the reference, it returns an index with the following key: * The first column is the Place. * The second column is the...
Returns a seed from an altered map. The map needs to have the structure of this ``pyny.Space``, that is, the same as ``self.get_map()``. :param map_: the points, and the same order, that appear at ``pyny.Space.get_map()``. :type map_: ndarray (shape=(N, 3)) ...
def map2seed(self, map_): """ Returns a seed from an altered map. The map needs to have the structure of this ``pyny.Space``, that is, the same as ``self.get_map()``. :param map_: the points, and the same order, that appear at ``pyny.Space.get_map()`...
Collects all the polygons, holes and points in the Space packaged in a list. The returned geometries are not in *pyny3d* form, instead the will be represented as *ndarrays*. :returns: The polygons, the holes and the points. :rtype: list
def explode(self): """ Collects all the polygons, holes and points in the Space packaged in a list. The returned geometries are not in *pyny3d* form, instead the will be represented as *ndarrays*. :returns: The polygons, the holes and the points. :rtype: ...
Much faster version of ``pyny.Space.explode()`` method for previously locked ``pyny.Space``. :param map_: the points, and the same order, that appear at ``pyny.Space.get_map()``. There is no need for the index if locked. :type map_: ndarray (shape=(N, 3)...
def explode_map(self, map_): """ Much faster version of ``pyny.Space.explode()`` method for previously locked ``pyny.Space``. :param map_: the points, and the same order, that appear at ``pyny.Space.get_map()``. There is no need for the index if ...
Launch ``pyny.Place.get_height(points)`` recursively for all the ``pyny.Place``. The points outside the object will have a NaN value in the z column. These point will not be stored but it will be returned. :param points: list of coordinates of the point...
def get_height(self, points, edge=True, attach=False, extra_height=0): """ Launch ``pyny.Place.get_height(points)`` recursively for all the ``pyny.Place``. The points outside the object will have a NaN value in the z column. These point will not be stored but it w...
Launch `pyny.Place.mesh(points)` recursively for all the ``pyny.Place`` individually. :param mesh_size: distance between points. :type mesh_size: float :param extra_height: Adds an extra height (z value) to the resulting points. :type extra_height: fl...
def mesh(self, mesh_size=1, extra_height=0.1, edge=True, attach=True): """ Launch `pyny.Place.mesh(points)` recursively for all the ``pyny.Place`` individually. :param mesh_size: distance between points. :type mesh_size: float :param extra_height: Adds an...
Translate the whole Space in x, y and z coordinates. :param d_xyz: displacement in x, y(, and z). :type d_xyz: tuple (len=2 or 3) :param inplace: If True, the moved ``pyny.Space`` is copied and added to the current ``pyny.Space``. If False, it returns the...
def move(self, d_xyz, inplace=False): """ Translate the whole Space in x, y and z coordinates. :param d_xyz: displacement in x, y(, and z). :type d_xyz: tuple (len=2 or 3) :param inplace: If True, the moved ``pyny.Space`` is copied and added to the cu...
Returns a new Space which is the same but rotated about a given axis. If the axis given is ``None``, the rotation will be computed about the Space's centroid. :param angle: Rotation angle (in radians) :type angle: float :param direction: Axis di...
def rotate(self, angle, direction='z', axis=None): """ Returns a new Space which is the same but rotated about a given axis. If the axis given is ``None``, the rotation will be computed about the Space's centroid. :param angle: Rotation angle (i...
Copy the ``pyny.Space`` along a 3D matrix given by the three tuples x, y, z: :param x: Number of copies and distance between them in this direction. :type x: tuple (len=2) :param inplace: If True, the moved ``pyny.Space`` is copied and added to th...
def matrix(self, x=(0, 0), y=(0, 0) , z=(0, 0), inplace=True): """ Copy the ``pyny.Space`` along a 3D matrix given by the three tuples x, y, z: :param x: Number of copies and distance between them in this direction. :type x: tuple (len=2) :par...
Generates a symmetry of the Space respect global axes. :param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'... :type axes: str :param inplace: If True, the new ``pyny.Space`` is copied and added to the current ``pyny.Space``. If False, it returns the new ``pyny.S...
def mirror(self, axes='x', inplace=False): """ Generates a symmetry of the Space respect global axes. :param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'... :type axes: str :param inplace: If True, the new ``pyny.Space`` is copied and added to the current ``...
Computes a change of the reference system for the whole ``pyny.Space`` to align the `y` axis with a given direction. Returns its elements (polygons, holes, points) extracted in a list. In its conception, this method was created as a tool for the shadows computat...
def photo(self, azimuth_zenit, plot=False): """ Computes a change of the reference system for the whole ``pyny.Space`` to align the `y` axis with a given direction. Returns its elements (polygons, holes, points) extracted in a list. In its conception, th...
Improved plot that allows to visualize the Places in the Space selectively. It also allows to plot polygons and holes in different colors and to change the size and the color of the set of points. The points can be plotted accordingly to a ndarray colormap. ...
def iplot(self, places=-1, c_poly='default', c_holes='default', c_sop='r', s_sop=25, extra_height=0, ret=False, ax=None): """ Improved plot that allows to visualize the Places in the Space selectively. It also allows to plot polygons and holes in different colors and ...
Initializes a ShadowManager object for this ``pyny.Space`` instance. The 'empty' initialization accepts ``data`` and ``t`` and ``dt`` but the ShadowsManager will not start the calculations. It will wait the user to manually insert the rest of the parameters. Call ...
def shadows(self, data=None, t=None, dt=None, latitude=None, init='empty', resolution='mid'): ''' Initializes a ShadowManager object for this ``pyny.Space`` instance. The 'empty' initialization accepts ``data`` and ``t`` and ``dt`` but the Shadows...
Series from iterable of member iterables.
def frommembers(cls, members): """Series from iterable of member iterables.""" return cls.frombitsets(map(cls.BitSet.frommembers, members))
Series from iterable of boolean evaluable iterables.
def frombools(cls, bools): """Series from iterable of boolean evaluable iterables.""" return cls.frombitsets(map(cls.BitSet.frombools, bools))
Series from binary string arguments.
def frombits(cls, bits): """Series from binary string arguments.""" return cls.frombitsets(map(cls.BitSet.frombits, bits))
Series from integer rank arguments.
def fromints(cls, ints): """Series from integer rank arguments.""" return cls.frombitsets(map(cls.BitSet.fromint, ints))
Return the series as list of index set tuples.
def index_sets(self, as_set=False): """Return the series as list of index set tuples.""" indexes = frozenset if as_set else tuple return [indexes(b.iter_set()) for b in self]
Append an array to another padding with NaNs for constant length. Parameters ---------- many : array_like of rank (j, k) values appended to a copy of this array. This may be a 1-D or 2-D array. single : array_like of rank l values to append. This should be a 1-D array. Retu...
def append_arrays(many, single): """Append an array to another padding with NaNs for constant length. Parameters ---------- many : array_like of rank (j, k) values appended to a copy of this array. This may be a 1-D or 2-D array. single : array_like of rank l values to appen...
Locate locations within the profile.
def _get_locations(self, calc): """Locate locations within the profile.""" return (self._location_in(calc.profile), self._location_out(calc.profile))
Find useful region of a given spectrum Detemine the useful region of a given spectrum by skipping the initial (final) pixels with values equal to 'sought_value'. Parameters ---------- sp : 1D numpy array Input spectrum. sought_value : int, float, bool Pixel value that indicate ...
def find_pix_borders(sp, sought_value): """Find useful region of a given spectrum Detemine the useful region of a given spectrum by skipping the initial (final) pixels with values equal to 'sought_value'. Parameters ---------- sp : 1D numpy array Input spectrum. sought_value : int,...
Replace a few pixels at the borders of each spectrum. Set to 'replacement_value' 'nreplace' pixels at the beginning (at the end) of each spectrum just after (before) the spectrum value changes from (to) 'sought_value', as seen from the image borders. Parameters ---------- image2d : numpy array...
def fix_pix_borders(image2d, nreplace, sought_value, replacement_value): """Replace a few pixels at the borders of each spectrum. Set to 'replacement_value' 'nreplace' pixels at the beginning (at the end) of each spectrum just after (before) the spectrum value changes from (to) 'sought_value', as seen ...
Generate mask avoiding undesired values at the borders. Set to True image borders with values equal to 'sought_value' Parameters ---------- image2d : numpy array Initial 2D image. sought_value : int, float, bool Pixel value that indicates missing data in the spectrum. naddition...
def define_mask_borders(image2d, sought_value, nadditional=0): """Generate mask avoiding undesired values at the borders. Set to True image borders with values equal to 'sought_value' Parameters ---------- image2d : numpy array Initial 2D image. sought_value : int, float, bool ...
Evaluate wavelength at xpos using the provided polynomial.
def update_features(self, poly): """Evaluate wavelength at xpos using the provided polynomial.""" for feature in self.features: feature.wavelength = poly(feature.xpos)
Build a DataFrame object from a list.
def dataframe_from_list(values): """Build a DataFrame object from a list.""" if(isinstance(values, six.string_types)): return DataFrame(filename=values) elif(isinstance(values, fits.HDUList)): return DataFrame(frame=values) else: return None
Build a ObservationResult object from a dictionary.
def obsres_from_dict(values): """Build a ObservationResult object from a dictionary.""" obsres = ObservationResult() ikey = 'frames' # Workaround if 'images' in values: ikey = 'images' obsres.id = values.get('id', 1) obsres.mode = values['mode'] obsres.instrument = values['ins...
Return first available image in observation result
def get_sample_frame(self): """Return first available image in observation result""" for frame in self.frames: return frame.open() for res in self.results.values(): return res.open() return None
Loop over the first axis applying Fowler processing. *fowlerdata* is assumed to be a 3D numpy.ndarray containing the result of a nIR observation in Fowler mode (Fowler and Gatley 1991). The shape of the array must be of the form 2N_p x M x N, with N_p being the number of pairs in Fowler mode. The ...
def fowler_array(fowlerdata, ti=0.0, ts=0.0, gain=1.0, ron=1.0, badpixels=None, dtype='float64', saturation=65631, blank=0, normalize=False): """Loop over the first axis applying Fowler processing. *fowlerdata* is assumed to be a 3D numpy.ndarray containing the result of a...
different Eagle versions need differnt TAB count. 6.5 -> 2 6.6 -> 3 7.4 -> 2
def accept_freeware_license(): '''different Eagle versions need differnt TAB count. 6.5 -> 2 6.6 -> 3 7.4 -> 2 ''' ntab = 3 if version().startswith('6.6.') else 2 for _ in range(ntab): EasyProcess('xdotool key KP_Tab').call() time.sleep(0.5) EasyProcess('xdotool key KP...
Return fully qualified name from object
def fully_qualified_name(obj, sep='.'): """Return fully qualified name from object""" if inspect.isclass(obj): return obj.__module__ + sep + obj.__name__ else: return obj.__module__ + sep + obj.__class__.__name__
Compute fit residuals
def fun_residuals(params, xnor, ynor, w, bbox, k, ext): """Compute fit residuals""" spl = LSQUnivariateSpline( x=xnor, y=ynor, t=[item.value for item in params.values()], w=w, bbox=bbox, k=k, ext=ext, check_finite=False ) return spl.get_re...
Observing mode processing mode of numina.
def mode_run_common_obs(args, extra_args): """Observing mode processing mode of numina.""" # Loading observation result if exists loaded_obs = [] sessions = [] if args.session: for obfile in args.obsresult: _logger.info("session file from %r", obfile) with open(obfi...
Parse a dictionary of strings as if yaml reads it
def parse_as_yaml(strdict): """Parse a dictionary of strings as if yaml reads it""" interm = "" for key, val in strdict.items(): interm = "%s: %s, %s" % (key, val, interm) fin = '{%s}' % interm return yaml.load(fin)
Connection to atomic structures on the Catalysis-Hub server with ase db cli. Arguments to the the ase db cli client must be enclosed in one string. For example: <cathub ase 'formula=Ag6In6H -s energy -L 200'>. To see possible ase db arguments run <ase db --help>
def ase(dbuser, dbpassword, args, gui): """Connection to atomic structures on the Catalysis-Hub server with ase db cli. Arguments to the the ase db cli client must be enclosed in one string. For example: <cathub ase 'formula=Ag6In6H -s energy -L 200'>. To see possible ase db arguments ru...
Read folder and collect data in local sqlite3 database
def folder2db(folder_name, debug, energy_limit, skip_folders, goto_reaction): """Read folder and collect data in local sqlite3 database""" folder_name = folder_name.rstrip('/') skip = [] for s in skip_folders.split(', '): for sk in s.split(','): skip.append(sk) pub...
Transfer data from local database to Catalysis Hub server
def db2server(dbfile, block_size, dbuser, dbpassword): """Transfer data from local database to Catalysis Hub server""" _db2server.main(dbfile, write_reaction=True, write_ase=True, write_publication=True, write_reaction_system=True,...
Search for reactions
def reactions(columns, n_results, write_db, queries): """Search for reactions""" if not isinstance(queries, dict): query_dict = {} for q in queries: key, value = q.split('=') if key == 'distinct': if value in ['True', 'true']: query_dic...
Search for publications
def publications(columns, n_results, queries): """Search for publications""" if not isinstance(queries, dict): query_dict = {} for q in queries: key, value = q.split('=') if key == 'distinct': if value in ['True', 'true']: query_dict.up...
Create a basic folder tree for dumping DFT calculcations for reaction energies. Dear all Use this command make the right structure for your folders for submitting data for Catalysis Hub's Surface Reactions. Start by creating a template file by calling: $ cathub make_folders <template_name> ...
def make_folders(template, custom_base): """Create a basic folder tree for dumping DFT calculcations for reaction energies. Dear all Use this command make the right structure for your folders for submitting data for Catalysis Hub's Surface Reactions. Start by creating a template file by calling: ...
Read reactions from non-organized folder
def organize(**kwargs): """Read reactions from non-organized folder""" # do argument wrangling before turning it into an obect # since namedtuples are immutable if len(kwargs['adsorbates']) == 0: print("""Warning: no adsorbates specified, can't pick up reaction reaction energies.""") ...
Set up screen properties
def initCurses(self): """ Set up screen properties """ curses.noecho() curses.cbreak() curses.curs_set(0) curses.start_color() curses.use_default_colors() curses.init_pair(1, curses.COLOR_WHITE, -1) curses.init_pair(2, curses.COLOR_YELLOW, ...
Fix curses addch function for python 3.4.0
def patchCurses(self): """ Fix curses addch function for python 3.4.0 """ if (sys.version_info)[:3] == (3, 4, 0): self.addchar = lambda y, x, *args: self.win.addch(x, y, *args) else: self.addchar = self.win.addch
Draw splash screen
def splash(self): """ Draw splash screen """ dirname = os.path.split(os.path.abspath(__file__))[0] try: splash = open(os.path.join(dirname, "splash"), "r").readlines() except IOError: return width = len(max(splash, key=len)) y = in...
Draw information on population size and current generation
def drawHUD(self): """ Draw information on population size and current generation """ self.win.move(self.height - 2, self.x_pad) self.win.clrtoeol() self.win.box() self.addstr(2, self.x_pad + 1, "Population: %i" % len(self.grid)) self.addstr(3, self.x_pad ...
Redraw the grid with the new generation
def drawGrid(self): """ Redraw the grid with the new generation """ for cell in self.grid: y, x = cell y += self.y_pad x += self.x_pad if self.traditional: sprite = '.' color = curses.color_pair(4) ...
Decide the fate of the cells
def nextGen(self): """ Decide the fate of the cells """ self.current_gen += 1 self.change_gen[self.current_gen % 3] = copy.copy(self.grid) grid_cp = copy.copy(self.grid) for cell in self.grid: y, x = cell y1 = (y - 1) % self.y_grid ...
Return the number active neighbours within one positions away from cell
def countNeighbours(self, cell): """ Return the number active neighbours within one positions away from cell """ count = 0 y, x = cell y = y % self.y_grid x = x % self.x_grid y1 = (y - 1) % self.y_grid y2 = (y + 1) % self.y_grid x1 = (x - 1...
Initialise the game grid
def initGrid(self): """ Initialise the game grid """ blinker = [(4, 4), (4, 5), (4, 6)] toad = [(9, 5), (9, 6), (9, 7), (10, 4), (10, 5), (10, 6)] glider = [(4, 11), (5, 12), (6, 10), (6, 11), (6, 12)] r_pentomino = [(10, 60), (9, 61), (10, 61), (11, 61), (9, 62)]...
Restart the game from a new generation 0
def restart(self): """ Restart the game from a new generation 0 """ self.initGrid() self.win.clear() self.current_gen = 1 self.start
Game logic
def start(self): """ Game logic """ self.initGrid() self.win.clear() self.state = 'running' while self.state == 'running': if self.hud: self.drawHUD() self.drawGrid() self.nextGen() sleep(self.rate) ...
Game Finished - Restart or Quit
def end(self): """ Game Finished - Restart or Quit """ if self.loop: self.restart return self.addstr(2, self.x_grid / 2 - 4, "GAMEOVER", 7) if self.hud: self.addstr(2, self.x_pad + 13, len(self.grid), 5) self.addstr(3, sel...
Combine arrays using the mean, with masks and offsets. Arrays and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. The function returns an array with one more dimension than the inputs and with size (3, shape). out[0] contains...
def mean(arrays, masks=None, dtype=None, out=None, zeros=None, scales=None, weights=None): """Combine arrays using the mean, with masks and offsets. Arrays and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. ...
Combine arrays using the median, with masks. Arrays and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. The function returns an array with one more dimension than the inputs and with size (3, shape). out[0] contains the mean,...
def median(arrays, masks=None, dtype=None, out=None, zeros=None, scales=None, weights=None): """Combine arrays using the median, with masks. Arrays and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. The...
Combine arrays using the sigma-clipping, with masks. Inputs and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. The function returns an array with one more dimension than the inputs and with size (3, shape). out[0] contains t...
def sigmaclip(arrays, masks=None, dtype=None, out=None, zeros=None, scales=None, weights=None, low=3., high=3.): """Combine arrays using the sigma-clipping, with masks. Inputs and masks are a list of array objects. All input arrays have the same shape. If present, the masks have...
Combine arrays using mix max rejection, with masks. Inputs and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. The function returns an array with one more dimension than the inputs and with size (3, shape). out[0] contains th...
def minmax(arrays, masks=None, dtype=None, out=None, zeros=None, scales=None, weights=None, nmin=1, nmax=1): """Combine arrays using mix max rejection, with masks. Inputs and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape al...
Combine arrays using the sigma-clipping, with masks. Inputs and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. The function returns an array with one more dimension than the inputs and with size (3, shape). out[0] contains t...
def quantileclip(arrays, masks=None, dtype=None, out=None, zeros=None, scales=None, weights=None, fclip=0.10): """Combine arrays using the sigma-clipping, with masks. Inputs and masks are a list of array objects. All input arrays have the same shape. If present, the masks ...
Combine flat arrays. :param arrays: a list of arrays :param masks: a list of mask arrays, True values are masked :param dtype: data type of the output :param out: optional output, with one more axis than the input arrays :param blank: non-positive values are substituted by this on output :retur...
def flatcombine(arrays, masks=None, dtype=None, scales=None, low=3.0, high=3.0, blank=1.0): """Combine flat arrays. :param arrays: a list of arrays :param masks: a list of mask arrays, True values are masked :param dtype: data type of the output :param out: optional output, with one...
Combine zero arrays. :param arrays: a list of arrays :param masks: a list of mask arrays, True values are masked :param dtype: data type of the output :param scales: :return: median, variance of the median and number of points stored
def zerocombine(arrays, masks, dtype=None, scales=None): """Combine zero arrays. :param arrays: a list of arrays :param masks: a list of mask arrays, True values are masked :param dtype: data type of the output :param scales: :return: median, variance of the median and number of points stored ...
Combine arrays by addition, with masks and offsets. Arrays and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. The function returns an array with one more dimension than the inputs and with size (3, shape). out[0] contains th...
def sum(arrays, masks=None, dtype=None, out=None, zeros=None, scales=None): """Combine arrays by addition, with masks and offsets. Arrays and masks are a list of array objects. All input arrays have the same shape. If present, the masks have the same shape also. The function returns an ar...
Stack arrays using different methods. :param method: the combination method :type method: PyCObject :param arrays: a list of arrays :param masks: a list of mask arrays, True values are masked :param dtype: data type of the output :param zeros: :param scales: :param weights: :return:...
def generic_combine(method, arrays, masks=None, dtype=None, out=None, zeros=None, scales=None, weights=None): """Stack arrays using different methods. :param method: the combination method :type method: PyCObject :param arrays: a list of arrays :param masks: a list of mask array...
Compute the FWHM.
def compute_fwhm_1d_simple(Y, xc, X=None): """Compute the FWHM.""" return compute_fw_at_frac_max_1d_simple(Y, xc, X=X, f=0.5)
Compute the full width at fraction f of the maximum
def compute_fw_at_frac_max_1d_simple(Y, xc, X=None, f=0.5): """Compute the full width at fraction f of the maximum""" yy = np.asarray(Y) if yy.ndim != 1: raise ValueError('array must be 1-d') if yy.size == 0: raise ValueError('array is empty') if X is None: xx = np.arange...
Compute r12 using linear interpolation.
def _fwhm_side_lineal(uu, vv): '''Compute r12 using linear interpolation.''' res1, = np.nonzero(vv < 0) if len(res1) == 0: return 0, 1 # error, no negative value else: # first value i2 = res1[0] i1 = i2 - 1 dx = uu[i2] - uu[i1] dy = vv[i2] - vv[i1] ...
Returns the zero point energy from a list of frequencies. Parameters ---------- viblist : List of numbers or string of list of numbers. Returns ------- ZPE : Zero point energy in eV.
def get_ZPE(viblist): """Returns the zero point energy from a list of frequencies. Parameters ---------- viblist : List of numbers or string of list of numbers. Returns ------- ZPE : Zero point energy in eV. """ if type(viblist) is str: l = ast.literal_eval(viblist) els...
Transforms atomic system information into well-formatted labels. Parameters ---------- df : Pandas DataFrame. Returns ------- labels : list of system labels.
def auto_labels(df): """Transforms atomic system information into well-formatted labels. Parameters ---------- df : Pandas DataFrame. Returns ------- labels : list of system labels. """ systems = list(df.system) facets = list(df.facet) systems_labels = [w.replace('_', '\ ')...
Returns the Gibbs free energy of proton in bulk solution. Parameters ---------- pH : pH of bulk solution temperature : numeric temperature in K pressure : numeric pressure in mbar Returns ------- G_H, G_OH : Gibbs free energy of proton and hydroxide.
def proton_hydroxide_free_energy(temperature, pressure, pH): """Returns the Gibbs free energy of proton in bulk solution. Parameters ---------- pH : pH of bulk solution temperature : numeric temperature in K pressure : numeric pressure in mbar Returns ------- G_H, G_...
Returns the Gibbs free energy corrections to be added to raw reaction energies. Parameters ---------- molecule_list : list of strings temperature : numeric temperature in K pressure : numeric pressure in mbar Returns ------- G_H, G_OH : Gibbs free energy of proton and hy...
def get_FEC(molecule_list, temperature, pressure, electronic_energy='Default'): """Returns the Gibbs free energy corrections to be added to raw reaction energies. Parameters ---------- molecule_list : list of strings temperature : numeric temperature in K pressure : numeric press...
Returns a matplotlib object with the plotted reaction path. Parameters ---------- df : Pandas DataFrame generated by reaction_network temperature : numeric temperature in K pressure : numeric pressure in mbar pH : PH in bulk solution potential : Electric potential vs. SHE in ...
def plot_reaction_scheme(df, temperature, pressure, potential, pH, e_lim=None): """Returns a matplotlib object with the plotted reaction path. Parameters ---------- df : Pandas DataFrame generated by reaction_network temperature : numeric temperature in K pressure : numeric press...
Gathers relevant data from SQL database generated by CATHUB. Parameters ---------- db_file : Path to database slab : Which metal (slab) to select. facet : Which facets to select. Returns ------- data : SQL cursor output.
def select_data(db_file, slab=None, facet=None): """Gathers relevant data from SQL database generated by CATHUB. Parameters ---------- db_file : Path to database slab : Which metal (slab) to select. facet : Which facets to select. Returns ------- data : SQL cursor output. """ ...
Read in file and return pandas data_frame. Parameters ---------- filename : Filename including path. Returns ------- df : pandas data frame
def file_to_df(file_name): """Read in file and return pandas data_frame. Parameters ---------- filename : Filename including path. Returns ------- df : pandas data frame """ filename, file_extension = os.path.splitext(file_name) if file_extension=='.csv': df = pd.read_c...
Transforms database to data frame. Parameters ---------- db_file : Path to database slabs : Which metals (slabs) to select. facet : Which facets to select. Returns ------- df : Data frame.
def db_to_df(db_file, slabs=None, facet=None): """Transforms database to data frame. Parameters ---------- db_file : Path to database slabs : Which metals (slabs) to select. facet : Which facets to select. Returns ------- df : Data frame. """ systems = [] data = [] ...
Identifies unique elementary reactions in data frame. Parameters ---------- df : Data frame. Returns ------- reaction_list : List of unique elementary reactions.
def unique_reactions(df): """Identifies unique elementary reactions in data frame. Parameters ---------- df : Data frame. Returns ------- reaction_list : List of unique elementary reactions. """ reaction_list =[] for idx, entry in enumerate(df['reactants']): reaction = ...
Returns the Helmholtz energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric energy in eV verbose : boolean whether to print ASE thermochemistry output Returns ...
def get_helmholtz_energy(self, temperature, electronic_energy=0, verbose=False): """Returns the Helmholtz energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric energy in eV verbose...
Returns the internal energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric energy in eV verbose : boolean whether to print ASE thermochemistry output Returns -...
def get_internal_energy(self, temperature, electronic_energy=0, verbose=False): """Returns the internal energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric energy in eV verbose :...
Returns the internal energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric energy in eV pressure : numeric pressure in mbar Returns ------- internal_energ...
def get_free_energy(self, temperature, pressure = 'Default', electronic_energy = 'Default', overbinding = True): """Returns the internal energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric ...
Returns the internal energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric energy in eV Returns ------- internal_energy : numeric Internal energy in eV
def get_enthalpy(self, temperature, electronic_energy = 'Default'): """Returns the internal energy of an adsorbed molecule. Parameters ---------- temperature : numeric temperature in K electronic_energy : numeric energy in eV Returns ------- ...
Returns a list of vibration in energy units eV. Returns ------- vibs : list of vibrations in eV
def get_vib_energies(self): """Returns a list of vibration in energy units eV. Returns ------- vibs : list of vibrations in eV """ vibs = self.molecule_dict[self.name]['vibrations'] vibs = np.array(vibs) * cm2ev return (vibs)
Sets up intermediates and specifies whether it's an electrochemical step. Either provide individual contributions or net contributions. If both are given, only the net contributions are used. intermediate_list: list of basestrings transition_states: list of True and False electr...
def set_intermediates(self, intermediates, betas=None, transition_states=None): """Sets up intermediates and specifies whether it's an electrochemical step. Either provide individual contributions or net contributions. If both are given, only the net contributions are used. intermediate...
Returns a dataframe with Gibbs free reaction energies. Parameters ---------- df : Pandas DataFrame generated by db_to_df temperature : numeric temperature in K pressure : numeric pressure in mbar pH : PH in bulk solution potential : Electri...
def reaction_scheme(self, df, temperature, pressure, pH, potential): """Returns a dataframe with Gibbs free reaction energies. Parameters ---------- df : Pandas DataFrame generated by db_to_df temperature : numeric temperature in K pressure : numeric ...
Return the current debugger instance, or create if none.
def debugger(): """Return the current debugger instance, or create if none.""" sdb = _current[0] if sdb is None or not sdb.active: sdb = _current[0] = Sdb() return sdb
Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match.
def global_matches(self, text): """Compute matches when text is a simple name. Return a list of all keywords, built-in functions and names currently defined in self.namespace that match. """ matches = [] n = len(text) for word in self.namespace: if wor...
对字典中为None的值,重新设置默认值 :param dict_item: :param default_value: :return:
def set_dict_none_default(dict_item, default_value): """ 对字典中为None的值,重新设置默认值 :param dict_item: :param default_value: :return: """ for (k, v) in iteritems(dict_item): if v is None: dict_item[k] = default_value
自动将 site-user 识别成 SiteUser :param model_name: :return:
def auto_model_name_recognize(model_name): """ 自动将 site-user 识别成 SiteUser :param model_name: :return: """ name_list = model_name.split('-') return ''.join(['%s%s' % (name[0].upper(), name[1:]) for name in name_list])
只选择 id 和 name,用来做列表选择 :param model_class: :param filter_dict: :param q_filter: :return:
def model_to_select_list(model_class, filter_dict=None, q_filter=None): """ 只选择 id 和 name,用来做列表选择 :param model_class: :param filter_dict: :param q_filter: :return: """ if filter_dict is None: filter_dict = {} if q_filter is not None: filter_list = [q_filter] else...
不分页 :param values: :param to_json_method: :param model_class: :param filter_dict: :param order_by_list: :param select_related_fields: :param q_filter: :return:
def model_to_list(model_class, filter_dict=None, order_by_list=None, select_related_fields=None, q_filter=None, values=None, to_json_method='to_json'): """ 不分页 :param values: :param to_json_method: :param model_class: :param filter_dict: ...
:param max_page_size: :param model_class: :param page_num: :param page_size: :param filter_dict: :param order_by_list: :param select_related_fields: :param q_filter: Q(uuid__contains=keyword) | Q(memo__contains=keyword) :param values: :param to_json_method: :return:
def model_to_page_list(model_class, page_num, page_size=DEFAULT_PAGE_SIZE, filter_dict=None, order_by_list=None, select_related_fields=None, q_filter=None, values=None, to_json_method='to_json', max_page_s...
:type session requests.session :param method: :param url: :param headers: :param data: :param session: :return:
def request(method, url, headers=None, data=None, session=None): """ :type session requests.session :param method: :param url: :param headers: :param data: :param session: :return: """ base_headers = { 'User-Agent': random_agent() } if headers is None: hea...
从文件中读取请求头,并根据格式化字符串模板,进行字符串格式化 :param file_name: :param params: :return:
def read_request(file_name, **params): """ 从文件中读取请求头,并根据格式化字符串模板,进行字符串格式化 :param file_name: :param params: :return: """ with open(file_name, 'r') as f: data = f.read() return read_request_from_str(data, **params)
从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化 :param data: :param params: :return:
def read_request_from_str(data, **params): """ 从字符串中读取请求头,并根据格式化字符串模板,进行字符串格式化 :param data: :param params: :return: """ method, uri = None, None headers = {} host = '' try: split_list = data.split('\n\n') headers_text = split_list[0] body = '\n\n'.join(sp...
将查询字符串,转换成字典 a=123&b=456 {'a': '123', 'b': '456'} :param query_str: :return:
def query_str_2_dict(query_str): """ 将查询字符串,转换成字典 a=123&b=456 {'a': '123', 'b': '456'} :param query_str: :return: """ if query_str: query_list = query_str.split('&') query_dict = {} for t in query_list: x = t.split('=') query_dict[x[0]] = x...
发送邮件 :param is_ssl: 使用SSL的方式发生 :param mail_to_list: 收件人列表 :param subject: 邮件主题 :param content: 邮件正文 :param file_name_list: 附近的文件路径列表 :return:
def do_send_mail(self, is_ssl, mail_to_list, subject, content, file_name_list): """ 发送邮件 :param is_ssl: 使用SSL的方式发生 :param mail_to_list: 收件人列表 :param subject: 邮件主题 :param content: 邮件正文 :param file_name_list: 附近的文件路径列表 :return: """ if is_ssl:...
:param content_type: 如果 text 是html,则需要设置 _subtype='html' :param mail_to: :param subject: :param content: :param files: (f_name, f_data) :return:
def send_email(self, mail_to, subject, content, content_type='plain', files=None): """ :param content_type: 如果 text 是html,则需要设置 _subtype='html' :param mail_to: :param subject: :param content: :param files: (f_name, f_data) :return: """ assert type(...
:param handlers: :return:
def init_log(*handlers, **kwargs): """ :param handlers: :return: """ disable_existing_loggers = kwargs.get('disable_existing_loggers', False) handlers_config = [t.get_handler() for t in handlers] new_handlers_config = {} for t in handlers_config: new_handlers_config.update(t) ...
获取客户端的IP :param request: :return:
def get_client_ip(request): """ 获取客户端的IP :param request: :return: """ x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') x_real_ip = request.META.get('HTTP_X_REAL_IP') if x_real_ip: ip = x_real_ip elif x_forwarded_for: ip = x_forwarded_for.split(',')[0] el...
对一些数据类型的 json 序列化, 默认情况下 json 没有对 datetime 和 Decimal 进行序列化 如果不指定的话,会抛异常 :param obj: :return:
def json_default(obj): """ 对一些数据类型的 json 序列化, 默认情况下 json 没有对 datetime 和 Decimal 进行序列化 如果不指定的话,会抛异常 :param obj: :return: """ if isinstance(obj, datetime): return obj.strftime("%Y-%m-%d %H:%M:%S") elif isinstance(obj, Decimal): return float(obj) elif isinstance(obj,...
返回json数据 :param encoding: :param ensure_ascii: :param sort_keys: :param indent: :param dict_data: :return:
def dumps(dict_data, ensure_ascii=True, indent=None, sort_keys=False, encoding='utf-8', **kwargs): """ 返回json数据 :param encoding: :param ensure_ascii: :param sort_keys: :param indent: :param dict_data: :return: """ return json.dumps(dict_data, default=json_default, ...