docstring
stringlengths
52
499
function
stringlengths
67
35.2k
__index_level_0__
int64
52.6k
1.16M
Upgrade or degrade resolution of a pixel list. Parameters: ----------- ipix:array-like the input pixel(s) nside_in:int the nside of the input pixel(s) nside_out:int the desired nside of the output pixel(s) order:str pixel ordering of input and output ("RING" or "NESTED") ...
def ud_grade_ipix(ipix, nside_in, nside_out, nest=False): if nside_in == nside_out: return ipix elif nside_in < nside_out: return u_grade_ipix(ipix, nside_in, nside_out, nest) elif nside_in > nside_out: return d_grade_ipix(ipix, nside_in, nside_out, nest)
848,389
Check if (lon,lat) in pixel list. Assumes RING formatting. Parameters: ----------- lon : longitude (deg) lat : latitude (deg) pixels : pixel list [RING format] to check for inclusion nside : nside of pixel list Returns: -------- inpix : boolean array for inclusion
def in_pixels(lon,lat,pixels,nside): pix = ang2pix(nside,lon,lat) return np.in1d(pix,pixels)
848,395
Find the indices of a set of pixels into another set of pixels. !!! ASSUMES SORTED PIXELS !!! Parameters: ----------- pix : set of search pixels pixels : set of reference pixels Returns: -------- index : index into the reference pixels
def index_pix_in_pixels(pix,pixels,sort=False,outside=-1): # ADW: Not really safe to set index = -1 (accesses last entry); # -np.inf would be better, but breaks other code... # ADW: Are the pixels always sorted? Is there a quick way to check? if sort: pixels = np.sort(pixels) # Assumes that ...
848,396
Find the indices of a set of angles into a set of pixels Parameters: ----------- pix : set of search pixels pixels : set of reference pixels Returns: -------- index : index into the reference pixels
def index_lonlat_in_pixels(lon,lat,pixels,nside,sort=False,outside=-1): pix = ang2pix(nside,lon,lat) return index_pix_in_pixels(pix,pixels,sort,outside)
848,397
Read a partial HEALPix file(s) and return pixels and values/map. Can handle 3D healpix maps (pix, value, zdim). Returned array has shape (dimz,npix). Parameters: ----------- filenames : list of input filenames column : column of interest fullsky : partial or fullsky map ...
def read_partial_map(filenames, column, fullsky=True, **kwargs): # Make sure that PIXEL is in columns #kwargs['columns'] = ['PIXEL',column] kwargs['columns'] = ['PIXEL'] + np.atleast_1d(column).tolist() filenames = np.atleast_1d(filenames) header = fitsio.read_header(filenames[0],ext=kwargs.ge...
848,402
Merge header information from likelihood files. Parameters: ----------- filenames : input filenames oufile : the merged file to write Returns: -------- data : the data being written
def merge_likelihood_headers(filenames, outfile): filenames = np.atleast_1d(filenames) ext='PIX_DATA' nside = fitsio.read_header(filenames[0],ext=ext)['LKDNSIDE'] keys=['STELLAR','NINSIDE','NANNULUS'] data_dict = odict(PIXEL=[]) for k in keys: data_dict[k] = [] for i,fil...
848,404
Extends the reservation on this cart by the given timedelta. This can only be done if the current state of the cart is valid (i.e all items and discounts in the cart are still available.) Arguments: timedelta (timedelta): The amount of time to extend the cart by. The...
def extend_reservation(self, timedelta): self.validate_cart() cart = self.cart cart.refresh_from_db() elapsed = (timezone.now() - cart.time_last_updated) if cart.reservation_duration - elapsed > timedelta: return cart.time_last_updated = timezone....
848,411
Decorator that converts a report view function into something that displays a Report. Arguments: title (str): The title of the report. form_type (Optional[forms.Form]): A form class that can make this report display things. If not supplied, no form will be di...
def report_view(title, form_type=None): # Create & return view def _report(view): report_view = ReportView(view, title, form_type) report_view = user_passes_test(views._staff_only)(report_view) report_view = wraps(view)(report_view) # Add this report to the list of reports...
848,452
Renders the reports based on data.content_type's value. Arguments: data (ReportViewRequestData): The report data. data.content_type is used to determine how the reports are rendered. Returns: HTTPResponse: The rendered version of the report.
def render(self, data): renderers = { "text/csv": self._render_as_csv, "text/html": self._render_as_html, None: self._render_as_html, } render = renderers[data.content_type] return render(data)
848,468
Marks an invoice as refunded and requests a credit note for the full amount paid against the invoice. This view requires a login, and the logged in user must be staff. Arguments: invoice_id (castable to int): The ID of the invoice to refund. Returns: redirect: Redirects to...
def refund(request, invoice_id): current_invoice = InvoiceController.for_id_or_404(invoice_id) try: current_invoice.refund() messages.success(request, "This invoice has been refunded.") except ValidationError as ve: messages.error(request, ve) return redirect("invoice", i...
848,864
Server query for the isochrone file. Parameters: ----------- outfile : name of output isochrone file age : isochrone age metallicity : isochrone metallicity Returns: -------- outfile : name of output isochrone file
def query_server(self,outfile,age,metallicity): params = copy.deepcopy(self.download_defaults) epsilon = 1e-4 lage = np.log10(age*1e9) lage_min,lage_max = params['isoc_lage0'],params['isoc_lage1'] if not (lage_min-epsilon < lage <lage_max+epsilon): msg = 'Ag...
849,134
Object to efficiently search over a grid of ROI positions. Parameters: ----------- config : Configuration object or filename. loglike : Log-likelihood object Returns: -------- grid : GridSearch instance
def __init__(self, config, loglike): # What it should be... self.config = Config(config) self.loglike = loglike self.roi = self.loglike.roi self.mask = self.loglike.mask logger.info(str(self.loglike)) self.stellar_mass_conversion = self.loglike.source.stellar...
849,139
DEPRECATED: ADW 20170627 Precompute color probabilities for background ('u_background') and signal ('u_color') for each star in catalog. Precompute observable fraction in each ROI pixel. # Precompute still operates over the full ROI, not just the likelihood region Parameters:...
def precompute(self, distance_modulus_array=None): msg = "'%s.precompute': ADW 2017-09-20"%self.__class__.__name__ DeprecationWarning(msg) if distance_modulus_array is not None: self.distance_modulus_array = distance_modulus_array else: self.distance_mod...
849,140
Identify peak using Gaussian kernel density estimator. Parameters: ----------- data : The 1d data sample npoints : The number of kde points to evaluate
def kde(data, npoints=_npoints): # Clipping of severe outliers to concentrate more KDE samples in the parameter range of interest mad = np.median(np.fabs(np.median(data) - data)) cut = (data > np.median(data) - 5. * mad) & (data < np.median(data) + 5. * mad) x = data[cut] kde = scipy.stats.gaus...
849,184
Produces a callable so that functions can be lazily evaluated in templates. Arguments: function (callable): The function to call at evaluation time. args: Positional arguments, passed directly to ``function``. kwargs: Keyword arguments, passed directly to ``function``. Return: ...
def lazy(function, *args, **kwargs): NOT_EVALUATED = object() retval = [NOT_EVALUATED] def evaluate(): if retval[0] is NOT_EVALUATED: retval[0] = function(*args, **kwargs) return retval[0] return evaluate
849,310
Returns the named object. Arguments: name (str): A string of form `package.subpackage.etc.module.property`. This function will import `package.subpackage.etc.module` and return `property` from that module.
def get_object_from_name(name): dot = name.rindex(".") mod_name, property_name = name[:dot], name[dot + 1:] __import__(mod_name) return getattr(sys.modules[mod_name], property_name)
849,311
Break catalog into chunks by healpix pixel. Parameters: ----------- infiles : List of input files config : Configuration file force : Overwrite existing files (depricated) Returns: -------- None
def pixelizeCatalog(infiles, config, force=False): nside_catalog = config['coords']['nside_catalog'] nside_pixel = config['coords']['nside_pixel'] coordsys = config['coords']['coordsys'].upper() outdir = mkdir(config['catalog']['dirname']) filenames = config.getFilenames() lon_field = confi...
849,364
Get flow direction induced cell length dict. Args: flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported.
def get_cell_length(flow_model): assert flow_model.lower() in FlowModelConst.d8_lens return FlowModelConst.d8_lens.get(flow_model.lower())
849,431
Get flow direction induced cell shift dict. Args: flow_model: Currently, "TauDEM", "ArcGIS", and "Whitebox" are supported.
def get_cell_shift(flow_model): assert flow_model.lower() in FlowModelConst.d8_deltas return FlowModelConst.d8_deltas.get(flow_model.lower())
849,432
convert D8 flow direction code from one algorithm to another. Args: in_file: input raster file path out_file: output raster file path in_alg: available algorithms are in FlowModelConst.d8_dirs. "taudem" is the default out_alg: same as in_alg. "arcgis" is the defau...
def convert_code(in_file, out_file, in_alg='taudem', out_alg='arcgis', datatype=None): FileClass.check_file_exists(in_file) in_alg = in_alg.lower() out_alg = out_alg.lower() if in_alg not in FlowModelConst.d8_dirs or out_alg not in FlowModelConst.d8_dirs: raise Runti...
849,434
checks if name has been changed and ignores the name change if the changed_item is an existing script Args: changed_item:
def name_changed(self, changed_item): name = str(changed_item.text()) # if the item has been moved we ignore this because the item only went from one tree to the other without changing names if name != '': if name != self.selected_element_name: self.elements...
849,454
fills a tree with nested parameters Args: tree: QtGui.QTreeView parameters: dictionary or Parameter object Returns:
def fill_tree(self, tree, input_dict): def add_element(item, key, value): child_name = QtGui.QStandardItem(key) child_name.setDragEnabled(False) child_name.setSelectable(False) child_name.setEditable(False) if isinstance(value, dict): ...
849,458
Parse .ped formatted family info. Add all family info to the parser object Arguments: family_info (iterator): An iterator with family info
def ped_parser(self, family_info): for line in family_info: # Check if commented line or empty line: if not line.startswith('#') and not all(c in whitespace for c in line.rstrip()): splitted_line = line.rstrip().split('\t') if len(splitte...
849,470
Parse alternative formatted family info This parses a information with more than six columns. For alternative information header comlumn must exist and each row must have the same amount of columns as the header. First six columns must be the same as in the ped format. ...
def alternative_parser(self, family_file): alternative_header = None for line in family_file: if line.startswith('#'): alternative_header = line[1:].rstrip().split('\t') self.logger.info("Alternative header found: {0}".format(line)) ...
849,471
Check if the affection status is correct. Args: ind_object : An Individuals object Yields: bool : True if affection status is correct False otherwise
def check_cmms_affection_status(self, ind_object): valid_affection_statuses = ['A', 'U', 'X'] ind_id = ind_object.individual_id.split('-') phenotype = ind_object.phenotype affection_status = ind_id[-1][-1] if affection_status not in valid_affection_statuses: ...
849,473
Check if the phenotype is correct. Args: ind_object : An Individuals object Yields: bool : True if phenotype status is correct False otherwise
def check_cmms_gender(self, ind_object): ind_id = ind_object.individual_id.split('-') sex = ind_object.sex sex_code = int(ind_id[-1][:-1])# Males allways have odd numbers and womans even if (sex_code % 2 == 0 and sex != 2) or (sex_code % 2 != 0 and sex != 1): raise W...
849,474
Check what genetic models that are found and return them as a set. Args: genetic_models : A string with genetic models Yields: correct_model_names : A set with the correct model names
def get_models(self, genetic_models): correct_model_names = set() genetic_models = genetic_models.split(';') correct_model_names = set() for model in genetic_models: # We need to allow typos if model in self.legal_ar_hom_names: model = 'AR...
849,475
overwrites the standard dictionary and checks if value is valid Args: key: dictionary key value: dictionary value
def __setitem__(self, key, value): # print('AHHAHAH', self.valid_values) message = "{0} (of type {1}) is not in {2}".format(str(value), type(value), str(self.valid_values[key])) assert self.is_valid(value, self.valid_values[key]), message if isinstance(value, dict) and len(sel...
849,497
check is the value is valid Args: value: value to be tested valid_values: allowed valid values (type or list of values) Returns:
def is_valid(value, valid_values): valid = False if isinstance(valid_values, type) and type(value) is valid_values: valid = True elif isinstance(valid_values, type) and valid_values == float and type(value) == int: #special case to allow ints as float inputs ...
849,499
Example of a script Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings
def __init__(self, name=None, settings=None, log_function = None, data_path = None): Script.__init__(self, name, settings, log_function= log_function, data_path = data_path)
849,651
plots the data only the axes objects that are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript data: data to be plotted if empty take self.data Returns: None
def _plot(self, axes_list, data = None): plot_type = self.settings['plot_style'] if data is None: data = self.data if data is not None and data is not {}: if plot_type in ('main', 'two'): if not data['random data'] is None: a...
849,653
updates the data in already existing plots. the axes objects are provided in axes_list Args: axes_list: a list of axes objects, this should be implemented in each subscript Returns: None
def _update(self, axes_list): plot_type = self.settings['plot_style'] if plot_type == '2D': # we expect exactely one image in the axes object (see ScriptDummy.plot) implot = axes_list[1].get_images()[0] # now update the data implot.set_data(self.d...
849,654
Example of a script Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings
def __init__(self, instruments = None, scripts = None, name=None, settings=None, log_function = None, data_path = None): super(ScriptDummyWrapper, self).__init__(self, name, settings, log_function= log_function, data_path=data_path)
849,655
Example of a script that emits a QT signal for the gui Args: name (optional): name of script, if empty same as class name settings (optional): settings for this script, if empty same as default settings
def __init__(self, instruments, scripts = None, name=None, settings=None, log_function=None, data_path = None): Script.__init__(self, name, settings=settings, scripts=scripts, instruments=instruments, log_function=log_function, data_path = data_path) self.data = {'plant_output': deque(maxlen=s...
849,656
fills a tree with nested parameters Args: tree: QtGui.QTreeView to fill parameters: dictionary or Parameter object which contains the information to use to fill
def fill_list(self, list, input_list): for name in input_list: # print(index, loaded_item, loaded_item_settings) item = QtGui.QStandardItem(name) item.setSelectable(True) item.setEditable(False) list.model().appendRow(item)
849,677
fills a tree with nested parameters Args: tree: QtGui.QTreeView parameters: dictionary or Parameter object Returns:
def fill_tree(self, tree, input_dict): def removeAll(tree): if tree.model().rowCount() > 0: for i in range(0, tree.model().rowCount()): item = tree.model().item(i) del item tree.model().removeRows(0, tree.model()...
849,749
Check if there are any grand parents. Set the grandparents id:s Arguments: mother (Individual): An Individual object that represents the mother father (Individual): An Individual object that represents the father
def check_grandparents(self, mother = None, father = None): if mother: if mother.mother != '0': self.grandparents[mother.mother] = '' elif mother.father != '0': self.grandparents[mother.father] = '' if father: if father.mother...
849,751
returns all the packages in the module Args: module_name: name of module Returns:
def explore_package(module_name): packages = [] loader = pkgutil.get_loader(module_name) for sub_module in pkgutil.walk_packages([os.path.dirname(loader.get_filename())], prefix=module_name + '.'): _, sub_module_name, _ = sub_module packages....
849,773
gets the value for "name" from "path_to_file" config file Args: name: name of varibale in config file path_to_file: path to config file Returns: path to dll if name exists in the file; otherwise, returns None
def get_config_value(name, path_to_file='config.txt'): # if the function is called from gui then the file has to be located with respect to the gui folder if not os.path.isfile(path_to_file): path_to_file = os.path.join('../instruments/', path_to_file) path_to_file = os.path.abspath(path_to_f...
849,781
loads a .b26 file into a dictionary Args: file_name: Returns: dictionary with keys instrument, scripts, probes
def load_b26_file(file_name): # file_name = "Z:\Lab\Cantilever\Measurements\\tmp_\\a" assert os.path.exists(file_name) with open(file_name, 'r') as infile: data = yaml.safe_load(infile) return data
849,782
save instruments, scripts and probes as a json file Args: filename: instruments: scripts: probes: dictionary of the form {instrument_name : probe_1_of_intrument, probe_2_of_intrument, ...} Returns:
def save_b26_file(filename, instruments=None, scripts=None, probes=None, overwrite=False, verbose=False): # if overwrite is false load existing data and append to new instruments if os.path.isfile(filename) and overwrite == False: data_dict = load_b26_file(filename) else: data_dict = {...
849,783
NOT IMPLEMENTED YET tries to instantiate all the instruments that are imported in /instruments/__init__.py and the probes of each instrument that could be instantiated into a .b26 file in the folder path Args: path: target path for .b26 files
def export_default_probes(path, module_name = '', raise_errors = False): raise NotImplementedError import b26_toolkit.b26_toolkit.instruments as instruments from pylabcontrol.core import Probe for name, obj in inspect.getmembers(instruments): if inspect.isclass(obj): try: ...
849,794
tries to instantiate all the scripts that are imported in /scripts/__init__.py saves each script that could be instantiated into a .b26 file in the folder path Args: target_folder: target path for .b26 files source_folder: location of python script files
def export_default_scripts(target_folder, source_folder = None, raise_errors = False, verbose=False): scripts_to_load = get_classes_in_folder(source_folder, Script) if verbose: print(('attempt to load {:d} scripts: '.format(len(scripts_to_load)))) loaded_scripts, failed, loaded_instruments =...
849,795
Create a new OEmbedEndpoint object. Args: url: The url of a provider API (API endpoint). urlSchemes: A list of URL schemes for this endpoint.
def __init__(self, url, urlSchemes=None): self._urlApi = url self._urlSchemes = {} self._initRequestHeaders() self._urllib = urllib2 if urlSchemes is not None: for urlScheme in urlSchemes: self.addUrlScheme(urlScheme) self._implicitF...
849,848
Add a url scheme to this endpoint. It takes a url string and create the OEmbedUrlScheme object internally. Args: url: The url string that represents a url scheme to add.
def addUrlScheme(self, url): #@TODO: validate invalid url format according to http://oembed.com/ if not isinstance(url, str): raise TypeError('url must be a string value') if not url in self._urlSchemes: self._urlSchemes[url] = OEmbedUrlScheme(url)
849,849
Try to find if url matches against any of the schemes within this endpoint. Args: url: The url to match against each scheme Returns: True if a matching scheme was found for the url, False otherwise
def match(self, url): try: urlSchemes = self._urlSchemes.itervalues() # Python 2 except AttributeError: urlSchemes = self._urlSchemes.values() # Python 3 for urlScheme in urlSchemes: if urlScheme.match(url): return True return...
849,850
Format the input url and optional parameters, and provides the final url where to get the given resource. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: The complete url of the endpoint and resource.
def request(self, url, **opt): params = opt params['url'] = url urlApi = self._urlApi if 'format' in params and self._implicitFormat: urlApi = self._urlApi.replace('{format}', params['format']) del params['format'] if '?' in urlApi: ...
849,851
Convert the resource url to a complete url and then fetch the data from it. Args: url: The url of an OEmbed resource. **opt: Parameters passed to the url. Returns: OEmbedResponse object according to data fetched
def get(self, url, **opt): return self.fetch(self.request(url, **opt))
849,852
Fetch url and create a response object according to the mime-type. Args: url: The url to fetch data from Returns: OEmbedResponse object according to data fetched
def fetch(self, url): opener = self._urllib.build_opener() opener.addheaders = self._requestHeaders.items() response = opener.open(url) headers = response.info() raw = response.read() raw = raw.decode('utf8') if not 'Content-Type' in headers: ...
849,853
Get an OEmbedResponse from one of the providers configured in this consumer according to the resource url. Args: url: The url of the resource to get. format: Desired response format. **opt: Optional parameters to pass in the url to the provider. Returns: ...
def embed(self, url, format='json', **opt): if format not in ['json', 'xml']: raise OEmbedInvalidRequest('Format must be json or xml') opt['format'] = format return self._request(url, **opt)
849,857
figures out the iterator type based on the script settings and (optionally) subscripts Args: script_settings: iterator_type subscripts: subscripts Returns:
def get_iterator_type(script_settings, subscripts={}): if 'iterator_type' in script_settings: # figure out the iterator type if script_settings['iterator_type'] == 'Loop': iterator_type = 'loop' elif script_settings['iterator_type'] == 'Parameter Swe...
849,861
this function takes care of signals emitted by the subscripts Args: progress_subscript: progress of subscript
def _receive_signal(self, progress_subscript): self.progress = self._estimate_progress() self.updateProgress.emit(int(self.progress))
849,863
Connect to the Herkulex bus Connect to serial port to which Herkulex Servos are attatched Args: portname (str): The serial port name baudrate (int): The serial port baudrate Raises: SerialException: Error occured while opening serial port
def connect(portname, baudrate): global SERPORT try: SERPORT = serial.Serial(portname, baudrate, timeout = 0.1) except: raise HerkulexError("could not open the serial port")
849,868
Calculate Checksum 1 Calculate the ckecksum 1 required for the herkulex data packet Args: data (list): the data of which checksum is to be calculated stringlength (int): the length of the data Returns: int: The calculated checksum 1
def checksum1(data, stringlength): value_buffer = 0 for count in range(0, stringlength): value_buffer = value_buffer ^ data[count] return value_buffer&0xFE
849,869
Send data to herkulex Paketize & write the packet to serial port Args: data (list): the data to be sent Raises: SerialException: Error occured while opening serial port
def send_data(data): datalength = len(data) csm1 = checksum1(data, datalength) csm2 = checksum2(csm1) data.insert(0, 0xFF) data.insert(1, 0xFF) data.insert(5, csm1) data.insert(6, csm2) stringtosend = "" for i in range(len(data)): byteformat = '%02X' % data[i] st...
849,870
Clears the errors register of all Herkulex servos Args: none
def clear_errors(): data = [] data.append(0x0B) data.append(BROADCAST_ID) data.append(RAM_WRITE_REQ) data.append(STATUS_ERROR_RAM) data.append(BYTE2) data.append(0x00) data.append(0x00) send_data(data)
849,871
Scan for the herkulex servos connected This function will scan for all the herkulex servos connected to the bus. Args: none Returns: list: a list of tuples of the form [(id, model)]
def scan_servos(): servos = [] for servo_id in range(0x00, 0xFE): model = get_model(servo_id) if model: servos += [(servo_id, model)] return servos
849,873
Get the servo model This function gets the model of the herkules servo, provided its id Args: servoid(int): the id of the servo Returns: int: an integer corresponding to the model number 0x06 for DRS-602 0x04 for DRS-402 0x02 for DRS-202
def get_model(servoid): data = [] data.append(0x09) data.append(servoid) data.append(EEP_READ_REQ) data.append(MODEL_NO1_EEP) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) return ord(rxdata[9])&0xFF except: raise Herkul...
849,874
Get the error status of servo This function gets the error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet
def get_servo_status(self): data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(STATUS_ERROR_RAM) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) ...
849,875
Get the detailed error status of servo This function gets the detailed error status (if any) of the servo Args: none Returns: int: an integer corresponding to the servo status * refer datasheet
def get_servo_status_detail(self): data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(STATUS_DETAIL_RAM) data.append(BYTE1) send_data(data) rxdata = [] try: rxdata = SERPORT.read(12) ...
849,876
Set the LED Color of Herkulex Args: colorcode (int): The code for colors (0x00-OFF 0x02-BLUE 0x03-CYAN 0x04-RED 0x05-ORANGE 0x...
def set_led(self, colorcode): data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(LED_CONTROL_RAM) data.append(0x01) data.append(colorcode) send_data(data)
849,877
Set the Brakes of Herkulex In braked mode, position control and velocity control will not work, enable torque before that Args: none
def brake_on(self): data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x40) send_data(data)
849,878
Set the torques of Herkulex to zero In this mode, position control and velocity control will not work, enable torque before that. Also the servo shaft is freely movable Args: none
def torque_off(self): data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x00) send_data(data)
849,879
Enable the torques of Herkulex In this mode, position control and velocity control will work. Args: none
def torque_on(self): data = [] data.append(0x0A) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(TORQUE_CONTROL_RAM) data.append(0x01) data.append(0x60) send_data(data)
849,880
Set the position of Herkulex Enable torque using torque_on function before calling this Args: goalposition (int): The desired position, min-0 & max-1023 goaltime (int): the time taken to move from present position to goalposition led (int): the LED col...
def set_servo_position(self, goalposition, goaltime, led): goalposition_msb = int(goalposition) >> 8 goalposition_lsb = int(goalposition) & 0xff data = [] data.append(0x0C) data.append(self.servoid) data.append(I_JOG_REQ) data.append(goalposition_lsb) ...
849,882
Gets the current position of Herkulex Args: none Returns: int: position of the servo- 0 to 1023 Raises: SerialException: Error occured while opening serial port
def get_servo_position(self): #global SERPORT data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(CALIBRATED_POSITION_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxd...
849,883
Gets the current temperature of Herkulex Args: none Returns: int: the current temperature register of Herkulex Raises: SerialException: Error occured while opening serial port
def get_servo_temperature(self): data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(TEMPERATURE_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) ...
849,884
Gets the current torque of Herkulex Gives the current load on the servo shaft. It is actually the PWM value to the motors Args: none Returns: int: the torque on servo shaft. range from -1023 to 1023 Raises: SerialException: Error occured wh...
def get_servo_torque(self): data = [] data.append(0x09) data.append(self.servoid) data.append(RAM_READ_REQ) data.append(PWM_RAM) data.append(BYTE2) send_data(data) rxdata = [] try: rxdata = SERPORT.read(13) if ord(r...
849,885
Set the Herkulex in continuous rotation mode Args: goalspeed (int): the speed , range -1023 to 1023 led (int): the LED color 0x00 LED off 0x04 GREEN 0x08 BLUE 0x10 RED
def set_servo_speed(self, goalspeed, led): if goalspeed>0 : goalspeed_msb = (int(goalspeed)& 0xFF00) >> 8 goalspeed_lsb = int(goalspeed) & 0xff elif goalspeed<0 : goalspeed_msb = 64+(255- ((int(goalspeed)& 0xFF00) >> 8)) goalspeed_lsb = (abs(goals...
849,886
Set the P gain of the position PID Args: pvalue (int): P value
def set_position_p(self, pvalue): pvalue_msb = int(pvalue) >> 8 pvalue_lsb = int(pvalue) & 0xff data = [] data.append(0x0B) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(POSITION_KP_RAM) data.append(BYTE2) data.append( p...
849,887
Set the I gain of the position PID Args: ivalue (int): I value
def set_position_i(self, ivalue): ivalue_msb = int(ivalue) >> 8 ivalue_lsb = int(ivalue) & 0xff data = [] data.append(0x0B) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(POSITION_KI_RAM) data.append(BYTE2) data.append(i...
849,888
Set the D gain of the PID Args: dvalue (int): D value
def set_position_d(self, dvalue): dvalue_msb = int(dvalue) >> 8 dvalue_lsb = int(dvalue) & 0xff data = [] data.append(0x0B) data.append(self.servoid) data.append(RAM_WRITE_REQ) data.append(POSITION_KD_RAM) data.append(BYTE2) data.append(dv...
849,889
Sets the servo angle (in degrees) Enable torque using torque_on function before calling this Args: goalangle (int): The desired angle in degrees, range -150 to 150 goaltime (int): the time taken to move from present position to goalposition led (int): t...
def set_servo_angle(self, goalangle, goaltime, led): if (self.servomodel==0x06) or (self.servomodel == 0x04): goalposition = scale(goalangle, -159.9, 159.6, 10627, 22129) else: goalposition = scale(goalangle, -150, 150, 21, 1002) self.set_servo_position(goalposi...
849,894
Gets the current angle of the servo in degrees Args: none Returns: int : the current servo angle
def get_servo_angle(self): servoposition = self.get_servo_position() if (self.servomodel==0x06) or (self.servomodel == 0x04): return scale(servoposition, 10627, 22129, -159.9, 159.6) else: return scale(servoposition, 21, 1002, -150, 150)
849,895
executes scripts and stores script parameters and settings Args: name (optional): name of script, if not provided take name of function settings (optional): a Parameter object that contains all the information needed in the script instruments (optional): instruments used in ...
def __init__(self, name=None, settings=None, instruments=None, scripts=None, log_function=None, data_path=None): QObject.__init__(self) self._script_class = self.__class__.__name__ if name is None: name = self.__class__.__name__ self.name = name self._ins...
849,921
updates the internal dictionary Args: settings: parameters to be set # mabe in the future: # Returns: boolean that is true if update successful
def update(self, settings): if 'settings' in settings: self._settings.update(settings['settings']) else: self._settings.update(settings) if 'instruments' in settings: for instrument_name, instrument_setting in settings['instruments'].items(): ...
849,928
this function takes care of signals emitted by the subscripts the default behaviour is that it just reemits the signal Args: progress: progress of subscript
def _receive_signal(self, progress): # print(datetime.datetime.now().strftime("%B %d, %Y %H:%M:%S"), self.name,QtCore.QThread.currentThread(), self._current_subscript_stage['current_subscript'].name, # 'received signal. emitting....') self.progress = progress self.updateP...
849,932
creates a filename based Args: appendix: appendix for file Returns: filename
def filename(self, appendix=None, create_if_not_existing=False): # if provided path is a relative path and self.data_path exists, build path if os.path.isabs(self.settings['path']) == False and self.data_path is not None: path = os.path.join(self.data_path, self.settings['path']) ...
849,935
saves the instance of the script to a file using pickle Args: filename: target filename
def save(self, filename): if filename is None: filename = self.filename('.b26s') # if len(filename.split('\\\\?\\')) == 1: # filename = '\\\\?\\' + filename with open(filename, 'w') as outfile: outfile.write(pickle.dumps(self.__dict__))
849,939
loads an script instance using pickle Args: filename: source filename instruments: optional - only needed if script requires instruments dictionary of form instruments = { name_of_instrument_1 : instance_of_instrument_1, ...
def load(filename, instruments = None): with open(filename, 'r') as infile: dataPickle = infile.read() script_as_dict = pickle.loads(dataPickle) script_class = script_as_dict['_script_class'] script_instance, _, updated_instruments = Script.load_and_append({'script...
849,940
loads the data that has been save with Script.save. Args: path: path to folder saved by Script.save or raw_data folder within Returns: a dictionary with the data of form data = {param_1_name: param_1_data, ...}
def load_data(path): # check that path exists if not os.path.exists(path): print(path) raise AttributeError('Path given does not exist!') # windows can't deal with long filenames (>260 chars) so we have to use the prefix '\\\\?\\' # if len(path.split('...
849,941
wrapper to get the module for a script Args: script_information: information of the script. This can be - a dictionary - a Script instance - name of Script class package (optional): name of the package to which the script belongs, i.e. pyl...
def get_script_module(script_information, package='pylabcontrol', verbose=False): module, _, _, _, _, _, _ = Script.get_script_information(script_information=script_information, package=package, verbose=verbose) return module
849,942
plots the data contained in self.data, which should be a dictionary or a deque of dictionaries for the latter use the last entry Args: figure_list: list of figure objects that are passed to self.get_axes_layout to get axis objects for plotting
def plot(self, figure_list): # if there is not data we do not plot anything if not self.data: return # if plot function is called when script is not running we request a plot refresh if not self.is_running: self._plot_refresh = True axes_list = ...
849,944
returns the axes objects the script needs to plot its data the default creates a single axes object on each figure This can/should be overwritten in a child script if more axes objects are needed Args: figure_list: a list of figure objects Returns: axes_list: a li...
def get_axes_layout(self, figure_list): axes_list = [] if self._plot_refresh is True: for fig in figure_list: fig.clf() axes_list.append(fig.add_subplot(111)) else: for fig in figure_list: axes_list.append(fig.axes...
849,945
function is overloaded: - read_probes() - read_probes(key) Args: key: name of requested value Returns: - if called without argument: returns the values of all probes in dictionary form - if called with argument: returns the value the requeste...
def read_probes(self, key = None): print(('xxxxx probes', key, self._PROBES())) if key is None: # return the value all probe in dictionary form d = {} for k in list(self._PROBES.keys()): d[k] = self.read_probes(k) return d ...
849,992
allows to read instrument inputs in the form value = instrument.input Args: name: name of input channel Returns: value of input channel
def __getattr__(self, name): # try: # print('xxxxx', name, self._PROBES()) # xx = self.read_probes(name) # print(xx) # return xx # # return self.read_probes(name) # except: # # restores standard behavior for missing keys ...
849,993
Split string by split character space(' ') and indent('\t') as default Examples: >>> StringClass.split_string('exec -ini test.ini', ' ') ['exec', '-ini', 'test.ini'] Args: str_src: source string spliters: e.g. [' ', '\t'], [], ' ', None elim_...
def split_string(str_src, spliters=None, elim_empty=False): # type: (AnyStr, Union[AnyStr, List[AnyStr], None], bool) -> List[AnyStr] if is_string(spliters): spliters = [spliters] if spliters is None or not spliters: spliters = [' ', '\t'] dest_strs = lis...
850,100
get file names with the given suffixes in the given directory Args: dir_src: directory path suffixes: wanted suffixes list, the suffix in suffixes can with or without '.' Returns: file names with the given suffixes as list
def get_filename_by_suffixes(dir_src, suffixes): # type: (AnyStr, Union[AnyStr, List[AnyStr]]) -> Optional[List[AnyStr]] list_files = os.listdir(dir_src) re_files = list() if is_string(suffixes): suffixes = [suffixes] if not isinstance(suffixes, list): ...
850,111
get full file names with the given suffixes in the given directory Args: dir_src: directory path suffixes: wanted suffixes Returns: full file names with the given suffixes as list
def get_full_filename_by_suffixes(dir_src, suffixes): # type: (AnyStr, Union[AnyStr, List[AnyStr]]) -> Optional[List[AnyStr]] file_names = FileClass.get_filename_by_suffixes(dir_src, suffixes) if file_names is None: return None return list(dir_src + os.sep + name for...
850,112
Execute external command, and return the output lines list. In windows, refers to `handling-subprocess-crash-in-windows`_. Args: commands: string or list Returns: output lines .. _handling-subprocess-crash-in-windows: https://stackoverflow.com/quest...
def run_command(commands): # type: (Union[AnyStr, List[AnyStr]]) -> List[AnyStr] # commands = StringClass.convert_unicode2str(commands) # print(commands) use_shell = False subprocess_flags = 0 startupinfo = None if sysstr == 'Windows': if isi...
850,116
Draw every pixel's ID After computing all given value's pixels connectivity, every pixel will have an ID. Then we need to draw these pixels' ID on the undrawed rasterfile. Args: ID: given ID value idx_array: pixels position set which have the given ID value drawID_rast...
def draw_ID(ID, idx_array, drawID_raster): for i in range(idx_array.shape[0]): x = idx_array[i, 0] y = idx_array[i, 1] drawID_raster[x, y] = ID return drawID_raster
850,129
Add an individual to the family. Arguments: individual_object (Individual)
def add_individual(self, individual_object): ind_id = individual_object.individual_id self.logger.info("Adding individual {0}".format(ind_id)) family_id = individual_object.family if family_id != self.family_id: raise PedigreeError(self.family, individual_object.indi...
850,289
Return the phenotype of an individual If individual does not exist return 0 Arguments: individual_id (str): Represents the individual id Returns: int : Integer that represents the phenotype
def get_phenotype(self, individual_id): phenotype = 0 # This is if unknown phenotype if individual_id in self.individuals: phenotype = self.individuals[individual_id].phenotype return phenotype
850,290
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are listed. Precondition: must have an existing image in figure_list[0] to plot over Args: figure_list:
def plot(self, figure_list): # if there is not image data get it from the current plot if not self.data == {} and self.data['image_data'] is None: axes = figure_list[0].axes[0] if len(axes.images)>0: self.data['image_data'] = np.array(axes.images[0].get_...
850,327
Plots a dot on top of each selected NV, with a corresponding number denoting the order in which the NVs are listed. Precondition: must have an existing image in figure_list[0] to plot over Args: figure_list:
def _plot(self, axes_list): axes = axes_list[0] if self.plot_settings: axes.imshow(self.data['image_data'], cmap=self.plot_settings['cmap'], interpolation=self.plot_settings['interpol'], extent=self.data['extent']) axes.set_xlabel(self.plot_settings['xlabel']) ...
850,328
If there is not currently a selected NV within self.settings[patch_size] of pt, adds it to the selected list. If there is, removes that point from the selected list. Args: pt: the point to add or remove from the selected list Poststate: updates selected list
def toggle_NV(self, pt): if not self.data['nv_locations']: #if self.data is empty so this is the first point self.data['nv_locations'].append(pt) self.data['image_data'] = None # clear image data else: # use KDTree to find NV closest to mouse click ...
850,330
loads the data that has been save with Script.save. Args: path: path to folder saved by Script.save or raw_data folder within verbose: if true print additional information raise_errors: if true raise errors if false just print to std out Returns: a diction...
def load_data(path, verbose=False, raise_errors = False): # check that path exists if not os.path.exists(path): if raise_errors: raise AttributeError('Path given does not exist!') else: print('Path given does not exist!') ...
850,336
loads the settings that has been save with Script.save_b26. Args: path: path to folder saved by Script.save_b26 setttings_only: if true returns only the settings if the .b26 file contains only a single script Returns: a dictionary with the settings
def load_settings(path, setttings_only = True): # check that path exists if not os.path.exists(path): print(path) raise AttributeError('Path given does not exist!') tag = '_'.join(os.path.basename(os.path.dirname(os.path.abspath(path) + '/')).split('_')[3:]) ...
850,337
TEMPORARY / UNDER DEVELOPMENT THIS IS TO ALLOW COPYING OF PARAMETERS VIA DRAP AND DROP Args: object: event: Returns:
def eventFilter(self, object, event): if (object is self.tree_scripts): # print('XXXXXXX = event in scripts', event.type(), # QtCore.QEvent.DragEnter, QtCore.QEvent.DragMove, QtCore.QEvent.DragLeave) if (event.type() == QtCore.QEvent.ChildAdded): ...
850,355
sets the filename to which the probe logging function will write Args: checked: boolean (True: opens file) (False: closes file)
def set_probe_file_name(self, checked): if checked: file_name = os.path.join(self.gui_settings['probes_log_folder'], '{:s}_probes.csv'.format(datetime.datetime.now().strftime('%y%m%d-%H_%M_%S'))) if os.path.isfile(file_name) == False: self.probe_file = open(file_...
850,356