_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | 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 \
... | 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 \
o... | 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 \
o... | 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 ... | 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 ... | 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 ga... | 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 extrac... | 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, ... | 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 con... | 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.LensDa... | 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 coo... | 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 ... | 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. """
phi_radians = np.radians(self.phi)
return np.cos(phi_radians), np.sin(phi_radians) | 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 re... | 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 reg... | 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... | 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 pr... | 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 p... | 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 the luminosity within a circle"""
r = x * axis_ratio
return 2 * np.pi * r * self.intensities_from_grid_radii(x) | 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.
... | 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.
... | 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 de... | 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... | 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_... | 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_m... | 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):
return grid - deflections
return self.grid_stack.map_function(minus, self.deflection_stack) | 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 \
"""
return np.linspace(np.amin(self.grid_stack.regular[:, 0]), np.amax(self.grid_stack.regular[:, 0]), 4) | 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"""
return np.linspace(np.amin(self.grid_stack.regular[:, 1]), np.amax(self.grid_stack.regular[:, 1]), 4) | 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
----------
padded_grid_sta... | 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, deflections),
self.positions, self.deflections)) | 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 o... | 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
----------
... | 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... | 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... | 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 pix... | 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.
... | 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
----------
... | 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 ... | 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)
... | 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 ell... | 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
---... | 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_mat... | 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=... | 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):
... | python | {
"resource": ""
} |
q257947 | contained_in | validation | def contained_in(filename, directory):
"""Test if a file is located within the given directory."""
filename = os.path.normcase(os.path.abspath(filename))
directory = os.path.normcase(os.path.abspath(directory))
return os.path.commonprefix([filename, directory]) == directory | 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.envir... | python | {
"resource": ""
} |
q257949 | build_sdist | validation | def build_sdist(sdist_directory, config_settings):
"""Invoke the mandatory build_sdist hook."""
backend = _build_backend()
try:
return backend.build_sdist(sdist_directory, config_settings)
except getattr(backend, 'UnsupportedOperation', _DummyException):
raise GotUnsupportedOperation(tra... | 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.ra... | 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.... | python | {
"resource": ""
} |
q257952 | FileMetadata.toJSON | validation | def toJSON(self):
"""Get a json dict of the attributes of this object."""
return {"id": self.id,
"compile": self.compile,
"position": self.position,
"version": self.version} | 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) ran... | 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 FileMetadat... | 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)... | 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')
ret_data = self.file_create(File.from_string(model_str, position,
... | 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')
ret_data = self.file_create(File.from_file(model_fpath, position,
... | 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 s... | 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']
ret = progress_info['simulation_progress_is_running']
except KeyError: # Simulation has not... | 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 = datetime.now()
while self.get_is_sim_running():
sleep(0.5)
if tim... | 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... | 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.
... | 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 ... | 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.
"""
if self.Tcapture > 0:
self.DSP_tic.append(time.time()-self.start_time) | 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 if
Tcapture = 0.
"""
if self.Tcapture > 0:
self.DSP_toc.append(time.time()-self.start_time) | 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,... | 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):
w,Htemp = signal.freqz(sos[k,:3],sos[k,3:],w)
Hcas *= Htemp
return w, Hcas | 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)... | 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 number of taps must be provided.
Mark Wickert October 2016
"""
return signal.firwin(N_... | 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
rel... | 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
re... | 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 passba... | 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 passba... | 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 f... | 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
li... | 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(... | 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 ... | 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.writ... | 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 C... | 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 da... | 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 : nd... | 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... | 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, dat... | 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 sam... | 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
----------... | 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 = 10... | 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.
"""
data_str = bin(data & (2**width-1))[2:].zfill(width)
return [int(x) for x in tuple(data_str)] | 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.
"""
width = len(bin_array)
bin_wgts = 2**np.arange(width-1,-1,-1)
return int(np.dot(bin_array,bin_wgts)) | python | {
"resource": ""
} |
q257989 | multirate_FIR.filter | validation | def filter(self,x):
"""
Filter the signal
"""
y = signal.lfilter(self.b,[1],x)
return y | python | {
"resource": ""
} |
q257990 | multirate_IIR.filter | validation | def filter(self,x):
"""
Filter the signal using second-order sections
"""
y = signal.sosfilt(self.sos,x)
return y | python | {
"resource": ""
} |
q257991 | multirate_IIR.freq_resp | validation | def freq_resp(self, mode= 'dB', fs = 8000, ylim = [-100,2]):
"""
Frequency response plot
"""
iir_d.freqz_resp_cas_list([self.sos],mode,fs=fs)
pylab.grid()
pylab.ylim(ylim) | 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... | 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:/... | python | {
"resource": ""
} |
q257994 | _LockManagerRedis.reset_lock | validation | def reset_lock(self):
"""Removed the lock regardless of timeout."""
redis_key = self.CELERY_LOCK.format(task_id=self.task_identifier)
self.celery_self.backend.client.delete(redis_key) | 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(... | 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))
chunksize = int(chunksize)
for _ in range(int(num_s... | python | {
"resource": ""
} |
q257997 | reduce_chunk | validation | def reduce_chunk(func, array):
"""Reduce with `func`, chunk by chunk, the passed pytable `array`.
"""
res = []
for slice in iter_chunk_slice(array.shape[-1], array.chunkshape[-1]):
res.append(func(array[..., slice]))
return func(res) | 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 iter_chunk_slice(array.shape[-1], array.chunkshape[-1]):
out_array.append(func(array[..., slice]))
return out_a... | 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])
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.