INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
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.
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...
Setup a mask where all pixels are unmasked.
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...
Setup a mask where unmasked pixels are within a circle of an input arc second radius and centre.
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. ...
Setup a mask where unmasked pixels are within an annulus of input inner and outer arc second radii and \ centre.
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 ---------- ...
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.
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 ...
Setup a mask where unmasked pixels are within an ellipse of an input arc second major - axis and centre.
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) ...
Setup a mask where unmasked pixels are within an elliptical annulus of input inner and outer arc second \ major - axis and centre.
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...
For a 2D array ( e. g. an image noise_map etc. ) map it to a masked 1D array of valuees using this mask.
def map_2d_array_to_masked_1d_array(self, array_2d): """For a 2D array (e.g. an image, noise_map, etc.) map it to a masked 1D array of valuees using this mask. Parameters ---------- array_2d : ndarray | None | float The 2D array to be mapped to a masked 1D array. """...
Compute a blurring mask which represents all masked pixels whose light will be blurred into unmasked \ pixels via PSF convolution ( see grid_stack. RegularGrid. blurring_grid_from_mask_and_psf_shape ).
def blurring_mask_for_psf_shape(self, psf_shape): """Compute a blurring mask, which represents all masked pixels whose light will be blurred into unmasked \ pixels via PSF convolution (see grid_stack.RegularGrid.blurring_grid_from_mask_and_psf_shape). Parameters ---------- psf_s...
The zoomed rectangular region corresponding to the square encompassing all unmasked values.
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 = ...
Compute the hyper vector * D * from a blurred mapping matrix * f * and the 1D image * d * and 1D noise - map * \ sigma * \ ( see Warren & Dye 2003 ). Parameters ----------- blurred_mapping_matrix: ndarray The matrix representing the blurred mappings between sub - grid pixels and pixelization pixels. image_1d: ndarray F...
def data_vector_from_blurred_mapping_matrix_and_data(blurred_mapping_matrix, image_1d, noise_map_1d): """Compute the hyper vector *D* from a blurred mapping matrix *f* and the 1D image *d* and 1D noise-map *\sigma* \ (see Warren & Dye 2003). Parameters ----------- blurred_mapping_matrix : ndarr...
Compute the curvature matrix * F * from a blurred mapping matrix * f * and the 1D noise - map * \ sigma * \ ( see Warren & Dye 2003 ).
def curvature_matrix_from_blurred_mapping_matrix(blurred_mapping_matrix, noise_map_1d): """Compute the curvature matrix *F* from a blurred mapping matrix *f* and the 1D noise-map *\sigma* \ (see Warren & Dye 2003). Parameters ----------- blurred_mapping_matrix : ndarray The matrix represen...
Compute the curvature matrix * F * from a blurred mapping matrix * f * and the 1D noise - map * \ sigma * \ ( see Warren & Dye 2003 ).
def curvature_matrix_from_blurred_mapping_matrix_jit(blurred_mapping_matrix, noise_map_1d, flist, iflist): """Compute the curvature matrix *F* from a blurred mapping matrix *f* and the 1D noise-map *\sigma* \ (see Warren & Dye 2003). Parameters ----------- blurred_mapping_matrix : ndarray T...
Compute the reconstructed hyper vector from the blurrred mapping matrix * f * and solution vector * S *.
def reconstructed_data_vector_from_blurred_mapping_matrix_and_solution_vector(blurred_mapping_matrix, solution_vector): """ Compute the reconstructed hyper vector from the blurrred mapping matrix *f* and solution vector *S*. Parameters ----------- blurred_mapping_matrix : ndarray The matrix rep...
Compute the regularization term of an inversion. This term represents the sum of the difference in flux \ between every pair of neighboring pixels. This is computed as:
def regularization_term(self): """ Compute the regularization term of an inversion. This term represents the sum of the difference in flux \ between every pair of neighboring pixels. This is computed as: s_T * H * s = solution_vector.T * regularization_matrix * solution_vector The term...
There are two terms in the inversion s Bayesian likelihood function which require the log determinant of \ a matrix. These are ( Nightingale & Dye 2015 Nightingale Dye and Massey 2018 ):
def log_determinant_of_matrix_cholesky(matrix): """There are two terms in the inversion's Bayesian likelihood function which require the log determinant of \ a matrix. These are (Nightingale & Dye 2015, Nightingale, Dye and Massey 2018): ln[det(F + H)] = ln[det(curvature_reg_matrix)] ln...
Returns ------- light_profiles: [ light_profiles. LightProfile ] Light profiles with set variables
def constant_light_profiles(self): """ Returns ------- light_profiles: [light_profiles.LightProfile] Light profiles with set variables """ return [value for value in self.__dict__.values() if galaxy.is_light_profile(value)]
Returns ------- mass_profiles: [ mass_profiles. MassProfile ] Mass profiles with set variables
def constant_mass_profiles(self): """ Returns ------- mass_profiles: [mass_profiles.MassProfile] Mass profiles with set variables """ return [value for value in self.__dict__.values() if galaxy.is_mass_profile(value)]
Returns ------- prior_models: [ model_mapper. PriorModel ] A list of the prior models ( e. g. variable profiles ) attached to this galaxy prior
def prior_models(self): """ Returns ------- prior_models: [model_mapper.PriorModel] A list of the prior models (e.g. variable profiles) attached to this galaxy prior """ return [value for _, value in filter(lambda t: isinstance(t[1], pm.PriorMo...
Returns ------- profile_prior_model_dict: { str: PriorModel } A dictionary mapping_matrix instance variable names to variable profiles.
def profile_prior_model_dict(self): """ Returns ------- profile_prior_model_dict: {str: PriorModel} A dictionary mapping_matrix instance variable names to variable profiles. """ return {key: value for key, value in filter(lambda t: isinstance(t...
Returns ------- constant_profile_dict: { str: geometry_profiles. GeometryProfile } A dictionary mapping_matrix instance variable names to profiles with set variables.
def constant_profile_dict(self): """ Returns ------- constant_profile_dict: {str: geometry_profiles.GeometryProfile} A dictionary mapping_matrix instance variable names to profiles with set variables. """ return {key: value for key, value in self.__dict__.item...
Returns ------- prior_class_dict: { Prior: class } A dictionary mapping_matrix priors to the class associated with their prior model.
def prior_class_dict(self): """ Returns ------- prior_class_dict: {Prior: class} A dictionary mapping_matrix priors to the class associated with their prior model. """ return {prior: cls for prior_model in self.prior_models for prior, cls in pr...
Create an instance of the associated class for a set of arguments
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 ---...
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.
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...
Plot the observed image of the ccd data.
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=...
Plot the ccd data as a sub - plot of all its quantites ( e. g. the data noise_map - map PSF Signal - to_noise - map \ etc ).
def plot_ccd_subplot( ccd_data, plot_origin=True, mask=None, extract_array_from_mask=False, zoom_around_mask=False, should_plot_border=False, positions=None, units='arcsec', kpc_per_arcsec=None, figsize=None, aspect='square', cmap='jet', norm='linear', norm_min=None, norm_max=None, linth...
Plot each attribute of the ccd data as individual figures one by one ( e. g. the data noise_map - map PSF \ Signal - to_noise - map etc ).
def plot_ccd_individual( ccd_data, plot_origin=True, mask=None, extract_array_from_mask=False, zoom_around_mask=False, positions=None, should_plot_image=False, should_plot_noise_map=False, should_plot_psf=False, should_plot_signal_to_noise_map=False, should_plot_absolute_...
Normalise and check a backend path.
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): ...
Test if a file is located within the given directory.
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
Find and load the build backend
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...
Invoke the mandatory build_sdist hook.
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...
Print errors. Stop travis - ci from leaking api keys: param e: The error: return: None
def log_error(self, e): """ Print errors. Stop travis-ci from leaking api keys :param e: The error :return: None """ if not environ.get('CI'): self.log_function(e) if hasattr(e, 'response') and hasattr(e.response, 'text'): ...
Sleep between requests but don t force asynchronous code to wait: param seconds: The number of seconds to sleep: return: None
def _sleep(self, seconds): """ Sleep between requests, but don't force asynchronous code to wait :param seconds: The number of seconds to sleep :return: None """ for _ in range(int(seconds)): if not self.force_stop: sleep(1)
An interface for get requests that handles errors more gracefully to prevent data loss
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...
: param node:: param edge:: param fields:: param params:: return:
def node_edge(self, node, edge, fields=None, params=None): """ :param node: :param edge: :param fields: :param params: :return: """ if fields: fields = ",".join(fields) parameters = {"fields": fields, ...
: param post_id:: param fields:: param params:: return:
def post(self, post_id, fields=None, **params): """ :param post_id: :param fields: :param params: :return: """ if fields: fields = ",".join(fields) parameters = {"fields": fields, "access_token": self.key} ...
: param page_id:: param after:: param post_type: Can be posts feed tagged promotable_posts: param include_hidden:: param fields:: param params:: return:
def page_posts(self, page_id, after='', post_type="posts", include_hidden=False, fields=None, **params): """ :param page_id: :param after: :param post_type: Can be 'posts', 'feed', 'tagged', 'promotable_posts' :param include_hidden: :param fi...
: param post_id:: param after:: param order: Can be ranked chronological reverse_chronological: param filter: Can be stream toplevel: param fields: Can be id application attachment can_comment can_remove can_hide can_like can_reply_privately comments comment_count created_time from likes like_count live_broadcast_times...
def post_comments(self, post_id, after='', order="chronological", filter="stream", fields=None, **params): """ :param post_id: :param after: :param order: Can be 'ranked', 'chronological', 'reverse_chronological' :param filter: Can be 'stream', 'to...
Turn a nested dictionary into a flattened dictionary: param dictionary: The dictionary to flatten: param parent_key: The string to prepend to dictionary s keys: param separator: The string used to separate flattened keys: return: A flattened dictionary
def flatten(dictionary, parent_key=False, separator='.'): """ Turn a nested dictionary into a flattened dictionary :param dictionary: The dictionary to flatten :param parent_key: The string to prepend to dictionary's keys :param separator: The string used to separate flattened keys :retu...
Fill gaps in a list of dictionaries. Add empty keys to dictionaries in the list that don t contain other entries keys: param list_dicts: A list of dictionaries: return: A list of field names a list of dictionaries with identical keys
def fill_gaps(list_dicts): """ Fill gaps in a list of dictionaries. Add empty keys to dictionaries in the list that don't contain other entries' keys :param list_dicts: A list of dictionaries :return: A list of field names, a list of dictionaries with identical keys """ field_name...
DEPRECATED Write a list of dicts to a csv file: param data: List of dicts: param field_names: The list column names: param filename: The name of the file: param overwrite: Overwrite the file if exists: param write_headers: Write the headers to the csv file: param append: Write new rows if the file exists: param flat: F...
def to_csv(data, field_names=None, filename='data.csv', overwrite=True, write_headers=True, append=False, flat=True, primary_fields=None, sort_fields=True): """ DEPRECATED Write a list of dicts to a csv file :param data: List of dicts :param field_names: The ...
Write an object to a json file: param data: The object: param filename: The name of the file: param indent: The indentation of the file: return: None
def to_json(data, filename='data.json', indent=4): """ Write an object to a json file :param data: The object :param filename: The name of the file :param indent: The indentation of the file :return: None """ with open(filename, 'w') as f: f.write(json.dumps(data, in...
Download and save a file at path: param filename: The name of the file: param source: The location of the resource online: param folder: The directory the file will be saved in: return: None
def save_file(filename, source, folder="Downloads"): """ Download and save a file at path :param filename: The name of the file :param source: The location of the resource online :param folder: The directory the file will be saved in :return: None """ r = requests.get(source,...
Try to convert a tar file containing a sequence of frames saved by the meshcat viewer into a single video file.
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....
Get a json dict of the attributes of this object.
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}
Convenience method to create a file from a string.
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...
Convience method to create a kappa file object from a file on disk
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...
Make api method docs inheritted.
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)...
Add a kappa model given in a string to the project.
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, ...
Add a kappa model from a file at given path to the project.
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, ...
Set the simulation default simulation parameters.
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...
Check if the current simulation is running.
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...
Block until the simulation is done or timeout seconds exceeded.
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...
Display available input and output audio devices along with their port indices.: return: Dictionary whose keys are the device index the number of inputs and outputs and their names.: rtype: dict
def available_devices(): """ Display available input and output audio devices along with their port indices. :return: Dictionary whose keys are the device index, the number of inputs and outputs, and their names. :rtype: dict """ devices = {} pA = pyaudio.PyAudio() device...
Checks the input and output to see if they are valid
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...
Stream audio with start and stop radio buttons Interactive stream is designed for streaming audio through this object using a callback function. This stream is threaded so it can be used with ipywidgets. Click on the Start Streaming button to start streaming and click on Stop Streaming button to stop streaming. Paramet...
def interactive_stream(self,Tsec = 2, numChan = 1): """ Stream audio with start and stop radio buttons Interactive stream is designed for streaming audio through this object using a callback function. This stream is threaded, so it can be used with ipywidgets. Clic...
Stream audio in a thread using callback. The stream is threaded so widgets can be used simultaneously during stream. Parameters ---------- Tsec: stream time in seconds if Tsec > 0. If Tsec = 0 then stream goes to infinite mode. When in infinite mode Tsec. stop () can be used to stop the stream. numChan: number of chann...
def thread_stream(self,Tsec = 2,numChan = 1): """ Stream audio in a thread using callback. The stream is threaded, so widgets can be used simultaneously during stream. Parameters ---------- Tsec : stream time in seconds if Tsec > 0. If Tsec = 0, then stream goes...
Stream audio using callback Parameters ---------- Tsec: stream time in seconds if Tsec > 0. If Tsec = 0 then stream goes to infinite mode. When in infinite mode Tsec. stop () can be used to stop the stream. numChan: number of channels. Use 1 for mono and 2 for stereo.
def stream(self,Tsec = 2,numChan = 1): """ Stream audio using callback Parameters ---------- Tsec : stream time in seconds if Tsec > 0. If Tsec = 0, then stream goes to infinite mode. When in infinite mode, Tsec.stop() can be used to stop the stream. ...
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.
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. ...
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.
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 ...
Add new tic time to the DSP_tic list. Will not be called if Tcapture = 0.
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)
Add new toc time to the DSP_toc list. Will not be called if Tcapture = 0.
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)
Display basic statistics of callback execution: ideal period between callbacks average measured period between callbacks and average time spent in the callback.
def stream_stats(self): """ Display basic statistics of callback execution: ideal period between callbacks, average measured period between callbacks, and average time spent in the callback. """ Tp = self.frame_length/float(self.fs)*1000 print('D...
Plot timing information of time spent in the callback. This is similar to what a logic analyzer provides when probing an interrupt. cb_active_plot ( start_ms stop_ms line_color = b )
def cb_active_plot(self,start_ms,stop_ms,line_color='b'): """ Plot timing information of time spent in the callback. This is similar to what a logic analyzer provides when probing an interrupt. cb_active_plot( start_ms,stop_ms,line_color='b') """ # Find ...
Splits incoming packed stereo data into separate left and right channels and returns an array of left samples and an array of right samples Parameters ---------- in_data: input data from the streaming object in the callback function. Returns ------- left_in: array of incoming left channel samples right_in: array of inc...
def get_LR(self,in_data): """ Splits incoming packed stereo data into separate left and right channels and returns an array of left samples and an array of right samples Parameters ---------- in_data : input data from the streaming object in the callback f...
Packs separate left and right channel data into one array to output and returns the output. Parameters ---------- left_out: left channel array of samples going to output right_out: right channel array of samples going to output Returns ------- out: packed left and right channel array of samples
def pack_LR(self,left_out,right_out): """ Packs separate left and right channel data into one array to output and returns the output. Parameters ---------- left_out : left channel array of samples going to output right_out : right channel array of samples...
Design an IIR lowpass 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. Parameters ---------- f_pass: Passband critical frequency in Hz f_stop: Stopband critical frequency in Hz R...
def IIR_lpf(f_pass, f_stop, Ripple_pass, Atten_stop, fs = 1.00, ftype = 'butter'): """ Design an IIR lowpass 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 sa...
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
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,...
A method for displaying digital filter frequency response magnitude phase and group delay. A plot is produced using matplotlib freq_resp ( self mode = dB Npts = 1024 ) A method for displaying the filter frequency response magnitude phase and group delay. A plot is produced using matplotlib freqz_resp ( b a = [ 1 ] mode...
def freqz_resp_list(b,a=np.array([1]),mode = 'dB',fs=1.0,Npts = 1024,fsize=(6,4)): """ A method for displaying digital filter frequency response magnitude, phase, and group delay. A plot is produced using matplotlib freq_resp(self,mode = 'dB',Npts = 1024) A method for displaying the filter ...
Cascade frequency response Mark Wickert October 2016
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
The average of the root values is used when multiplicity is greater than one. Mark Wickert October 2016
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)...
Create an z - plane pole - zero plot. Create an z - plane pole - zero plot using the numerator and denominator z - domain system function coefficient ndarrays b and a respectively. Assume descending powers of z. Parameters ---------- sos: ndarray of the sos coefficients auto_scale: bool ( default True ) size: plot radi...
def sos_zplane(sos,auto_scale=True,size=2,tol = 0.001): """ Create an z-plane pole-zero plot. Create an z-plane pole-zero plot using the numerator and denominator z-domain system function coefficient ndarrays b and a respectively. Assume descending powers of z. Parameters --------...
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
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_...
Design an FIR lowpass filter using the sinc () kernel and a Kaiser window. 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. Note: the passband ripple cannot be set independent of the stopband attenuation. Mark Wickert...
def firwin_kaiser_lpf(f_pass, f_stop, d_stop, fs = 1.0, N_bump=0): """ Design an FIR lowpass filter using the sinc() kernel and a Kaiser window. 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 f...
Design an FIR bandpass filter using the sinc () kernel and a Kaiser window. The filter order is determined based on f_stop1 Hz f_pass1 Hz f_pass2 Hz f_stop2 Hz and the desired stopband attenuation d_stop in dB for both stopbands all relative to a sampling rate of fs Hz. Note: the passband ripple cannot be set independe...
def firwin_kaiser_bpf(f_stop1, f_pass1, f_pass2, f_stop2, d_stop, fs = 1.0, N_bump=0): """ Design an FIR bandpass filter using the sinc() kernel and a Kaiser window. The filter order is determined based on f_stop1 Hz, f_pass1 Hz, f_pass2 Hz, f_stop2 Hz, and the desired...
Optimal FIR ( equal ripple ) Lowpass Order Determination Text reference: Ifeachor Digital Signal Processing a Practical Approach second edition Prentice Hall 2002. Journal paper reference: Herriman et al. Practical Design Rules for Optimum Finite Imulse Response Digitl Filters Bell Syst. Tech. J. vol 52 pp. 769 - 799 J...
def lowpass_order(f_pass, f_stop, dpass_dB, dstop_dB, fsamp = 1): """ Optimal FIR (equal ripple) Lowpass Order Determination Text reference: Ifeachor, Digital Signal Processing a Practical Approach, second edition, Prentice Hall, 2002. Journal paper reference: Herriman et al., Practical ...
Optimal FIR ( equal ripple ) Bandpass Order Determination Text reference: Ifeachor Digital Signal Processing a Practical Approach second edition Prentice Hall 2002. Journal paper reference: F. Mintzer & B. Liu Practical Design Rules for Optimum FIR Bandpass Digital Filters IEEE Transactions on Acoustics and Speech pp. ...
def bandpass_order(f_stop1, f_pass1, f_pass2, f_stop2, dpass_dB, dstop_dB, fsamp = 1): """ Optimal FIR (equal ripple) Bandpass Order Determination Text reference: Ifeachor, Digital Signal Processing a Practical Approach, second edition, Prentice Hall, 2002. Journal paper reference: F. Mi...
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
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...
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
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...
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
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...
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
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...
A functional form implementation of a cascade of integrator comb ( CIC ) filters.
def CIC(M, K): """ A functional form implementation of a cascade of integrator comb (CIC) filters. Parameters ---------- M : Effective number of taps per section (typically the decimation factor). K : The number of CIC sections cascaded (larger K gives the filter a wider image rejection bandwid...
Filter the input signal x with a ten - band equalizer having octave gain values in ndarray GdB. The signal x is filtered using octave - spaced peaking filters starting at 31. 25 Hz and stopping at 16 kHz. The Q of each filter is 3. 5 but can be changed. The sampling rate is assumed to be 44. 1 kHz. Parameters ---------...
def ten_band_eq_filt(x,GdB,Q=3.5): """ Filter the input signal x with a ten-band equalizer having octave gain values in ndarray GdB. The signal x is filtered using octave-spaced peaking filters starting at 31.25 Hz and stopping at 16 kHz. The Q of each filter is 3.5, but can be changed. The samplin...
Create a frequency response magnitude plot in dB of a ten band equalizer using a semilogplot ( semilogx () ) type plot Parameters ---------- GdB: Gain vector for 10 peaking filters [ G0... G9 ] Q: Quality factor for each peaking filter ( default 3. 5 ) Returns ------- Nothing: two plots are created Examples -------- >>...
def ten_band_eq_resp(GdB,Q=3.5): """ Create a frequency response magnitude plot in dB of a ten band equalizer using a semilogplot (semilogx()) type plot Parameters ---------- GdB : Gain vector for 10 peaking filters [G0,...,G9] Q : Quality factor for each peaking filter (default 3....
A second - order peaking filter having GdB gain at fc and approximately and 0 dB otherwise. The filter coefficients returns correspond to a biquadratic system function containing five parameters. Parameters ---------- GdB: Lowpass gain in dB fc: Center frequency in Hz Q: Filter Q which is inversely proportional to band...
def peaking(GdB, fc, Q=3.5, fs=44100.): """ A second-order peaking filter having GdB gain at fc and approximately and 0 dB otherwise. The filter coefficients returns correspond to a biquadratic system function containing five parameters. Parameters ---------- GdB : Lowpass gain...
Generate a triangle pulse as described in Example 6 - 2 of Chapter 6. You need to supply an index array n that covers at least [ - 2 5 ]. The function returns the hard - coded signal of the example. Parameters ---------- n: time index ndarray covering at least - 2 to + 5. Returns ------- x: ndarray of signal samples in...
def ex6_2(n): """ Generate a triangle pulse as described in Example 6-2 of Chapter 6. You need to supply an index array n that covers at least [-2, 5]. The function returns the hard-coded signal of the example. Parameters ---------- n : time index ndarray covering at least -2 ...
CD sled position control case study of Chapter 18.
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...
Cruise control with PI controller and hill disturbance.
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...
Create an s - plane pole - zero plot. As input the function uses the numerator and denominator s - domain system function coefficient ndarrays b and a respectively. Assumed to be stored in descending powers of s. Parameters ---------- b: numerator coefficient ndarray. a: denominator coefficient ndarray. auto_scale: Tru...
def splane(b,a,auto_scale=True,size=[-1,1,-1,1]): """ Create an s-plane pole-zero plot. As input the function uses the numerator and denominator s-domain system function coefficient ndarrays b and a respectively. Assumed to be stored in descending powers of s. Parameters --------...
Overlap and save transform domain FIR filtering. This function implements the classical overlap and save method of transform domain filtering using a length P FIR filter. Parameters ---------- x: input signal to be filtered as an ndarray h: FIR filter coefficients as an ndarray of length P N: FFT size > P typically a p...
def OS_filter(x,h,N,mode=0): """ Overlap and save transform domain FIR filtering. This function implements the classical overlap and save method of transform domain filtering using a length P FIR filter. Parameters ---------- x : input signal to be filtered as an ndarray h : FI...
Lowpass sampling theorem plotting function. Display the spectrum of a sampled signal after setting the bandwidth sampling frequency maximum display frequency and spectral shape. Parameters ---------- fb: spectrum lowpass bandwidth in Hz fs: sampling frequency in Hz fmax: plot over [ - fmax fmax ] shape: tri or line N: ...
def lp_samp(fb,fs,fmax,N,shape='tri',fsize=(6,4)): """ Lowpass sampling theorem plotting function. Display the spectrum of a sampled signal after setting the bandwidth, sampling frequency, maximum display frequency, and spectral shape. Parameters ---------- fb : spectrum lowpass b...
Triangle spectral shape function used by: func: lp_samp.
def lp_tri(f, fb): """ Triangle spectral shape function used by :func:`lp_samp`. Parameters ---------- f : ndarray containing frequency samples fb : the bandwidth as a float constant Returns ------- x : ndarray of spectrum samples for a single triangle shape Notes ----...
Add white Gaussian noise to a single real sinusoid. Input a single sinusoid to this function and it returns a noisy sinusoid at a specific SNR value in dB. Sinusoid power is calculated using np. var. Parameters ---------- x: Input signal as ndarray consisting of a single sinusoid SNRdB: SNR in dB for output sinusoid Re...
def sinusoidAWGN(x,SNRdB): """ Add white Gaussian noise to a single real sinusoid. Input a single sinusoid to this function and it returns a noisy sinusoid at a specific SNR value in dB. Sinusoid power is calculated using np.var. Parameters ---------- x : Input signal as ndarra...
function disdata = discrim ( x ) where x is an angle modulated signal in complex baseband form. Mark Wickert
def discrim(x): """ function disdata = discrim(x) where x is an angle modulated signal in complex baseband form. Mark Wickert """ X=np.real(x) # X is the real part of the received signal Y=np.imag(x) # Y is the imaginary part of the received signal b=np.array(...
Decimate complex baseband input by 10 Design 1st decimation lowpass filter ( f_c = 200 KHz )
def mono_FM(x,fs=2.4e6,file_name='test.wav'): """ Decimate complex baseband input by 10 Design 1st decimation lowpass filter (f_c = 200 KHz) """ b = signal.firwin(64,2*200e3/float(fs)) # Filter and decimate (should be polyphase) y = signal.lfilter(b,1,x) z = ss.downsample(y,10) ...
Stereo demod from complex baseband at sampling rate fs. Assume fs is 2400 ksps Mark Wickert July 2017
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(...
theta phi_error = pilot_PLL ( xr fq fs loop_type Bn zeta ) Mark Wickert April 2014
def pilot_PLL(xr,fq,fs,loop_type,Bn,zeta): """ theta, phi_error = pilot_PLL(xr,fq,fs,loop_type,Bn,zeta) Mark Wickert, April 2014 """ T = 1/float(fs) # Set the VCO gain in Hz/V Kv = 1.0 # Design a lowpass filter to remove the double freq term Norder = 5 b_lp,a_lp...
rx_symb_d clk track = sccs_bit_sync ( y Ns )////////////////////////////////////////////////////// Symbol synchronization algorithm using SCCS////////////////////////////////////////////////////// y = baseband NRZ data waveform Ns = nominal number of samples per symbol Reworked from ECE 5675 Project Translated from m -...
def sccs_bit_sync(y,Ns): """ rx_symb_d,clk,track = sccs_bit_sync(y,Ns) ////////////////////////////////////////////////////// Symbol synchronization algorithm using SCCS ////////////////////////////////////////////////////// y = baseband NRZ data waveform Ns = nominal numb...
fsk_BEP ( rx_data m flip ) Estimate the BEP of the data bits recovered by the RTL - SDR Based FSK Receiver. The reference m - sequence generated in Python was found to produce sequences running in the opposite direction relative to the m - sequences generated by the mbed. To allow error detection the reference m - sequ...
def fsk_BEP(rx_data,m,flip): """ fsk_BEP(rx_data,m,flip) Estimate the BEP of the data bits recovered by the RTL-SDR Based FSK Receiver. The reference m-sequence generated in Python was found to produce sequences running in the opposite direction relative to the m-sequence...
Save a complex signal vector to a wav file for compact binary storage of 16 - bit signal samples. The wav left and right channels are used to save real ( I ) and imaginary ( Q ) values. The rate is just a convent way of documenting the original signal sample rate. complex2wav ( filename rate x ) Mark Wickert April 2014
def complex2wav(filename,rate,x): """ Save a complex signal vector to a wav file for compact binary storage of 16-bit signal samples. The wav left and right channels are used to save real (I) and imaginary (Q) values. The rate is just a convent way of documenting the original signal sample rate...