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 = ke...
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_p...
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...
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_p...
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_ab...
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)<EO...
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 = ...
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 ...
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)....
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(...
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_L...
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...
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):...
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_L...
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>els...
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>...
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><DEDEN...
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><INDE...
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><INDE...
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...
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.app...
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:<...
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>...
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....
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><DEDEN...
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 op...
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...
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['...
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:<...
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_f...
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><IN...
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...
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 GyazoErr...
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_pro...
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-...
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): ...
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 burni...
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 befo...
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...
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 ...
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_likelih...
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...
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 ...
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) +...
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.CLFun...
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