code
string | signature
string | docstring
string | loss_without_docstring
float64 | loss_with_docstring
float64 | factor
float64 |
---|---|---|---|---|---|
if len(key) > 250:
raise ValueError(
"Cache key is longer than the maxmimum 250 characters: {}"
.format(key),
)
return super(MySQLCache, self).validate_key(key) | def validate_key(self, key) | Django normally warns about maximum key length, but we error on it. | 4.761692 | 4.052027 | 1.175138 |
if self._is_valid_mysql_bigint(obj):
return obj, 'i'
value = pickle.dumps(obj, pickle.HIGHEST_PROTOCOL)
value_type = 'p'
if (
self._compress_min_length
and len(value) >= self._compress_min_length
):
value = zlib.compress(value, self._compress_level)
value_type = 'z'
return value, value_type | def encode(self, obj) | Take a Python object and return it as a tuple (value, value_type), a
blob and a one-char code for what type it is | 3.843067 | 3.457218 | 1.111607 |
if value_type == 'i':
return int(value)
if value_type == 'z':
value = zlib.decompress(value)
value_type = 'p'
if value_type == 'p':
return pickle.loads(force_bytes(value))
raise ValueError(
"Unknown value_type '{}' read from the cache table."
.format(value_type),
) | def decode(self, value, value_type) | Take a value blob and its value_type one-char code and convert it back
to a python object | 4.097928 | 4.06781 | 1.007404 |
if '*/' in string:
raise ValueError("Bad label - cannot be embedded in SQL comment")
return self.extra(where=["/*QueryRewrite':label={}*/1".format(string)]) | def label(self, string) | Adds an arbitrary user-defined comment that will appear after
SELECT/UPDATE/DELETE which can be used to identify where the query was
generated, etc. | 47.58279 | 33.372799 | 1.425796 |
if len(kwargs) == 0:
return None, None
elif len(kwargs) > 1:
raise ValueError("You can't pass more than one value expression, "
"you passed {}".format(",".join(kwargs.keys())))
name, value = list(kwargs.items())[0]
if not name.startswith('value'):
raise ValueError("The keyword arg {} is not valid for this "
"function".format(name))
if name == 'value':
return ('=', value)
if not name.startswith('value__'):
raise ValueError("The keyword arg {} is not valid for this "
"function".format(name))
operator = name[name.find('__') + 2:]
try:
return (self._operator_values[operator], value)
except KeyError:
raise ValueError(
"The operator {op} is not valid for index value matching. "
"Valid operators are {valid}"
.format(
op=operator,
valid=",".join(self._operator_values.keys()),
),
) | def _parse_index_value(self, kwargs) | Parse the HANDLER-supported subset of django's __ expression syntax | 2.862042 | 2.804614 | 1.020476 |
if not cls._is_simple_query(queryset.query):
raise ValueError("This QuerySet's WHERE clause is too complex to "
"be used in a HANDLER")
sql, params = queryset.query.sql_with_params()
where_pos = sql.find('WHERE ')
if where_pos != -1:
# Cut the query to extract just its WHERE clause
where_clause = sql[where_pos:]
# Replace absolute table.column references with relative ones
# since that is all HANDLER can work with
# This is a bit flakey - if you inserted extra SQL with extra() or
# an expression or something it might break.
where_clause, _ = cls.absolute_col_re.subn(r"\1", where_clause)
return (where_clause, params)
else:
return ("", ()) | def _extract_where(cls, queryset) | Was this a queryset with filters/excludes/expressions set? If so,
extract the WHERE clause from the ORM output so we can use it in the
handler queries. | 7.271473 | 6.653122 | 1.092942 |
return (
not query.low_mark
and not query.high_mark
and not query.select
and not query.group_by
and not query.distinct
and not query.order_by
and len(query.alias_map) <= 1
) | def _is_simple_query(cls, query) | Inspect the internals of the Query and say if we think its WHERE clause
can be used in a HANDLER statement | 3.713687 | 3.140894 | 1.182366 |
column_types = {}
for line in sql.splitlines()[1:]: # first line = CREATE TABLE
sline = line.strip()
if not sline.startswith('`'):
# We've finished parsing the columns
break
bits = sline.split('`')
assert len(bits) == 3
column_name = bits[1]
column_spec = bits[2].lstrip().rstrip(',')
column_types[column_name] = column_spec
return column_types | def parse_create_table(sql) | Split output of SHOW CREATE TABLE into {column: column_spec} | 3.550452 | 3.00156 | 1.182869 |
if names is None:
return []
table_names = OrderedDict() # Preserve order and ignore duplicates
while len(names):
name = names.pop(0)
if hasattr(name, '_meta'):
if name._meta.abstract:
raise ValueError("Can't lock abstract model {}"
.format(name.__name__))
table_names[name._meta.db_table] = True
# Include all parent models - the keys are the model classes
if name._meta.parents:
names.extend(name._meta.parents.keys())
else:
table_names[name] = True
return table_names.keys() | def _process_names(self, names) | Convert a list of models/table names into a list of table names. Deals
with cases of model inheritance, etc. | 4.243229 | 3.747474 | 1.13229 |
while True:
index = 0
anim = getattr(self.animations, seq_name)
speed = anim.speed if hasattr(anim, "speed") else 1
num_frames = len(anim.frames)
while index < num_frames:
frame = anim.frames[int(index)]
index += speed
if isinstance(frame, int):
yield self[frame]
else:
for subseq_frame in self.animate(frame):
yield subseq_frame
if not hasattr(anim, "next"):
break
seq_name = anim.next | def animate(self, seq_name) | Returns a generator which "executes" an animation sequence for the given
``seq_name``, inasmuch as the next frame for the given animation is
yielded when requested.
:param seq_name: The name of a previously defined animation sequence.
:type seq_name: str
:returns: A generator that yields all frames from the animation
sequence.
:raises AttributeError: If the ``seq_name`` is unknown. | 2.968123 | 3.231278 | 0.91856 |
if self.start_time is None:
self.start_time = 0
elapsed = monotonic() - self.start_time
return self.called / elapsed | def effective_FPS(self) | Calculates the effective frames-per-second - this should largely
correlate to the desired FPS supplied in the constructor, but no
guarantees are given.
:returns: The effective frame rate.
:rtype: float | 5.374355 | 5.814854 | 0.924246 |
assert(size[0])
assert(size[1])
return self._image.crop(box=self._crop_box(size)) | def image(self, size) | :param size: The width, height of the image composition.
:type size: tuple
:returns: An image, cropped to the boundaries specified
by ``size``.
:rtype: PIL.Image.Image | 4.82541 | 4.474114 | 1.078518 |
(left, top) = self.offset
right = left + min(size[0], self.width)
bottom = top + min(size[1], self.height)
return (left, top, right, bottom) | def _crop_box(self, size) | Helper that calculates the crop box for the offset within the image.
:param size: The width and height of the image composition.
:type size: tuple
:returns: The bounding box of the image, given ``size``.
:rtype: tuple | 2.736654 | 3.226186 | 0.848263 |
self._clear()
for img in self.composed_images:
self._background_image.paste(img.image(self._device.size),
img.position)
self._background_image.crop(box=self._device.bounding_box) | def refresh(self) | Clears the composition and renders all the images
taking into account their position and offset. | 7.799737 | 5.701852 | 1.367931 |
draw = ImageDraw.Draw(self._background_image)
draw.rectangle(self._device.bounding_box,
fill="black")
del draw | def _clear(self) | Helper that clears the composition. | 7.246379 | 7.129278 | 1.016425 |
self.bounding_box = ImageChops.difference(self.image, image).getbbox()
if self.bounding_box is not None:
self.image = image.copy()
return True
else:
return False | def redraw_required(self, image) | Calculates the difference from the previous image, return a boolean
indicating whether a redraw is required. A side effect is that
``bounding_box`` and ``image`` attributes are updated accordingly, as is
priming :py:func:`getdata`.
:param image: The image to render.
:type image: PIL.Image.Image
:returns: ``True`` or ``False``
:rtype: bool | 2.997358 | 2.613124 | 1.14704 |
left, top, right, bottom = self.bounding_box
self.bounding_box = (
left & 0xFFFC,
top,
right if right % 4 == 0 else (right & 0xFFFC) + 0x04,
bottom)
return self.bounding_box | def inflate_bbox(self) | Realign the left and right edges of the bounding box such that they are
inflated to align modulo 4.
This method is optional, and used mainly to accommodate devices with
COM/SEG GDDRAM structures that store pixels in 4-bit nibbles. | 4.456964 | 4.112798 | 1.083682 |
if self.bounding_box:
return self.image.crop(self.bounding_box).getdata() | def getdata(self) | A sequence of pixel data relating to the changes that occurred
since the last time :py:func:`redraw_required` was last called.
:returns: A sequence of pixels or ``None``.
:rtype: iterable | 6.248955 | 6.976995 | 0.895651 |
left, top = xy
right, bottom = left + entity.width, top + entity.height
return [left, top, right, bottom] | def calc_bounds(xy, entity) | For an entity with width and height attributes, determine
the bounding box if were positioned at ``(x, y)``. | 2.765262 | 3.083864 | 0.896687 |
(x, y) = xy
assert(0 <= x <= self.width - hotspot.width)
assert(0 <= y <= self.height - hotspot.height)
# TODO: should it check to see whether hotspots overlap each other?
# Is sensible to _allow_ them to overlap?
self._hotspots.append((hotspot, xy)) | def add_hotspot(self, hotspot, xy) | Add the hotspot at ``(x, y)``. The hotspot must fit inside the bounds
of the virtual device. If it does not then an ``AssertError`` is
raised. | 5.221321 | 5.203072 | 1.003507 |
self._hotspots.remove((hotspot, xy))
eraser = Image.new(self.mode, hotspot.size)
self._backing_image.paste(eraser, xy) | def remove_hotspot(self, hotspot, xy) | Remove the hotspot at ``(x, y)``: Any previously rendered image where
the hotspot was placed is erased from the backing image, and will be
"undrawn" the next time the virtual device is refreshed. If the
specified hotspot is not found for ``(x, y)``, a ``ValueError`` is
raised. | 5.107615 | 4.361827 | 1.170981 |
l1, t1, r1, b1 = calc_bounds(xy, hotspot)
l2, t2, r2, b2 = calc_bounds(self._position, self._device)
return range_overlap(l1, r1, l2, r2) and range_overlap(t1, b1, t2, b2) | def is_overlapping_viewport(self, hotspot, xy) | Checks to see if the hotspot at position ``(x, y)``
is (at least partially) visible according to the
position of the viewport. | 2.785243 | 2.929917 | 0.950622 |
self._cx, self._cy = (0, 0)
self._canvas.rectangle(self._device.bounding_box,
fill=self.default_bgcolor)
self.flush() | def clear(self) | Clears the display and resets the cursor position to ``(0, 0)``. | 9.121778 | 6.557188 | 1.391111 |
if self.word_wrap:
# find directives in complete text
directives = ansi_color.find_directives(text, self)
# strip ansi from text
clean_text = ansi_color.strip_ansi_codes(text)
# wrap clean text
clean_lines = self.tw.wrap(clean_text)
# print wrapped text
index = 0
for line in clean_lines:
line_length = len(line)
y = 0
while y < line_length:
method, args = directives[index]
if method == self.putch:
y += 1
method(*args)
index += 1
self.newline()
else:
self.puts(text)
self.newline() | def println(self, text="") | Prints the supplied text to the device, scrolling where necessary.
The text is always followed by a newline.
:param text: The text to print.
:type text: str | 4.669629 | 4.869305 | 0.958993 |
for method, args in ansi_color.find_directives(text, self):
method(*args) | def puts(self, text) | Prints the supplied text, handling special character codes for carriage
return (\\r), newline (\\n), backspace (\\b) and tab (\\t). ANSI color
codes are also supported.
If the ``animate`` flag was set to True (default), then each character
is flushed to the device, giving the effect of 1970's teletype device.
:param text: The text to print.
:type text: str | 24.2323 | 38.679626 | 0.626487 |
if char == '\r':
self.carriage_return()
elif char == '\n':
self.newline()
elif char == '\b':
self.backspace()
elif char == '\t':
self.tab()
else:
w = self.font.getsize(char)[0]
if self._cx + w >= self._device.width:
self.newline()
self.erase()
self._canvas.text((self._cx, self._cy),
text=char,
font=self.font,
fill=self._fgcolor)
self._cx += w
if self.animate:
self.flush() | def putch(self, char) | Prints the specific character, which must be a valid printable ASCII
value in the range 32..127 only, or one of carriage return (\\r),
newline (\\n), backspace (\\b) or tab (\\t).
:param char: The character to print. | 2.958706 | 3.05915 | 0.967166 |
soft_tabs = self.tabstop - ((self._cx // self._cw) % self.tabstop)
for _ in range(soft_tabs):
self.putch(" ") | def tab(self) | Advances the cursor position to the next (soft) tabstop. | 9.738987 | 6.930445 | 1.405247 |
self.carriage_return()
if self._cy + (2 * self._ch) >= self._device.height:
# Simulate a vertical scroll
copy = self._backing_image.crop((0, self._ch, self._device.width,
self._device.height))
self._backing_image.paste(copy, (0, 0))
self._canvas.rectangle((0, copy.height, self._device.width,
self._device.height), fill=self.default_bgcolor)
else:
self._cy += self._ch
self.flush()
if self.animate:
time.sleep(0.2) | def newline(self) | Advances the cursor position ot the left hand side, and to the next
line. If the cursor is on the lowest line, the displayed contents are
scrolled, causing the top line to be lost. | 4.755735 | 4.526211 | 1.05071 |
if self._cx + self._cw >= 0:
self.erase()
self._cx -= self._cw
self.flush() | def backspace(self) | Moves the cursor one place to the left, erasing the character at the
current position. Cannot move beyond column zero, nor onto the
previous line. | 9.105964 | 9.465628 | 0.962003 |
bounds = (self._cx, self._cy, self._cx + self._cw, self._cy + self._ch)
self._canvas.rectangle(bounds, fill=self._bgcolor) | def erase(self) | Erase the contents of the cursor's current position without moving the
cursor's position. | 4.288136 | 4.554847 | 0.941445 |
self._fgcolor = self.default_fgcolor
self._bgcolor = self.default_bgcolor | def reset(self) | Resets the foreground and background color value back to the original
when initialised. | 4.846443 | 3.345762 | 1.448532 |
self._bgcolor, self._fgcolor = self._fgcolor, self._bgcolor | def reverse_colors(self) | Flips the foreground and background colors. | 5.097151 | 3.48838 | 1.46118 |
if self._last_image:
self._savepoints.append(self._last_image)
self._last_image = None | def savepoint(self) | Copies the last displayed image. | 4.670933 | 3.390959 | 1.377466 |
assert(drop >= 0)
while drop > 0:
self._savepoints.pop()
drop -= 1
img = self._savepoints.pop()
self.display(img) | def restore(self, drop=0) | Restores the last savepoint. If ``drop`` is supplied and greater than
zero, then that many savepoints are dropped, and the next savepoint is
restored.
:param drop:
:type drop: int | 5.994037 | 5.464404 | 1.096924 |
self._text_buffer = observable(mutable_string(value),
observer=self._flush) | def text(self, value) | Updates the seven-segment display with the given value. If there is not
enough space to show the full text, an ``OverflowException`` is raised.
:param value: The value to render onto the device. Any characters which
cannot be rendered will be converted into the ``undefined``
character supplied in the constructor.
:type value: str | 35.556835 | 49.206406 | 0.722606 |
self.tasks.put((func, args, kargs)) | def add_task(self, func, *args, **kargs) | Add a task to the queue. | 4.65787 | 3.569752 | 1.304816 |
assert mode in ("1", "RGB", "RGBA")
assert rotate in (0, 1, 2, 3)
self._w = width
self._h = height
self.width = width if rotate % 2 == 0 else height
self.height = height if rotate % 2 == 0 else width
self.size = (self.width, self.height)
self.bounding_box = (0, 0, self.width - 1, self.height - 1)
self.rotate = rotate
self.mode = mode
self.persist = False | def capabilities(self, width, height, rotate, mode="1") | Assigns attributes such as ``width``, ``height``, ``size`` and
``bounding_box`` correctly oriented from the supplied parameters.
:param width: The device width.
:type width: int
:param height: The device height.
:type height: int
:param rotate: An integer value of 0 (default), 1, 2 or 3 only, where 0 is
no rotation, 1 is rotate 90° clockwise, 2 is 180° rotation and 3
represents 270° rotation.
:type rotate: int
:param mode: The supported color model, one of ``"1"``, ``"RGB"`` or
``"RGBA"`` only.
:type mode: str | 2.448957 | 2.121269 | 1.154477 |
self.display(Image.new(self.mode, self.size)) | def clear(self) | Initializes the device memory with an empty (blank) image. | 10.404049 | 5.954619 | 1.747223 |
if self.rotate == 0:
return image
angle = self.rotate * -90
return image.rotate(angle, expand=True).crop((0, 0, self._w, self._h)) | def preprocess(self, image) | Provides a preprocessing facility (which may be overridden) whereby the supplied image is
rotated according to the device's rotate capability. If this method is
overridden, it is important to call the ``super`` method.
:param image: An image to pre-process.
:type image: PIL.Image.Image
:returns: A new processed image.
:rtype: PIL.Image.Image | 4.492204 | 3.51286 | 1.278788 |
font = font or DEFAULT_FONT
src = [c for ascii_code in txt for c in font[ord(ascii_code)]]
return (len(src), 8) | def textsize(txt, font=None) | Calculates the bounding box of the text, as drawn in the specified font.
This method is most useful for when the
:py:class:`~luma.core.legacy.font.proportional` wrapper is used.
:param txt: The text string to calculate the bounds for
:type txt: str
:param font: The font (from :py:mod:`luma.core.legacy.font`) to use. | 6.882891 | 13.37968 | 0.514429 |
font = font or DEFAULT_FONT
x, y = xy
for ch in txt:
for byte in font[ord(ch)]:
for j in range(8):
if byte & 0x01 > 0:
draw.point((x, y + j), fill=fill)
byte >>= 1
x += 1 | def text(draw, xy, txt, fill=None, font=None) | Draw a legacy font starting at :py:attr:`x`, :py:attr:`y` using the
prescribed fill and font.
:param draw: A valid canvas to draw the text onto.
:type draw: PIL.ImageDraw
:param txt: The text string to display (must be ASCII only).
:type txt: str
:param xy: An ``(x, y)`` tuple denoting the top-left corner to draw the
text.
:type xy: tuple
:param fill: The fill color to use (standard Pillow color name or RGB
tuple).
:param font: The font (from :py:mod:`luma.core.legacy.font`) to use. | 3.060562 | 4.238222 | 0.722134 |
fps = 0 if scroll_delay == 0 else 1.0 / scroll_delay
regulator = framerate_regulator(fps)
font = font or DEFAULT_FONT
with canvas(device) as draw:
w, h = textsize(msg, font)
x = device.width
virtual = viewport(device, width=w + x + x, height=device.height)
with canvas(virtual) as draw:
text(draw, (x, y_offset), msg, font=font, fill=fill)
i = 0
while i <= w + x:
with regulator:
virtual.set_position((i, 0))
i += 1 | def show_message(device, msg, y_offset=0, fill=None, font=None,
scroll_delay=0.03) | Scrolls a message right-to-left across the devices display.
:param device: The device to scroll across.
:param msg: The text message to display (must be ASCII only).
:type msg: str
:param y_offset: The row to use to display the text.
:type y_offset: int
:param fill: The fill color to use (standard Pillow color name or RGB
tuple).
:param font: The font (from :py:mod:`luma.core.legacy.font`) to use.
:param scroll_delay: The number of seconds to delay between scrolling.
:type scroll_delay: float | 4.155461 | 4.362862 | 0.952462 |
assert(len(cmd) <= 32)
try:
self._bus.write_i2c_block_data(self._addr, self._cmd_mode,
list(cmd))
except (IOError, OSError) as e:
if e.errno in [errno.EREMOTEIO, errno.EIO]:
# I/O error
raise luma.core.error.DeviceNotFoundError(
'I2C device not found on address: 0x{0:02X}'.format(self._addr))
else: # pragma: no cover
raise | def command(self, *cmd) | Sends a command or sequence of commands through to the I²C address
- maximum allowed is 32 bytes in one go.
:param cmd: A spread of commands.
:type cmd: int
:raises luma.core.error.DeviceNotFoundError: I2C device could not be found. | 3.090772 | 2.662092 | 1.161031 |
if self._managed:
self._bus.i2c_rdwr(self._i2c_msg_write(self._addr, [self._data_mode] + data))
else:
i = 0
n = len(data)
write = self._bus.write_i2c_block_data
while i < n:
write(self._addr, self._data_mode, list(data[i:i + 32]))
i += 32 | def data(self, data) | Sends a data byte or sequence of data bytes to the I²C address.
If the bus is in managed mode backed by smbus2, the i2c_rdwr
method will be used to avoid having to send in chunks.
For SMBus devices the maximum allowed in one transaction is
32 bytes, so if data is larger than this, it is sent in chunks.
:param data: A data sequence.
:type data: list, bytearray | 3.593274 | 2.895513 | 1.24098 |
prog = re.compile(r'^\033\[(\d+(;\d+)*)m', re.UNICODE)
while text != "":
result = prog.match(text)
if result:
for code in result.group(1).split(";"):
directive = valid_attributes.get(int(code), None)
if directive:
yield directive
n = len(result.group(0))
text = text[n:]
else:
yield ["putch", text[0]]
text = text[1:] | def parse_str(text) | Given a string of characters, for each normal ASCII character, yields
a directive consisting of a 'putch' instruction followed by the character
itself.
If a valid ANSI escape sequence is detected within the string, the
supported codes are translated into directives. For example ``\\033[42m``
would emit a directive of ``["background_color", "green"]``.
Note that unrecognised escape sequences are silently ignored: Only reset,
reverse colours and 8 foreground and background colours are supported.
It is up to the consumer to interpret the directives and update its state
accordingly.
:param text: An ASCII string which may or may not include valid ANSI Color
escape codes.
:type text: str | 3.852163 | 3.11053 | 1.238426 |
directives = []
for directive in parse_str(text):
method = klass.__getattribute__(directive[0])
args = directive[1:]
directives.append((method, args))
return directives | def find_directives(text, klass) | Find directives on class ``klass`` in string ``text``.
Returns list of ``(method, args)`` tuples.
.. versionadded:: 0.9.0
:param text: String containing directives.
:type text: str
:type klass: object
:rtype: list | 3.723496 | 3.860366 | 0.964545 |
assert(0 <= level <= 255)
self.command(self._const.SETCONTRAST, level) | def contrast(self, level) | Switches the display contrast to the desired level, in the range
0-255. Note that setting the level to a low (or zero) value will
not necessarily dim the display to nearly off. In other words,
this method is **NOT** suitable for fade-in/out animation.
:param level: Desired contrast level in the range of 0-255.
:type level: int | 6.038434 | 6.98655 | 0.864294 |
if not self.persist:
self.hide()
self.clear()
self._serial_interface.cleanup() | def cleanup(self) | Attempt to switch the device off or put into low power mode (this
helps prolong the life of the device), clear the screen and close
resources associated with the underlying serial interface.
If :py:attr:`persist` is ``True``, the device will not be switched off.
This is a managed function, which is called when the python processs
is being shutdown, so shouldn't usually need be called directly in
application code. | 13.564178 | 7.175587 | 1.890323 |
assert(image.size == self.size)
self.image = self.preprocess(image).copy() | def display(self, image) | Takes a :py:mod:`PIL.Image` and makes a copy of it for later
use/inspection.
:param image: Image to display.
:type image: PIL.Image.Image | 7.913536 | 8.972899 | 0.881937 |
try:
module = importlib.import_module(module_name)
if hasattr(module, '__all__'):
return module.__all__
else:
return [name for name, _ in inspect.getmembers(module, inspect.isclass)
if name != "device"]
except ImportError:
return [] | def get_choices(module_name) | Retrieve members from ``module_name``'s ``__all__`` list.
:rtype: list | 2.5031 | 2.814058 | 0.889498 |
display_types = get_display_types()
for key in display_types.keys():
if display_type in display_types[key]:
return key | def get_library_for_display_type(display_type) | Get library name for ``display_type``, e.g. ``ssd1306`` should return
``oled``.
.. versionadded:: 1.2.0
:param display_type: Display type, e.g. ``ssd1306``.
:type display_type: str
:rtype: str or None | 2.671369 | 3.787326 | 0.705344 |
try:
module = importlib.import_module('luma.' + module_name)
if hasattr(module, '__version__'):
return module.__version__
else:
return None
except ImportError:
return None | def get_library_version(module_name) | Get version number from ``module_name``'s ``__version__`` attribute.
.. versionadded:: 1.2.0
:param module_name: The module name, e.g. ``luma.oled``.
:type module_name: str
:rtype: str | 2.685373 | 2.647367 | 1.014356 |
display_types = OrderedDict()
for namespace in get_supported_libraries():
display_types[namespace] = get_choices('luma.{0}.device'.format(
namespace))
return display_types | def get_display_types() | Get ordered dict containing available display types from available luma
sub-projects.
:rtype: collections.OrderedDict | 10.341074 | 8.37176 | 1.235233 |
from luma.emulator.render import transformer
return [fn for fn in dir(transformer) if fn[0:2] != "__"] | def get_transformer_choices() | :rtype: list | 8.314351 | 7.414827 | 1.121314 |
args = []
with open(path, 'r') as fp:
for line in fp.readlines():
if line.strip() and not line.startswith("#"):
args.append(line.replace("\n", ""))
return args | def load_config(path) | Load device configuration from file path and return list with parsed lines.
:param path: Location of configuration file.
:type path: str
:rtype: list | 2.748609 | 2.863306 | 0.959942 |
device = None
if display_types is None:
display_types = get_display_types()
if args.display in display_types.get('oled'):
import luma.oled.device
Device = getattr(luma.oled.device, args.display)
Serial = getattr(make_serial(args), args.interface)
device = Device(Serial(), **vars(args))
elif args.display in display_types.get('lcd'):
import luma.lcd.device
import luma.lcd.aux
Device = getattr(luma.lcd.device, args.display)
spi = make_serial(args).spi()
device = Device(spi, **vars(args))
luma.lcd.aux.backlight(gpio=spi._gpio, gpio_LIGHT=args.gpio_backlight, active_low=args.backlight_active == "low").enable(True)
elif args.display in display_types.get('led_matrix'):
import luma.led_matrix.device
from luma.core.interface.serial import noop
Device = getattr(luma.led_matrix.device, args.display)
spi = make_serial(args, gpio=noop()).spi()
device = Device(serial_interface=spi, **vars(args))
elif args.display in display_types.get('emulator'):
import luma.emulator.device
Device = getattr(luma.emulator.device, args.display)
device = Device(**vars(args))
return device | def create_device(args, display_types=None) | Create and return device.
:type args: object
:type display_types: dict | 2.68811 | 2.784269 | 0.965463 |
r
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd, output=output)
return output | def check_output(*popenargs, **kwargs) | r"""Run command with arguments and return its output as a byte string.
If the exit code was non-zero it raises a CalledProcessError. The
CalledProcessError object will have the return code in the returncode
attribute and output in the output attribute.
The arguments are the same as for the Popen constructor. Example:
>>> check_output(["ls", "-l", "/dev/null"])
'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\n'
The stdout argument is not allowed as it is used internally.
To capture standard error in the result, use stderr=STDOUT.
>>> check_output(["/bin/sh", "-c",
... "ls -l non_existent_file ; exit 0"],
... stderr=STDOUT)
'ls: non_existent_file: No such file or directory\n' | 1.551926 | 2.180367 | 0.711773 |
# Optimization: If we are only using one pipe, or no pipe at
# all, using select() or threads is unnecessary.
if [self.stdin, self.stdout, self.stderr].count(None) >= 2:
stdout = None
stderr = None
if self.stdin:
if input:
try:
self.stdin.write(input)
except IOError as e:
if e.errno != errno.EPIPE and e.errno != errno.EINVAL:
raise
self.stdin.close()
elif self.stdout:
stdout = _eintr_retry_call(self.stdout.read)
self.stdout.close()
elif self.stderr:
stderr = _eintr_retry_call(self.stderr.read)
self.stderr.close()
self.wait()
return (stdout, stderr)
return self._communicate(input) | def communicate(self, input=None) | Interact with process: Send data to stdin. Read data from
stdout and stderr, until end-of-file is reached. Wait for
process to terminate. The optional input argument should be a
string to be sent to the child process, or None, if no data
should be sent to the child.
communicate() returns a tuple (stdout, stderr). | 3.161206 | 2.82101 | 1.120594 |
for k,v2 in d2.items():
v1 = d1.get(k) # returns None if v1 has no value for this key
if ( isinstance(v1, collections.Mapping) and
isinstance(v2, collections.Mapping) ):
merge_dict(v1, v2)
else:
d1[k] = v2 | def merge_dict(d1, d2) | Modifies d1 in-place to contain values from d2. If any value
in d1 is a dictionary (or dict-like), *and* the corresponding
value in d2 is also a dictionary, then merge them in-place. | 2.457636 | 2.271832 | 1.081786 |
color = color or len(self.particles) # assigned or default color number
p = Particle(pos, charge, mass, radius, color, vel, fixed, negligible)
self.particles.append(p) | def add_particle(
self,
pos=(0, 0, 0),
charge=1e-6,
mass=1e-3,
radius=0.005,
color=None,
vel=(0, 0, 0),
fixed=False,
negligible=False,
) | Adds a new particle with specified properties (in SI units) | 4.348714 | 4.095423 | 1.061847 |
# Main simulation loop
for i in range(self.iterations):
for a in self.particles:
if a.fixed:
continue
ftot = vector(0, 0, 0) # total force acting on particle a
for b in self.particles:
if a.negligible and b.negligible or a == b:
continue
ab = a.pos - b.pos
ftot += ((K_COULOMB * a.charge * b.charge) / mag2(ab)) * versor(ab)
a.vel += ftot / a.mass * self.dt # update velocity and position of a
a.pos += a.vel * self.dt
a.vtk_actor.pos(a.pos)
if vp:
vp.show(zoom=1.2)
vp.camera.Azimuth(0.1) | def simulate(self) | Runs the particle simulation. Simulates one time step, dt, of the particle motion.
Calculates the force between each pair of particles and updates particles' motion accordingly | 5.035864 | 4.771394 | 1.055428 |
vp = settings.plotter_instance
if actor is None:
actor = vp.lastActor()
if not hasattr(actor, "mapper"):
colors.printc("~times Error in addScalarBar: input is not a Actor.", c=1)
return None
if vp and vp.renderer and actor.scalarbar_actor:
vp.renderer.RemoveActor(actor.scalarbar)
lut = actor.mapper.GetLookupTable()
if not lut:
return None
vtkscalars = actor.poly.GetPointData().GetScalars()
if vtkscalars is None:
vtkscalars = actor.poly.GetCellData().GetScalars()
if not vtkscalars:
return None
rng = list(vtkscalars.GetRange())
if vmin:
rng[0] = vmin
if vmin:
rng[1] = vmax
actor.mapper.SetScalarRange(rng)
if c is None:
if vp.renderer: # automatic black or white
c = (0.9, 0.9, 0.9)
if numpy.sum(vp.renderer.GetBackground()) > 1.5:
c = (0.1, 0.1, 0.1)
else:
c = "k"
c = colors.getColor(c)
sb = vtk.vtkScalarBarActor()
sb.SetLookupTable(lut)
if title:
titprop = vtk.vtkTextProperty()
titprop.BoldOn()
titprop.ItalicOff()
titprop.ShadowOff()
titprop.SetColor(c)
titprop.SetVerticalJustificationToTop()
sb.SetTitle(title)
sb.SetVerticalTitleSeparation(15)
sb.SetTitleTextProperty(titprop)
if vtk.vtkVersion().GetVTKMajorVersion() > 7:
sb.UnconstrainedFontSizeOn()
sb.FixedAnnotationLeaderLineColorOff()
sb.DrawAnnotationsOn()
sb.DrawTickLabelsOn()
sb.SetMaximumNumberOfColors(512)
if horizontal:
sb.SetOrientationToHorizontal()
sb.SetNumberOfLabels(4)
sb.SetTextPositionToSucceedScalarBar()
sb.SetPosition(0.8, 0.05)
sb.SetMaximumWidthInPixels(1000)
sb.SetMaximumHeightInPixels(50)
else:
sb.SetNumberOfLabels(10)
sb.SetTextPositionToPrecedeScalarBar()
sb.SetPosition(0.87, 0.05)
sb.SetMaximumWidthInPixels(80)
sb.SetMaximumHeightInPixels(500)
sctxt = sb.GetLabelTextProperty()
sctxt.SetColor(c)
sctxt.SetShadow(0)
sctxt.SetFontFamily(0)
sctxt.SetItalic(0)
sctxt.SetBold(0)
sctxt.SetFontSize(12)
if not vp.renderer:
save_int = vp.interactive
vp.show(interactive=0)
vp.interactive = save_int
sb.PickableOff()
vp.renderer.AddActor(sb)
vp.scalarbars.append(sb)
actor.scalarbar_actor = sb
vp.renderer.Render()
return sb | def addScalarBar(actor=None, c=None, title="", horizontal=False, vmin=None, vmax=None) | Add a 2D scalar bar for the specified actor.
If `actor` is ``None`` will add it to the last actor in ``self.actors``.
.. hint:: |mesh_bands| |mesh_bands.py|_ | 2.889428 | 2.917383 | 0.990418 |
vp = settings.plotter_instance
if c is None: # automatic black or white
c = (0.8, 0.8, 0.8)
if numpy.sum(colors.getColor(vp.backgrcol)) > 1.5:
c = (0.2, 0.2, 0.2)
else:
c = colors.getColor(c)
if value is None or value < xmin:
value = xmin
t = 1.5 / numpy.sqrt(utils.mag(numpy.array(pos2) - pos1)) # better norm
sliderRep = vtk.vtkSliderRepresentation3D()
sliderRep.SetMinimumValue(xmin)
sliderRep.SetValue(value)
sliderRep.SetMaximumValue(xmax)
sliderRep.GetPoint1Coordinate().SetCoordinateSystemToWorld()
sliderRep.GetPoint2Coordinate().SetCoordinateSystemToWorld()
sliderRep.GetPoint1Coordinate().SetValue(pos2)
sliderRep.GetPoint2Coordinate().SetValue(pos1)
sliderRep.SetSliderWidth(0.03 * t)
sliderRep.SetTubeWidth(0.01 * t)
sliderRep.SetSliderLength(0.04 * t)
sliderRep.SetSliderShapeToCylinder()
sliderRep.GetSelectedProperty().SetColor(1, 0, 0)
sliderRep.GetSliderProperty().SetColor(numpy.array(c) / 2)
sliderRep.GetCapProperty().SetOpacity(0)
sliderRep.SetRotation(rotation)
if not showValue:
sliderRep.ShowSliderLabelOff()
sliderRep.SetTitleText(title)
sliderRep.SetTitleHeight(s * t)
sliderRep.SetLabelHeight(s * t * 0.85)
sliderRep.GetTubeProperty()
sliderRep.GetTubeProperty().SetColor(c)
sliderWidget = vtk.vtkSliderWidget()
sliderWidget.SetInteractor(vp.interactor)
sliderWidget.SetRepresentation(sliderRep)
sliderWidget.SetAnimationModeToJump()
sliderWidget.AddObserver("InteractionEvent", sliderfunc)
sliderWidget.EnabledOn()
vp.sliders.append([sliderWidget, sliderfunc])
return sliderWidget | def addSlider3D(
sliderfunc,
pos1,
pos2,
xmin,
xmax,
value=None,
s=0.03,
title="",
rotation=0,
c=None,
showValue=True,
) | Add a 3D slider widget which can call an external custom function.
:param sliderfunc: external function to be called by the widget
:param list pos1: first position coordinates
:param list pos2: second position coordinates
:param float xmin: lower value
:param float xmax: upper value
:param float value: initial value
:param float s: label scaling factor
:param str title: title text
:param c: slider color
:param float rotation: title rotation around slider axis
:param bool showValue: if True current value is shown
.. hint:: |sliders3d| |sliders3d.py|_ | 2.578645 | 2.598435 | 0.992384 |
vp = settings.plotter_instance
if not vp.renderer:
colors.printc("~timesError: Use addButton() after rendering the scene.", c=1)
return
import vtkplotter.vtkio as vtkio
bu = vtkio.Button(fnc, states, c, bc, pos, size, font, bold, italic, alpha, angle)
vp.renderer.AddActor2D(bu.actor)
vp.window.Render()
vp.buttons.append(bu)
return bu | def addButton(
fnc,
states=("On", "Off"),
c=("w", "w"),
bc=("dg", "dr"),
pos=(20, 40),
size=24,
font="arial",
bold=False,
italic=False,
alpha=1,
angle=0,
) | Add a button to the renderer window.
:param list states: a list of possible states ['On', 'Off']
:param c: a list of colors for each state
:param bc: a list of background colors for each state
:param pos: 2D position in pixels from left-bottom corner
:param size: size of button font
:param str font: font type (arial, courier, times)
:param bool bold: bold face (False)
:param bool italic: italic face (False)
:param float alpha: opacity level
:param float angle: anticlockwise rotation in degrees
.. hint:: |buttons| |buttons.py|_ | 6.228199 | 6.281145 | 0.991571 |
if isinstance(actor, vtk.vtkVolume):
return _addVolumeCutterTool(actor)
elif isinstance(actor, vtk.vtkImageData):
from vtkplotter import Volume
return _addVolumeCutterTool(Volume(actor))
vp = settings.plotter_instance
if not vp.renderer:
save_int = vp.interactive
vp.show(interactive=0)
vp.interactive = save_int
vp.clickedActor = actor
if hasattr(actor, "polydata"):
apd = actor.polydata()
else:
apd = actor.GetMapper().GetInput()
planes = vtk.vtkPlanes()
planes.SetBounds(apd.GetBounds())
clipper = vtk.vtkClipPolyData()
clipper.GenerateClipScalarsOff()
clipper.SetInputData(apd)
clipper.SetClipFunction(planes)
clipper.InsideOutOn()
clipper.GenerateClippedOutputOn()
act0Mapper = vtk.vtkPolyDataMapper() # the part which stays
act0Mapper.SetInputConnection(clipper.GetOutputPort())
act0 = Actor()
act0.SetMapper(act0Mapper)
act0.GetProperty().SetColor(actor.GetProperty().GetColor())
act0.GetProperty().SetOpacity(1)
act1Mapper = vtk.vtkPolyDataMapper() # the part which is cut away
act1Mapper.SetInputConnection(clipper.GetClippedOutputPort())
act1 = vtk.vtkActor()
act1.SetMapper(act1Mapper)
act1.GetProperty().SetOpacity(0.02)
act1.GetProperty().SetRepresentationToWireframe()
act1.VisibilityOn()
vp.renderer.AddActor(act0)
vp.renderer.AddActor(act1)
vp.renderer.RemoveActor(actor)
def SelectPolygons(vobj, event):
vobj.GetPlanes(planes)
boxWidget = vtk.vtkBoxWidget()
boxWidget.OutlineCursorWiresOn()
boxWidget.GetSelectedOutlineProperty().SetColor(1, 0, 1)
boxWidget.GetOutlineProperty().SetColor(0.1, 0.1, 0.1)
boxWidget.GetOutlineProperty().SetOpacity(0.8)
boxWidget.SetPlaceFactor(1.05)
boxWidget.SetInteractor(vp.interactor)
boxWidget.SetInputData(apd)
boxWidget.PlaceWidget()
boxWidget.AddObserver("InteractionEvent", SelectPolygons)
boxWidget.On()
vp.cutterWidget = boxWidget
vp.clickedActor = act0
ia = vp.actors.index(actor)
vp.actors[ia] = act0
colors.printc("Mesh Cutter Tool:", c="m", invert=1)
colors.printc(" Move gray handles to cut away parts of the mesh", c="m")
colors.printc(" Press X to save file to: clipped.vtk", c="m")
vp.interactor.Start()
boxWidget.Off()
vp.widgets.append(boxWidget)
vp.interactor.Start() # allow extra interaction
return act0 | def addCutterTool(actor) | Create handles to cut away parts of a mesh.
.. hint:: |cutter| |cutter.py|_ | 2.969054 | 2.944965 | 1.00818 |
vp = settings.plotter_instance
if not vp.renderer:
colors.printc("~lightningWarning: Use addIcon() after first rendering the scene.", c=3)
save_int = vp.interactive
vp.show(interactive=0)
vp.interactive = save_int
widget = vtk.vtkOrientationMarkerWidget()
widget.SetOrientationMarker(iconActor)
widget.SetInteractor(vp.interactor)
if utils.isSequence(pos):
widget.SetViewport(pos[0] - size, pos[1] - size, pos[0] + size, pos[1] + size)
else:
if pos < 2:
widget.SetViewport(0, 1 - 2 * size, size * 2, 1)
elif pos == 2:
widget.SetViewport(1 - 2 * size, 1 - 2 * size, 1, 1)
elif pos == 3:
widget.SetViewport(0, 0, size * 2, size * 2)
elif pos == 4:
widget.SetViewport(1 - 2 * size, 0, 1, size * 2)
widget.EnabledOn()
widget.InteractiveOff()
vp.widgets.append(widget)
if iconActor in vp.actors:
vp.actors.remove(iconActor)
return widget | def addIcon(iconActor, pos=3, size=0.08) | Add an inset icon mesh into the same renderer.
:param pos: icon position in the range [1-4] indicating one of the 4 corners,
or it can be a tuple (x,y) as a fraction of the renderer size.
:param float size: size of the square inset.
.. hint:: |icon| |icon.py|_ | 2.900775 | 2.795436 | 1.037683 |
if hasattr(arg, "strip"):
return False
if hasattr(arg, "__getslice__"):
return True
if hasattr(arg, "__iter__"):
return True
return False | def isSequence(arg) | Check if input is iterable. | 2.845673 | 2.609121 | 1.090663 |
def genflatten(lst):
for elem in lst:
if isinstance(elem, (list, tuple)):
for x in flatten(elem):
yield x
else:
yield elem
return list(genflatten(list_to_flatten)) | def flatten(list_to_flatten) | Flatten out a list. | 2.611658 | 2.491875 | 1.048069 |
import re
def alphanum_key(s):
# Turn a string into a list of string and number chunks.
# e.g. "z23a" -> ["z", 23, "a"]
def tryint(s):
if s.isdigit():
return int(s)
return s
return [tryint(c) for c in re.split("([0-9]+)", s)]
l.sort(key=alphanum_key)
return None | def humansort(l) | Sort in place a given list the way humans expect.
E.g. ['file11', 'file1'] -> ['file1', 'file11'] | 2.18548 | 2.227951 | 0.980937 |
s = (x - rangeX[0]) / mag(rangeX[1] - rangeX[0])
y = rangeY[0] * (1 - s) + rangeY[1] * s
return y | def lin_interp(x, rangeX, rangeY) | Interpolate linearly variable x in rangeX onto rangeY. | 2.594558 | 2.677811 | 0.96891 |
if y is None: # assume x is already [x,y,z]
return np.array(x, dtype=np.float64)
return np.array([x, y, z], dtype=np.float64) | def vector(x, y=None, z=0.0) | Return a 3D numpy array representing a vector (of type `numpy.float64`).
If `y` is ``None``, assume input is already in the form `[x,y,z]`. | 2.570524 | 2.615658 | 0.982745 |
if isinstance(v[0], np.ndarray):
return np.divide(v, mag(v)[:, None])
else:
return v / mag(v) | def versor(v) | Return the unit vector. Input can be a list of vectors. | 3.822228 | 3.249464 | 1.176264 |
if isinstance(z[0], np.ndarray):
return np.array(list(map(np.linalg.norm, z)))
else:
return np.linalg.norm(z) | def mag(z) | Get the magnitude of a vector. | 2.170002 | 2.352554 | 0.922402 |
import math
x = float(x)
if x == 0.0:
return "0." + "0" * (p - 1)
out = []
if x < 0:
out.append("-")
x = -x
e = int(math.log10(x))
tens = math.pow(10, e - p + 1)
n = math.floor(x / tens)
if n < math.pow(10, p - 1):
e = e - 1
tens = math.pow(10, e - p + 1)
n = math.floor(x / tens)
if abs((n + 1.0) * tens - x) <= abs(n * tens - x):
n = n + 1
if n >= math.pow(10, p):
n = n / 10.0
e = e + 1
m = "%.*g" % (p, n)
if e < -2 or e >= p:
out.append(m[0])
if p > 1:
out.append(".")
out.extend(m[1:p])
out.append("e")
if e > 0:
out.append("+")
out.append(str(e))
elif e == (p - 1):
out.append(m)
elif e >= 0:
out.append(m[: e + 1])
if e + 1 < len(m):
out.append(".")
out.extend(m[e + 1 :])
else:
out.append("0.")
out.extend(["0"] * -(e + 1))
out.append(m)
return "".join(out) | def precision(x, p) | Returns a string representation of `x` formatted with precision `p`.
Based on the webkit javascript implementation taken
`from here <https://code.google.com/p/webkit-mirror/source/browse/JavaScriptCore/kjs/number_object.cpp>`_,
and implemented by `randlet <https://github.com/randlet/to-precision>`_. | 1.606355 | 1.616913 | 0.99347 |
p = np.array(p)
u = np.array(p2) - p1
v = np.array(p3) - p1
n = np.cross(u, v)
w = p - p1
ln = np.dot(n, n)
if not ln:
return True # degenerate triangle
gamma = (np.dot(np.cross(u, w), n)) / ln
beta = (np.dot(np.cross(w, v), n)) / ln
alpha = 1 - gamma - beta
if 0 < alpha < 1 and 0 < beta < 1 and 0 < gamma < 1:
return True
return False | def pointIsInTriangle(p, p1, p2, p3) | Return True if a point is inside (or above/below) a triangle defined by 3 points in space. | 2.225384 | 2.165929 | 1.02745 |
d = np.sqrt(vtk.vtkLine.DistanceToLine(p, p1, p2))
return d | def pointToLineDistance(p, p1, p2) | Compute the distance of a point to a line (not the segment) defined by `p1` and `p2`. | 4.865802 | 4.566001 | 1.06566 |
st = np.sin(theta)
sp = np.sin(phi)
ct = np.cos(theta)
cp = np.cos(phi)
rhost = rho * st
x = rhost * cp
y = rhost * sp
z = rho * ct
return np.array([x, y, z]) | def spher2cart(rho, theta, phi) | Spherical to Cartesian coordinate conversion. | 2.127163 | 2.14098 | 0.993546 |
hxy = np.hypot(x, y)
r = np.hypot(hxy, z)
theta = np.arctan2(z, hxy)
phi = np.arctan2(y, x)
return r, theta, phi | def cart2spher(x, y, z) | Cartesian to Spherical coordinate conversion. | 1.807046 | 1.803839 | 1.001778 |
theta = np.arctan2(y, x)
rho = np.hypot(x, y)
return theta, rho | def cart2pol(x, y) | Cartesian to Polar coordinates conversion. | 2.199347 | 2.048518 | 1.073628 |
x = rho * np.cos(theta)
y = rho * np.sin(theta)
return x, y | def pol2cart(theta, rho) | Polar to Cartesian coordinates conversion. | 1.677099 | 1.945797 | 0.861908 |
for i in [0, 1, 2, 3]:
for j in [0, 1, 2, 3]:
e = M.GetElement(i, j)
if i == j:
if np.abs(e - 1) > tol:
return False
elif np.abs(e) > tol:
return False
return True | def isIdentity(M, tol=1e-06) | Check if vtkMatrix4x4 is Identity. | 2.059016 | 1.790044 | 1.15026 |
import re
try:
afile = open(filename, "r")
except:
print("Error in utils.grep(): cannot open file", filename)
exit()
content = None
for line in afile:
if re.search(tag, line):
content = line.split()
if firstOccurrence:
break
if content:
if len(content) == 2:
content = content[1]
else:
content = content[1:]
afile.close()
return content | def grep(filename, tag, firstOccurrence=False) | Greps the line that starts with a specific `tag` string from inside a file. | 2.725777 | 2.757734 | 0.988412 |
if numberOfBands < 2:
return inputlist
vmin = np.min(inputlist)
vmax = np.max(inputlist)
bb = np.linspace(vmin, vmax, numberOfBands, endpoint=0)
dr = bb[1] - bb[0]
bb += dr / 2
tol = dr / 2 * 1.001
newlist = []
for s in inputlist:
for b in bb:
if abs(s - b) < tol:
newlist.append(b)
break
return np.array(newlist) | def makeBands(inputlist, numberOfBands) | Group values of a list into bands of equal value.
:param int numberOfBands: number of bands, a positive integer > 2.
:return: a binned list of the same length as the input. | 2.75279 | 2.872299 | 0.958393 |
if not settings.plotter_instance:
return
settings.plotter_instance.clear(actor)
return settings.plotter_instance | def clear(actor=()) | Clear specific actor or list of actors from the current rendering window. | 6.562538 | 6.068268 | 1.081452 |
import matplotlib.pyplot as plt
import matplotlib as mpl
from mpl_toolkits.axes_grid1 import make_axes_locatable
M = numpy.array(M)
m,n = numpy.shape(M)
M = M.round(decimals=2)
fig = plt.figure()
ax = fig.add_subplot(111)
cmap = mpl.cm.get_cmap(cmap)
if not continuous:
unq = numpy.unique(M)
im = ax.imshow(M, cmap=cmap, interpolation='None')
divider = make_axes_locatable(ax)
cax = divider.append_axes("right", size="5%", pad=0.05)
dim = r'$%i \times %i$ ' % (m,n)
ax.set_title(dim + title)
ax.axis('off')
cb = plt.colorbar(im, cax=cax)
if not continuous:
cb.set_ticks(unq)
cb.set_ticklabels(unq)
plt.show() | def plotMatrix(M, title='matrix', continuous=True, cmap='Greys') | Plot a matrix using `matplotlib`.
:Example:
.. code-block:: python
from vtkplotter.dolfin import plotMatrix
import numpy as np
M = np.eye(9) + np.random.randn(9,9)/4
plotMatrix(M)
|pmatrix| | 2.260794 | 2.496283 | 0.905664 |
acts = vtkio.load(inputobj, c, alpha, wire, bc, texture, smoothing, threshold, connectivity)
if utils.isSequence(acts):
self.actors += acts
else:
self.actors.append(acts)
return acts | def load(
self,
inputobj,
c="gold",
alpha=1,
wire=False,
bc=None,
texture=None,
smoothing=None,
threshold=None,
connectivity=False,
) | Returns a ``vtkActor`` from reading a file, directory or ``vtkPolyData``.
:param c: color in RGB format, hex, symbol or name
:param alpha: transparency (0=invisible)
:param wire: show surface as wireframe
:param bc: backface color of internal surface
:param texture: any png/jpg file can be used as texture
For volumetric data (tiff, slc, vti files):
:param smoothing: gaussian filter to smooth vtkImageData
:param threshold: value to draw the isosurface
:param bool connectivity: if True only keeps the largest portion of the polydata | 3.702512 | 4.319588 | 0.857145 |
if renderer is None:
renderer = self.renderer
elif isinstance(renderer, int):
renderer = self.renderers.index(renderer)
else:
return []
if obj is None or isinstance(obj, int):
if obj is None:
acs = renderer.GetVolumes()
elif obj >= len(self.renderers):
colors.printc("~timesError in getVolumes: non existing renderer", obj, c=1)
return []
else:
acs = self.renderers[obj].GetVolumes()
vols = []
acs.InitTraversal()
for i in range(acs.GetNumberOfItems()):
a = acs.GetNextItem()
if a.GetPickable():
r = self.renderers.index(renderer)
if a == self.axes_exist[r]:
continue
vols.append(a)
return vols | def getVolumes(self, obj=None, renderer=None) | Return the list of the rendered Volumes. | 3.994014 | 3.816012 | 1.046646 |
if renderer is None:
renderer = self.renderer
elif isinstance(renderer, int):
renderer = self.renderers.index(renderer)
else:
return []
if obj is None or isinstance(obj, int):
if obj is None:
acs = renderer.GetActors()
elif obj >= len(self.renderers):
colors.printc("~timesError in getActors: non existing renderer", obj, c=1)
return []
else:
acs = self.renderers[obj].GetActors()
actors = []
acs.InitTraversal()
for i in range(acs.GetNumberOfItems()):
a = acs.GetNextItem()
if a.GetPickable():
r = self.renderers.index(renderer)
if a == self.axes_exist[r]:
continue
actors.append(a)
return actors
elif isinstance(obj, vtk.vtkAssembly):
cl = vtk.vtkPropCollection()
obj.GetActors(cl)
actors = []
cl.InitTraversal()
for i in range(obj.GetNumberOfPaths()):
act = vtk.vtkActor.SafeDownCast(cl.GetNextProp())
if act.GetPickable():
actors.append(act)
return actors
elif isinstance(obj, str): # search the actor by the legend name
actors = []
for a in self.actors:
if hasattr(a, "_legend") and obj in a._legend:
actors.append(a)
return actors
elif isinstance(obj, vtk.vtkActor):
return [obj]
if self.verbose:
colors.printc("~lightning Warning in getActors: unexpected input type", obj, c=1)
return [] | def getActors(self, obj=None, renderer=None) | Return an actors list.
If ``obj`` is:
``None``, return actors of current renderer
``int``, return actors in given renderer number
``vtkAssembly`` return the contained actors
``string``, return actors matching legend name
:param int,vtkRenderer renderer: specify which renederer to look into. | 3.111607 | 2.806296 | 1.108795 |
if utils.isSequence(actors):
for a in actors:
if a not in self.actors:
self.actors.append(a)
return None
else:
self.actors.append(actors)
return actors | def add(self, actors) | Append input object to the internal list of actors to be shown.
:return: returns input actor for possible concatenation. | 2.682545 | 2.814627 | 0.953073 |
if isinstance(fraction, int):
colors.printc("~lightning Warning in moveCamera(): fraction should not be an integer", c=1)
if fraction > 1:
colors.printc("~lightning Warning in moveCamera(): fraction is > 1", c=1)
cam = vtk.vtkCamera()
cam.DeepCopy(camstart)
p1 = numpy.array(camstart.GetPosition())
f1 = numpy.array(camstart.GetFocalPoint())
v1 = numpy.array(camstart.GetViewUp())
c1 = numpy.array(camstart.GetClippingRange())
s1 = camstart.GetDistance()
p2 = numpy.array(camstop.GetPosition())
f2 = numpy.array(camstop.GetFocalPoint())
v2 = numpy.array(camstop.GetViewUp())
c2 = numpy.array(camstop.GetClippingRange())
s2 = camstop.GetDistance()
cam.SetPosition(p2 * fraction + p1 * (1 - fraction))
cam.SetFocalPoint(f2 * fraction + f1 * (1 - fraction))
cam.SetViewUp(v2 * fraction + v1 * (1 - fraction))
cam.SetDistance(s2 * fraction + s1 * (1 - fraction))
cam.SetClippingRange(c2 * fraction + c1 * (1 - fraction))
self.camera = cam
save_int = self.interactive
self.show(resetcam=0, interactive=0)
self.interactive = save_int | def moveCamera(self, camstart, camstop, fraction) | Takes as input two ``vtkCamera`` objects and returns a
new ``vtkCamera`` that is at an intermediate position:
fraction=0 -> camstart, fraction=1 -> camstop.
Press ``shift-C`` key in interactive mode to dump a python snipplet
of parameters for the current camera view. | 2.01547 | 2.012856 | 1.001299 |
if isinstance(fp, vtk.vtkActor):
fp = fp.GetPosition()
light = vtk.vtkLight()
light.SetLightTypeToSceneLight()
light.SetPosition(pos)
light.SetPositional(1)
light.SetConeAngle(deg)
light.SetFocalPoint(fp)
light.SetDiffuseColor(colors.getColor(diffuse))
light.SetAmbientColor(colors.getColor(ambient))
light.SetSpecularColor(colors.getColor(specular))
save_int = self.interactive
self.show(interactive=0)
self.interactive = save_int
if showsource:
lightActor = vtk.vtkLightActor()
lightActor.SetLight(light)
self.renderer.AddViewProp(lightActor)
self.renderer.AddLight(light)
return light | def light(
self,
pos=(1, 1, 1),
fp=(0, 0, 0),
deg=25,
diffuse="y",
ambient="r",
specular="b",
showsource=False,
) | Generate a source of light placed at pos, directed to focal point fp.
:param fp: focal Point, if this is a ``vtkActor`` use its position.
:type fp: vtkActor, list
:param deg: aperture angle of the light source
:param showsource: if `True`, will show a vtk representation
of the source of light as an extra actor
.. hint:: |lights.py|_ | 2.451072 | 2.489167 | 0.984696 |
return addons.addScalarBar(actor, c, title, horizontal, vmin, vmax) | def addScalarBar(self, actor=None, c=None, title="", horizontal=False, vmin=None, vmax=None) | Add a 2D scalar bar for the specified actor.
If `actor` is ``None`` will add it to the last actor in ``self.actors``.
.. hint:: |mesh_bands| |mesh_bands.py|_ | 6.090643 | 10.027001 | 0.607424 |
return addons.addScalarBar3D(obj, at, pos, normal, sx, sy, nlabels, ncols, cmap, c, alpha) | def addScalarBar3D(
self,
obj=None,
at=0,
pos=(0, 0, 0),
normal=(0, 0, 1),
sx=0.1,
sy=2,
nlabels=9,
ncols=256,
cmap=None,
c=None,
alpha=1,
) | Draw a 3D scalar bar.
``obj`` input can be:
- a list of numbers,
- a list of two numbers in the form `(min, max)`,
- a ``vtkActor`` already containing a set of scalars associated to vertices or cells,
- if ``None`` the last actor in the list of actors will be used.
.. hint:: |scalbar| |mesh_coloring.py|_ | 3.260938 | 4.192692 | 0.777767 |
return addons.addSlider2D(sliderfunc, xmin, xmax, value, pos, s, title, c, showValue) | def addSlider2D(
self, sliderfunc, xmin, xmax, value=None, pos=4, s=0.04, title="", c=None, showValue=True
) | Add a slider widget which can call an external custom function.
:param sliderfunc: external function to be called by the widget
:param float xmin: lower value
:param float xmax: upper value
:param float value: current value
:param list pos: position corner number: horizontal [1-4] or vertical [11-14]
it can also be specified by corners coordinates [(x1,y1), (x2,y2)]
:param str title: title text
:param bool showValue: if true current value is shown
.. hint:: |sliders| |sliders.py|_ | 3.900783 | 4.702123 | 0.829579 |
return addons.addSlider3D(
sliderfunc, pos1, pos2, xmin, xmax, value, s, title, rotation, c, showValue
) | def addSlider3D(
self,
sliderfunc,
pos1,
pos2,
xmin,
xmax,
value=None,
s=0.03,
title="",
rotation=0,
c=None,
showValue=True,
) | Add a 3D slider widget which can call an external custom function.
:param sliderfunc: external function to be called by the widget
:param list pos1: first position coordinates
:param list pos2: second position coordinates
:param float xmin: lower value
:param float xmax: upper value
:param float value: initial value
:param float s: label scaling factor
:param str title: title text
:param c: slider color
:param float rotation: title rotation around slider axis
:param bool showValue: if True current value is shown
.. hint:: |sliders3d| |sliders3d.py|_ | 3.183047 | 3.988203 | 0.798115 |
return addons.addButton(fnc, states, c, bc, pos, size, font, bold, italic, alpha, angle) | def addButton(
self,
fnc,
states=("On", "Off"),
c=("w", "w"),
bc=("dg", "dr"),
pos=(20, 40),
size=24,
font="arial",
bold=False,
italic=False,
alpha=1,
angle=0,
) | Add a button to the renderer window.
:param list states: a list of possible states ['On', 'Off']
:param c: a list of colors for each state
:param bc: a list of background colors for each state
:param pos: 2D position in pixels from left-bottom corner
:param size: size of button font
:param str font: font type (arial, courier, times)
:param bool bold: bold face (False)
:param bool italic: italic face (False)
:param float alpha: opacity level
:param float angle: anticlockwise rotation in degrees
.. hint:: |buttons| |buttons.py|_ | 3.638401 | 4.493654 | 0.809675 |
return addons.addIcon(iconActor, pos, size) | def addIcon(self, iconActor, pos=3, size=0.08) | Add an inset icon mesh into the same renderer.
:param pos: icon position in the range [1-4] indicating one of the 4 corners,
or it can be a tuple (x,y) as a fraction of the renderer size.
:param float size: size of the square inset.
.. hint:: |icon| |icon.py|_ | 13.581365 | 28.128275 | 0.482837 |
if not self.initializedPlotter:
save_int = self.interactive
self.show(interactive=0)
self.interactive = save_int
return
if self.renderer:
self.renderer.RemoveActor(a)
if hasattr(a, 'renderedAt'):
ir = self.renderers.index(self.renderer)
a.renderedAt.discard(ir)
if a in self.actors:
i = self.actors.index(a)
del self.actors[i] | def removeActor(self, a) | Remove ``vtkActor`` or actor index from current renderer. | 4.728938 | 4.131468 | 1.144615 |
if not utils.isSequence(actors):
actors = [actors]
if len(actors):
for a in actors:
self.removeActor(a)
else:
for a in settings.collectable_actors:
self.removeActor(a)
settings.collectable_actors = []
self.actors = []
for a in self.getActors():
self.renderer.RemoveActor(a)
for a in self.getVolumes():
self.renderer.RemoveVolume(a)
for s in self.sliders:
s.EnabledOff()
for b in self.buttons:
self.renderer.RemoveActor(b)
for w in self.widgets:
w.EnabledOff()
for c in self.scalarbars:
self.renderer.RemoveActor(c) | def clear(self, actors=()) | Delete specified list of actors, by default delete all. | 2.985614 | 2.893512 | 1.03183 |
clm = (1 - t) * clm1 + t * clm2
grid_reco = clm.expand(lmax=lmax) # cut "high frequency" components
agrid_reco = grid_reco.to_array()
pts = []
for i, longs in enumerate(agrid_reco):
ilat = grid_reco.lats()[i]
for j, value in enumerate(longs):
ilong = grid_reco.lons()[j]
th = (90 - ilat) / 57.3
ph = ilong / 57.3
r = value + rbias
p = np.array([sin(th) * cos(ph), sin(th) * sin(ph), cos(th)]) * r
pts.append(p)
return pts | def morph(clm1, clm2, t, lmax) | Interpolate linearly the two sets of sph harm. coeeficients. | 4.195697 | 4.190624 | 1.001211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.