_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 31 13.1k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q257900 | convergence_of_galaxies_from_grid | validation | def convergence_of_galaxies_from_grid(grid, galaxies):
"""Compute the convergence of a list of galaxies from an input grid, by summing the individual convergence \
of each galaxy's mass profile.
If the input grid is a *grids.SubGrid*, the convergence is calculated on the sub-grid and binned-up to the \
original regular grid by taking the mean value of every set of sub-pixels.
If no galaxies are entered into the function, an array of all zeros is returned.
Parameters
-----------
grid : RegularGrid
The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \
| python | {
"resource": ""
} |
q257901 | potential_of_galaxies_from_grid | validation | def potential_of_galaxies_from_grid(grid, galaxies):
"""Compute the potential of a list of galaxies from an input grid, by summing the individual potential \
of each galaxy's mass profile.
If the input grid is a *grids.SubGrid*, the surface-density is calculated on the sub-grid and binned-up to the \
original regular grid by taking the mean value of every set of sub-pixels.
If no galaxies are entered into the function, an array of all zeros is returned.
Parameters
-----------
grid : RegularGrid
The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \
| python | {
"resource": ""
} |
q257902 | deflections_of_galaxies_from_grid | validation | def deflections_of_galaxies_from_grid(grid, galaxies):
"""Compute the deflections of a list of galaxies from an input grid, by summing the individual deflections \
of each galaxy's mass profile.
If the input grid is a *grids.SubGrid*, the potential is calculated on the sub-grid and binned-up to the \
original regular grid by taking the mean value of every set of sub-pixels.
If no galaxies are entered into the function, an array of all zeros is returned.
Parameters
-----------
grid : RegularGrid
The grid (regular or sub) of (y,x) arc-second coordinates at the centre of every unmasked pixel which the \
deflections is calculated on.
galaxies : [galaxy.Galaxy]
The galaxies whose mass profiles are used | python | {
"resource": ""
} |
q257903 | deflections_of_galaxies_from_sub_grid | validation | def deflections_of_galaxies_from_sub_grid(sub_grid, galaxies):
"""Compute the deflections of a list of galaxies from an input sub-grid, by summing the individual deflections \
of each galaxy's mass profile.
The deflections are calculated on the sub-grid and binned-up to the original regular grid by taking the mean value \
of every set of sub-pixels.
If no galaxies are entered into the | python | {
"resource": ""
} |
q257904 | blurred_image_of_planes_from_1d_images_and_convolver | validation | def blurred_image_of_planes_from_1d_images_and_convolver(total_planes, image_plane_image_1d_of_planes,
image_plane_blurring_image_1d_of_planes, convolver,
map_to_scaled_array):
"""For a tracer, extract the image-plane image of every plane and blur it with the PSF.
If none of the galaxies in a plane have a light profie or pixelization (and thus don't have an image) a *None* \
is used.
Parameters
----------
total_planes : int
The total number of planes that blurred images are computed for.
image_plane_image_1d_of_planes : [ndarray]
For every plane, the 1D image-plane image.
image_plane_blurring_image_1d_of_planes : [ndarray]
| python | {
"resource": ""
} |
q257905 | unmasked_blurred_image_of_planes_from_padded_grid_stack_and_psf | validation | def unmasked_blurred_image_of_planes_from_padded_grid_stack_and_psf(planes, padded_grid_stack, psf):
"""For lens data, compute the unmasked blurred image of every unmasked unblurred image of each plane. To do this, \
this function iterates over all planes to extract their unmasked unblurred images.
If a galaxy in a plane has a pixelization, the unmasked image is returned as None, as as the inversion's model \
image cannot be mapped to an unmasked version.
This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \
entire image as opposed to just the masked region.
This returns a list, where each list index corresponds to [plane_index].
Parameters
----------
planes : [plane.Plane]
The list of planes the unmasked blurred images are computed using.
padded_grid_stack : grids.GridStack
A | python | {
"resource": ""
} |
q257906 | unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf | validation | def unmasked_blurred_image_of_planes_and_galaxies_from_padded_grid_stack_and_psf(planes, padded_grid_stack, psf):
"""For lens data, compute the unmasked blurred image of every unmasked unblurred image of every galaxy in each \
plane. To do this, this function iterates over all planes and then galaxies to extract their unmasked unblurred \
images.
If a galaxy in a plane has a pixelization, the unmasked image of that galaxy in the plane is returned as None \
as as the inversion's model image cannot be mapped to an unmasked version.
This relies on using the lens data's padded-grid, which is a grid of (y,x) coordinates which extends over the \
entire image as opposed to just the masked region.
This returns a list of lists, where each list index corresponds to [plane_index][galaxy_index].
Parameters
| python | {
"resource": ""
} |
q257907 | contribution_maps_1d_from_hyper_images_and_galaxies | validation | def contribution_maps_1d_from_hyper_images_and_galaxies(hyper_model_image_1d, hyper_galaxy_images_1d, hyper_galaxies,
hyper_minimum_values):
"""For a fitting hyper_galaxy_image, hyper_galaxy model image, list of hyper galaxies images and model hyper galaxies, compute
their contribution maps, which are used to compute a scaled-noise_map map. All quantities are masked 1D arrays.
The reason this is separate from the *contributions_from_fitting_hyper_images_and_hyper_galaxies* function is that
each hyper_galaxy image has a list of hyper galaxies images and associated hyper galaxies (one for each galaxy). Thus,
this function breaks down the calculation of each 1D masked contribution map and returns them in the same datas
structure (2 lists with indexes [image_index][contribution_map_index].
Parameters
| python | {
"resource": ""
} |
q257908 | scaled_noise_map_from_hyper_galaxies_and_contribution_maps | validation | def scaled_noise_map_from_hyper_galaxies_and_contribution_maps(contribution_maps, hyper_galaxies, noise_map):
"""For a contribution map and noise-map, use the model hyper galaxies to compute a scaled noise-map.
Parameters
-----------
contribution_maps : ndarray
The image's list of 1D masked contribution maps (e.g. one for each hyper galaxy)
hyper_galaxies : [galaxy.Galaxy]
The hyper galaxies which represent the model components used to scale the noise_map, which correspond to
individual galaxies in the image.
noise_map : ccd.NoiseMap or ndarray
An array describing the RMS standard deviation error in each pixel, preferably in units of electrons per
second.
"""
| python | {
"resource": ""
} |
q257909 | LensDataFit.for_data_and_tracer | validation | def for_data_and_tracer(cls, lens_data, tracer, padded_tracer=None):
"""Fit lens data with a model tracer, automatically determining the type of fit based on the \
properties of the galaxies in the tracer.
Parameters
-----------
lens_data : lens_data.LensData or lens_data.LensDataHyper
The lens-images that is fitted.
tracer : ray_tracing.TracerNonStack
The tracer, which describes the ray-tracing and strong lens configuration.
padded_tracer : ray_tracing.Tracer or None
A tracer with an identical strong lens configuration to the tracer above, but using the lens data's \
padded grid_stack such that unmasked model-images can be computed.
"""
if tracer.has_light_profile and not tracer.has_pixelization:
return | python | {
"resource": ""
} |
q257910 | transform_grid | validation | def transform_grid(func):
"""Wrap the function in a function that checks whether the coordinates have been transformed. If they have not \
been transformed then they are transformed.
Parameters
----------
func : (profiles, *args, **kwargs) -> Object
A function that requires transformed coordinates
Returns
-------
A function that can except cartesian or transformed coordinates
"""
@wraps(func)
def wrapper(profile, grid, *args, **kwargs): | python | {
"resource": ""
} |
q257911 | cache | validation | def cache(func):
"""
Caches results of a call to a grid function. If a grid that evaluates to the same byte value is passed into the same
function of the same instance as previously then the cached result is returned.
Parameters
----------
func
Some instance method that takes a grid as its argument
| python | {
"resource": ""
} |
q257912 | EllipticalProfile.cos_and_sin_from_x_axis | validation | def cos_and_sin_from_x_axis(self):
""" Determine the sin and cosine of the angle between the profile's ellipse and the positive x-axis, \
counter-clockwise. """
| python | {
"resource": ""
} |
q257913 | EllipticalProfile.grid_angle_to_profile | validation | def grid_angle_to_profile(self, grid_thetas):
"""The angle between each angle theta on the grid and the profile, in radians.
Parameters
-----------
grid_thetas : ndarray
The angle theta counter-clockwise from the positive x-axis to each coordinate in radians.
""" | python | {
"resource": ""
} |
q257914 | mapping_matrix_from_sub_to_pix | validation | def mapping_matrix_from_sub_to_pix(sub_to_pix, pixels, regular_pixels, sub_to_regular, sub_grid_fraction):
"""Computes the mapping matrix, by iterating over the known mappings between the sub-grid and pixelization.
Parameters
-----------
sub_to_pix : ndarray
The mappings between the observed regular's sub-pixels and pixelization's pixels.
pixels : int
The number of pixels in the pixelization.
regular_pixels : int
The number of datas pixels in the observed datas and thus on the regular grid.
sub_to_regular : ndarray
The mappings between the observed regular's sub-pixels and observed regular's pixels.
sub_grid_fraction : float
| python | {
"resource": ""
} |
q257915 | voronoi_regular_to_pix_from_grids_and_geometry | validation | def voronoi_regular_to_pix_from_grids_and_geometry(regular_grid, regular_to_nearest_pix, pixel_centres,
pixel_neighbors, pixel_neighbors_size):
""" Compute the mappings between a set of regular-grid pixels and pixelization pixels, using information on \
how regular pixels map to their closest pixelization pixel on the image-plane pix-grid and the pixelization's \
pixel centres.
To determine the complete set of regular-pixel to pixelization pixel mappings, we must pair every regular-pixel to \
its nearest pixel. Using a full nearest neighbor search to do this is slow, thus the pixel neighbors (derived via \
the Voronoi grid) are used to localize each nearest neighbor search via a graph search.
Parameters
----------
regular_grid : RegularGrid
The grid of (y,x) arc-second coordinates at the centre of every unmasked pixel, which has been traced to \
to an irregular grid via lens.
regular_to_nearest_pix : ndarray
A 1D array that maps every regular-grid pixel to its nearest pix-grid pixel (as determined on the unlensed \
2D array).
pixel_centres : ndarray
The (y,x) centre of every Voronoi pixel in arc-seconds.
pixel_neighbors : ndarray
An array of length (voronoi_pixels) which provides the index of all neighbors of every pixel in \
| python | {
"resource": ""
} |
q257916 | voronoi_sub_to_pix_from_grids_and_geometry | validation | def voronoi_sub_to_pix_from_grids_and_geometry(sub_grid, regular_to_nearest_pix, sub_to_regular, pixel_centres,
pixel_neighbors, pixel_neighbors_size):
""" Compute the mappings between a set of sub-grid pixels and pixelization pixels, using information on \
how the regular pixels hosting each sub-pixel map to their closest pixelization pixel on the image-plane pix-grid \
and the pixelization's pixel centres.
To determine the complete set of sub-pixel to pixelization pixel mappings, we must pair every sub-pixel to \
its nearest pixel. Using a full nearest neighbor search to do this is slow, thus the pixel neighbors (derived via \
the Voronoi grid) are used to localize each nearest neighbor search by using a graph search.
Parameters
----------
regular_grid : RegularGrid
The grid of (y,x) arc-second coordinates at the centre of every unmasked pixel, which has been traced to \
to an irregular grid via lens.
regular_to_nearest_pix : ndarray
A 1D array that maps every regular-grid pixel to its nearest pix-grid pixel (as determined on the unlensed \
2D array).
pixel_centres : (float, float)
The (y,x) centre of every Voronoi pixel in arc-seconds.
pixel_neighbors : ndarray
An array of length (voronoi_pixels) which provides the index of | python | {
"resource": ""
} |
q257917 | EllipticalLightProfile.luminosity_within_circle_in_units | validation | def luminosity_within_circle_in_units(self, radius: dim.Length, unit_luminosity='eps', kpc_per_arcsec=None,
exposure_time=None):
"""Integrate the light profile to compute the total luminosity within a circle of specified radius. This is \
centred on the light profile's centre.
The following units for mass can be specified and output:
- Electrons per second (default) - 'eps'.
- Counts - 'counts' (multiplies the luminosity in electrons per second by the exposure time).
Parameters
----------
| python | {
"resource": ""
} |
q257918 | EllipticalLightProfile.luminosity_within_ellipse_in_units | validation | def luminosity_within_ellipse_in_units(self, major_axis, unit_luminosity='eps', kpc_per_arcsec=None,
exposure_time=None):
"""Integrate the light profiles to compute the total luminosity within an ellipse of specified major axis. \
This is centred on the light profile's centre.
The following units for mass can be specified and output:
- Electrons per second (default) - 'eps'.
- Counts - 'counts' (multiplies the luminosity in electrons per second by the exposure time).
Parameters
----------
major_axis : float
| python | {
"resource": ""
} |
q257919 | EllipticalLightProfile.luminosity_integral | validation | def luminosity_integral(self, x, axis_ratio):
"""Routine to integrate the luminosity of an elliptical light profile.
The axis ratio is set to 1.0 for computing | python | {
"resource": ""
} |
q257920 | EllipticalGaussian.intensities_from_grid_radii | validation | def intensities_from_grid_radii(self, grid_radii):
"""Calculate the intensity of the Gaussian light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
| python | {
"resource": ""
} |
q257921 | EllipticalSersic.intensities_from_grid_radii | validation | def intensities_from_grid_radii(self, grid_radii):
"""
Calculate the intensity of the Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
"""
np.seterr(all='ignore')
| python | {
"resource": ""
} |
q257922 | EllipticalCoreSersic.intensities_from_grid_radii | validation | def intensities_from_grid_radii(self, grid_radii):
"""Calculate the intensity of the cored-Sersic light profile on a grid of radial coordinates.
Parameters
----------
grid_radii : float
The radial distance from the centre of the profile. for each coordinate on the grid.
"""
return np.multiply(np.multiply(self.intensity_prime, np.power(
np.add(1, np.power(np.divide(self.radius_break, grid_radii), self.alpha)), (self.gamma / self.alpha))),
np.exp(np.multiply(-self.sersic_constant,
| python | {
"resource": ""
} |
q257923 | AbstractPlane.luminosities_of_galaxies_within_circles_in_units | validation | def luminosities_of_galaxies_within_circles_in_units(self, radius : dim.Length, unit_luminosity='eps', exposure_time=None):
"""Compute the total luminosity of all galaxies in this plane within a circle of specified radius.
See *galaxy.light_within_circle* and *light_profiles.light_within_circle* for details \
of how this is performed.
Parameters
----------
radius : float
The radius of the circle to compute the dimensionless mass within.
units_luminosity : str
The units the luminosity is returned in (eps | counts).
exposure_time : float
| python | {
"resource": ""
} |
q257924 | AbstractPlane.luminosities_of_galaxies_within_ellipses_in_units | validation | def luminosities_of_galaxies_within_ellipses_in_units(self, major_axis : dim.Length, unit_luminosity='eps',
exposure_time=None):
"""
Compute the total luminosity of all galaxies in this plane within a ellipse of specified major-axis.
The value returned by this integral is dimensionless, and a conversion factor can be specified to convert it \
to a physical value (e.g. the photometric zeropoint).
See *galaxy.light_within_ellipse* and *light_profiles.light_within_ellipse* for details
of how this is performed.
Parameters
----------
major_axis : float
The major-axis radius of the ellipse.
| python | {
"resource": ""
} |
q257925 | AbstractPlane.masses_of_galaxies_within_circles_in_units | validation | def masses_of_galaxies_within_circles_in_units(self, radius : dim.Length, unit_mass='angular',
critical_surface_density=None):
"""Compute the total mass of all galaxies in this plane within a circle of specified radius.
See *galaxy.angular_mass_within_circle* and *mass_profiles.angular_mass_within_circle* for details
of how this is performed.
Parameters
----------
radius : float
The radius of the circle to compute the dimensionless mass within.
units_mass : str
The units the mass is returned in (angular | solMass).
critical_surface_density : float
| python | {
"resource": ""
} |
q257926 | AbstractPlane.masses_of_galaxies_within_ellipses_in_units | validation | def masses_of_galaxies_within_ellipses_in_units(self, major_axis : dim.Length, unit_mass='angular',
critical_surface_density=None):
"""Compute the total mass of all galaxies in this plane within a ellipse of specified major-axis.
See *galaxy.angular_mass_within_ellipse* and *mass_profiles.angular_mass_within_ellipse* for details \
of how this is performed.
Parameters
----------
major_axis : float
The major-axis radius of the ellipse.
units_luminosity : str
The units the luminosity is returned in (eps | | python | {
"resource": ""
} |
q257927 | AbstractGriddedPlane.trace_grid_stack_to_next_plane | validation | def trace_grid_stack_to_next_plane(self):
"""Trace this plane's grid_stacks to the next plane, using its deflection angles."""
def minus(grid, deflections):
| python | {
"resource": ""
} |
q257928 | AbstractGriddedPlane.yticks | validation | def yticks(self):
"""Compute the yticks labels of this grid_stack, used for plotting the y-axis ticks when visualizing an image \
"""
| python | {
"resource": ""
} |
q257929 | AbstractGriddedPlane.xticks | validation | def xticks(self):
"""Compute the xticks labels of this grid_stack, used for plotting the x-axis ticks when visualizing an \
image"""
| python | {
"resource": ""
} |
q257930 | Plane.unmasked_blurred_image_of_galaxies_from_psf | validation | def unmasked_blurred_image_of_galaxies_from_psf(self, padded_grid_stack, psf):
"""This is a utility function for the function above, which performs the iteration over each plane's galaxies \
and computes each galaxy's unmasked blurred image.
Parameters | python | {
"resource": ""
} |
q257931 | PlanePositions.trace_to_next_plane | validation | def trace_to_next_plane(self):
"""Trace the positions to the next plane."""
return list(map(lambda positions, deflections: np.subtract(positions, | python | {
"resource": ""
} |
q257932 | ScaledSquarePixelArray.single_value | validation | def single_value(cls, value, shape, pixel_scale, origin=(0.0, 0.0)):
"""
Creates an instance of Array and fills it with a single value
Parameters
----------
value: float
The value with which the array should be filled
shape: (int, int)
The shape of the array
pixel_scale: float
The scale of a pixel in arc seconds
Returns
| python | {
"resource": ""
} |
q257933 | ScaledSquarePixelArray.zoomed_scaled_array_around_mask | validation | def zoomed_scaled_array_around_mask(self, mask, buffer=1):
"""Extract the 2D region of an array corresponding to the rectangle encompassing all unmasked values.
This is used to extract and visualize only the region of an image that is used in an analysis.
Parameters
----------
mask : mask.Mask
The mask around which the scaled array is extracted.
buffer : int
The buffer of pixels around the extraction.
"""
| python | {
"resource": ""
} |
q257934 | ScaledSquarePixelArray.resized_scaled_array_from_array | validation | def resized_scaled_array_from_array(self, new_shape, new_centre_pixels=None, new_centre_arcsec=None):
"""resized the array to a new shape and at a new origin.
Parameters
-----------
new_shape : (int, int)
The new two-dimensional shape of the array.
"""
if new_centre_pixels is None and new_centre_arcsec is None:
new_centre = (-1, -1) # In Numba, the input origin must be the same image type as the origin, thus we cannot
# pass 'None' and instead use the tuple (-1, -1).
elif new_centre_pixels is not None and new_centre_arcsec is None:
new_centre = new_centre_pixels
elif new_centre_pixels is None and new_centre_arcsec is not None:
| python | {
"resource": ""
} |
q257935 | fit_lens_data_with_sensitivity_tracers | validation | def fit_lens_data_with_sensitivity_tracers(lens_data, tracer_normal, tracer_sensitive):
"""Fit lens data with a normal tracer and sensitivity tracer, to determine our sensitivity to a selection of \
galaxy components. This factory automatically determines the type of fit based on the properties of the galaxies \
in the tracers.
Parameters
-----------
lens_data : lens_data.LensData or lens_data.LensDataHyper
The lens-images that is fitted.
tracer_normal : ray_tracing.AbstractTracer
A tracer whose galaxies have the same model components (e.g. light profiles, mass profiles) as the \
lens data that we are fitting.
tracer_sensitive : ray_tracing.AbstractTracerNonStack
A tracer whose galaxies have the same model components (e.g. | python | {
"resource": ""
} |
q257936 | Mask.unmasked_for_shape_and_pixel_scale | validation | def unmasked_for_shape_and_pixel_scale(cls, shape, pixel_scale, invert=False):
"""Setup a mask where all pixels are unmasked.
Parameters
----------
shape : (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion | python | {
"resource": ""
} |
q257937 | Mask.circular | validation | def circular(cls, shape, pixel_scale, radius_arcsec, centre=(0., 0.), invert=False):
"""Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
radius_arcsec : float
The radius (in arc seconds) of the circle within which pixels unmasked.
centre: (float, float)
The centre of the circle used to mask pixels. | python | {
"resource": ""
} |
q257938 | Mask.circular_annular | validation | def circular_annular(cls, shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec, centre=(0., 0.),
invert=False):
"""Setup a mask where unmasked pixels are within an annulus of input inner and outer arc second radii and \
centre.
Parameters
----------
shape : (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
inner_radius_arcsec : float
The radius (in arc seconds) of the inner circle outside of which pixels are unmasked.
outer_radius_arcsec : float
The radius (in arc seconds) of the outer circle | python | {
"resource": ""
} |
q257939 | Mask.circular_anti_annular | validation | def circular_anti_annular(cls, shape, pixel_scale, inner_radius_arcsec, outer_radius_arcsec, outer_radius_2_arcsec,
centre=(0., 0.), invert=False):
"""Setup a mask where unmasked pixels are outside an annulus of input inner and outer arc second radii, but \
within a second outer radius, and at a given centre.
This mask there has two distinct unmasked regions (an inner circle and outer annulus), with an inner annulus \
of masked pixels.
Parameters
----------
shape : (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
inner_radius_arcsec : float
The radius (in arc seconds) of the inner circle inside of which pixels are unmasked.
outer_radius_arcsec : float
The radius (in arc seconds) of the outer circle within which pixels are masked and outside of which they \
are unmasked.
outer_radius_2_arcsec : float
The radius (in arc seconds) of the second outer circle within which pixels are unmasked and outside of \
| python | {
"resource": ""
} |
q257940 | Mask.elliptical | validation | def elliptical(cls, shape, pixel_scale, major_axis_radius_arcsec, axis_ratio, phi, centre=(0., 0.),
invert=False):
""" Setup a mask where unmasked pixels are within an ellipse of an input arc second major-axis and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
major_axis_radius_arcsec : float
The major-axis (in arc seconds) of the ellipse within which pixels are unmasked.
axis_ratio : float
The axis-ratio of the ellipse within which pixels are unmasked.
phi : float
The rotation | python | {
"resource": ""
} |
q257941 | Mask.elliptical_annular | validation | def elliptical_annular(cls, shape, pixel_scale,inner_major_axis_radius_arcsec, inner_axis_ratio, inner_phi,
outer_major_axis_radius_arcsec, outer_axis_ratio, outer_phi, centre=(0.0, 0.0),
invert=False):
"""Setup a mask where unmasked pixels are within an elliptical annulus of input inner and outer arc second \
major-axis and centre.
Parameters
----------
shape: (int, int)
The (y,x) shape of the mask in units of pixels.
pixel_scale: float
The arc-second to pixel conversion factor of each pixel.
inner_major_axis_radius_arcsec : float
The major-axis (in arc seconds) of the inner ellipse within which pixels are masked.
inner_axis_ratio : float
The axis-ratio of the inner ellipse within which pixels are masked.
inner_phi : float
The rotation angle of the inner ellipse within which pixels are masked, (counter-clockwise from the \
positive x-axis).
outer_major_axis_radius_arcsec : float
The major-axis (in arc seconds) of the outer ellipse within which pixels are unmasked.
outer_axis_ratio : float
The axis-ratio of the outer ellipse within which pixels are | python | {
"resource": ""
} |
q257942 | Mask.zoom_region | validation | def zoom_region(self):
"""The zoomed rectangular region corresponding to the square encompassing all unmasked values.
This is used to zoom in on the region of an image that is used in an analysis for visualization."""
# Have to convert mask to bool for invert function to work.
where = | python | {
"resource": ""
} |
q257943 | GalaxyModel.instance_for_arguments | validation | def instance_for_arguments(self, arguments):
"""
Create an instance of the associated class for a set of arguments
Parameters
----------
arguments: {Prior: value}
Dictionary mapping_matrix priors to attribute analysis_path and value pairs
Returns
-------
An instance of the class
"""
profiles = {**{key: value.instance_for_arguments(arguments)
for key, value
in self.profile_prior_model_dict.items()}, **self.constant_profile_dict}
try:
redshift = self.redshift.instance_for_arguments(arguments)
except AttributeError:
redshift = self.redshift
pixelization = self.pixelization.instance_for_arguments(arguments) \
| python | {
"resource": ""
} |
q257944 | GalaxyModel.gaussian_prior_model_for_arguments | validation | def gaussian_prior_model_for_arguments(self, arguments):
"""
Create a new galaxy prior from a set of arguments, replacing the priors of some of this galaxy prior's prior
models with new arguments.
Parameters
----------
arguments: dict
A dictionary mapping_matrix between old priors and their replacements.
Returns
-------
new_model: GalaxyModel
A model with some or all priors replaced.
"""
| python | {
"resource": ""
} |
q257945 | plot_image | validation | def plot_image(
image, plot_origin=True, mask=None, extract_array_from_mask=False, zoom_around_mask=False,
should_plot_border=False, positions=None, as_subplot=False,
units='arcsec', kpc_per_arcsec=None, figsize=(7, 7), aspect='square',
cmap='jet', norm='linear', norm_min=None, norm_max=None, linthresh=0.05, linscale=0.01,
cb_ticksize=10, cb_fraction=0.047, cb_pad=0.01, cb_tick_values=None, cb_tick_labels=None,
title='Image', titlesize=16, xlabelsize=16, ylabelsize=16, xyticksize=16,
mask_pointsize=10, position_pointsize=30, grid_pointsize=1,
output_path=None, output_format='show', output_filename='image'):
"""Plot the observed image of the ccd data.
Set *autolens.data.array.plotters.array_plotters* for a description of all input parameters not described below.
Parameters
-----------
image : ScaledSquarePixelArray
| python | {
"resource": ""
} |
q257946 | norm_and_check | validation | def norm_and_check(source_tree, requested):
"""Normalise and check a backend path.
Ensure that the requested backend path is specified as a relative path,
and resolves to a location under the given source tree.
Return an absolute version of the requested path.
"""
if os.path.isabs(requested):
raise ValueError("paths must be relative")
abs_source = os.path.abspath(source_tree)
abs_requested = os.path.normpath(os.path.join(abs_source, requested))
# We have to use commonprefix for Python 2.7 compatibility. So we
| python | {
"resource": ""
} |
q257947 | contained_in | validation | def contained_in(filename, directory):
"""Test if a file is located within the given directory."""
filename = | python | {
"resource": ""
} |
q257948 | _build_backend | validation | def _build_backend():
"""Find and load the build backend"""
# Add in-tree backend directories to the front of sys.path.
backend_path = os.environ.get('PEP517_BACKEND_PATH')
if backend_path:
extra_pathitems = backend_path.split(os.pathsep)
sys.path[:0] = extra_pathitems
ep = os.environ['PEP517_BUILD_BACKEND']
| python | {
"resource": ""
} |
q257949 | build_sdist | validation | def build_sdist(sdist_directory, config_settings):
"""Invoke the mandatory build_sdist hook."""
backend = _build_backend()
try:
| python | {
"resource": ""
} |
q257950 | API.get | validation | def get(self, *args, **kwargs):
"""
An interface for get requests that handles errors more gracefully to
prevent data loss
"""
try:
req_func = self.session.get if self.session else requests.get
req = req_func(*args, **kwargs)
req.raise_for_status()
self.failed_last = False
return req
except requests.exceptions.RequestException as e:
self.log_error(e)
for i in range(1, self.num_retries):
sleep_time = self.retry_rate * i
self.log_function("Retrying in %s seconds" % sleep_time)
self._sleep(sleep_time)
try:
req = requests.get(*args, **kwargs)
req.raise_for_status()
self.log_function("New request successful")
| python | {
"resource": ""
} |
q257951 | convert_frames_to_video | validation | def convert_frames_to_video(tar_file_path, output_path="output.mp4", framerate=60, overwrite=False):
"""
Try to convert a tar file containing a sequence of frames saved by the
meshcat viewer into a single video file.
This relies on having `ffmpeg` installed on your system.
"""
output_path = os.path.abspath(output_path)
if os.path.isfile(output_path) and not overwrite:
raise ValueError("The output path {:s} already exists. To overwrite that file, you can pass overwrite=True to this function.".format(output_path))
with tempfile.TemporaryDirectory() as tmp_dir:
with tarfile.open(tar_file_path) as tar:
tar.extractall(tmp_dir)
args = ["ffmpeg",
"-r", str(framerate),
"-i", r"%07d.png",
"-vcodec", "libx264",
"-preset", "slow",
"-crf", "18"]
if overwrite:
args.append("-y") | python | {
"resource": ""
} |
q257952 | FileMetadata.toJSON | validation | def toJSON(self):
"""Get a json dict of the attributes of this object."""
return {"id": self.id, | python | {
"resource": ""
} |
q257953 | File.from_string | validation | def from_string(cls, content, position=1, file_id=None):
"""
Convenience method to create a file from a string.
This file object's metadata will have the id 'inlined_input'.
Inputs
------
content -- the content of the file (a string).
position -- (default 1) rank among all files of the model while parsing
| python | {
"resource": ""
} |
q257954 | File.from_file | validation | def from_file(cls, fpath, position=1, file_id=None):
"""
Convience method to create a kappa file object from a file on disk
Inputs
------
fpath -- path to the file on disk
position -- (default 1) rank among all files of the model while parsing
see FileMetadata
file_id -- (default = fpath) the file_id that will be used by kappa.
"""
if file_id is None:
file_id = | python | {
"resource": ""
} |
q257955 | KappaApi._fix_docs | validation | def _fix_docs(this_abc, child_class):
"""Make api method docs inheritted.
Specifically, insepect.getdoc will return values inheritted from this
abc for standardized api methods.
"""
# After python 3.5, this is basically handled automatically
if sys.version_info >= (3, 5):
return child_class
if not issubclass(child_class, this_abc):
| python | {
"resource": ""
} |
q257956 | KappaApi.add_model_string | validation | def add_model_string(self, model_str, position=1, file_id=None):
"""Add a kappa model given in a string to the project."""
if file_id is None:
file_id = self.make_unique_id('inlined_input')
| python | {
"resource": ""
} |
q257957 | KappaApi.add_model_file | validation | def add_model_file(self, model_fpath, position=1, file_id=None):
"""Add a kappa model from a file at given path to the project."""
if file_id is None:
file_id = self.make_unique_id('file_input')
| python | {
"resource": ""
} |
q257958 | KappaApi.set_default_sim_param | validation | def set_default_sim_param(self, *args, **kwargs):
"""Set the simulation default simulation parameters.
You can pass one of two things in as input:
- a kappa_common.SimulationParameter instance
- the arguments and keyword argument to create such an instance.
The parameters you specify will be used by default in simulations run
by | python | {
"resource": ""
} |
q257959 | KappaApi.get_is_sim_running | validation | def get_is_sim_running(self):
"""Check if the current simulation is running."""
sim_info = self.simulation_info()
try:
progress_info = sim_info['simulation_info_progress']
| python | {
"resource": ""
} |
q257960 | KappaApi.wait_for_simulation_stop | validation | def wait_for_simulation_stop(self, timeout=None):
"""Block until the simulation is done or timeout seconds exceeded.
If the simulation stops before timeout, siminfo is returned.
"""
start = | python | {
"resource": ""
} |
q257961 | DSP_io_stream.in_out_check | validation | def in_out_check(self):
"""
Checks the input and output to see if they are valid
"""
devices = available_devices()
if not self.in_idx in devices:
raise OSError("Input device is unavailable")
in_check = devices[self.in_idx]
if not self.out_idx in devices:
raise OSError("Output device is unavailable")
out_check = devices[self.out_idx]
| python | {
"resource": ""
} |
q257962 | DSP_io_stream.DSP_capture_add_samples | validation | def DSP_capture_add_samples(self,new_data):
"""
Append new samples to the data_capture array and increment the sample counter
If length reaches Tcapture, then the newest samples will be kept. If Tcapture = 0
then new values are not appended to the data_capture array.
"""
self.capture_sample_count += len(new_data)
| python | {
"resource": ""
} |
q257963 | DSP_io_stream.DSP_capture_add_samples_stereo | validation | def DSP_capture_add_samples_stereo(self,new_data_left,new_data_right):
"""
Append new samples to the data_capture_left array and the data_capture_right
array and increment the sample counter. If length reaches Tcapture, then the
newest samples will be kept. If Tcapture = 0 then new values are not appended
to the data_capture array.
"""
self.capture_sample_count = self.capture_sample_count + len(new_data_left) + len(new_data_right)
if self.Tcapture > 0:
| python | {
"resource": ""
} |
q257964 | DSP_io_stream.DSP_callback_tic | validation | def DSP_callback_tic(self):
"""
Add new tic time to the DSP_tic list. Will not be called if
Tcapture = 0.
"""
| python | {
"resource": ""
} |
q257965 | DSP_io_stream.DSP_callback_toc | validation | def DSP_callback_toc(self):
"""
Add new toc time to the DSP_toc list. Will not be called | python | {
"resource": ""
} |
q257966 | IIR_bsf | validation | def IIR_bsf(f_pass1, f_stop1, f_stop2, f_pass2, Ripple_pass, Atten_stop,
fs = 1.00, ftype = 'butter'):
"""
Design an IIR bandstop filter using scipy.signal.iirdesign.
The filter order is determined based on
f_pass Hz, f_stop Hz, and the desired stopband attenuation
d_stop in dB, all relative to a sampling rate of fs Hz.
Mark Wickert October 2016
"""
b,a = signal.iirdesign([2*float(f_pass1)/fs, 2*float(f_pass2)/fs],
[2*float(f_stop1)/fs, 2*float(f_stop2)/fs],
Ripple_pass, Atten_stop,
| python | {
"resource": ""
} |
q257967 | freqz_cas | validation | def freqz_cas(sos,w):
"""
Cascade frequency response
Mark Wickert October 2016
"""
Ns,Mcol = sos.shape
w,Hcas = signal.freqz(sos[0,:3],sos[0,3:],w)
for k in range(1,Ns):
| python | {
"resource": ""
} |
q257968 | unique_cpx_roots | validation | def unique_cpx_roots(rlist,tol = 0.001):
"""
The average of the root values is used when multiplicity
is greater than one.
Mark Wickert October 2016
"""
uniq = [rlist[0]]
mult = [1]
for k in range(1,len(rlist)):
N_uniq = len(uniq)
for m in range(N_uniq):
if abs(rlist[k]-uniq[m]) <= tol:
mult[m] += 1
| python | {
"resource": ""
} |
q257969 | firwin_bpf | validation | def firwin_bpf(N_taps, f1, f2, fs = 1.0, pass_zero=False):
"""
Design a windowed FIR bandpass filter in terms of passband
critical frequencies f1 < f2 in Hz relative to sampling rate
fs in Hz. The | python | {
"resource": ""
} |
q257970 | fir_remez_lpf | validation | def fir_remez_lpf(f_pass, f_stop, d_pass, d_stop, fs = 1.0, N_bump=5):
"""
Design an FIR lowpass filter using remez with order
determination. The filter order is determined based on
f_pass Hz, fstop Hz, and the desired passband ripple
d_pass dB and stopband attenuation d_stop dB all
relative to a sampling rate of fs Hz.
Mark Wickert October 2016, updated October 2018
"""
| python | {
"resource": ""
} |
q257971 | fir_remez_hpf | validation | def fir_remez_hpf(f_stop, f_pass, d_pass, d_stop, fs = 1.0, N_bump=5):
"""
Design an FIR highpass filter using remez with order
determination. The filter order is determined based on
f_pass Hz, fstop Hz, and the desired passband ripple
d_pass dB and stopband attenuation d_stop dB all
relative to a sampling rate of fs Hz.
Mark Wickert October 2016, updated October 2018
| python | {
"resource": ""
} |
q257972 | fir_remez_bpf | validation | def fir_remez_bpf(f_stop1, f_pass1, f_pass2, f_stop2, d_pass, d_stop,
fs = 1.0, N_bump=5):
"""
Design an FIR bandpass filter using remez with order
determination. The filter order is determined based on
f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the
desired passband ripple d_pass dB and stopband attenuation
d_stop dB all relative to a sampling rate of fs Hz.
Mark Wickert October 2016, updated October 2018
"""
n, ff, aa, wts = bandpass_order(f_stop1, f_pass1, f_pass2, f_stop2,
| python | {
"resource": ""
} |
q257973 | fir_remez_bsf | validation | def fir_remez_bsf(f_pass1, f_stop1, f_stop2, f_pass2, d_pass, d_stop,
fs = 1.0, N_bump=5):
"""
Design an FIR bandstop filter using remez with order
determination. The filter order is determined based on
f_pass1 Hz, f_stop1 Hz, f_stop2 Hz, f_pass2 Hz, and the
desired passband ripple d_pass dB and stopband attenuation
d_stop dB all relative to a sampling rate of fs Hz.
Mark Wickert October 2016, updated October 2018
"""
n, ff, aa, wts = bandstop_order(f_pass1, f_stop1, f_stop2, f_pass2,
d_pass, d_stop, fsamp=fs)
# Bump up the order by | python | {
"resource": ""
} |
q257974 | position_CD | validation | def position_CD(Ka,out_type = 'fb_exact'):
"""
CD sled position control case study of Chapter 18.
The function returns the closed-loop and open-loop
system function for a CD/DVD sled position control
system. The loop amplifier gain is the only variable
that may be changed. The returned system function can
however be changed.
Parameters
----------
Ka : loop amplifier gain, start with 50.
out_type : 'open_loop' for open loop system function
out_type : 'fb_approx' for closed-loop approximation
out_type : 'fb_exact' for closed-loop exact
Returns
-------
b : numerator coefficient ndarray
a : denominator coefficient ndarray
Notes
-----
With the exception of the loop amplifier gain, all
other parameters are hard-coded from Case Study example.
Examples
-------- | python | {
"resource": ""
} |
q257975 | cruise_control | validation | def cruise_control(wn,zeta,T,vcruise,vmax,tf_mode='H'):
"""
Cruise control with PI controller and hill disturbance.
This function returns various system function configurations
for a the cruise control Case Study example found in
the supplementary article. The plant model is obtained by the
linearizing the equations of motion and the controller contains a
proportional and integral gain term set via the closed-loop parameters
natuarl frequency wn (rad/s) and damping zeta.
Parameters
----------
wn : closed-loop natural frequency in rad/s, nominally 0.1
zeta : closed-loop damping factor, nominally 1.0
T : vehicle time constant, nominally 10 s
vcruise : cruise velocity set point, nominally 75 mph
vmax : maximum vehicle velocity, nominally 120 mph
tf_mode : 'H', 'HE', 'HVW', or 'HED' controls the system function returned by the function
| python | {
"resource": ""
} |
q257976 | stereo_FM | validation | def stereo_FM(x,fs=2.4e6,file_name='test.wav'):
"""
Stereo demod from complex baseband at sampling rate fs.
Assume fs is 2400 ksps
Mark Wickert July 2017
"""
N1 = 10
b = signal.firwin(64,2*200e3/float(fs))
# Filter and decimate (should be polyphase)
y = signal.lfilter(b,1,x)
z = ss.downsample(y,N1)
# Apply complex baseband discriminator
z_bb = discrim(z)
# Work with the (3) stereo multiplex signals:
# Begin by designing a lowpass filter for L+R and DSP demoded (L-R)
# (fc = 12 KHz)
b12 = signal.firwin(128,2*12e3/(float(fs)/N1))
# The L + R term is at baseband, we just lowpass filter to remove
# other terms above 12 kHz.
y_lpr = signal.lfilter(b12,1,z_bb)
b19 = signal.firwin(128,2*1e3*np.array([19-5,19+5])/(float(fs)/N1),
pass_zero=False);
z_bb19 = signal.lfilter(b19,1,z_bb)
# Lock PLL to 19 kHz pilot
# A type 2 loop with bandwidth Bn = 10 Hz and damping zeta = 0.707
# The VCO quiescent frequency is set to 19000 Hz.
theta, phi_error = pilot_PLL(z_bb19,19000,fs/N1,2,10,0.707)
# Coherently demodulate the L - R subcarrier at 38 kHz.
# theta is the PLL output phase at 19 kHz, so to double multiply
# by 2 and wrap with cos() or sin().
# First bandpass filter
b38 = signal.firwin(128,2*1e3*np.array([38-5,38+5])/(float(fs)/N1),
pass_zero=False);
x_lmr = signal.lfilter(b38,1,z_bb)
# Coherently demodulate using the PLL output phase
x_lmr = 2*np.sqrt(2)*np.cos(2*theta)*x_lmr
# Lowpass at 12 kHz to recover the desired DSB demod term
| python | {
"resource": ""
} |
q257977 | FIR_header | validation | def FIR_header(fname_out, h):
"""
Write FIR Filter Header Files
Mark Wickert February 2015
"""
M = len(h)
N = 3 # Coefficients per line
f = open(fname_out, 'wt')
f.write('//define a FIR coefficient Array\n\n')
f.write('#include <stdint.h>\n\n')
f.write('#ifndef M_FIR\n')
f.write('#define M_FIR %d\n' % M)
f.write('#endif\n')
f.write('/************************************************************************/\n');
f.write('/* FIR Filter Coefficients */\n');
f.write('float32_t h_FIR[M_FIR] = {')
kk = 0;
for k in range(M):
# k_mod = k % M
if (kk < N - 1) and (k < M - 1):
f.write('%15.12f,' % h[k])
kk += 1
| python | {
"resource": ""
} |
q257978 | FIR_fix_header | validation | def FIR_fix_header(fname_out, h):
"""
Write FIR Fixed-Point Filter Header Files
Mark Wickert February 2015
"""
M = len(h)
hq = int16(rint(h * 2 ** 15))
N = 8 # Coefficients per line
f = open(fname_out, 'wt')
f.write('//define a FIR coefficient Array\n\n')
f.write('#include <stdint.h>\n\n')
f.write('#ifndef M_FIR\n')
f.write('#define M_FIR %d\n' % M)
f.write('#endif\n')
f.write('/************************************************************************/\n');
f.write('/* | python | {
"resource": ""
} |
q257979 | IIR_sos_header | validation | def IIR_sos_header(fname_out, SOS_mat):
"""
Write IIR SOS Header Files
File format is compatible with CMSIS-DSP IIR
Directform II Filter Functions
Mark Wickert March 2015-October 2016
"""
Ns, Mcol = SOS_mat.shape
f = open(fname_out, 'wt')
f.write('//define a IIR SOS CMSIS-DSP coefficient array\n\n')
f.write('#include <stdint.h>\n\n')
f.write('#ifndef STAGES\n')
f.write('#define STAGES %d\n' % Ns)
f.write('#endif\n')
f.write('/*********************************************************/\n');
f.write('/* IIR SOS Filter Coefficients */\n');
f.write('float32_t ba_coeff[%d] = { //b0,b1,b2,a1,a2,... by stage\n' % (5 * Ns))
for k in range(Ns):
if (k < Ns - 1):
f.write(' %+-13e, %+-13e, %+-13e,\n' % \
(SOS_mat[k, 0], SOS_mat[k, 1], SOS_mat[k, 2]))
f.write(' %+-13e, %+-13e,\n' % \
(-SOS_mat[k, 4], -SOS_mat[k, 5]))
else:
f.write(' %+-13e, %+-13e, %+-13e,\n' % \
| python | {
"resource": ""
} |
q257980 | eye_plot | validation | def eye_plot(x,L,S=0):
"""
Eye pattern plot of a baseband digital communications waveform.
The signal must be real, but can be multivalued in terms of the underlying
modulation scheme. Used for BPSK eye plots in the Case Study article.
Parameters
----------
x : ndarray of the real input data vector/array
L : display length in samples (usually two symbols)
S : start index
Returns
-------
None : A plot window opens containing the eye plot
Notes
-----
Increase S to eliminate filter transients.
Examples
--------
1000 bits at 10 samples per bit with 'rc' shaping.
>>> import matplotlib.pyplot as plt
>>> | python | {
"resource": ""
} |
q257981 | scatter | validation | def scatter(x,Ns,start):
"""
Sample a baseband digital communications waveform at the symbol spacing.
Parameters
----------
x : ndarray of the input digital comm signal
Ns : number of samples per symbol (bit)
start : the array index to start the sampling
Returns
-------
xI : ndarray of the real part of x following sampling
xQ : ndarray of the imaginary part of x following sampling
Notes
-----
Normally the signal is complex, so the scatter plot contains
clusters at point in the complex plane. For a binary signal
such as BPSK, the point centers are nominally +/-1 on the real
axis. Start is used to eliminate transients from the FIR
pulse shaping filters from appearing in the scatter plot.
Examples
--------
>>> import matplotlib.pyplot | python | {
"resource": ""
} |
q257982 | MPSK_bb | validation | def MPSK_bb(N_symb,Ns,M,pulse='rect',alpha = 0.25,MM=6):
"""
Generate a complex baseband MPSK signal with pulse shaping.
Parameters
----------
N_symb : number of MPSK symbols to produce
Ns : the number of samples per bit,
M : MPSK modulation order, e.g., 4, 8, 16, ...
pulse_type : 'rect' , 'rc', 'src' (default 'rect')
alpha : excess bandwidth factor(default 0.25)
MM : single sided pulse duration (default = 6)
Returns
-------
x : ndarray of the MPSK signal values
b : ndarray of the pulse shape
data : ndarray of the underlying data bits
Notes
-----
Pulse shapes include 'rect' (rectangular), 'rc' (raised cosine),
'src' (root raised cosine). The actual pulse length is 2*M+1 samples.
This function is used by BPSK_tx in the Case Study article.
Examples
--------
>>> from sk_dsp_comm import digitalcom as dc
>>> import scipy.signal as signal
>>> import matplotlib.pyplot as plt
>>> x,b,data = dc.MPSK_bb(500,10,8,'src',0.35)
>>> # Matched filter received signal x
>>> | python | {
"resource": ""
} |
q257983 | QPSK_rx | validation | def QPSK_rx(fc,N_symb,Rs,EsN0=100,fs=125,lfsr_len=10,phase=0,pulse='src'):
"""
This function generates
"""
Ns = int(np.round(fs/Rs))
print('Ns = ', Ns)
print('Rs = ', fs/float(Ns))
print('EsN0 = ', EsN0, 'dB')
print('phase = ', phase, 'degrees')
print('pulse = ', pulse)
x, b, data = QPSK_bb(N_symb,Ns,lfsr_len,pulse)
| python | {
"resource": ""
} |
q257984 | rc_imp | validation | def rc_imp(Ns,alpha,M=6):
"""
A truncated raised cosine pulse used in digital communications.
The pulse shaping factor :math:`0 < \\alpha < 1` is required as well as the
truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.
Parameters
----------
Ns : number of samples per symbol
alpha : excess bandwidth factor on (0, 1), e.g., 0.35
M : equals RC one-sided symbol truncation factor
Returns
-------
b : ndarray containing the pulse shape
See Also
--------
sqrt_rc_imp
Notes
-----
The pulse shape b is typically used as the FIR filter coefficients
when forming a pulse shaped digital communications waveform.
Examples
--------
Ten samples per symbol and :math:`\\alpha = 0.35`.
>>> import matplotlib.pyplot as | python | {
"resource": ""
} |
q257985 | sqrt_rc_imp | validation | def sqrt_rc_imp(Ns,alpha,M=6):
"""
A truncated square root raised cosine pulse used in digital communications.
The pulse shaping factor :math:`0 < \\alpha < 1` is required as well as the
truncation factor M which sets the pulse duration to be :math:`2*M*T_{symbol}`.
Parameters
----------
Ns : number of samples per symbol
alpha : excess bandwidth factor on (0, 1), e.g., 0.35
M : equals RC one-sided symbol truncation factor
Returns
-------
b : ndarray containing the pulse shape
Notes
-----
The pulse shape b is typically used as the FIR filter coefficients
when forming a pulse shaped digital communications waveform. When
square root raised cosine (SRC) pulse is used to generate Tx signals and
| python | {
"resource": ""
} |
q257986 | my_psd | validation | def my_psd(x,NFFT=2**10,Fs=1):
"""
A local version of NumPy's PSD function that returns the plot arrays.
A mlab.psd wrapper function that returns two ndarrays;
makes no attempt to auto plot anything.
Parameters
----------
x : ndarray input signal
NFFT : a power of two, e.g., 2**10 = 1024
Fs : the sampling rate in Hz
Returns
-------
Px : ndarray of the power spectrum estimate
f : ndarray of frequency values
Notes
-----
This function makes it easier to overlay spectrum plots because
you have better control over the axis scaling than when using psd()
in the autoscale mode.
| python | {
"resource": ""
} |
q257987 | to_bin | validation | def to_bin(data, width):
"""
Convert an unsigned integer to a numpy binary array with the first
element the MSB and the last element the LSB.
"""
| python | {
"resource": ""
} |
q257988 | from_bin | validation | def from_bin(bin_array):
"""
Convert binary array back a nonnegative integer. The array length is
the bit width. The first input index holds the MSB and the last holds the LSB.
""" | python | {
"resource": ""
} |
q257989 | multirate_FIR.filter | validation | def filter(self,x):
"""
Filter the signal
"""
| python | {
"resource": ""
} |
q257990 | multirate_IIR.filter | validation | def filter(self,x):
"""
Filter the signal using second-order sections
"""
| python | {
"resource": ""
} |
q257991 | multirate_IIR.freq_resp | validation | def freq_resp(self, mode= 'dB', fs = 8000, ylim = [-100,2]):
"""
Frequency response plot
"""
| python | {
"resource": ""
} |
q257992 | _select_manager | validation | def _select_manager(backend_name):
"""Select the proper LockManager based on the current backend used by Celery.
:raise NotImplementedError: If Celery is using an unsupported backend.
:param str backend_name: Class name of the current Celery backend. Usually value of
current_app.extensions['celery'].celery.backend.__class__.__name__.
:return: Class definition object (not instance). One of the _LockManager* classes.
"""
if | python | {
"resource": ""
} |
q257993 | single_instance | validation | def single_instance(func=None, lock_timeout=None, include_args=False):
"""Celery task decorator. Forces the task to have only one running instance at a time.
Use with binded tasks (@celery.task(bind=True)).
Modeled after:
http://loose-bits.com/2010/10/distributed-task-locking-in-celery.html
http://blogs.it.ox.ac.uk/inapickle/2012/01/05/python-decorators-with-optional-arguments/
Written by @Robpol86.
:raise OtherInstanceError: If another instance is already running.
:param function func: The function to decorate, must be also decorated by @celery.task.
:param int lock_timeout: Lock timeout in seconds plus five more seconds, in-case the task crashes and fails to
release the lock. If not specified, the values of the task's soft/hard limits are used. If all else fails,
| python | {
"resource": ""
} |
q257994 | _LockManagerRedis.reset_lock | validation | def reset_lock(self):
"""Removed the lock regardless of timeout."""
| python | {
"resource": ""
} |
q257995 | Celery.init_app | validation | def init_app(self, app):
"""Actual method to read celery settings from app configuration and initialize the celery instance.
:param app: Flask application instance.
"""
_state._register_app = self.original_register_app # Restore Celery app registration function.
if not hasattr(app, 'extensions'):
app.extensions = dict()
if 'celery' in app.extensions:
raise ValueError('Already registered extension CELERY.')
app.extensions['celery'] = _CeleryState(self, app)
# Instantiate celery and read config.
super(Celery, self).__init__(app.import_name, broker=app.config['CELERY_BROKER_URL'])
# Set result backend default.
if 'CELERY_RESULT_BACKEND' in app.config:
self._preconf['CELERY_RESULT_BACKEND'] = app.config['CELERY_RESULT_BACKEND']
| python | {
"resource": ""
} |
q257996 | iter_chunksize | validation | def iter_chunksize(num_samples, chunksize):
"""Iterator used to iterate in chunks over an array of size `num_samples`.
At each iteration returns `chunksize` except for the last iteration.
"""
last_chunksize = int(np.mod(num_samples, chunksize))
| python | {
"resource": ""
} |
q257997 | reduce_chunk | validation | def reduce_chunk(func, array):
"""Reduce with `func`, chunk by chunk, the passed pytable `array`.
| python | {
"resource": ""
} |
q257998 | map_chunk | validation | def map_chunk(func, array, out_array):
"""Map with `func`, chunk by chunk, the input pytable `array`.
The result is stored in the output pytable array `out_array`.
"""
for slice in | python | {
"resource": ""
} |
q257999 | merge_ph_times | validation | def merge_ph_times(times_list, times_par_list, time_block):
"""Build an array of timestamps joining the arrays in `ph_times_list`.
`time_block` is the duration of each array of timestamps.
"""
offsets = np.arange(len(times_list)) * time_block
cum_sizes = np.cumsum([ts.size for ts in times_list])
times = np.zeros(cum_sizes[-1])
times_par = np.zeros(cum_sizes[-1], dtype='uint8')
i1 = 0
for i2, ts, | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.