text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emulate_press(self, key_code, scan_code, value, timeval):
"""Emulate a button press. Currently supports 5 buttons. The Microsoft documentation does not define what happens with a mouse with more than five buttons, and I don't have such a mouse. From reading the Linux sources, I guess evdev can support up to 255 buttons. Therefore, I guess we could support more buttons quite easily, if we had any useful hardware. """ |
scan_event = self.create_event_object(
"Misc",
0x04,
scan_code,
timeval)
key_event = self.create_event_object(
"Key",
key_code,
value,
timeval)
return scan_event, key_event |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emulate_abs(self, x_val, y_val, timeval):
"""Emulate the absolute co-ordinates of the mouse cursor.""" |
x_event = self.create_event_object(
"Absolute",
0x00,
x_val,
timeval)
y_event = self.create_event_object(
"Absolute",
0x01,
y_val,
timeval)
return x_event, y_event |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def listen():
"""Listen for keyboard input.""" |
msg = MSG()
ctypes.windll.user32.GetMessageA(ctypes.byref(msg), 0, 0, 0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_fptr(self):
"""Get the function pointer.""" |
cmpfunc = ctypes.CFUNCTYPE(ctypes.c_int,
WPARAM,
LPARAM,
ctypes.POINTER(KBDLLHookStruct))
return cmpfunc(self.handle_input) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def install_handle_input(self):
"""Install the hook.""" |
self.pointer = self.get_fptr()
self.hooked = ctypes.windll.user32.SetWindowsHookExA(
13,
self.pointer,
ctypes.windll.kernel32.GetModuleHandleW(None),
0
)
if not self.hooked:
return False
return True |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def uninstall_handle_input(self):
"""Remove the hook.""" |
if self.hooked is None:
return
ctypes.windll.user32.UnhookWindowsHookEx(self.hooked)
self.hooked = None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def emulate_mouse(self, key_code, x_val, y_val, data):
"""Emulate the ev codes using the data Windows has given us. Note that by default in Windows, to recognise a double click, you just notice two clicks in a row within a reasonablely short time period. However, if the application developer sets the application window's class style to CS_DBLCLKS, the operating system will notice the four button events (down, up, down, up), intercept them and then send a single key code instead. There are no such special double click codes on other platforms, so not obvious what to do with them. It might be best to just convert them back to four events. Currently we do nothing. ((0x0203, 'WM_LBUTTONDBLCLK'), (0x0206, 'WM_RBUTTONDBLCLK'), (0x0209, 'WM_MBUTTONDBLCLK'), (0x020D, 'WM_XBUTTONDBLCLK')) """ |
# Once again ignore Windows' relative time (since system
# startup) and use the absolute time (since epoch i.e. 1st Jan
# 1970).
self.update_timeval()
events = []
if key_code == 0x0200:
# We have a mouse move alone.
# So just pass through to below
pass
elif key_code == 0x020A:
# We have a vertical mouse wheel turn
events.append(self.emulate_wheel(data, 'y', self.timeval))
elif key_code == 0x020E:
# We have a horizontal mouse wheel turn
# https://msdn.microsoft.com/en-us/library/windows/desktop/
# ms645614%28v=vs.85%29.aspx
events.append(self.emulate_wheel(data, 'x', self.timeval))
else:
# We have a button press.
# Distinguish the second extra button
if key_code == 0x020B and data == 2:
key_code = 0x020B2
elif key_code == 0x020C and data == 2:
key_code = 0x020C2
# Get the mouse codes
code, value, scan_code = self.mouse_codes[key_code]
# Add in the press events
scan_event, key_event = self.emulate_press(
code, scan_code, value, self.timeval)
events.append(scan_event)
events.append(key_event)
# Add in the absolute position of the mouse cursor
x_event, y_event = self.emulate_abs(x_val, y_val, self.timeval)
events.append(x_event)
events.append(y_event)
# End with a sync marker
events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(events) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_button(self, event, event_type):
"""Convert the button information from quartz into evdev format.""" |
# 0 for left
# 1 for right
# 2 for middle/center
# 3 for side
mouse_button_number = self._get_mouse_button_number(event)
# Identify buttons 3,4,5
if event_type in (25, 26):
event_type = event_type + (mouse_button_number * 0.1)
# Add buttons to events
event_type_string, event_code, value, scan = self.codes[event_type]
if event_type_string == "Key":
scan_event, key_event = self.emulate_press(
event_code, scan, value, self.timeval)
self.events.append(scan_event)
self.events.append(key_event)
# doubleclick/n-click of button
click_state = self._get_click_state(event)
repeat = self.emulate_repeat(click_state, self.timeval)
self.events.append(repeat) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_relative(self, event):
"""Relative mouse movement.""" |
delta_x, delta_y = self._get_relative(event)
if delta_x:
self.events.append(
self.emulate_rel(0x00,
delta_x,
self.timeval))
if delta_y:
self.events.append(
self.emulate_rel(0x01,
delta_y,
self.timeval)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_input(self, proxy, event_type, event, refcon):
"""Handle an input event.""" |
self.update_timeval()
self.events = []
if event_type in (1, 2, 3, 4, 25, 26, 27):
self.handle_button(event, event_type)
if event_type == 22:
self.handle_scrollwheel(event)
# Add in the absolute position of the mouse cursor
self.handle_absolute(event)
# Add in the relative position of the mouse cursor
self.handle_relative(event)
# End with a sync marker
self.events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(self.events) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_deltas(event):
"""Get the changes from the appkit event.""" |
delta_x = round(event.deltaX())
delta_y = round(event.deltaY())
delta_z = round(event.deltaZ())
return delta_x, delta_y, delta_z |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_button(self, event, event_type):
"""Handle mouse click.""" |
mouse_button_number = self._get_mouse_button_number(event)
# Identify buttons 3,4,5
if event_type in (25, 26):
event_type = event_type + (mouse_button_number * 0.1)
# Add buttons to events
event_type_name, event_code, value, scan = self.codes[event_type]
if event_type_name == "Key":
scan_event, key_event = self.emulate_press(
event_code, scan, value, self.timeval)
self.events.append(scan_event)
self.events.append(key_event) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_scrollwheel(self, event):
"""Make endev from appkit scroll wheel event.""" |
delta_x, delta_y, delta_z = self._get_deltas(event)
if delta_x:
self.events.append(
self.emulate_wheel(delta_x, 'x', self.timeval))
if delta_y:
self.events.append(
self.emulate_wheel(delta_y, 'y', self.timeval))
if delta_z:
self.events.append(
self.emulate_wheel(delta_z, 'z', self.timeval)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_relative(self, event):
"""Get the position of the mouse on the screen.""" |
delta_x, delta_y, delta_z = self._get_deltas(event)
if delta_x:
self.events.append(
self.emulate_rel(0x00,
delta_x,
self.timeval))
if delta_y:
self.events.append(
self.emulate_rel(0x01,
delta_y,
self.timeval))
if delta_z:
self.events.append(
self.emulate_rel(0x02,
delta_z,
self.timeval)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_input(self, event):
"""Process the mouse event.""" |
self.update_timeval()
self.events = []
code = self._get_event_type(event)
# Deal with buttons
self.handle_button(event, code)
# Mouse wheel
if code == 22:
self.handle_scrollwheel(event)
# Other relative mouse movements
else:
self.handle_relative(event)
# Add in the absolute position of the mouse cursor
self.handle_absolute(event)
# End with a sync marker
self.events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(self.events) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_key_value(self, event, event_type):
"""Get the key value.""" |
if event_type == 10:
value = 1
elif event_type == 11:
value = 0
elif event_type == 12:
value = self._get_flag_value(event)
else:
value = -1
return value |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_input(self, event):
"""Process they keyboard input.""" |
self.update_timeval()
self.events = []
code = self._get_event_key_code(event)
if code in self.codes:
new_code = self.codes[code]
else:
new_code = 0
event_type = self._get_event_type(event)
value = self._get_key_value(event, event_type)
scan_event, key_event = self.emulate_press(
new_code, code, value, self.timeval)
self.events.append(scan_event)
self.events.append(key_event)
# End with a sync marker
self.events.append(self.sync_marker(self.timeval))
# We are done
self.write_to_pipe(self.events) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_path_infomation(self):
"""Get useful infomation from the device path.""" |
long_identifier = self._device_path.split('/')[4]
protocol, remainder = long_identifier.split('-', 1)
identifier, _, device_type = remainder.rsplit('-', 2)
return (protocol, identifier, device_type) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_total_read_size(self):
"""How much event data to process at once.""" |
if self.read_size:
read_size = EVENT_SIZE * self.read_size
else:
read_size = EVENT_SIZE
return read_size |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _make_event(self, tv_sec, tv_usec, ev_type, code, value):
"""Create a friendly Python object from an evdev style event.""" |
event_type = self.manager.get_event_type(ev_type)
eventinfo = {
"ev_type": event_type,
"state": value,
"timestamp": tv_sec + (tv_usec / 1000000),
"code": self.manager.get_event_string(event_type, code)
}
return InputEvent(self, eventinfo) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _pipe(self):
"""On Windows we use a pipe to emulate a Linux style character buffer.""" |
if self._evdev:
return None
if not self.__pipe:
target_function = self._get_target_function()
if not target_function:
return None
self.__pipe, child_conn = Pipe(duplex=False)
self._listener = Process(target=target_function,
args=(child_conn,), daemon=True)
self._listener.start()
return self.__pipe |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _number_xpad(self):
"""Get the number of the joystick.""" |
js_path = self._device_path.replace('-event', '')
js_chardev = os.path.realpath(js_path)
try:
number_text = js_chardev.split('js')[1]
except IndexError:
return
try:
number = int(number_text)
except ValueError:
return
self.__device_number = number |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __check_state(self):
"""On Windows, check the state and fill the event character device.""" |
state = self.__read_device()
if not state:
raise UnpluggedError(
"Gamepad %d is not connected" % self.__device_number)
if state.packet_number != self.__last_state.packet_number:
# state has changed, handle the change
self.__handle_changed_state(state)
self.__last_state = state |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_event_object(self, event_type, code, value, timeval=None):
"""Create an evdev style object.""" |
if not timeval:
timeval = self.__get_timeval()
try:
event_code = self.manager.codes['type_codes'][event_type]
except KeyError:
raise UnknownEventType(
"We don't know what kind of event a %s is." % event_type)
event = struct.pack(EVENT_FORMAT,
timeval[0],
timeval[1],
event_code,
code,
value)
return event |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __write_to_character_device(self, event_list, timeval=None):
"""Emulate the Linux character device on other platforms such as Windows.""" |
# Remember the position of the stream
pos = self._character_device.tell()
# Go to the end of the stream
self._character_device.seek(0, 2)
# Write the new data to the end
for event in event_list:
self._character_device.write(event)
# Add a sync marker
sync = self.create_event_object("Sync", 0, 0, timeval)
self._character_device.write(sync)
# Put the stream back to its original position
self._character_device.seek(pos) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __get_button_events(self, state, timeval=None):
"""Get the button events from xinput.""" |
changed_buttons = self.__detect_button_events(state)
events = self.__emulate_buttons(changed_buttons, timeval)
return events |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __get_axis_events(self, state, timeval=None):
"""Get the stick events from xinput.""" |
axis_changes = self.__detect_axis_events(state)
events = self.__emulate_axis(axis_changes, timeval)
return events |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __emulate_axis(self, axis_changes, timeval=None):
"""Make the axis events use the Linux style format.""" |
events = []
for axis in axis_changes:
code, value = self.__map_axis(axis)
event = self.create_event_object(
"Absolute",
code,
value,
timeval=timeval)
events.append(event)
return events |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __emulate_buttons(self, changed_buttons, timeval=None):
"""Make the button events use the Linux style format.""" |
events = []
for button in changed_buttons:
code, value, ev_type = self.__map_button(button)
event = self.create_event_object(
ev_type,
code,
value,
timeval=timeval)
events.append(event)
return events |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __get_bit_values(self, number, size=32):
"""Get bit values as a list for a given number True [1L, 1L, 0L, 1L, 1L, 1L, 1L, 0L, 1L, 0L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 0L, 1L, 1L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 0L, 1L, 1L, 1L, 1L] You may override the default word size of 32-bits to match your actual application. [1L, 1L] [0L, 0L, 1L, 1L] """ |
res = list(self.__gen_bit_values(number))
res.reverse()
# 0-pad the most significant bit
res = [0] * (size - len(res)) + res
return res |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __read_device(self):
"""Read the state of the gamepad.""" |
state = XinputState()
res = self.manager.xinput.XInputGetState(
self.__device_number, ctypes.byref(state))
if res == XINPUT_ERROR_SUCCESS:
return state
if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:
raise RuntimeError(
"Unknown error %d attempting to get state of device %d" % (
res, self.__device_number))
# else (device is not connected)
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _start_vibration_win(self, left_motor, right_motor):
"""Start the vibration, which will run until stopped.""" |
xinput_set_state = self.manager.xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
vibration = XinputVibration(
int(left_motor * 65535), int(right_motor * 65535))
xinput_set_state(self.__device_number, ctypes.byref(vibration)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _stop_vibration_win(self):
"""Stop the vibration.""" |
xinput_set_state = self.manager.xinput.XInputSetState
xinput_set_state.argtypes = [
ctypes.c_uint, ctypes.POINTER(XinputVibration)]
xinput_set_state.restype = ctypes.c_uint
stop_vibration = ctypes.byref(XinputVibration(0, 0))
xinput_set_state(self.__device_number, stop_vibration) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_vibration_win(self, left_motor, right_motor, duration):
"""Control the motors on Windows.""" |
self._start_vibration_win(left_motor, right_motor)
stop_process = Process(target=delay_and_stop,
args=(duration,
self.manager.xinput_dll,
self.__device_number))
stop_process.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __get_vibration_code(self, left_motor, right_motor, duration):
"""This is some crazy voodoo, if you can simplify it, please do.""" |
inner_event = struct.pack(
'2h6x2h2x2H28x',
0x50,
-1,
duration,
0,
int(left_motor * 65535),
int(right_motor * 65535))
buf_conts = ioctl(self._write_device, 1076905344, inner_event)
return int(codecs.encode(buf_conts[1:3], 'hex'), 16) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_vibration_nix(self, left_motor, right_motor, duration):
"""Control the motors on Linux. Duration is in miliseconds.""" |
code = self.__get_vibration_code(left_motor, right_motor, duration)
secs, msecs = convert_timeval(time.time())
outer_event = struct.pack(EVENT_FORMAT, secs, msecs, 0x15, code, 1)
self._write_device.write(outer_event)
self._write_device.flush() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def max_brightness(self):
"""Get the device's maximum brightness level.""" |
status_filename = os.path.join(self.path, 'max_brightness')
with open(status_filename) as status_fp:
result = status_fp.read()
status_text = result.strip()
try:
status = int(status_text)
except ValueError:
return status_text
return status |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _write_device(self):
"""The output device.""" |
if not self._write_file:
if not NIX:
return None
try:
self._write_file = io.open(
self._character_device_path, 'wb')
except PermissionError:
# Python 3
raise PermissionError(PERMISSIONS_ERROR_TEXT)
except IOError as err:
# Python 2 only
if err.errno == 13: # pragma: no cover
raise PermissionError(PERMISSIONS_ERROR_TEXT)
else:
raise
return self._write_file |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _post_init(self):
"""Set up the device path and type code.""" |
self._led_type_code = self.manager.get_typecode('LED')
self.device_path = os.path.realpath(os.path.join(self.path, 'device'))
if '::' in self.name:
chardev, code_name = self.name.split('::')
if code_name in self.manager.codes['LED_type_codes']:
self.code = self.manager.codes['LED_type_codes'][code_name]
try:
event_number = chardev.split('input')[1]
except IndexError:
print("Failed with", self.name)
raise
else:
self._character_device_path = '/dev/input/event' + event_number
self._match_device() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match_device(self):
"""If the LED is connected to an input device, associate the objects.""" |
for device in self.manager.all_devices:
if (device.get_char_device_path() ==
self._character_device_path):
self.device = device
device.leds.append(self)
break |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _post_init(self):
"""Call the find devices method for the relevant platform.""" |
if WIN:
self._find_devices_win()
elif MAC:
self._find_devices_mac()
else:
self._find_devices()
self._update_all_devices()
if NIX:
self._find_leds() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _update_all_devices(self):
"""Update the all_devices list.""" |
self.all_devices = []
self.all_devices.extend(self.keyboards)
self.all_devices.extend(self.mice)
self.all_devices.extend(self.gamepads)
self.all_devices.extend(self.other_devices) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _parse_device_path(self, device_path, char_path_override=None):
"""Parse each device and add to the approriate list.""" |
# 1. Make sure that we can parse the device path.
try:
device_type = device_path.rsplit('-', 1)[1]
except IndexError:
warn("The following device path was skipped as it could "
"not be parsed: %s" % device_path, RuntimeWarning)
return
# 2. Make sure each device is only added once.
realpath = os.path.realpath(device_path)
if realpath in self._raw:
return
self._raw.append(realpath)
# 3. All seems good, append the device to the relevant list.
if device_type == 'kbd':
self.keyboards.append(Keyboard(self, device_path,
char_path_override))
elif device_type == 'mouse':
self.mice.append(Mouse(self, device_path,
char_path_override))
elif device_type == 'joystick':
self.gamepads.append(GamePad(self,
device_path,
char_path_override))
else:
self.other_devices.append(OtherDevice(self,
device_path,
char_path_override)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_xinput(self):
"""Find most recent xinput library.""" |
for dll in XINPUT_DLL_NAMES:
try:
self.xinput = getattr(ctypes.windll, dll)
except OSError:
pass
else:
# We found an xinput driver
self.xinput_dll = dll
break
else:
# We didn't find an xinput library
warn(
"No xinput driver dll found, gamepads not supported.",
RuntimeWarning) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_devices_win(self):
"""Find devices on Windows.""" |
self._find_xinput()
self._detect_gamepads()
self._count_devices()
if self._raw_device_counts['keyboards'] > 0:
self.keyboards.append(Keyboard(
self,
"/dev/input/by-id/usb-A_Nice_Keyboard-event-kbd"))
if self._raw_device_counts['mice'] > 0:
self.mice.append(Mouse(
self,
"/dev/input/by-id/usb-A_Nice_Mouse_called_Arthur-event-mouse")) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_devices_mac(self):
"""Find devices on Mac.""" |
self.keyboards.append(Keyboard(self))
self.mice.append(MightyMouse(self))
self.mice.append(Mouse(self)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _detect_gamepads(self):
"""Find gamepads.""" |
state = XinputState()
# Windows allows up to 4 gamepads.
for device_number in range(4):
res = self.xinput.XInputGetState(
device_number, ctypes.byref(state))
if res == XINPUT_ERROR_SUCCESS:
# We found a gamepad
device_path = (
"/dev/input/by_id/" +
"usb-Microsoft_Corporation_Controller_%s-event-joystick"
% device_number)
self.gamepads.append(GamePad(self, device_path))
continue
if res != XINPUT_ERROR_DEVICE_NOT_CONNECTED:
raise RuntimeError(
"Unknown error %d attempting to get state of device %d"
% (res, device_number)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _count_devices(self):
"""See what Windows' GetRawInputDeviceList wants to tell us. For now, we are just seeing if there is at least one keyboard and/or mouse attached. GetRawInputDeviceList could be used to help distinguish between different keyboards and mice on the system in the way Linux can. However, Roma uno die non est condita. """ |
number_of_devices = ctypes.c_uint()
if ctypes.windll.user32.GetRawInputDeviceList(
ctypes.POINTER(ctypes.c_int)(),
ctypes.byref(number_of_devices),
ctypes.sizeof(RawInputDeviceList)) == -1:
warn("Call to GetRawInputDeviceList was unsuccessful."
"We have no idea if a mouse or keyboard is attached.",
RuntimeWarning)
return
devices_found = (RawInputDeviceList * number_of_devices.value)()
if ctypes.windll.user32.GetRawInputDeviceList(
devices_found,
ctypes.byref(number_of_devices),
ctypes.sizeof(RawInputDeviceList)) == -1:
warn("Call to GetRawInputDeviceList was unsuccessful."
"We have no idea if a mouse or keyboard is attached.",
RuntimeWarning)
return
for device in devices_found:
if device.dwType == 0:
self._raw_device_counts['mice'] += 1
elif device.dwType == 1:
self._raw_device_counts['keyboards'] += 1
elif device.dwType == 2:
self._raw_device_counts['otherhid'] += 1
else:
self._raw_device_counts['unknown'] += 1 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_by(self, key):
"""Find devices.""" |
by_path = glob.glob('/dev/input/by-{key}/*-event-*'.format(key=key))
for device_path in by_path:
self._parse_device_path(device_path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_special(self):
"""Look for special devices.""" |
charnames = self._get_char_names()
for eventdir in glob.glob('/sys/class/input/event*'):
char_name = os.path.split(eventdir)[1]
if char_name in charnames:
continue
name_file = os.path.join(eventdir, 'device', 'name')
with open(name_file) as name_file:
device_name = name_file.read().strip()
if device_name in self.codes['specials']:
self._parse_device_path(
self.codes['specials'][device_name],
os.path.join('/dev/input', char_name)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_event_string(self, evtype, code):
"""Get the string name of the event.""" |
if WIN and evtype == 'Key':
# If we can map the code to a common one then do it
try:
code = self.codes['wincodes'][code]
except KeyError:
pass
try:
return self.codes[evtype][code]
except KeyError:
raise UnknownEventCode("We don't know this event.", evtype, code) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def detect_microbit(self):
"""Detect a microbit.""" |
try:
gpad = MicroBitPad(self)
except ModuleNotFoundError:
warn(
"The microbit library could not be found in the pythonpath. \n"
"For more information, please visit \n"
"https://inputs.readthedocs.io/en/latest/user/microbit.html",
RuntimeWarning)
else:
self.microbits.append(gpad)
self.gamepads.append(gpad) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_display(self, index=None):
"""Show an image on the display.""" |
# pylint: disable=no-member
if index:
image = self.microbit.Image.STD_IMAGES[index]
else:
image = self.default_image
self.microbit.display.show(image) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _setup_rumble(self):
"""Setup the three animations which simulate a rumble.""" |
self.left_rumble = self._get_ready_to('99500')
self.right_rumble = self._get_ready_to('00599')
self.double_rumble = self._get_ready_to('99599') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_ready_to(self, rumble):
"""Watch us wreck the mike! PSYCHE!""" |
# pylint: disable=no-member
return [self.microbit.Image(':'.join(
[rumble if char == '1' else '00500'
for char in code])) for code in SPIN_UP_MOTOR] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _full_speed_rumble(self, images, duration):
"""Simulate the motors running at full.""" |
while duration > 0:
self.microbit.display.show(images[0]) # pylint: disable=no-member
time.sleep(0.04)
self.microbit.display.show(images[1]) # pylint: disable=no-member
time.sleep(0.04)
duration -= 0.08 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _spin_up(self, images, duration):
"""Simulate the motors getting warmed up.""" |
total = 0
# pylint: disable=no-member
for image in images:
self.microbit.display.show(image)
time.sleep(0.05)
total += 0.05
if total >= duration:
return
remaining = duration - total
self._full_speed_rumble(images[-2:], remaining)
self.set_display() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_new_events(self, events):
"""Add each new events to the event queue.""" |
for event in events:
self.events.append(
self.create_event_object(
event[0],
event[1],
int(event[2]))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_abs(self):
"""Gets the state as the raw abolute numbers.""" |
# pylint: disable=no-member
x_raw = self.microbit.accelerometer.get_x()
y_raw = self.microbit.accelerometer.get_y()
x_abs = ('Absolute', 0x00, x_raw)
y_abs = ('Absolute', 0x01, y_raw)
return x_abs, y_abs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_dpad(self):
"""Gets the state of the virtual dpad.""" |
# pylint: disable=no-member
x_raw = self.microbit.accelerometer.get_x()
y_raw = self.microbit.accelerometer.get_y()
minus_sens = self.sensitivity * -1
if x_raw < minus_sens:
x_state = ('Absolute', 0x10, -1)
elif x_raw > self.sensitivity:
x_state = ('Absolute', 0x10, 1)
else:
x_state = ('Absolute', 0x10, 0)
if y_raw < minus_sens:
y_state = ('Absolute', 0x11, -1)
elif y_raw > self.sensitivity:
y_state = ('Absolute', 0x11, 1)
else:
y_state = ('Absolute', 0x11, 1)
return x_state, y_state |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_state(self):
"""Tracks differences in the device state.""" |
if self.dpad:
x_state, y_state = self.handle_dpad()
else:
x_state, y_state = self.handle_abs()
# pylint: disable=no-member
new_state = set((
x_state,
y_state,
('Key', 0x130, int(self.microbit.button_a.is_pressed())),
('Key', 0x131, int(self.microbit.button_b.is_pressed())),
('Key', 0x13a, int(self.microbit.pin0.is_touched())),
('Key', 0x133, int(self.microbit.pin1.is_touched())),
('Key', 0x134, int(self.microbit.pin2.is_touched())),
))
events = new_state - self.state
self.state = new_state
return events |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_input(self):
"""Sends differences in the device state to the MicroBitPad as events.""" |
difference = self.check_state()
if not difference:
return
self.events = []
self.handle_new_events(difference)
self.update_timeval()
self.events.append(self.sync_marker(self.timeval))
self.write_to_pipe(self.events) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Just print out some event infomation when the mouse is used.""" |
while 1:
events = get_mouse()
for event in events:
print(event.ev_type, event.code, event.state) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Just print out some event infomation when keys are pressed.""" |
while 1:
events = get_key()
if events:
for event in events:
print(event.ev_type, event.code, event.state) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main():
"""Just print out some event infomation when the gamepad is used.""" |
while 1:
events = get_gamepad()
for event in events:
print(event.ev_type, event.code, event.state) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main(gamepad=None):
"""Vibrate the gamepad.""" |
if not gamepad:
gamepad = inputs.devices.gamepads[0]
# Vibrate left
gamepad.set_vibration(1, 0, 1000)
time.sleep(2)
# Vibrate right
gamepad.set_vibration(0, 1, 1000)
time.sleep(2)
# Vibrate Both
gamepad.set_vibration(1, 1, 2000)
time.sleep(2) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate(self, value):
""" Check if ``value`` is valid. :returns: [errors] If ``value`` is invalid, otherwise []. """ |
errors = []
# Make sure the type validates first.
valid = self._is_valid(value)
if not valid:
errors.append(self.fail(value))
return errors
# Then validate all the constraints second.
for constraint in self._constraints_inst:
error = constraint.is_valid(value)
if error:
errors.append(error)
return errors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _process_schema(self, schema_dict, validators):
""" Go through a schema and construct validators. """ |
schema_flat = util.flatten(schema_dict)
for key, expression in schema_flat.items():
try:
schema_flat[key] = syntax.parse(expression, validators)
except SyntaxError as e:
# Tack on some more context and rethrow.
error = str(e) + ' at node \'%s\'' % key
raise SyntaxError(error)
return schema_flat |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate(self, validator, data, key, position=None, includes=None):
""" Run through a schema and a data structure, validating along the way. Ignores fields that are in the data structure, but not in the schema. Returns an array of errors. """ |
errors = []
if position:
position = '%s.%s' % (position, key)
else:
position = key
try: # Pull value out of data. Data can be a map or a list/sequence
data_item = util.get_value(data, key)
except KeyError: # Oops, that field didn't exist.
if validator.is_optional: # Optional? Who cares.
return errors
# SHUT DOWN EVERTYHING
errors.append('%s: Required field missing' % position)
return errors
return self._validate_item(validator, data_item, position, includes) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_item(self, validator, data_item, position, includes):
""" Validates a single data item against validator. Returns an array of errors. """ |
errors = []
# Optional field with optional value? Who cares.
if data_item is None and validator.is_optional and validator.can_be_none:
return errors
errors += self._validate_primitive(validator, data_item, position)
if errors:
return errors
if isinstance(validator, val.Include):
errors += self._validate_include(validator, data_item,
includes, position)
elif isinstance(validator, (val.Map, val.List)):
errors += self._validate_map_list(validator, data_item,
includes, position)
elif isinstance(validator, val.Any):
errors += self._validate_any(validator, data_item,
includes, position)
return errors |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_data_path_schema(data_path, schema_name):
""" Starts in the data file folder and recursively looks in parents for `schema_name` """ |
if not data_path or data_path == '/' or data_path == '.':
return None
directory = os.path.dirname(data_path)
path = glob.glob(os.path.join(directory, schema_name))
if not path:
return _find_schema(directory, schema_name)
return path[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_schema(data_path, schema_name):
""" Checks if `schema_name` is a valid file, if not searches in `data_path` for it. """ |
path = glob.glob(schema_name)
for p in path:
if os.path.isfile(p):
return p
return _find_data_path_schema(data_path, schema_name) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def flatten(dic, keep_iter=False, position=None):
""" Returns a flattened dictionary from a dictionary of nested dictionaries and lists. `keep_iter` will treat iterables as valid values, while also flattening them. """ |
child = {}
if not dic:
return {}
for k, v in get_iter(dic):
if isstr(k):
k = k.replace('.', '_')
if position:
item_position = '%s.%s' % (position, k)
else:
item_position = '%s' % k
if is_iter(v):
child.update(flatten(dic[k], keep_iter, item_position))
if keep_iter:
child[item_position] = v
else:
child[item_position] = v
return child |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_representation(self, obj):
""" convert value to representation. DRF ModelField uses ``value_to_string`` for this purpose. Mongoengine fields do not have such method. This implementation uses ``django.utils.encoding.smart_text`` to convert everything to text, while keeping json-safe types intact. NB: The argument is whole object, instead of attribute value. This is upstream feature. Probably because the field can be represented by a complicated method with nontrivial way to extract data. """ |
value = self.model_field.__get__(obj, None)
return smart_text(value, strings_only=True) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def run_validators(self, value):
""" validate value. Uses document field's ``validate()`` """ |
try:
self.model_field.validate(value)
except MongoValidationError as e:
raise ValidationError(e.message)
super(DocumentField, self).run_validators(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_object_or_404(queryset, *args, **kwargs):
""" replacement of rest_framework.generics and django.shrtcuts analogues """ |
try:
return queryset.get(*args, **kwargs)
except (ValueError, TypeError, DoesNotExist, ValidationError):
raise Http404() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def recursive_save(self, validated_data, instance=None):
""" Recursively traverses validated_data and creates EmbeddedDocuments of the appropriate subtype from them. Returns Mongonengine model instance. """ |
# me_data is an analogue of validated_data, but contains
# mongoengine EmbeddedDocument instances for nested data structures
# instead of OrderedDicts.
#
# For example:
# validated_data = {'id:, "1", 'embed': OrderedDict({'a': 'b'})}
# me_data = {'id': "1", 'embed': <EmbeddedDocument>}
me_data = dict()
for key, value in validated_data.items():
try:
field = self.fields[key]
# for EmbeddedDocumentSerializers, call recursive_save
if isinstance(field, EmbeddedDocumentSerializer):
me_data[key] = field.recursive_save(value)
# same for lists of EmbeddedDocumentSerializers i.e.
# ListField(EmbeddedDocumentField) or EmbeddedDocumentListField
elif ((isinstance(field, serializers.ListSerializer) or
isinstance(field, serializers.ListField)) and
isinstance(field.child, EmbeddedDocumentSerializer)):
me_data[key] = []
for datum in value:
me_data[key].append(field.child.recursive_save(datum))
# same for dicts of EmbeddedDocumentSerializers (or, speaking
# in Mongoengine terms, MapField(EmbeddedDocument(Embed))
elif (isinstance(field, drfm_fields.DictField) and
hasattr(field, "child") and
isinstance(field.child, EmbeddedDocumentSerializer)):
me_data[key] = {}
for datum_key, datum_value in value.items():
me_data[key][datum_key] = field.child.recursive_save(datum_value)
# for regular fields just set value
else:
me_data[key] = value
except KeyError: # this is dynamic data
me_data[key] = value
# create (if needed), save (if needed) and return mongoengine instance
if not instance:
instance = self.Meta.model(**me_data)
else:
for key, value in me_data.items():
setattr(instance, key, value)
if self._saving_instances:
instance.save()
return instance |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def apply_customization(self, serializer, customization):
""" Applies fields customization to a nested or embedded DocumentSerializer. """ |
# apply fields or exclude
if customization.fields is not None:
if len(customization.fields) == 0:
# customization fields are empty, set Meta.fields to '__all__'
serializer.Meta.fields = ALL_FIELDS
else:
serializer.Meta.fields = customization.fields
if customization.exclude is not None:
serializer.Meta.exclude = customization.exclude
# apply extra_kwargs
if customization.extra_kwargs is not None:
serializer.Meta.extra_kwargs = customization.extra_kwargs
# apply validate_methods
for method_name, method in customization.validate_methods.items():
setattr(serializer, method_name, method) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_internal_value(self, data):
""" Updates _validated_data with dynamic data, i.e. data, not listed in fields. """ |
ret = super(DynamicDocumentSerializer, self).to_internal_value(data)
dynamic_data = self._get_dynamic_data(ret)
ret.update(dynamic_data)
return ret |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_field_kwargs(field_name, model_field):
""" Creating a default instance of a basic non-relational field. """ |
kwargs = {}
# The following will only be used by ModelField classes.
# Gets removed for everything else.
kwargs['model_field'] = model_field
if hasattr(model_field, 'verbose_name') and needs_label(model_field, field_name):
kwargs['label'] = capfirst(model_field.verbose_name)
if hasattr(model_field, 'help_text'):
kwargs['help_text'] = model_field.help_text
if isinstance(model_field, me_fields.DecimalField):
precision = model_field.precision
max_value = getattr(model_field, 'max_value', None)
if max_value is not None:
max_length = len(str(max_value)) + precision
else:
max_length = 65536
kwargs['decimal_places'] = precision
kwargs['max_digits'] = max_length
if isinstance(model_field, me_fields.GeoJsonBaseField):
kwargs['geo_type'] = model_field._type
if isinstance(model_field, me_fields.SequenceField) or model_field.primary_key or model_field.db_field == '_id':
# If this field is read-only, then return early.
# Further keyword arguments are not valid.
kwargs['read_only'] = True
return kwargs
if model_field.default and not isinstance(model_field, me_fields.ComplexBaseField):
kwargs['default'] = model_field.default
if model_field.null:
kwargs['allow_null'] = True
if model_field.null and isinstance(model_field, me_fields.StringField):
kwargs['allow_blank'] = True
if 'default' not in kwargs:
kwargs['required'] = model_field.required
# handle special cases - compound fields: mongoengine.ListField/DictField
if kwargs['required'] is True:
if isinstance(model_field, me_fields.ListField) or isinstance(model_field, me_fields.DictField):
kwargs['allow_empty'] = False
if model_field.choices:
# If this model field contains choices, then return early.
# Further keyword arguments are not valid.
kwargs['choices'] = model_field.choices
return kwargs
if isinstance(model_field, me_fields.StringField):
if model_field.regex:
kwargs['regex'] = model_field.regex
max_length = getattr(model_field, 'max_length', None)
if max_length is not None and isinstance(model_field, me_fields.StringField):
kwargs['max_length'] = max_length
min_length = getattr(model_field, 'min_length', None)
if min_length is not None and isinstance(model_field, me_fields.StringField):
kwargs['min_length'] = min_length
max_value = getattr(model_field, 'max_value', None)
if max_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
kwargs['max_value'] = max_value
min_value = getattr(model_field, 'min_value', None)
if min_value is not None and isinstance(model_field, NUMERIC_FIELD_TYPES):
kwargs['min_value'] = min_value
return kwargs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_relation_kwargs(field_name, relation_info):
""" Creating a default instance of a flat relational field. """ |
model_field, related_model = relation_info
kwargs = {}
if related_model and not issubclass(related_model, EmbeddedDocument):
kwargs['queryset'] = related_model.objects
if model_field:
if hasattr(model_field, 'verbose_name') and needs_label(model_field, field_name):
kwargs['label'] = capfirst(model_field.verbose_name)
if hasattr(model_field, 'help_text'):
kwargs['help_text'] = model_field.help_text
kwargs['required'] = model_field.required
if model_field.null:
kwargs['allow_null'] = True
if getattr(model_field, 'unique', False):
validator = UniqueValidator(queryset=related_model.objects)
kwargs['validators'] = [validator]
return kwargs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_nested_relation_kwargs(field_name, relation_info):
""" Creating a default instance of a nested serializer """ |
kwargs = get_relation_kwargs(field_name, relation_info)
kwargs.pop('queryset')
kwargs.pop('required')
kwargs['read_only'] = True
return kwargs |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def degrees_dir(CIJ):
'''
Node degree is the number of links connected to the node. The indegree
is the number of inward links and the outdegree is the number of
outward links.
Parameters
----------
CIJ : NxN np.ndarray
directed binary/weighted connection matrix
Returns
-------
id : Nx1 np.ndarray
node in-degree
od : Nx1 np.ndarray
node out-degree
deg : Nx1 np.ndarray
node degree (in-degree + out-degree)
Notes
-----
Inputs are assumed to be on the columns of the CIJ matrix.
Weight information is discarded.
'''
CIJ = binarize(CIJ, copy=True) # ensure CIJ is binary
id = np.sum(CIJ, axis=0) # indegree = column sum of CIJ
od = np.sum(CIJ, axis=1) # outdegree = row sum of CIJ
deg = id + od # degree = indegree+outdegree
return id, od, deg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def degrees_und(CIJ):
'''
Node degree is the number of links connected to the node.
Parameters
----------
CIJ : NxN np.ndarray
undirected binary/weighted connection matrix
Returns
-------
deg : Nx1 np.ndarray
node degree
Notes
-----
Weight information is discarded.
'''
CIJ = binarize(CIJ, copy=True) # ensure CIJ is binary
return np.sum(CIJ, axis=0) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def strengths_dir(CIJ):
'''
Node strength is the sum of weights of links connected to the node. The
instrength is the sum of inward link weights and the outstrength is the
sum of outward link weights.
Parameters
----------
CIJ : NxN np.ndarray
directed weighted connection matrix
Returns
-------
is : Nx1 np.ndarray
node in-strength
os : Nx1 np.ndarray
node out-strength
str : Nx1 np.ndarray
node strength (in-strength + out-strength)
Notes
-----
Inputs are assumed to be on the columns of the CIJ matrix.
'''
istr = np.sum(CIJ, axis=0)
ostr = np.sum(CIJ, axis=1)
return istr + ostr |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def strengths_und_sign(W):
'''
Node strength is the sum of weights of links connected to the node.
Parameters
----------
W : NxN np.ndarray
undirected connection matrix with positive and negative weights
Returns
-------
Spos : Nx1 np.ndarray
nodal strength of positive weights
Sneg : Nx1 np.ndarray
nodal strength of positive weights
vpos : float
total positive weight
vneg : float
total negative weight
'''
W = W.copy()
n = len(W)
np.fill_diagonal(W, 0) # clear diagonal
Spos = np.sum(W * (W > 0), axis=0) # positive strengths
Sneg = np.sum(W * (W < 0), axis=0) # negative strengths
vpos = np.sum(W[W > 0]) # positive weight
vneg = np.sum(W[W < 0]) # negative weight
return Spos, Sneg, vpos, vneg |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def edge_nei_overlap_bu(CIJ):
'''
This function determines the neighbors of two nodes that are linked by
an edge, and then computes their overlap. Connection matrix must be
binary and directed. Entries of 'EC' that are 'inf' indicate that no
edge is present. Entries of 'EC' that are 0 denote "local bridges", i.e.
edges that link completely non-overlapping neighborhoods. Low values
of EC indicate edges that are "weak ties".
If CIJ is weighted, the weights are ignored.
Parameters
----------
CIJ : NxN np.ndarray
undirected binary/weighted connection matrix
Returns
-------
EC : NxN np.ndarray
edge neighborhood overlap matrix
ec : Kx1 np.ndarray
edge neighborhood overlap per edge vector
degij : NxN np.ndarray
degrees of node pairs connected by each edge
'''
ik, jk = np.where(CIJ)
lel = len(CIJ[ik, jk])
n = len(CIJ)
deg = degrees_und(CIJ)
ec = np.zeros((lel,))
degij = np.zeros((2, lel))
for e in range(lel):
neiik = np.setdiff1d(np.union1d(
np.where(CIJ[ik[e], :]), np.where(CIJ[:, ik[e]])), (ik[e], jk[e]))
neijk = np.setdiff1d(np.union1d(
np.where(CIJ[jk[e], :]), np.where(CIJ[:, jk[e]])), (ik[e], jk[e]))
ec[e] = len(np.intersect1d(neiik, neijk)) / \
len(np.union1d(neiik, neijk))
degij[:, e] = (deg[ik[e]], deg[jk[e]])
EC = np.tile(np.inf, (n, n))
EC[ik, jk] = ec
return EC, ec, degij |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def matching_ind(CIJ):
'''
For any two nodes u and v, the matching index computes the amount of
overlap in the connection patterns of u and v. Self-connections and
u-v connections are ignored. The matching index is a symmetric
quantity, similar to a correlation or a dot product.
Parameters
----------
CIJ : NxN np.ndarray
adjacency matrix
Returns
-------
Min : NxN np.ndarray
matching index for incoming connections
Mout : NxN np.ndarray
matching index for outgoing connections
Mall : NxN np.ndarray
matching index for all connections
Notes
-----
Does not use self- or cross connections for comparison.
Does not use connections that are not present in BOTH u and v.
All output matrices are calculated for upper triangular only.
'''
n = len(CIJ)
Min = np.zeros((n, n))
Mout = np.zeros((n, n))
Mall = np.zeros((n, n))
# compare incoming connections
for i in range(n - 1):
for j in range(i + 1, n):
c1i = CIJ[:, i]
c2i = CIJ[:, j]
usei = np.logical_or(c1i, c2i)
usei[i] = 0
usei[j] = 0
nconi = np.sum(c1i[usei]) + np.sum(c2i[usei])
if not nconi:
Min[i, j] = 0
else:
Min[i, j] = 2 * \
np.sum(np.logical_and(c1i[usei], c2i[usei])) / nconi
c1o = CIJ[i, :]
c2o = CIJ[j, :]
useo = np.logical_or(c1o, c2o)
useo[i] = 0
useo[j] = 0
ncono = np.sum(c1o[useo]) + np.sum(c2o[useo])
if not ncono:
Mout[i, j] = 0
else:
Mout[i, j] = 2 * \
np.sum(np.logical_and(c1o[useo], c2o[useo])) / ncono
c1a = np.ravel((c1i, c1o))
c2a = np.ravel((c2i, c2o))
usea = np.logical_or(c1a, c2a)
usea[i] = 0
usea[i + n] = 0
usea[j] = 0
usea[j + n] = 0
ncona = np.sum(c1a[usea]) + np.sum(c2a[usea])
if not ncona:
Mall[i, j] = 0
else:
Mall[i, j] = 2 * \
np.sum(np.logical_and(c1a[usea], c2a[usea])) / ncona
Min = Min + Min.T
Mout = Mout + Mout.T
Mall = Mall + Mall.T
return Min, Mout, Mall |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dice_pairwise_und(a1, a2):
'''
Calculates pairwise dice similarity for each vertex between two
matrices. Treats the matrices as binary and undirected.
Paramaters
----------
A1 : NxN np.ndarray
Matrix 1
A2 : NxN np.ndarray
Matrix 2
Returns
-------
D : Nx1 np.ndarray
dice similarity vector
'''
a1 = binarize(a1, copy=True)
a2 = binarize(a2, copy=True) # ensure matrices are binary
n = len(a1)
np.fill_diagonal(a1, 0)
np.fill_diagonal(a2, 0) # set diagonals to 0
d = np.zeros((n,)) # dice similarity
# calculate the common neighbors for each vertex
for i in range(n):
d[i] = 2 * (np.sum(np.logical_and(a1[:, i], a2[:, i])) /
(np.sum(a1[:, i]) + np.sum(a2[:, i])))
return d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def corr_flat_und(a1, a2):
'''
Returns the correlation coefficient between two flattened adjacency
matrices. Only the upper triangular part is used to avoid double counting
undirected matrices. Similarity metric for weighted matrices.
Parameters
----------
A1 : NxN np.ndarray
undirected matrix 1
A2 : NxN np.ndarray
undirected matrix 2
Returns
-------
r : float
Correlation coefficient describing edgewise similarity of a1 and a2
'''
n = len(a1)
if len(a2) != n:
raise BCTParamError("Cannot calculate flattened correlation on "
"matrices of different size")
triu_ix = np.where(np.triu(np.ones((n, n)), 1))
return np.corrcoef(a1[triu_ix].flat, a2[triu_ix].flat)[0][1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def corr_flat_dir(a1, a2):
'''
Returns the correlation coefficient between two flattened adjacency
matrices. Similarity metric for weighted matrices.
Parameters
----------
A1 : NxN np.ndarray
directed matrix 1
A2 : NxN np.ndarray
directed matrix 2
Returns
-------
r : float
Correlation coefficient describing edgewise similarity of a1 and a2
'''
n = len(a1)
if len(a2) != n:
raise BCTParamError("Cannot calculate flattened correlation on "
"matrices of different size")
ix = np.logical_not(np.eye(n))
return np.corrcoef(a1[ix].flat, a2[ix].flat)[0][1] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def adjacency_plot_und(A, coor, tube=False):
'''
This function in matlab is a visualization helper which translates an
adjacency matrix and an Nx3 matrix of spatial coordinates, and plots a
3D isometric network connecting the undirected unweighted nodes using a
specific plotting format. Including the formatted output is not useful at
all for bctpy since matplotlib will not be able to plot it in quite the
same way.
Instead of doing this, I have included code that will plot the adjacency
matrix onto nodes at the given spatial coordinates in mayavi
This routine is basically a less featureful version of the 3D brain in
cvu, the connectome visualization utility which I also maintain. cvu uses
freesurfer surfaces and annotations to get the node coordinates (rather
than leaving them up to the user) and has many other interactive
visualization features not included here for the sake of brevity.
There are other similar visualizations in the ConnectomeViewer and the
UCLA multimodal connectivity database.
Note that unlike other bctpy functions, this function depends on mayavi.
Paramaters
----------
A : NxN np.ndarray
adjacency matrix
coor : Nx3 np.ndarray
vector of node coordinates
tube : bool
plots using cylindrical tubes for higher resolution image. If True,
plots cylindrical tube sources. If False, plots line sources. Default
value is False.
Returns
-------
fig : Instance(Scene)
handle to a mayavi figure.
Notes
-----
To display the output interactively, call
fig=adjacency_plot_und(A,coor)
from mayavi import mlab
mlab.show()
Note: Thresholding the matrix is strongly recommended. It is recommended
that the input matrix have fewer than 5000 total connections in order to
achieve reasonable performance and noncluttered visualization.
'''
from mayavi import mlab
n = len(A)
nr_edges = (n * n - 1) // 2
#starts = np.zeros((nr_edges,3))
#vecs = np.zeros((nr_edges,3))
#adjdat = np.zeros((nr_edges,))
ixes, = np.where(np.triu(np.ones((n, n)), 1).flat)
# i=0
# for r2 in xrange(n):
# for r1 in xrange(r2):
# starts[i,:] = coor[r1,:]
# vecs[i,:] = coor[r2,:] - coor[r1,:]
# adjdat[i,:]
# i+=1
adjdat = A.flat[ixes]
A_r = np.tile(coor, (n, 1, 1))
starts = np.reshape(A_r, (n * n, 3))[ixes, :]
vecs = np.reshape(A_r - np.transpose(A_r, (1, 0, 2)), (n * n, 3))[ixes, :]
# plotting
fig = mlab.figure()
nodesource = mlab.pipeline.scalar_scatter(
coor[:, 0], coor[:, 1], coor[:, 2], figure=fig)
nodes = mlab.pipeline.glyph(nodesource, scale_mode='none',
scale_factor=3., mode='sphere', figure=fig)
nodes.glyph.color_mode = 'color_by_scalar'
vectorsrc = mlab.pipeline.vector_scatter(
starts[:, 0], starts[:, 1], starts[
:, 2], vecs[:, 0], vecs[:, 1], vecs[:, 2],
figure=fig)
vectorsrc.mlab_source.dataset.point_data.scalars = adjdat
thres = mlab.pipeline.threshold(vectorsrc,
low=0.0001, up=np.max(A), figure=fig)
vectors = mlab.pipeline.vectors(thres, colormap='YlOrRd',
scale_mode='vector', figure=fig)
vectors.glyph.glyph.clamping = False
vectors.glyph.glyph.color_mode = 'color_by_scalar'
vectors.glyph.color_mode = 'color_by_scalar'
vectors.glyph.glyph_source.glyph_position = 'head'
vectors.actor.property.opacity = .7
if tube:
vectors.glyph.glyph_source.glyph_source = (vectors.glyph.glyph_source.
glyph_dict['cylinder_source'])
vectors.glyph.glyph_source.glyph_source.radius = 0.015
else:
vectors.glyph.glyph_source.glyph_source.glyph_type = 'dash'
return fig |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def backbone_wu(CIJ, avgdeg):
'''
The network backbone contains the dominant connections in the network
and may be used to aid network visualization. This function computes
the backbone of a given weighted and undirected connection matrix CIJ,
using a minimum-spanning-tree based algorithm.
Parameters
----------
CIJ : NxN np.ndarray
weighted undirected connection matrix
avgdeg : int
desired average degree of backbone
Returns
-------
CIJtree : NxN np.ndarray
connection matrix of the minimum spanning tree of CIJ
CIJclus : NxN np.ndarray
connection matrix of the minimum spanning tree plus strongest
connections up to some average degree 'avgdeg'. Identical to CIJtree
if the degree requirement is already met.
Notes
-----
NOTE: nodes with zero strength are discarded.
NOTE: CIJclus will have a total average degree exactly equal to
(or very close to) 'avgdeg'.
NOTE: 'avgdeg' backfill is handled slightly differently than in Hagmann
et al 2008.
'''
n = len(CIJ)
if not np.all(CIJ == CIJ.T):
raise BCTParamError('backbone_wu can only be computed for undirected '
'matrices. If your matrix is has noise, correct it with np.around')
CIJtree = np.zeros((n, n))
# find strongest edge (if multiple edges are tied, use only first one)
i, j = np.where(np.max(CIJ) == CIJ)
im = [i[0], i[1]] # what? why take two values? doesnt that mess up multiples?
jm = [j[0], j[1]]
# copy into tree graph
CIJtree[im, jm] = CIJ[im, jm]
in_ = im
out = np.setdiff1d(range(n), in_)
# repeat n-2 times
for ix in range(n - 2):
CIJ_io = CIJ[np.ix_(in_, out)]
i, j = np.where(np.max(CIJ_io) == CIJ_io)
# i,j=np.where(np.max(CIJ[in_,out])==CIJ[in_,out])
print(i, j)
im = in_[i[0]]
jm = out[j[0]]
# copy into tree graph
CIJtree[im, jm] = CIJ[im, jm]
CIJtree[jm, im] = CIJ[jm, im]
in_ = np.append(in_, jm)
out = np.setdiff1d(range(n), in_)
# now add connections back with the total number of added connections
# determined by the desired avgdeg
CIJnotintree = CIJ * np.logical_not(CIJtree)
ix, = np.where(CIJnotintree.flat)
a = np.sort(CIJnotintree.flat[ix])[::-1]
cutoff = avgdeg * n - 2 * (n - 1) - 1
# if the avgdeg req is already satisfied, skip this
if cutoff >= np.size(a):
CIJclus = CIJtree.copy()
else:
thr = a[cutoff]
CIJclus = CIJtree + CIJnotintree * (CIJnotintree >= thr)
return CIJtree, CIJclus |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reorderMAT(m, H=5000, cost='line'):
'''
This function reorders the connectivity matrix in order to place more
edges closer to the diagonal. This often helps in displaying community
structure, clusters, etc.
Parameters
----------
MAT : NxN np.ndarray
connection matrix
H : int
number of reordering attempts
cost : str
'line' or 'circ' for shape of lattice (linear or ring lattice).
Default is linear lattice.
Returns
-------
MATreordered : NxN np.ndarray
reordered connection matrix
MATindices : Nx1 np.ndarray
reordered indices
MATcost : float
objective function cost of reordered matrix
Notes
-----
I'm not 100% sure how the algorithms between this and reorder_matrix
differ, but this code looks a ton sketchier and might have had some minor
bugs in it. Considering reorder_matrix() does the same thing using a well
vetted simulated annealing algorithm, just use that. ~rlaplant
'''
from scipy import linalg, stats
m = m.copy()
n = len(m)
np.fill_diagonal(m, 0)
# generate cost function
if cost == 'line':
profile = stats.norm.pdf(range(1, n + 1), 0, n / 2)[::-1]
elif cost == 'circ':
profile = stats.norm.pdf(range(1, n + 1), n / 2, n / 4)[::-1]
else:
raise BCTParamError('dfun must be line or circ')
costf = linalg.toeplitz(profile, r=profile)
lowcost = np.sum(costf * m)
# keep track of starting configuration
m_start = m.copy()
starta = np.arange(n)
# reorder
for h in range(H):
a = np.arange(n)
# choose two positions and flip them
r1, r2 = rng.randint(n, size=(2,))
a[r1] = r2
a[r2] = r1
costnew = np.sum((m[np.ix_(a, a)]) * costf)
# if this reduced the overall cost
if costnew < lowcost:
m = m[np.ix_(a, a)]
r2_swap = starta[r2]
r1_swap = starta[r1]
starta[r1] = r2_swap
starta[r2] = r1_swap
lowcost = costnew
M_reordered = m_start[np.ix_(starta, starta)]
m_indices = starta
cost = lowcost
return M_reordered, m_indices, cost |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def reorder_matrix(m1, cost='line', verbose=False, H=1e4, Texp=10, T0=1e-3, Hbrk=10):
'''
This function rearranges the nodes in matrix M1 such that the matrix
elements are squeezed along the main diagonal. The function uses a
version of simulated annealing.
Parameters
----------
M1 : NxN np.ndarray
connection matrix weighted/binary directed/undirected
cost : str
'line' or 'circ' for shape of lattice (linear or ring lattice).
Default is linear lattice.
verbose : bool
print out cost at each iteration. Default False.
H : int
annealing parameter, default value 1e6
Texp : int
annealing parameter, default value 1. Coefficient of H s.t.
Texp0=1-Texp/H
T0 : float
annealing parameter, default value 1e-3
Hbrk : int
annealing parameter, default value = 10. Coefficient of H s.t.
Hbrk0 = H/Hkbr
Returns
-------
Mreordered : NxN np.ndarray
reordered connection matrix
Mindices : Nx1 np.ndarray
reordered indices
Mcost : float
objective function cost of reordered matrix
Notes
-----
Note that in general, the outcome will depend on the initial condition
(the setting of the random number seed). Also, there is no good way to
determine optimal annealing parameters in advance - these paramters
will need to be adjusted "by hand" (particularly H, Texp, and T0).
For large and/or dense matrices, it is highly recommended to perform
exploratory runs varying the settings of 'H' and 'Texp' and then select
the best values.
Based on extensive testing, it appears that T0 and Hbrk can remain
unchanged in most cases. Texp may be varied from 1-1/H to 1-10/H, for
example. H is the most important parameter - set to larger values as
the problem size increases. It is advisable to run this function
multiple times and select the solution(s) with the lowest 'cost'.
Setting 'Texp' to zero cancels annealing and uses a greedy algorithm
instead.
'''
from scipy import linalg, stats
n = len(m1)
if n < 2:
raise BCTParamError("align_matrix will infinite loop on a singleton "
"or null matrix.")
# generate cost function
if cost == 'line':
profile = stats.norm.pdf(range(1, n + 1), loc=0, scale=n / 2)[::-1]
elif cost == 'circ':
profile = stats.norm.pdf(
range(1, n + 1), loc=n / 2, scale=n / 4)[::-1]
else:
raise BCTParamError('cost must be line or circ')
costf = linalg.toeplitz(profile, r=profile) * np.logical_not(np.eye(n))
costf /= np.sum(costf)
# establish maxcost, lowcost, mincost
maxcost = np.sum(np.sort(costf.flat) * np.sort(m1.flat))
lowcost = np.sum(m1 * costf) / maxcost
mincost = lowcost
# initialize
anew = np.arange(n)
amin = np.arange(n)
h = 0
hcnt = 0
# adjust annealing parameters
# H determines the maximal number of steps (user specified)
# Texp determines the steepness of the temperature gradient
Texp = 1 - Texp / H
# T0 sets the initial temperature and scales the energy term (user provided)
# Hbrk sets a break point for the stimulation
Hbrk = H / Hbrk
while h < H:
h += 1
hcnt += 1
# terminate if no new mincost has been found for some time
if hcnt > Hbrk:
break
T = T0 * Texp**h
atmp = anew.copy()
r1, r2 = rng.randint(n, size=(2,))
while r1 == r2:
r2 = rng.randint(n)
atmp[r1] = anew[r2]
atmp[r2] = anew[r1]
costnew = np.sum((m1[np.ix_(atmp, atmp)]) * costf) / maxcost
# annealing
if costnew < lowcost or rng.random_sample() < np.exp(-(costnew - lowcost) / T):
anew = atmp
lowcost = costnew
# is this a new absolute best?
if lowcost < mincost:
amin = anew
mincost = lowcost
if verbose:
print('step %i ... current lowest cost = %f' % (h, mincost))
hcnt = 0
if verbose:
print('step %i ... final lowest cost = %f' % (h, mincost))
M_reordered = m1[np.ix_(amin, amin)]
M_indices = amin
cost = mincost
return M_reordered, M_indices, cost |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def writetoPAJ(CIJ, fname, directed):
'''
This function writes a Pajek .net file from a numpy matrix
Parameters
----------
CIJ : NxN np.ndarray
adjacency matrix
fname : str
filename
directed : bool
True if the network is directed and False otherwise. The data format
may be required to know this for some reason so I am afraid to just
use directed as the default value.
'''
n = np.size(CIJ, axis=0)
with open(fname, 'w') as fd:
fd.write('*vertices %i \r' % n)
for i in range(1, n + 1):
fd.write('%i "%i" \r' % (i, i))
if directed:
fd.write('*arcs \r')
else:
fd.write('*edges \r')
for i in range(n):
for j in range(n):
if CIJ[i, j] != 0:
fd.write('%i %i %.6f \r' % (i + 1, j + 1, CIJ[i, j])) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def makeevenCIJ(n, k, sz_cl, seed=None):
'''
This function generates a random, directed network with a specified
number of fully connected modules linked together by evenly distributed
remaining random connections.
Parameters
----------
N : int
number of vertices (must be power of 2)
K : int
number of edges
sz_cl : int
size of clusters (must be power of 2)
seed : hashable, optional
If None (default), use the np.random's global random state to generate random numbers.
Otherwise, use a new np.random.RandomState instance seeded with the given value.
Returns
-------
CIJ : NxN np.ndarray
connection matrix
Notes
-----
N must be a power of 2.
A warning is generated if all modules contain more edges than K.
Cluster size is 2^sz_cl;
'''
rng = get_rng(seed)
# compute number of hierarchical levels and adjust cluster size
mx_lvl = int(np.floor(np.log2(n)))
sz_cl -= 1
# make a stupid little template
t = np.ones((2, 2)) * 2
# check n against the number of levels
Nlvl = 2**mx_lvl
if Nlvl != n:
print("Warning: n must be a power of 2")
n = Nlvl
# create hierarchical template
for lvl in range(1, mx_lvl):
s = 2**(lvl + 1)
CIJ = np.ones((s, s))
grp1 = range(int(s / 2))
grp2 = range(int(s / 2), s)
ix1 = np.add.outer(np.array(grp1) * s, grp1).flatten()
ix2 = np.add.outer(np.array(grp2) * s, grp2).flatten()
CIJ.flat[ix1] = t # numpy indexing is teh sucks :(
CIJ.flat[ix2] = t
CIJ += 1
t = CIJ.copy()
CIJ -= (np.ones((s, s)) + mx_lvl * np.eye(s))
# assign connection probabilities
CIJp = (CIJ >= (mx_lvl - sz_cl))
# determine nr of non-cluster connections left and their possible positions
rem_k = k - np.size(np.where(CIJp.flatten()))
if rem_k < 0:
print("Warning: K is too small, output matrix contains clusters only")
return CIJp
a, b = np.where(np.logical_not(CIJp + np.eye(n)))
# assign remK randomly dstributed connections
rp = rng.permutation(len(a))
a = a[rp[:rem_k]]
b = b[rp[:rem_k]]
for ai, bi in zip(a, b):
CIJp[ai, bi] = 1
return np.array(CIJp, dtype=int) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def makerandCIJdegreesfixed(inv, outv, seed=None):
'''
This function generates a directed random network with a specified
in-degree and out-degree sequence.
Parameters
----------
inv : Nx1 np.ndarray
in-degree vector
outv : Nx1 np.ndarray
out-degree vector
seed : hashable, optional
If None (default), use the np.random's global random state to generate random numbers.
Otherwise, use a new np.random.RandomState instance seeded with the given value.
Returns
-------
CIJ : NxN np.ndarray
Notes
-----
Necessary conditions include:
length(in) = length(out) = n
sum(in) = sum(out) = k
in(i), out(i) < n-1
in(i) + out(j) < n+2
in(i) + out(i) < n
No connections are placed on the main diagonal
The algorithm used in this function is not, technically, guaranteed to
terminate. If a valid distribution of in and out degrees is provided,
this function will find it in bounded time with probability
1-(1/(2*(k^2))). This turns out to be a serious problem when
computing infinite degree matrices, but offers good performance
otherwise.
'''
rng = get_rng(seed)
n = len(inv)
k = np.sum(inv)
in_inv = np.zeros((k,))
out_inv = np.zeros((k,))
i_in = 0
i_out = 0
for i in range(n):
in_inv[i_in:i_in + inv[i]] = i
out_inv[i_out:i_out + outv[i]] = i
i_in += inv[i]
i_out += outv[i]
CIJ = np.eye(n)
edges = np.array((out_inv, in_inv[rng.permutation(k)]))
# create CIJ and check for double edges and self connections
for i in range(k):
if CIJ[edges[0, i], edges[1, i]]:
tried = set()
while True:
if len(tried) == k:
raise BCTParamError('Could not resolve the given '
'in and out vectors')
switch = rng.randint(k)
while switch in tried:
switch = rng.randint(k)
if not (CIJ[edges[0, i], edges[1, switch]] or
CIJ[edges[0, switch], edges[1, i]]):
CIJ[edges[0, switch], edges[1, switch]] = 0
CIJ[edges[0, switch], edges[1, i]] = 1
if switch < i:
CIJ[edges[0, switch], edges[1, switch]] = 0
CIJ[edges[0, switch], edges[1, i]] = 1
t = edges[1, i]
edges[1, i] = edges[1, switch]
edges[1, switch] = t
break
tried.add(switch)
else:
CIJ[edges[0, i], edges[1, i]] = 1
CIJ -= np.eye(n)
return CIJ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def makerandCIJ_dir(n, k, seed=None):
'''
This function generates a directed random network
Parameters
----------
N : int
number of vertices
K : int
number of edges
seed : hashable, optional
If None (default), use the np.random's global random state to generate random numbers.
Otherwise, use a new np.random.RandomState instance seeded with the given value.
Returns
-------
CIJ : NxN np.ndarray
directed random connection matrix
Notes
-----
no connections are placed on the main diagonal.
'''
rng = get_rng(seed)
ix, = np.where(np.logical_not(np.eye(n)).flat)
rp = rng.permutation(np.size(ix))
CIJ = np.zeros((n, n))
CIJ.flat[ix[rp][:k]] = 1
return CIJ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def randmio_dir(R, itr, seed=None):
'''
This function randomizes a directed network, while preserving the in-
and out-degree distributions. In weighted networks, the function
preserves the out-strength but not the in-strength distributions.
Parameters
----------
W : NxN np.ndarray
directed binary/weighted connection matrix
itr : int
rewiring parameter. Each edge is rewired approximately itr times.
seed : hashable, optional
If None (default), use the np.random's global random state to generate random numbers.
Otherwise, use a new np.random.RandomState instance seeded with the given value.
Returns
-------
R : NxN np.ndarray
randomized network
eff : int
number of actual rewirings carried out
'''
rng = get_rng(seed)
R = R.copy()
n = len(R)
i, j = np.where(R)
k = len(i)
itr *= k
max_attempts = np.round(n * k / (n * (n - 1)))
eff = 0
for it in range(int(itr)):
att = 0
while att <= max_attempts: # while not rewired
while True:
e1 = rng.randint(k)
e2 = rng.randint(k)
while e1 == e2:
e2 = rng.randint(k)
a = i[e1]
b = j[e1]
c = i[e2]
d = j[e2]
if a != c and a != d and b != c and b != d:
break # all 4 vertices must be different
# rewiring condition
if not (R[a, d] or R[c, b]):
R[a, d] = R[a, b]
R[a, b] = 0
R[c, b] = R[c, d]
R[c, d] = 0
i.setflags(write=True)
j.setflags(write=True)
i[e1] = d
j[e2] = b # reassign edge indices
eff += 1
break
att += 1
return R, eff |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.