INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Returns the units of the measured value for the current mode. May return empty string
def units(self): """ Returns the units of the measured value for the current mode. May return empty string """ self._units, value = self.get_attr_string(self._units, 'units') return value
Returns the value or values measured by the sensor. Check num_values to see how many values there are. Values with N >= num_values will return an error. The values are fixed point numbers, so check decimals to see if you need to divide to get the actual value.
def value(self, n=0): """ Returns the value or values measured by the sensor. Check num_values to see how many values there are. Values with N >= num_values will return an error. The values are fixed point numbers, so check decimals to see if you need to divide to get the actual ...
Returns the format of the values in `bin_data` for the current mode. Possible values are: - `u8`: Unsigned 8-bit integer (byte) - `s8`: Signed 8-bit integer (sbyte) - `u16`: Unsigned 16-bit integer (ushort) - `s16`: Signed 16-bit integer (short) - `s16_be`: Signed 16-bit...
def bin_data_format(self): """ Returns the format of the values in `bin_data` for the current mode. Possible values are: - `u8`: Unsigned 8-bit integer (byte) - `s8`: Signed 8-bit integer (sbyte) - `u16`: Unsigned 16-bit integer (ushort) - `s16`: Signed 16-bit in...
Returns the unscaled raw values in the `value<N>` attributes as raw byte array. Use `bin_data_format`, `num_values` and the individual sensor documentation to determine how to interpret the data. Use `fmt` to unpack the raw bytes into a struct. Example:: >>> from ev3dev2.s...
def bin_data(self, fmt=None): """ Returns the unscaled raw values in the `value<N>` attributes as raw byte array. Use `bin_data_format`, `num_values` and the individual sensor documentation to determine how to interpret the data. Use `fmt` to unpack the raw bytes into a struct. ...
Returns the firmware version of the sensor if available. Currently only I2C/NXT sensors support this.
def fw_version(self): """ Returns the firmware version of the sensor if available. Currently only I2C/NXT sensors support this. """ (self._fw_version, value) = self.get_cached_attr_string(self._fw_version, 'fw_version') return value
Returns the polling period of the sensor in milliseconds. Writing sets the polling period. Setting to 0 disables polling. Minimum value is hard coded as 50 msec. Returns -EOPNOTSUPP if changing polling is not supported. Currently only I2C/NXT sensors support changing the polling period.
def poll_ms(self): """ Returns the polling period of the sensor in milliseconds. Writing sets the polling period. Setting to 0 disables polling. Minimum value is hard coded as 50 msec. Returns -EOPNOTSUPP if changing polling is not supported. Currently only I2C/NXT sensors suppor...
Return the framebuffer file descriptor. Try to use the FRAMEBUFFER environment variable if fbdev is not given. Use '/dev/fb0' by default.
def _open_fbdev(fbdev=None): """Return the framebuffer file descriptor. Try to use the FRAMEBUFFER environment variable if fbdev is not given. Use '/dev/fb0' by default. """ dev = fbdev or os.getenv('FRAMEBUFFER', '/dev/fb0') fbfid = os.open(dev, os.O_RDWR) ...
Return the fix screen info from the framebuffer file descriptor.
def _get_fix_info(fbfid): """Return the fix screen info from the framebuffer file descriptor.""" fix_info = FbMem.FixScreenInfo() fcntl.ioctl(fbfid, FbMem.FBIOGET_FSCREENINFO, fix_info) return fix_info
Return the var screen info from the framebuffer file descriptor.
def _get_var_info(fbfid): """Return the var screen info from the framebuffer file descriptor.""" var_info = FbMem.VarScreenInfo() fcntl.ioctl(fbfid, FbMem.FBIOGET_VSCREENINFO, var_info) return var_info
Applies pending changes to the screen. Nothing will be drawn on the screen until this function is called.
def update(self): """ Applies pending changes to the screen. Nothing will be drawn on the screen until this function is called. """ if self.var_info.bits_per_pixel == 1: b = self._img.tobytes("raw", "1;R") self.mmap[:len(b)] = b elif self.var_info...
Map the framebuffer memory.
def _map_fb_memory(fbfid, fix_info): """Map the framebuffer memory.""" return mmap.mmap( fbfid, fix_info.smem_len, mmap.MAP_SHARED, mmap.PROT_READ | mmap.PROT_WRITE, offset=0 )
Draw a line from (x1, y1) to (x2, y2)
def line(self, clear_screen=True, x1=10, y1=10, x2=50, y2=50, line_color='black', width=1): """ Draw a line from (x1, y1) to (x2, y2) """ if clear_screen: self.clear() return self.draw.line((x1, y1, x2, y2), fill=line_color, width=width)
Draw a circle of 'radius' centered at (x, y)
def circle(self, clear_screen=True, x=50, y=50, radius=40, fill_color='black', outline_color='black'): """ Draw a circle of 'radius' centered at (x, y) """ if clear_screen: self.clear() x1 = x - radius y1 = y - radius x2 = x + radius y2 = y +...
Draw a rectangle where the top left corner is at (x1, y1) and the bottom right corner is at (x2, y2)
def rectangle(self, clear_screen=True, x1=10, y1=10, x2=80, y2=40, fill_color='black', outline_color='black'): """ Draw a rectangle where the top left corner is at (x1, y1) and the bottom right corner is at (x2, y2) """ if clear_screen: self.clear() return s...
Draw a single pixel at (x, y)
def point(self, clear_screen=True, x=10, y=10, point_color='black'): """ Draw a single pixel at (x, y) """ if clear_screen: self.clear() return self.draw.point((x, y), fill=point_color)
Display `text` starting at pixel (x, y). The EV3 display is 178x128 pixels - (0, 0) would be the top left corner of the display - (89, 64) would be right in the middle of the display 'text_color' : PIL says it supports "common HTML color names". There are 140 HTML color names ...
def text_pixels(self, text, clear_screen=True, x=0, y=0, text_color='black', font=None): """ Display `text` starting at pixel (x, y). The EV3 display is 178x128 pixels - (0, 0) would be the top left corner of the display - (89, 64) would be right in the middle of the display ...
Display 'text' starting at grid (x, y) The EV3 display can be broken down in a grid that is 22 columns wide and 12 rows tall. Each column is 8 pixels wide and each row is 10 pixels tall. 'text_color' : PIL says it supports "common HTML color names". There are 140 HTML color nam...
def text_grid(self, text, clear_screen=True, x=0, y=0, text_color='black', font=None): """ Display 'text' starting at grid (x, y) The EV3 display can be broken down in a grid that is 22 columns wide and 12 rows tall. Each column is 8 pixels wide and each row is 10 pixels tall. ...
Utility function used by Sound class for building the note frequencies table
def _make_scales(notes): """ Utility function used by Sound class for building the note frequencies table """ res = dict() for note, freq in notes: freq = round(freq) for n in note.split('/'): res[n] = freq return res
Call beep command with the provided arguments (if any). See `beep man page`_ and google `linux beep music`_ for inspiration. :param string args: Any additional arguments to be passed to ``beep`` (see the `beep man page`_ for details) :param play_type: The behavior of ``beep`` once playback has...
def beep(self, args='', play_type=PLAY_WAIT_FOR_COMPLETE): """ Call beep command with the provided arguments (if any). See `beep man page`_ and google `linux beep music`_ for inspiration. :param string args: Any additional arguments to be passed to ``beep`` (see the `beep man page`_ for...
.. rubric:: tone(tone_sequence) Play tone sequence. Here is a cheerful example:: my_sound = Sound() my_sound.tone([ (392, 350, 100), (392, 350, 100), (392, 350, 100), (311.1, 250, 100), (466.2, 25, 100), (392, 350, 100), (311.1, 250, 100), (466....
def tone(self, *args, play_type=PLAY_WAIT_FOR_COMPLETE): """ .. rubric:: tone(tone_sequence) Play tone sequence. Here is a cheerful example:: my_sound = Sound() my_sound.tone([ (392, 350, 100), (392, 350, 100), (392, 350, 100), (311.1, 250, 100)...
Play a single tone, specified by its frequency, duration, volume and final delay. :param int frequency: the tone frequency, in Hertz :param float duration: Tone duration, in seconds :param float delay: Delay after tone, in seconds (can be useful when chaining calls to ``play_tone``) :pa...
def play_tone(self, frequency, duration, delay=0.0, volume=100, play_type=PLAY_WAIT_FOR_COMPLETE): """ Play a single tone, specified by its frequency, duration, volume and final delay. :param int frequency: the tone frequency, in Hertz :param float duration: Tone duration, in ...
Plays a note, given by its name as defined in ``_NOTE_FREQUENCIES``. :param string note: The note symbol with its octave number :param float duration: Tone duration, in seconds :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``play_not...
def play_note(self, note, duration, volume=100, play_type=PLAY_WAIT_FOR_COMPLETE): """ Plays a note, given by its name as defined in ``_NOTE_FREQUENCIES``. :param string note: The note symbol with its octave number :param float duration: Tone duration, in seconds :param int volume: The ...
Play a sound file (wav format) at a given volume. :param string wav_file: The sound file path :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``play_file`` once playback has been initiated :type play_type: ``Sound.PLAY_WAIT_FOR_COMPLET...
def play_file(self, wav_file, volume=100, play_type=PLAY_WAIT_FOR_COMPLETE): """ Play a sound file (wav format) at a given volume. :param string wav_file: The sound file path :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``play_file`...
Speak the given text aloud. Uses the ``espeak`` external command. :param string text: The text to speak :param string espeak_opts: ``espeak`` command options (advanced usage) :param int volume: The play volume, in percent of maximum volume :param play_type: The behavior of ``s...
def speak(self, text, espeak_opts='-a 200 -s 130', volume=100, play_type=PLAY_WAIT_FOR_COMPLETE): """ Speak the given text aloud. Uses the ``espeak`` external command. :param string text: The text to speak :param string espeak_opts: ``espeak`` command options (advanced usage) :...
:returns: The detected sound channel :rtype: string
def _get_channel(self): """ :returns: The detected sound channel :rtype: string """ if self.channel is None: # Get default channel as the first one that pops up in # 'amixer scontrols' output, which contains strings in the # following format: ...
Sets the sound volume to the given percentage [0-100] by calling ``amixer -q set <channel> <pct>%``. If the channel is not specified, it tries to determine the default one by running ``amixer scontrols``. If that fails as well, it uses the ``Playback`` channel, as that is the only channe...
def set_volume(self, pct, channel=None): """ Sets the sound volume to the given percentage [0-100] by calling ``amixer -q set <channel> <pct>%``. If the channel is not specified, it tries to determine the default one by running ``amixer scontrols``. If that fails as well, it uses...
Gets the current sound volume by parsing the output of ``amixer get <channel>``. If the channel is not specified, it tries to determine the default one by running ``amixer scontrols``. If that fails as well, it uses the ``Playback`` channel, as that is the only channel on the EV3.
def get_volume(self, channel=None): """ Gets the current sound volume by parsing the output of ``amixer get <channel>``. If the channel is not specified, it tries to determine the default one by running ``amixer scontrols``. If that fails as well, it uses the ``Playback``...
Plays a song provided as a list of tuples containing the note name and its value using music conventional notation instead of numerical values for frequency and duration. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and durations (e.g. ``q``, ``h``). For an exhaustive lis...
def play_song(self, song, tempo=120, delay=0.05): """ Plays a song provided as a list of tuples containing the note name and its value using music conventional notation instead of numerical values for frequency and duration. It supports symbolic notes (e.g. ``A4``, ``D#3``, ``Gb5``) and...
Look in /sys/class/board-info/ to determine the platform type. This can return 'ev3', 'evb', 'pistorms', 'brickpi', 'brickpi3' or 'fake'.
def get_current_platform(): """ Look in /sys/class/board-info/ to determine the platform type. This can return 'ev3', 'evb', 'pistorms', 'brickpi', 'brickpi3' or 'fake'. """ board_info_dir = '/sys/class/board-info/' if not os.path.exists(board_info_dir) or os.environ.get("FAKE_SYS"): r...
This is a generator function that lists names of all devices matching the provided parameters. Parameters: class_path: class path of the device, a subdirectory of /sys/class. For example, '/sys/class/tacho-motor'. name_pattern: pattern that device name should match. For ...
def list_device_names(class_path, name_pattern, **kwargs): """ This is a generator function that lists names of all devices matching the provided parameters. Parameters: class_path: class path of the device, a subdirectory of /sys/class. For example, '/sys/class/tacho-motor'. ...
This is a generator function that takes same arguments as `Device` class and enumerates all devices present in the system that match the provided arguments. Parameters: class_name: class name of the device, a subdirectory of /sys/class. For example, 'tacho-motor'. name_pattern: ...
def list_devices(class_name, name_pattern, **kwargs): """ This is a generator function that takes same arguments as `Device` class and enumerates all devices present in the system that match the provided arguments. Parameters: class_name: class name of the device, a subdirectory of /sys/cla...
Device attribute getter
def _get_attribute(self, attribute, name): """Device attribute getter""" try: if attribute is None: attribute = self._attribute_file_open( name ) else: attribute.seek(0) return attribute, attribute.read().strip().decode() except...
Device attribute setter
def _set_attribute(self, attribute, name, value): """Device attribute setter""" try: if attribute is None: attribute = self._attribute_file_open( name ) else: attribute.seek(0) if isinstance(value, str): value = value.e...
Close all file handles and stop all motors.
def shutdown(self): """Close all file handles and stop all motors.""" self.stop_balance.set() # Stop balance thread self.motor_left.stop() self.motor_right.stop() self.gyro_file.close() self.touch_file.close() self.encoder_left_file.close() self.encoder_r...
Function for fast reading from sensor files.
def _fast_read(self, infile): """Function for fast reading from sensor files.""" infile.seek(0) return(int(infile.read().decode().strip()))
Function for fast writing to motor files.
def _fast_write(self, outfile, value): """Function for fast writing to motor files.""" outfile.truncate(0) outfile.write(str(int(value))) outfile.flush()
Function to set the duty cycle of the motors.
def _set_duty(self, motor_duty_file, duty, friction_offset, voltage_comp): """Function to set the duty cycle of the motors.""" # Compensate for nominal voltage and round the input duty_int = int(round(duty*voltage_comp)) # Add or subtract offset and clamp the value bet...
Run the _balance method as a thread.
def balance(self): """Run the _balance method as a thread.""" balance_thread = threading.Thread(target=self._balance) balance_thread.start()
Make the robot balance.
def _balance(self): """Make the robot balance.""" while True and not self.stop_balance.is_set(): # Reset the motors self.motor_left.reset() # Reset the encoder self.motor_right.reset() self.motor_left.run_direct() # Set to run direct mode se...
Move robot.
def _move(self, speed=0, steering=0, seconds=None): """Move robot.""" self.drive_queue.put((speed, steering)) if seconds is not None: time.sleep(seconds) self.drive_queue.put((0, 0)) self.drive_queue.join()
Move robot forward.
def move_forward(self, seconds=None): """Move robot forward.""" self._move(speed=SPEED_MAX, steering=0, seconds=seconds)
Move robot backward.
def move_backward(self, seconds=None): """Move robot backward.""" self._move(speed=-SPEED_MAX, steering=0, seconds=seconds)
Rotate robot left.
def rotate_left(self, seconds=None): """Rotate robot left.""" self._move(speed=0, steering=STEER_MAX, seconds=seconds)
Rotate robot right.
def rotate_right(self, seconds=None): """Rotate robot right.""" self._move(speed=0, steering=-STEER_MAX, seconds=seconds)
Return our corresponding evdev device object
def evdev_device(self): """ Return our corresponding evdev device object """ devices = [evdev.InputDevice(fn) for fn in evdev.list_devices()] for device in devices: if device.name == self.evdev_device_name: return device raise Exception("%s: ...
Check for currenly pressed buttons. If the new state differs from the old state, call the appropriate button event handlers.
def process(self, new_state=None): """ Check for currenly pressed buttons. If the new state differs from the old state, call the appropriate button event handlers. """ if new_state is None: new_state = set(self.buttons_pressed) old_state = self._state ...
Wait for the button to be pressed down and then released. Both actions must happen within timeout_ms.
def wait_for_bump(self, buttons, timeout_ms=None): """ Wait for the button to be pressed down and then released. Both actions must happen within timeout_ms. """ start_time = time.time() if self.wait_for_pressed(buttons, timeout_ms): if timeout_ms is not None:...
Returns list of names of pressed buttons.
def buttons_pressed(self): """ Returns list of names of pressed buttons. """ for b in self._buffer_cache: fcntl.ioctl(self._button_file(b), self.EVIOCGKEY, self._buffer_cache[b]) pressed = [] for k, v in self._buttons.items(): buf = self._buffer_c...
Waits maximum of 5 minutes for orted process to start
def _orted_process(): """Waits maximum of 5 minutes for orted process to start""" for i in range(5 * 60): procs = [p for p in psutil.process_iter(attrs=['name']) if p.info['name'] == 'orted'] if procs: return procs time.sleep(1)
Checks if the connection to provided ``host`` and ``port`` is possible or not. Args: host (str): Hostname for the host to check connection. port (int): Port name of the host to check connection on.
def _can_connect(host, port=22): # type: (str, int) -> bool """Checks if the connection to provided ``host`` and ``port`` is possible or not. Args: host (str): Hostname for the host to check connection. port (int): Port name of the host to check connection on. """ try: ...
Parse custom MPI options provided by user. Known options default value will be overridden and unknown options would be identified separately.
def _parse_custom_mpi_options(custom_mpi_options): # type: (str) -> Tuple[argparse.Namespace, List[str]] """Parse custom MPI options provided by user. Known options default value will be overridden and unknown options would be identified separately.""" parser = argparse.ArgumentParser() parser.add_...
The WorkerRunner proceeds as following: - wait for the MPI Master to create its SSH daemon - start its SSH daemon - monitor the MPI orted process and wait it to finish the MPI execution
def run(self, wait=True, capture_error=False): # type: (bool, bool) -> None """The WorkerRunner proceeds as following: - wait for the MPI Master to create its SSH daemon - start its SSH daemon - monitor the MPI orted process and wait it to finish the MPI execution """ l...
Add a signal-based timeout to any block of code. If multiple time units are specified, they will be added together to determine time limit. Usage: with timeout(seconds=5): my_slow_function(...) Args: - seconds: The time limit, in seconds. - minutes: The time limit, in minutes. ...
def timeout(seconds=0, minutes=0, hours=0): """ Add a signal-based timeout to any block of code. If multiple time units are specified, they will be added together to determine time limit. Usage: with timeout(seconds=5): my_slow_function(...) Args: - seconds: The time limit, in se...
Prepare a Python script (or module) to be imported as a module. If the script does not contain a setup.py file, it creates a minimal setup. Args: path (str): path to directory with the script or module. name (str): name of the script or module.
def prepare(path, name): # type: (str, str) -> None """Prepare a Python script (or module) to be imported as a module. If the script does not contain a setup.py file, it creates a minimal setup. Args: path (str): path to directory with the script or module. name (str): name of the script or...
Install a Python module in the executing Python environment. Args: path (str): Real path location of the Python module. capture_error (bool): Default false. If True, the running process captures the stderr, and appends it to the returned Exception message in case of errors.
def install(path, capture_error=False): # type: (str, bool) -> None """Install a Python module in the executing Python environment. Args: path (str): Real path location of the Python module. capture_error (bool): Default false. If True, the running process captures the stderr, and ...
Download, prepare and install a compressed tar file from S3 or local directory as a module. The SageMaker Python SDK saves the user provided scripts as compressed tar files in S3. This function downloads this compressed file and, if provided, transforms it into a module before installing it. This meth...
def download_and_install(uri, name=DEFAULT_MODULE_NAME, cache=True): # type: (str, str, bool) -> None """Download, prepare and install a compressed tar file from S3 or local directory as a module. The SageMaker Python SDK saves the user provided scripts as compressed tar files in S3. This function down...
Run Python module as a script. Search sys.path for the named module and execute its contents as the __main__ module. Since the argument is a module name, you must not give a file extension (.py). The module name should be a valid absolute Python module name, but the implementation may not always enforce t...
def run(module_name, args=None, env_vars=None, wait=True, capture_error=False): # type: (str, list, dict, bool, bool) -> subprocess.Popen """Run Python module as a script. Search sys.path for the named module and execute its contents as the __main__ module. Since the argument is a module name, you mus...
Download, prepare and install a compressed tar file from S3 or provided directory as a module. SageMaker Python SDK saves the user provided scripts as compressed tar files in S3 https://github.com/aws/sagemaker-python-sdk. This function downloads this compressed file, if provided, and transforms it as a mod...
def import_module(uri, name=DEFAULT_MODULE_NAME, cache=None): # type: (str, str, bool) -> module """Download, prepare and install a compressed tar file from S3 or provided directory as a module. SageMaker Python SDK saves the user provided scripts as compressed tar files in S3 https://github.com/aws/sagema...
Download, prepare and executes a compressed tar file from S3 or provided directory as a module. SageMaker Python SDK saves the user provided scripts as compressed tar files in S3 https://github.com/aws/sagemaker-python-sdk. This function downloads this compressed file, transforms it as a module, and execut...
def run_module(uri, args, env_vars=None, name=DEFAULT_MODULE_NAME, cache=None, wait=True, capture_error=False): # type: (str, list, dict, str, bool, bool, bool) -> subprocess.Popen """Download, prepare and executes a compressed tar file from S3 or provided directory as a module. SageMaker Python SDK saves ...
The request's content-type. Returns: (str): The value, if any, of the header 'ContentType' (used by some AWS services) and 'Content-Type'. Otherwise, returns 'application/json' as default.
def content_type(self): # type: () -> str """The request's content-type. Returns: (str): The value, if any, of the header 'ContentType' (used by some AWS services) and 'Content-Type'. Otherwise, returns 'application/json' as default. """ # todo(mvsusp): ...
The content-type for the response to the client. Returns: (str): The value of the header 'Accept' or the user-supplied SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT environment variable.
def accept(self): # type: () -> str """The content-type for the response to the client. Returns: (str): The value of the header 'Accept' or the user-supplied SAGEMAKER_DEFAULT_INVOCATIONS_ACCEPT environment variable. """ accept = self.headers.get('Accept...
The request incoming data. It automatic decodes from utf-8 Returns: (obj): incoming data
def content(self): # type: () -> object """The request incoming data. It automatic decodes from utf-8 Returns: (obj): incoming data """ as_text = self.content_type in _content_types.UTF8_TYPES return self.get_data(as_text=as_text)
Download, prepare and executes a compressed tar file from S3 or provided directory as an user entrypoint. Runs the user entry point, passing env_vars as environment variables and args as command arguments. If the entry point is: - A Python package: executes the packages as >>> env_vars python -m mo...
def run(uri, user_entry_point, args, env_vars=None, wait=True, capture_error=False, runner=_runner.ProcessRunnerType, extra_opts=None): # type: (str, str, List[str], Dict[str, str], bool, bool, _runner.RunnerType, Dict[str, str]) -> None """Download, prepa...
Install the user provided entry point to be executed as follow: - add the path to sys path - if the user entry point is a command, gives exec permissions to the script Args: name (str): name of the script or module. dst (str): path to directory with the script or module. cap...
def install(name, dst, capture_error=False): """Install the user provided entry point to be executed as follow: - add the path to sys path - if the user entry point is a command, gives exec permissions to the script Args: name (str): name of the script or module. dst (str): path...
Set logger configuration. Args: level (int): Logger level format (str): Logger format
def configure_logger(level, format='%(asctime)s %(name)-12s %(levelname)-8s %(message)s'): # type: (int, str) -> None """Set logger configuration. Args: level (int): Logger level format (str): Logger format """ logging.basicConfig(format=format, level=level) if level >= logging...
Return a timestamp with microsecond precision.
def _timestamp(): """Return a timestamp with microsecond precision.""" moment = time.time() moment_us = repr(moment).split('.')[1] return time.strftime("%Y-%m-%d-%H-%M-%S-{}".format(moment_us), time.gmtime(moment))
As soon as a user is done with a file under `/opt/ml/output/intermediate` we would get notified by using inotify. We would copy this file under `/opt/ml/output/intermediate/.tmp.sagemaker_s3_sync` folder preserving the same folder structure to prevent it from being further modified. As we copy the file ...
def _watch(inotify, watchers, watch_flags, s3_uploader): """As soon as a user is done with a file under `/opt/ml/output/intermediate` we would get notified by using inotify. We would copy this file under `/opt/ml/output/intermediate/.tmp.sagemaker_s3_sync` folder preserving the same folder structure to ...
Starts intermediate folder sync which copies files from 'opt/ml/output/intermediate' directory to the provided s3 output location as files created or modified. If files are deleted it doesn't delete them from s3. It starts intermediate folder behavior as a daemonic process and only if the directory doe...
def start_sync(s3_output_location, region): """Starts intermediate folder sync which copies files from 'opt/ml/output/intermediate' directory to the provided s3 output location as files created or modified. If files are deleted it doesn't delete them from s3. It starts intermediate folder behavior as a...
Transform a dictionary in a dictionary of env vars. Example: >>>env_vars = mapping.to_env_vars({'model_dir': '/opt/ml/model', 'batch_size': 25}) >>> >>>print(args) ['MODEL_DIR', '/opt/ml/model', 'BATCH_SIZE', 25] Args: mapping (dict[str, object]): A Python mapping....
def to_env_vars(mapping): # type: (dict) -> dict """Transform a dictionary in a dictionary of env vars. Example: >>>env_vars = mapping.to_env_vars({'model_dir': '/opt/ml/model', 'batch_size': 25}) >>> >>>print(args) ['MODEL_DIR', '/opt/ml/model', 'BATCH_SIZE', 25] Args...
Transform a dictionary in a list of cmd arguments. Example: >>>args = mapping.to_cmd_args({'model_dir': '/opt/ml/model', 'batch_size': 25}) >>> >>>print(args) ['--model_dir', '/opt/ml/model', '--batch_size', 25] Args: mapping (dict[str, object]): A Python mapping. Ret...
def to_cmd_args(mapping): # type: (dict) -> list """Transform a dictionary in a list of cmd arguments. Example: >>>args = mapping.to_cmd_args({'model_dir': '/opt/ml/model', 'batch_size': 25}) >>> >>>print(args) ['--model_dir', '/opt/ml/model', '--batch_size', 25] Args: ...
Decode an object to unicode. Args: obj (bytes or str or unicode or anything serializable): object to be decoded Returns: object decoded in unicode.
def _decode(obj): # type: (bytes or str or unicode or object) -> unicode # noqa ignore=F821 """Decode an object to unicode. Args: obj (bytes or str or unicode or anything serializable): object to be decoded Returns: object decoded in unicode. """ if obj is None: return u'' ...
Split a dictionary in two by the provided keys. Args: dictionary (dict[str, object]): A Python dictionary keys (sequence [str]): A sequence of keys which will be added the split criteria prefix (str): A prefix which will be added the split criteria Returns: `SplitResultSpec` : ...
def split_by_criteria(dictionary, keys=None, prefix=None): # type: (dict, set or list or tuple) -> SplitResultSpec """Split a dictionary in two by the provided keys. Args: dictionary (dict[str, object]): A Python dictionary keys (sequence [str]): A sequence of keys which will be added the spli...
Returns: (list[str]) List of public properties
def properties(self): # type: () -> list """ Returns: (list[str]) List of public properties """ _type = type(self) return [_property for _property in dir(_type) if self._is_property(_property)]
Function responsible to serialize the prediction for the response. Args: prediction (obj): prediction returned by predict_fn . accept (str): accept content-type expected by the client. Returns: (worker.Response): a Flask response object with the following args: * Args: ...
def default_output_fn(prediction, accept): """Function responsible to serialize the prediction for the response. Args: prediction (obj): prediction returned by predict_fn . accept (str): accept content-type expected by the client. Returns: (worker.Response): a Flask response object...
Take a request with input data, deserialize it, make a prediction, and return a serialized response. Returns: sagemaker_containers.beta.framework.worker.Response: a Flask response object with the following args: * response: the serialized data to return ...
def transform(self): # type: () -> _worker.Response """Take a request with input data, deserialize it, make a prediction, and return a serialized response. Returns: sagemaker_containers.beta.framework.worker.Response: a Flask response object with the following args:...
Make predictions against the model and return a serialized response. This serves as the default implementation of transform_fn, used when the user has not implemented one themselves. Args: model (obj): model loaded by model_fn. content: request content. cont...
def _default_transform_fn(self, model, content, content_type, accept): """Make predictions against the model and return a serialized response. This serves as the default implementation of transform_fn, used when the user has not implemented one themselves. Args: model (obj)...
Args: path (string): Directory where the entry point is located name (string): Name of the entry point file Returns: (_EntryPointType): The type of the entry point
def get(path, name): # type: (str, str) -> _EntryPointType """ Args: path (string): Directory where the entry point is located name (string): Name of the entry point file Returns: (_EntryPointType): The type of the entry point """ if 'setup.py' in os.listdir(path): ...
Create a TrainingEnv. Returns: TrainingEnv: an instance of TrainingEnv
def training_env(): # type: () -> _env.TrainingEnv """Create a TrainingEnv. Returns: TrainingEnv: an instance of TrainingEnv """ from sagemaker_containers import _env return _env.TrainingEnv( resource_config=_env.read_resource_config(), input_data_config=_env.read_input_d...
Writes a serializeable object as a JSON file
def _write_json(obj, path): # type: (object, str) -> None """Writes a serializeable object as a JSON file""" with open(path, 'w') as f: json.dump(obj, f)
Sets the environment variable SAGEMAKER_BASE_DIR as ~/sagemaker_local/{timestamp}/opt/ml Returns: (bool): indicating whe
def _set_base_path_env(): # type: () -> None """Sets the environment variable SAGEMAKER_BASE_DIR as ~/sagemaker_local/{timestamp}/opt/ml Returns: (bool): indicating whe """ local_config_dir = os.path.join(os.path.expanduser('~'), 'sagemaker_local', 'jobs', ...
Creates the directory structure and files necessary for training under the base path
def _create_training_directories(): """Creates the directory structure and files necessary for training under the base path """ logger.info('Creating a new training folder under %s .' % base_dir) os.makedirs(model_dir) os.makedirs(input_config_dir) os.makedirs(output_data_dir) _write_json(...
Read the hyperparameters from /opt/ml/input/config/hyperparameters.json. For more information about hyperparameters.json: https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html#your-algorithms-training-algo-running-container-hyperparameters Returns: (dict[string, objec...
def read_hyperparameters(): # type: () -> dict """Read the hyperparameters from /opt/ml/input/config/hyperparameters.json. For more information about hyperparameters.json: https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html#your-algorithms-training-algo-running-container-hyp...
The number of gpus available in the current container. Returns: int: number of gpus available in the current container.
def num_gpus(): # type: () -> int """The number of gpus available in the current container. Returns: int: number of gpus available in the current container. """ try: cmd = shlex.split('nvidia-smi --list-gpus') output = subprocess.check_output(cmd).decode('utf-8') return...
Write the dictionary env_vars in the system, as environment variables. Args: env_vars (): Returns:
def write_env_vars(env_vars=None): # type: (dict) -> None """Write the dictionary env_vars in the system, as environment variables. Args: env_vars (): Returns: """ env_vars = env_vars or {} env_vars['PYTHONPATH'] = ':'.join(sys.path) for name, value in env_vars.items(): ...
Environment variable representation of the training environment Returns: dict: an instance of dictionary
def to_env_vars(self): """Environment variable representation of the training environment Returns: dict: an instance of dictionary """ env = { 'hosts': self.hosts, 'network_interface_name': self.network_interface_name, 'hps': self.hyperparameters, 'u...
Convert an array like object to the NPY format. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays Args: array_like (np.array or Iterable or int or float): array like object to be co...
def array_to_npy(array_like): # type: (np.array or Iterable or int or float) -> object """Convert an array like object to the NPY format. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays ...
Convert an NPY array into numpy. Args: npy_array (npy array): to be converted to numpy array Returns: (np.array): converted numpy array.
def npy_to_numpy(npy_array): # type: (object) -> np.array """Convert an NPY array into numpy. Args: npy_array (npy array): to be converted to numpy array Returns: (np.array): converted numpy array. """ stream = BytesIO(npy_array) return np.load(stream, allow_pickle=True)
Convert an array like object to JSON. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays Args: array_like (np.array or Iterable or int or float): array like object to be converted to...
def array_to_json(array_like): # type: (np.array or Iterable or int or float) -> str """Convert an array like object to JSON. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays Args: ...
Convert a JSON object to a numpy array. Args: string_like (str): JSON string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the contents of each column, individually. This argument can only b...
def json_to_numpy(string_like, dtype=None): # type: (str) -> np.array """Convert a JSON object to a numpy array. Args: string_like (str): JSON string. dtype (dtype, optional): Data type of the resulting array. If None, the dtypes will be determined by the ...
Convert an array like object to CSV. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays Args: array_like (np.array or Iterable or int or float): array like object to be converted to ...
def array_to_csv(array_like): # type: (np.array or Iterable or int or float) -> str """Convert an array like object to CSV. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays Args: ...
Decode an object ton a one of the default content types to a numpy array. Args: obj (object): to be decoded. content_type (str): content type to be used. Returns: np.array: decoded object.
def decode(obj, content_type): # type: (np.array or Iterable or int or float, str) -> np.array """Decode an object ton a one of the default content types to a numpy array. Args: obj (object): to be decoded. content_type (str): content type to be used. Returns: np.array: decoded...
Encode an array like object in a specific content_type to a numpy array. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-python-array-like-objects-to-numpy-arrays Args: array_like (np.array or Iterable or int or float): t...
def encode(array_like, content_type): # type: (np.array or Iterable or int or float, str) -> np.array """Encode an array like object in a specific content_type to a numpy array. To understand better what an array like object is see: https://docs.scipy.org/doc/numpy/user/basics.creation.html#converting-...
Create a file 'success' when training is successful. This file doesn't need to have any content. See: https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html
def write_success_file(): # type: () -> None """Create a file 'success' when training is successful. This file doesn't need to have any content. See: https://docs.aws.amazon.com/sagemaker/latest/dg/your-algorithms-training-algo.html """ file_path = os.path.join(_env.output_dir, 'success') empty_con...
Create a file 'failure' if training fails after all algorithm output (for example, logging) completes, the failure description should be written to this file. In a DescribeTrainingJob response, Amazon SageMaker returns the first 1024 characters from this file as FailureReason. See: https://docs.aws.amazon.c...
def write_failure_file(failure_msg): # type: (str) -> None """Create a file 'failure' if training fails after all algorithm output (for example, logging) completes, the failure description should be written to this file. In a DescribeTrainingJob response, Amazon SageMaker returns the first 1024 characters ...
Create a temporary directory with a context manager. The file is deleted when the context exits. The prefix, suffix, and dir arguments are the same as for mkstemp(). Args: suffix (str): If suffix is specified, the file name will end with that suffix, otherwise there will be no ...
def tmpdir(suffix='', prefix='tmp', dir=None): # type: (str, str, str) -> None """Create a temporary directory with a context manager. The file is deleted when the context exits. The prefix, suffix, and dir arguments are the same as for mkstemp(). Args: suffix (str): If suffix is specified, the ...
Write data to a file. Args: path (str): path to the file. data (str): data to be written to the file. mode (str): mode which the file will be open.
def write_file(path, data, mode='w'): # type: (str, str, str) -> None """Write data to a file. Args: path (str): path to the file. data (str): data to be written to the file. mode (str): mode which the file will be open. """ with open(path, mode) as f: f.write(data)
Download, prepare and install a compressed tar file from S3 or local directory as an entry point. SageMaker Python SDK saves the user provided entry points as compressed tar files in S3 Args: name (str): name of the entry point. uri (str): the location of the entry point. path (bool): ...
def download_and_extract(uri, name, path): # type: (str, str, str) -> None """Download, prepare and install a compressed tar file from S3 or local directory as an entry point. SageMaker Python SDK saves the user provided entry points as compressed tar files in S3 Args: name (str): name of the ent...
Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved.
def s3_download(url, dst): # type: (str, str) -> None """Download a file from S3. Args: url (str): the s3 url of the file. dst (str): the destination where the file will be saved. """ url = parse.urlparse(url) if url.scheme != 's3': raise ValueError("Expecting 's3' scheme,...
Given a function fn and a dict dictionary, returns the function arguments that match the dict keys. Example: def train(channel_dirs, model_dir): pass dictionary = {'channel_dirs': {}, 'model_dir': '/opt/ml/model', 'other_args': None} args = functions.matching_args(train, dictionary) # {'...
def matching_args(fn, dictionary): # type: (Callable, _mapping.Mapping) -> dict """Given a function fn and a dict dictionary, returns the function arguments that match the dict keys. Example: def train(channel_dirs, model_dir): pass dictionary = {'channel_dirs': {}, 'model_dir': '/opt/ml/mod...
Get the names and default values of a function's arguments. Args: fn (function): a function Returns: `inspect.ArgSpec`: A collections.namedtuple with the following attributes: * Args: args (list): a list of the argument names (it may contain nested lists). ...
def getargspec(fn): # type: (Callable) -> inspect.ArgSpec """Get the names and default values of a function's arguments. Args: fn (function): a function Returns: `inspect.ArgSpec`: A collections.namedtuple with the following attributes: * Args: args (list): a...