INSTRUCTION stringlengths 1 46.3k | RESPONSE stringlengths 75 80.2k |
|---|---|
Filter spectrum in Fourier space and apply cosine bell.
Parameters
----------
sp : numpy array
Spectrum to be filtered and masked.
fmin : float
Minimum frequency to be employed.
fmax : float
Maximum frequency to be employed.
debugplot : int
Debugging level for me... | def filtmask(sp, fmin=0.02, fmax=0.15, debugplot=0):
"""Filter spectrum in Fourier space and apply cosine bell.
Parameters
----------
sp : numpy array
Spectrum to be filtered and masked.
fmin : float
Minimum frequency to be employed.
fmax : float
Maximum frequency to be ... |
Return a cosine bell spanning n pixels, masking a fraction of pixels
Parameters
----------
n : int
Number of pixels.
fraction : float
Length fraction over which the data will be masked. | def cosinebell(n, fraction):
"""Return a cosine bell spanning n pixels, masking a fraction of pixels
Parameters
----------
n : int
Number of pixels.
fraction : float
Length fraction over which the data will be masked.
"""
mask = np.ones(n)
nmasked = int(fraction * n)
... |
Convolve a set of lines of known wavelengths and flux.
Parameters
----------
lines_wave : array like
Input array with wavelengths
lines_flux : array like
Input array with fluxes
sigma : float
Sigma of the broadening gaussian to be applied.
crpix1 : float
CRPIX1 o... | def convolve_comb_lines(lines_wave, lines_flux, sigma,
crpix1, crval1, cdelt1, naxis1):
"""Convolve a set of lines of known wavelengths and flux.
Parameters
----------
lines_wave : array like
Input array with wavelengths
lines_flux : array like
Input array wi... |
Periodic correlation between two spectra, implemented using FFT.
Parameters
----------
sp_reference : numpy array
Reference spectrum.
sp_offset : numpy array
Spectrum which offset is going to be measured relative to the
reference spectrum.
fminmax : tuple of floats or None
... | def periodic_corr1d(sp_reference, sp_offset,
fminmax=None,
naround_zero=None,
norm_spectra=False,
plottitle=None,
pdf=None,
debugplot=0):
"""Periodic correlation between two spectra, implemented u... |
Compute broadening to match 'sp_obj' with 'sp_ref'.
The reference spectrum 'sp_ref' should have a better spectral
resolution than the object spectrum 'sp_obj'.
It is assumed that the wavelength arrays are provided in
ascending order.
The wavelength sampling 'wv_ref' and 'wv_ref' can be different.... | def compute_broadening(wv_obj, sp_obj, wv_ref, sp_ref,
sigmalist, fpixminmax=None, naround_zero=None,
ax1=None, ax2=None,
debugplot=0):
"""Compute broadening to match 'sp_obj' with 'sp_ref'.
The reference spectrum 'sp_ref' should have a bette... |
Extract author names out of refextract authors output. | def _split_refextract_authors_str(authors_str):
"""Extract author names out of refextract authors output."""
author_seq = (x.strip() for x in RE_SPLIT_AUTH.split(authors_str) if x)
res = []
current = ''
for author in author_seq:
if not isinstance(author, six.text_type):
author =... |
Put a value in the publication info of the reference. | def _set_publication_info_field(self, field_name, value):
"""Put a value in the publication info of the reference."""
self._ensure_reference_field('publication_info', {})
self.obj['reference']['publication_info'][field_name] = value |
Parse pubnote and populate correct fields. | def set_pubnote(self, pubnote):
"""Parse pubnote and populate correct fields."""
if 'publication_info' in self.obj.get('reference', {}):
self.add_misc(u'Additional pubnote: {}'.format(pubnote))
return
if self.RE_VALID_PUBNOTE.match(pubnote):
pubnote = split_p... |
Add unique identifier in correct field.
The ``skip_handle`` flag is used when adding a uid through the add_url function
since urls can be easily confused with handle elements. | def _add_uid(self, uid, skip_handle=False):
"""Add unique identifier in correct field.
The ``skip_handle`` flag is used when adding a uid through the add_url function
since urls can be easily confused with handle elements.
"""
# We might add None values from wherever. Kill them ... |
Add artid, start, end pages to publication info of a reference.
Args:
page_start(Optional[string]): value for the field page_start
page_end(Optional[string]): value for the field page_end
artid(Optional[string]): value for the field artid
Raises:
ValueEr... | def set_page_artid(self, page_start=None, page_end=None, artid=None):
"""Add artid, start, end pages to publication info of a reference.
Args:
page_start(Optional[string]): value for the field page_start
page_end(Optional[string]): value for the field page_end
artid(... |
Separate include and exclude globs. | def separate_globs(globs):
"""Separate include and exclude globs."""
exclude = []
include = []
for path in globs:
if path.startswith("!"):
exclude.append(path[1:])
else:
include.append(path)
return (exclude, include) |
Parse a glob. | def parse_glob(path, included):
"""Parse a glob."""
files = glob.glob(path, recursive=True)
array = []
for file in files:
file = os.path.abspath(file)
if file not in included:
array.append(file)
included += array
return array |
Find the base of a glob. | def find_base(path):
"""Find the base of a glob."""
result = _pattern.match(path)
if result:
base = result.group(0)
else:
base = "./"
if base.endswith('/') or base.endswith('\\'):
return os.path.abspath(base)
else:
return os.path.dirname(os.path.abspath(base)) |
Compute wavelengths from channels.
The wavelength calibration is provided through the usual parameters
CRPIX1, CRVAL1 and CDELT1.
Parameters
----------
xchannel : numpy array
Input channels where the wavelengths will be evaluated.
crpix1: float
CRPIX1 keyword.
crval1: float... | def fun_wv(xchannel, crpix1, crval1, cdelt1):
"""Compute wavelengths from channels.
The wavelength calibration is provided through the usual parameters
CRPIX1, CRVAL1 and CDELT1.
Parameters
----------
xchannel : numpy array
Input channels where the wavelengths will be evaluated.
cr... |
Check wavelength calibration of the provided spectrum.
Parameters
----------
sp : numpy array
Wavelength calibrated spectrum.
crpix1: float
CRPIX1 keyword.
crval1: float
CRVAL1 keyword.
cdelt1: float
CDELT1 keyword.
wv_master: numpy array
Array with t... | def check_wlcalib_sp(sp, crpix1, crval1, cdelt1, wv_master,
coeff_ini=None, naxis1_ini=None,
min_nlines_to_refine=0,
interactive=False,
threshold=0,
nwinwidth_initial=7,
nwinwidth_refined=5,
... |
Update wavelength calibration polynomial using the residuals fit.
The idea is to repeat the original fit using the information
previously computed with the function check_wlcalib_sp() in this
module.
Parameters
----------
coeff_ini : array like (floats)
Coefficients corresponding to th... | def update_poly_wlcalib(coeff_ini, coeff_residuals, naxis1_ini, debugplot):
"""Update wavelength calibration polynomial using the residuals fit.
The idea is to repeat the original fit using the information
previously computed with the function check_wlcalib_sp() in this
module.
Parameters
----... |
Add documentation to generated classes | def generate_docs(klass):
"""Add documentation to generated classes"""
import numina.types.datatype
attrh = ('Attributes\n'
'----------\n')
doc = getattr(klass, '__doc__', None)
if doc is None or doc == '':
doc = "%s documentation." % klass.__name__
if len(klass.stored()... |
Extract metadata from serialized file | def extract_db_info(self, obj, keys):
"""Extract metadata from serialized file"""
result = {}
if isinstance(obj, dict):
try:
qc = obj['quality_control']
except KeyError:
qc = QC.UNKNOWN
elif isinstance(obj, DataFrame):
w... |
Integer with reversed and inverted bits of n assuming bit length r.
>>> reinverted(1, 6)
31
>>> [reinverted(x, 6) for x in [7, 11, 13, 14, 19, 21, 22, 25, 26, 28]]
[7, 11, 19, 35, 13, 21, 37, 25, 41, 49] | def reinverted(n, r):
"""Integer with reversed and inverted bits of n assuming bit length r.
>>> reinverted(1, 6)
31
>>> [reinverted(x, 6) for x in [7, 11, 13, 14, 19, 21, 22, 25, 26, 28]]
[7, 11, 19, 35, 13, 21, 37, 25, 41, 49]
"""
result = 0
r = 1 << (r - 1)
while n:
if n... |
Rank items from sequence in colexicographical order.
>>> [rank(i) for i in ('', 'a', 'b', 'ab', 'c')]
[0, 1, 2, 3, 4]
>>> rank('spam')
299009 | def rank(items, sequence=string.ascii_lowercase):
"""Rank items from sequence in colexicographical order.
>>> [rank(i) for i in ('', 'a', 'b', 'ab', 'c')]
[0, 1, 2, 3, 4]
>>> rank('spam')
299009
"""
items = set(items)
return sum(1 << i for i, s in enumerate(sequence) if s in items) |
Unrank n from sequence in colexicographical order.
>>> [''.join(unrank(i)) for i in range(8)]
['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
>>> unrank(299009)
['a', 'm', 'p', 's'] | def unrank(n, sequence=string.ascii_lowercase):
"""Unrank n from sequence in colexicographical order.
>>> [''.join(unrank(i)) for i in range(8)]
['', 'a', 'b', 'ab', 'c', 'ac', 'bc', 'abc']
>>> unrank(299009)
['a', 'm', 'p', 's']
"""
return list(map(sequence.__getitem__, indexes(n))) |
Estimate the background in a 2D array | def background_estimator(bdata):
"""Estimate the background in a 2D array"""
crowded = False
std = numpy.std(bdata)
std0 = std
mean = bdata.mean()
while True:
prep = len(bdata)
numpy.clip(bdata, mean - 3 * std, mean + 3 * std, out=bdata)
if prep == len(bdata):
... |
Create a background map with a given mesh size | def create_background_map(data, bsx, bsy):
"""Create a background map with a given mesh size"""
sx, sy = data.shape
mx = sx // bsx
my = sy // bsy
comp = []
rms = []
# Rows
sp = numpy.split(data, numpy.arange(bsx, sx, bsx), axis=0)
for s in sp:
# Columns
rp = numpy.spl... |
Return the list of column queries read from the given JSON file.
:param f: path to the file to read
:type f: string
:rtype: list of dicts | def _read_columns_file(f):
"""Return the list of column queries read from the given JSON file.
:param f: path to the file to read
:type f: string
:rtype: list of dicts
"""
try:
columns = json.loads(open(f, 'r').read(),
object_pairs_hook=collections.Ordered... |
Write the given table (list of dicts) to the given file as CSV.
Writes UTF8-encoded, CSV-formatted text.
``f`` could be an opened file, sys.stdout, or a StringIO. | def _write_csv(f, table_):
"""Write the given table (list of dicts) to the given file as CSV.
Writes UTF8-encoded, CSV-formatted text.
``f`` could be an opened file, sys.stdout, or a StringIO.
"""
fieldnames = table_[0].keys()
set_fieldname = set(table_[0].keys())
# go through all the fie... |
Return the given table converted to a CSV string.
:param table: the table to convert
:type table: list of OrderedDicts each with the same keys in the same
order
:rtype: UTF8-encoded, CSV-formatted string | def _table_to_csv(table_):
"""Return the given table converted to a CSV string.
:param table: the table to convert
:type table: list of OrderedDicts each with the same keys in the same
order
:rtype: UTF8-encoded, CSV-formatted string
"""
f = cStringIO.StringIO()
try:
_writ... |
Query a list of dicts with a list of queries and return a table.
A "table" is a list of OrderedDicts each having the same keys in the same
order.
:param dicts: the list of input dicts
:type dicts: list of dicts
:param columns: the list of column query dicts, or the path to a JSON file
con... | def table(dicts, columns, csv=False, pretty=False):
"""Query a list of dicts with a list of queries and return a table.
A "table" is a list of OrderedDicts each having the same keys in the same
order.
:param dicts: the list of input dicts
:type dicts: list of dicts
:param columns: the list of... |
Query the given dict with the given pattern path and return the result.
The ``pattern_path`` is a either a single regular expression string or a
list of regex strings that will be matched against the keys of the dict and
its subdicts to find the value(s) in the dict to return.
The returned result is e... | def query(pattern_path, dict_, max_length=None, strip=False,
case_sensitive=False, unique=False, deduplicate=False,
string_transformations=None, hyperlink=False,
return_multiple_columns=False):
"""Query the given dict with the given pattern path and return the result.
The ``patter... |
Observing mode processing mode of numina. | def run_reduce(datastore, obsid, copy_files=True):
"""Observing mode processing mode of numina."""
request = 'reduce'
request_params = {}
rb = ReductionBlock()
rb.id = obsid
request_params['oblock_id'] = rb.id
request_params["pipeline"] = rb.pipeline
request_params["instrument_configu... |
Get reactions from server
Give key value strings as arguments | def get_reactions(columns='all', n_results=20, write_db=False, **kwargs):
"""
Get reactions from server
Give key value strings as arguments
"""
if write_db or columns == 'all':
columns = all_columns['reactions']
queries = {}
for key, value in kwargs.items():
key = map_column... |
Redirect Recipe log messages to a file. | def create_recipe_file_logger(logger, logfile, logformat):
"""Redirect Recipe log messages to a file."""
recipe_formatter = logging.Formatter(logformat)
fh = logging.FileHandler(logfile, mode='w')
fh.setLevel(logging.DEBUG)
fh.setFormatter(recipe_formatter)
return fh |
Recipe execution mode of numina. | def run_recipe(recipe, task, rinput, workenv, logger_control):
"""Recipe execution mode of numina."""
# Creating custom logger file
recipe_logger = logging.getLogger(logger_control['default'])
if logger_control['enabled']:
logfile = os.path.join(workenv.resultsdir, logger_control['logfile'])
... |
Run the recipe and count the time it takes. | def run_recipe_timed(task, recipe, rinput):
"""Run the recipe and count the time it takes."""
_logger.info('running recipe')
now1 = datetime.datetime.now()
task.state = 1
task.time_start = now1
#
result = recipe(rinput)
_logger.info('result: %r', result)
task.result = result
#
... |
This takes some input (int, string, list, iterable, whatever) and
makes sure it is an iterable, making it a single item list if not.
Importantly, it does rational things with strings.
You can pass it more than one item. Cast is optional.
def foo(offsets=10):
offsets = iterit(offsets, cast=int)... | def iterit(*args, **kwargs):
"""
This takes some input (int, string, list, iterable, whatever) and
makes sure it is an iterable, making it a single item list if not.
Importantly, it does rational things with strings.
You can pass it more than one item. Cast is optional.
def foo(offsets=10):
... |
Stops the last db_session | def stop_db_session(exc=None):
"""Stops the last db_session"""
# print('==> Stop session', type(exc))
if has_db_session():
exc_type = None
tb = None
if exc:
exc_type, exc, tb = get_exc_info(exc)
db_session.__exit__(exc_type, exc, tb) |
Get the writing path of a file. | def get_path(dest, file, cwd = None):
"""Get the writing path of a file."""
if callable(dest):
return dest(file)
if not cwd:
cwd = file.cwd
if not os.path.isabs(dest):
dest = os.path.join(cwd, dest)
relative = os.path.relpath(file.path, file.base)
return os.path.join(dest, relative) |
Write contents to a local file. | def write_file(path, contents):
"""Write contents to a local file."""
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w") as file:
file.write(contents) |
Function called when a file need to be transformed. | async def transform(self, file):
"""Function called when a file need to be transformed."""
path = get_path(self.dest, file)
await self.loop.run_in_executor(self.exe, write_file, path, file.contents)
return file |
construct publication id | def get_pub_id(title, authors, year):
"construct publication id"
if len(title.split(' ')) > 1 \
and title.split(' ')[0].lower() in ['the', 'a']:
_first_word = title.split(' ')[1].split('_')[0]
else:
_first_word = title.split(' ')[0].split('_')[0]
pub_id = authors[0].split(',')[0]... |
Return a string with all atoms in molecule | def extract_atoms(molecule):
"""Return a string with all atoms in molecule"""
if molecule == '':
return molecule
try:
return float(molecule)
except BaseException:
pass
atoms = ''
if not molecule[0].isalpha():
i = 0
while not molecule[i].isalpha():
... |
Check the stoichiometry and format of chemical reaction used for
folder structure.
list of reactants -> list of products | def check_reaction(reactants, products):
"""Check the stoichiometry and format of chemical reaction used for
folder structure.
list of reactants -> list of products
"""
reactant_list = [reactant.split('@')[0].strip(
'star').strip('gas') for reactant in reactants]
product_list = [product.... |
Validate keys in a section | def check_section(node, section, keys=None):
"""Validate keys in a section"""
if keys:
for key in keys:
if key not in node:
raise ValueError('Missing key %r inside %r node' % (key, section)) |
Load the DRPS from a resource file. | def drp_load(package, resource, confclass=None):
"""Load the DRPS from a resource file."""
data = pkgutil.get_data(package, resource)
return drp_load_data(package, data, confclass=confclass) |
Load the DRPS from data. | def drp_load_data(package, data, confclass=None):
"""Load the DRPS from data."""
drpdict = yaml.safe_load(data)
ins = load_instrument(package, drpdict, confclass=confclass)
if ins.version == 'undefined':
pkg = importlib.import_module(package)
ins.version = getattr(pkg, '__version__', 'un... |
Load all observing modes | def load_modes(node):
"""Load all observing modes"""
if isinstance(node, list):
values = [load_mode(child) for child in node]
keys = [mode.key for mode in values]
return dict(zip(keys,values))
elif isinstance(node, dict):
values = {key: load_mode(child) for key, child in node... |
Load one observing mdode | def load_mode(node):
"""Load one observing mdode"""
obs_mode = ObservingMode()
obs_mode.__dict__.update(node)
# handle validator
load_mode_validator(obs_mode, node)
# handle builder
load_mode_builder(obs_mode, node)
# handle tagger:
load_mode_tagger(obs_mode, node)
return obs... |
Load observing mode OB tagger | def load_mode_tagger(obs_mode, node):
"""Load observing mode OB tagger"""
# handle tagger:
ntagger = node.get('tagger')
if ntagger is None:
pass
elif isinstance(ntagger, list):
def full_tagger(obsres):
return get_tags_from_full_ob(obsres, reqtags=ntagger)
obs_... |
Load observing mode OB builder | def load_mode_builder(obs_mode, node):
"""Load observing mode OB builder"""
# Check 'builder' and 'builder_options'
nval1 = node.get('builder')
if nval1 is not None:
if isinstance(nval1, str):
# override method
newmethod = import_object(nval1)
obs_mode.build... |
Load observing mode validator | def load_mode_validator(obs_mode, node):
"""Load observing mode validator"""
nval = node.get('validator')
if nval is None:
pass
elif isinstance(nval, str):
# load function
obs_mode.validator = import_object(nval)
else:
raise TypeError('validator must be None or a st... |
Sorts the columns for an entire ``ndarrray`` according to sorting
one of them.
:param array: Array to sort.
:type array: ndarray
:param col: Master column to sort.
:type col: int
:param order_back: If True, also returns the index to undo the
new order.
:type order_back:... | def sort_numpy(array, col=0, order_back=False):
"""
Sorts the columns for an entire ``ndarrray`` according to sorting
one of them.
:param array: Array to sort.
:type array: ndarray
:param col: Master column to sort.
:type col: int
:param order_back: If True, also returns th... |
Returns ``np.arange`` in a column form.
:param n: Length of the array.
:type n: int
:param dtype: Type of the array.
:type dtype: type
:returns: ``np.arange`` in a column form.
:rtype: ndarray | def arange_col(n, dtype=int):
"""
Returns ``np.arange`` in a column form.
:param n: Length of the array.
:type n: int
:param dtype: Type of the array.
:type dtype: type
:returns: ``np.arange`` in a column form.
:rtype: ndarray
"""
return np.reshape(np.arange(n, dt... |
Returns a numpy boolean array with Trues in the input index
positions.
:param index: index array with the Trues positions.
:type index: ndarray (type=int)
:param length: Length of the returned array.
:type length: int or None
:returns: array with Trues in the input index positions.
... | def index2bool(index, length=None):
"""
Returns a numpy boolean array with Trues in the input index
positions.
:param index: index array with the Trues positions.
:type index: ndarray (type=int)
:param length: Length of the returned array.
:type length: int or None
:return... |
Generates a basic 3D visualization.
:param color: Polygons color.
:type color: matplotlib color, 'default' or 't' (transparent)
:param ret: If True, returns the figure. It can be used to add
more elements to the plot or to modify it.
:type ret: bool
:param ... | def plot(self, color='default', ret=False, ax=None):
"""
Generates a basic 3D visualization.
:param color: Polygons color.
:type color: matplotlib color, 'default' or 't' (transparent)
:param ret: If True, returns the figure. It can be used to add
more elem... |
Centers and keep the aspect ratio in a 3D representation.
Created to help higher classes to manage cascade representation
of multiple lower objects.
:param ax: Axes to apply the method.
:type ax: mplot3d.Axes3D
:returns: None | def center_plot(self, ax):
"""
Centers and keep the aspect ratio in a 3D representation.
Created to help higher classes to manage cascade representation
of multiple lower objects.
:param ax: Axes to apply the method.
:type ax: mplot3d.Axes3D
... |
Precomputes some parameters to run faster specific methods like
Surface.classify.
Stores ``self.domain`` and ``self.path``, both very used in
the shadows simulation, in order to avoid later unnecessary
calculations and verifications.
:returns: None
... | def lock(self):
"""
Precomputes some parameters to run faster specific methods like
Surface.classify.
Stores ``self.domain`` and ``self.path``, both very used in
the shadows simulation, in order to avoid later unnecessary
calculations and verifications.
... |
Static method. Returns True if the polygon is convex regardless
of whether its vertices follow a clockwise or a
counter-clockwise order. This is a requirement for the rest of
the program.
:param points: Points intented to form a polygon.
:type points: ndarray wi... | def is_convex(points):
"""
Static method. Returns True if the polygon is convex regardless
of whether its vertices follow a clockwise or a
counter-clockwise order. This is a requirement for the rest of
the program.
:param points: Points intented to form... |
Static method. Returns a counterclock wise ordered sequence of
points. If there are any repeated point, the method will raise
an error.
Due to the 3D character of the package, the order or the points
will be tried following this order:
1. z=0 pprojection
... | def make_ccw(points):
"""
Static method. Returns a counterclock wise ordered sequence of
points. If there are any repeated point, the method will raise
an error.
Due to the 3D character of the package, the order or the points
will be tried following this... |
Generates the real 2D polygon of the 3D polygon. This method
performs a change of reference system obtaining the same polygon
but with the new z=0 plane containing the polygon.
This library mostly uses the z=0 projection to perform
operations with the polygons. For this reason, if rea... | def to_2d(self):
"""
Generates the real 2D polygon of the 3D polygon. This method
performs a change of reference system obtaining the same polygon
but with the new z=0 plane containing the polygon.
This library mostly uses the z=0 projection to perform
operations wit... |
Point-in-Polygon algorithm for multiple points for the z=0
projection of the ``pyny.Polygon``.
:param points: Set of points to evaluate.
:type points: ndarray with points (xyz or xy) in rows
:param edge: If True, consider the points in the Polygon's edge
as in... | def contains(self, points, edge=True):
"""
Point-in-Polygon algorithm for multiple points for the z=0
projection of the ``pyny.Polygon``.
:param points: Set of points to evaluate.
:type points: ndarray with points (xyz or xy) in rows
:param edge: If True,... |
Calculates the parametric equation of the plane that contains
the polygon. The output has the form np.array([a, b, c, d])
for:
.. math::
a*x + b*y + c*z + d = 0
:param check: Checks whether the points are actually
in the same plane with certain... | def get_parametric(self, check=True, tolerance=0.001):
"""
Calculates the parametric equation of the plane that contains
the polygon. The output has the form np.array([a, b, c, d])
for:
.. math::
a*x + b*y + c*z + d = 0
:param check: Check... |
:returns: matplotlib.path.Path object for the z=0 projection of
this polygon. | def get_path(self):
"""
:returns: matplotlib.path.Path object for the z=0 projection of
this polygon.
"""
if self.path == None:
from matplotlib import path
return path.Path(self.points[:, :2]) # z=0 projection!
return self.path |
:returns: shapely.Polygon object of the z=0 projection of
this polygon. | def get_shapely(self):
"""
:returns: shapely.Polygon object of the z=0 projection of
this polygon.
"""
if self.shapely == None:
from shapely.geometry import Polygon as shPolygon
self.shapely = shPolygon(self.points[:, :2]) # z=0 projection!
... |
: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])
"""
if self.domain is None:
return np.array([self.points.min(axis=0),
self.points.max(axis=0)]... |
:returns: The area of the polygon. | def get_area(self):
"""
:returns: The area of the polygon.
"""
if self.area is None:
self.area = self.to_2d().get_shapely().area
return self.area |
Given a set of points, it computes the z value for the
parametric equation of the plane where the polygon belongs.
Only the two first columns of the points will be taken into
account as x and y.
By default, the points outside the object will have a NaN value
... | def get_height(self, points, only_in = True, edge=True, full=False):
"""
Given a set of points, it computes the z value for the
parametric equation of the plane where the polygon belongs.
Only the two first columns of the points will be taken into
account as x and y.
... |
:returns: matplotlib Poly3DCollection
:rtype: mpl_toolkits.mplot3d | def get_plotable3d(self):
"""
:returns: matplotlib Poly3DCollection
:rtype: mpl_toolkits.mplot3d
"""
import mpl_toolkits.mplot3d as mplot3d
return [mplot3d.art3d.Poly3DCollection([self.points])] |
Point-in-Polygon for the z=0 projection. This function enhances
the performance of ``Polygon.contains()`` by verifying only the
points which are inside the bounding box of the polygon. To do
it fast, it needs the points array to be already sorted by one
column.
:... | def pip(self, points, sorted_col=0, radius=0):
"""
Point-in-Polygon for the z=0 projection. This function enhances
the performance of ``Polygon.contains()`` by verifying only the
points which are inside the bounding box of the polygon. To do
it fast, it needs the points ar... |
Generates a 2D plot for the z=0 Polygon projection.
:param color: Polygon color.
:type color: matplotlib color
:param alpha: Opacity.
:type alpha: float
:param ret: If True, returns the figure. It can be used to add
more elements to the plot or to mod... | def plot2d(self, color='default', alpha=1, ret=True):
"""
Generates a 2D plot for the z=0 Polygon projection.
:param color: Polygon color.
:type color: matplotlib color
:param alpha: Opacity.
:type alpha: float
:param ret: If True, returns the fig... |
Copy the ``pyny.Polygon`` 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)
:returns: list of ``pyny.Polygons`` | def matrix(self, x=(0, 0), y=(0, 0) , z=(0, 0)):
"""
Copy the ``pyny.Polygon`` 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)
:returns: list ... |
Calculates the belonging relationship between the polygons
in the Surface and a set of points.
This function enhances the performance of ``Polygon.contains()``
when used with multiple non-overlapping polygons (stored in a
Surface) by verifying only the points which are inside the z=0 ... | def classify(self, points, edge=True, col=1, already_sorted=False):
"""
Calculates the belonging relationship between the polygons
in the Surface and a set of points.
This function enhances the performance of ``Polygon.contains()``
when used with multiple non-overlapping... |
Calculates the intersection between the polygons in this surface
and other polygon, in the z=0 projection.
This method rely on the ``shapely.Polygon.intersects()`` method.
The way this method is used is intersecting this polygon
recursively with all identified polygons whi... | def intersect_with(self, polygon):
"""
Calculates the intersection between the polygons in this surface
and other polygon, in the z=0 projection.
This method rely on the ``shapely.Polygon.intersects()`` method.
The way this method is used is intersecting this polyg... |
:returns: opposite vertices of the bounding prism for this
object in the form of ndarray([min], [max])
.. note:: This method automatically stores the solution in order
to do not repeat calculations if the user needs to call it
more than once. | def get_domain(self):
"""
:returns: opposite vertices of the bounding prism for this
object in the form of ndarray([min], [max])
.. note:: This method automatically stores the solution in order
to do not repeat calculations if the user needs to call it
... |
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 | 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
"""
... |
Given a set of points, computes the z value for the parametric
equation of the Polygons in the Surface.
This method computes recursively the ``Polygon.get_height()``
method for all the Polygons in the Surface, obtaining the z
value for the points according to the local Pol... | def get_height(self, points, edge=True):
"""
Given a set of points, computes the z value for the parametric
equation of the Polygons in the Surface.
This method computes recursively the ``Polygon.get_height()``
method for all the Polygons in the Surface, obtaining ... |
Add holes to the holes list.
:param holes_list: Polygons that will be treated as holes.
:type holes_list: list or pyny.Polygon
:param make_ccw: If True, points will be sorted ccw.
:type make_ccw: bool
:returns: None
.. note:: The holes can be any... | def add_holes(self, holes_list, make_ccw=True):
"""
Add holes to the holes list.
:param holes_list: Polygons that will be treated as holes.
:type holes_list: list or pyny.Polygon
:param make_ccw: If True, points will be sorted ccw.
:type make_ccw: bool
... |
Find and merge groups of polygons in the surface that meet the
following criteria:
* Are coplanars.
* Are contiguous.
* The result is convex.
This method is very useful at reducing the number the items and,
therefore, the shadowi... | def melt(self, plot=False):
"""
Find and merge groups of polygons in the surface that meet the
following criteria:
* Are coplanars.
* Are contiguous.
* The result is convex.
This method is very useful at reducing the num... |
:returns: The area of the surface.
.. warning:: The area is computed as the sum of the areas of all
the polygons minus the sum of the areas of all the holes. | def get_area(self):
"""
:returns: The area of the surface.
.. warning:: The area is computed as the sum of the areas of all
the polygons minus the sum of the areas of all the holes.
"""
polys = sum([polygon.get_area() for polygon in self])
hol... |
Static method. Check whether a set of convex polygons are all
contiguous. Two polygons are considered contiguous if they
share, at least, one side (two vertices).
This is not a complete verification, it is a very simplified
one. For a given set of polygons this method will verify tha... | def contiguous(polygons):
"""
Static method. Check whether a set of convex polygons are all
contiguous. Two polygons are considered contiguous if they
share, at least, one side (two vertices).
This is not a complete verification, it is a very simplified
one. For a g... |
Generates a 2D plot for the z=0 Surface projection.
:param c_poly: Polygons color.
:type c_poly: matplotlib color
:param alpha: Opacity.
:type alpha: float
:param cmap: colormap
:type cmap: matplotlib.cm
:param ret: If True, returns the figure. It... | def plot2d(self, c_poly='default', alpha=1, cmap='default', ret=False,
title=' ', colorbar=False, cbar_label=''):
"""
Generates a 2D plot for the z=0 Surface projection.
:param c_poly: Polygons color.
:type c_poly: matplotlib color
:param alpha: Op... |
Improved plot that allows to plot polygons and holes in
different colors.
:param c_poly: Polygons color.
:type c_poly: matplotlib color, 'default' or 't' (transparent)
:param c_holes: Holes color.
:type c_holes: matplotlib color, 'default' or 't' (transparent)
... | def iplot(self, c_poly='default', c_holes='c', ret=False, ax=None):
"""
Improved plot that allows to plot polygons and holes in
different colors.
:param c_poly: Polygons color.
:type c_poly: matplotlib color, 'default' or 't' (transparent)
:param c_holes: ... |
Translate the Surface in x, y and z coordinates.
:param d_xyz: displacement in x, y(, and z).
:type d_xyz: tuple (len=2 or 3)
:returns: ``pyny.Surface`` | def move(self, d_xyz):
"""
Translate the Surface in x, y and z coordinates.
:param d_xyz: displacement in x, y(, and z).
:type d_xyz: tuple (len=2 or 3)
:returns: ``pyny.Surface``
"""
return Space(Place(self)).move(d_xyz, inplace=False)[0].surface |
Returns a new Surface which is the same but rotated about a
given axis.
If the axis given is ``None``, the rotation will be computed
about the Surface's centroid.
:param angle: Rotation angle (in radians)
:type angle: float
:param direction: Axi... | def rotate(self, angle, direction='z', axis=None):
"""
Returns a new Surface which is the same but rotated about a
given axis.
If the axis given is ``None``, the rotation will be computed
about the Surface's centroid.
:param angle: Rotation angl... |
Generates a symmetry of the Surface respect global axes.
:param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'...
:type axes: str
:returns: ``pyny.Surface`` | def mirror(self, axes='x'):
"""
Generates a symmetry of the Surface respect global axes.
:param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'...
:type axes: str
:returns: ``pyny.Surface``
"""
return Space(Place(self)).mirror(axes, inplace=False)[0].surfac... |
Static method. Creates a closed ``pyny.Polyhedron`` connecting
two polygons. Both polygons must have the same number of
vertices. The faces of the Polyhedron created have to be planar,
otherwise, an error will be raised.
The Polyhedron will have the *poly1* and *poly2* a... | def by_two_polygons(poly1, poly2, make_ccw=True):
"""
Static method. Creates a closed ``pyny.Polyhedron`` connecting
two polygons. Both polygons must have the same number of
vertices. The faces of the Polyhedron created have to be planar,
otherwise, an error will be raise... |
Translate the Polyhedron in x, y and z coordinates.
:param d_xyz: displacement in x, y(, and z).
:type d_xyz: tuple (len=2 or 3)
:returns: ``pyny.Polyhedron`` | def move(self, d_xyz):
"""
Translate the Polyhedron in x, y and z coordinates.
:param d_xyz: displacement in x, y(, and z).
:type d_xyz: tuple (len=2 or 3)
:returns: ``pyny.Polyhedron``
"""
polygon = np.array([[0,0], [0,1], [1,1], [0,1]])
... |
Returns a new Polyhedron which is the same but rotated about a
given axis.
If the axis given is ``None``, the rotation will be computed
about the Polyhedron's centroid.
:param angle: Rotation angle (in radians)
:type angle: float
:param directio... | def rotate(self, angle, direction='z', axis=None):
"""
Returns a new Polyhedron which is the same but rotated about a
given axis.
If the axis given is ``None``, the rotation will be computed
about the Polyhedron's centroid.
:param angle: Rotatio... |
Generates a symmetry of the Polyhedron respect global axes.
:param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'...
:type axes: str
:returns: ``pyny.Polyhedron`` | def mirror(self, axes='x'):
"""
Generates a symmetry of the Polyhedron respect global axes.
:param axes: 'x', 'y', 'z', 'xy', 'xz', 'yz'...
:type axes: str
:returns: ``pyny.Polyhedron``
"""
polygon = np.array([[0,0], [0,1], [1,1]])
space ... |
Copy the ``pyny.Polyhedron`` 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)
:returns: list of ``pyny.Polyhedron`` | def matrix(self, x=(0, 0), y=(0, 0) , z=(0, 0)):
"""
Copy the ``pyny.Polyhedron`` 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)
:returns: li... |
Add a new set of points to the existing one without removing it.
:param points: Points to be added.
:type points: ndarray (shape=(N, 3))
:returns: None | def add_set_of_points(self, points):
"""
Add a new set of points to the existing one without removing it.
:param points: Points to be added.
:type points: ndarray (shape=(N, 3))
:returns: None
"""
self.set_of_points = np.concatenate((self.set_of_p... |
: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])
"""
if self.polyhedra != []:
polyhedras_domain = np.vstack([poly.get_domain()
for... |
Launch ``pyny.Surface.get_height(points)`` for the Place's
Surface.
This method gives the possibility to store the computed points
along with the Place's set of points. It also makes possible to
add an extra height (z value) to these points.
The points o... | def get_height(self, points, edge=True, attach=False,
extra_height=0):
"""
Launch ``pyny.Surface.get_height(points)`` for the Place's
Surface.
This method gives the possibility to store the computed points
along with the Place's set of points.... |
Generates a set of points distributed in a mesh that covers the
whole Place and computes their height.
Generates a xy mesh with a given mesh_size in the
Place.surface's domain and computes the Surface's height for the
nodes. This mesh is alligned with the main directions `x` an... | def mesh(self, mesh_size=1, extra_height=0.1, edge=True, attach=True):
"""
Generates a set of points distributed in a mesh that covers the
whole Place and computes their height.
Generates a xy mesh with a given mesh_size in the
Place.surface's domain and computes the S... |
Add holes to the Place's ``pyny.Surface``.
:param holes_list: Polygons that will be treated as holes.
:type holes_list: list or ``pyny.Polygon``
:param make_ccw: If True, points will be sorted ccw.
:type make_ccw: bool
:returns: None
.. note:: Th... | def add_holes(self, holes_list, make_ccw=True):
"""
Add holes to the Place's ``pyny.Surface``.
:param holes_list: Polygons that will be treated as holes.
:type holes_list: list or ``pyny.Polygon``
:param make_ccw: If True, points will be sorted ccw.
:type ... |
Add polyhedras to the Place by giving their top polygon and
applying extrusion along the z axis. The resulting polygon
from the intersection will be declared as a hole in the Surface.
:param top_polys: Polygons to be extruded to the Surface.
:type top_polys: list of ``pyny.... | def add_extruded_obstacles(self, top_polys, make_ccw=True):
"""
Add polyhedras to the Place by giving their top polygon and
applying extrusion along the z axis. The resulting polygon
from the intersection will be declared as a hole in the Surface.
:param top_polys:... |
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 | 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: matplotlib Poly3DCollection
:rtype: list of mpl_toolkits.mplot3d | def get_plotable3d(self):
"""
:returns: matplotlib Poly3DCollection
:rtype: list of mpl_toolkits.mplot3d
"""
polyhedra = sum([polyhedron.get_plotable3d()
for polyhedron in self.polyhedra], [])
return polyhedra + self.surface.get_plotable3d... |
Improved plot that 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.
:param c_poly: Polygons color.
:type c_poly: matplotlib color,... | def iplot(self, c_poly='default', c_holes='default', c_sop='r',
s_sop=25, extra_height=0, ret=False, ax=None):
"""
Improved plot that allows to plot polygons and holes in
different colors and to change the size and the color of the
set of points.
The... |
Returns a new Place which is the same but rotated about a
given axis.
If the axis given is ``None``, the rotation will be computed
about the Place'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 Place which is the same but rotated about a
given axis.
If the axis given is ``None``, the rotation will be computed
about the Place's centroid.
:param angle: Rotation angle (i... |
Precomputes some parameters to run faster specific methods like
Surface.classify. This method is automatically launched before shadows
computation.
:returns: None | def lock(self):
"""
Precomputes some parameters to run faster specific methods like
Surface.classify. This method is automatically launched before shadows
computation.
:returns: None
"""
if self.locked: return
from pyny3d.utils import bool2inde... |
Add ``pyny.Places`` to the current space.
:param places: Places to add.
:type places: list of pyny.Place
:param ret: If True, returns the whole updated Space.
:type ret: bool
:returns: None, ``pyny.Space``
.. warning:: This method acts inplace. | def add_places(self, places, ret=False):
"""
Add ``pyny.Places`` to the current space.
:param places: Places to add.
:type places: list of pyny.Place
:param ret: If True, returns the whole updated Space.
:type ret: bool
:returns: None, ``pyny.Spa... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.