signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def get_absolute_time(self, key): | keyframe = self.dct[key]<EOL>try:<EOL><INDENT>return keyframe['<STR_LIT>']<EOL><DEDENT>except KeyError:<EOL><INDENT>if keyframe['<STR_LIT>'] is None:<EOL><INDENT>keyframe['<STR_LIT>'] = keyframe['<STR_LIT:time>']<EOL><DEDENT>else:<EOL><INDENT>parent_time = self.get_absolute_time(keyframe['<STR_LIT>'])<EOL>abs_time = keyframe['<STR_LIT:time>'] + parent_time<EOL>keyframe['<STR_LIT>'] = abs_time<EOL><DEDENT>return keyframe['<STR_LIT>']<EOL><DEDENT> | Returns the absolute time position of the key.
If absolute time positions are not calculated, then this function
calculates it. | f15494:c0:m3 |
def sorted_key_list(self): | if not self.is_baked:<EOL><INDENT>self.bake()<EOL><DEDENT>key_value_tuple = sorted(self.dct.items(),<EOL>key=lambda x: x[<NUM_LIT:1>]['<STR_LIT>'])<EOL>skl = [k[<NUM_LIT:0>] for k in key_value_tuple]<EOL>return skl<EOL> | Returns list of keys sorted according to their absolute time. | f15494:c0:m4 |
def set_time(self, key_name, new_time): | self.unbake()<EOL>kf = self.dct[key_name]<EOL>kf['<STR_LIT:time>'] = new_time<EOL>self.bake()<EOL> | Sets the time of key. | f15494:c0:m5 |
def set_comment(self, key_name, new_comment): | kf = self.dct[key_name]<EOL>kf['<STR_LIT>'] = new_comment<EOL> | Sets the comment of key. | f15494:c0:m6 |
def set_parent(self, key_name, new_parent): | self.unbake()<EOL>kf = self.dct[key_name]<EOL>kf['<STR_LIT>'] = new_parent<EOL>self.bake()<EOL> | Sets the parent of the key. | f15494:c0:m7 |
def is_ancestor(self, child_key_name, ancestor_key_name): | <EOL>if ancestor_key_name is None:<EOL><INDENT>return True<EOL><DEDENT>one_up_parent = self.dct[child_key_name]['<STR_LIT>']<EOL>if child_key_name == ancestor_key_name:<EOL><INDENT>return True<EOL><DEDENT>elif one_up_parent is None:<EOL><INDENT>return False<EOL><DEDENT>else:<EOL><INDENT>return self.is_ancestor(one_up_parent, ancestor_key_name)<EOL><DEDENT> | Returns True if ancestor lies in the ancestry tree of child. | f15494:c0:m11 |
def add_hook(self, key_name, hook_name, hook_dict): | kf = self.dct[key_name]<EOL>if '<STR_LIT>' not in kf:<EOL><INDENT>kf['<STR_LIT>'] = {}<EOL><DEDENT>kf['<STR_LIT>'][str(hook_name)] = hook_dict<EOL> | Add hook to the keyframe key_name. | f15494:c0:m12 |
def remove_hook(self, key_name, hook_name): | kf = self.dct[key_name]<EOL>if '<STR_LIT>' in kf:<EOL><INDENT>if hook_name in kf['<STR_LIT>']:<EOL><INDENT>return kf['<STR_LIT>'].pop(hook_name)<EOL><DEDENT><DEDENT> | Remove hook from the keyframe key_name. | f15494:c0:m13 |
def list_hooks(self, key_name): | kf = self.dct[key_name]<EOL>if '<STR_LIT>' not in kf:<EOL><INDENT>return []<EOL><DEDENT>else:<EOL><INDENT>return kf['<STR_LIT>'].iterkeys()<EOL><DEDENT> | Return list of all hooks attached to key_name. | f15494:c0:m14 |
def do_keyframes_overlap(self): | skl = self.sorted_key_list()<EOL>for i in range(len(skl)-<NUM_LIT:1>):<EOL><INDENT>this_time = self.dct[skl[i]]['<STR_LIT>']<EOL>next_time = self.dct[skl[i+<NUM_LIT:1>]]['<STR_LIT>']<EOL>if abs(next_time-this_time) < <NUM_LIT>:<EOL><INDENT>return skl[i]<EOL><DEDENT><DEDENT>return None<EOL> | Checks for keyframs timing overlap.
Returns the name of the first keyframs that overlapped. | f15494:c0:m16 |
def set_name(self, new_ch_name): | self.ch_name = new_ch_name<EOL> | Sets the name of the channel. | f15494:c1:m1 |
def del_unused_keyframes(self): | skl = self.key_frame_list.sorted_key_list()<EOL>unused_keys = [k for k in self.dct['<STR_LIT>']<EOL>if k not in skl]<EOL>for k in unused_keys:<EOL><INDENT>del self.dct['<STR_LIT>'][k]<EOL><DEDENT> | Scans through list of keyframes in the channel and removes those
which are not in self.key_frame_list. | f15494:c1:m2 |
def get_used_key_frames(self): | skl = self.key_frame_list.sorted_key_list()<EOL>used_key_frames = []<EOL>for kf in skl:<EOL><INDENT>if kf in self.dct['<STR_LIT>']:<EOL><INDENT>used_key_frames.append((kf, self.dct['<STR_LIT>'][kf]))<EOL><DEDENT><DEDENT>return used_key_frames<EOL> | Returns a list of the keyframes used by this channel, sorted with
time. Each element in the list is a tuple. The first element is the
key_name and the second is the channel data at that keyframe. | f15494:c1:m4 |
def get_used_key_frame_list(self): | skl = self.key_frame_list.sorted_key_list()<EOL>used_key_frames = []<EOL>for kf in skl:<EOL><INDENT>if kf in self.dct['<STR_LIT>']:<EOL><INDENT>used_key_frames.append(kf)<EOL><DEDENT><DEDENT>return used_key_frames<EOL> | Returns a list of the keyframes used by this channel, sorted with
time. | f15494:c1:m5 |
def get_ramp_regions(self): | skl = self.key_frame_list.sorted_key_list()<EOL>ramp_or_jump = np.zeros(len(skl) - <NUM_LIT:1>)<EOL>used_key_frames = self.get_used_key_frame_list()<EOL>for region_number, start_key in enumerate(skl[:-<NUM_LIT:1>]):<EOL><INDENT>if start_key in used_key_frames:<EOL><INDENT>key_data = self.dct['<STR_LIT>'][start_key]<EOL>ramp_type = key_data['<STR_LIT>']<EOL>if ramp_type != "<STR_LIT>":<EOL><INDENT>curr_key_num = used_key_frames.index(start_key)<EOL>end_key_number = curr_key_num + <NUM_LIT:1><EOL>if end_key_number < len(used_key_frames):<EOL><INDENT>end_key_name = used_key_frames[end_key_number]<EOL>end_region_index = skl.index(end_key_name)<EOL>ramp_or_jump[region_number:end_region_index] = <NUM_LIT:1><EOL><DEDENT><DEDENT><DEDENT><DEDENT>return ramp_or_jump<EOL> | Returns a numpy array where each element corresponds to whether to
ramp in that region or jump. | f15494:c1:m6 |
def generate_ramp(self, time_div=<NUM_LIT>): | if self.dct['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>is_analog = True<EOL><DEDENT>else:<EOL><INDENT>is_analog = False<EOL><DEDENT>skl = self.key_frame_list.sorted_key_list()<EOL>used_key_frames = self.get_used_key_frames()<EOL>max_time = self.key_frame_list.get_absolute_time(skl[-<NUM_LIT:1>]) + time_div<EOL>num_points = int(round(max_time/time_div))<EOL>time = np.arange(num_points) * time_div<EOL>if is_analog:<EOL><INDENT>voltage = np.zeros(time.shape, dtype=float)<EOL><DEDENT>else:<EOL><INDENT>voltage = np.zeros(time.shape, dtype='<STR_LIT>')<EOL><DEDENT>kf_times = np.array([self.key_frame_list.get_absolute_time(ukf[<NUM_LIT:0>])<EOL>for ukf in used_key_frames])<EOL>kf_positions = kf_times/time_div<EOL>if is_analog:<EOL><INDENT>start_voltage = used_key_frames[<NUM_LIT:0>][<NUM_LIT:1>]['<STR_LIT>']['<STR_LIT:value>']<EOL>end_voltage = used_key_frames[-<NUM_LIT:1>][<NUM_LIT:1>]['<STR_LIT>']['<STR_LIT:value>']<EOL>voltage[<NUM_LIT:0>:kf_positions[<NUM_LIT:0>]] = start_voltage<EOL>voltage[kf_positions[-<NUM_LIT:1>]:] = end_voltage<EOL><DEDENT>else:<EOL><INDENT>start_voltage = int(used_key_frames[<NUM_LIT:0>][<NUM_LIT:1>]['<STR_LIT:state>'])<EOL>end_voltage = int(used_key_frames[-<NUM_LIT:1>][<NUM_LIT:1>]['<STR_LIT:state>'])<EOL>voltage[<NUM_LIT:0>:kf_positions[<NUM_LIT:0>]] = start_voltage<EOL>voltage[kf_positions[-<NUM_LIT:1>]:] = end_voltage<EOL><DEDENT>for i in range(len(kf_times)-<NUM_LIT:1>):<EOL><INDENT>start_time = kf_times[i]<EOL>end_time = kf_times[i+<NUM_LIT:1>]<EOL>start_index = kf_positions[i]<EOL>end_index = kf_positions[i+<NUM_LIT:1>]<EOL>time_subarray = time[start_index:end_index]<EOL>ramp_type = used_key_frames[i][<NUM_LIT:1>]['<STR_LIT>']<EOL>ramp_data = used_key_frames[i][<NUM_LIT:1>]['<STR_LIT>']<EOL>if is_analog:<EOL><INDENT>value_final = used_key_frames[i+<NUM_LIT:1>][<NUM_LIT:1>]['<STR_LIT>']['<STR_LIT:value>']<EOL><DEDENT>else:<EOL><INDENT>state = used_key_frames[i][<NUM_LIT:1>]['<STR_LIT:state>']<EOL><DEDENT>if is_analog:<EOL><INDENT>parms_tuple = (ramp_data, start_time, end_time, value_final,<EOL>time_subarray)<EOL><DEDENT>else:<EOL><INDENT>parms_tuple = (ramp_data, start_time, end_time, state,<EOL>time_subarray)<EOL><DEDENT>if is_analog:<EOL><INDENT>ramp_function = analog_ramp_functions[ramp_type]<EOL><DEDENT>else:<EOL><INDENT>ramp_function = digital_ramp_functions[ramp_type]<EOL><DEDENT>voltage_sub = ramp_function(*parms_tuple)<EOL>voltage[start_index:end_index] = voltage_sub<EOL><DEDENT>return time, self.convert_voltage(voltage, time)<EOL> | Returns the generated ramp and a time array.
This function assumes a uniform time division throughout.
time_div - time resolution of the ramp. | f15494:c1:m8 |
def digital_channel_ids(): | line_fmt = '<STR_LIT>'<EOL>line_ids = [line_fmt.format(n) for n in range(<NUM_LIT:5>, <NUM_LIT>)]<EOL>return line_ids<EOL> | Returns list of digital channels used in the experiment. | f15496:m0 |
def get_digital_channels(channel_list): | dig_ids = digital_channel_ids()<EOL>dig_channels = []<EOL>for ln in dig_ids:<EOL><INDENT>for ch in channel_list:<EOL><INDENT>if ch.dct['<STR_LIT:id>'] == ln:<EOL><INDENT>dig_channels.append(ch)<EOL>break<EOL><DEDENT><DEDENT><DEDENT>return dig_channels<EOL> | Goes through channel list and returns digital channels with ids
Dev1/port0/line08, Dev1/port0/line09... Dev1/port0/line30. | f15496:m6 |
def check_ramp_for_errors(ramp_data): | error_list = []<EOL>keyframe_list = ramps.KeyFrameList(ramp_data['<STR_LIT>'])<EOL>sorted_key_list = keyframe_list.sorted_key_list()<EOL>channel_list = [ramps.Channel(ch_name, ramp_data['<STR_LIT>'][ch_name],<EOL>keyframe_list)<EOL>for ch_name in ramp_data['<STR_LIT>']]<EOL>sorted_absolute_times = [keyframe_list.get_absolute_time(sk) for sk<EOL>in sorted_key_list]<EOL>ramp_properties = ramp_data['<STR_LIT>']<EOL>jump_resolution = ramp_properties['<STR_LIT>']<EOL>for key_name, abs_time in zip(sorted_key_list, sorted_absolute_times):<EOL><INDENT>if abs_time < <NUM_LIT:0.0>:<EOL><INDENT>error_fmt = "<STR_LIT>"<EOL>error_str = error_fmt.format(key_name, abs_time)<EOL>error_list.append(error_str)<EOL><DEDENT>steps_float = abs_time / jump_resolution<EOL>steps_residue = steps_float - round(steps_float)<EOL>if steps_residue > <NUM_LIT>:<EOL><INDENT>error_fmt = ("<STR_LIT>"<EOL>"<STR_LIT>")<EOL>error_str = error_fmt.format(key_name, abs_time, jump_resolution)<EOL>error_list.append(error_str)<EOL><DEDENT><DEDENT>ch_ids = digital_channel_ids()<EOL>ch_ids += dev2_analog_ids()<EOL>for ch_id in ch_ids:<EOL><INDENT>n_found = <NUM_LIT:0><EOL>for ch in channel_list:<EOL><INDENT>if ch.dct['<STR_LIT:id>'] == ch_id:<EOL><INDENT>n_found += <NUM_LIT:1><EOL><DEDENT><DEDENT>if n_found != <NUM_LIT:1>:<EOL><INDENT>error_fmt = '<STR_LIT>'<EOL>error_str = error_fmt.format(n_found, ch_id)<EOL>error_list.append(error_str)<EOL><DEDENT><DEDENT>error_keyname = keyframe_list.do_keyframes_overlap()<EOL>if error_keyname is not None:<EOL><INDENT>error_fmt = '<STR_LIT>'<EOL>error_str = error_fmt.format(error_keyname)<EOL>error_list.append(error_str)<EOL><DEDENT>return error_list<EOL> | Checks ramp for errors. This is experiment specific checklist. | f15496:m12 |
def make_folder_for_today(log_dir): | now = datetime.datetime.now()<EOL>sub_folders_list = ['<STR_LIT>'.format(now.year),<EOL>'<STR_LIT>'.format(now.month),<EOL>'<STR_LIT>'.format(now.day)]<EOL>folder = log_dir<EOL>for sf in sub_folders_list:<EOL><INDENT>folder = os.path.join(folder, sf)<EOL>if not os.path.exists(folder):<EOL><INDENT>os.makedirs(folder)<EOL><DEDENT><DEDENT>return folder<EOL> | Creates the folder log_dir/yyyy/mm/dd in log_dir if it doesn't exist
and returns the full path of the folder. | f15496:m15 |
def queue_ramp_dicts(ramp_dict_list, server_ip_and_port): | client = server.ClientForServer(server.BECServer, server_ip_and_port)<EOL>for dct in ramp_dict_list:<EOL><INDENT>client.queue_ramp(dct)<EOL><DEDENT>client.start({})<EOL> | Simple utility function to queue up a list of dictionaries. | f15497:m2 |
def flatten_dict(dct, separator='<STR_LIT>', allowed_types=[int, float, bool]): | flat_list = []<EOL>for key in sorted(dct):<EOL><INDENT>if key[:<NUM_LIT:2>] == '<STR_LIT>':<EOL><INDENT>continue<EOL><DEDENT>key_type = type(dct[key])<EOL>if key_type in allowed_types:<EOL><INDENT>flat_list.append(str(key))<EOL><DEDENT>elif key_type is dict:<EOL><INDENT>sub_list = flatten_dict(dct[key])<EOL>sub_list = [str(key) + separator + sl for sl in sub_list]<EOL>flat_list += sub_list<EOL><DEDENT><DEDENT>return flat_list<EOL> | Returns a list of string identifiers for each element in dct.
Recursively scans through dct and finds every element whose type is in
allowed_types and adds a string indentifier for it.
eg:
dct = {
'a': 'a string',
'b': {
'c': 1.0,
'd': True
}
}
flatten_dict(dct) would return
['a', 'b-->c', 'b-->d'] | f15497:m3 |
def set_dict_item(dct, name_string, set_to): | key_strings = str(name_string).split('<STR_LIT>')<EOL>d = dct<EOL>for ks in key_strings[:-<NUM_LIT:1>]:<EOL><INDENT>d = d[ks]<EOL><DEDENT>item_type = type(d[key_strings[-<NUM_LIT:1>]])<EOL>d[key_strings[-<NUM_LIT:1>]] = item_type(set_to)<EOL> | Sets dictionary item identified by name_string to set_to.
name_string is the indentifier generated using flatten_dict.
Maintains the type of the orginal object in dct and tries to convert set_to
to that type. | f15497:m4 |
def updateAllKeys(self): | for kf, key in zip(self.kf_list, self.sorted_key_list()):<EOL><INDENT>kf.update(key, self.dct[key])<EOL><DEDENT> | Update times for all keys in the layout. | f15498:c3:m11 |
def rampChanged(self): | self.is_saved = False<EOL>self.setWindowTitle(self.path_to_ramp_file + '<STR_LIT:*>')<EOL> | Call this whenever the ramp is changed. | f15499:c0:m2 |
def loadSettings(self): | self.settings.beginGroup('<STR_LIT>')<EOL>geometry = self.settings.value('<STR_LIT>').toByteArray()<EOL>state = self.settings.value('<STR_LIT>').toByteArray()<EOL>default_ramp_path = os.path.join(main_package_dir,<EOL>'<STR_LIT>')<EOL>self.path_to_ramp_file = str(self.settings.value('<STR_LIT>',<EOL>default_ramp_path).toString())<EOL>self.path_to_load_mot_file = str(self.settings.value('<STR_LIT>',<EOL>default_ramp_path).toString())<EOL>if not os.path.isfile(self.path_to_ramp_file):<EOL><INDENT>self.path_to_ramp_file = default_ramp_path<EOL><DEDENT>self.settings.endGroup()<EOL>self.restoreGeometry(geometry)<EOL>self.restoreState(state)<EOL> | Load window state from self.settings | f15499:c0:m3 |
def saveSettings(self): | self.settings.beginGroup('<STR_LIT>')<EOL>self.settings.setValue('<STR_LIT>', self.saveGeometry())<EOL>self.settings.setValue('<STR_LIT>', self.saveState())<EOL>self.settings.setValue('<STR_LIT>', self.path_to_ramp_file)<EOL>self.settings.setValue('<STR_LIT>',<EOL>self.path_to_load_mot_file)<EOL>self.settings.endGroup()<EOL> | Save window state to self.settings. | f15499:c0:m4 |
def setWindowTitle(self, newTitle='<STR_LIT>'): | title = '<STR_LIT>' + newTitle<EOL>super(MainWindow, self).setWindowTitle(title)<EOL> | Prepend Rampage to all window titles. | f15499:c0:m6 |
def loadSettings(self): | self.settings.beginGroup('<STR_LIT>')<EOL>geometry = self.settings.value('<STR_LIT>').toByteArray()<EOL>self.settings.endGroup()<EOL>self.restoreGeometry(geometry)<EOL> | Load window state from self.settings | f15500:c2:m5 |
def saveSettings(self): | self.settings.beginGroup('<STR_LIT>')<EOL>self.settings.setValue('<STR_LIT>', self.saveGeometry())<EOL>self.settings.endGroup()<EOL> | Save window state to self.settings. | f15500:c2:m6 |
def clearLayout(layout): | while layout.count():<EOL><INDENT>child = layout.takeAt(<NUM_LIT:0>)<EOL>child.widget().deleteLater()<EOL><DEDENT> | Removes all widgets in the layout. Useful when opening a new file, want
to clear everything. | f15502:m0 |
def edit_channel_info(self, new_ch_name, ch_dct): | self.ch_name = new_ch_name<EOL>self.dct = ch_dct<EOL>if ch_dct['<STR_LIT:type>'] == '<STR_LIT>':<EOL><INDENT>fmter = fmt.green<EOL><DEDENT>else:<EOL><INDENT>fmter = fmt.blue<EOL><DEDENT>self.ch_name_label.setText(fmt.b(fmter(self.ch_name)))<EOL>self.generateToolTip()<EOL> | Parent widget calls this whenever the user edits channel info. | f15503:c1:m5 |
def print_device_info(dev_name): | string_buffer = ctypes.create_string_buffer(<NUM_LIT>)<EOL>attributes = [pydaq.DAQmx_Dev_ProductType, pydaq.DAQmx_Dev_SerialNum,<EOL>pydaq.DAQmx_Dev_AO_PhysicalChans,<EOL>pydaq.DAQmx_Dev_CI_PhysicalChans,<EOL>pydaq.DAQmx_Dev_CO_PhysicalChans,<EOL>pydaq.DAQmx_Dev_DO_Lines]<EOL>attribute_names = ['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>']<EOL>ret_values = []<EOL>for a in attributes:<EOL><INDENT>pydaq.DAQmxGetDeviceAttribute(dev_name, a, string_buffer)<EOL>ret_values.append(str(string_buffer.value))<EOL><DEDENT>print(('<STR_LIT>' + dev_name))<EOL>for n, v in zip(attribute_names, ret_values):<EOL><INDENT>print('<STR_LIT:\t>' + n + '<STR_LIT>' + v)<EOL><DEDENT> | Prints information about the given device.
Usage:
print_device_info("Dev1") | f15507:m0 |
def get_device_name_list(): | dev_names = ctypes.create_string_buffer(<NUM_LIT>)<EOL>pydaq.DAQmxGetSysDevNames(dev_names, len(dev_names))<EOL>return dev_names.value.split('<STR_LIT:U+002CU+0020>')<EOL> | Returns a list of device names installed. | f15507:m1 |
def print_all_device_info(): | for dev in get_device_name_list():<EOL><INDENT>print_device_info(dev)<EOL><DEDENT> | Prints info on all devices. | f15507:m2 |
def reset_analog_sample_clock(state=False): | set_digital_line_state(expt_settings.dev1_clock_out_name, state)<EOL>set_digital_line_state(expt_settings.dev2_clock_out_name, state)<EOL>set_digital_line_state(expt_settings.dev3_clock_out_name, state)<EOL>set_digital_line_state(expt_settings.dev4_clock_out_name, state)<EOL> | Reset the clock line.
Use this just before starting a run to avoid timing issues. | f15507:m3 |
def set_digital_line_state(line_name, state): | <EOL>bits_to_shift = int(line_name.split('<STR_LIT>')[-<NUM_LIT:1>])<EOL>dig_data = np.ones(<NUM_LIT:2>, dtype="<STR_LIT>")*bool(state)*(<NUM_LIT:2>**bits_to_shift)<EOL>DigitalOutputTask(line_name, dig_data).StartAndWait()<EOL> | Set the state of a single digital line.
line_name (str) - The physical name of the line.
e.g line_name="Dev1/port0/line3"
This should be a single digital line. Specifying more than one would
result in unexpected behaviour. For example "Dev1/port0/line0:5" is
not allowed.
see http://zone.ni.com/reference/en-XX/help/370466W-01/mxcncpts/physchannames/
for details of naming lines.
state (bool) - state=True sets the line to high, state=False sets to low. | f15507:m4 |
def p24_pulse_train(n_samples=<NUM_LIT:100>): | samples = (np.arange(n_samples, dtype="<STR_LIT>") % <NUM_LIT:2>)*(<NUM_LIT:2>**<NUM_LIT>)<EOL>samples[-<NUM_LIT:1>] = <NUM_LIT:0><EOL>DigitalOutputTask("<STR_LIT>", samples).StartAndWait()<EOL> | Sends a pulse train of on-off in Dev1/port0/line24.
This function creates a task, starts it and waits until it is over.
Uses expt_settings.external_clock_line as a clock.
n_samples - number of on off samples. | f15507:m6 |
def StartAndWait(self): | self.StartTask()<EOL>self.WaitUntilTaskDone(pydaq.DAQmx_Val_WaitInfinitely)<EOL>self.ClearTask()<EOL> | Starts the task and waits until it is done. | f15507:c1:m2 |
def isDone(self): | done = pydaq.bool32()<EOL>self.IsTaskDone(ctypes.byref(done))<EOL>return done.value<EOL> | Returns true if task is done. | f15507:c1:m3 |
def padDigitalData(self, dig_data, n): | n = int(n)<EOL>l0 = len(dig_data)<EOL>if l0 % n == <NUM_LIT:0>:<EOL><INDENT>return dig_data <EOL><DEDENT>else:<EOL><INDENT>ladd = n - (l0 % n)<EOL>dig_data_add = np.zeros(ladd, dtype="<STR_LIT>")<EOL>dig_data_add.fill(dig_data[-<NUM_LIT:1>])<EOL>return np.concatenate((dig_data, dig_data_add))<EOL><DEDENT> | Pad dig_data with its last element so that the new array is a
multiple of n. | f15507:c2:m2 |
def EveryNCallback(self): | <EOL>if self.do_callbacks:<EOL><INDENT>if self.n_callbacks >= self.callback_step:<EOL><INDENT>for func, func_dict in self.callback_funcs:<EOL><INDENT>func(func_dict)<EOL>print(('<STR_LIT>', func))<EOL><DEDENT>self.latest_callback_index +=<NUM_LIT:1><EOL>if self.latest_callback_index >= len(self.callback_function_list):<EOL><INDENT>self.do_callbacks = False<EOL><DEDENT>else:<EOL><INDENT>out = self.callback_function_list[self.latest_callback_index]<EOL>callback_time = out[<NUM_LIT:0>]<EOL>self.callback_step = int(callback_time/expt_settings.callback_resolution)<EOL>self.callback_funcs = out[<NUM_LIT:1>]<EOL><DEDENT><DEDENT><DEDENT>self.n_callbacks += <NUM_LIT:1><EOL>return <NUM_LIT:0><EOL> | Called by PyDAQmx whenever a callback event occurs. | f15507:c2:m3 |
def DoneCallback(self, status): | logging.info('<STR_LIT>')<EOL>self.is_task_done = True<EOL>return <NUM_LIT:0><EOL> | Called whenever the task is done. | f15507:c2:m4 |
def set_output(self, state): | if state:<EOL><INDENT>self.instr.write('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>self.instr.write('<STR_LIT>')<EOL><DEDENT> | Sets whether the function generator is outputting a voltage. | f15509:c0:m2 |
def set_fm_ext(self, freq, amplitude, peak_freq_dev=None,<EOL>output_state=True): | if peak_freq_dev is None:<EOL><INDENT>peak_freq_dev = freq<EOL><DEDENT>commands = ['<STR_LIT>', <EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(freq),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(peak_freq_dev),<EOL>'<STR_LIT>'.format(amplitude),<EOL>'<STR_LIT>'] <EOL>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT>command_string = '<STR_LIT:\n>'.join(commands)<EOL>print_string = '<STR_LIT>' + command_string.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>logging.info(print_string)<EOL>self.instr.write(command_string)<EOL> | Sets the func generator to frequency modulation with external modulation.
freq is the carrier frequency in Hz. | f15509:c0:m3 |
def set_burst(self, freq, amplitude, period, output_state=True): | ncyc = int(period*freq)<EOL>commands = ['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>', <EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(freq),<EOL>'<STR_LIT>'.format(amplitude),<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(ncyc)]<EOL>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT>command_string = '<STR_LIT:\n>'.join(commands)<EOL>print_string = '<STR_LIT>' + command_string.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>logging.info(print_string)<EOL>self.instr.write(command_string)<EOL> | Sets the func generator to burst mode with external trigerring. | f15509:c0:m4 |
def set_continuous(self, freq, amplitude, offset, output_state=True): | commands = ['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(freq),<EOL>'<STR_LIT>'.format(amplitude),<EOL>'<STR_LIT>'.format(offset),<EOL>]<EOL>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT>command_string = '<STR_LIT:\n>'.join(commands)<EOL>print_string = '<STR_LIT>' + command_string.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>logging.info(print_string)<EOL>self.instr.write(command_string)<EOL> | Programs the function generator to output a continuous sine wave. | f15509:c0:m5 |
def set_arbitrary(self, freq, low_volt, high_volt, output_state=True): | commands = ['<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>',<EOL>'<STR_LIT>'.format(freq),<EOL>'<STR_LIT>'.format(high_volt),<EOL>'<STR_LIT>'.format(low_volt),<EOL>]<EOL>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT>command_string = '<STR_LIT:\n>'.join(commands)<EOL>print_string = '<STR_LIT>' + command_string.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>logging.info(print_string)<EOL>self.instr.write(command_string)<EOL> | Programs the function generator to output the arbitrary waveform. | f15509:c0:m7 |
def set_continuous(self, freq, amplitude, offset, output_state=True): | commands = ['<STR_LIT>', <EOL>'<STR_LIT>'.format(freq)<EOL>]<EOL>if freq > <NUM_LIT>:<EOL><INDENT>commands.append('<STR_LIT>'.format(amplitude)) <EOL>if offset > <NUM_LIT:0.0>:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT><DEDENT>elif freq < <NUM_LIT>:<EOL><INDENT>commands.extend(['<STR_LIT>'.format(amplitude), '<STR_LIT>'.format(offset)]) <EOL>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT><DEDENT>command_string = '<STR_LIT:\n>'.join(commands)<EOL>print_string = '<STR_LIT>' + command_string.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>logging.info(print_string)<EOL>self.instr.write(command_string)<EOL> | Programs the Stanford MW function generator to output a continuous sine wave.
External 'triggering' is accomplished using the MW switch. | f15509:c5:m3 |
def set_continuous_Vpp(self, freq, amplitude, offset, output_state=True): | commands = ['<STR_LIT>', <EOL>'<STR_LIT>'.format(freq)<EOL>]<EOL>if freq > <NUM_LIT>:<EOL><INDENT>commands.append('<STR_LIT>'.format(amplitude)) <EOL>if offset > <NUM_LIT:0.0>:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT><DEDENT>elif freq < <NUM_LIT>:<EOL><INDENT>commands.extend(['<STR_LIT>'.format(amplitude), '<STR_LIT>'.format(offset)]) <EOL>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT><DEDENT>command_string = '<STR_LIT:\n>'.join(commands)<EOL>print_string = '<STR_LIT>' + command_string.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>logging.info(print_string)<EOL>self.instr.write(command_string)<EOL> | Programs the Stanford MW function generator to output a continuous sine wave.
External 'triggering' is accomplished using the MW switch. | f15509:c5:m4 |
def set_fm_ext(self, freq, amplitude, offset=<NUM_LIT:0.0>, peak_fm_deviation=None, output_state=True): | if peak_fm_deviation is None:<EOL><INDENT>peak_fm_deviation = freq<EOL><DEDENT>commands = ['<STR_LIT>', <EOL>'<STR_LIT>', <EOL>'<STR_LIT>'.format(freq),<EOL>'<STR_LIT>'.format(peak_fm_deviation),<EOL>'<STR_LIT>' <EOL>]<EOL>if freq > <NUM_LIT>:<EOL><INDENT>commands.append('<STR_LIT>'.format(amplitude)) <EOL>if offset > <NUM_LIT:0.0>:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT><DEDENT>elif freq < <NUM_LIT>:<EOL><INDENT>commands.extend(['<STR_LIT>'.format(amplitude), '<STR_LIT>'.format(offset)]) <EOL>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT><DEDENT>command_string = '<STR_LIT:\n>'.join(commands)<EOL>print_string = '<STR_LIT>' + command_string.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>logging.info(print_string)<EOL>self.instr.write(command_string)<EOL> | Sets the Stanford MW function generator to freq modulation with external modulation.
freq is the carrier frequency in Hz. | f15509:c5:m5 |
def set_freqsweep_ext(self, amplitude, sweep_low_end, sweep_high_end, offset=<NUM_LIT:0.0>, output_state=True): | sweep_deviation = round(abs(sweep_low_end - sweep_high_end)/<NUM_LIT>,<NUM_LIT:6>)<EOL>freq = sweep_low_end + sweep_deviation<EOL>commands = ['<STR_LIT>', <EOL>'<STR_LIT>', <EOL>'<STR_LIT>'.format(freq),<EOL>'<STR_LIT>'.format(sweep_deviation),<EOL>'<STR_LIT>' <EOL>]<EOL>if freq > <NUM_LIT>:<EOL><INDENT>commands.append('<STR_LIT>'.format(amplitude)) <EOL>if offset > <NUM_LIT:0.0>:<EOL><INDENT>print('<STR_LIT>')<EOL><DEDENT>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT><DEDENT>elif freq < <NUM_LIT>:<EOL><INDENT>commands.extend(['<STR_LIT>'.format(amplitude), '<STR_LIT>'.format(offset)]) <EOL>if output_state is True:<EOL><INDENT>commands.append('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>commands.append('<STR_LIT>')<EOL><DEDENT><DEDENT>command_string = '<STR_LIT:\n>'.join(commands)<EOL>print_string = '<STR_LIT>' + command_string.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>logging.info(print_string)<EOL>self.instr.write(command_string)<EOL> | Sets the Stanford MW function generator to freq modulation with external modulation.
freq is the carrier frequency in Hz. | f15509:c5:m6 |
def set_output(self, state): | freq = float(self.instr.query('<STR_LIT>'))<EOL>if freq > <NUM_LIT>:<EOL><INDENT>if state:<EOL><INDENT>self.instr.write('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>self.instr.write('<STR_LIT>')<EOL><DEDENT><DEDENT>elif freq < <NUM_LIT>:<EOL><INDENT>if state:<EOL><INDENT>self.instr.write('<STR_LIT>') <EOL><DEDENT>else:<EOL><INDENT>self.instr.write('<STR_LIT>')<EOL><DEDENT><DEDENT> | Sets whether the function generator is outputting a voltage. | f15509:c5:m7 |
def trigger_ListMode(self): | self.instr.write('<STR_LIT>')<EOL> | Iterates the function generator to the next state in ListMode
NOTE: ListMode does not enable outputs, but only writes the function
generator state. Output must be enabled separately | f15509:c5:m8 |
def disable_all(self, disable): | commands = ['<STR_LIT>', <EOL>'<STR_LIT>', <EOL>'<STR_LIT>' <EOL>]<EOL>command_string = '<STR_LIT:\n>'.join(commands)<EOL>print_string = '<STR_LIT>' + command_string.replace('<STR_LIT:\n>', '<STR_LIT>')<EOL>logging.info(print_string)<EOL>if disable:<EOL><INDENT>self.instr.write(command_string)<EOL><DEDENT> | Disables all modulation and outputs of the Standford MW func. generator | f15509:c5:m9 |
def set_output(self, state, channel=<NUM_LIT:2>): | if state:<EOL><INDENT>self.instr.write('<STR_LIT>'.format(channel))<EOL><DEDENT>else:<EOL><INDENT>self.instr.write('<STR_LIT>'.format(channel))<EOL><DEDENT> | Sets whether the function generator is outputting a voltage. | f15509:c6:m2 |
def set_continuous(self, freq, amplitude, offset, phase, channel=<NUM_LIT:2>): | commands = ['<STR_LIT>'.format(channel),<EOL>'<STR_LIT>'.format(freq),<EOL>'<STR_LIT>'.format(amplitude),<EOL>'<STR_LIT>'.format(offset),<EOL>'<STR_LIT>'.format(phase),<EOL>]<EOL>command_string = '<STR_LIT>'.join(commands)<EOL>logging.info(command_string)<EOL>self.instr.write(command_string)<EOL> | Programs the function generator to output a continuous sine wave. | f15509:c6:m3 |
def format_code(source, preferred_quote="<STR_LIT:'>"): | try:<EOL><INDENT>return _format_code(source, preferred_quote)<EOL><DEDENT>except (tokenize.TokenError, IndentationError):<EOL><INDENT>return source<EOL><DEDENT> | Return source code with quotes unified. | f15514:m0 |
def _format_code(source, preferred_quote): | if not source:<EOL><INDENT>return source<EOL><DEDENT>modified_tokens = []<EOL>sio = io.StringIO(source)<EOL>for (token_type,<EOL>token_string,<EOL>start,<EOL>end,<EOL>line) in tokenize.generate_tokens(sio.readline):<EOL><INDENT>if token_type == tokenize.STRING:<EOL><INDENT>token_string = unify_quotes(token_string,<EOL>preferred_quote=preferred_quote)<EOL><DEDENT>modified_tokens.append(<EOL>(token_type, token_string, start, end, line))<EOL><DEDENT>return untokenize.untokenize(modified_tokens)<EOL> | Return source code with quotes unified. | f15514:m1 |
def unify_quotes(token_string, preferred_quote): | bad_quote = {'<STR_LIT:">': "<STR_LIT:'>",<EOL>"<STR_LIT:'>": '<STR_LIT:">'}[preferred_quote]<EOL>allowed_starts = {<EOL>'<STR_LIT>': bad_quote,<EOL>'<STR_LIT:f>': '<STR_LIT:f>' + bad_quote,<EOL>'<STR_LIT:b>': '<STR_LIT:b>' + bad_quote<EOL>}<EOL>if not any(token_string.startswith(start)<EOL>for start in allowed_starts.values()):<EOL><INDENT>return token_string<EOL><DEDENT>if token_string.count(bad_quote) != <NUM_LIT:2>:<EOL><INDENT>return token_string<EOL><DEDENT>if preferred_quote in token_string:<EOL><INDENT>return token_string<EOL><DEDENT>assert token_string.endswith(bad_quote)<EOL>assert len(token_string) >= <NUM_LIT:2><EOL>for prefix, start in allowed_starts.items():<EOL><INDENT>if token_string.startswith(start):<EOL><INDENT>chars_to_strip_from_front = len(start)<EOL>return '<STR_LIT>'.format(<EOL>prefix=prefix,<EOL>preferred_quote=preferred_quote,<EOL>token=token_string[chars_to_strip_from_front:-<NUM_LIT:1>]<EOL>)<EOL><DEDENT><DEDENT> | Return string with quotes changed to preferred_quote if possible. | f15514:m2 |
def open_with_encoding(filename, encoding, mode='<STR_LIT:r>'): | return io.open(filename, mode=mode, encoding=encoding,<EOL>newline='<STR_LIT>')<EOL> | Return opened file with a specific encoding. | f15514:m3 |
def detect_encoding(filename): | try:<EOL><INDENT>with open(filename, '<STR_LIT:rb>') as input_file:<EOL><INDENT>from lib2to3.pgen2 import tokenize as lib2to3_tokenize<EOL>encoding = lib2to3_tokenize.detect_encoding(input_file.readline)[<NUM_LIT:0>]<EOL>with open_with_encoding(filename, encoding) as input_file:<EOL><INDENT>input_file.read()<EOL><DEDENT><DEDENT>return encoding<EOL><DEDENT>except (SyntaxError, LookupError, UnicodeDecodeError):<EOL><INDENT>return '<STR_LIT>'<EOL><DEDENT> | Return file encoding. | f15514:m4 |
def format_file(filename, args, standard_out): | encoding = detect_encoding(filename)<EOL>with open_with_encoding(filename, encoding=encoding) as input_file:<EOL><INDENT>source = input_file.read()<EOL>formatted_source = format_code(<EOL>source,<EOL>preferred_quote=args.quote)<EOL><DEDENT>if source != formatted_source:<EOL><INDENT>if args.in_place:<EOL><INDENT>with open_with_encoding(filename, mode='<STR_LIT:w>',<EOL>encoding=encoding) as output_file:<EOL><INDENT>output_file.write(formatted_source)<EOL><DEDENT><DEDENT>else:<EOL><INDENT>import difflib<EOL>diff = difflib.unified_diff(<EOL>source.splitlines(),<EOL>formatted_source.splitlines(),<EOL>'<STR_LIT>' + filename,<EOL>'<STR_LIT>' + filename,<EOL>lineterm='<STR_LIT>')<EOL>standard_out.write('<STR_LIT:\n>'.join(list(diff) + ['<STR_LIT>']))<EOL>return True<EOL><DEDENT><DEDENT> | Run format_code() on a file.
Returns `True` if any changes are needed and they are not being done
in-place. | f15514:m5 |
def _main(argv, standard_out, standard_error): | import argparse<EOL>parser = argparse.ArgumentParser(description=__doc__, prog='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>',<EOL>help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT:-c>', '<STR_LIT>', action='<STR_LIT:store_true>',<EOL>help='<STR_LIT>'<EOL>'<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', '<STR_LIT>', action='<STR_LIT:store_true>',<EOL>help='<STR_LIT>')<EOL>parser.add_argument('<STR_LIT>', help='<STR_LIT>', choices=["<STR_LIT:'>", '<STR_LIT:">'],<EOL>default="<STR_LIT:'>")<EOL>parser.add_argument('<STR_LIT>', action='<STR_LIT:version>',<EOL>version='<STR_LIT>' + __version__)<EOL>parser.add_argument('<STR_LIT>', nargs='<STR_LIT:+>',<EOL>help='<STR_LIT>')<EOL>args = parser.parse_args(argv[<NUM_LIT:1>:])<EOL>filenames = list(set(args.files))<EOL>changes_needed = False<EOL>failure = False<EOL>while filenames:<EOL><INDENT>name = filenames.pop(<NUM_LIT:0>)<EOL>if args.recursive and os.path.isdir(name):<EOL><INDENT>for root, directories, children in os.walk(unicode(name)):<EOL><INDENT>filenames += [os.path.join(root, f) for f in children<EOL>if f.endswith('<STR_LIT>') and<EOL>not f.startswith('<STR_LIT:.>')]<EOL>directories[:] = [d for d in directories<EOL>if not d.startswith('<STR_LIT:.>')]<EOL><DEDENT><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>if format_file(name, args=args, standard_out=standard_out):<EOL><INDENT>changes_needed = True<EOL><DEDENT><DEDENT>except IOError as exception:<EOL><INDENT>print(unicode(exception), file=standard_error)<EOL>failure = True<EOL><DEDENT><DEDENT><DEDENT>if failure or (args.check_only and changes_needed):<EOL><INDENT>return <NUM_LIT:1><EOL><DEDENT> | Run quotes unifying on files.
Returns `1` if any quoting changes are still needed, otherwise
`None`. | f15514:m6 |
def main(): | try:<EOL><INDENT>signal.signal(signal.SIGPIPE, signal.SIG_DFL)<EOL><DEDENT>except AttributeError:<EOL><INDENT>pass<EOL><DEDENT>try:<EOL><INDENT>return _main(sys.argv,<EOL>standard_out=sys.stdout,<EOL>standard_error=sys.stderr)<EOL><DEDENT>except KeyboardInterrupt:<EOL><INDENT>return <NUM_LIT:2><EOL><DEDENT> | Main entry point. | f15514:m7 |
@contextlib.contextmanager<EOL>def temporary_file(contents, directory='<STR_LIT:.>', prefix='<STR_LIT>'): | f = tempfile.NamedTemporaryFile(suffix='<STR_LIT>', prefix=prefix,<EOL>delete=False, dir=directory)<EOL>try:<EOL><INDENT>f.write(contents.encode())<EOL>f.close()<EOL>yield f.name<EOL><DEDENT>finally:<EOL><INDENT>import os<EOL>os.remove(f.name)<EOL><DEDENT> | Write contents to temporary file and yield it. | f15515:m0 |
@contextlib.contextmanager<EOL>def temporary_directory(directory='<STR_LIT:.>', prefix='<STR_LIT>'): | temp_directory = tempfile.mkdtemp(prefix=prefix, dir=directory)<EOL>try:<EOL><INDENT>yield temp_directory<EOL><DEDENT>finally:<EOL><INDENT>import shutil<EOL>shutil.rmtree(temp_directory)<EOL><DEDENT> | Create temporary directory and yield its path. | f15515:m1 |
def version(): | with open('<STR_LIT>') as input_file:<EOL><INDENT>for line in input_file:<EOL><INDENT>if line.startswith('<STR_LIT>'):<EOL><INDENT>return ast.parse(line).body[<NUM_LIT:0>].value.s<EOL><DEDENT><DEDENT><DEDENT> | Return version string. | f15516:m0 |
@staticmethod<EOL><INDENT>def from_dict(data):<DEDENT> | data = deepcopy(data)<EOL>created_at = data.get('<STR_LIT>', None)<EOL>if created_at is not None:<EOL><INDENT>data['<STR_LIT>'] = dateutil.parser.parse(created_at)<EOL><DEDENT>return Image(**data)<EOL> | Create a new instance from dict
:param data: A JSON dict | f15519:c0:m1 |
def __str__(self): | return self.to_json()<EOL> | Return a string representation of this instance | f15519:c0:m2 |
def __unicode__(self): | return self.to_json()<EOL> | Return a string representation of this instance | f15519:c0:m3 |
@property<EOL><INDENT>def filename(self):<DEDENT> | if self.url:<EOL><INDENT>return self.url.split('<STR_LIT:/>')[-<NUM_LIT:1>]<EOL><DEDENT>return None<EOL> | An image filename
:getter: Return an image filename if it exists | f15519:c0:m5 |
@property<EOL><INDENT>def thumb_filename(self):<DEDENT> | return self.thumb_url.split('<STR_LIT:/>')[-<NUM_LIT:1>]<EOL> | A thumbnail image filename
:getter: Return a thumbnail filename | f15519:c0:m6 |
@property<EOL><INDENT>def local_created_at(self):<DEDENT> | return self.created_at.astimezone(dateutil.tz.tzlocal())<EOL> | The time this image was created in local time zone
:getter: Return the time this image was created in local time zone | f15519:c0:m7 |
def to_json(self, indent=None, sort_keys=True): | return json.dumps(self.to_dict(), indent=indent, sort_keys=sort_keys)<EOL> | Return a JSON string representation of this instance
:param indent: specify an indent level or a string used to indent each
level
:param sort_keys: the output is sorted by key | f15519:c0:m8 |
def to_dict(self): | data = {}<EOL>if self.created_at:<EOL><INDENT>data['<STR_LIT>'] = self.created_at.strftime(<EOL>'<STR_LIT>')<EOL><DEDENT>if self.image_id:<EOL><INDENT>data['<STR_LIT>'] = self.image_id<EOL><DEDENT>if self.permalink_url:<EOL><INDENT>data['<STR_LIT>'] = self.permalink_url<EOL><DEDENT>if self.thumb_url:<EOL><INDENT>data['<STR_LIT>'] = self.thumb_url<EOL><DEDENT>if self.type:<EOL><INDENT>data['<STR_LIT:type>'] = self.type<EOL><DEDENT>if self.url:<EOL><INDENT>data['<STR_LIT:url>'] = self.url<EOL><DEDENT>return data<EOL> | Return a dict representation of this instance | f15519:c0:m9 |
def download(self): | if self.url:<EOL><INDENT>try:<EOL><INDENT>return requests.get(self.url).content<EOL><DEDENT>except requests.RequestException as e:<EOL><INDENT>raise GyazoError(str(e))<EOL><DEDENT><DEDENT>return None<EOL> | Download an image file if it exists
:raise GyazoError: | f15519:c0:m10 |
def download_thumb(self): | try:<EOL><INDENT>return requests.get(self.thumb_url).content<EOL><DEDENT>except requests.RequestException as e:<EOL><INDENT>raise GyazoError(str(e))<EOL><DEDENT> | Download a thumbnail image file
:raise GyazoError: | f15519:c0:m11 |
@property<EOL><INDENT>def num_pages(self):<DEDENT> | return math.ceil(self.total_count / self.per_page)<EOL> | The number of pages
:getter: Return the number of pages | f15519:c1:m7 |
def has_next_page(self): | return self.current_page < math.ceil(self.total_count / self.per_page)<EOL> | Whether there is a next page or not
:getter: Return true if there is a next page | f15519:c1:m8 |
def has_previous_page(self): | return <NUM_LIT:0> < self.current_page<EOL> | Whether there is a previous page or not
:getter: Return true if there is a previous page | f15519:c1:m9 |
def set_attributes_from_headers(self, headers): | self.total_count = headers.get('<STR_LIT>', None)<EOL>self.current_page = headers.get('<STR_LIT>', None)<EOL>self.per_page = headers.get('<STR_LIT>', None)<EOL>self.user_type = headers.get('<STR_LIT>', None)<EOL>if self.total_count:<EOL><INDENT>self.total_count = int(self.total_count)<EOL><DEDENT>if self.current_page:<EOL><INDENT>self.current_page = int(self.current_page)<EOL><DEDENT>if self.per_page:<EOL><INDENT>self.per_page = int(self.per_page)<EOL><DEDENT> | Set instance attributes with HTTP header
:param headers: HTTP header | f15519:c1:m10 |
def to_json(self, indent=None, sort_keys=True): | return json.dumps([i.to_dict() for i in self.images],<EOL>indent=indent, sort_keys=sort_keys)<EOL> | Return a JSON string representation of this instance
:param indent: specify an indent level or a string used to indent each
level
:param sort_keys: the output of dictionaries is sorted by key | f15519:c1:m11 |
@staticmethod<EOL><INDENT>def from_list(data):<DEDENT> | return ImageList(images=[Image.from_dict(d) for d in data])<EOL> | Create a new instance from list
:param data: A JSON list | f15519:c1:m12 |
def __init__(self,<EOL>client_id=None,<EOL>client_secret=None,<EOL>access_token=None,<EOL>api_url='<STR_LIT>',<EOL>upload_url='<STR_LIT>'): | self.api_url = api_url<EOL>self.upload_url = upload_url<EOL>self._client_id = client_id<EOL>self._client_secret = client_secret<EOL>self._access_token = access_token<EOL> | :param client_id: API client ID
:param client_secret: API secret
:param access_token: API access token
:param api_url: (optional) API endpoint URL
(default: https://api.gyazo.com)
:param upload_url: (optional) Upload API endpoint URL
(default: https://upload.gyazo.com) | f15522:c0:m0 |
def get_image_list(self, page=<NUM_LIT:1>, per_page=<NUM_LIT:20>): | url = self.api_url + '<STR_LIT>'<EOL>params = {<EOL>'<STR_LIT>': page,<EOL>'<STR_LIT>': per_page<EOL>}<EOL>response = self._request_url(<EOL>url, '<STR_LIT>', params=params, with_access_token=True)<EOL>headers, result = self._parse_and_check(response)<EOL>images = ImageList.from_list(result)<EOL>images.set_attributes_from_headers(headers)<EOL>return images<EOL> | Return a list of user's saved images
:param page: (optional) Page number (default: 1)
:param per_page: (optional) Number of images per page
(default: 20, min: 1, max: 100) | f15522:c0:m1 |
def upload_image(self,<EOL>image_file,<EOL>referer_url=None,<EOL>title=None,<EOL>desc=None,<EOL>created_at=None,<EOL>collection_id=None): | url = self.upload_url + '<STR_LIT>'<EOL>data = {}<EOL>if referer_url is not None:<EOL><INDENT>data['<STR_LIT>'] = referer_url<EOL><DEDENT>if title is not None:<EOL><INDENT>data['<STR_LIT:title>'] = title<EOL><DEDENT>if desc is not None:<EOL><INDENT>data['<STR_LIT>'] = desc<EOL><DEDENT>if created_at is not None:<EOL><INDENT>data['<STR_LIT>'] = str(created_at)<EOL><DEDENT>if collection_id is not None:<EOL><INDENT>data['<STR_LIT>'] = collection_id<EOL><DEDENT>files = {<EOL>'<STR_LIT>': image_file<EOL>}<EOL>response = self._request_url(<EOL>url, '<STR_LIT>', data=data, files=files, with_access_token=True)<EOL>headers, result = self._parse_and_check(response)<EOL>return Image.from_dict(result)<EOL> | Upload an image
:param image_file: File-like object of an image file
:param referer_url: Referer site URL
:param title: Site title
:param desc: Comment
:param created_at: Image's created time in unix time
:param collection_id: Collection ID | f15522:c0:m2 |
def delete_image(self, image_id): | url = self.api_url + '<STR_LIT>' + image_id<EOL>response = self._request_url(url, '<STR_LIT>', with_access_token=True)<EOL>headers, result = self._parse_and_check(response)<EOL>return Image.from_dict(result)<EOL> | Delete an image
:param image_id: Image ID | f15522:c0:m3 |
def get_oembed(self, url): | api_url = self.api_url + '<STR_LIT>'<EOL>parameters = {<EOL>'<STR_LIT:url>': url<EOL>}<EOL>response = self._request_url(api_url, '<STR_LIT>', params=parameters)<EOL>headers, result = self._parse_and_check(response)<EOL>return result<EOL> | Return an oEmbed format json dictionary
:param url: Image page URL (ex. http://gyazo.com/xxxxx) | f15522:c0:m4 |
def _request_url(self,<EOL>url,<EOL>method,<EOL>params=None,<EOL>data=None,<EOL>files=None,<EOL>with_client_id=False,<EOL>with_access_token=False): | headers = {} <EOL>if data is None:<EOL><INDENT>data = {}<EOL><DEDENT>if params is None:<EOL><INDENT>params = {}<EOL><DEDENT>if with_client_id and self._client_id is not None:<EOL><INDENT>params['<STR_LIT>'] = self._client_id<EOL><DEDENT>if with_access_token and self._access_token is not None:<EOL><INDENT>headers['<STR_LIT>'] = "<STR_LIT>" + self._access_token<EOL><DEDENT>try:<EOL><INDENT>return requests.request(method, url,<EOL>params=params,<EOL>data=data,<EOL>files=files,<EOL>headers=headers)<EOL><DEDENT>except requests.RequestException as e:<EOL><INDENT>raise GyazoError(str(e))<EOL><DEDENT> | Send HTTP request
:param url: URL
:param method: HTTP method (get, post or delete)
:param with_client_id: send request with client_id (default: false)
:param with_access_token: send request with with_access_token
(default: false)
:raise GyazoError: | f15522:c0:m5 |
def __init__(self, ll_func, log_prior_func, x0, data=None, cl_runtime_info=None, **kwargs): | self._cl_runtime_info = cl_runtime_info or CLRuntimeInfo()<EOL>self._logger = logging.getLogger(__name__)<EOL>self._ll_func = ll_func<EOL>self._log_prior_func = log_prior_func<EOL>self._data = data<EOL>self._x0 = x0<EOL>if len(x0.shape) < <NUM_LIT:2>:<EOL><INDENT>self._x0 = self._x0[..., None]<EOL><DEDENT>self._nmr_problems = self._x0.shape[<NUM_LIT:0>]<EOL>self._nmr_params = self._x0.shape[<NUM_LIT:1>]<EOL>self._sampling_index = <NUM_LIT:0><EOL>float_type = self._cl_runtime_info.mot_float_dtype<EOL>self._current_chain_position = np.require(np.copy(self._x0), requirements='<STR_LIT>', dtype=float_type)<EOL>self._current_log_likelihood = np.zeros(self._nmr_problems, dtype=float_type)<EOL>self._current_log_prior = np.zeros(self._nmr_problems, dtype=float_type)<EOL>self._rng_state = np.random.uniform(low=np.iinfo(np.uint32).min, high=np.iinfo(np.uint32).max + <NUM_LIT:1>,<EOL>size=(self._nmr_problems, <NUM_LIT:6>)).astype(np.uint32)<EOL>self._initialize_likelihood_prior(self._current_chain_position, self._current_log_likelihood,<EOL>self._current_log_prior)<EOL> | Abstract base class for sample routines.
Sampling routines implementing this interface should be stateful objects that, for the given likelihood
and prior, keep track of the sample state over multiple calls to :meth:`sample`.
Args:
ll_func (mot.lib.cl_function.CLFunction): The log-likelihood function. A CL function with the signature:
.. code-block:: c
double <func_name>(local const mot_float_type* const x, void* data);
log_prior_func (mot.lib.cl_function.CLFunction): The log-prior function. A CL function with the signature:
.. code-block:: c
mot_float_type <func_name>(local const mot_float_type* const x, void* data);
x0 (ndarray): the starting positions for the sampler. Should be a two dimensional matrix
with for every modeling instance (first dimension) and every parameter (second dimension) a value.
data (mot.lib.kernel_data.KernelData): the user provided data for the ``void* data`` pointer. | f15532:c0:m0 |
def _get_mcmc_method_kernel_data(self): | raise NotImplementedError()<EOL> | Get the kernel data specific for the implemented method.
This will be provided as a void pointer to the implementing MCMC method.
Returns:
mot.lib.kernel_data.KernelData: the kernel data object | f15532:c0:m1 |
def _get_state_update_cl_func(self, nmr_samples, thinning, return_output): | raise NotImplementedError()<EOL> | Get the function that can advance the sampler state.
This function is called by the MCMC sampler to draw and return a new sample.
Args:
nmr_samples (int): the number of samples we will draw
thinning (int): the thinning factor we want to use
return_output (boolean): if the kernel should return output
Returns:
str: a CL function with signature:
.. code-block:: c
void _advanceSampler(void* method_data,
void* data,
ulong current_iteration,
void* rng_data,
global mot_float_type* current_position,
global mot_float_type* current_log_likelihood,
global mot_float_type* current_log_prior); | f15532:c0:m2 |
def set_cl_runtime_info(self, cl_runtime_info): | self._cl_runtime_info = cl_runtime_info<EOL> | Update the CL runtime information.
Args:
cl_runtime_info (mot.configuration.CLRuntimeInfo): the new runtime information | f15532:c0:m3 |
def sample(self, nmr_samples, burnin=<NUM_LIT:0>, thinning=<NUM_LIT:1>): | if not thinning or thinning < <NUM_LIT:1>:<EOL><INDENT>thinning = <NUM_LIT:1><EOL><DEDENT>if not burnin or burnin < <NUM_LIT:0>:<EOL><INDENT>burnin = <NUM_LIT:0><EOL><DEDENT>max_samples_per_batch = max(<NUM_LIT:1000> // thinning, <NUM_LIT:100>)<EOL>with self._logging(nmr_samples, burnin, thinning):<EOL><INDENT>if burnin > <NUM_LIT:0>:<EOL><INDENT>for batch_start, batch_end in split_in_batches(burnin, max_samples_per_batch):<EOL><INDENT>self._sample(batch_end - batch_start, return_output=False)<EOL><DEDENT><DEDENT>if nmr_samples > <NUM_LIT:0>:<EOL><INDENT>outputs = []<EOL>for batch_start, batch_end in split_in_batches(nmr_samples, max_samples_per_batch):<EOL><INDENT>outputs.append(self._sample(batch_end - batch_start, thinning=thinning))<EOL><DEDENT>return SimpleSampleOutput(*[np.concatenate([o[ind] for o in outputs], axis=-<NUM_LIT:1>) for ind in range(<NUM_LIT:3>)])<EOL><DEDENT><DEDENT> | Take additional samples from the given likelihood and prior, using this sampler.
This method can be called multiple times in which the sample state is stored in between.
Args:
nmr_samples (int): the number of samples to return
burnin (int): the number of samples to discard before returning samples
thinning (int): how many sample we wait before storing a new one. This will draw extra samples such that
the total number of samples generated is ``nmr_samples * (thinning)`` and the number of samples
stored is ``nmr_samples``. If set to one or lower we store every sample after the burn in.
Returns:
SamplingOutput: the sample output object | f15532:c0:m4 |
def _sample(self, nmr_samples, thinning=<NUM_LIT:1>, return_output=True): | kernel_data = self._get_kernel_data(nmr_samples, thinning, return_output)<EOL>sample_func = self._get_compute_func(nmr_samples, thinning, return_output)<EOL>sample_func.evaluate(kernel_data, self._nmr_problems,<EOL>use_local_reduction=all(env.is_gpu for env in self._cl_runtime_info.cl_environments),<EOL>cl_runtime_info=self._cl_runtime_info)<EOL>self._sampling_index += nmr_samples * thinning<EOL>if return_output:<EOL><INDENT>return (kernel_data['<STR_LIT>'].get_data(),<EOL>kernel_data['<STR_LIT>'].get_data(),<EOL>kernel_data['<STR_LIT>'].get_data())<EOL><DEDENT> | Sample the given number of samples with the given thinning.
If ``return_output`` we will return the samples, log likelihoods and log priors. If not, we will advance the
state of the sampler without returning storing the samples.
Args:
nmr_samples (int): the number of iterations to advance the sampler
thinning (int): the thinning to apply
return_output (boolean): if we should return the output
Returns:
None or tuple: if ``return_output`` is True three ndarrays as (samples, log_likelihoods, log_priors) | f15532:c0:m5 |
def _initialize_likelihood_prior(self, positions, log_likelihoods, log_priors): | func = SimpleCLFunction.from_string('''<STR_LIT>''' + str(self._nmr_params) + '''<STR_LIT>''', dependencies=[self._get_log_prior_cl_func(), self._get_log_likelihood_cl_func()])<EOL>kernel_data = {<EOL>'<STR_LIT>': Array(positions, '<STR_LIT>', mode='<STR_LIT>', ensure_zero_copy=True),<EOL>'<STR_LIT>': Array(log_likelihoods, '<STR_LIT>', mode='<STR_LIT>', ensure_zero_copy=True),<EOL>'<STR_LIT>': Array(log_priors, '<STR_LIT>', mode='<STR_LIT>', ensure_zero_copy=True),<EOL>'<STR_LIT>': LocalMemory('<STR_LIT>', self._nmr_params),<EOL>'<STR_LIT:data>': self._data<EOL>}<EOL>func.evaluate(kernel_data, self._nmr_problems,<EOL>use_local_reduction=all(env.is_gpu for env in self._cl_runtime_info.cl_environments),<EOL>cl_runtime_info=self._cl_runtime_info)<EOL> | Initialize the likelihood and the prior using the given positions.
This is a general method for computing the log likelihoods and log priors for given positions.
Subclasses can use this to instantiate secondary chains as well. | f15532:c0:m6 |
def _get_kernel_data(self, nmr_samples, thinning, return_output): | kernel_data = {<EOL>'<STR_LIT:data>': self._data,<EOL>'<STR_LIT>': self._get_mcmc_method_kernel_data(),<EOL>'<STR_LIT>': Scalar(nmr_samples * thinning, ctype='<STR_LIT>'),<EOL>'<STR_LIT>': Scalar(self._sampling_index, ctype='<STR_LIT>'),<EOL>'<STR_LIT>': Array(self._rng_state, '<STR_LIT>', mode='<STR_LIT>', ensure_zero_copy=True),<EOL>'<STR_LIT>': Array(self._current_chain_position, '<STR_LIT>',<EOL>mode='<STR_LIT>', ensure_zero_copy=True),<EOL>'<STR_LIT>': Array(self._current_log_likelihood, '<STR_LIT>',<EOL>mode='<STR_LIT>', ensure_zero_copy=True),<EOL>'<STR_LIT>': Array(self._current_log_prior, '<STR_LIT>',<EOL>mode='<STR_LIT>', ensure_zero_copy=True),<EOL>}<EOL>if return_output:<EOL><INDENT>kernel_data.update({<EOL>'<STR_LIT>': Zeros((self._nmr_problems, self._nmr_params, nmr_samples), ctype='<STR_LIT>'),<EOL>'<STR_LIT>': Zeros((self._nmr_problems, nmr_samples), ctype='<STR_LIT>'),<EOL>'<STR_LIT>': Zeros((self._nmr_problems, nmr_samples), ctype='<STR_LIT>'),<EOL>})<EOL><DEDENT>return kernel_data<EOL> | Get the kernel data we will input to the MCMC sampler.
This sets the items:
* data: the pointer to the user provided data
* method_data: the data specific to the MCMC method
* nmr_iterations: the number of iterations to sample
* iteration_offset: the current sample index, that is, the offset to the given number of iterations
* rng_state: the random number generator state
* current_chain_position: the current position of the sampled chain
* current_log_likelihood: the log likelihood of the current position on the chain
* current_log_prior: the log prior of the current position on the chain
Additionally, if ``return_output`` is True, we add to that the arrays:
* samples: for the samples
* log_likelihoods: for storing the log likelihoods
* log_priors: for storing the priors
Args:
nmr_samples (int): the number of samples we will draw
thinning (int): the thinning factor we want to use
return_output (boolean): if the kernel should return output
Returns:
dict[str: mot.lib.utils.KernelData]: the kernel input data | f15532:c0:m7 |
def _get_compute_func(self, nmr_samples, thinning, return_output): | cl_func = '''<STR_LIT>''' + ('''<STR_LIT>''' if return_output else '<STR_LIT>') + '''<STR_LIT>'''<EOL>if return_output:<EOL><INDENT>cl_func += '''<STR_LIT>''' + str(thinning) + '''<STR_LIT>''' + str(thinning) + '''<STR_LIT>''' + str(thinning) + '''<STR_LIT>''' + str(self._nmr_params) + '''<STR_LIT>''' + str(thinning) + '''<STR_LIT>''' + str(nmr_samples) + '''<STR_LIT>'''<EOL><DEDENT>cl_func += '''<STR_LIT>'''<EOL>return SimpleCLFunction.from_string(<EOL>cl_func,<EOL>dependencies=[Rand123(), self._get_log_prior_cl_func(),<EOL>self._get_log_likelihood_cl_func(),<EOL>SimpleCLCodeObject(self._get_state_update_cl_func(nmr_samples, thinning, return_output))])<EOL> | Get the MCMC algorithm as a computable function.
Args:
nmr_samples (int): the number of samples we will draw
thinning (int): the thinning factor we want to use
return_output (boolean): if the kernel should return output
Returns:
mot.lib.cl_function.CLFunction: the compute function | f15532:c0:m8 |
def _get_log_prior_cl_func(self): | return SimpleCLFunction.from_string('''<STR_LIT>''' + self._log_prior_func.get_cl_function_name() + '''<STR_LIT>''', dependencies=[self._log_prior_func])<EOL> | Get the CL log prior compute function.
Returns:
str: the compute function for computing the log prior. | f15532:c0:m9 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.