INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Match two lists with wavelengths.
Assign individual wavelengths from wv_master to each expected
wavelength when the latter is within the maximum allowed range.
Parameters
----------
wv_master : numpy array
Array containing the master wavelengths.
wv_expected_all_peaks : numpy array
... | def match_wv_arrays(wv_master, wv_expected_all_peaks, delta_wv_max):
"""Match two lists with wavelengths.
Assign individual wavelengths from wv_master to each expected
wavelength when the latter is within the maximum allowed range.
Parameters
----------
wv_master : numpy array
Array co... |
Set window geometry.
Parameters
==========
geometry : tuple (4 integers) or None
x, y, dx, dy values employed to set the Qt backend geometry. | def set_window_geometry(geometry):
"""Set window geometry.
Parameters
==========
geometry : tuple (4 integers) or None
x, y, dx, dy values employed to set the Qt backend geometry.
"""
if geometry is not None:
x_geom, y_geom, dx_geom, dy_geom = geometry
mngr = plt.get_c... |
Parse a fixed width line. | def parse_fixed_width(types, lines):
"""Parse a fixed width line."""
values = []
line = []
for width, parser in types:
if not line:
line = lines.pop(0).replace('\n', '')
values.append(parser(line[:width]))
line = line[width:]
return values |
Parse nonlinear curves block. | def _parse_curves(block, **kwargs):
"""Parse nonlinear curves block."""
count = int(block.pop(0))
curves = []
for i in range(count):
for param in ['mod_reduc', 'damping']:
length, name = parse_fixed_width([(5, int), (65, to_str)], block)
curves.append(
si... |
Parse soil profile block. | def _parse_soil_profile(block, units, curves, **kwargs):
"""Parse soil profile block."""
wt_layer, length, _, name = parse_fixed_width(
3 * [(5, int)] + [(55, to_str)], block)
layers = []
soil_types = []
for i in range(length):
index, soil_idx, thickness, shear_mod, damping, unit_wt... |
Parse motin specification block. | def _parse_motion(block, **kwargs):
"""Parse motin specification block."""
_, fa_length, time_step, name, fmt = parse_fixed_width(
[(5, int), (5, int), (10, float), (30, to_str), (30, to_str)], block)
scale, pga, _, header_lines, _ = parse_fixed_width(
3 * [(10, to_float)] + 2 * [(5, int)],... |
Parse input location block. | def _parse_input_loc(block, profile, **kwargs):
"""Parse input location block."""
layer, wave_field = parse_fixed_width(2 * [(5, int)], block)
return profile.location(
motion.WaveField[wave_field],
index=(layer - 1), ) |
Parse run control block. | def _parse_run_control(block):
"""Parse run control block."""
_, max_iterations, strain_ratio, _, _ = parse_fixed_width(
2 * [(5, int)] + [(10, float)] + 2 * [(5, int)], block)
return propagation.EquivalentLinearCalculation(
strain_ratio, max_iterations, tolerance=10.) |
Compute 1d block intervals to be used by combine.
blockgen1d computes the slices by recursively halving the initial
interval (0, size) by 2 until its size is lesser or equal than block
:param block: an integer maximum block size
:param size: original size of the interval, it corresponds to a 0:size sl... | def blockgen1d(block, size):
"""Compute 1d block intervals to be used by combine.
blockgen1d computes the slices by recursively halving the initial
interval (0, size) by 2 until its size is lesser or equal than block
:param block: an integer maximum block size
:param size: original size of the int... |
Generate a list of slice tuples to be used by combine.
The tuples represent regions in an N-dimensional image.
:param blocks: a tuple of block sizes
:param shape: the shape of the n-dimensional array
:return: an iterator to the list of tuples of slices
Example:
>>> blocks = (500, 512)
... | def blockgen(blocks, shape):
"""Generate a list of slice tuples to be used by combine.
The tuples represent regions in an N-dimensional image.
:param blocks: a tuple of block sizes
:param shape: the shape of the n-dimensional array
:return: an iterator to the list of tuples of slices
Example:... |
Return the part of a 1d array covered by a block.
:param blk: size of the 1d block
:param size: size of the 1d a image
:return: a tuple of size covered and remaining size
Example:
>>> blk_coverage_1d(7, 100)
(98, 2) | def blk_coverage_1d(blk, size):
"""Return the part of a 1d array covered by a block.
:param blk: size of the 1d block
:param size: size of the 1d a image
:return: a tuple of size covered and remaining size
Example:
>>> blk_coverage_1d(7, 100)
(98, 2)
"""
rem = size % blk
... |
Return the maximum shape of an array covered by a block.
:param blk: the N-dimensional shape of the block
:param shape: the N-dimensional shape of the array
:return: the shape of the covered region
Example:
>>> max_blk_coverage(blk=(7, 6), shape=(100, 43))
(98, 42) | def max_blk_coverage(blk, shape):
"""Return the maximum shape of an array covered by a block.
:param blk: the N-dimensional shape of the block
:param shape: the N-dimensional shape of the array
:return: the shape of the covered region
Example:
>>> max_blk_coverage(blk=(7, 6), shape=(100, ... |
Iterate through the slices that recover a line.
This function is used by :func:`blk_nd_short` as a base 1d case.
The function stops yielding slices when the size of
the remaining slice is lesser than `blk`.
:param blk: the size of the block
:param shape: the size of the array
:return: a gener... | def blk_1d_short(blk, shape):
"""Iterate through the slices that recover a line.
This function is used by :func:`blk_nd_short` as a base 1d case.
The function stops yielding slices when the size of
the remaining slice is lesser than `blk`.
:param blk: the size of the block
:param shape: the s... |
Iterate trough the blocks that strictly cover an array.
Iterate trough the blocks that recover the part of the array
given by max_blk_coverage.
:param blk: the N-dimensional shape of the block
:param shape: the N-dimensional shape of the array
:return: a generator that yields the blocks
Examp... | def blk_nd_short(blk, shape):
"""Iterate trough the blocks that strictly cover an array.
Iterate trough the blocks that recover the part of the array
given by max_blk_coverage.
:param blk: the N-dimensional shape of the block
:param shape: the N-dimensional shape of the array
:return: a genera... |
Iterate through the slices that recover a line.
This function is used by :func:`blk_nd` as a base 1d case.
The last slice is returned even if is lesser than blk.
:param blk: the size of the block
:param shape: the size of the array
:return: a generator that yields the slices | def blk_1d(blk, shape):
"""Iterate through the slices that recover a line.
This function is used by :func:`blk_nd` as a base 1d case.
The last slice is returned even if is lesser than blk.
:param blk: the size of the block
:param shape: the size of the array
:return: a generator that yields ... |
Iterate through the blocks that cover an array.
This function first iterates trough the blocks that recover
the part of the array given by max_blk_coverage
and then iterates with smaller blocks for the rest
of the array.
:param blk: the N-dimensional shape of the block
:param shape: the N-dime... | def blk_nd(blk, shape):
"""Iterate through the blocks that cover an array.
This function first iterates trough the blocks that recover
the part of the array given by max_blk_coverage
and then iterates with smaller blocks for the rest
of the array.
:param blk: the N-dimensional shape of the blo... |
Provide a 2D block view to 2D array.
No error checking made. Therefore meaningful (as implemented) only for
blocks strictly compatible with the shape of A. | def block_view(arr, block=(3, 3)):
"""Provide a 2D block view to 2D array.
No error checking made. Therefore meaningful (as implemented) only for
blocks strictly compatible with the shape of A.
"""
# simple shape and strides computations may seem at first strange
# unless one is able to recog... |
Check some fields in order to define if the article is citeable.
:param publication_info: publication_info field
already populated
:type publication_info: list | def is_citeable(publication_info):
"""Check some fields in order to define if the article is citeable.
:param publication_info: publication_info field
already populated
:type publication_info: list
"""
def _item_has_pub_info(item):
return all(
key in item for key in (
... |
Like ``dict(**kwargs)``, but where the ``source`` key is special. | def _sourced_dict(self, source=None, **kwargs):
"""Like ``dict(**kwargs)``, but where the ``source`` key is special.
"""
if source:
kwargs['source'] = source
elif self.source:
kwargs['source'] = self.source
return kwargs |
Add abstract.
:param abstract: abstract for the current document.
:type abstract: string
:param source: source for the given abstract.
:type source: string | def add_abstract(self, abstract, source=None):
"""Add abstract.
:param abstract: abstract for the current document.
:type abstract: string
:param source: source for the given abstract.
:type source: string
"""
self._append_to('abstracts', self._sourced_dict(
... |
Add arxiv eprint.
:param arxiv_id: arxiv id for the current document.
:type arxiv_id: string
:param arxiv_categories: arXiv categories for the current document.
:type arxiv_categories: list | def add_arxiv_eprint(self, arxiv_id, arxiv_categories):
"""Add arxiv eprint.
:param arxiv_id: arxiv id for the current document.
:type arxiv_id: string
:param arxiv_categories: arXiv categories for the current document.
:type arxiv_categories: list
"""
self._app... |
Add doi.
:param doi: doi for the current document.
:type doi: string
:param source: source for the doi.
:type source: string
:param material: material for the doi.
:type material: string | def add_doi(self, doi, source=None, material=None):
"""Add doi.
:param doi: doi for the current document.
:type doi: string
:param source: source for the doi.
:type source: string
:param material: material for the doi.
:type material: string
"""
... |
Make a subrecord representing an author.
Args:
full_name(str): full name of the author. If not yet in standard
Inspire form, it will be normalized.
affiliations(List[str]): Inspire normalized affiliations of the
author.
roles(List[str]): Inspi... | def make_author(self, full_name,
affiliations=(),
roles=(),
raw_affiliations=(),
source=None,
ids=(),
emails=(),
alternative_names=()):
"""Make a subrecord representing an ... |
Make a dictionary that is representing a book.
:param publisher: publisher name
:type publisher: string
:param place: place of publication
:type place: string
:param date: A (partial) date in any format.
The date should contain at least a year
:type date: ... | def add_book(self, publisher=None, place=None, date=None):
"""
Make a dictionary that is representing a book.
:param publisher: publisher name
:type publisher: string
:param place: place of publication
:type place: string
:param date: A (partial) date in any f... |
:param isbns: the isbns of the book
:type isbns: object | def add_isbn(self, isbn, medium=None):
"""
:param isbns: the isbns of the book
:type isbns: object
"""
isbn_dict = {}
if isbn is not None:
isbn_dict['value'] = normalize_isbn(isbn)
if medium is not None:
isbn_dict['medium'] = medium
... |
:param volume: the volume of the book
:type volume: string
:param title: the title of the book
:type title: string | def add_book_series(self, title, volume=None):
"""
:param volume: the volume of the book
:type volume: string
:param title: the title of the book
:type title: string
"""
book_series = {}
if title is not None:
book_series['title'] = title
... |
Add inspire categories.
:param subject_terms: user categories for the current document.
:type subject_terms: list
:param source: source for the given categories.
:type source: string | def add_inspire_categories(self, subject_terms, source=None):
"""Add inspire categories.
:param subject_terms: user categories for the current document.
:type subject_terms: list
:param source: source for the given categories.
:type source: string
"""
for catego... |
Add a keyword.
Args:
keyword(str): keyword to add.
schema(str): schema to which the keyword belongs.
source(str): source for the keyword. | def add_keyword(self, keyword, schema=None, source=None):
"""Add a keyword.
Args:
keyword(str): keyword to add.
schema(str): schema to which the keyword belongs.
source(str): source for the keyword.
"""
keyword_dict = self._sourced_dict(source, value=... |
Add private notes.
:param private_notes: hidden notes for the current document
:type private_notes: string
:param source: source for the given private notes
:type source: string | def add_private_note(self, private_notes, source=None):
"""Add private notes.
:param private_notes: hidden notes for the current document
:type private_notes: string
:param source: source for the given private notes
:type source: string
"""
self._append_to('_pri... |
Add publication info.
:param year: year of publication
:type year: integer
:param cnum: inspire conference number
:type cnum: string
:param artid: article id
:type artid: string
:param page_end: final page for the article
:type page_end: string
... | def add_publication_info(
self,
year=None,
cnum=None,
artid=None,
page_end=None,
page_start=None,
journal_issue=None,
journal_title=None,
journal_volume=None,
pubinfo_freetext=None,
material=None,
parent_record=None,
... |
Add thesis info.
:param defense_date: defense date for the current thesis
:type defense_date: string. A formatted date is required (yyyy-mm-dd)
:param degree_type: degree type for the current thesis
:type degree_type: string
:param institution: author's affiliation for the cur... | def add_thesis(
self,
defense_date=None,
degree_type=None,
institution=None,
date=None
):
"""Add thesis info.
:param defense_date: defense date for the current thesis
:type defense_date: string. A formatted date is required (yyyy-mm-dd)
:para... |
Add license.
:param url: url for the description of the license
:type url: string
:param license: license type
:type license: string
:param material: material type
:type material: string
:param imposing: imposing type
:type imposing: string | def add_license(
self,
url=None,
license=None,
material=None,
imposing=None
):
"""Add license.
:param url: url for the description of the license
:type url: string
:param license: license type
:type license: string
:param mat... |
Add public note.
:param public_note: public note for the current article.
:type public_note: string
:param source: source for the given notes.
:type source: string | def add_public_note(self, public_note, source=None):
"""Add public note.
:param public_note: public note for the current article.
:type public_note: string
:param source: source for the given notes.
:type source: string
"""
self._append_to('public_notes', self._... |
Add title.
:param title: title for the current document
:type title: string
:param subtitle: subtitle for the current document
:type subtitle: string
:param source: source for the given title
:type source: string | def add_title(self, title, subtitle=None, source=None):
"""Add title.
:param title: title for the current document
:type title: string
:param subtitle: subtitle for the current document
:type subtitle: string
:param source: source for the given title
:type sour... |
Add title translation.
:param title: translated title
:type title: string
:param language: language for the original title
:type language: string (2 characters ISO639-1)
:param source: source for the given title
:type source: string | def add_title_translation(self, title, language, source=None):
"""Add title translation.
:param title: translated title
:type title: string
:param language: language for the original title
:type language: string (2 characters ISO639-1)
:param source: source for the giv... |
Add report numbers.
:param report_number: report number for the current document
:type report_number: string
:param source: source for the given report number
:type source: string | def add_report_number(self, report_number, source=None):
"""Add report numbers.
:param report_number: report number for the current document
:type report_number: string
:param source: source for the given report number
:type source: string
"""
self._append_to('r... |
Add acquisition source.
:type submission_number: integer
:type email: integer
:type source: string
:param date: UTC date in isoformat
.. deprecated:: 30.1.0
Use ``datetime`` instead.
:type date: string
:param method: meth... | def add_acquisition_source(
self,
method,
date=None,
submission_number=None,
internal_uid=None,
email=None,
orcid=None,
source=None,
datetime=None,
):
"""Add acquisition source.
:type submission_number: integer
:type e... |
Add Copyright.
:type material: string
:type holder: string
:type statement: string
:type url: string
:type year: int | def add_copyright(
self,
material=None,
holder=None,
statement=None,
url=None,
year=None
):
"""Add Copyright.
:type material: string
:type holder: string
:type statement: string
:type url: string
:type year: int
... |
Add a figure.
Args:
key (string): document key
url (string): document url
Keyword Args:
caption (string): simple description
label (string):
material (string):
original_url (string): original url
filename (string): curr... | def add_figure(self, key, url, **kwargs):
"""Add a figure.
Args:
key (string): document key
url (string): document url
Keyword Args:
caption (string): simple description
label (string):
material (string):
original_url (stri... |
Adds document to record
Args:
key (string): document key
url (string): document url
Keyword Args:
description (string): simple description
fulltext (bool): mark if this is a full text
hidden (bool): is document should be hidden
mate... | def add_document(self, key, url, **kwargs):
"""
Adds document to record
Args:
key (string): document key
url (string): document url
Keyword Args:
description (string): simple description
fulltext (bool): mark if this is a full text
... |
Fit a rotation and a traslation between two sets points.
Fit a rotation matrix and a traslation bewtween two matched sets
consisting of M N-dimensional points
Parameters
----------
coords0 : (M, N) array_like
coords1 : (M, N) array_lke
Returns
-------
offset : (N, ) array_like
... | def fit_offset_and_rotation(coords0, coords1):
"""Fit a rotation and a traslation between two sets points.
Fit a rotation matrix and a traslation bewtween two matched sets
consisting of M N-dimensional points
Parameters
----------
coords0 : (M, N) array_like
coords1 : (M, N) array_lke
... |
Exporting eagle .brd file into 3D image file
using Eagle3D and povray.
GUI is not displayed if ``pyvirtualdisplay`` is installed.
If export is blocked somehow (e.g. popup window is displayed) then after timeout operation is canceled with exception.
Problem can be investigated by setting 'showgui' flag.
... | def export_image3d(input, output, size=(800, 600), pcb_rotate=(0, 0, 0), timeout=20, showgui=False):
'''
Exporting eagle .brd file into 3D image file
using Eagle3D and povray.
GUI is not displayed if ``pyvirtualdisplay`` is installed.
If export is blocked somehow (e.g. popup window is displayed) the... |
same as export_image3d, but there is no output file, PIL object is returned instead | def pil_image3d(input, size=(800, 600), pcb_rotate=(0, 0, 0), timeout=20, showgui=False):
'''
same as export_image3d, but there is no output file, PIL object is returned instead
'''
f = tempfile.NamedTemporaryFile(suffix='.png', prefix='eagexp_')
output = f.name
export_image3d(input, output=out... |
Returns the first coincidence... | def search_prod_type_tags(self, ins, type, tags, pipeline):
'''Returns the first coincidence...'''
return StoredProduct(id=100, content='null.fits', tags={}) |
Polynomial fit with display of residuals and additional work with R.
Parameters
----------
x : 1d numpy array, float
X coordinates of the data being fitted.
y : 1d numpy array, float
Y coordinates of the data being fitted.
deg : int
Degree of the fitting polynomial.
reje... | def polfit_residuals(
x, y, deg, reject=None,
color='b', size=75,
xlim=None, ylim=None,
xlabel=None, ylabel=None, title=None,
use_r=False,
geometry=(0,0,640,480),
debugplot=0):
"""Polynomial fit with display of residuals and additional work with R.
Parame... |
Polynomial fit with iterative rejection of points.
This function makes use of function polfit_residuals for display
purposes.
Parameters
----------
x : 1d numpy array, float
X coordinates of the data being fitted.
y : 1d numpy array, float
Y coordinates of the data being fitted... | def polfit_residuals_with_sigma_rejection(
x, y, deg, times_sigma_reject,
color='b', size=75,
xlim=None, ylim=None,
xlabel=None, ylabel=None, title=None,
use_r=None,
geometry=(0,0,640,480),
debugplot=0):
"""Polynomial fit with iterative rejection of points.
... |
Polynomial fit with iterative rejection of points.
This function makes use of function polfit_residuals for display
purposes.
Parameters
----------
x : 1d numpy array, float
X coordinates of the data being fitted.
y : 1d numpy array, float
Y coordinates of the data being fitted... | def polfit_residuals_with_cook_rejection(
x, y, deg, times_sigma_cook,
color='b', size=75,
xlim=None, ylim=None,
xlabel=None, ylabel=None, title=None,
use_r=None,
geometry=(0,0,640,480),
debugplot=0):
"""Polynomial fit with iterative rejection of points.
... |
Create a function that set the foreground color. | def _make_color_fn(color):
"""Create a function that set the foreground color."""
def _color(text = ""):
return (_color_sep + color + _color_sep2 + text +
_color_sep + "default" + _color_sep2)
return _color |
Log a text without adding the current time. | def just_log(*texts, sep = ""):
"""Log a text without adding the current time."""
if config.silent:
return
text = _color_sep + "default" + _color_sep2 + sep.join(texts)
array = text.split(_color_sep)
for part in array:
parts = part.split(_color_sep2, 1)
if len(parts) != 2 or not parts[1]:
continue
if... |
Log a text. | def log(*texts, sep = ""):
"""Log a text."""
text = sep.join(texts)
count = text.count("\n")
just_log("\n" * count, *get_time(), text.replace("\n", ""), sep=sep) |
Find files to include. | def find_files(globs):
"""Find files to include."""
last_cwd = os.getcwd()
os.chdir(config.cwd)
gex, gin = separate_globs(globs)
# Find excluded files
exclude = []
for glob in gex:
parse_glob(glob, exclude)
files = []
include = []
order = 0
# Find included files and removed excluded files
for glob in... |
Read some files and return a stream. | def src(globs, **options):
"""Read some files and return a stream."""
# Create an array of globs if only one string is given
if isinstance(globs, str):
globs = [ globs ]
# Find files
files = find_files(globs)
# Create a stream
stream = Stream()
# Options
options["cwd"] = config.cwd
if "base" in options... |
:return
D is declination (+ve east)
I is inclination (+ve down)
H is horizontal intensity
X is north component
Y is east component
Z is vertical component (+ve down)
F is total intensity | def igrf_value(lat, lon, alt=0., year=2005.):
"""
:return
D is declination (+ve east)
I is inclination (+ve down)
H is horizontal intensity
X is north component
Y is east component
Z is vertical component (+ve down)
F is total intensity
"""
... |
Annual variation
D is declination (+ve east)
I is inclination (+ve down)
H is horizontal intensity
X is north component
Y is east component
Z is vertical component (+ve down)
F is total intensity | def igrf_variation(lat, lon, alt=0., year=2005):
"""
Annual variation
D is declination (+ve east)
I is inclination (+ve down)
H is horizontal intensity
X is north component
Y is east component
Z is vertical component (+ve down)
F is total inten... |
Decorate function, adding a logger handler stored in FITS. | def log_to_history(logger, name):
"""Decorate function, adding a logger handler stored in FITS."""
def log_to_history_decorator(method):
def l2h_method(self, ri):
history_header = fits.Header()
fh = FITSHistoryHandler(history_header)
fh.setLevel(logging.INFO)
... |
Create metadata structure | def create_db_info():
"""Create metadata structure"""
result = {}
result['instrument'] = ''
result['uuid'] = ''
result['tags'] = {}
result['type'] = ''
result['mode'] = ''
result['observation_date'] = ""
result['origin'] = {}
return result |
Decorator for creating a task. | def task(obj = None, deps = None):
"""Decorator for creating a task."""
# The decorator is not used as a function
if callable(obj):
__task(obj.__name__, obj)
return obj
# The decorator is used as a function
def __decorated(func):
__task(obj if obj else obj.__name__, deps, func)
return func
return __deco... |
Read a single byte, or raise OSError on failure. | def _read_one_byte(self, fd):
"""Read a single byte, or raise OSError on failure."""
c = os.read(fd, 1)
if not c:
raise OSError
return c |
Auxiliary function to give an error if the file already exists.
Parameters
----------
parser : parser object
Instance of argparse.ArgumentParser()
arg : string
File name.
mode : string
Optional string that specifies the mode in which the file is
opened.
Returns
... | def arg_file_is_new(parser, arg, mode='w'):
"""Auxiliary function to give an error if the file already exists.
Parameters
----------
parser : parser object
Instance of argparse.ArgumentParser()
arg : string
File name.
mode : string
Optional string that specifies the mode... |
Compute intersection of spectrum trail with arc line.
Parameters
----------
spectrail : SpectrumTrail object
Instance of SpectrumTrail class.
arcline : ArcLine object
Instance of ArcLine class
Returns
-------
xroot, yroot : tuple of floats
(X,Y) coordinates of the i... | def intersection_spectrail_arcline(spectrail, arcline):
"""Compute intersection of spectrum trail with arc line.
Parameters
----------
spectrail : SpectrumTrail object
Instance of SpectrumTrail class.
arcline : ArcLine object
Instance of ArcLine class
Returns
-------
xr... |
Update the arc line from least squares fit to data.
Parameters
----------
x : 1d numpy array, float
X coordinates of the data being fitted.
y : 1d numpy array, float
Y coordinates of the data being fitted.
deg : int
Degree of the fitting polyn... | def fit(self, x, y, deg, w=None, y_vs_x=True,
times_sigma_reject=None, title=None, debugplot=0):
"""Update the arc line from least squares fit to data.
Parameters
----------
x : 1d numpy array, float
X coordinates of the data being fitted.
y : 1d numpy ar... |
Return x,y values evaluated with a given pixel step.
The returned values are computed within the corresponding
bounding box of the line.
Parameters
----------
start : float
Minimum pixel coordinate to evaluate the independent
variable.
stop : flo... | def linspace_pix(self, start=None, stop=None, pixel_step=1, y_vs_x=None):
"""Return x,y values evaluated with a given pixel step.
The returned values are computed within the corresponding
bounding box of the line.
Parameters
----------
start : float
Minimum ... |
Return a copy of self, shifted a constant offset.
Parameters
----------
offset_value : float
Number of pixels to shift the CCDLine. | def offset(self, offset_value):
"""Return a copy of self, shifted a constant offset.
Parameters
----------
offset_value : float
Number of pixels to shift the CCDLine.
"""
new_instance = deepcopy(self)
new_instance.poly_funct.coef[0] += offset_value
... |
Return x,y values evaluated with a given pixel step. | def linspace_pix(self, start=None, stop=None, pixel_step=1, y_vs_x=False):
"""Return x,y values evaluated with a given pixel step."""
return CCDLine.linspace_pix(self, start=start, stop=stop,
pixel_step=pixel_step, y_vs_x=y_vs_x) |
Return x,y values evaluated with a given pixel step. | def linspace_pix(self, start=None, stop=None, pixel_step=1, y_vs_x=True):
"""Return x,y values evaluated with a given pixel step."""
return CCDLine.linspace_pix(self, start=start, stop=stop,
pixel_step=pixel_step, y_vs_x=y_vs_x) |
Compute output = file1 operation file2.
Parameters
----------
file1 : file object
First FITS file.
file2 : file object
Second FITS file.
operation : string
Mathematical operation.
output : file object
Output FITS file.
display : string
Character strin... | def compute_operation(file1, file2, operation, output, display,
args_z1z2, args_bbox, args_keystitle, args_geometry):
"""Compute output = file1 operation file2.
Parameters
----------
file1 : file object
First FITS file.
file2 : file object
Second FITS file.
... |
Compute a robust estimator of the standard deviation
See Eq. 3.36 (page 84) in Statistics, Data Mining, and Machine
in Astronomy, by Ivezic, Connolly, VanderPlas & Gray
Parameters
----------
x : 1d numpy array, float
Array of input values which standard deviation is requested.
debug : ... | def robust_std(x, debug=False):
"""Compute a robust estimator of the standard deviation
See Eq. 3.36 (page 84) in Statistics, Data Mining, and Machine
in Astronomy, by Ivezic, Connolly, VanderPlas & Gray
Parameters
----------
x : 1d numpy array, float
Array of input values which standa... |
Run. | async def run(websession: ClientSession):
"""Run."""
try:
# Create a client:
client = Client(
'<API_KEY>',
39.7974509,
-104.8887227,
websession,
altitude=1609.3)
# Get current UV info:
print('CURRENT UV DATA:')
... |
Compute basic statistical parameters.
Parameters
----------
x : 1d numpy array, float
Input array with values which statistical properties are
requested.
rm_nan : bool
If True, filter out NaN values before computing statistics.
debug : bool
If True prints computed v... | def summary(x, rm_nan=False, debug=False):
"""Compute basic statistical parameters.
Parameters
----------
x : 1d numpy array, float
Input array with values which statistical properties are
requested.
rm_nan : bool
If True, filter out NaN values before computing statistics.
... |
Trace peak in array starting in (x,y).
Trace a peak feature in an array starting in position (x,y).
Parameters
----------
arr : array
A 2D array
x : float
x coordinate of the initial position
y : float
y coordinate of the initial position
axis : {0, 1}
S... | def trace(arr, x, y, axis=0, background=0.0,
step=4, hs=1, tol=2, maxdis=2.0, gauss=1):
'''Trace peak in array starting in (x,y).
Trace a peak feature in an array starting in position (x,y).
Parameters
----------
arr : array
A 2D array
x : float
x coordinate of the i... |
Fit a trace information table to a polynomial.
Parameters
----------
trace
A 2D array, 2 columns and n rows
deg : int
Degree of polynomial
axis : {0, 1}
Spatial axis of the array (0 is Y, 1 is X). | def fit_trace_polynomial(trace, deg, axis=0):
'''
Fit a trace information table to a polynomial.
Parameters
----------
trace
A 2D array, 2 columns and n rows
deg : int
Degree of polynomial
axis : {0, 1}
Spatial axis of the array (0 is Y, 1 is X).
'''
... |
Returns a list of FileInfo instances if filename is a TXT file.
Parameters
----------
filename : string
Name of a file (wildcards are acceptable) or a TXT file
containing a list of files. Empty Lines, and lines starting by
a hash or a at symbol in the TXT file are ignored.
... | def list_fileinfo_from_txt(filename):
"""Returns a list of FileInfo instances if filename is a TXT file.
Parameters
----------
filename : string
Name of a file (wildcards are acceptable) or a TXT file
containing a list of files. Empty Lines, and lines starting by
a hash or a... |
Return a humanized price | def price_humanized(value, inst, currency=None):
"""
Return a humanized price
"""
return (natural_number_with_currency(value, ugettext('CZK') if currency is None else currency) if value is not None
else ugettext('(None)')) |
Obtain a unique identifier of the image.
Parameters
----------
img : astropy.io.fits.HDUList
Returns
-------
str:
Identification of the image | def get_imgid(self, img):
"""Obtain a unique identifier of the image.
Parameters
----------
img : astropy.io.fits.HDUList
Returns
-------
str:
Identification of the image
"""
imgid = img.filename()
# More heuristics here...... |
Obtain DARKTIME | def get_darktime(self, img):
"""Obtain DARKTIME"""
header = self.get_header(img)
if 'DARKTIME' in header.keys():
return header['DARKTIME']
else:
return self.get_exptime(img) |
Obtain EXPTIME | def get_exptime(self, img):
"""Obtain EXPTIME"""
header = self.get_header(img)
if 'EXPTIME' in header.keys():
etime = header['EXPTIME']
elif 'EXPOSED' in header.keys():
etime = header['EXPOSED']
else:
etime = 1.0
return etime |
Obtain a summary of information about the image. | def gather_info(self, dframe):
"""Obtain a summary of information about the image."""
with dframe.open() as hdulist:
info = self.gather_info_hdu(hdulist)
return info |
Obtain a summary of information about the image. | def gather_info_hdu(self, hdulist):
"""Obtain a summary of information about the image."""
values = {}
values['n_ext'] = len(hdulist)
extnames = [hdu.header.get('extname', '') for hdu in hdulist[1:]]
values['name_ext'] = ['PRIMARY'] + extnames
fits_extractor = self.extra... |
Automatically generate an organized folder structure for a DFT
calculation.
Start by copying the script to a folder in your username
and assign the right information to the arguments in the function.
You can change the parameters and run the script several times if you,
for example, are using diff... | def main(
title,
authors,
year,
email,
journal='',
volume='',
number='',
pages='',
publisher='',
doi='',
tags=[],
DFT_code='Quantum ESPRESSO',
DFT_functionals=['BEEF-vdW'],
reactions=[
{'reactants... |
Log that the task has started. | def log_starting(self):
"""Log that the task has started."""
self.start_time = time.perf_counter()
logger.log("Starting '", logger.cyan(self.name), "'...") |
Log that this task is done. | def log_finished(self):
"""Log that this task is done."""
delta = time.perf_counter() - self.start_time
logger.log("Finished '", logger.cyan(self.name),
"' after ", logger.magenta(time_to_text(delta))) |
Call the function attached to the task. | def call_task_fn(self):
"""Call the function attached to the task."""
if not self.fn:
return self.log_finished()
future = asyncio.Future()
future.add_done_callback(lambda x: self.log_finished())
if inspect.iscoroutinefunction(self.fn):
f = asyncio.ensure_future(self.fn())
f.add_done_callback(lambda... |
Bind a 'TaskEndTransformer' to a stream. | def bind_end(self, stream, future):
"""Bind a 'TaskEndTransformer' to a stream."""
if not isinstance(stream, Stream):
future.set_result(None)
else:
stream.pipe(TaskEndTransformer(future)) |
Start running dependencies. | async def start_deps(self, deps):
"""Start running dependencies."""
# Get only new dependencies
deps = list(filter(lambda dep: dep not in self.called, deps))
self.called += deps
# Start only existing dependencies
runners = list(filter(lambda x: x and x.future, map(lambda dep: pylp.start(dep), deps)))
if... |
Create a set from an iterable of members. | def frommembers(cls, members=()):
"""Create a set from an iterable of members."""
return cls.fromint(sum(map(cls._map.__getitem__, set(members)))) |
Create a set from an iterable of boolean evaluable items. | def frombools(cls, bools=()):
"""Create a set from an iterable of boolean evaluable items."""
return cls.fromint(sum(compress(cls._atoms, bools))) |
Create a set from binary string. | def frombits(cls, bits='0'):
"""Create a set from binary string."""
if len(bits) > cls._len:
raise ValueError('too many bits %r' % (bits,))
return cls.fromint(bits[::-1], 2) |
Return the set members tuple/frozenset. | def members(self, as_set=False):
"""Return the set members tuple/frozenset."""
if as_set:
return frozenset(map(self._members.__getitem__, self._indexes()))
return tuple(map(self._members.__getitem__, self._indexes())) |
Yield the singleton for every set member. | def atoms(self, reverse=False):
"""Yield the singleton for every set member."""
if reverse:
return filter(self.__and__, reversed(self._atoms))
return filter(self.__and__, self._atoms) |
Yield the singleton for every non-member. | def inatoms(self, reverse=False):
"""Yield the singleton for every non-member."""
if reverse:
return filterfalse(self.__and__, reversed(self._atoms))
return filterfalse(self.__and__, self._atoms) |
Yield combinations from start to self in short lexicographic order. | def powerset(self, start=None, excludestart=False):
"""Yield combinations from start to self in short lexicographic order."""
if start is None:
start = self.infimum
other = self.atoms()
else:
if self | start != self:
raise ValueError('%r is no ... |
Returns the number of present/absent members. | def count(self, value=True):
"""Returns the number of present/absent members."""
if value not in (True, False):
raise ValueError('can only count True or False, not %r' % (value,))
return bin(self)[2:].count('01'[value]) |
Changes a given `changed_fields` on object, saves it and returns changed object. | def change_and_save(obj, update_only_changed_fields=False, save_kwargs=None, **changed_fields):
"""
Changes a given `changed_fields` on object, saves it and returns changed object.
"""
from chamber.models import SmartModel
change(obj, **changed_fields)
if update_only_changed_fields and not isin... |
Changes a given `changed_fields` on object and returns changed object. | def change(obj, **changed_fields):
"""
Changes a given `changed_fields` on object and returns changed object.
"""
obj_field_names = {
field.name for field in obj._meta.fields
} | {
field.attname for field in obj._meta.fields
} | {'pk'}
for field_name, value in changed_fields... |
Changes a given `changed_fields` on each object in a given `iterable`, saves objects
and returns the changed objects. | def bulk_change_and_save(iterable, update_only_changed_fields=False, save_kwargs=None, **changed_fields):
"""
Changes a given `changed_fields` on each object in a given `iterable`, saves objects
and returns the changed objects.
"""
return [
change_and_save(obj, update_only_changed_fields=upd... |
Integrate a Gaussian profile. | def gauss_box_model(x, amplitude=1.0, mean=0.0, stddev=1.0, hpix=0.5):
"""Integrate a Gaussian profile."""
z = (x - mean) / stddev
z2 = z + hpix / stddev
z1 = z - hpix / stddev
return amplitude * (norm.cdf(z2) - norm.cdf(z1)) |
Derivative of the integral of a Gaussian profile. | def gauss_box_model_deriv(x, amplitude=1.0, mean=0.0, stddev=1.0, hpix=0.5):
"""Derivative of the integral of a Gaussian profile."""
z = (x - mean) / stddev
z2 = z + hpix / stddev
z1 = z - hpix / stddev
da = norm.cdf(z2) - norm.cdf(z1)
fp2 = norm_pdf_t(z2)
fp1 = norm_pdf_t(z1)
dl = -... |
Find peaks in array.
The algorithm imposes that the signal at both sides of the peak
decreases monotonically.
Parameters
----------
sx : 1d numpy array, floats
Input array.
nwinwidth : int
Width of the window where each peak must be found.
threshold : float
Minimum ... | def find_peaks_spectrum(sx, nwinwidth, threshold=0, debugplot=0):
"""Find peaks in array.
The algorithm imposes that the signal at both sides of the peak
decreases monotonically.
Parameters
----------
sx : 1d numpy array, floats
Input array.
nwinwidth : int
Width of the win... |
Refine line peaks in spectrum.
Parameters
----------
sx : 1d numpy array, floats
Input array.
ixpeaks : 1d numpy array, int
Initial peak locations, in array coordinates (integers).
These values can be the output from the function
find_peaks_spectrum().
nwinwidth : in... | def refine_peaks_spectrum(sx, ixpeaks, nwinwidth, method=None,
geometry=None, debugplot=0):
"""Refine line peaks in spectrum.
Parameters
----------
sx : 1d numpy array, floats
Input array.
ixpeaks : 1d numpy array, int
Initial peak locations, in array coord... |
Make a path more "readable | def make_readable_path(path):
"""Make a path more "readable"""
home = os.path.expanduser("~")
if path.startswith(home):
path = "~" + path[len(home):]
return path |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.