INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Yield all unions of start with other in shortlex order. >>> ['{:03b}'.format(s) for s in shortlex(0, [0b100, 0b010, 0b001])] ['000', '100', '010', '001', '110', '101', '011', '111'] >>> ', '.join(''.join(sorted(s)) ... for s in shortlex(set(), [{'a'}, {'b'}, {'c'}, {'d'}])) ', a, b, c, d, ab, ac, ...
def shortlex(start, other, excludestart=False): """Yield all unions of start with other in shortlex order. >>> ['{:03b}'.format(s) for s in shortlex(0, [0b100, 0b010, 0b001])] ['000', '100', '010', '001', '110', '101', '011', '111'] >>> ', '.join(''.join(sorted(s)) ... for s in shortlex(set(), [{'...
Yield all intersections of end with other in reverse shortlex order. >>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])] ['111', '011', '101', '110', '001', '010', '100', '000'] >>> ', '.join(''.join(sorted(s)) ... for s in reverse_shortlex({'a', 'b', 'c', 'd'}, ... [{...
def reverse_shortlex(end, other, excludeend=False): """Yield all intersections of end with other in reverse shortlex order. >>> ['{:03b}'.format(s) for s in reverse_shortlex(0b111, [0b011, 0b101, 0b110])] ['111', '011', '101', '110', '001', '010', '100', '000'] >>> ', '.join(''.join(sorted(s)) ......
Get a representative text of a time (in s).
def time_to_text(time): """Get a representative text of a time (in s).""" if time < 0.001: return str(round(time * 1000000)) + " µs" elif time < 1: return str(round(time * 1000)) + " ms" elif time < 60: return str(round(time, 1)) + " s" else: return str(round(tim...
Pass this function to upload_to argument of FileField to store the file on an unguessable path. The format of the path is class_name/hash/original_filename.
def generate_random_upload_path(instance, filename): """ Pass this function to upload_to argument of FileField to store the file on an unguessable path. The format of the path is class_name/hash/original_filename. """ return os.path.join(instance.__class__.__name__.lower(), uuid().hex, filename)
removes UTF chars from filename
def generate_filename(self, instance, filename): """ removes UTF chars from filename """ from unidecode import unidecode return super().generate_filename(instance, unidecode(force_text(filename)))
Retrieve the next item in the queue. Returns deserialized value, or None if there were no entries in the Queue.
def next(self): """ Retrieve the next item in the queue. Returns deserialized value, or None if there were no entries in the Queue. """ if self.blocking >= 0: # returns queue name and item, we just need item res = self.redis.blpop([self.name], timeout=sel...
Send a value to this LIFO Queue. Provided argument is serialized and pushed out. Don't send None.
def send(self, *args): """ Send a value to this LIFO Queue. Provided argument is serialized and pushed out. Don't send None. """ # this and the serializer could use some streamlining if None in args: raise TypeError('None is not a valid queue item.') serializ...
Clear any existing values from this queue.
def clear(self): """ Clear any existing values from this queue. """ logger.debug('Clearing queue: "%s"', self.name) return self.redis.delete(self.name)
Converts a 32 bit unsigned number to signed. uint32:= an unsigned 32 bit number ... print(u2i(4294967272)) -24 print(u2i(37)) 37 ...
def u2i(uint32): """ Converts a 32 bit unsigned number to signed. uint32:= an unsigned 32 bit number ... print(u2i(4294967272)) -24 print(u2i(37)) 37 ... """ mask = (2 ** 32) - 1 if uint32 & (1 << 31): v = uint32 | ~mask else: v = uint32 & mask r...
Converts a 32 bit unsigned number to signed. If the number is negative it indicates an error. On error a pigpio exception will be raised if exceptions is True.
def _u2i(uint32): """ Converts a 32 bit unsigned number to signed. If the number is negative it indicates an error. On error a pigpio exception will be raised if exceptions is True. """ v = u2i(uint32) if v < 0: if exceptions: raise ApigpioError(error_text(v)) retur...
Adds a callback.
def append(self, cb): """Adds a callback.""" self.callbacks.append(cb.callb) self.monitor = self.monitor | cb.callb.bit yield from self.pi._pigpio_aio_command(_PI_CMD_NB, self.handle, self.monitor)
Removes a callback.
def remove(self, cb): """Removes a callback.""" if cb in self.callbacks: self.callbacks.remove(cb) new_monitor = 0 for c in self.callbacks: new_monitor |= c.bit if new_monitor != self.monitor: self.monitor = new_monitor ...
Runs a pigpio socket command. sl:= command socket and lock. cmd:= the command to be executed. p1:= command parameter 1 (if applicable). p2:= command parameter 2 (if applicable).
def _pigpio_aio_command(self, cmd, p1, p2,): """ Runs a pigpio socket command. sl:= command socket and lock. cmd:= the command to be executed. p1:= command parameter 1 (if applicable). p2:= command parameter 2 (if applicable). """ with (yield from self...
Runs an extended pigpio socket command. sl:= command socket and lock. cmd:= the command to be executed. p1:= command parameter 1 (if applicable). p2:= command parameter 2 (if applicable). p3:= total size in bytes of following extents extents:= addition...
def _pigpio_aio_command_ext(self, cmd, p1, p2, p3, extents, rl=True): """ Runs an extended pigpio socket command. sl:= command socket and lock. cmd:= the command to be executed. p1:= command parameter 1 (if applicable). p2:= command parameter 2 (if applica...
Connect to a remote or local gpiod daemon. :param address: a pair (address, port), the address must be already resolved (for example an ip address) :return:
def connect(self, address): """ Connect to a remote or local gpiod daemon. :param address: a pair (address, port), the address must be already resolved (for example an ip address) :return: """ self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) self...
Store a script for later execution. script:= the script text as a series of bytes. Returns a >=0 script id if OK. ... sid = pi.store_script( b'tag 0 w 22 1 mils 100 w 22 0 mils 100 dcr p0 jp 0') ...
def store_script(self, script): """ Store a script for later execution. script:= the script text as a series of bytes. Returns a >=0 script id if OK. ... sid = pi.store_script( b'tag 0 w 22 1 mils 100 w 22 0 mils 100 dcr p0 jp 0') ... """ ...
Runs a stored script. script_id:= id of stored script. params:= up to 10 parameters required by the script. ... s = pi.run_script(sid, [par1, par2]) s = pi.run_script(sid) s = pi.run_script(sid, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]) ...
def run_script(self, script_id, params=None): """ Runs a stored script. script_id:= id of stored script. params:= up to 10 parameters required by the script. ... s = pi.run_script(sid, [par1, par2]) s = pi.run_script(sid) s = pi.run_script(sid, [1, 2,...
Returns the run status of a stored script as well as the current values of parameters 0 to 9. script_id:= id of stored script. The run status may be . . PI_SCRIPT_INITING PI_SCRIPT_HALTED PI_SCRIPT_RUNNING PI_SCRIPT_WAITING PI_SCRIPT_FAILED ...
def script_status(self, script_id): """ Returns the run status of a stored script as well as the current values of parameters 0 to 9. script_id:= id of stored script. The run status may be . . PI_SCRIPT_INITING PI_SCRIPT_HALTED PI_SCRIPT_RUNNING...
Stops a running script. script_id:= id of stored script. ... status = pi.stop_script(sid) ...
def stop_script(self, script_id): """ Stops a running script. script_id:= id of stored script. ... status = pi.stop_script(sid) ... """ res = yield from self._pigpio_aio_command(_PI_CMD_PROCS, script_id, 0) return _u2i(res)
Deletes a stored script. script_id:= id of stored script. ... status = pi.delete_script(sid) ...
def delete_script(self, script_id): """ Deletes a stored script. script_id:= id of stored script. ... status = pi.delete_script(sid) ... """ res = yield from self._pigpio_aio_command(_PI_CMD_PROCD, script_id, 0) return _u2i(res)
Clears gpios 0-31 if the corresponding bit in bits is set. bits:= a 32 bit mask with 1 set if the corresponding gpio is to be cleared. A returned status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of the gpios. ... pi.clear_...
def clear_bank_1(self, bits): """ Clears gpios 0-31 if the corresponding bit in bits is set. bits:= a 32 bit mask with 1 set if the corresponding gpio is to be cleared. A returned status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or...
Sets gpios 0-31 if the corresponding bit in bits is set. bits:= a 32 bit mask with 1 set if the corresponding gpio is to be set. A returned status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of the gpios. ... pi.set_bank_1(i...
def set_bank_1(self, bits): """ Sets gpios 0-31 if the corresponding bit in bits is set. bits:= a 32 bit mask with 1 set if the corresponding gpio is to be set. A returned status of PI_SOME_PERMITTED indicates that the user is not allowed to write to one or more of...
Sets the gpio mode. gpio:= 0-53. mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5. ... pi.set_mode( 4, apigpio.INPUT) # gpio 4 as input pi.set_mode(17, apigpio.OUTPUT) # gpio 17 as output pi.set_mode(24, apigpio.ALT2) # gpio 24 as ALT2 ...
def set_mode(self, gpio, mode): """ Sets the gpio mode. gpio:= 0-53. mode:= INPUT, OUTPUT, ALT0, ALT1, ALT2, ALT3, ALT4, ALT5. ... pi.set_mode( 4, apigpio.INPUT) # gpio 4 as input pi.set_mode(17, apigpio.OUTPUT) # gpio 17 as output pi.set_mode(24, apig...
Sets or clears the internal GPIO pull-up/down resistor. gpio:= 0-53. pud:= PUD_UP, PUD_DOWN, PUD_OFF. ... yield from pi.set_pull_up_down(17, apigpio.PUD_OFF) yield from pi.set_pull_up_down(23, apigpio.PUD_UP) yield from pi.set_pull_up_down(24, apigpio.PUD_DOWN) ....
def set_pull_up_down(self, gpio, pud): """ Sets or clears the internal GPIO pull-up/down resistor. gpio:= 0-53. pud:= PUD_UP, PUD_DOWN, PUD_OFF. ... yield from pi.set_pull_up_down(17, apigpio.PUD_OFF) yield from pi.set_pull_up_down(23, apigpio.PUD_UP) yie...
Returns the gpio mode. gpio:= 0-53. Returns a value as follows . . 0 = INPUT 1 = OUTPUT 2 = ALT5 3 = ALT4 4 = ALT0 5 = ALT1 6 = ALT2 7 = ALT3 . . ... print(pi.get_mode(0)) 4 ...
def get_mode(self, gpio): """ Returns the gpio mode. gpio:= 0-53. Returns a value as follows . . 0 = INPUT 1 = OUTPUT 2 = ALT5 3 = ALT4 4 = ALT0 5 = ALT1 6 = ALT2 7 = ALT3 . . ... print(pi...
Sets the gpio level. gpio:= 0-53. level:= 0, 1. If PWM or servo pulses are active on the gpio they are switched off. ... pi.set_mode(17, pigpio.OUTPUT) pi.write(17,0) print(pi.read(17)) 0 pi.write(17,1) print(pi.read(17)) ...
def write(self, gpio, level): """ Sets the gpio level. gpio:= 0-53. level:= 0, 1. If PWM or servo pulses are active on the gpio they are switched off. ... pi.set_mode(17, pigpio.OUTPUT) pi.write(17,0) print(pi.read(17)) 0 ...
Returns the GPIO level. gpio:= 0-53. ... yield from pi.set_mode(23, pigpio.INPUT) yield from pi.set_pull_up_down(23, pigpio.PUD_DOWN) print(yield from pi.read(23)) 0 yield from pi.set_pull_up_down(23, pigpio.PUD_UP) print(yield from pi.read(23)) 1 ...
def read(self, gpio): """ Returns the GPIO level. gpio:= 0-53. ... yield from pi.set_mode(23, pigpio.INPUT) yield from pi.set_pull_up_down(23, pigpio.PUD_DOWN) print(yield from pi.read(23)) 0 yield from pi.set_pull_up_down(23, pigpio.PUD_UP) ...
Send a trigger pulse to a GPIO. The GPIO is set to level for pulse_len microseconds and then reset to not level. user_gpio:= 0-31 pulse_len:= 1-100 level:= 0-1 ... pi.gpio_trigger(23, 10, 1) ...
def gpio_trigger(self, user_gpio, pulse_len=10, level=1): """ Send a trigger pulse to a GPIO. The GPIO is set to level for pulse_len microseconds and then reset to not level. user_gpio:= 0-31 pulse_len:= 1-100 level:= 0-1 ... pi.gpio_trigger(23, 10, 1...
Sets a glitch filter on a GPIO. Level changes on the GPIO are not reported unless the level has been stable for at least [*steady*] microseconds. The level is then reported. Level changes of less than [*steady*] microseconds are ignored. user_gpio:= 0-31 steady:= 0-3...
def set_glitch_filter(self, user_gpio, steady): """ Sets a glitch filter on a GPIO. Level changes on the GPIO are not reported unless the level has been stable for at least [*steady*] microseconds. The level is then reported. Level changes of less than [*steady*] micros...
Sets a noise filter on a GPIO. Level changes on the GPIO are ignored until a level which has been stable for [*steady*] microseconds is detected. Level changes on the GPIO are then reported for [*active*] microseconds after which the process repeats. user_gpio:= 0-31 ...
def set_noise_filter(self, user_gpio, steady, active): """ Sets a noise filter on a GPIO. Level changes on the GPIO are ignored until a level which has been stable for [*steady*] microseconds is detected. Level changes on the GPIO are then reported for [*active*] microse...
Starts (non-zero dutycycle) or stops (0) PWM pulses on the GPIO. user_gpio:= 0-31. dutycycle:= 0-range (range defaults to 255). The [*set_PWM_range*] function can change the default range of 255. ... pi.set_PWM_dutycycle(4, 0) # PWM off pi.set_PWM_dutycycle(4, 64) # PW...
def set_PWM_dutycycle(self, user_gpio, dutycycle): """ Starts (non-zero dutycycle) or stops (0) PWM pulses on the GPIO. user_gpio:= 0-31. dutycycle:= 0-range (range defaults to 255). The [*set_PWM_range*] function can change the default range of 255. ... pi.set_PW...
Calls a user supplied function (a callback) whenever the specified gpio edge is detected. user_gpio:= 0-31. edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE. func:= user supplied callback function. The user supplied callback receives three parameters, the gpio, ...
def add_callback(self, user_gpio, edge=RISING_EDGE, func=None): """ Calls a user supplied function (a callback) whenever the specified gpio edge is detected. user_gpio:= 0-31. edge:= EITHER_EDGE, RISING_EDGE (default), or FALLING_EDGE. func:= user supplied callback...
Starts (500-2500) or stops (0) servo pulses on the GPIO. user_gpio:= 0-31. pulsewidth:= 0 (off), 500 (most anti-clockwise) - 2500 (most clockwise). The selected pulsewidth will continue to be transmitted until changed by a subsequent call to set_servo_pulsewidth. ...
def set_servo_pulsewidth(self, user_gpio, pulsewidth): """ Starts (500-2500) or stops (0) servo pulses on the GPIO. user_gpio:= 0-31. pulsewidth:= 0 (off), 500 (most anti-clockwise) - 2500 (most clockwise). The selected pulsewidth will continue to be transmi...
Converts a camelcase string to a list.
def camelcase2list(s, lower=False): """Converts a camelcase string to a list.""" s = re.findall(r'([A-Z][a-z0-9]+)', s) return [w.lower() for w in s] if lower else s
Returns parameter names from the route.
def get_route_param_names(endpoint): """Returns parameter names from the route.""" try: g = current_app.url_map.iter_rules(endpoint) return next(g).arguments except KeyError: return {}
Run the shadowing computation with the values stored in ``self.arg_``. Precomputed information is stored in: * **.diff_t** (*ndarray*): ``np.diff(t)`` * **.integral** (*ndarray*): Trapezoidal data integration over time. The steps are: ...
def run(self): """ Run the shadowing computation with the values stored in ``self.arg_``. Precomputed information is stored in: * **.diff_t** (*ndarray*): ``np.diff(t)`` * **.integral** (*ndarray*): Trapezoidal data integration over time. ...
Generates a equally spaced mesh on the Solar Horizont (SH). Computes the Voronoi diagram from a set of points given by pairs of (azimuth, zenit) values. This discretization completely covers all the Sun positions. The smaller mesh size, the better resolution obtai...
def Vonoroi_SH(self, mesh_size=0.1): """ Generates a equally spaced mesh on the Solar Horizont (SH). Computes the Voronoi diagram from a set of points given by pairs of (azimuth, zenit) values. This discretization completely covers all the Sun positions. ...
Computes the Sun positions for the *t* time vector. *t* have to be in absolute minutes (0 at 00:00 01 Jan). The and in Sun positions calculated are in solar time, that is, maximun solar zenit exactly at midday. The generated information is stored in: ...
def get_sunpos(self, t, true_time=False): """ Computes the Sun positions for the *t* time vector. *t* have to be in absolute minutes (0 at 00:00 01 Jan). The and in Sun positions calculated are in solar time, that is, maximun solar zenit exactly at midday. ...
Computes the shadoing for the ``pyny.Space`` stored in ``.space`` for the time intervals and Sun positions stored in ``.arg_t`` and ``.sun_pos``, respectively. The generated information is stored in: * **.light_vor** (*ndarray (dtype=bool)*): Array with the ...
def compute_shadows(self): """ Computes the shadoing for the ``pyny.Space`` stored in ``.space`` for the time intervals and Sun positions stored in ``.arg_t`` and ``.sun_pos``, respectively. The generated information is stored in: * **.light_vor** (*...
Assign the sum of ``.integral``\* to each sensible point in the ``pyny.Space`` for the intervals that the points are visible to the Sun. The generated information is stored in: * **.proj_vor** (*ndarray*): ``.integral`` projected to the Voronoi diagram. ...
def project_data(self): ''' Assign the sum of ``.integral``\* to each sensible point in the ``pyny.Space`` for the intervals that the points are visible to the Sun. The generated information is stored in: * **.proj_vor** (*ndarray*): ``.integral`` projected t...
Voronoi diagram visualizations. There are three types: 1. **vor**: Voronoi diagram of the Solar Horizont. 2. **freq**: Frequency of Sun positions in t in the Voronoi diagram of the Solar Horizont. 3. **data**: Accumulated time integral of the data projec...
def vor_plot(self, which='vor'): """ Voronoi diagram visualizations. There are three types: 1. **vor**: Voronoi diagram of the Solar Horizont. 2. **freq**: Frequency of Sun positions in t in the Voronoi diagram of the Solar Horizont. 3....
Converts ``datetime`` objects lists into absolute minutes vectors. It also can be used to generate absolute minutes vector from a time interval (in minutes). :param time_obj: ``datetime`` objects to convert into absolute minutes. :type time_obj: list of ``dat...
def to_minutes(time_obj = None, dt = None): ''' Converts ``datetime`` objects lists into absolute minutes vectors. It also can be used to generate absolute minutes vector from a time interval (in minutes). :param time_obj: ``datetime`` objects to convert into abso...
Plots the exposure of the sensible points in a space to the data and the Sun positions. It is required to previously compute the shadowing. If the computation has been made with a data timeseries, the plot will have a colorbar. Units are accumulated kilounits*hour (for ...
def exposure_plot(self, places=-1, c_poly='default', c_holes='default', s_sop=25, extra_height=0.1): """ Plots the exposure of the sensible points in a space to the data and the Sun positions. It is required to previously compute the shadowing. ...
name: str or file or file-like or pathlib.Path File to be opened
def open(name): """" name: str or file or file-like or pathlib.Path File to be opened """ with builtins.open(name, mode='r') as fd: data = json.load(fd) return loads(data)
Extract metadata from serialized file
def extract_db_info(self, obj, keys): """Extract metadata from serialized file""" objl = self.convert_in(obj) # FIXME: this is too complex if isinstance(objl, self.__class__): return objl.update_meta_info() try: with builtins.open(objl, mode='r') as fd:...
Extract metadata from myself
def update_meta_info(self): """Extract metadata from myself""" result = super(BaseStructuredCalibration, self).update_meta_info() result['instrument'] = self.instrument result['uuid'] = self.uuid result['tags'] = self.tags result['type'] = self.name() minfo = se...
Call a Gnuplot script, passing it arguments and datasets. Args: scipt_name(str): The name of the Gnuplot script. args_dict(dict): A dictionary of parameters to pass to the script. The `key` is the name of the variable that the `item` will be passed to the Gnuplot script...
def gnuplot(script_name, args_dict={}, data=[], silent=True): ''' Call a Gnuplot script, passing it arguments and datasets. Args: scipt_name(str): The name of the Gnuplot script. args_dict(dict): A dictionary of parameters to pass to the script. The `key` is the name of the...
Function to produce a general 2D plot. Args: x (list): x points. y (list): y points. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). x_label (str): x-axis label. y_label (str): y-axis label.
def gnuplot_2d(x, y, filename, title='', x_label='', y_label=''): ''' Function to produce a general 2D plot. Args: x (list): x points. y (list): y points. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). x_label...
Function to produce a general 3D plot from a 2D matrix. Args: z_matrix (list): 2D matrix. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). x_label (str): x-axis label. y_label (str): y-axis label.
def gnuplot_3d_matrix(z_matrix, filename, title='', x_label='', y_label=''): ''' Function to produce a general 3D plot from a 2D matrix. Args: z_matrix (list): 2D matrix. filename (str): Filename of the output image. title (str): Title of the plot. Default is '' (no title). ...
Get reactions from folders. Parameters ---------- skip: list of str list of folders not to read goto_reaction: str Skip ahead to this metal goto_reaction: Skip ahead to this reacion
def read(self, skip=[], goto_metal=None, goto_reaction=None): """ Get reactions from folders. Parameters ---------- skip: list of str list of folders not to read goto_reaction: str Skip ahead to this metal goto_reaction: Skip a...
Create empty dictionaries
def read_reaction(self, root): folder_name = os.path.basename(root) self.reaction, self.sites = ase_tools.get_reaction_from_folder( folder_name) # reaction dict self.stdout.write( '----------- REACTION: {} --> {} --------------\n' .format('+'.join(self.rea...
Match adsorbate structures with reaction entries
def read_energies(self, root): self.key_value_pairs_reaction = None slab_structures = collect_structures(root) if len(slab_structures) == 0: self.raise_warning('No structure files in {root}: Skipping this folder' .format(root=root)) return...
Return an slice with a symmetric region around center.
def slice_create(center, block, start=0, stop=None): '''Return an slice with a symmetric region around center.''' do = coor_to_pix_1d(center - block) up = coor_to_pix_1d(center + block) l = max(start, do) if stop is not None: h = min(up + 1, stop) else: h = up + 1 return ...
Create a region of size box, around a center in a image of shape.
def image_box(center, shape, box): '''Create a region of size box, around a center in a image of shape.''' return tuple(slice_create(c, b, stop=s) for c, s, b in zip(center, shape, box))
Expand a slice on the start/stop limits
def expand_slice(s, a, b, start=0, stop=None): '''Expand a slice on the start/stop limits''' n1 = max(s.start - a, start) n2 = s.stop + b if stop is not None: n2 = min(n2, stop) return slice(n1, n2, 1)
Apply expend_slice on a tuple of slices
def expand_region(tuple_of_s, a, b, start=0, stop=None): '''Apply expend_slice on a tuple of slices''' return tuple(expand_slice(s, a, b, start=start, stop=stop) for s in tuple_of_s)
Adapt obsres after file copy
def adapt_obsres(self, obsres): """Adapt obsres after file copy""" _logger.debug('adapt observation result for work dir') for f in obsres.images: # Remove path components f.filename = os.path.basename(f.filename) return obsres
Store the values of the completed task.
def store(self, completed_task, resultsdir): """Store the values of the completed task.""" with working_directory(resultsdir): _logger.info('storing result') return completed_task.store(self)
Validate convertibility to internal representation Returns ------- bool True if 'obj' matches the data type Raises ------- ValidationError If the validation fails
def validate(self, obj): """Validate convertibility to internal representation Returns ------- bool True if 'obj' matches the data type Raises ------- ValidationError If the validation fails """ if not isinstance(obj, self....
Grant SELECT on public schema
def create_user(self, user, table_privileges=['ALL PRIVILEGES'], schema_privileges=['ALL PRIVILEGES'], row_limit=50000): con = self.connection or self._connect() cur = con.cursor() cur.execute('CREATE SCHEMA {0};'.format(user)) # self._initialize(...
Delete user and all data
def delete_user(self, user): """ Delete user and all data""" assert self.user == 'catroot' or self.user == 'postgres' assert not user == 'public' con = self.connection or self._connect() cur = con.cursor() cur.execute('DROP SCHEMA {user} CASCADE;'.format(user=user)) ...
Transfer dataset from one schema to another
def release(self, pub_ids=None, email=None, from_schema='upload', to_schema='public'): """ Transfer dataset from one schema to another""" assert pub_ids or email,\ "Specify either pub_ids or email" assert not (pub_ids and email),\ "Specify either pub_ids ...
Check if a user owns a publication
def get_pub_id_owner(self, pub_id): """Check if a user owns a publication""" con = self.connection or self._connect() cur = con.cursor() cur.execute( """SELECT distinct username from upload.reaction WHERE pub_id = '{pub_id}'""" .format(pub_id=pub_id))...
Delete dataset from upload schema
def delete_publication(self, pub_id, schema='upload'): """ Delete dataset from upload schema""" if schema == 'upload': user = 'upload_admin' elif schema == 'public': user = 'catroot' if not self.user == 'catroot': assert self.user == user, \ ...
Write to reaction_system tables
def write_reaction(self, value_dict): con = self.connection or self._connect() self._initialize(con) cur = con.cursor() ase_ids = value_dict['ase_ids'] energy_corrections = value_dict.get('energy_corrections', {}) key_list = get_key_list(start_index=1) values = ...
Will delete all data in schema. Only for test use!
def truncate_schema(self): """ Will delete all data in schema. Only for test use!""" assert self.server == 'localhost' con = self.connection or self._connect() self._initialize(con) cur = con.cursor() cur.execute('DELETE FROM publication;') cur.execute('TRUNCATE...
Transfer data from local sqlite3 .db file to the catalysis-hub postgreSQL server Parameters: filename_sqlite: str name of .db file block_size: int (default 1000) Number of atomic structures and reactions to write together in each block. start_...
def transfer(self, filename_sqlite, block_size=1000, start_block=0, write_ase=True, write_publication=True, write_reaction=True, write_reaction_system=True, check=False): """ Transfer data from local sqlite3 .db file to the catalysis-hub postgreSQL serv...
Call the stream's write method without linebreaks at line endings.
def write(self, *args, **kwargs): """ Call the stream's write method without linebreaks at line endings. """ return self.stream.write(ending="", *args, **kwargs)
Initialize the 1D interpolation.
def _update(self): """Initialize the 1D interpolation.""" if self.strains.size and self.strains.size == self.values.size: x = np.log(self.strains) y = self.values if x.size < 4: self._interpolater = interp1d( x, ...
If nonlinear properties are specified.
def is_nonlinear(self): """If nonlinear properties are specified.""" return any( isinstance(p, NonlinearProperty) for p in [self.mod_reduc, self.damping])
minimum damping [decimal]
def _calc_damping_min(self): """minimum damping [decimal]""" return ((0.8005 + 0.0129 * self._plas_index * self._ocr ** -0.1069) * (self._stress_mean * KPA_TO_ATM) ** -0.2889 * (1 + 0.2919 * np.log(self._freq))) / 100
Compute the reference strain using Equation (6).
def _calc_strain_ref(x_3, x_3_mean): """Compute the reference strain using Equation (6).""" b_9 = -1.41 b_10 = -0.950 return np.exp(b_9 + b_10 * (x_3 - x_3_mean)) / 100
Compute the shear modulus reduction using Equation (1).
def _calc_mod_reduc(self, strains, strain_ref, x_1, x_1_mean, x_2, x_2_mean, x_3, x_3_mean): """Compute the shear modulus reduction using Equation (1).""" ones = np.ones_like(strains) # Predictor x_4 = np.log(self._lab_consol_ratio) * ones x = np.c_[ones,...
Compute the damping ratio using Equation (16).
def _calc_damping(mod_reducs, x_2, x_2_mean, x_3, x_3_mean): """Compute the damping ratio using Equation (16).""" # Mean values of the predictors x_1_mean = -1.0 x_1 = np.log(np.log(1 / mod_reducs) + 0.103) ones = np.ones_like(mod_reducs) x = np.c_[ones, x_1, x_2, x_3, (...
The relative error, in percent, between the two iterations.
def relative_error(self): """The relative error, in percent, between the two iterations. """ if self.previous is not None: # FIXME # Use the maximum strain value -- this is important for error # calculation with frequency dependent properties # pr...
Create a copy of the layer.
def duplicate(cls, other): """Create a copy of the layer.""" return cls(other.soil_type, other.thickness, other.shear_vel)
Strain-compatible damping.
def damping(self): """Strain-compatible damping.""" try: value = self._damping.value except AttributeError: value = self._damping return value
Strain-compatible complex shear modulus [kN/m²].
def comp_shear_mod(self): """Strain-compatible complex shear modulus [kN/m²]. """ damping = self.damping if COMP_MODULUS_MODEL == 'seed': # Frequency independent model (Seed et al., 1970) # Correct dissipated energy # Incorrect shear modulus: G * \sqrt...
Strain-compatible shear modulus [kN//m²].
def shear_mod(self): """Strain-compatible shear modulus [kN//m²].""" try: value = self._shear_mod.value except AttributeError: value = self._shear_mod return value
Vertical stress from the top of the layer [kN//m²].
def stress_vert(self, depth_within=0, effective=False): """Vertical stress from the top of the layer [kN//m²].""" assert depth_within <= self.thickness stress_vert = self._stress_vert + depth_within * self.unit_wt if effective: pore_pressure = self._profile.pore_pressure(self...
Subdivide the layers to capture strain variation. Parameters ---------- max_freq: float Maximum frequency of interest [Hz]. wave_frac: float Fraction of wavelength required. Typically 1/3 to 1/5. Returns ------- profile: Profile ...
def auto_discretize(self, max_freq=50., wave_frac=0.2): """Subdivide the layers to capture strain variation. Parameters ---------- max_freq: float Maximum frequency of interest [Hz]. wave_frac: float Fraction of wavelength required. Typically 1/3 to 1/5. ...
Create a Location for a specific depth. Parameters ---------- wave_field: str Wave field. See :class:`Location` for possible values. depth: float, optional Depth corresponding to the :class`Location` of interest. If provided, then index is ignored. ...
def location(self, wave_field, depth=None, index=None): """Create a Location for a specific depth. Parameters ---------- wave_field: str Wave field. See :class:`Location` for possible values. depth: float, optional Depth corresponding to the :class`Locati...
Calculate the time-average velocity. Parameters ---------- depth: float Depth over which the average velocity is computed. Returns ------- avg_vel: float Time averaged velocity.
def time_average_vel(self, depth): """Calculate the time-average velocity. Parameters ---------- depth: float Depth over which the average velocity is computed. Returns ------- avg_vel: float Time averaged velocity. """ de...
Simplified Rayliegh velocity of the site. This follows the simplifications proposed by Urzua et al. (2017) Returns ------- rayleigh_vel : float Equivalent shear-wave velocity.
def simplified_rayliegh_vel(self): """Simplified Rayliegh velocity of the site. This follows the simplifications proposed by Urzua et al. (2017) Returns ------- rayleigh_vel : float Equivalent shear-wave velocity. """ # FIXME: What if last layer has ...
Iterate over the varied thicknesses. The layering is generated using a non-homogenous Poisson process. The following routine is used to generate the layering. The rate function, :math:`\lambda(t)`, is integrated from 0 to t to generate cumulative rate function, :math:`\Lambda(t)`. This ...
def iter_thickness(self, depth_total): """Iterate over the varied thicknesses. The layering is generated using a non-homogenous Poisson process. The following routine is used to generate the layering. The rate function, :math:`\lambda(t)`, is integrated from 0 to t to generate c...
Calculate the covariance matrix. Parameters ---------- profile : site.Profile Input site profile Yields ------ covar : `class`:numpy.array Covariance matrix
def _calc_covar_matrix(self, profile): """Calculate the covariance matrix. Parameters ---------- profile : site.Profile Input site profile Yields ------ covar : `class`:numpy.array Covariance matrix """ corr = self._calc_c...
Compute the adjacent-layer correlations Parameters ---------- profile : :class:`site.Profile` Input site profile Yields ------ corr : :class:`numpy.array` Adjacent-layer correlations
def _calc_corr(self, profile): """Compute the adjacent-layer correlations Parameters ---------- profile : :class:`site.Profile` Input site profile Yields ------ corr : :class:`numpy.array` Adjacent-layer correlations """ d...
Use generic model parameters based on site class. Parameters ---------- site_class: str Site classification. Possible options are: * Geomatrix AB * Geomatrix CD * USGS AB * USGS CD * USGS A * USGS B ...
def generic_model(cls, site_class, **kwds): """Use generic model parameters based on site class. Parameters ---------- site_class: str Site classification. Possible options are: * Geomatrix AB * Geomatrix CD * USGS AB * USG...
Calculate the standard deviation as a function of G/G_max. Equation 7.29 from Darendeli (2001). Parameters ---------- mod_reduc : array_like Modulus reduction values. Returns ------- std : :class:`numpy.ndarray` Standard deviation.
def calc_std_mod_reduc(mod_reduc): """Calculate the standard deviation as a function of G/G_max. Equation 7.29 from Darendeli (2001). Parameters ---------- mod_reduc : array_like Modulus reduction values. Returns ------- std : :class:`numpy....
Calculate the standard deviation as a function of damping in decimal. Equation 7.30 from Darendeli (2001). Parameters ---------- damping : array_like Material damping values in decimal. Returns ------- std : :class:`numpy.ndarray` Standa...
def calc_std_damping(damping): """Calculate the standard deviation as a function of damping in decimal. Equation 7.30 from Darendeli (2001). Parameters ---------- damping : array_like Material damping values in decimal. Returns ------- std :...
Append the ``element`` to the ``field`` of the record. This method is smart: it does nothing if ``element`` is empty and creates ``field`` if it does not exit yet. Args: :param field: the name of the field of the record to append to :type field: string :para...
def _append_to(self, field, element): """Append the ``element`` to the ``field`` of the record. This method is smart: it does nothing if ``element`` is empty and creates ``field`` if it does not exit yet. Args: :param field: the name of the field of the record to append to ...
Add name variant. Args: :param name: name variant for the current author. :type name: string
def add_name_variant(self, name): """Add name variant. Args: :param name: name variant for the current author. :type name: string """ self._ensure_field('name', {}) self.obj['name'].setdefault('name_variants', []).append(name)
Add native name. Args: :param name: native name for the current author. :type name: string
def add_native_name(self, name): """Add native name. Args: :param name: native name for the current author. :type name: string """ self._ensure_field('name', {}) self.obj['name'].setdefault('native_names', []).append(name)
Add previous name. Args: :param name: previous name for the current author. :type name: string
def add_previous_name(self, name): """Add previous name. Args: :param name: previous name for the current author. :type name: string """ self._ensure_field('name', {}) self.obj['name'].setdefault('previous_names', []).append(name)
Add email address. Args: :param email: email of the author. :type email: string :param hidden: if email is public or not. :type hidden: boolean
def add_email_address(self, email, hidden=None): """Add email address. Args: :param email: email of the author. :type email: string :param hidden: if email is public or not. :type hidden: boolean """ existing_emails = get_value(self.obj, ...
Add a personal website. Args: :param url: url to the person's website. :type url: string :param description: short description of the website. :type description: string
def add_url(self, url, description=None): """Add a personal website. Args: :param url: url to the person's website. :type url: string :param description: short description of the website. :type description: string """ url = { ...
Add an institution where the person works/worked. Args: :param institution: name of the institution. :type institution: string :param start_date: the date when the person joined the institution, in any format. :type start_date: string :param end_dat...
def add_institution(self, institution, start_date=None, end_date=None, rank=None, record=None, curated=False, current=False): """Add an institution where the person works/worked. Args: :param institution: name of the institution. :type institution: string :param sta...
Add an experiment that the person worked on. Args: :param name: name of the experiment. :type name: string :param start_date: the date when the person started working on the experiment. :type start_date: string :param end_date: the date when the per...
def add_project(self, name, record=None, start_date=None, end_date=None, curated=False, current=False): """Add an experiment that the person worked on. Args: :param name: name of the experiment. :type name: string :param start_date: the date when the person started ...
Add an advisor. Args: :param name: full name of the advisor. :type name: string :param ids: list with the IDs of the advisor. :type ids: list :param degree_type: one of the allowed types of degree the advisor helped with. :type degree_ty...
def add_advisor(self, name, ids=None, degree_type=None, record=None, curated=False): """Add an advisor. Args: :param name: full name of the advisor. :type name: string :param ids: list with the IDs of the advisor. :type ids: list :param degr...
Add a private note. Args: :param comment: comment about the author. :type comment: string :param source: the source of the comment. :type source: string
def add_private_note(self, note, source=None): """Add a private note. Args: :param comment: comment about the author. :type comment: string :param source: the source of the comment. :type source: string """ note = { 'value': n...